content
stringlengths
253
286k
index
int64
4
1.23k
secrets
stringlengths
64
1.84k
has_secrets
bool
1 class
number_secrets
int64
1
20
new_content
stringlengths
239
286k
modified
bool
1 class
references
stringlengths
254
286k
/** * @NApiVersion 2.x * @NScriptType ScheduledScript * @NAmdConfig ./custom_modules_config.json * * Module Description * * @Author: ankith.ravindran * @Date: 2018-09-19 13:20:56 * @Last Modified by: Anesu Chakaingesu * @Last Modified time: 2020-04-30 14:56:03 */ define(['N/ui/serverWidget', 'N/email', 'N/runtime', 'N/search', 'N/record', 'N/http', 'N/log', 'N/redirect', 'N/task', 'moment2', 'N/format'], function(ui, email, runtime, search, record, http, log, redirect, task, moment, format) { // log.debug({ // title: 'moment Defined', // details: JSON.stringify(moment) // }); var days_of_week = []; days_of_week[0] = 0; days_of_week[1] = 'custrecord_service_freq_stop.custrecord_service_freq_day_mon'; days_of_week[2] = 'custrecord_service_freq_stop.custrecord_service_freq_day_tue'; days_of_week[3] = 'custrecord_service_freq_stop.custrecord_service_freq_day_wed'; days_of_week[4] = 'custrecord_service_freq_stop.custrecord_service_freq_day_thu'; days_of_week[5] = 'custrecord_service_freq_stop.custrecord_service_freq_day_fri'; days_of_week[6] = 6; var days_of_week2 = []; days_of_week2[0] = 0; days_of_week2[1] = 'custrecord_service_freq_day_mon'; days_of_week2[2] = 'custrecord_service_freq_day_tue'; days_of_week2[3] = 'custrecord_service_freq_day_wed'; days_of_week2[4] = 'custrecord_service_freq_day_thu'; days_of_week2[5] = 'custrecord_service_freq_day_fri'; days_of_week2[6] = 6; var usage_threshold = 200; //20 var usage_threshold_invoice = 1000; //1000 var adhoc_inv_deploy = 'customdeploy2'; var prev_inv_deploy = null; var ctx = runtime.getCurrentScript(); var date_of_week; function main(){ var day = moment().utc().day(); var date = moment().utc().add(1, 'days').date(); var month = moment().utc().month(); var year = moment().utc().year(); var startDate = moment([year, month]); var endDate = moment(startDate).endOf('month').date(); if(moment().utc().date() == endDate){ date_of_week = date + '/' + (month + 2) + '/' + year; } else { date_of_week = date + '/' + (month + 1) + '/' + year; } // date_of_week = date + '/' + (month + 1) + '/' + year; log.audit({ title: 'moment().utc()', details: moment().utc() }) log.audit({ title: 'day', details: day }) log.audit({ title: 'original date', details: moment().utc().date() }) log.audit({ title: 'date', details: date }) log.audit({ title: 'Last Day of Month', details: endDate }) log.audit({ title: 'month', details: month }) log.audit({ title: 'year', details: year }) log.audit({ title: 'date_of_week', details: date_of_week }) log.audit({ title: 'days_of_week[day + 1]', details: days_of_week[day + 1] }); log.audit({ title: 'days_of_week[day]', details: days_of_week[day] }); log.audit({ title: 'prev_deployment', details: ctx.getParameter({ name: 'custscript_rp_prev_deployment_create_app' }) }) if (!isNullorEmpty(ctx.getParameter({ name: 'custscript_rp_prev_deployment_create_app' }))) { prev_inv_deploy = ctx.getParameter({ name: 'custscript_rp_prev_deployment_create_app' }) } else { prev_inv_deploy = ctx.deploymentId; } var zeeSearch = search.load({ type: 'partner', id: 'customsearch_rp_zee_no_job_created_2_2' }); var resultZee = zeeSearch.run(); //.getRange({ start: 0, end: 1}) // log.audit({ // title: 'searchResultZee', // details: resultZee // }) resultZee.each(function(searchResultZee) { var zee_id = searchResultZee.getValue({ name: "internalid"}); // var zee_id = 215 // Alexandria // var zee_id = 5386 // Arncliffe // var zee_id = 621451 // Gold Coast // var zee_id = 780481 // TEST - ACT // var zee_id = 779884 // TEST - NSW // var zee_id = 626844 // TEST - QLD // var zee_id = 626428 // TEST - VIC // var zee_id = 626845 // TEST - WA var zee_name = searchResultZee.getValue({ name: "entityid"}); log.debug({ title: 'Zee Name', details: zee_name }); //SEARCH: RP - Service Leg Frequency - All - Create App Jobs // if (day != 0 && day != 6){ var runPlanSearch; new_day = day + 1; log.debug({ title: 'day', details: 'New Day' + new_day + 'Old Day' + day }); switch (new_day){ case 1: runPlanSearch = search.load({ type: 'customrecord_service_leg', id: 'customsearch_rp_leg_freq_create_app_mon'}); break; case 2: runPlanSearch = search.load({ type: 'customrecord_service_leg', id: 'customsearch_rp_leg_freq_create_app_tue'}); break; case 3: runPlanSearch = search.load({ type: 'customrecord_service_leg', id: 'customsearch_rp_leg_freq_create_app_wed'}); break; case 4: runPlanSearch = search.load({ type: 'customrecord_service_leg', id: 'customsearch_rp_leg_freq_create_app_thu'}); break; case 5: runPlanSearch = search.load({ type: 'customrecord_service_leg', id: 'customsearch_rp_leg_freq_create_app_fri'}); break; } log.debug({ title: 'runPlanSearch', details: runPlanSearch }) // } // var runPlanSearch = search.load({ type: 'customrecord_service_leg', id: 'customsearch_rp_leg_freq_create_app_jo_2'}); // customsearch_rp_leg_freq_create_app_jo_2 or customsearch_rp_leg_freq_create_app_jobs // log.debug({ // title: 'days_of_week[day]', // details: days_of_week[day] // }); // log.debug({ // title: 'service_leg_customer', // details: service_leg_customer // }); if (day != 0 && day != 6) { var filterExpression = []; var filterExpression = runPlanSearch.filterExpression; filterExpression.push('AND'); filterExpression.push([ [days_of_week[day + 1], search.Operator.IS , 'T'], // customer id "OR", ["custrecord_service_freq_stop.custrecord_service_freq_day_adhoc", search.Operator.IS , 'T'] ]); filterExpression.push("AND", ["isinactive", search.Operator.IS , "F"]); filterExpression.push("AND", ["custrecord_service_leg_customer.partner", search.Operator.IS , zee_id]); filterExpression.push("AND", ["custrecord_service_leg_customer.status", search.Operator.ANYOF, "32", "13"]); filterExpression.push("AND", ["custrecord_service_leg_service.isinactive", search.Operator.IS , "F"]); filterExpression.push("AND", ["custrecord_service_freq_stop.internalid", search.Operator.NONEOF, "@NONE@"]); filterExpression.push("AND", [ ["formulatext: CASE WHEN TO_CHAR({custrecord_service_leg_closing_date}, 'DD/MM/YYYY') <= TO_CHAR(SYSDATE, 'DD/MM/YYYY') THEN 'T' ELSE 'F' END", search.Operator.IS , "F"], "AND", ["formulatext: CASE WHEN TO_CHAR({custrecord_service_leg_opening_date}, 'DD/MM/YYYY') > TO_CHAR(SYSDATE, 'DD/MM/YYYY') THEN 'T' ELSE 'F' END", search.Operator.IS, "F"] ]); filterExpression.push("AND", ["custrecord_app_ser_leg_daily_job_create", search.Operator.ANYOF, "2", "@NONE@"]); // runPlanSearch.filterExpression = filterExpression; } log.debug({ title: 'filterExpression', details: runPlanSearch.filterExpression }); var resultRunPlan = runPlanSearch.run(); // var runPlanResult = resultRunPlan.getResults() // log.debug({ // title: 'Length', // details: runPlanResult.length // }) if (!isNullorEmpty(ctx.getParameter({ name: 'custscript_rp_old_service_id_create_app'}))) { var old_service_id = ctx.getParameter({ name: 'custscript_rp_old_service_id_create_app'}); } else { var old_service_id; } if (!isNullorEmpty(ctx.getParameter({ name: 'custscript_rp_app_job_group_id_create_app'}))) { var app_job_group_id2 = ctx.getParameter({ name: 'custscript_rp_app_job_group_id_create_app'}); } else { var app_job_group_id2; } var count = 0; var exit = false; resultRunPlan.each(function(searchResult) { var service_leg_id = searchResult.getValue({ name: "internalid", join: null, summary: search.Summary.GROUP}); var service_leg_name = searchResult.getValue({ name: "name", join: null, summary: search.Summary.GROUP}); var service_leg_zee = searchResult.getValue({ name: "custrecord_service_leg_franchisee", join: null, summary: search.Summary.GROUP}); var service_leg_customer = searchResult.getValue({ name: "custrecord_service_leg_customer", join: null, summary: search.Summary.GROUP}); var service_leg_customer_text = searchResult.getText({ name: "custrecord_service_leg_customer", join: null, summary: search.Summary.GROUP}); var service_id = searchResult.getValue({ name: "internalid", join: "CUSTRECORD_SERVICE_LEG_SERVICE", summary: search.Summary.GROUP}); var service_leg_service = searchResult.getValue({ name: "custrecord_service_leg_service", join: null, summary: search.Summary.GROUP}); var service_leg_service_text = searchResult.getText({ name: "custrecord_service_leg_service", join: null, summary: search.Summary.GROUP}); var service_price = searchResult.getValue({ name: "custrecord_service_price", join: "CUSTRECORD_SERVICE_LEG_SERVICE", summary: search.Summary.GROUP}); var service_cat = searchResult.getValue({ name: "custrecord_service_category", join: "CUSTRECORD_SERVICE_LEG_SERVICE", summary: search.Summary.GROUP}); var service_leg_no = searchResult.getValue({ name: "custrecord_service_leg_number", join: null, summary: search.Summary.GROUP}); var service_leg_ncl = searchResult.getValue({ name: "custrecord_service_leg_non_cust_location", join: null, summary: search.Summary.GROUP}); var service_leg_addr = searchResult.getValue({ name: "custrecord_service_leg_addr", join: null, summary: search.Summary.GROUP}); var service_leg_addr_postal = searchResult.getValue({ name: "custrecord_service_leg_addr_postal", join: null, summary: search.Summary.GROUP}); var service_leg_addr_subdwelling = searchResult.getValue({ name: "custrecord_service_leg_addr_subdwelling", join: null, summary: search.Summary.GROUP}); var service_leg_addr_st_num = searchResult.getValue({ name: "custrecord_service_leg_addr_st_num_name", join: null, summary: search.Summary.GROUP}); var service_leg_addr_suburb = searchResult.getValue({ name: "custrecord_service_leg_addr_suburb", join: null, summary: search.Summary.GROUP}); var service_leg_addr_state = searchResult.getValue({ name: "custrecord_service_leg_addr_state", join: null, summary: search.Summary.GROUP}); var service_leg_addr_postcode = searchResult.getValue({ name: "custrecord_service_leg_addr_postcode", join: null, summary: search.Summary.GROUP}); var service_leg_addr_lat = searchResult.getValue({ name: "custrecord_service_leg_addr_lat", join: null, summary: search.Summary.GROUP}); var service_leg_addr_lon = searchResult.getValue({ name: "custrecord_service_leg_addr_lon", join: null, summary: search.Summary.GROUP}); var service_leg_type = searchResult.getValue({ name: "custrecord_service_leg_type", join: null, summary: search.Summary.GROUP}); var service_leg_duration = searchResult.getValue({ name: "custrecord_service_leg_duration", join: null, summary: search.Summary.GROUP}); var service_leg_notes = searchResult.getValue({ name: "custrecord_service_leg_notes", join: null, summary: search.Summary.GROUP}); var service_leg_location_type = searchResult.getValue({ name: "custrecord_service_leg_location_type", join: null, summary: search.Summary.GROUP}); var service_leg_transfer_type = searchResult.getValue({ name: "custrecord_service_leg_trf_type", join: null, summary: search.Summary.GROUP}); var service_leg_transfer_linked_stop = searchResult.getValue({ name: "custrecord_service_leg_trf_linked_stop", join: null, summary: search.Summary.GROUP}); var service_freq_id = searchResult.getValue({ name: "internalid", join: "CUSTRECORD_SERVICE_FREQ_STOP", summary: search.Summary.GROUP}); var service_freq_mon = searchResult.getValue({ name: "custrecord_service_freq_day_mon", join: "CUSTRECORD_SERVICE_FREQ_STOP", summary: search.Summary.GROUP}); var service_freq_tue = searchResult.getValue({ name: "custrecord_service_freq_day_tue", join: "CUSTRECORD_SERVICE_FREQ_STOP", summary: search.Summary.GROUP}); var service_freq_wed = searchResult.getValue({ name: "custrecord_service_freq_day_wed", join: "CUSTRECORD_SERVICE_FREQ_STOP", summary: search.Summary.GROUP}); var service_freq_thu = searchResult.getValue({ name: "custrecord_service_freq_day_thu", join: "CUSTRECORD_SERVICE_FREQ_STOP", summary: search.Summary.GROUP}); var service_freq_fri = searchResult.getValue({ name: "custrecord_service_freq_day_fri", join: "CUSTRECORD_SERVICE_FREQ_STOP", summary: search.Summary.GROUP}); var service_freq_adhoc = searchResult.getValue({ name: "custrecord_service_freq_day_adhoc", join: "CUSTRECORD_SERVICE_FREQ_STOP", summary: search.Summary.GROUP}); var service_freq_time_current = searchResult.getValue({ name: "custrecord_service_freq_time_current", join: "CUSTRECORD_SERVICE_FREQ_STOP", summary: search.Summary.GROUP}); var service_freq_time_start = searchResult.getValue({ name: "custrecord_service_freq_time_start", join: "CUSTRECORD_SERVICE_FREQ_STOP", summary: search.Summary.GROUP}); var service_freq_time_end = searchResult.getValue({ name: "custrecord_service_freq_time_end", join: "CUSTRECORD_SERVICE_FREQ_STOP", summary: search.Summary.GROUP}); var service_freq_run_plan_id = searchResult.getValue({ name: "custrecord_service_freq_run_plan", join: "CUSTRECORD_SERVICE_FREQ_STOP", summary: search.Summary.GROUP}); var service_freq_operator = searchResult.getValue({ name: "custrecord_service_freq_operator", join: "CUSTRECORD_SERVICE_FREQ_STOP", summary: search.Summary.GROUP}); var service_freq_zee = searchResult.getValue({ name: "custrecord_service_freq_franchisee", join: "CUSTRECORD_SERVICE_FREQ_STOP", summary: search.Summary.GROUP}); var service_multiple_operators = searchResult.getValue({ name: "custrecord_multiple_operators", join: "CUSTRECORD_SERVICE_LEG_SERVICE", summary: search.Summary.GROUP}); var street_no_name = null; log.debug({ title: 'service_leg_id', details: service_leg_id }); try { // statements if (!isNullorEmpty(service_freq_run_plan_id)) { log.debug({ title: 'service_freq_run_plan_id', details: service_freq_run_plan_id }) var run_plan_record = record.load({ id: service_freq_run_plan_id, type: 'customrecord_run_plan' }) var run_plan_inactive = run_plan_record.getValue({ fieldId: 'isinactive'}); log.debug({ title: 'run_plan_inactive ?', details: run_plan_inactive }) var serviceLegRecord = record.load({ type: 'customrecord_service_freq', id: service_freq_id }); var weekOfDay = serviceLegRecord.getValue({ fieldId: days_of_week2[day + 1]}); log.debug({ title: 'weekOfDay', details: weekOfDay }) if (weekOfDay == false && service_freq_adhoc == false) { } else { if (run_plan_inactive == false) { log.audit({ title: 'Run Plan Inactive = False' }); if (isNullorEmpty(service_leg_addr_subdwelling) && !isNullorEmpty(service_leg_addr_st_num)) { street_no_name = service_leg_addr_st_num; } else if (!isNullorEmpty(service_leg_addr_subdwelling) && isNullorEmpty(service_leg_addr_st_num)) { street_no_name = service_leg_addr_subdwelling; } else { street_no_name = service_leg_addr_subdwelling + ', ' + service_leg_addr_st_num; } service_leg_addr_st_num = street_no_name; if (old_service_id != service_id) { var usage_loopstart_cust = ctx.getRemainingUsage(); log.debug({ title: 'usage_loopstart_cust', details: usage_loopstart_cust }) log.debug({ title: 'usage_threshold', details: usage_threshold }) if (usage_loopstart_cust < usage_threshold) { var params = { custscript_rp_prev_deployment_create_app: ctx.deploymentId, custscript_rp_old_service_id_create_app: old_service_id, custscript_rp_app_job_group_id_create_app: app_job_group_id2 } reschedule = task.create({ taskType: task.TaskType.SCHEDULED_SCRIPT, scriptId: 'customscript_ss_create_app_jobs_2', deploymentId: 'customdeploy_ss_create_app_jobs_2', params: params }); log.audit({​​​​​ title: 'Reschedule Return - IN LOOP' }); var rescheduled = reschedule.submit(); // if (task.checkStatus({​​​​​ taskId: reschedule}​​​​​) == false) {​​​​​ // exit = true; // return false; // }​​​​​ } createAppJobs(service_leg_id, service_leg_customer, service_leg_name, service_id, service_price, service_freq_time_current, service_freq_time_end, service_freq_time_start, service_leg_no, app_job_group_id2, service_leg_addr_st_num, service_leg_addr_suburb, service_leg_addr_state, service_leg_addr_postcode, service_leg_addr_lat, service_leg_addr_lon, service_leg_zee, service_id, service_leg_notes, service_freq_run_plan_id, service_leg_location_type, service_freq_adhoc, service_leg_customer_text, service_multiple_operators); var service_leg_record = record.load({ id: service_leg_id, type: 'customrecord_service_leg' }) service_leg_record.setValue({ fieldId: 'custrecord_app_ser_leg_daily_job_create', value: 1}); var service = service_leg_record.save(); log.audit({ title: 'Service Leg - Saved', details: service }) app_job_group_id2 = createAppJobGroup(service_leg_service_text, service_leg_customer, service_leg_zee, service_id); } else { createAppJobs(service_leg_id, service_leg_customer, service_leg_name, service_id, service_price, service_freq_time_current, service_freq_time_end, service_freq_time_start, service_leg_no, app_job_group_id2, service_leg_addr_st_num, service_leg_addr_suburb, service_leg_addr_state, service_leg_addr_postcode, service_leg_addr_lat, service_leg_addr_lon, service_leg_zee, service_id, service_leg_notes, service_freq_run_plan_id, service_leg_location_type, service_freq_adhoc, service_leg_customer_text, service_multiple_operators); var service_leg_record = record.load({ id: service_leg_id, type: 'customrecord_service_leg' }) service_leg_record.setValue({ fieldId: 'custrecord_app_ser_leg_daily_job_create', value: 1}); service_leg_record.save(); } } log.audit({ title: 'Finised Run Plan' }); } } } catch (e) { // statements var body = 'Error on one of the following: \n'; body += 'Service Leg ID: ' + service_leg_id + '\n'; body += 'Service Leg Freq ID: ' + service_freq_id + '\n'; body += 'Run Plan: ' + service_freq_run_plan_id + '\n'; body += 'e: ' + e + '\n'; email.send({ author: 112209, recipients: 'ankith.ravindran@mailplus.com.au', subject: 'Create App Jobs', body: body}) log.debug({ title: 'ERROR', details: body }); } old_service_id = service_id; count++; return true; }); log.audit({ title: 'Total Count for ' + zee_name, details: count }); if (exit == false) { var zee_record = record.load({type: 'partner', id: zee_id}); zee_record.setValue({ fieldId: 'custentity_zee_app_job_created', value: 1}); // REMEMBER TO UNCOMMENT zee_record.save(); reschedule = task.create({ taskType: task.TaskType.SCHEDULED_SCRIPT, scriptId: 'customscript_ss_create_app_jobs_2', deploymentId: 'customdeploy_ss_create_app_jobs_2' }); log.emergency({​​​​​ title: 'Reschedule Return - END LOOP' }); var rescheduled = reschedule.submit(); // if (task.checkStatus({​​​​​ taskId: rescheduled}​​​​​) == false) {​​​​​ // // exit = true; // log.debug({ // title: 'Reschedule Status False' // }); // return false; // }​​​​​ } // To remove or not too remove?!?!? // return true; }); } function createAppJobGroup(service_leg_service_text, service_leg_customer, service_leg_zee, service_id) { var app_job_group_rec = record.create({ type: 'customrecord_jobgroup' }); log.audit({ title: 'Create Jobs Group Activated', details: app_job_group_rec }); app_job_group_rec.setValue({ fieldId: 'name', value: service_leg_service_text + '_' + date_of_week}); app_job_group_rec.setValue({ fieldId: 'custrecord_jobgroup_ref', value: service_leg_service_text + '_' + date_of_week}); app_job_group_rec.setValue({ fieldId: 'custrecord_jobgroup_customer', value: service_leg_customer}); app_job_group_rec.setValue({ fieldId: 'custrecord_jobgroup_franchisee', value: service_leg_zee}); app_job_group_rec.setValue({ fieldId: 'custrecord_jobgroup_service', value: service_id}); app_job_group_rec.setValue({ fieldId: 'custrecord_jobgroup_status', value: 4}); var app_job_group_id = app_job_group_rec.save(); return app_job_group_id; } function createAppJobs(service_leg_id, service_leg_customer, service_leg_name, service_id, service_price, service_freq_time_current, service_freq_time_end, service_freq_time_start, service_leg_no, app_job_group_id, service_leg_addr_st_num, service_leg_addr_suburb, service_leg_addr_state, service_leg_addr_postcode, service_leg_addr_lat, service_leg_addr_lon, service_leg_zee, service_id, service_leg_notes, service_freq_run_plan_id, service_leg_location_type, service_freq_adhoc, service_leg_customer_text, service_multiple_operators) { var app_job_rec = record.create({ type: 'customrecord_job' }); log.audit({ title: 'Create Jobs Function Activated', details: app_job_rec }); app_job_rec.setValue({ fieldId: 'custrecord_job_franchisee', value: service_leg_zee}); log.audit({ title: 'Adhoc Value', details: service_freq_adhoc }); // if (service_freq_adhoc == 'T') { if (service_freq_adhoc == true) { if (service_leg_location_type == 2) { app_job_rec.setValue({ fieldId:'custrecord_app_job_stop_name', value: 'ADHOC - ' + service_leg_name + ' - ' + service_leg_customer_text}); } else { app_job_rec.setValue({ fieldId:'custrecord_app_job_stop_name', value: 'ADHOC - ' + service_leg_name}); } } else { app_job_rec.setValue({ fieldId: 'custrecord_app_job_stop_name', value: service_leg_name}); } app_job_rec.setValue({ fieldId: 'custrecord_job_customer', value: service_leg_customer}); app_job_rec.setValue({ fieldId: 'custrecord_job_source', value: 6}); app_job_rec.setValue({ fieldId: 'custrecord_job_service', value: service_id}); app_job_rec.setValue({ fieldId: 'custrecord_job_service_price', value: service_price}); app_job_rec.setValue({ fieldId: 'custrecord_job_stop', value: service_leg_id}); app_job_rec.setValue({ fieldId: 'custrecord159', value: service_leg_id}); app_job_rec.setValue({ fieldId: 'custrecord_job_status', value: 1}); var new_date_of_week = format.parse({ type: format.Type.DATE, value: date_of_week }); app_job_rec.setValue({ fieldId: 'custrecord_job_date_scheduled', value: new_date_of_week}); var convert_curr_arr = convertTo24Hour(service_freq_time_current); var curr_arr = convert_curr_arr.split(':'); var curr_1 = parseInt(curr_arr[0]); var curr_2 = parseInt(curr_arr[1]); var currTimeVar = new Date (); currTimeVar.setHours(curr_1, curr_2, 0, 0); app_job_rec.setValue({ fieldId: 'custrecord_job_time_scheduled', value: currTimeVar}); var convert_end_arr = convertTo24Hour(service_freq_time_end); var end_arr = convert_end_arr.split(':'); var end_1 = parseInt(end_arr[0]); var end_2 = parseInt(end_arr[1]); var endTimeVar = new Date (); endTimeVar.setHours(end_1, end_2, 0, 0); app_job_rec.setValue({ fieldId: 'custrecord_job_time_scheduled_after', value: endTimeVar}); var convert_start_arr = convertTo24Hour(service_freq_time_start); var start_arr = convert_start_arr.split(':'); var start_1 = parseInt(start_arr[0]); var start_2 = parseInt(start_arr[1]); var startTimeVar = new Date ();; startTimeVar.setHours(start_1, start_2, 0, 0); app_job_rec.setValue({ fieldId: 'custrecord_job_time_scheduled_before', value: startTimeVar}); app_job_rec.setValue({ fieldId: 'custrecord_job_service_leg', value: service_leg_no}); app_job_rec.setValue({ fieldId: 'custrecord_job_group', value: app_job_group_id}); // app_job_rec.setValue({ fieldId: 'custrecord_job_group_status'}); app_job_rec.setValue({ fieldId: 'custrecord_app_job_st_name_no', value: service_leg_addr_st_num}); app_job_rec.setValue({ fieldId: 'custrecord_app_job_suburb', value: service_leg_addr_suburb}); app_job_rec.setValue({ fieldId: 'custrecord_app_job_state', value: service_leg_addr_state}); app_job_rec.setValue({ fieldId: 'custrecord_app_job_post_code', value: service_leg_addr_postcode}); app_job_rec.setValue({ fieldId: 'custrecord_app_job_lat', value: service_leg_addr_lat}); app_job_rec.setValue({ fieldId: 'custrecord_app_job_lon', value: service_leg_addr_lon}); app_job_rec.setValue({ fieldId: 'custrecord_app_job_notes', value: service_leg_notes}); app_job_rec.setValue({ fieldId: 'custrecord_app_job_run', value: service_freq_run_plan_id}); app_job_rec.setValue({ fieldId: 'custrecord_app_job_location_type', value: service_leg_location_type}); app_job_rec.setValue({ fieldId: 'custrecord_job_multiple_operators', value: service_multiple_operators}); // log.audit({ // title: 'Create App Jobs Completed', // }) var create_app_id = app_job_rec.save(); log.audit({ title: 'Create_App Saved with ID', details: create_app_id }); } function convertTo24Hour(time) { // nlapiLogExecution('DEBUG', 'time', time); var hours = parseInt(time.substr(0, 2)); if (time.indexOf('AM') != -1 && hours == 12) { time = time.replace('12', '0'); } if (time.indexOf('AM') != -1 && hours < 10) { time = time.replace(hours, ('0' + hours)); } if (time.indexOf('PM') != -1 && hours < 12) { time = time.replace(hours, (hours + 12)); } return time.replace(/( AM| PM)/, ''); } function onTimeChange(value) { if (!isNullorEmpty(value)) { var timeSplit = value.split(':'), hours, minutes, meridian; hours = timeSplit[0]; minutes = timeSplit[1]; if (hours > 12) { meridian = 'PM'; hours -= 12; } else if (hours < 12) { meridian = 'AM'; if (hours == 0) { hours = 12; } } else { meridian = 'PM'; } return (hours + ':' + minutes + ' ' + meridian); } } function isNullorEmpty(val) { if (val == '' || val == null) { return true; } else { return false; } } return { execute: main } });
638
[{"tag": "EMAIL", "value": "ankith.ravindran@mailplus.com.au", "start": 26518, "end": 26550}]
true
1
/** * @NApiVersion 2.x * @NScriptType ScheduledScript * @NAmdConfig ./custom_modules_config.json * * Module Description * * @Author: ankith.ravindran * @Date: 2018-09-19 13:20:56 * @Last Modified by: Anesu Chakaingesu * @Last Modified time: 2020-04-30 14:56:03 */ define(['N/ui/serverWidget', 'N/email', 'N/runtime', 'N/search', 'N/record', 'N/http', 'N/log', 'N/redirect', 'N/task', 'moment2', 'N/format'], function(ui, email, runtime, search, record, http, log, redirect, task, moment, format) { // log.debug({ // title: 'moment Defined', // details: JSON.stringify(moment) // }); var days_of_week = []; days_of_week[0] = 0; days_of_week[1] = 'custrecord_service_freq_stop.custrecord_service_freq_day_mon'; days_of_week[2] = 'custrecord_service_freq_stop.custrecord_service_freq_day_tue'; days_of_week[3] = 'custrecord_service_freq_stop.custrecord_service_freq_day_wed'; days_of_week[4] = 'custrecord_service_freq_stop.custrecord_service_freq_day_thu'; days_of_week[5] = 'custrecord_service_freq_stop.custrecord_service_freq_day_fri'; days_of_week[6] = 6; var days_of_week2 = []; days_of_week2[0] = 0; days_of_week2[1] = 'custrecord_service_freq_day_mon'; days_of_week2[2] = 'custrecord_service_freq_day_tue'; days_of_week2[3] = 'custrecord_service_freq_day_wed'; days_of_week2[4] = 'custrecord_service_freq_day_thu'; days_of_week2[5] = 'custrecord_service_freq_day_fri'; days_of_week2[6] = 6; var usage_threshold = 200; //20 var usage_threshold_invoice = 1000; //1000 var adhoc_inv_deploy = 'customdeploy2'; var prev_inv_deploy = null; var ctx = runtime.getCurrentScript(); var date_of_week; function main(){ var day = moment().utc().day(); var date = moment().utc().add(1, 'days').date(); var month = moment().utc().month(); var year = moment().utc().year(); var startDate = moment([year, month]); var endDate = moment(startDate).endOf('month').date(); if(moment().utc().date() == endDate){ date_of_week = date + '/' + (month + 2) + '/' + year; } else { date_of_week = date + '/' + (month + 1) + '/' + year; } // date_of_week = date + '/' + (month + 1) + '/' + year; log.audit({ title: 'moment().utc()', details: moment().utc() }) log.audit({ title: 'day', details: day }) log.audit({ title: 'original date', details: moment().utc().date() }) log.audit({ title: 'date', details: date }) log.audit({ title: 'Last Day of Month', details: endDate }) log.audit({ title: 'month', details: month }) log.audit({ title: 'year', details: year }) log.audit({ title: 'date_of_week', details: date_of_week }) log.audit({ title: 'days_of_week[day + 1]', details: days_of_week[day + 1] }); log.audit({ title: 'days_of_week[day]', details: days_of_week[day] }); log.audit({ title: 'prev_deployment', details: ctx.getParameter({ name: 'custscript_rp_prev_deployment_create_app' }) }) if (!isNullorEmpty(ctx.getParameter({ name: 'custscript_rp_prev_deployment_create_app' }))) { prev_inv_deploy = ctx.getParameter({ name: 'custscript_rp_prev_deployment_create_app' }) } else { prev_inv_deploy = ctx.deploymentId; } var zeeSearch = search.load({ type: 'partner', id: 'customsearch_rp_zee_no_job_created_2_2' }); var resultZee = zeeSearch.run(); //.getRange({ start: 0, end: 1}) // log.audit({ // title: 'searchResultZee', // details: resultZee // }) resultZee.each(function(searchResultZee) { var zee_id = searchResultZee.getValue({ name: "internalid"}); // var zee_id = 215 // Alexandria // var zee_id = 5386 // Arncliffe // var zee_id = 621451 // Gold Coast // var zee_id = 780481 // TEST - ACT // var zee_id = 779884 // TEST - NSW // var zee_id = 626844 // TEST - QLD // var zee_id = 626428 // TEST - VIC // var zee_id = 626845 // TEST - WA var zee_name = searchResultZee.getValue({ name: "entityid"}); log.debug({ title: 'Zee Name', details: zee_name }); //SEARCH: RP - Service Leg Frequency - All - Create App Jobs // if (day != 0 && day != 6){ var runPlanSearch; new_day = day + 1; log.debug({ title: 'day', details: 'New Day' + new_day + 'Old Day' + day }); switch (new_day){ case 1: runPlanSearch = search.load({ type: 'customrecord_service_leg', id: 'customsearch_rp_leg_freq_create_app_mon'}); break; case 2: runPlanSearch = search.load({ type: 'customrecord_service_leg', id: 'customsearch_rp_leg_freq_create_app_tue'}); break; case 3: runPlanSearch = search.load({ type: 'customrecord_service_leg', id: 'customsearch_rp_leg_freq_create_app_wed'}); break; case 4: runPlanSearch = search.load({ type: 'customrecord_service_leg', id: 'customsearch_rp_leg_freq_create_app_thu'}); break; case 5: runPlanSearch = search.load({ type: 'customrecord_service_leg', id: 'customsearch_rp_leg_freq_create_app_fri'}); break; } log.debug({ title: 'runPlanSearch', details: runPlanSearch }) // } // var runPlanSearch = search.load({ type: 'customrecord_service_leg', id: 'customsearch_rp_leg_freq_create_app_jo_2'}); // customsearch_rp_leg_freq_create_app_jo_2 or customsearch_rp_leg_freq_create_app_jobs // log.debug({ // title: 'days_of_week[day]', // details: days_of_week[day] // }); // log.debug({ // title: 'service_leg_customer', // details: service_leg_customer // }); if (day != 0 && day != 6) { var filterExpression = []; var filterExpression = runPlanSearch.filterExpression; filterExpression.push('AND'); filterExpression.push([ [days_of_week[day + 1], search.Operator.IS , 'T'], // customer id "OR", ["custrecord_service_freq_stop.custrecord_service_freq_day_adhoc", search.Operator.IS , 'T'] ]); filterExpression.push("AND", ["isinactive", search.Operator.IS , "F"]); filterExpression.push("AND", ["custrecord_service_leg_customer.partner", search.Operator.IS , zee_id]); filterExpression.push("AND", ["custrecord_service_leg_customer.status", search.Operator.ANYOF, "32", "13"]); filterExpression.push("AND", ["custrecord_service_leg_service.isinactive", search.Operator.IS , "F"]); filterExpression.push("AND", ["custrecord_service_freq_stop.internalid", search.Operator.NONEOF, "@NONE@"]); filterExpression.push("AND", [ ["formulatext: CASE WHEN TO_CHAR({custrecord_service_leg_closing_date}, 'DD/MM/YYYY') <= TO_CHAR(SYSDATE, 'DD/MM/YYYY') THEN 'T' ELSE 'F' END", search.Operator.IS , "F"], "AND", ["formulatext: CASE WHEN TO_CHAR({custrecord_service_leg_opening_date}, 'DD/MM/YYYY') > TO_CHAR(SYSDATE, 'DD/MM/YYYY') THEN 'T' ELSE 'F' END", search.Operator.IS, "F"] ]); filterExpression.push("AND", ["custrecord_app_ser_leg_daily_job_create", search.Operator.ANYOF, "2", "@NONE@"]); // runPlanSearch.filterExpression = filterExpression; } log.debug({ title: 'filterExpression', details: runPlanSearch.filterExpression }); var resultRunPlan = runPlanSearch.run(); // var runPlanResult = resultRunPlan.getResults() // log.debug({ // title: 'Length', // details: runPlanResult.length // }) if (!isNullorEmpty(ctx.getParameter({ name: 'custscript_rp_old_service_id_create_app'}))) { var old_service_id = ctx.getParameter({ name: 'custscript_rp_old_service_id_create_app'}); } else { var old_service_id; } if (!isNullorEmpty(ctx.getParameter({ name: 'custscript_rp_app_job_group_id_create_app'}))) { var app_job_group_id2 = ctx.getParameter({ name: 'custscript_rp_app_job_group_id_create_app'}); } else { var app_job_group_id2; } var count = 0; var exit = false; resultRunPlan.each(function(searchResult) { var service_leg_id = searchResult.getValue({ name: "internalid", join: null, summary: search.Summary.GROUP}); var service_leg_name = searchResult.getValue({ name: "name", join: null, summary: search.Summary.GROUP}); var service_leg_zee = searchResult.getValue({ name: "custrecord_service_leg_franchisee", join: null, summary: search.Summary.GROUP}); var service_leg_customer = searchResult.getValue({ name: "custrecord_service_leg_customer", join: null, summary: search.Summary.GROUP}); var service_leg_customer_text = searchResult.getText({ name: "custrecord_service_leg_customer", join: null, summary: search.Summary.GROUP}); var service_id = searchResult.getValue({ name: "internalid", join: "CUSTRECORD_SERVICE_LEG_SERVICE", summary: search.Summary.GROUP}); var service_leg_service = searchResult.getValue({ name: "custrecord_service_leg_service", join: null, summary: search.Summary.GROUP}); var service_leg_service_text = searchResult.getText({ name: "custrecord_service_leg_service", join: null, summary: search.Summary.GROUP}); var service_price = searchResult.getValue({ name: "custrecord_service_price", join: "CUSTRECORD_SERVICE_LEG_SERVICE", summary: search.Summary.GROUP}); var service_cat = searchResult.getValue({ name: "custrecord_service_category", join: "CUSTRECORD_SERVICE_LEG_SERVICE", summary: search.Summary.GROUP}); var service_leg_no = searchResult.getValue({ name: "custrecord_service_leg_number", join: null, summary: search.Summary.GROUP}); var service_leg_ncl = searchResult.getValue({ name: "custrecord_service_leg_non_cust_location", join: null, summary: search.Summary.GROUP}); var service_leg_addr = searchResult.getValue({ name: "custrecord_service_leg_addr", join: null, summary: search.Summary.GROUP}); var service_leg_addr_postal = searchResult.getValue({ name: "custrecord_service_leg_addr_postal", join: null, summary: search.Summary.GROUP}); var service_leg_addr_subdwelling = searchResult.getValue({ name: "custrecord_service_leg_addr_subdwelling", join: null, summary: search.Summary.GROUP}); var service_leg_addr_st_num = searchResult.getValue({ name: "custrecord_service_leg_addr_st_num_name", join: null, summary: search.Summary.GROUP}); var service_leg_addr_suburb = searchResult.getValue({ name: "custrecord_service_leg_addr_suburb", join: null, summary: search.Summary.GROUP}); var service_leg_addr_state = searchResult.getValue({ name: "custrecord_service_leg_addr_state", join: null, summary: search.Summary.GROUP}); var service_leg_addr_postcode = searchResult.getValue({ name: "custrecord_service_leg_addr_postcode", join: null, summary: search.Summary.GROUP}); var service_leg_addr_lat = searchResult.getValue({ name: "custrecord_service_leg_addr_lat", join: null, summary: search.Summary.GROUP}); var service_leg_addr_lon = searchResult.getValue({ name: "custrecord_service_leg_addr_lon", join: null, summary: search.Summary.GROUP}); var service_leg_type = searchResult.getValue({ name: "custrecord_service_leg_type", join: null, summary: search.Summary.GROUP}); var service_leg_duration = searchResult.getValue({ name: "custrecord_service_leg_duration", join: null, summary: search.Summary.GROUP}); var service_leg_notes = searchResult.getValue({ name: "custrecord_service_leg_notes", join: null, summary: search.Summary.GROUP}); var service_leg_location_type = searchResult.getValue({ name: "custrecord_service_leg_location_type", join: null, summary: search.Summary.GROUP}); var service_leg_transfer_type = searchResult.getValue({ name: "custrecord_service_leg_trf_type", join: null, summary: search.Summary.GROUP}); var service_leg_transfer_linked_stop = searchResult.getValue({ name: "custrecord_service_leg_trf_linked_stop", join: null, summary: search.Summary.GROUP}); var service_freq_id = searchResult.getValue({ name: "internalid", join: "CUSTRECORD_SERVICE_FREQ_STOP", summary: search.Summary.GROUP}); var service_freq_mon = searchResult.getValue({ name: "custrecord_service_freq_day_mon", join: "CUSTRECORD_SERVICE_FREQ_STOP", summary: search.Summary.GROUP}); var service_freq_tue = searchResult.getValue({ name: "custrecord_service_freq_day_tue", join: "CUSTRECORD_SERVICE_FREQ_STOP", summary: search.Summary.GROUP}); var service_freq_wed = searchResult.getValue({ name: "custrecord_service_freq_day_wed", join: "CUSTRECORD_SERVICE_FREQ_STOP", summary: search.Summary.GROUP}); var service_freq_thu = searchResult.getValue({ name: "custrecord_service_freq_day_thu", join: "CUSTRECORD_SERVICE_FREQ_STOP", summary: search.Summary.GROUP}); var service_freq_fri = searchResult.getValue({ name: "custrecord_service_freq_day_fri", join: "CUSTRECORD_SERVICE_FREQ_STOP", summary: search.Summary.GROUP}); var service_freq_adhoc = searchResult.getValue({ name: "custrecord_service_freq_day_adhoc", join: "CUSTRECORD_SERVICE_FREQ_STOP", summary: search.Summary.GROUP}); var service_freq_time_current = searchResult.getValue({ name: "custrecord_service_freq_time_current", join: "CUSTRECORD_SERVICE_FREQ_STOP", summary: search.Summary.GROUP}); var service_freq_time_start = searchResult.getValue({ name: "custrecord_service_freq_time_start", join: "CUSTRECORD_SERVICE_FREQ_STOP", summary: search.Summary.GROUP}); var service_freq_time_end = searchResult.getValue({ name: "custrecord_service_freq_time_end", join: "CUSTRECORD_SERVICE_FREQ_STOP", summary: search.Summary.GROUP}); var service_freq_run_plan_id = searchResult.getValue({ name: "custrecord_service_freq_run_plan", join: "CUSTRECORD_SERVICE_FREQ_STOP", summary: search.Summary.GROUP}); var service_freq_operator = searchResult.getValue({ name: "custrecord_service_freq_operator", join: "CUSTRECORD_SERVICE_FREQ_STOP", summary: search.Summary.GROUP}); var service_freq_zee = searchResult.getValue({ name: "custrecord_service_freq_franchisee", join: "CUSTRECORD_SERVICE_FREQ_STOP", summary: search.Summary.GROUP}); var service_multiple_operators = searchResult.getValue({ name: "custrecord_multiple_operators", join: "CUSTRECORD_SERVICE_LEG_SERVICE", summary: search.Summary.GROUP}); var street_no_name = null; log.debug({ title: 'service_leg_id', details: service_leg_id }); try { // statements if (!isNullorEmpty(service_freq_run_plan_id)) { log.debug({ title: 'service_freq_run_plan_id', details: service_freq_run_plan_id }) var run_plan_record = record.load({ id: service_freq_run_plan_id, type: 'customrecord_run_plan' }) var run_plan_inactive = run_plan_record.getValue({ fieldId: 'isinactive'}); log.debug({ title: 'run_plan_inactive ?', details: run_plan_inactive }) var serviceLegRecord = record.load({ type: 'customrecord_service_freq', id: service_freq_id }); var weekOfDay = serviceLegRecord.getValue({ fieldId: days_of_week2[day + 1]}); log.debug({ title: 'weekOfDay', details: weekOfDay }) if (weekOfDay == false && service_freq_adhoc == false) { } else { if (run_plan_inactive == false) { log.audit({ title: 'Run Plan Inactive = False' }); if (isNullorEmpty(service_leg_addr_subdwelling) && !isNullorEmpty(service_leg_addr_st_num)) { street_no_name = service_leg_addr_st_num; } else if (!isNullorEmpty(service_leg_addr_subdwelling) && isNullorEmpty(service_leg_addr_st_num)) { street_no_name = service_leg_addr_subdwelling; } else { street_no_name = service_leg_addr_subdwelling + ', ' + service_leg_addr_st_num; } service_leg_addr_st_num = street_no_name; if (old_service_id != service_id) { var usage_loopstart_cust = ctx.getRemainingUsage(); log.debug({ title: 'usage_loopstart_cust', details: usage_loopstart_cust }) log.debug({ title: 'usage_threshold', details: usage_threshold }) if (usage_loopstart_cust < usage_threshold) { var params = { custscript_rp_prev_deployment_create_app: ctx.deploymentId, custscript_rp_old_service_id_create_app: old_service_id, custscript_rp_app_job_group_id_create_app: app_job_group_id2 } reschedule = task.create({ taskType: task.TaskType.SCHEDULED_SCRIPT, scriptId: 'customscript_ss_create_app_jobs_2', deploymentId: 'customdeploy_ss_create_app_jobs_2', params: params }); log.audit({​​​​​ title: 'Reschedule Return - IN LOOP' }); var rescheduled = reschedule.submit(); // if (task.checkStatus({​​​​​ taskId: reschedule}​​​​​) == false) {​​​​​ // exit = true; // return false; // }​​​​​ } createAppJobs(service_leg_id, service_leg_customer, service_leg_name, service_id, service_price, service_freq_time_current, service_freq_time_end, service_freq_time_start, service_leg_no, app_job_group_id2, service_leg_addr_st_num, service_leg_addr_suburb, service_leg_addr_state, service_leg_addr_postcode, service_leg_addr_lat, service_leg_addr_lon, service_leg_zee, service_id, service_leg_notes, service_freq_run_plan_id, service_leg_location_type, service_freq_adhoc, service_leg_customer_text, service_multiple_operators); var service_leg_record = record.load({ id: service_leg_id, type: 'customrecord_service_leg' }) service_leg_record.setValue({ fieldId: 'custrecord_app_ser_leg_daily_job_create', value: 1}); var service = service_leg_record.save(); log.audit({ title: 'Service Leg - Saved', details: service }) app_job_group_id2 = createAppJobGroup(service_leg_service_text, service_leg_customer, service_leg_zee, service_id); } else { createAppJobs(service_leg_id, service_leg_customer, service_leg_name, service_id, service_price, service_freq_time_current, service_freq_time_end, service_freq_time_start, service_leg_no, app_job_group_id2, service_leg_addr_st_num, service_leg_addr_suburb, service_leg_addr_state, service_leg_addr_postcode, service_leg_addr_lat, service_leg_addr_lon, service_leg_zee, service_id, service_leg_notes, service_freq_run_plan_id, service_leg_location_type, service_freq_adhoc, service_leg_customer_text, service_multiple_operators); var service_leg_record = record.load({ id: service_leg_id, type: 'customrecord_service_leg' }) service_leg_record.setValue({ fieldId: 'custrecord_app_ser_leg_daily_job_create', value: 1}); service_leg_record.save(); } } log.audit({ title: 'Finised Run Plan' }); } } } catch (e) { // statements var body = 'Error on one of the following: \n'; body += 'Service Leg ID: ' + service_leg_id + '\n'; body += 'Service Leg Freq ID: ' + service_freq_id + '\n'; body += 'Run Plan: ' + service_freq_run_plan_id + '\n'; body += 'e: ' + e + '\n'; email.send({ author: 112209, recipients: 'hzdkv@example.com', subject: 'Create App Jobs', body: body}) log.debug({ title: 'ERROR', details: body }); } old_service_id = service_id; count++; return true; }); log.audit({ title: 'Total Count for ' + zee_name, details: count }); if (exit == false) { var zee_record = record.load({type: 'partner', id: zee_id}); zee_record.setValue({ fieldId: 'custentity_zee_app_job_created', value: 1}); // REMEMBER TO UNCOMMENT zee_record.save(); reschedule = task.create({ taskType: task.TaskType.SCHEDULED_SCRIPT, scriptId: 'customscript_ss_create_app_jobs_2', deploymentId: 'customdeploy_ss_create_app_jobs_2' }); log.emergency({​​​​​ title: 'Reschedule Return - END LOOP' }); var rescheduled = reschedule.submit(); // if (task.checkStatus({​​​​​ taskId: rescheduled}​​​​​) == false) {​​​​​ // // exit = true; // log.debug({ // title: 'Reschedule Status False' // }); // return false; // }​​​​​ } // To remove or not too remove?!?!? // return true; }); } function createAppJobGroup(service_leg_service_text, service_leg_customer, service_leg_zee, service_id) { var app_job_group_rec = record.create({ type: 'customrecord_jobgroup' }); log.audit({ title: 'Create Jobs Group Activated', details: app_job_group_rec }); app_job_group_rec.setValue({ fieldId: 'name', value: service_leg_service_text + '_' + date_of_week}); app_job_group_rec.setValue({ fieldId: 'custrecord_jobgroup_ref', value: service_leg_service_text + '_' + date_of_week}); app_job_group_rec.setValue({ fieldId: 'custrecord_jobgroup_customer', value: service_leg_customer}); app_job_group_rec.setValue({ fieldId: 'custrecord_jobgroup_franchisee', value: service_leg_zee}); app_job_group_rec.setValue({ fieldId: 'custrecord_jobgroup_service', value: service_id}); app_job_group_rec.setValue({ fieldId: 'custrecord_jobgroup_status', value: 4}); var app_job_group_id = app_job_group_rec.save(); return app_job_group_id; } function createAppJobs(service_leg_id, service_leg_customer, service_leg_name, service_id, service_price, service_freq_time_current, service_freq_time_end, service_freq_time_start, service_leg_no, app_job_group_id, service_leg_addr_st_num, service_leg_addr_suburb, service_leg_addr_state, service_leg_addr_postcode, service_leg_addr_lat, service_leg_addr_lon, service_leg_zee, service_id, service_leg_notes, service_freq_run_plan_id, service_leg_location_type, service_freq_adhoc, service_leg_customer_text, service_multiple_operators) { var app_job_rec = record.create({ type: 'customrecord_job' }); log.audit({ title: 'Create Jobs Function Activated', details: app_job_rec }); app_job_rec.setValue({ fieldId: 'custrecord_job_franchisee', value: service_leg_zee}); log.audit({ title: 'Adhoc Value', details: service_freq_adhoc }); // if (service_freq_adhoc == 'T') { if (service_freq_adhoc == true) { if (service_leg_location_type == 2) { app_job_rec.setValue({ fieldId:'custrecord_app_job_stop_name', value: 'ADHOC - ' + service_leg_name + ' - ' + service_leg_customer_text}); } else { app_job_rec.setValue({ fieldId:'custrecord_app_job_stop_name', value: 'ADHOC - ' + service_leg_name}); } } else { app_job_rec.setValue({ fieldId: 'custrecord_app_job_stop_name', value: service_leg_name}); } app_job_rec.setValue({ fieldId: 'custrecord_job_customer', value: service_leg_customer}); app_job_rec.setValue({ fieldId: 'custrecord_job_source', value: 6}); app_job_rec.setValue({ fieldId: 'custrecord_job_service', value: service_id}); app_job_rec.setValue({ fieldId: 'custrecord_job_service_price', value: service_price}); app_job_rec.setValue({ fieldId: 'custrecord_job_stop', value: service_leg_id}); app_job_rec.setValue({ fieldId: 'custrecord159', value: service_leg_id}); app_job_rec.setValue({ fieldId: 'custrecord_job_status', value: 1}); var new_date_of_week = format.parse({ type: format.Type.DATE, value: date_of_week }); app_job_rec.setValue({ fieldId: 'custrecord_job_date_scheduled', value: new_date_of_week}); var convert_curr_arr = convertTo24Hour(service_freq_time_current); var curr_arr = convert_curr_arr.split(':'); var curr_1 = parseInt(curr_arr[0]); var curr_2 = parseInt(curr_arr[1]); var currTimeVar = new Date (); currTimeVar.setHours(curr_1, curr_2, 0, 0); app_job_rec.setValue({ fieldId: 'custrecord_job_time_scheduled', value: currTimeVar}); var convert_end_arr = convertTo24Hour(service_freq_time_end); var end_arr = convert_end_arr.split(':'); var end_1 = parseInt(end_arr[0]); var end_2 = parseInt(end_arr[1]); var endTimeVar = new Date (); endTimeVar.setHours(end_1, end_2, 0, 0); app_job_rec.setValue({ fieldId: 'custrecord_job_time_scheduled_after', value: endTimeVar}); var convert_start_arr = convertTo24Hour(service_freq_time_start); var start_arr = convert_start_arr.split(':'); var start_1 = parseInt(start_arr[0]); var start_2 = parseInt(start_arr[1]); var startTimeVar = new Date ();; startTimeVar.setHours(start_1, start_2, 0, 0); app_job_rec.setValue({ fieldId: 'custrecord_job_time_scheduled_before', value: startTimeVar}); app_job_rec.setValue({ fieldId: 'custrecord_job_service_leg', value: service_leg_no}); app_job_rec.setValue({ fieldId: 'custrecord_job_group', value: app_job_group_id}); // app_job_rec.setValue({ fieldId: 'custrecord_job_group_status'}); app_job_rec.setValue({ fieldId: 'custrecord_app_job_st_name_no', value: service_leg_addr_st_num}); app_job_rec.setValue({ fieldId: 'custrecord_app_job_suburb', value: service_leg_addr_suburb}); app_job_rec.setValue({ fieldId: 'custrecord_app_job_state', value: service_leg_addr_state}); app_job_rec.setValue({ fieldId: 'custrecord_app_job_post_code', value: service_leg_addr_postcode}); app_job_rec.setValue({ fieldId: 'custrecord_app_job_lat', value: service_leg_addr_lat}); app_job_rec.setValue({ fieldId: 'custrecord_app_job_lon', value: service_leg_addr_lon}); app_job_rec.setValue({ fieldId: 'custrecord_app_job_notes', value: service_leg_notes}); app_job_rec.setValue({ fieldId: 'custrecord_app_job_run', value: service_freq_run_plan_id}); app_job_rec.setValue({ fieldId: 'custrecord_app_job_location_type', value: service_leg_location_type}); app_job_rec.setValue({ fieldId: 'custrecord_job_multiple_operators', value: service_multiple_operators}); // log.audit({ // title: 'Create App Jobs Completed', // }) var create_app_id = app_job_rec.save(); log.audit({ title: 'Create_App Saved with ID', details: create_app_id }); } function convertTo24Hour(time) { // nlapiLogExecution('DEBUG', 'time', time); var hours = parseInt(time.substr(0, 2)); if (time.indexOf('AM') != -1 && hours == 12) { time = time.replace('12', '0'); } if (time.indexOf('AM') != -1 && hours < 10) { time = time.replace(hours, ('0' + hours)); } if (time.indexOf('PM') != -1 && hours < 12) { time = time.replace(hours, (hours + 12)); } return time.replace(/( AM| PM)/, ''); } function onTimeChange(value) { if (!isNullorEmpty(value)) { var timeSplit = value.split(':'), hours, minutes, meridian; hours = timeSplit[0]; minutes = timeSplit[1]; if (hours > 12) { meridian = 'PM'; hours -= 12; } else if (hours < 12) { meridian = 'AM'; if (hours == 0) { hours = 12; } } else { meridian = 'PM'; } return (hours + ':' + minutes + ' ' + meridian); } } function isNullorEmpty(val) { if (val == '' || val == null) { return true; } else { return false; } } return { execute: main } });
true
/** * @NApiVersion 2.x * @NScriptType ScheduledScript * @NAmdConfig ./custom_modules_config.json * * Module Description * * @Author: ankith.ravindran * @Date: 2018-09-19 13:20:56 * @Last Modified by: Anesu Chakaingesu * @Last Modified time: 2020-04-30 14:56:03 */ define(['N/ui/serverWidget', 'N/email', 'N/runtime', 'N/search', 'N/record', 'N/http', 'N/log', 'N/redirect', 'N/task', 'moment2', 'N/format'], function(ui, email, runtime, search, record, http, log, redirect, task, moment, format) { // log.debug({ // title: 'moment Defined', // details: JSON.stringify(moment) // }); var days_of_week = []; days_of_week[0] = 0; days_of_week[1] = 'custrecord_service_freq_stop.custrecord_service_freq_day_mon'; days_of_week[2] = 'custrecord_service_freq_stop.custrecord_service_freq_day_tue'; days_of_week[3] = 'custrecord_service_freq_stop.custrecord_service_freq_day_wed'; days_of_week[4] = 'custrecord_service_freq_stop.custrecord_service_freq_day_thu'; days_of_week[5] = 'custrecord_service_freq_stop.custrecord_service_freq_day_fri'; days_of_week[6] = 6; var days_of_week2 = []; days_of_week2[0] = 0; days_of_week2[1] = 'custrecord_service_freq_day_mon'; days_of_week2[2] = 'custrecord_service_freq_day_tue'; days_of_week2[3] = 'custrecord_service_freq_day_wed'; days_of_week2[4] = 'custrecord_service_freq_day_thu'; days_of_week2[5] = 'custrecord_service_freq_day_fri'; days_of_week2[6] = 6; var usage_threshold = 200; //20 var usage_threshold_invoice = 1000; //1000 var adhoc_inv_deploy = 'customdeploy2'; var prev_inv_deploy = null; var ctx = runtime.getCurrentScript(); var date_of_week; function main(){ var day = moment().utc().day(); var date = moment().utc().add(1, 'days').date(); var month = moment().utc().month(); var year = moment().utc().year(); var startDate = moment([year, month]); var endDate = moment(startDate).endOf('month').date(); if(moment().utc().date() == endDate){ date_of_week = date + '/' + (month + 2) + '/' + year; } else { date_of_week = date + '/' + (month + 1) + '/' + year; } // date_of_week = date + '/' + (month + 1) + '/' + year; log.audit({ title: 'moment().utc()', details: moment().utc() }) log.audit({ title: 'day', details: day }) log.audit({ title: 'original date', details: moment().utc().date() }) log.audit({ title: 'date', details: date }) log.audit({ title: 'Last Day of Month', details: endDate }) log.audit({ title: 'month', details: month }) log.audit({ title: 'year', details: year }) log.audit({ title: 'date_of_week', details: date_of_week }) log.audit({ title: 'days_of_week[day + 1]', details: days_of_week[day + 1] }); log.audit({ title: 'days_of_week[day]', details: days_of_week[day] }); log.audit({ title: 'prev_deployment', details: ctx.getParameter({ name: 'custscript_rp_prev_deployment_create_app' }) }) if (!isNullorEmpty(ctx.getParameter({ name: 'custscript_rp_prev_deployment_create_app' }))) { prev_inv_deploy = ctx.getParameter({ name: 'custscript_rp_prev_deployment_create_app' }) } else { prev_inv_deploy = ctx.deploymentId; } var zeeSearch = search.load({ type: 'partner', id: 'customsearch_rp_zee_no_job_created_2_2' }); var resultZee = zeeSearch.run(); //.getRange({ start: 0, end: 1}) // log.audit({ // title: 'searchResultZee', // details: resultZee // }) resultZee.each(function(searchResultZee) { var zee_id = searchResultZee.getValue({ name: "internalid"}); // var zee_id = 215 // Alexandria // var zee_id = 5386 // Arncliffe // var zee_id = 621451 // Gold Coast // var zee_id = 780481 // TEST - ACT // var zee_id = 779884 // TEST - NSW // var zee_id = 626844 // TEST - QLD // var zee_id = 626428 // TEST - VIC // var zee_id = 626845 // TEST - WA var zee_name = searchResultZee.getValue({ name: "entityid"}); log.debug({ title: 'Zee Name', details: zee_name }); //SEARCH: RP - Service Leg Frequency - All - Create App Jobs // if (day != 0 && day != 6){ var runPlanSearch; new_day = day + 1; log.debug({ title: 'day', details: 'New Day' + new_day + 'Old Day' + day }); switch (new_day){ case 1: runPlanSearch = search.load({ type: 'customrecord_service_leg', id: 'customsearch_rp_leg_freq_create_app_mon'}); break; case 2: runPlanSearch = search.load({ type: 'customrecord_service_leg', id: 'customsearch_rp_leg_freq_create_app_tue'}); break; case 3: runPlanSearch = search.load({ type: 'customrecord_service_leg', id: 'customsearch_rp_leg_freq_create_app_wed'}); break; case 4: runPlanSearch = search.load({ type: 'customrecord_service_leg', id: 'customsearch_rp_leg_freq_create_app_thu'}); break; case 5: runPlanSearch = search.load({ type: 'customrecord_service_leg', id: 'customsearch_rp_leg_freq_create_app_fri'}); break; } log.debug({ title: 'runPlanSearch', details: runPlanSearch }) // } // var runPlanSearch = search.load({ type: 'customrecord_service_leg', id: 'customsearch_rp_leg_freq_create_app_jo_2'}); // customsearch_rp_leg_freq_create_app_jo_2 or customsearch_rp_leg_freq_create_app_jobs // log.debug({ // title: 'days_of_week[day]', // details: days_of_week[day] // }); // log.debug({ // title: 'service_leg_customer', // details: service_leg_customer // }); if (day != 0 && day != 6) { var filterExpression = []; var filterExpression = runPlanSearch.filterExpression; filterExpression.push('AND'); filterExpression.push([ [days_of_week[day + 1], search.Operator.IS , 'T'], // customer id "OR", ["custrecord_service_freq_stop.custrecord_service_freq_day_adhoc", search.Operator.IS , 'T'] ]); filterExpression.push("AND", ["isinactive", search.Operator.IS , "F"]); filterExpression.push("AND", ["custrecord_service_leg_customer.partner", search.Operator.IS , zee_id]); filterExpression.push("AND", ["custrecord_service_leg_customer.status", search.Operator.ANYOF, "32", "13"]); filterExpression.push("AND", ["custrecord_service_leg_service.isinactive", search.Operator.IS , "F"]); filterExpression.push("AND", ["custrecord_service_freq_stop.internalid", search.Operator.NONEOF, "@NONE@"]); filterExpression.push("AND", [ ["formulatext: CASE WHEN TO_CHAR({custrecord_service_leg_closing_date}, 'DD/MM/YYYY') <= TO_CHAR(SYSDATE, 'DD/MM/YYYY') THEN 'T' ELSE 'F' END", search.Operator.IS , "F"], "AND", ["formulatext: CASE WHEN TO_CHAR({custrecord_service_leg_opening_date}, 'DD/MM/YYYY') > TO_CHAR(SYSDATE, 'DD/MM/YYYY') THEN 'T' ELSE 'F' END", search.Operator.IS, "F"] ]); filterExpression.push("AND", ["custrecord_app_ser_leg_daily_job_create", search.Operator.ANYOF, "2", "@NONE@"]); // runPlanSearch.filterExpression = filterExpression; } log.debug({ title: 'filterExpression', details: runPlanSearch.filterExpression }); var resultRunPlan = runPlanSearch.run(); // var runPlanResult = resultRunPlan.getResults() // log.debug({ // title: 'Length', // details: runPlanResult.length // }) if (!isNullorEmpty(ctx.getParameter({ name: 'custscript_rp_old_service_id_create_app'}))) { var old_service_id = ctx.getParameter({ name: 'custscript_rp_old_service_id_create_app'}); } else { var old_service_id; } if (!isNullorEmpty(ctx.getParameter({ name: 'custscript_rp_app_job_group_id_create_app'}))) { var app_job_group_id2 = ctx.getParameter({ name: 'custscript_rp_app_job_group_id_create_app'}); } else { var app_job_group_id2; } var count = 0; var exit = false; resultRunPlan.each(function(searchResult) { var service_leg_id = searchResult.getValue({ name: "internalid", join: null, summary: search.Summary.GROUP}); var service_leg_name = searchResult.getValue({ name: "name", join: null, summary: search.Summary.GROUP}); var service_leg_zee = searchResult.getValue({ name: "custrecord_service_leg_franchisee", join: null, summary: search.Summary.GROUP}); var service_leg_customer = searchResult.getValue({ name: "custrecord_service_leg_customer", join: null, summary: search.Summary.GROUP}); var service_leg_customer_text = searchResult.getText({ name: "custrecord_service_leg_customer", join: null, summary: search.Summary.GROUP}); var service_id = searchResult.getValue({ name: "internalid", join: "CUSTRECORD_SERVICE_LEG_SERVICE", summary: search.Summary.GROUP}); var service_leg_service = searchResult.getValue({ name: "custrecord_service_leg_service", join: null, summary: search.Summary.GROUP}); var service_leg_service_text = searchResult.getText({ name: "custrecord_service_leg_service", join: null, summary: search.Summary.GROUP}); var service_price = searchResult.getValue({ name: "custrecord_service_price", join: "CUSTRECORD_SERVICE_LEG_SERVICE", summary: search.Summary.GROUP}); var service_cat = searchResult.getValue({ name: "custrecord_service_category", join: "CUSTRECORD_SERVICE_LEG_SERVICE", summary: search.Summary.GROUP}); var service_leg_no = searchResult.getValue({ name: "custrecord_service_leg_number", join: null, summary: search.Summary.GROUP}); var service_leg_ncl = searchResult.getValue({ name: "custrecord_service_leg_non_cust_location", join: null, summary: search.Summary.GROUP}); var service_leg_addr = searchResult.getValue({ name: "custrecord_service_leg_addr", join: null, summary: search.Summary.GROUP}); var service_leg_addr_postal = searchResult.getValue({ name: "custrecord_service_leg_addr_postal", join: null, summary: search.Summary.GROUP}); var service_leg_addr_subdwelling = searchResult.getValue({ name: "custrecord_service_leg_addr_subdwelling", join: null, summary: search.Summary.GROUP}); var service_leg_addr_st_num = searchResult.getValue({ name: "custrecord_service_leg_addr_st_num_name", join: null, summary: search.Summary.GROUP}); var service_leg_addr_suburb = searchResult.getValue({ name: "custrecord_service_leg_addr_suburb", join: null, summary: search.Summary.GROUP}); var service_leg_addr_state = searchResult.getValue({ name: "custrecord_service_leg_addr_state", join: null, summary: search.Summary.GROUP}); var service_leg_addr_postcode = searchResult.getValue({ name: "custrecord_service_leg_addr_postcode", join: null, summary: search.Summary.GROUP}); var service_leg_addr_lat = searchResult.getValue({ name: "custrecord_service_leg_addr_lat", join: null, summary: search.Summary.GROUP}); var service_leg_addr_lon = searchResult.getValue({ name: "custrecord_service_leg_addr_lon", join: null, summary: search.Summary.GROUP}); var service_leg_type = searchResult.getValue({ name: "custrecord_service_leg_type", join: null, summary: search.Summary.GROUP}); var service_leg_duration = searchResult.getValue({ name: "custrecord_service_leg_duration", join: null, summary: search.Summary.GROUP}); var service_leg_notes = searchResult.getValue({ name: "custrecord_service_leg_notes", join: null, summary: search.Summary.GROUP}); var service_leg_location_type = searchResult.getValue({ name: "custrecord_service_leg_location_type", join: null, summary: search.Summary.GROUP}); var service_leg_transfer_type = searchResult.getValue({ name: "custrecord_service_leg_trf_type", join: null, summary: search.Summary.GROUP}); var service_leg_transfer_linked_stop = searchResult.getValue({ name: "custrecord_service_leg_trf_linked_stop", join: null, summary: search.Summary.GROUP}); var service_freq_id = searchResult.getValue({ name: "internalid", join: "CUSTRECORD_SERVICE_FREQ_STOP", summary: search.Summary.GROUP}); var service_freq_mon = searchResult.getValue({ name: "custrecord_service_freq_day_mon", join: "CUSTRECORD_SERVICE_FREQ_STOP", summary: search.Summary.GROUP}); var service_freq_tue = searchResult.getValue({ name: "custrecord_service_freq_day_tue", join: "CUSTRECORD_SERVICE_FREQ_STOP", summary: search.Summary.GROUP}); var service_freq_wed = searchResult.getValue({ name: "custrecord_service_freq_day_wed", join: "CUSTRECORD_SERVICE_FREQ_STOP", summary: search.Summary.GROUP}); var service_freq_thu = searchResult.getValue({ name: "custrecord_service_freq_day_thu", join: "CUSTRECORD_SERVICE_FREQ_STOP", summary: search.Summary.GROUP}); var service_freq_fri = searchResult.getValue({ name: "custrecord_service_freq_day_fri", join: "CUSTRECORD_SERVICE_FREQ_STOP", summary: search.Summary.GROUP}); var service_freq_adhoc = searchResult.getValue({ name: "custrecord_service_freq_day_adhoc", join: "CUSTRECORD_SERVICE_FREQ_STOP", summary: search.Summary.GROUP}); var service_freq_time_current = searchResult.getValue({ name: "custrecord_service_freq_time_current", join: "CUSTRECORD_SERVICE_FREQ_STOP", summary: search.Summary.GROUP}); var service_freq_time_start = searchResult.getValue({ name: "custrecord_service_freq_time_start", join: "CUSTRECORD_SERVICE_FREQ_STOP", summary: search.Summary.GROUP}); var service_freq_time_end = searchResult.getValue({ name: "custrecord_service_freq_time_end", join: "CUSTRECORD_SERVICE_FREQ_STOP", summary: search.Summary.GROUP}); var service_freq_run_plan_id = searchResult.getValue({ name: "custrecord_service_freq_run_plan", join: "CUSTRECORD_SERVICE_FREQ_STOP", summary: search.Summary.GROUP}); var service_freq_operator = searchResult.getValue({ name: "custrecord_service_freq_operator", join: "CUSTRECORD_SERVICE_FREQ_STOP", summary: search.Summary.GROUP}); var service_freq_zee = searchResult.getValue({ name: "custrecord_service_freq_franchisee", join: "CUSTRECORD_SERVICE_FREQ_STOP", summary: search.Summary.GROUP}); var service_multiple_operators = searchResult.getValue({ name: "custrecord_multiple_operators", join: "CUSTRECORD_SERVICE_LEG_SERVICE", summary: search.Summary.GROUP}); var street_no_name = null; log.debug({ title: 'service_leg_id', details: service_leg_id }); try { // statements if (!isNullorEmpty(service_freq_run_plan_id)) { log.debug({ title: 'service_freq_run_plan_id', details: service_freq_run_plan_id }) var run_plan_record = record.load({ id: service_freq_run_plan_id, type: 'customrecord_run_plan' }) var run_plan_inactive = run_plan_record.getValue({ fieldId: 'isinactive'}); log.debug({ title: 'run_plan_inactive ?', details: run_plan_inactive }) var serviceLegRecord = record.load({ type: 'customrecord_service_freq', id: service_freq_id }); var weekOfDay = serviceLegRecord.getValue({ fieldId: days_of_week2[day + 1]}); log.debug({ title: 'weekOfDay', details: weekOfDay }) if (weekOfDay == false && service_freq_adhoc == false) { } else { if (run_plan_inactive == false) { log.audit({ title: 'Run Plan Inactive = False' }); if (isNullorEmpty(service_leg_addr_subdwelling) && !isNullorEmpty(service_leg_addr_st_num)) { street_no_name = service_leg_addr_st_num; } else if (!isNullorEmpty(service_leg_addr_subdwelling) && isNullorEmpty(service_leg_addr_st_num)) { street_no_name = service_leg_addr_subdwelling; } else { street_no_name = service_leg_addr_subdwelling + ', ' + service_leg_addr_st_num; } service_leg_addr_st_num = street_no_name; if (old_service_id != service_id) { var usage_loopstart_cust = ctx.getRemainingUsage(); log.debug({ title: 'usage_loopstart_cust', details: usage_loopstart_cust }) log.debug({ title: 'usage_threshold', details: usage_threshold }) if (usage_loopstart_cust < usage_threshold) { var params = { custscript_rp_prev_deployment_create_app: ctx.deploymentId, custscript_rp_old_service_id_create_app: old_service_id, custscript_rp_app_job_group_id_create_app: app_job_group_id2 } reschedule = task.create({ taskType: task.TaskType.SCHEDULED_SCRIPT, scriptId: 'customscript_ss_create_app_jobs_2', deploymentId: 'customdeploy_ss_create_app_jobs_2', params: params }); log.audit({​​​​​ title: 'Reschedule Return - IN LOOP' }); var rescheduled = reschedule.submit(); // if (task.checkStatus({​​​​​ taskId: reschedule}​​​​​) == false) {​​​​​ // exit = true; // return false; // }​​​​​ } createAppJobs(service_leg_id, service_leg_customer, service_leg_name, service_id, service_price, service_freq_time_current, service_freq_time_end, service_freq_time_start, service_leg_no, app_job_group_id2, service_leg_addr_st_num, service_leg_addr_suburb, service_leg_addr_state, service_leg_addr_postcode, service_leg_addr_lat, service_leg_addr_lon, service_leg_zee, service_id, service_leg_notes, service_freq_run_plan_id, service_leg_location_type, service_freq_adhoc, service_leg_customer_text, service_multiple_operators); var service_leg_record = record.load({ id: service_leg_id, type: 'customrecord_service_leg' }) service_leg_record.setValue({ fieldId: 'custrecord_app_ser_leg_daily_job_create', value: 1}); var service = service_leg_record.save(); log.audit({ title: 'Service Leg - Saved', details: service }) app_job_group_id2 = createAppJobGroup(service_leg_service_text, service_leg_customer, service_leg_zee, service_id); } else { createAppJobs(service_leg_id, service_leg_customer, service_leg_name, service_id, service_price, service_freq_time_current, service_freq_time_end, service_freq_time_start, service_leg_no, app_job_group_id2, service_leg_addr_st_num, service_leg_addr_suburb, service_leg_addr_state, service_leg_addr_postcode, service_leg_addr_lat, service_leg_addr_lon, service_leg_zee, service_id, service_leg_notes, service_freq_run_plan_id, service_leg_location_type, service_freq_adhoc, service_leg_customer_text, service_multiple_operators); var service_leg_record = record.load({ id: service_leg_id, type: 'customrecord_service_leg' }) service_leg_record.setValue({ fieldId: 'custrecord_app_ser_leg_daily_job_create', value: 1}); service_leg_record.save(); } } log.audit({ title: 'Finised Run Plan' }); } } } catch (e) { // statements var body = 'Error on one of the following: \n'; body += 'Service Leg ID: ' + service_leg_id + '\n'; body += 'Service Leg Freq ID: ' + service_freq_id + '\n'; body += 'Run Plan: ' + service_freq_run_plan_id + '\n'; body += 'e: ' + e + '\n'; email.send({ author: 112209, recipients: 'PI:EMAIL:hzdkv@example.comEND_PI', subject: 'Create App Jobs', body: body}) log.debug({ title: 'ERROR', details: body }); } old_service_id = service_id; count++; return true; }); log.audit({ title: 'Total Count for ' + zee_name, details: count }); if (exit == false) { var zee_record = record.load({type: 'partner', id: zee_id}); zee_record.setValue({ fieldId: 'custentity_zee_app_job_created', value: 1}); // REMEMBER TO UNCOMMENT zee_record.save(); reschedule = task.create({ taskType: task.TaskType.SCHEDULED_SCRIPT, scriptId: 'customscript_ss_create_app_jobs_2', deploymentId: 'customdeploy_ss_create_app_jobs_2' }); log.emergency({​​​​​ title: 'Reschedule Return - END LOOP' }); var rescheduled = reschedule.submit(); // if (task.checkStatus({​​​​​ taskId: rescheduled}​​​​​) == false) {​​​​​ // // exit = true; // log.debug({ // title: 'Reschedule Status False' // }); // return false; // }​​​​​ } // To remove or not too remove?!?!? // return true; }); } function createAppJobGroup(service_leg_service_text, service_leg_customer, service_leg_zee, service_id) { var app_job_group_rec = record.create({ type: 'customrecord_jobgroup' }); log.audit({ title: 'Create Jobs Group Activated', details: app_job_group_rec }); app_job_group_rec.setValue({ fieldId: 'name', value: service_leg_service_text + '_' + date_of_week}); app_job_group_rec.setValue({ fieldId: 'custrecord_jobgroup_ref', value: service_leg_service_text + '_' + date_of_week}); app_job_group_rec.setValue({ fieldId: 'custrecord_jobgroup_customer', value: service_leg_customer}); app_job_group_rec.setValue({ fieldId: 'custrecord_jobgroup_franchisee', value: service_leg_zee}); app_job_group_rec.setValue({ fieldId: 'custrecord_jobgroup_service', value: service_id}); app_job_group_rec.setValue({ fieldId: 'custrecord_jobgroup_status', value: 4}); var app_job_group_id = app_job_group_rec.save(); return app_job_group_id; } function createAppJobs(service_leg_id, service_leg_customer, service_leg_name, service_id, service_price, service_freq_time_current, service_freq_time_end, service_freq_time_start, service_leg_no, app_job_group_id, service_leg_addr_st_num, service_leg_addr_suburb, service_leg_addr_state, service_leg_addr_postcode, service_leg_addr_lat, service_leg_addr_lon, service_leg_zee, service_id, service_leg_notes, service_freq_run_plan_id, service_leg_location_type, service_freq_adhoc, service_leg_customer_text, service_multiple_operators) { var app_job_rec = record.create({ type: 'customrecord_job' }); log.audit({ title: 'Create Jobs Function Activated', details: app_job_rec }); app_job_rec.setValue({ fieldId: 'custrecord_job_franchisee', value: service_leg_zee}); log.audit({ title: 'Adhoc Value', details: service_freq_adhoc }); // if (service_freq_adhoc == 'T') { if (service_freq_adhoc == true) { if (service_leg_location_type == 2) { app_job_rec.setValue({ fieldId:'custrecord_app_job_stop_name', value: 'ADHOC - ' + service_leg_name + ' - ' + service_leg_customer_text}); } else { app_job_rec.setValue({ fieldId:'custrecord_app_job_stop_name', value: 'ADHOC - ' + service_leg_name}); } } else { app_job_rec.setValue({ fieldId: 'custrecord_app_job_stop_name', value: service_leg_name}); } app_job_rec.setValue({ fieldId: 'custrecord_job_customer', value: service_leg_customer}); app_job_rec.setValue({ fieldId: 'custrecord_job_source', value: 6}); app_job_rec.setValue({ fieldId: 'custrecord_job_service', value: service_id}); app_job_rec.setValue({ fieldId: 'custrecord_job_service_price', value: service_price}); app_job_rec.setValue({ fieldId: 'custrecord_job_stop', value: service_leg_id}); app_job_rec.setValue({ fieldId: 'custrecord159', value: service_leg_id}); app_job_rec.setValue({ fieldId: 'custrecord_job_status', value: 1}); var new_date_of_week = format.parse({ type: format.Type.DATE, value: date_of_week }); app_job_rec.setValue({ fieldId: 'custrecord_job_date_scheduled', value: new_date_of_week}); var convert_curr_arr = convertTo24Hour(service_freq_time_current); var curr_arr = convert_curr_arr.split(':'); var curr_1 = parseInt(curr_arr[0]); var curr_2 = parseInt(curr_arr[1]); var currTimeVar = new Date (); currTimeVar.setHours(curr_1, curr_2, 0, 0); app_job_rec.setValue({ fieldId: 'custrecord_job_time_scheduled', value: currTimeVar}); var convert_end_arr = convertTo24Hour(service_freq_time_end); var end_arr = convert_end_arr.split(':'); var end_1 = parseInt(end_arr[0]); var end_2 = parseInt(end_arr[1]); var endTimeVar = new Date (); endTimeVar.setHours(end_1, end_2, 0, 0); app_job_rec.setValue({ fieldId: 'custrecord_job_time_scheduled_after', value: endTimeVar}); var convert_start_arr = convertTo24Hour(service_freq_time_start); var start_arr = convert_start_arr.split(':'); var start_1 = parseInt(start_arr[0]); var start_2 = parseInt(start_arr[1]); var startTimeVar = new Date ();; startTimeVar.setHours(start_1, start_2, 0, 0); app_job_rec.setValue({ fieldId: 'custrecord_job_time_scheduled_before', value: startTimeVar}); app_job_rec.setValue({ fieldId: 'custrecord_job_service_leg', value: service_leg_no}); app_job_rec.setValue({ fieldId: 'custrecord_job_group', value: app_job_group_id}); // app_job_rec.setValue({ fieldId: 'custrecord_job_group_status'}); app_job_rec.setValue({ fieldId: 'custrecord_app_job_st_name_no', value: service_leg_addr_st_num}); app_job_rec.setValue({ fieldId: 'custrecord_app_job_suburb', value: service_leg_addr_suburb}); app_job_rec.setValue({ fieldId: 'custrecord_app_job_state', value: service_leg_addr_state}); app_job_rec.setValue({ fieldId: 'custrecord_app_job_post_code', value: service_leg_addr_postcode}); app_job_rec.setValue({ fieldId: 'custrecord_app_job_lat', value: service_leg_addr_lat}); app_job_rec.setValue({ fieldId: 'custrecord_app_job_lon', value: service_leg_addr_lon}); app_job_rec.setValue({ fieldId: 'custrecord_app_job_notes', value: service_leg_notes}); app_job_rec.setValue({ fieldId: 'custrecord_app_job_run', value: service_freq_run_plan_id}); app_job_rec.setValue({ fieldId: 'custrecord_app_job_location_type', value: service_leg_location_type}); app_job_rec.setValue({ fieldId: 'custrecord_job_multiple_operators', value: service_multiple_operators}); // log.audit({ // title: 'Create App Jobs Completed', // }) var create_app_id = app_job_rec.save(); log.audit({ title: 'Create_App Saved with ID', details: create_app_id }); } function convertTo24Hour(time) { // nlapiLogExecution('DEBUG', 'time', time); var hours = parseInt(time.substr(0, 2)); if (time.indexOf('AM') != -1 && hours == 12) { time = time.replace('12', '0'); } if (time.indexOf('AM') != -1 && hours < 10) { time = time.replace(hours, ('0' + hours)); } if (time.indexOf('PM') != -1 && hours < 12) { time = time.replace(hours, (hours + 12)); } return time.replace(/( AM| PM)/, ''); } function onTimeChange(value) { if (!isNullorEmpty(value)) { var timeSplit = value.split(':'), hours, minutes, meridian; hours = timeSplit[0]; minutes = timeSplit[1]; if (hours > 12) { meridian = 'PM'; hours -= 12; } else if (hours < 12) { meridian = 'AM'; if (hours == 0) { hours = 12; } } else { meridian = 'PM'; } return (hours + ':' + minutes + ' ' + meridian); } } function isNullorEmpty(val) { if (val == '' || val == null) { return true; } else { return false; } } return { execute: main } });
/** * @NApiVersion 2.0 * @NScriptType Suitelet * Author: Ankith Ravindran * Created on: Wed Apr 19 2023 * Modified on: Wed Apr 19 2023 09:02:52 * SuiteScript Version: 2.0 * Description: Customer cancellation page. * * Copyright (c) 2023 MailPlus Pty. Ltd. */ define(['N/ui/serverWidget', 'N/runtime', 'N/search', 'N/record', 'N/log', 'N/redirect', 'N/error', 'N/currentRecord', 'N/file', 'N/http', 'N/email', 'N/format'], function (ui, runtime, search, record, log, redirect, error, currentRecord, file, http, email, format) { var zee = 0; var role = 0; var baseURL = 'https://1048144.app.netsuite.com'; if (runtime.EnvType == "SANDBOX") { baseURL = 'https://1048144-sb3.app.netsuite.com'; } role = runtime.getCurrentUser().role; if (role == 1000) { zee = runtime.getCurrentUser().id; } else if (role == 3) { //Administrator zee = 6; //test } else if (role == 1032) { // System Support zee = 425904; //test-AR } function onRequest(context) { var type = 'create'; if (context.request.method === 'GET') { var customer_id = null; var customer_record; var entityid; var companyName = ''; type = context.request.parameters.type; customer_id = context.request.parameters.custid; var customer_record = record.load({ type: record.Type.CUSTOMER, id: customer_id, isDynamic: true }); entityid = customer_record.getValue({ fieldId: 'entityid' }); companyName = customer_record.getValue({ fieldId: 'companyname' }); zee = customer_record.getValue({ fieldId: 'partner' }); var form = ui.createForm({ title: 'Customer Cancellation: <a href="' + baseURL + '/app/common/entity/custjob.nl?id=' + customer_id + '">' + entityid + '</a> ' + companyName }); if (!isNullorEmpty(zee)) { var zeeRecord = record.load({ type: record.Type.PARTNER, id: zee, isDynamic: true }); var franchisee_name = zeeRecord.getValue({ fieldId: 'companyname' }); zee_main_contact_name = zeeRecord.getValue({ fieldId: 'custentity3' }); zee_email = zeeRecord.getValue({ fieldId: 'email' }); zee_main_contact_phone = zeeRecord.getValue({ fieldId: 'custentity2' }); zee_abn = zeeRecord.getValue({ fieldId: 'custentity_abn_franchiserecord' }); } //Customer Status customer_status_id = customer_record.getValue({ fieldId: 'entitystatus' }); // Customer Franchisee Text zeeText = customer_record.getText({ fieldId: 'partner' }); /** * Description - To add all the API's to the begining of the page */ var inlineHtml = '<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"><script src="//code.jquery.com/jquery-1.11.0.min.js"></script><link type="text/css" rel="stylesheet" href="https://cdn.datatables.net/1.10.13/css/jquery.dataTables.min.css"><link href="//netdna.bootstrapcdn.com/bootstrap/3.3.2/css/bootstrap.min.css" rel="stylesheet"><script src="//netdna.bootstrapcdn.com/bootstrap/3.3.2/js/bootstrap.min.js"></script><link rel="stylesheet" href="https://1048144.app.netsuite.com/core/media/media.nl?id=2060796&c=1048144&h=9ee6accfd476c9cae718&_xt=.css"/><script src="https://1048144.app.netsuite.com/core/media/media.nl?id=2060797&c=1048144&h=ef2cda20731d146b5e98&_xt=.js"></script><link type="text/css" rel="stylesheet" href="https://1048144.app.netsuite.com/core/media/media.nl?id=2090583&c=1048144&h=a0ef6ac4e28f91203dfe&_xt=.css">'; inlineHtml += '<div class="container" style="padding-top: 3%;"><div id="alert" class="alert alert-danger fade in"></div></div>'; // Load DataTables inlineHtml += '<link rel="stylesheet" type="text/css" href="//cdn.datatables.net/1.10.21/css/jquery.dataTables.min.css">'; inlineHtml += '<script type="text/javascript" charset="utf8" src="//cdn.datatables.net/1.10.21/js/jquery.dataTables.min.js"></script>'; form.addField({ id: 'upload_file_1', label: 'SERVICE CANCELLATION PROOF - PDF FILE ONLY', type: ui.FieldType.FILE }).updateLayoutType({ layoutType: ui.FieldLayoutType.OUTSIDEBELOW }).isMandatory = true; inlineHtml += '<div class="form-group container open_invoices requester_header">'; inlineHtml += '<div class="row">'; inlineHtml += '<div class="col-xs-12 heading2">'; inlineHtml += '<h4><span class="label label-default col-xs-12" style="background-color: #095c7b;">SERVICE CANCELLATION DETAILS</span></h4>'; inlineHtml += '</div>'; inlineHtml += '</div>'; inlineHtml += '</div>'; inlineHtml += '<div class="form-group container date_effective_section">'; inlineHtml += '<div class="row">'; inlineHtml += '<div class="col-xs-12 "><div class="input-group"><span class="input-group-addon">DATE EFFECTIVE <span class="mandatory" style="color:red">*</span></span><input type="date" id="date_effective" value="" class="form-control date_effective"/></div></div>'; inlineHtml += '</div>'; inlineHtml += '</div>'; inlineHtml += '</select></div></div>'; inlineHtml += '</div>'; inlineHtml += '</div>'; inlineHtml += '<div class="form-group container cancel_reason_div ">'; inlineHtml += '<div class="row">'; inlineHtml += '<div class="col-xs-4 cancel_reason"><div class="input-group"><span class="input-group-addon" id="cancel_reason_text">CANCELATION REASON <span class="mandatory" style="color:red">*</span></span><select id="cancel_reason" class="form-control cancel_reason" ><option></option>'; var industry_search = search.create({ type: 'customlist58', columns: [{ name: 'name' }, { name: 'internalId' }], filters: ['isinactive', 'is', 'false'] }); industry_search.run().each(function (searchResult) { var listValue = searchResult.getValue('name'); var listID = searchResult.getValue('internalId'); inlineHtml += '<option value="' + listID + '">' + listValue + '</option>'; return true; }); inlineHtml += '</select></div></div>'; inlineHtml += '<div class="col-xs-4 cancel_notice"><div class="input-group"><span class="input-group-addon" id="cancel_notice_text">CANCELATION NOTICE <span class="mandatory" style="color:red">*</span></span><select id="cancel_notice" class="form-control cancel_notice" ><option></option>'; var industry_search = search.create({ type: 'customlist_cancellation_notice', columns: [{ name: 'name' }, { name: 'internalId' }], filters: ['isinactive', 'is', 'false'] }); industry_search.run().each(function (searchResult) { var listValue = searchResult.getValue('name'); var listID = searchResult.getValue('internalId'); inlineHtml += '<option value="' + listID + '">' + listValue + '</option>'; return true; }); inlineHtml += '</select></div></div>'; inlineHtml += '<div class="col-xs-4 cancel_comp"><div class="input-group"><span class="input-group-addon" id="cancel_comp_text">CANCELLATION COMPETITOR</span><select id="cancel_comp" class="form-control cancel_comp" ><option></option>'; var industry_search = search.create({ type: 'customlist33', columns: [{ name: 'name' }, { name: 'internalId' }], filters: ['isinactive', 'is', 'false'] }); industry_search.run().each(function (searchResult) { var listValue = searchResult.getValue('name'); var listID = searchResult.getValue('internalId'); inlineHtml += '<option value="' + listID + '">' + listValue + '</option>'; return true; }); inlineHtml += '</select></div></div>'; inlineHtml += '</div>'; inlineHtml += '</div>'; inlineHtml += '<div class="form-group container note_section">'; inlineHtml += '<div class="row">'; inlineHtml += '<div class="col-xs-12 note"><div class="input-group"><span class="input-group-addon" id="note_text">NOTE </span><textarea id="note" class="form-control note" rows="4" cols="50" /></textarea></div></div>'; inlineHtml += '</div>'; inlineHtml += '</div>'; inlineHtml += '</div>'; inlineHtml += '</div>'; // inlineHtml += openInvoicesSection(); form.addField({ id: 'custpage_customer_id', type: ui.FieldType.TEXT, label: 'Customer ID' }).updateDisplayType({ displayType: ui.FieldDisplayType.HIDDEN }).defaultValue = parseInt(customer_id); form.addField({ id: 'custpage_customer_entityid', type: ui.FieldType.TEXT, label: 'Customer ID' }).updateDisplayType({ displayType: ui.FieldDisplayType.HIDDEN }).defaultValue = entityid; form.addField({ id: 'custpage_customer_franchisee', type: ui.FieldType.TEXT, label: 'Franchisee ID' }).updateDisplayType({ displayType: ui.FieldDisplayType.HIDDEN }).defaultValue = zee; form.addField({ id: 'custpage_note', type: ui.FieldType.TEXT, label: 'Note' }).updateDisplayType({ displayType: ui.FieldDisplayType.HIDDEN }) form.addField({ id: 'custpage_email_body', type: ui.FieldType.TEXT, label: 'Email Body' }).updateDisplayType({ displayType: ui.FieldDisplayType.HIDDEN }) form.addField({ id: 'custpage_email_subject', type: ui.FieldType.TEXT, label: 'Email Body' }).updateDisplayType({ displayType: ui.FieldDisplayType.HIDDEN }) form.addField({ id: 'custpage_sale_type', type: ui.FieldType.TEXT, label: 'Email Body' }).updateDisplayType({ displayType: ui.FieldDisplayType.HIDDEN }) form.addField({ id: 'custpage_send_to', type: ui.FieldType.TEXT, label: 'Email Body' }).updateDisplayType({ displayType: ui.FieldDisplayType.HIDDEN }) form.addSubmitButton({ label: 'Submit' }); form.addField({ id: 'preview_table', label: 'inlinehtml', type: 'inlinehtml' }).updateLayoutType({ layoutType: ui.FieldLayoutType.STARTROW }).defaultValue = inlineHtml; form.addResetButton({ id: 'reset', label: 'Reset', functionName: 'onclick_reset()' }); form.addButton({ id: 'back', label: 'Back', functionName: 'onclick_back()' }); form.clientScriptFileId = 6332354; context.response.writePage(form); } else { var customerId = context.request.parameters.custpage_customer_id; var fileObj = context.request.files.upload_file_1; var note = context.request.parameters.custpage_note; var emailBody = context.request.parameters.custpage_email_body; var emailSubject = context.request.parameters.custpage_email_subject; var zee_email = context.request.parameters.custpage_send_to; log.debug({ title: 'customerId', details: customerId }); var proofid = null; if (!isNullorEmpty(fileObj)) { fileObj.folder = 3630868; var file_type = fileObj.fileType; if (file_type == 'PDF') { file_type == 'pdf'; var file_name = getDatePDF() + '_' + parseInt(customerId) + '.' + file_type; var file_name = getDatePDF() + '_service_change_notification_' + parseInt(customerId) + '.' + file_type; } fileObj.name = file_name; if (file_type == 'PDF') { // Create file and upload it to the file cabinet. proofid = fileObj.save(); } else { error.create({ message: 'Must be in PDF format', name: 'PDF_ERROR', notifyOff: true }); } } var customer_record = record.load({ type: record.Type.CUSTOMER, id: parseInt(customerId), isDynamic: true }); var fileEmailAttachObj = null; if (!isNullorEmpty(proofid)) { customer_record.setValue({ fieldId: 'custentity_cancel_proof', value: proofid }); fileEmailAttachObj = file.load({ id: proofid }); } customer_record.save(); // var userNoteRecord = record.create({ // type: record.Type.NOTE, // isDynamic: true // }); // userNoteRecord.setValue({ // fieldId: 'entity', // value: customer_id // }); // userNoteRecord.setValue({ // fieldId: 'title', // value: 'Cancellation' // }); // userNoteRecord.setValue({ // fieldId: 'direction', // value: 1 // }); // userNoteRecord.setValue({ // fieldId: 'notetype', // value: 3 // }); // userNoteRecord.setValue({ // fieldId: 'author', // value: runtime.getCurrentUser().id // }); // userNoteRecord.setValue({ // fieldId: 'notedate', // value: getDateStoreNS() // }); // userNoteRecord.setValue({ // fieldId: 'note', // value: note // }); // var userNoteRecordId = userNoteRecord.save(); if (!isNullorEmpty(fileEmailAttachObj)) { email.send({ author: 112209, recipients: [zee_email], subject: emailSubject, body: emailBody, cc: [ 'fiona.harrison@mailplus.com.au', 'turkan.koc@mailplus.com.au', 'popie.popie@mailplus.com.au' ], attachments: [fileEmailAttachObj], relatedRecords: { entityId: parseInt(customerId), } }); } else { email.send({ author: 112209, recipients: [zee_email], subject: emailSubject, body: emailBody, cc: [ 'fiona.harrison@mailplus.com.au', 'turkan.koc@mailplus.com.au', 'popie.popie@mailplus.com.au' ], relatedRecords: { entityId: parseInt(customerId), } }); } context.response.sendRedirect({ type: http.RedirectType.RECORD, identifier: record.Type.CUSTOMER, id: parseInt(customerId) }); } } /** * A Datatable displaying the open invoices of the customer * @param {Number} ticket_id * @param {String} selector_type * @return {String} inlineHtml */ function openInvoicesSection() { var hide_class_section = ''; // Open invoices header var inlineHtml = '<div class="form-group container open_invoices open_invoices_header ' + hide_class_section + '">'; inlineHtml += '<div class="row">'; inlineHtml += '<div class="col-xs-12 heading2">'; inlineHtml += '<h4><span class="label label-default col-xs-12" style="background-color: #095c7b;">OPEN INVOICES</span></h4>'; inlineHtml += '</div></div></div>'; // Open invoices dropdown field inlineHtml += '<div class="form-group container open_invoices invoices_dropdown ' + hide_class_section + '">'; inlineHtml += '<div class="row">'; inlineHtml += '<div class="col-xs-12 invoices_dropdown_div">'; inlineHtml += '<div class="input-group">'; inlineHtml += '<span class="input-group-addon" id="invoices_dropdown_text">INVOICE STATUS</span>'; inlineHtml += '<select id="invoices_dropdown" class="form-control">'; inlineHtml += '<option value="open" selected>Open</option>'; inlineHtml += '<option value="paidInFull">Paid In Full (last 3 months)</option>'; inlineHtml += '</select>'; inlineHtml += '</div></div></div></div>'; // Open Invoices Datatable inlineHtml += '<div class="form-group container open_invoices open_invoices_table ' + hide_class_section + '">'; inlineHtml += '<div class="row">'; inlineHtml += '<div class="col-xs-12" id="open_invoice_dt_div">'; // It is inserted as inline html in the script mp_cl_open_ticket inlineHtml += '</div></div></div>'; return inlineHtml; } function getDateStoreNS() { var date = new Date(); if (date.getHours() > 6) { date.setDate(date.getDate() + 1); } format.format({ value: date, type: format.Type.DATE, timezone: format.Timezone.AUSTRALIA_SYDNEY }) return date; } function getDatePDF() { var date = (new Date()); // if (date.getHours() > 6) { // date = nlapiAddDays(date, 1); // } // date.setHours(date.getHours() + 17); var date_string = date.getFullYear() + '' + (date.getMonth() + 1) + '' + date.getDate() + '_' + date.getHours() + '' + date.getMinutes(); return date_string; } function pad(s) { return (s < 10) ? '0' + s : s; } function GetFormattedDate(stringDate) { var todayDate = nlapiStringToDate(stringDate); var month = pad(todayDate.getMonth() + 1); var day = pad(todayDate.getDate()); var year = (todayDate.getFullYear()); return year + "-" + month + "-" + day; } function isNullorEmpty(val) { if (val == '' || val == null) { return true; } else { return false; } } return { onRequest: onRequest }; });
1,115
[{"tag": "EMAIL", "value": "fiona.harrison@mailplus.com.au", "start": 17658, "end": 17688}, {"tag": "EMAIL", "value": "turkan.koc@mailplus.com.au", "start": 17720, "end": 17746}, {"tag": "EMAIL", "value": "popie.popie@mailplus.com.au", "start": 17778, "end": 17805}, {"tag": "EMAIL", "value": "fiona.harrison@mailplus.com.au", "start": 18340, "end": 18370}, {"tag": "EMAIL", "value": "turkan.koc@mailplus.com.au", "start": 18402, "end": 18428}, {"tag": "EMAIL", "value": "popie.popie@mailplus.com.au", "start": 18460, "end": 18487}]
true
6
/** * @NApiVersion 2.0 * @NScriptType Suitelet * Author: Ankith Ravindran * Created on: Wed Apr 19 2023 * Modified on: Wed Apr 19 2023 09:02:52 * SuiteScript Version: 2.0 * Description: Customer cancellation page. * * Copyright (c) 2023 MailPlus Pty. Ltd. */ define(['N/ui/serverWidget', 'N/runtime', 'N/search', 'N/record', 'N/log', 'N/redirect', 'N/error', 'N/currentRecord', 'N/file', 'N/http', 'N/email', 'N/format'], function (ui, runtime, search, record, log, redirect, error, currentRecord, file, http, email, format) { var zee = 0; var role = 0; var baseURL = 'https://1048144.app.netsuite.com'; if (runtime.EnvType == "SANDBOX") { baseURL = 'https://1048144-sb3.app.netsuite.com'; } role = runtime.getCurrentUser().role; if (role == 1000) { zee = runtime.getCurrentUser().id; } else if (role == 3) { //Administrator zee = 6; //test } else if (role == 1032) { // System Support zee = 425904; //test-AR } function onRequest(context) { var type = 'create'; if (context.request.method === 'GET') { var customer_id = null; var customer_record; var entityid; var companyName = ''; type = context.request.parameters.type; customer_id = context.request.parameters.custid; var customer_record = record.load({ type: record.Type.CUSTOMER, id: customer_id, isDynamic: true }); entityid = customer_record.getValue({ fieldId: 'entityid' }); companyName = customer_record.getValue({ fieldId: 'companyname' }); zee = customer_record.getValue({ fieldId: 'partner' }); var form = ui.createForm({ title: 'Customer Cancellation: <a href="' + baseURL + '/app/common/entity/custjob.nl?id=' + customer_id + '">' + entityid + '</a> ' + companyName }); if (!isNullorEmpty(zee)) { var zeeRecord = record.load({ type: record.Type.PARTNER, id: zee, isDynamic: true }); var franchisee_name = zeeRecord.getValue({ fieldId: 'companyname' }); zee_main_contact_name = zeeRecord.getValue({ fieldId: 'custentity3' }); zee_email = zeeRecord.getValue({ fieldId: 'email' }); zee_main_contact_phone = zeeRecord.getValue({ fieldId: 'custentity2' }); zee_abn = zeeRecord.getValue({ fieldId: 'custentity_abn_franchiserecord' }); } //Customer Status customer_status_id = customer_record.getValue({ fieldId: 'entitystatus' }); // Customer Franchisee Text zeeText = customer_record.getText({ fieldId: 'partner' }); /** * Description - To add all the API's to the begining of the page */ var inlineHtml = '<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"><script src="//code.jquery.com/jquery-1.11.0.min.js"></script><link type="text/css" rel="stylesheet" href="https://cdn.datatables.net/1.10.13/css/jquery.dataTables.min.css"><link href="//netdna.bootstrapcdn.com/bootstrap/3.3.2/css/bootstrap.min.css" rel="stylesheet"><script src="//netdna.bootstrapcdn.com/bootstrap/3.3.2/js/bootstrap.min.js"></script><link rel="stylesheet" href="https://1048144.app.netsuite.com/core/media/media.nl?id=2060796&c=1048144&h=9ee6accfd476c9cae718&_xt=.css"/><script src="https://1048144.app.netsuite.com/core/media/media.nl?id=2060797&c=1048144&h=ef2cda20731d146b5e98&_xt=.js"></script><link type="text/css" rel="stylesheet" href="https://1048144.app.netsuite.com/core/media/media.nl?id=2090583&c=1048144&h=a0ef6ac4e28f91203dfe&_xt=.css">'; inlineHtml += '<div class="container" style="padding-top: 3%;"><div id="alert" class="alert alert-danger fade in"></div></div>'; // Load DataTables inlineHtml += '<link rel="stylesheet" type="text/css" href="//cdn.datatables.net/1.10.21/css/jquery.dataTables.min.css">'; inlineHtml += '<script type="text/javascript" charset="utf8" src="//cdn.datatables.net/1.10.21/js/jquery.dataTables.min.js"></script>'; form.addField({ id: 'upload_file_1', label: 'SERVICE CANCELLATION PROOF - PDF FILE ONLY', type: ui.FieldType.FILE }).updateLayoutType({ layoutType: ui.FieldLayoutType.OUTSIDEBELOW }).isMandatory = true; inlineHtml += '<div class="form-group container open_invoices requester_header">'; inlineHtml += '<div class="row">'; inlineHtml += '<div class="col-xs-12 heading2">'; inlineHtml += '<h4><span class="label label-default col-xs-12" style="background-color: #095c7b;">SERVICE CANCELLATION DETAILS</span></h4>'; inlineHtml += '</div>'; inlineHtml += '</div>'; inlineHtml += '</div>'; inlineHtml += '<div class="form-group container date_effective_section">'; inlineHtml += '<div class="row">'; inlineHtml += '<div class="col-xs-12 "><div class="input-group"><span class="input-group-addon">DATE EFFECTIVE <span class="mandatory" style="color:red">*</span></span><input type="date" id="date_effective" value="" class="form-control date_effective"/></div></div>'; inlineHtml += '</div>'; inlineHtml += '</div>'; inlineHtml += '</select></div></div>'; inlineHtml += '</div>'; inlineHtml += '</div>'; inlineHtml += '<div class="form-group container cancel_reason_div ">'; inlineHtml += '<div class="row">'; inlineHtml += '<div class="col-xs-4 cancel_reason"><div class="input-group"><span class="input-group-addon" id="cancel_reason_text">CANCELATION REASON <span class="mandatory" style="color:red">*</span></span><select id="cancel_reason" class="form-control cancel_reason" ><option></option>'; var industry_search = search.create({ type: 'customlist58', columns: [{ name: 'name' }, { name: 'internalId' }], filters: ['isinactive', 'is', 'false'] }); industry_search.run().each(function (searchResult) { var listValue = searchResult.getValue('name'); var listID = searchResult.getValue('internalId'); inlineHtml += '<option value="' + listID + '">' + listValue + '</option>'; return true; }); inlineHtml += '</select></div></div>'; inlineHtml += '<div class="col-xs-4 cancel_notice"><div class="input-group"><span class="input-group-addon" id="cancel_notice_text">CANCELATION NOTICE <span class="mandatory" style="color:red">*</span></span><select id="cancel_notice" class="form-control cancel_notice" ><option></option>'; var industry_search = search.create({ type: 'customlist_cancellation_notice', columns: [{ name: 'name' }, { name: 'internalId' }], filters: ['isinactive', 'is', 'false'] }); industry_search.run().each(function (searchResult) { var listValue = searchResult.getValue('name'); var listID = searchResult.getValue('internalId'); inlineHtml += '<option value="' + listID + '">' + listValue + '</option>'; return true; }); inlineHtml += '</select></div></div>'; inlineHtml += '<div class="col-xs-4 cancel_comp"><div class="input-group"><span class="input-group-addon" id="cancel_comp_text">CANCELLATION COMPETITOR</span><select id="cancel_comp" class="form-control cancel_comp" ><option></option>'; var industry_search = search.create({ type: 'customlist33', columns: [{ name: 'name' }, { name: 'internalId' }], filters: ['isinactive', 'is', 'false'] }); industry_search.run().each(function (searchResult) { var listValue = searchResult.getValue('name'); var listID = searchResult.getValue('internalId'); inlineHtml += '<option value="' + listID + '">' + listValue + '</option>'; return true; }); inlineHtml += '</select></div></div>'; inlineHtml += '</div>'; inlineHtml += '</div>'; inlineHtml += '<div class="form-group container note_section">'; inlineHtml += '<div class="row">'; inlineHtml += '<div class="col-xs-12 note"><div class="input-group"><span class="input-group-addon" id="note_text">NOTE </span><textarea id="note" class="form-control note" rows="4" cols="50" /></textarea></div></div>'; inlineHtml += '</div>'; inlineHtml += '</div>'; inlineHtml += '</div>'; inlineHtml += '</div>'; // inlineHtml += openInvoicesSection(); form.addField({ id: 'custpage_customer_id', type: ui.FieldType.TEXT, label: 'Customer ID' }).updateDisplayType({ displayType: ui.FieldDisplayType.HIDDEN }).defaultValue = parseInt(customer_id); form.addField({ id: 'custpage_customer_entityid', type: ui.FieldType.TEXT, label: 'Customer ID' }).updateDisplayType({ displayType: ui.FieldDisplayType.HIDDEN }).defaultValue = entityid; form.addField({ id: 'custpage_customer_franchisee', type: ui.FieldType.TEXT, label: 'Franchisee ID' }).updateDisplayType({ displayType: ui.FieldDisplayType.HIDDEN }).defaultValue = zee; form.addField({ id: 'custpage_note', type: ui.FieldType.TEXT, label: 'Note' }).updateDisplayType({ displayType: ui.FieldDisplayType.HIDDEN }) form.addField({ id: 'custpage_email_body', type: ui.FieldType.TEXT, label: 'Email Body' }).updateDisplayType({ displayType: ui.FieldDisplayType.HIDDEN }) form.addField({ id: 'custpage_email_subject', type: ui.FieldType.TEXT, label: 'Email Body' }).updateDisplayType({ displayType: ui.FieldDisplayType.HIDDEN }) form.addField({ id: 'custpage_sale_type', type: ui.FieldType.TEXT, label: 'Email Body' }).updateDisplayType({ displayType: ui.FieldDisplayType.HIDDEN }) form.addField({ id: 'custpage_send_to', type: ui.FieldType.TEXT, label: 'Email Body' }).updateDisplayType({ displayType: ui.FieldDisplayType.HIDDEN }) form.addSubmitButton({ label: 'Submit' }); form.addField({ id: 'preview_table', label: 'inlinehtml', type: 'inlinehtml' }).updateLayoutType({ layoutType: ui.FieldLayoutType.STARTROW }).defaultValue = inlineHtml; form.addResetButton({ id: 'reset', label: 'Reset', functionName: 'onclick_reset()' }); form.addButton({ id: 'back', label: 'Back', functionName: 'onclick_back()' }); form.clientScriptFileId = 6332354; context.response.writePage(form); } else { var customerId = context.request.parameters.custpage_customer_id; var fileObj = context.request.files.upload_file_1; var note = context.request.parameters.custpage_note; var emailBody = context.request.parameters.custpage_email_body; var emailSubject = context.request.parameters.custpage_email_subject; var zee_email = context.request.parameters.custpage_send_to; log.debug({ title: 'customerId', details: customerId }); var proofid = null; if (!isNullorEmpty(fileObj)) { fileObj.folder = 3630868; var file_type = fileObj.fileType; if (file_type == 'PDF') { file_type == 'pdf'; var file_name = getDatePDF() + '_' + parseInt(customerId) + '.' + file_type; var file_name = getDatePDF() + '_service_change_notification_' + parseInt(customerId) + '.' + file_type; } fileObj.name = file_name; if (file_type == 'PDF') { // Create file and upload it to the file cabinet. proofid = fileObj.save(); } else { error.create({ message: 'Must be in PDF format', name: 'PDF_ERROR', notifyOff: true }); } } var customer_record = record.load({ type: record.Type.CUSTOMER, id: parseInt(customerId), isDynamic: true }); var fileEmailAttachObj = null; if (!isNullorEmpty(proofid)) { customer_record.setValue({ fieldId: 'custentity_cancel_proof', value: proofid }); fileEmailAttachObj = file.load({ id: proofid }); } customer_record.save(); // var userNoteRecord = record.create({ // type: record.Type.NOTE, // isDynamic: true // }); // userNoteRecord.setValue({ // fieldId: 'entity', // value: customer_id // }); // userNoteRecord.setValue({ // fieldId: 'title', // value: 'Cancellation' // }); // userNoteRecord.setValue({ // fieldId: 'direction', // value: 1 // }); // userNoteRecord.setValue({ // fieldId: 'notetype', // value: 3 // }); // userNoteRecord.setValue({ // fieldId: 'author', // value: runtime.getCurrentUser().id // }); // userNoteRecord.setValue({ // fieldId: 'notedate', // value: getDateStoreNS() // }); // userNoteRecord.setValue({ // fieldId: 'note', // value: note // }); // var userNoteRecordId = userNoteRecord.save(); if (!isNullorEmpty(fileEmailAttachObj)) { email.send({ author: 112209, recipients: [zee_email], subject: emailSubject, body: emailBody, cc: [ 'dycjh@example.com', 'dycjh@example.com', 'envkt@example.com' ], attachments: [fileEmailAttachObj], relatedRecords: { entityId: parseInt(customerId), } }); } else { email.send({ author: 112209, recipients: [zee_email], subject: emailSubject, body: emailBody, cc: [ 'dycjh@example.com', 'dycjh@example.com', 'envkt@example.com' ], relatedRecords: { entityId: parseInt(customerId), } }); } context.response.sendRedirect({ type: http.RedirectType.RECORD, identifier: record.Type.CUSTOMER, id: parseInt(customerId) }); } } /** * A Datatable displaying the open invoices of the customer * @param {Number} ticket_id * @param {String} selector_type * @return {String} inlineHtml */ function openInvoicesSection() { var hide_class_section = ''; // Open invoices header var inlineHtml = '<div class="form-group container open_invoices open_invoices_header ' + hide_class_section + '">'; inlineHtml += '<div class="row">'; inlineHtml += '<div class="col-xs-12 heading2">'; inlineHtml += '<h4><span class="label label-default col-xs-12" style="background-color: #095c7b;">OPEN INVOICES</span></h4>'; inlineHtml += '</div></div></div>'; // Open invoices dropdown field inlineHtml += '<div class="form-group container open_invoices invoices_dropdown ' + hide_class_section + '">'; inlineHtml += '<div class="row">'; inlineHtml += '<div class="col-xs-12 invoices_dropdown_div">'; inlineHtml += '<div class="input-group">'; inlineHtml += '<span class="input-group-addon" id="invoices_dropdown_text">INVOICE STATUS</span>'; inlineHtml += '<select id="invoices_dropdown" class="form-control">'; inlineHtml += '<option value="open" selected>Open</option>'; inlineHtml += '<option value="paidInFull">Paid In Full (last 3 months)</option>'; inlineHtml += '</select>'; inlineHtml += '</div></div></div></div>'; // Open Invoices Datatable inlineHtml += '<div class="form-group container open_invoices open_invoices_table ' + hide_class_section + '">'; inlineHtml += '<div class="row">'; inlineHtml += '<div class="col-xs-12" id="open_invoice_dt_div">'; // It is inserted as inline html in the script mp_cl_open_ticket inlineHtml += '</div></div></div>'; return inlineHtml; } function getDateStoreNS() { var date = new Date(); if (date.getHours() > 6) { date.setDate(date.getDate() + 1); } format.format({ value: date, type: format.Type.DATE, timezone: format.Timezone.AUSTRALIA_SYDNEY }) return date; } function getDatePDF() { var date = (new Date()); // if (date.getHours() > 6) { // date = nlapiAddDays(date, 1); // } // date.setHours(date.getHours() + 17); var date_string = date.getFullYear() + '' + (date.getMonth() + 1) + '' + date.getDate() + '_' + date.getHours() + '' + date.getMinutes(); return date_string; } function pad(s) { return (s < 10) ? '0' + s : s; } function GetFormattedDate(stringDate) { var todayDate = nlapiStringToDate(stringDate); var month = pad(todayDate.getMonth() + 1); var day = pad(todayDate.getDate()); var year = (todayDate.getFullYear()); return year + "-" + month + "-" + day; } function isNullorEmpty(val) { if (val == '' || val == null) { return true; } else { return false; } } return { onRequest: onRequest }; });
true
/** * @NApiVersion 2.0 * @NScriptType Suitelet * Author: Ankith Ravindran * Created on: Wed Apr 19 2023 * Modified on: Wed Apr 19 2023 09:02:52 * SuiteScript Version: 2.0 * Description: Customer cancellation page. * * Copyright (c) 2023 MailPlus Pty. Ltd. */ define(['N/ui/serverWidget', 'N/runtime', 'N/search', 'N/record', 'N/log', 'N/redirect', 'N/error', 'N/currentRecord', 'N/file', 'N/http', 'N/email', 'N/format'], function (ui, runtime, search, record, log, redirect, error, currentRecord, file, http, email, format) { var zee = 0; var role = 0; var baseURL = 'https://1048144.app.netsuite.com'; if (runtime.EnvType == "SANDBOX") { baseURL = 'https://1048144-sb3.app.netsuite.com'; } role = runtime.getCurrentUser().role; if (role == 1000) { zee = runtime.getCurrentUser().id; } else if (role == 3) { //Administrator zee = 6; //test } else if (role == 1032) { // System Support zee = 425904; //test-AR } function onRequest(context) { var type = 'create'; if (context.request.method === 'GET') { var customer_id = null; var customer_record; var entityid; var companyName = ''; type = context.request.parameters.type; customer_id = context.request.parameters.custid; var customer_record = record.load({ type: record.Type.CUSTOMER, id: customer_id, isDynamic: true }); entityid = customer_record.getValue({ fieldId: 'entityid' }); companyName = customer_record.getValue({ fieldId: 'companyname' }); zee = customer_record.getValue({ fieldId: 'partner' }); var form = ui.createForm({ title: 'Customer Cancellation: <a href="' + baseURL + '/app/common/entity/custjob.nl?id=' + customer_id + '">' + entityid + '</a> ' + companyName }); if (!isNullorEmpty(zee)) { var zeeRecord = record.load({ type: record.Type.PARTNER, id: zee, isDynamic: true }); var franchisee_name = zeeRecord.getValue({ fieldId: 'companyname' }); zee_main_contact_name = zeeRecord.getValue({ fieldId: 'custentity3' }); zee_email = zeeRecord.getValue({ fieldId: 'email' }); zee_main_contact_phone = zeeRecord.getValue({ fieldId: 'custentity2' }); zee_abn = zeeRecord.getValue({ fieldId: 'custentity_abn_franchiserecord' }); } //Customer Status customer_status_id = customer_record.getValue({ fieldId: 'entitystatus' }); // Customer Franchisee Text zeeText = customer_record.getText({ fieldId: 'partner' }); /** * Description - To add all the API's to the begining of the page */ var inlineHtml = '<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"><script src="//code.jquery.com/jquery-1.11.0.min.js"></script><link type="text/css" rel="stylesheet" href="https://cdn.datatables.net/1.10.13/css/jquery.dataTables.min.css"><link href="//netdna.bootstrapcdn.com/bootstrap/3.3.2/css/bootstrap.min.css" rel="stylesheet"><script src="//netdna.bootstrapcdn.com/bootstrap/3.3.2/js/bootstrap.min.js"></script><link rel="stylesheet" href="https://1048144.app.netsuite.com/core/media/media.nl?id=2060796&c=1048144&h=9ee6accfd476c9cae718&_xt=.css"/><script src="https://1048144.app.netsuite.com/core/media/media.nl?id=2060797&c=1048144&h=ef2cda20731d146b5e98&_xt=.js"></script><link type="text/css" rel="stylesheet" href="https://1048144.app.netsuite.com/core/media/media.nl?id=2090583&c=1048144&h=a0ef6ac4e28f91203dfe&_xt=.css">'; inlineHtml += '<div class="container" style="padding-top: 3%;"><div id="alert" class="alert alert-danger fade in"></div></div>'; // Load DataTables inlineHtml += '<link rel="stylesheet" type="text/css" href="//cdn.datatables.net/1.10.21/css/jquery.dataTables.min.css">'; inlineHtml += '<script type="text/javascript" charset="utf8" src="//cdn.datatables.net/1.10.21/js/jquery.dataTables.min.js"></script>'; form.addField({ id: 'upload_file_1', label: 'SERVICE CANCELLATION PROOF - PDF FILE ONLY', type: ui.FieldType.FILE }).updateLayoutType({ layoutType: ui.FieldLayoutType.OUTSIDEBELOW }).isMandatory = true; inlineHtml += '<div class="form-group container open_invoices requester_header">'; inlineHtml += '<div class="row">'; inlineHtml += '<div class="col-xs-12 heading2">'; inlineHtml += '<h4><span class="label label-default col-xs-12" style="background-color: #095c7b;">SERVICE CANCELLATION DETAILS</span></h4>'; inlineHtml += '</div>'; inlineHtml += '</div>'; inlineHtml += '</div>'; inlineHtml += '<div class="form-group container date_effective_section">'; inlineHtml += '<div class="row">'; inlineHtml += '<div class="col-xs-12 "><div class="input-group"><span class="input-group-addon">DATE EFFECTIVE <span class="mandatory" style="color:red">*</span></span><input type="date" id="date_effective" value="" class="form-control date_effective"/></div></div>'; inlineHtml += '</div>'; inlineHtml += '</div>'; inlineHtml += '</select></div></div>'; inlineHtml += '</div>'; inlineHtml += '</div>'; inlineHtml += '<div class="form-group container cancel_reason_div ">'; inlineHtml += '<div class="row">'; inlineHtml += '<div class="col-xs-4 cancel_reason"><div class="input-group"><span class="input-group-addon" id="cancel_reason_text">CANCELATION REASON <span class="mandatory" style="color:red">*</span></span><select id="cancel_reason" class="form-control cancel_reason" ><option></option>'; var industry_search = search.create({ type: 'customlist58', columns: [{ name: 'name' }, { name: 'internalId' }], filters: ['isinactive', 'is', 'false'] }); industry_search.run().each(function (searchResult) { var listValue = searchResult.getValue('name'); var listID = searchResult.getValue('internalId'); inlineHtml += '<option value="' + listID + '">' + listValue + '</option>'; return true; }); inlineHtml += '</select></div></div>'; inlineHtml += '<div class="col-xs-4 cancel_notice"><div class="input-group"><span class="input-group-addon" id="cancel_notice_text">CANCELATION NOTICE <span class="mandatory" style="color:red">*</span></span><select id="cancel_notice" class="form-control cancel_notice" ><option></option>'; var industry_search = search.create({ type: 'customlist_cancellation_notice', columns: [{ name: 'name' }, { name: 'internalId' }], filters: ['isinactive', 'is', 'false'] }); industry_search.run().each(function (searchResult) { var listValue = searchResult.getValue('name'); var listID = searchResult.getValue('internalId'); inlineHtml += '<option value="' + listID + '">' + listValue + '</option>'; return true; }); inlineHtml += '</select></div></div>'; inlineHtml += '<div class="col-xs-4 cancel_comp"><div class="input-group"><span class="input-group-addon" id="cancel_comp_text">CANCELLATION COMPETITOR</span><select id="cancel_comp" class="form-control cancel_comp" ><option></option>'; var industry_search = search.create({ type: 'customlist33', columns: [{ name: 'name' }, { name: 'internalId' }], filters: ['isinactive', 'is', 'false'] }); industry_search.run().each(function (searchResult) { var listValue = searchResult.getValue('name'); var listID = searchResult.getValue('internalId'); inlineHtml += '<option value="' + listID + '">' + listValue + '</option>'; return true; }); inlineHtml += '</select></div></div>'; inlineHtml += '</div>'; inlineHtml += '</div>'; inlineHtml += '<div class="form-group container note_section">'; inlineHtml += '<div class="row">'; inlineHtml += '<div class="col-xs-12 note"><div class="input-group"><span class="input-group-addon" id="note_text">NOTE </span><textarea id="note" class="form-control note" rows="4" cols="50" /></textarea></div></div>'; inlineHtml += '</div>'; inlineHtml += '</div>'; inlineHtml += '</div>'; inlineHtml += '</div>'; // inlineHtml += openInvoicesSection(); form.addField({ id: 'custpage_customer_id', type: ui.FieldType.TEXT, label: 'Customer ID' }).updateDisplayType({ displayType: ui.FieldDisplayType.HIDDEN }).defaultValue = parseInt(customer_id); form.addField({ id: 'custpage_customer_entityid', type: ui.FieldType.TEXT, label: 'Customer ID' }).updateDisplayType({ displayType: ui.FieldDisplayType.HIDDEN }).defaultValue = entityid; form.addField({ id: 'custpage_customer_franchisee', type: ui.FieldType.TEXT, label: 'Franchisee ID' }).updateDisplayType({ displayType: ui.FieldDisplayType.HIDDEN }).defaultValue = zee; form.addField({ id: 'custpage_note', type: ui.FieldType.TEXT, label: 'Note' }).updateDisplayType({ displayType: ui.FieldDisplayType.HIDDEN }) form.addField({ id: 'custpage_email_body', type: ui.FieldType.TEXT, label: 'Email Body' }).updateDisplayType({ displayType: ui.FieldDisplayType.HIDDEN }) form.addField({ id: 'custpage_email_subject', type: ui.FieldType.TEXT, label: 'Email Body' }).updateDisplayType({ displayType: ui.FieldDisplayType.HIDDEN }) form.addField({ id: 'custpage_sale_type', type: ui.FieldType.TEXT, label: 'Email Body' }).updateDisplayType({ displayType: ui.FieldDisplayType.HIDDEN }) form.addField({ id: 'custpage_send_to', type: ui.FieldType.TEXT, label: 'Email Body' }).updateDisplayType({ displayType: ui.FieldDisplayType.HIDDEN }) form.addSubmitButton({ label: 'Submit' }); form.addField({ id: 'preview_table', label: 'inlinehtml', type: 'inlinehtml' }).updateLayoutType({ layoutType: ui.FieldLayoutType.STARTROW }).defaultValue = inlineHtml; form.addResetButton({ id: 'reset', label: 'Reset', functionName: 'onclick_reset()' }); form.addButton({ id: 'back', label: 'Back', functionName: 'onclick_back()' }); form.clientScriptFileId = 6332354; context.response.writePage(form); } else { var customerId = context.request.parameters.custpage_customer_id; var fileObj = context.request.files.upload_file_1; var note = context.request.parameters.custpage_note; var emailBody = context.request.parameters.custpage_email_body; var emailSubject = context.request.parameters.custpage_email_subject; var zee_email = context.request.parameters.custpage_send_to; log.debug({ title: 'customerId', details: customerId }); var proofid = null; if (!isNullorEmpty(fileObj)) { fileObj.folder = 3630868; var file_type = fileObj.fileType; if (file_type == 'PDF') { file_type == 'pdf'; var file_name = getDatePDF() + '_' + parseInt(customerId) + '.' + file_type; var file_name = getDatePDF() + '_service_change_notification_' + parseInt(customerId) + '.' + file_type; } fileObj.name = file_name; if (file_type == 'PDF') { // Create file and upload it to the file cabinet. proofid = fileObj.save(); } else { error.create({ message: 'Must be in PDF format', name: 'PDF_ERROR', notifyOff: true }); } } var customer_record = record.load({ type: record.Type.CUSTOMER, id: parseInt(customerId), isDynamic: true }); var fileEmailAttachObj = null; if (!isNullorEmpty(proofid)) { customer_record.setValue({ fieldId: 'custentity_cancel_proof', value: proofid }); fileEmailAttachObj = file.load({ id: proofid }); } customer_record.save(); // var userNoteRecord = record.create({ // type: record.Type.NOTE, // isDynamic: true // }); // userNoteRecord.setValue({ // fieldId: 'entity', // value: customer_id // }); // userNoteRecord.setValue({ // fieldId: 'title', // value: 'Cancellation' // }); // userNoteRecord.setValue({ // fieldId: 'direction', // value: 1 // }); // userNoteRecord.setValue({ // fieldId: 'notetype', // value: 3 // }); // userNoteRecord.setValue({ // fieldId: 'author', // value: runtime.getCurrentUser().id // }); // userNoteRecord.setValue({ // fieldId: 'notedate', // value: getDateStoreNS() // }); // userNoteRecord.setValue({ // fieldId: 'note', // value: note // }); // var userNoteRecordId = userNoteRecord.save(); if (!isNullorEmpty(fileEmailAttachObj)) { email.send({ author: 112209, recipients: [zee_email], subject: emailSubject, body: emailBody, cc: [ 'PI:EMAIL:dycjh@example.comEND_PI', 'PI:EMAIL:dycjh@example.comEND_PI', 'PI:EMAIL:envkt@example.comEND_PI' ], attachments: [fileEmailAttachObj], relatedRecords: { entityId: parseInt(customerId), } }); } else { email.send({ author: 112209, recipients: [zee_email], subject: emailSubject, body: emailBody, cc: [ 'PI:EMAIL:dycjh@example.comEND_PI', 'PI:EMAIL:dycjh@example.comEND_PI', 'PI:EMAIL:envkt@example.comEND_PI' ], relatedRecords: { entityId: parseInt(customerId), } }); } context.response.sendRedirect({ type: http.RedirectType.RECORD, identifier: record.Type.CUSTOMER, id: parseInt(customerId) }); } } /** * A Datatable displaying the open invoices of the customer * @param {Number} ticket_id * @param {String} selector_type * @return {String} inlineHtml */ function openInvoicesSection() { var hide_class_section = ''; // Open invoices header var inlineHtml = '<div class="form-group container open_invoices open_invoices_header ' + hide_class_section + '">'; inlineHtml += '<div class="row">'; inlineHtml += '<div class="col-xs-12 heading2">'; inlineHtml += '<h4><span class="label label-default col-xs-12" style="background-color: #095c7b;">OPEN INVOICES</span></h4>'; inlineHtml += '</div></div></div>'; // Open invoices dropdown field inlineHtml += '<div class="form-group container open_invoices invoices_dropdown ' + hide_class_section + '">'; inlineHtml += '<div class="row">'; inlineHtml += '<div class="col-xs-12 invoices_dropdown_div">'; inlineHtml += '<div class="input-group">'; inlineHtml += '<span class="input-group-addon" id="invoices_dropdown_text">INVOICE STATUS</span>'; inlineHtml += '<select id="invoices_dropdown" class="form-control">'; inlineHtml += '<option value="open" selected>Open</option>'; inlineHtml += '<option value="paidInFull">Paid In Full (last 3 months)</option>'; inlineHtml += '</select>'; inlineHtml += '</div></div></div></div>'; // Open Invoices Datatable inlineHtml += '<div class="form-group container open_invoices open_invoices_table ' + hide_class_section + '">'; inlineHtml += '<div class="row">'; inlineHtml += '<div class="col-xs-12" id="open_invoice_dt_div">'; // It is inserted as inline html in the script mp_cl_open_ticket inlineHtml += '</div></div></div>'; return inlineHtml; } function getDateStoreNS() { var date = new Date(); if (date.getHours() > 6) { date.setDate(date.getDate() + 1); } format.format({ value: date, type: format.Type.DATE, timezone: format.Timezone.AUSTRALIA_SYDNEY }) return date; } function getDatePDF() { var date = (new Date()); // if (date.getHours() > 6) { // date = nlapiAddDays(date, 1); // } // date.setHours(date.getHours() + 17); var date_string = date.getFullYear() + '' + (date.getMonth() + 1) + '' + date.getDate() + '_' + date.getHours() + '' + date.getMinutes(); return date_string; } function pad(s) { return (s < 10) ? '0' + s : s; } function GetFormattedDate(stringDate) { var todayDate = nlapiStringToDate(stringDate); var month = pad(todayDate.getMonth() + 1); var day = pad(todayDate.getDate()); var year = (todayDate.getFullYear()); return year + "-" + month + "-" + day; } function isNullorEmpty(val) { if (val == '' || val == null) { return true; } else { return false; } } return { onRequest: onRequest }; });
/** * @NApiVersion 2.x * @NScriptType Suitelet * @NModuleScope SameAccount */ define(['N/https', 'N/ui/serverWidget', 'N/record', '../api/suitebox'], /** * @param {https} https * @param {serverWidget} serverWidget */ function(https, serverWidget, record, suitebox) { /** * Definition of the Suitelet script trigger point. * * @param {Object} context * @param {ServerRequest} context.request - Encapsulation of the incoming request * @param {ServerResponse} context.response - Encapsulation of the Suitelet response * @Since 2015.2 */ function onRequest(context) { var paramReq = context.request.parameters; var idRec = paramReq.recid; var frmRocketBox = serverWidget.createForm({ title: 'RocketBox' }); var fldRecipient = frmRocketBox.addField({ label: 'Recipient', id: 'custpage_rbx_recipient', type: serverWidget.FieldType.SELECT }); var fldFiles = frmRocketBox.addField({ label: 'Files', id: 'custpage_rbx_files', type: serverWidget.FieldType.SELECT }); var fldSubject = frmRocketBox.addField({ label: 'Subject', id: 'custpage_rbx_subject', type: serverWidget.FieldType.TEXT }); var fldMessage = frmRocketBox.addField({ label: 'Message', id: 'custpage_rbx_message', type: serverWidget.FieldType.TEXTAREA }); var recEstimate; try{ recEstimate = record.load({ type: 'estimate', id: idRec }); } catch(err){ } fldFiles.isMandatory = true; fldRecipient.isMandatory = true; fldFiles.addSelectOption({ value: '', text: '' }); fldRecipient.addSelectOption({ value: '', text: '' }); var rbx; try{ rbx = suitebox.folderContents({ folder: { id: recEstimate.getValue('custbody_rbx_folderid') } }); var arrFile = rbx.response.data; for (var i = 0; i < arrFile.length; i++) { fldFiles.addSelectOption({ value: arrFile[i].id, text: arrFile[i].name }); } fldRecipient.addSelectOption({ value: 'patrick.alcomendas@servicerocket.com', text: 'Patrick Alcomendas' }); fldRecipient.addSelectOption({ value: 'janice.cheang@servicerocket.com', text: 'Janice Cheang' }); var fldInfo = frmRocketBox.addField({ label: 'Info', id: 'custpage_rbx_info', type: serverWidget.FieldType.INLINEHTML }); } catch(err){ } if(context.request.method === 'POST'){ var rbxSign = suitebox.requestSign({ "signers":[{ "role": "signer", "email": context.request.parameters.custpage_rbx_recipient }], "source_files": [{ "type": "file", "id": context.request.parameters.custpage_rbx_files }], "parent_folder": { "type": "folder", "id": "156767063747" }, 'email_subject': context.request.parameters.custpage_rbx_subject, 'email_message': context.request.parameters.custpage_rbx_message }); } frmRocketBox.addSubmitButton({label: 'Send to Sign'}); context.response.writePage(frmRocketBox); } return { onRequest: onRequest }; });
712
[{"tag": "EMAIL", "value": "patrick.alcomendas@servicerocket.com", "start": 2216, "end": 2252}, {"tag": "EMAIL", "value": "janice.cheang@servicerocket.com", "start": 2343, "end": 2374}]
true
2
/** * @NApiVersion 2.x * @NScriptType Suitelet * @NModuleScope SameAccount */ define(['N/https', 'N/ui/serverWidget', 'N/record', '../api/suitebox'], /** * @param {https} https * @param {serverWidget} serverWidget */ function(https, serverWidget, record, suitebox) { /** * Definition of the Suitelet script trigger point. * * @param {Object} context * @param {ServerRequest} context.request - Encapsulation of the incoming request * @param {ServerResponse} context.response - Encapsulation of the Suitelet response * @Since 2015.2 */ function onRequest(context) { var paramReq = context.request.parameters; var idRec = paramReq.recid; var frmRocketBox = serverWidget.createForm({ title: 'RocketBox' }); var fldRecipient = frmRocketBox.addField({ label: 'Recipient', id: 'custpage_rbx_recipient', type: serverWidget.FieldType.SELECT }); var fldFiles = frmRocketBox.addField({ label: 'Files', id: 'custpage_rbx_files', type: serverWidget.FieldType.SELECT }); var fldSubject = frmRocketBox.addField({ label: 'Subject', id: 'custpage_rbx_subject', type: serverWidget.FieldType.TEXT }); var fldMessage = frmRocketBox.addField({ label: 'Message', id: 'custpage_rbx_message', type: serverWidget.FieldType.TEXTAREA }); var recEstimate; try{ recEstimate = record.load({ type: 'estimate', id: idRec }); } catch(err){ } fldFiles.isMandatory = true; fldRecipient.isMandatory = true; fldFiles.addSelectOption({ value: '', text: '' }); fldRecipient.addSelectOption({ value: '', text: '' }); var rbx; try{ rbx = suitebox.folderContents({ folder: { id: recEstimate.getValue('custbody_rbx_folderid') } }); var arrFile = rbx.response.data; for (var i = 0; i < arrFile.length; i++) { fldFiles.addSelectOption({ value: arrFile[i].id, text: arrFile[i].name }); } fldRecipient.addSelectOption({ value: 'kenaa@example.com', text: 'Patrick Alcomendas' }); fldRecipient.addSelectOption({ value: 'upchh@example.com', text: 'Janice Cheang' }); var fldInfo = frmRocketBox.addField({ label: 'Info', id: 'custpage_rbx_info', type: serverWidget.FieldType.INLINEHTML }); } catch(err){ } if(context.request.method === 'POST'){ var rbxSign = suitebox.requestSign({ "signers":[{ "role": "signer", "email": context.request.parameters.custpage_rbx_recipient }], "source_files": [{ "type": "file", "id": context.request.parameters.custpage_rbx_files }], "parent_folder": { "type": "folder", "id": "156767063747" }, 'email_subject': context.request.parameters.custpage_rbx_subject, 'email_message': context.request.parameters.custpage_rbx_message }); } frmRocketBox.addSubmitButton({label: 'Send to Sign'}); context.response.writePage(frmRocketBox); } return { onRequest: onRequest }; });
true
/** * @NApiVersion 2.x * @NScriptType Suitelet * @NModuleScope SameAccount */ define(['N/https', 'N/ui/serverWidget', 'N/record', '../api/suitebox'], /** * @param {https} https * @param {serverWidget} serverWidget */ function(https, serverWidget, record, suitebox) { /** * Definition of the Suitelet script trigger point. * * @param {Object} context * @param {ServerRequest} context.request - Encapsulation of the incoming request * @param {ServerResponse} context.response - Encapsulation of the Suitelet response * @Since 2015.2 */ function onRequest(context) { var paramReq = context.request.parameters; var idRec = paramReq.recid; var frmRocketBox = serverWidget.createForm({ title: 'RocketBox' }); var fldRecipient = frmRocketBox.addField({ label: 'Recipient', id: 'custpage_rbx_recipient', type: serverWidget.FieldType.SELECT }); var fldFiles = frmRocketBox.addField({ label: 'Files', id: 'custpage_rbx_files', type: serverWidget.FieldType.SELECT }); var fldSubject = frmRocketBox.addField({ label: 'Subject', id: 'custpage_rbx_subject', type: serverWidget.FieldType.TEXT }); var fldMessage = frmRocketBox.addField({ label: 'Message', id: 'custpage_rbx_message', type: serverWidget.FieldType.TEXTAREA }); var recEstimate; try{ recEstimate = record.load({ type: 'estimate', id: idRec }); } catch(err){ } fldFiles.isMandatory = true; fldRecipient.isMandatory = true; fldFiles.addSelectOption({ value: '', text: '' }); fldRecipient.addSelectOption({ value: '', text: '' }); var rbx; try{ rbx = suitebox.folderContents({ folder: { id: recEstimate.getValue('custbody_rbx_folderid') } }); var arrFile = rbx.response.data; for (var i = 0; i < arrFile.length; i++) { fldFiles.addSelectOption({ value: arrFile[i].id, text: arrFile[i].name }); } fldRecipient.addSelectOption({ value: 'PI:EMAIL:kenaa@example.comEND_PI', text: 'Patrick Alcomendas' }); fldRecipient.addSelectOption({ value: 'PI:EMAIL:upchh@example.comEND_PI', text: 'Janice Cheang' }); var fldInfo = frmRocketBox.addField({ label: 'Info', id: 'custpage_rbx_info', type: serverWidget.FieldType.INLINEHTML }); } catch(err){ } if(context.request.method === 'POST'){ var rbxSign = suitebox.requestSign({ "signers":[{ "role": "signer", "email": context.request.parameters.custpage_rbx_recipient }], "source_files": [{ "type": "file", "id": context.request.parameters.custpage_rbx_files }], "parent_folder": { "type": "folder", "id": "156767063747" }, 'email_subject': context.request.parameters.custpage_rbx_subject, 'email_message': context.request.parameters.custpage_rbx_message }); } frmRocketBox.addSubmitButton({label: 'Send to Sign'}); context.response.writePage(frmRocketBox); } return { onRequest: onRequest }; });
/** * @NApiVersion 2.1 * @NScriptType Portlet * @NModuleScope SameAccount */ /* Modified version of SQL Portlet by β€’ Tim Dietrich β€’ timdietrich@me.com */ // The default portlet title. const default_title = 'Saved SQLSearch'; // The default SQL query. const default_sql = ` SELECT '<a href="/app/site/hosting/scriptlet.nl?script=846&deploy=1&dt=list&sqlid=' || ID || '">' || Name || '</a>' AS Name, '<a href="/app/site/hosting/scriptlet.nl?script=846&deploy=1&dt=list&sqlid=' || ID || '">List</a>' AS View, custrecordsql_description FROM customrecordsql_search WHERE IsInactive = 'F' ORDER BY Name `; var query, runtime; define( [ 'N/query', 'N/runtime' ], main ); function main( queryModule, runtimeModule ) { query = queryModule; runtime = runtimeModule; return { render: renderContent } } function renderContent( params ) { // Get the currently executing script. var scriptObj = runtime.getCurrentScript(); // Get the portlet's title. var title = scriptObj.getParameter( { name: 'custscript_title' } ); if ( title == null ) { title = default_title; } params.portlet.title = title; // Get the SQL to be used. var sql = scriptObj.getParameter( { name: 'custscript_sql' } ); if ( sql == null ) { sql = default_sql; } // Run the query. var queryResults = query.runSuiteQL( { query: sql } ); // Get the mapped results. var records = queryResults.asMappedResults(); // If records were returned... if ( records.length > 0 ) { // Get the column names. var columnNames = Object.keys( records[0] ); // Loop over the column names... for ( i = 0; i < columnNames.length; i++ ) { // Get the column name. var columnName = columnNames[i]; // Add the column to the portlet. params.portlet.addColumn( { id: 'custpage_' + columnName, type: 'text', label: columnName, align: 'LEFT' } ); } // Loop over the records... for ( r = 0; r < records.length; r++ ) { // Get the record. var record = records[r]; // Initialize a row object. var row = {}; // Loop over the columns names... for ( c = 0; c < columnNames.length; c++ ) { // Get the column name. var columnName = columnNames[c]; // Get the column value. var value = record[columnName]; if ( value != null ) { value = value.toString(); } // Add the column to the row object. row['custpage_' + columnName] = value; } // Add the row to the portlet. params.portlet.addRow( { row: row } ); } } }
78
[{"tag": "EMAIL", "value": "timdietrich@me.com", "start": 146, "end": 164}]
true
1
/** * @NApiVersion 2.1 * @NScriptType Portlet * @NModuleScope SameAccount */ /* Modified version of SQL Portlet by β€’ Tim Dietrich β€’ ychag@example.com */ // The default portlet title. const default_title = 'Saved SQLSearch'; // The default SQL query. const default_sql = ` SELECT '<a href="/app/site/hosting/scriptlet.nl?script=846&deploy=1&dt=list&sqlid=' || ID || '">' || Name || '</a>' AS Name, '<a href="/app/site/hosting/scriptlet.nl?script=846&deploy=1&dt=list&sqlid=' || ID || '">List</a>' AS View, custrecordsql_description FROM customrecordsql_search WHERE IsInactive = 'F' ORDER BY Name `; var query, runtime; define( [ 'N/query', 'N/runtime' ], main ); function main( queryModule, runtimeModule ) { query = queryModule; runtime = runtimeModule; return { render: renderContent } } function renderContent( params ) { // Get the currently executing script. var scriptObj = runtime.getCurrentScript(); // Get the portlet's title. var title = scriptObj.getParameter( { name: 'custscript_title' } ); if ( title == null ) { title = default_title; } params.portlet.title = title; // Get the SQL to be used. var sql = scriptObj.getParameter( { name: 'custscript_sql' } ); if ( sql == null ) { sql = default_sql; } // Run the query. var queryResults = query.runSuiteQL( { query: sql } ); // Get the mapped results. var records = queryResults.asMappedResults(); // If records were returned... if ( records.length > 0 ) { // Get the column names. var columnNames = Object.keys( records[0] ); // Loop over the column names... for ( i = 0; i < columnNames.length; i++ ) { // Get the column name. var columnName = columnNames[i]; // Add the column to the portlet. params.portlet.addColumn( { id: 'custpage_' + columnName, type: 'text', label: columnName, align: 'LEFT' } ); } // Loop over the records... for ( r = 0; r < records.length; r++ ) { // Get the record. var record = records[r]; // Initialize a row object. var row = {}; // Loop over the columns names... for ( c = 0; c < columnNames.length; c++ ) { // Get the column name. var columnName = columnNames[c]; // Get the column value. var value = record[columnName]; if ( value != null ) { value = value.toString(); } // Add the column to the row object. row['custpage_' + columnName] = value; } // Add the row to the portlet. params.portlet.addRow( { row: row } ); } } }
true
/** * @NApiVersion 2.1 * @NScriptType Portlet * @NModuleScope SameAccount */ /* Modified version of SQL Portlet by β€’ Tim Dietrich β€’ PI:EMAIL:ychag@example.comEND_PI */ // The default portlet title. const default_title = 'Saved SQLSearch'; // The default SQL query. const default_sql = ` SELECT '<a href="/app/site/hosting/scriptlet.nl?script=846&deploy=1&dt=list&sqlid=' || ID || '">' || Name || '</a>' AS Name, '<a href="/app/site/hosting/scriptlet.nl?script=846&deploy=1&dt=list&sqlid=' || ID || '">List</a>' AS View, custrecordsql_description FROM customrecordsql_search WHERE IsInactive = 'F' ORDER BY Name `; var query, runtime; define( [ 'N/query', 'N/runtime' ], main ); function main( queryModule, runtimeModule ) { query = queryModule; runtime = runtimeModule; return { render: renderContent } } function renderContent( params ) { // Get the currently executing script. var scriptObj = runtime.getCurrentScript(); // Get the portlet's title. var title = scriptObj.getParameter( { name: 'custscript_title' } ); if ( title == null ) { title = default_title; } params.portlet.title = title; // Get the SQL to be used. var sql = scriptObj.getParameter( { name: 'custscript_sql' } ); if ( sql == null ) { sql = default_sql; } // Run the query. var queryResults = query.runSuiteQL( { query: sql } ); // Get the mapped results. var records = queryResults.asMappedResults(); // If records were returned... if ( records.length > 0 ) { // Get the column names. var columnNames = Object.keys( records[0] ); // Loop over the column names... for ( i = 0; i < columnNames.length; i++ ) { // Get the column name. var columnName = columnNames[i]; // Add the column to the portlet. params.portlet.addColumn( { id: 'custpage_' + columnName, type: 'text', label: columnName, align: 'LEFT' } ); } // Loop over the records... for ( r = 0; r < records.length; r++ ) { // Get the record. var record = records[r]; // Initialize a row object. var row = {}; // Loop over the columns names... for ( c = 0; c < columnNames.length; c++ ) { // Get the column name. var columnName = columnNames[c]; // Get the column value. var value = record[columnName]; if ( value != null ) { value = value.toString(); } // Add the column to the row object. row['custpage_' + columnName] = value; } // Add the row to the portlet. params.portlet.addRow( { row: row } ); } } }
define(['N/search'], function(search) { /** * Add Google Map for Address form * @NApiVersion 2.x * @NScriptType ClientScript * @author trungpv <trung@lexor.com> */ /* === VARS === */ /* === EVENTS FUNCTIONS === */ /** * Sublist Changed * @param {*} context */ function sublistChanged(context) { const currentRecord = context.currentRecord; const sublistId = context.sublistId; const operation = context.operation; if (sublistId === 'addressbook') { const defaultbilling = currentRecord.getCurrentSublistValue({ sublistId: sublistId, fieldId: 'defaultbilling' }); const defaultshipping = currentRecord.getCurrentSublistValue({ sublistId: sublistId, fieldId: 'defaultshipping' }); if (operation === 'remove') { // Reset Default Value when remove address if (defaultbilling) { currentRecord.setValue({ fieldId: 'defaultaddress', value: '' }); } if (defaultshipping) { currentRecord.setValue({ fieldId: 'custentity_address_verification', value: '' }); } } else { if (defaultshipping) { const addressbookaddress_text = currentRecord.getCurrentSublistValue({ sublistId: sublistId, fieldId: 'addressbookaddress_text' }); var addressArr = addressbookaddress_text.split('\n'); if (addressArr.length > 3) { currentRecord.setValue({ fieldId: 'custentity_address_verification', value: formatAddressStandardization(addressbookaddress_text) }); } else { currentRecord.setValue({ fieldId: 'custentity_address_verification', value: '' }); } } } } } /** * Page Init * @param {*} context */ function pageInit(context) { console.log('pageInit Triggered!', context); loadCSSText( '.autocomplete{position:relative;display:inline-block}.autocomplete-items{position:absolute;z-index:99;display:inline-block}.autocomplete-items div{padding:10px;cursor:pointer;background-color:#fff;border:1px solid #d4d4d4}.autocomplete-items div:hover{background-color:#e9e9e9}.autocomplete-active{background-color:#1e90ff!important;color:#fff}' ); /*the autocomplete function takes two arguments, the text field element and an array of possible autocompleted values:*/ var currentFocus; var inp = document.getElementById('custentity_search_phone'); /*execute a function when someone writes in the text field:*/ inp.addEventListener('keyup', function(e) { // Press Left Arrow if (e.which === 39) { var a, b, i, val = this.value; var that = this; /*close any already open lists of autocompleted values*/ closeAllLists(); if (!val) { return false; } // Start Search const types = ['Customer', 'Lead', 'Prospect']; search.global .promise({ keywords: val }) .then(function(result) { result = arrayFilter(result, function(o) { if ( (o.getValue({ name: 'info1' }) !== '' || o.getValue({ name: 'info2' }) !== '') && types.includes( o.getValue({ name: 'type' }) ) ) { return o; } }); currentFocus = -1; /*create a DIV element that will contain the items (values):*/ a = document.createElement('DIV'); a.setAttribute('id', this.id + 'autocomplete-list'); a.setAttribute('class', 'autocomplete-items'); const inpPos = offset(inp); a.style.top = inpPos.top + 25 + 'px'; a.style.left = inpPos.left + 'px'; // a.style.display = "block"; /*append the DIV element as a child of the autocomplete container:*/ that.parentNode.appendChild(a); /*for each item in the array...*/ for (i = 0; i < result.length; i++) { var element = result[i]; var name = element.getValue({ name: 'name' }); var type = element.getValue({ name: 'type' }); var info1 = element.getValue({ name: 'info1' }); var info2 = element.getValue({ name: 'info2' }); var formatStr = '<p><strong>' + type + ': ' + name + '</strong></p>'; formatStr += info1 ? '<p> - ' + info1 + '</p>' : ''; formatStr += info2 ? '<p> - ' + info2 + '</p>' : ''; /*create a DIV element for each matching element:*/ b = document.createElement('DIV'); b.innerHTML = formatStr; /*insert a input field that will hold the current array item's value:*/ b.innerHTML += "<input type='hidden' value='" + formatStr; +"'>"; /*execute a function when someone clicks on the item value (DIV element):*/ b.addEventListener('click', function(e) { /*insert the value for the autocomplete text field:*/ // inp.value = this.getElementsByTagName("input")[0].value; /*close the list of autocompleted values, (or any other open lists of autocompleted values:*/ closeAllLists(); }); a.appendChild(b); } }) .catch(function onRejected(reason) { // do something on rejection console.log(reason); }); } }); /*execute a function when someone clicks in the document:*/ document.addEventListener('click', function(e) { closeAllLists(e.target); }); /** * Autocomplete */ function addActive(x) { /*a function to classify an item as "active":*/ if (!x) return false; /*start by removing the "active" class on all items:*/ removeActive(x); if (currentFocus >= x.length) currentFocus = 0; if (currentFocus < 0) currentFocus = x.length - 1; /*add class "autocomplete-active":*/ x[currentFocus].classList.add('autocomplete-active'); } function removeActive(x) { /*a function to remove the "active" class from all autocomplete items:*/ for (var i = 0; i < x.length; i++) { x[i].classList.remove('autocomplete-active'); } } function closeAllLists(elmnt) { /*close all autocomplete lists in the document, except the one passed as an argument:*/ var x = document.getElementsByClassName('autocomplete-items'); for (var i = 0; i < x.length; i++) { if (elmnt != x[i] && elmnt != inp) { x[i].parentNode.removeChild(x[i]); } } } return; } /** HELPER FUNCTIONS **/ function formatAddressStandardization(address) { address = address.split('\n'); var result = ''; if (address.length >= 4) { address.splice(0, 1); if (address.length === 4) { address.splice(1, 1); } } result = address.join('\n'); return result; } /** * Load CSS File * @param {*} file */ function loadCSS(file) { if (window.document) { var fileref = window.document.createElement('link'); fileref.setAttribute('rel', 'stylesheet'); fileref.setAttribute('type', 'text/css'); fileref.setAttribute('href', file); window.document.head.appendChild(fileref); } } /** * Load CSS from Text * @param {*} str */ function loadCSSText(str) { if (window.document) { var fileref = window.document.createElement('style'); fileref.innerHTML = str; window.document.head.appendChild(fileref); } } function offset(el) { var rect = el.getBoundingClientRect(), scrollLeft = window.pageXOffset || document.documentElement.scrollLeft, scrollTop = window.pageYOffset || document.documentElement.scrollTop; return { top: rect.top + scrollTop, left: rect.left + scrollLeft }; } /** * A specialized version of `_.filter` for arrays without support for * iteratee shorthands. * * @private * @param {Array} [array] The array to iterate over. * @param {Function} predicate The function invoked per iteration. * @returns {Array} Returns the new filtered array. */ function arrayFilter(array, predicate) { var index = -1, length = array == null ? 0 : array.length, resIndex = 0, result = []; while (++index < length) { var value = array[index]; if (predicate(value, index, array)) { result[resIndex++] = value; } } return result; } /** * Export Events */ var exports = {}; exports.pageInit = pageInit; exports.sublistChanged = sublistChanged; return exports; });
418
[{"tag": "EMAIL", "value": "trung@lexor.com", "start": 153, "end": 168}]
true
1
define(['N/search'], function(search) { /** * Add Google Map for Address form * @NApiVersion 2.x * @NScriptType ClientScript * @author trungpv <lyhxr@example.com> */ /* === VARS === */ /* === EVENTS FUNCTIONS === */ /** * Sublist Changed * @param {*} context */ function sublistChanged(context) { const currentRecord = context.currentRecord; const sublistId = context.sublistId; const operation = context.operation; if (sublistId === 'addressbook') { const defaultbilling = currentRecord.getCurrentSublistValue({ sublistId: sublistId, fieldId: 'defaultbilling' }); const defaultshipping = currentRecord.getCurrentSublistValue({ sublistId: sublistId, fieldId: 'defaultshipping' }); if (operation === 'remove') { // Reset Default Value when remove address if (defaultbilling) { currentRecord.setValue({ fieldId: 'defaultaddress', value: '' }); } if (defaultshipping) { currentRecord.setValue({ fieldId: 'custentity_address_verification', value: '' }); } } else { if (defaultshipping) { const addressbookaddress_text = currentRecord.getCurrentSublistValue({ sublistId: sublistId, fieldId: 'addressbookaddress_text' }); var addressArr = addressbookaddress_text.split('\n'); if (addressArr.length > 3) { currentRecord.setValue({ fieldId: 'custentity_address_verification', value: formatAddressStandardization(addressbookaddress_text) }); } else { currentRecord.setValue({ fieldId: 'custentity_address_verification', value: '' }); } } } } } /** * Page Init * @param {*} context */ function pageInit(context) { console.log('pageInit Triggered!', context); loadCSSText( '.autocomplete{position:relative;display:inline-block}.autocomplete-items{position:absolute;z-index:99;display:inline-block}.autocomplete-items div{padding:10px;cursor:pointer;background-color:#fff;border:1px solid #d4d4d4}.autocomplete-items div:hover{background-color:#e9e9e9}.autocomplete-active{background-color:#1e90ff!important;color:#fff}' ); /*the autocomplete function takes two arguments, the text field element and an array of possible autocompleted values:*/ var currentFocus; var inp = document.getElementById('custentity_search_phone'); /*execute a function when someone writes in the text field:*/ inp.addEventListener('keyup', function(e) { // Press Left Arrow if (e.which === 39) { var a, b, i, val = this.value; var that = this; /*close any already open lists of autocompleted values*/ closeAllLists(); if (!val) { return false; } // Start Search const types = ['Customer', 'Lead', 'Prospect']; search.global .promise({ keywords: val }) .then(function(result) { result = arrayFilter(result, function(o) { if ( (o.getValue({ name: 'info1' }) !== '' || o.getValue({ name: 'info2' }) !== '') && types.includes( o.getValue({ name: 'type' }) ) ) { return o; } }); currentFocus = -1; /*create a DIV element that will contain the items (values):*/ a = document.createElement('DIV'); a.setAttribute('id', this.id + 'autocomplete-list'); a.setAttribute('class', 'autocomplete-items'); const inpPos = offset(inp); a.style.top = inpPos.top + 25 + 'px'; a.style.left = inpPos.left + 'px'; // a.style.display = "block"; /*append the DIV element as a child of the autocomplete container:*/ that.parentNode.appendChild(a); /*for each item in the array...*/ for (i = 0; i < result.length; i++) { var element = result[i]; var name = element.getValue({ name: 'name' }); var type = element.getValue({ name: 'type' }); var info1 = element.getValue({ name: 'info1' }); var info2 = element.getValue({ name: 'info2' }); var formatStr = '<p><strong>' + type + ': ' + name + '</strong></p>'; formatStr += info1 ? '<p> - ' + info1 + '</p>' : ''; formatStr += info2 ? '<p> - ' + info2 + '</p>' : ''; /*create a DIV element for each matching element:*/ b = document.createElement('DIV'); b.innerHTML = formatStr; /*insert a input field that will hold the current array item's value:*/ b.innerHTML += "<input type='hidden' value='" + formatStr; +"'>"; /*execute a function when someone clicks on the item value (DIV element):*/ b.addEventListener('click', function(e) { /*insert the value for the autocomplete text field:*/ // inp.value = this.getElementsByTagName("input")[0].value; /*close the list of autocompleted values, (or any other open lists of autocompleted values:*/ closeAllLists(); }); a.appendChild(b); } }) .catch(function onRejected(reason) { // do something on rejection console.log(reason); }); } }); /*execute a function when someone clicks in the document:*/ document.addEventListener('click', function(e) { closeAllLists(e.target); }); /** * Autocomplete */ function addActive(x) { /*a function to classify an item as "active":*/ if (!x) return false; /*start by removing the "active" class on all items:*/ removeActive(x); if (currentFocus >= x.length) currentFocus = 0; if (currentFocus < 0) currentFocus = x.length - 1; /*add class "autocomplete-active":*/ x[currentFocus].classList.add('autocomplete-active'); } function removeActive(x) { /*a function to remove the "active" class from all autocomplete items:*/ for (var i = 0; i < x.length; i++) { x[i].classList.remove('autocomplete-active'); } } function closeAllLists(elmnt) { /*close all autocomplete lists in the document, except the one passed as an argument:*/ var x = document.getElementsByClassName('autocomplete-items'); for (var i = 0; i < x.length; i++) { if (elmnt != x[i] && elmnt != inp) { x[i].parentNode.removeChild(x[i]); } } } return; } /** HELPER FUNCTIONS **/ function formatAddressStandardization(address) { address = address.split('\n'); var result = ''; if (address.length >= 4) { address.splice(0, 1); if (address.length === 4) { address.splice(1, 1); } } result = address.join('\n'); return result; } /** * Load CSS File * @param {*} file */ function loadCSS(file) { if (window.document) { var fileref = window.document.createElement('link'); fileref.setAttribute('rel', 'stylesheet'); fileref.setAttribute('type', 'text/css'); fileref.setAttribute('href', file); window.document.head.appendChild(fileref); } } /** * Load CSS from Text * @param {*} str */ function loadCSSText(str) { if (window.document) { var fileref = window.document.createElement('style'); fileref.innerHTML = str; window.document.head.appendChild(fileref); } } function offset(el) { var rect = el.getBoundingClientRect(), scrollLeft = window.pageXOffset || document.documentElement.scrollLeft, scrollTop = window.pageYOffset || document.documentElement.scrollTop; return { top: rect.top + scrollTop, left: rect.left + scrollLeft }; } /** * A specialized version of `_.filter` for arrays without support for * iteratee shorthands. * * @private * @param {Array} [array] The array to iterate over. * @param {Function} predicate The function invoked per iteration. * @returns {Array} Returns the new filtered array. */ function arrayFilter(array, predicate) { var index = -1, length = array == null ? 0 : array.length, resIndex = 0, result = []; while (++index < length) { var value = array[index]; if (predicate(value, index, array)) { result[resIndex++] = value; } } return result; } /** * Export Events */ var exports = {}; exports.pageInit = pageInit; exports.sublistChanged = sublistChanged; return exports; });
true
define(['N/search'], function(search) { /** * Add Google Map for Address form * @NApiVersion 2.x * @NScriptType ClientScript * @author trungpv <PI:EMAIL:lyhxr@example.comEND_PI> */ /* === VARS === */ /* === EVENTS FUNCTIONS === */ /** * Sublist Changed * @param {*} context */ function sublistChanged(context) { const currentRecord = context.currentRecord; const sublistId = context.sublistId; const operation = context.operation; if (sublistId === 'addressbook') { const defaultbilling = currentRecord.getCurrentSublistValue({ sublistId: sublistId, fieldId: 'defaultbilling' }); const defaultshipping = currentRecord.getCurrentSublistValue({ sublistId: sublistId, fieldId: 'defaultshipping' }); if (operation === 'remove') { // Reset Default Value when remove address if (defaultbilling) { currentRecord.setValue({ fieldId: 'defaultaddress', value: '' }); } if (defaultshipping) { currentRecord.setValue({ fieldId: 'custentity_address_verification', value: '' }); } } else { if (defaultshipping) { const addressbookaddress_text = currentRecord.getCurrentSublistValue({ sublistId: sublistId, fieldId: 'addressbookaddress_text' }); var addressArr = addressbookaddress_text.split('\n'); if (addressArr.length > 3) { currentRecord.setValue({ fieldId: 'custentity_address_verification', value: formatAddressStandardization(addressbookaddress_text) }); } else { currentRecord.setValue({ fieldId: 'custentity_address_verification', value: '' }); } } } } } /** * Page Init * @param {*} context */ function pageInit(context) { console.log('pageInit Triggered!', context); loadCSSText( '.autocomplete{position:relative;display:inline-block}.autocomplete-items{position:absolute;z-index:99;display:inline-block}.autocomplete-items div{padding:10px;cursor:pointer;background-color:#fff;border:1px solid #d4d4d4}.autocomplete-items div:hover{background-color:#e9e9e9}.autocomplete-active{background-color:#1e90ff!important;color:#fff}' ); /*the autocomplete function takes two arguments, the text field element and an array of possible autocompleted values:*/ var currentFocus; var inp = document.getElementById('custentity_search_phone'); /*execute a function when someone writes in the text field:*/ inp.addEventListener('keyup', function(e) { // Press Left Arrow if (e.which === 39) { var a, b, i, val = this.value; var that = this; /*close any already open lists of autocompleted values*/ closeAllLists(); if (!val) { return false; } // Start Search const types = ['Customer', 'Lead', 'Prospect']; search.global .promise({ keywords: val }) .then(function(result) { result = arrayFilter(result, function(o) { if ( (o.getValue({ name: 'info1' }) !== '' || o.getValue({ name: 'info2' }) !== '') && types.includes( o.getValue({ name: 'type' }) ) ) { return o; } }); currentFocus = -1; /*create a DIV element that will contain the items (values):*/ a = document.createElement('DIV'); a.setAttribute('id', this.id + 'autocomplete-list'); a.setAttribute('class', 'autocomplete-items'); const inpPos = offset(inp); a.style.top = inpPos.top + 25 + 'px'; a.style.left = inpPos.left + 'px'; // a.style.display = "block"; /*append the DIV element as a child of the autocomplete container:*/ that.parentNode.appendChild(a); /*for each item in the array...*/ for (i = 0; i < result.length; i++) { var element = result[i]; var name = element.getValue({ name: 'name' }); var type = element.getValue({ name: 'type' }); var info1 = element.getValue({ name: 'info1' }); var info2 = element.getValue({ name: 'info2' }); var formatStr = '<p><strong>' + type + ': ' + name + '</strong></p>'; formatStr += info1 ? '<p> - ' + info1 + '</p>' : ''; formatStr += info2 ? '<p> - ' + info2 + '</p>' : ''; /*create a DIV element for each matching element:*/ b = document.createElement('DIV'); b.innerHTML = formatStr; /*insert a input field that will hold the current array item's value:*/ b.innerHTML += "<input type='hidden' value='" + formatStr; +"'>"; /*execute a function when someone clicks on the item value (DIV element):*/ b.addEventListener('click', function(e) { /*insert the value for the autocomplete text field:*/ // inp.value = this.getElementsByTagName("input")[0].value; /*close the list of autocompleted values, (or any other open lists of autocompleted values:*/ closeAllLists(); }); a.appendChild(b); } }) .catch(function onRejected(reason) { // do something on rejection console.log(reason); }); } }); /*execute a function when someone clicks in the document:*/ document.addEventListener('click', function(e) { closeAllLists(e.target); }); /** * Autocomplete */ function addActive(x) { /*a function to classify an item as "active":*/ if (!x) return false; /*start by removing the "active" class on all items:*/ removeActive(x); if (currentFocus >= x.length) currentFocus = 0; if (currentFocus < 0) currentFocus = x.length - 1; /*add class "autocomplete-active":*/ x[currentFocus].classList.add('autocomplete-active'); } function removeActive(x) { /*a function to remove the "active" class from all autocomplete items:*/ for (var i = 0; i < x.length; i++) { x[i].classList.remove('autocomplete-active'); } } function closeAllLists(elmnt) { /*close all autocomplete lists in the document, except the one passed as an argument:*/ var x = document.getElementsByClassName('autocomplete-items'); for (var i = 0; i < x.length; i++) { if (elmnt != x[i] && elmnt != inp) { x[i].parentNode.removeChild(x[i]); } } } return; } /** HELPER FUNCTIONS **/ function formatAddressStandardization(address) { address = address.split('\n'); var result = ''; if (address.length >= 4) { address.splice(0, 1); if (address.length === 4) { address.splice(1, 1); } } result = address.join('\n'); return result; } /** * Load CSS File * @param {*} file */ function loadCSS(file) { if (window.document) { var fileref = window.document.createElement('link'); fileref.setAttribute('rel', 'stylesheet'); fileref.setAttribute('type', 'text/css'); fileref.setAttribute('href', file); window.document.head.appendChild(fileref); } } /** * Load CSS from Text * @param {*} str */ function loadCSSText(str) { if (window.document) { var fileref = window.document.createElement('style'); fileref.innerHTML = str; window.document.head.appendChild(fileref); } } function offset(el) { var rect = el.getBoundingClientRect(), scrollLeft = window.pageXOffset || document.documentElement.scrollLeft, scrollTop = window.pageYOffset || document.documentElement.scrollTop; return { top: rect.top + scrollTop, left: rect.left + scrollLeft }; } /** * A specialized version of `_.filter` for arrays without support for * iteratee shorthands. * * @private * @param {Array} [array] The array to iterate over. * @param {Function} predicate The function invoked per iteration. * @returns {Array} Returns the new filtered array. */ function arrayFilter(array, predicate) { var index = -1, length = array == null ? 0 : array.length, resIndex = 0, result = []; while (++index < length) { var value = array[index]; if (predicate(value, index, array)) { result[resIndex++] = value; } } return result; } /** * Export Events */ var exports = {}; exports.pageInit = pageInit; exports.sublistChanged = sublistChanged; return exports; });
/** * @NApiVersion 2.0 * @NScriptType Suitelet * * Module Description * * NSVersion Date Author * 2.00 2021-09-20 09:33:08 Anesu * * Description: xxxxxxxx * * @Last Modified by: Anesu * @Last Modified time: 2021-09-20 09:33:08 * */ define(['N/ui/serverWidget', 'N/email', 'N/runtime', 'N/search', 'N/record', 'N/http', 'N/log', 'N/redirect', 'N/task', 'N/format'], function (ui, email, runtime, search, record, http, log, redirect, task, format) { var zee = 0; var role = 0; var baseURL = 'https://1048144.app.netsuite.com'; if (runtime.EnvType == "SANDBOX") { baseURL = 'https://1048144-sb3.app.netsuite.com'; } role = runtime.getCurrentUser().role; if (role == 1000) { zee = runtime.getCurrentUser().id; } else if (role == 3) { //Administrator zee = 6; //test } else if (role == 1032) { // System Support zee = 425904; //test-AR } function onRequest(context) { if (context.request.method === 'GET') { var is_params = 'T'; type = context.request.parameters.type; var form = ui.createForm({ title: ' ' }); // Load jQuery var inlineHtml = '<script src="https://code.jquery.com/jquery-1.12.4.min.js" integrity="sha384-nvAa0+6Qg9clwYCGGPpDQLVpLNn0fRaROjHqs13t4Ggj3Ez50XnGQqc/r8MhnRDZ" crossorigin="anonymous"></script>'; // Load Tooltip inlineHtml += '<script src="https://unpkg.com/@popperjs/core@2"></script>'; // Load Bootstrap inlineHtml += '<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/3.4.1/css/bootstrap.min.css" integrity="sha384-HSMxcRTRxnN+Bdg0JdbxYKrThecOKuH5zCYotlSAcp1+c8xmyTe9GYg1l9a69psu" crossorigin="anonymous">'; inlineHtml += '<script src="https://stackpath.bootstrapcdn.com/bootstrap/3.4.1/js/bootstrap.min.js" integrity="sha384-aJ21OjlMXNL5UyIl/XNwTMqvzeRMZH2w8c5cRVpzpU8Y5bApTppSuUkhZXN0VxHd" crossorigin="anonymous"></script>'; // Load Bootstrap-Select inlineHtml += '<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap-select@1.13.14/dist/css/bootstrap-select.min.css">'; inlineHtml += '<script src="https://cdn.jsdelivr.net/npm/bootstrap-select@1.13.14/dist/js/bootstrap-select.min.js"></script>'; // Load DataTables inlineHtml += '<link rel="stylesheet" type="text/css" href="//cdn.datatables.net/1.10.21/css/jquery.dataTables.min.css">'; inlineHtml += '<script type="text/javascript" charset="utf8" src="//cdn.datatables.net/1.10.21/js/jquery.dataTables.min.js"></script>'; inlineHtml += '<script type="text/javascript" charset="utf8" src="//cdn.datatables.net/rowgroup/1.1.3/js/dataTables.rowGroup.min.js"></script> ' inlineHtml += '<script type="text/javascript" charset="utf8" src="//cdn.datatables.net/buttons/2.0.0/js/dataTables.buttons.min.js"></script> ' inlineHtml += '<script type="text/javascript" charset="utf8" src="//cdnjs.cloudflare.com/ajax/libs/jszip/3.1.3/jszip.min.js"></script> ' inlineHtml += '<script type="text/javascript" charset="utf8" src="//cdnjs.cloudflare.com/ajax/libs/pdfmake/0.1.53/pdfmake.min.js"></script> ' inlineHtml += '<script type="text/javascript" charset="utf8" src="//cdnjs.cloudflare.com/ajax/libs/pdfmake/0.1.53/vfs_fonts.js"></script> ' inlineHtml += '<script type="text/javascript" charset="utf8" src="//cdn.datatables.net/buttons/2.0.0/js/buttons.html5.min.js"></script> ' inlineHtml += '<script type="text/javascript" charset="utf8" src="//cdn.datatables.net/buttons/2.0.0/js/buttons.print.min.js"></script> ' // Load Bootstrap-Select inlineHtml += '<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap-select@1.13.14/dist/css/bootstrap-select.min.css">'; inlineHtml += '<script src="https://cdn.jsdelivr.net/npm/bootstrap-select@1.13.14/dist/js/bootstrap-select.min.js"></script>'; // Load Netsuite stylesheet and script inlineHtml += '<link rel="stylesheet" href="https://1048144.app.netsuite.com/core/media/media.nl?id=2060796&c=1048144&h=9ee6accfd476c9cae718&_xt=.css"/>'; inlineHtml += '<script src="https://1048144.app.netsuite.com/core/media/media.nl?id=2060797&c=1048144&h=ef2cda20731d146b5e98&_xt=.js"></script>'; inlineHtml += '<link type="text/css" rel="stylesheet" href="https://1048144.app.netsuite.com/core/media/media.nl?id=2090583&c=1048144&h=a0ef6ac4e28f91203dfe&_xt=.css">'; inlineHtml += '<style>.mandatory{color:red;}</style>'; // New Website Color Schemes // Main Color: #379E8F // Background Color: #CFE0CE // Button Color: #FBEA51 // Text Color: #103D39 // inlineHtml += '<div class="a" style="width: 100%; background-color: #CFE0CE; padding: 20px; min-height: 100vh; height: 100%; ">'; // margin-top: -40px // inlineHtml += '<style>.nav > li.active > a, .nav > li.active > a:focus, .nav > li.active > a:hover { background-color: #379E8F; color: #fff }'; // inlineHtml += '.nav > li > a, .nav > li > a:focus, .nav > li > a:hover { margin-left: 5px; margin-right: 5px; border: 2px solid #379E8F; color: #379E8F; }'; // inlineHtml += '</style>'; // Title inlineHtml += '<h1 style="font-size: 25px; font-weight: 700; color: #103D39; text-align: center">Debt Collection: Assign Customers</h1>'; // Define alert window. inlineHtml += '<div class="container" style="margin-top:14px;" hidden><div id="alert" class="alert alert-danger fade in"></div></div>'; // Define information window. inlineHtml += '<div class="container" hidden><p id="info" class="alert alert-info"></p></div>'; inlineHtml += '<div style="margin-top: -40px"><br/>'; // Buttons // inlineHtml += '<button style="margin-left: 10px; margin-right: 5px; background-color: #FBEA51; color: #103D39; font-weight: 700; border-color: transparent; border-width: 2px; border-radius: 15px; height: 30px" type="button" id="new_agreement" onclick="">New Franchisee Agreement</button>'; inlineHtml += tabsSection(); // inlineHtml += dataTable(); inlineHtml += '</div></div>' form.addField({ id: 'preview_table', label: 'inlinehtml', type: 'inlinehtml' }).updateLayoutType({ layoutType: ui.FieldLayoutType.STARTROW }).defaultValue = inlineHtml; form.addField({ id: 'custpage_debt_inv_assign_emp_id', label: 'Employee ID', type: ui.FieldType.TEXT }).updateDisplayType({ displayType: ui.FieldDisplayType.HIDDEN }) form.addField({ id: 'custpage_debt_inv_assign_emp_split', label: 'Split', type: ui.FieldType.TEXT }).updateDisplayType({ displayType: ui.FieldDisplayType.HIDDEN }) form.addField({ id: 'custpage_debt_inv_assign_emp_split_id', label: 'Split ID', type: ui.FieldType.TEXT }).updateDisplayType({ displayType: ui.FieldDisplayType.HIDDEN }) form.addField({ id: 'custpage_debt_inv_assign_count', label: 'Count', type: ui.FieldType.TEXT }).updateDisplayType({ displayType: ui.FieldDisplayType.HIDDEN }); form.addSubmitButton({ label: ' ' }); form.clientScriptFileId = 5142730; //5064221 context.response.writePage(form); } else { var params = context.request.parameters; var emp_id = context.request.parameters.custpage_debt_inv_assign_emp_id // Array of Id's for Employees var split_bool = context.request.parameters.custpage_debt_inv_assign_emp_split var emp_split_id = context.request.parameters.custpage_debt_inv_assign_emp_split_id var count = context.request.parameters.custpage_debt_inv_assign_count; log.debug({ title: 'Submitter: Params', details: params }); log.debug({ title: 'Submitter: Params Employee ID', details: params.custpage_debt_inv_assign_emp_id }); log.debug({ title: 'Submitter: Params count', details: params.custpage_debt_inv_assign_count }); // CALL SCHEDULED SCRIPT var params2 = { custscript_debt_inv_assign_emp_id: emp_id, custscript_debt_inv_assign_emp_split: split_bool, custscript_debt_inv_assign_emp_split_id: emp_split_id, custscript_debt_inv_assign_count: count } var scriptTask = task.create({ taskType: task.TaskType.SCHEDULED_SCRIPT, scriptId: 'customscript_ss_debt_coll_assign', deploymentId: 'customdeploy_ss_debt_coll_assign', params: params2 }); var ss_id = scriptTask.submit(); var myTaskStatus = task.checkStatus({ taskId: ss_id }); log.audit({ title: 'Task Status', details: myTaskStatus }); log.audit({ title: 'Task Submit: Params', details: scriptTask.params }) log.audit({ title: 'Task Submit: Params Employee ID', details: scriptTask.params.emp_id }); var form = ui.createForm({ title: ' ', }); var inlineHtml = '<script src="https://code.jquery.com/jquery-1.12.4.min.js" integrity="sha384-nvAa0+6Qg9clwYCGGPpDQLVpLNn0fRaROjHqs13t4Ggj3Ez50XnGQqc/r8MhnRDZ" crossorigin="anonymous"></script>'; // Load Tooltip inlineHtml += '<script src="https://unpkg.com/@popperjs/core@2"></script>'; // Load Bootstrap inlineHtml += '<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/3.4.1/css/bootstrap.min.css" integrity="sha384-HSMxcRTRxnN+Bdg0JdbxYKrThecOKuH5zCYotlSAcp1+c8xmyTe9GYg1l9a69psu" crossorigin="anonymous">'; inlineHtml += '<script src="https://stackpath.bootstrapcdn.com/bootstrap/3.4.1/js/bootstrap.min.js" integrity="sha384-aJ21OjlMXNL5UyIl/XNwTMqvzeRMZH2w8c5cRVpzpU8Y5bApTppSuUkhZXN0VxHd" crossorigin="anonymous"></script>'; // Load Bootstrap-Select inlineHtml += '<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap-select@1.13.14/dist/css/bootstrap-select.min.css">'; inlineHtml += '<script src="https://cdn.jsdelivr.net/npm/bootstrap-select@1.13.14/dist/js/bootstrap-select.min.js"></script>'; // Load DataTables inlineHtml += '<link rel="stylesheet" type="text/css" href="//cdn.datatables.net/1.10.21/css/jquery.dataTables.min.css">'; inlineHtml += '<script type="text/javascript" charset="utf8" src="//cdn.datatables.net/1.10.21/js/jquery.dataTables.min.js"></script>'; inlineHtml += '<script type="text/javascript" charset="utf8" src="//cdn.datatables.net/rowgroup/1.1.3/js/dataTables.rowGroup.min.js"></script> ' inlineHtml += '<script type="text/javascript" charset="utf8" src="//cdn.datatables.net/buttons/2.0.0/js/dataTables.buttons.min.js"></script> ' inlineHtml += '<script type="text/javascript" charset="utf8" src="//cdnjs.cloudflare.com/ajax/libs/jszip/3.1.3/jszip.min.js"></script> ' inlineHtml += '<script type="text/javascript" charset="utf8" src="//cdnjs.cloudflare.com/ajax/libs/pdfmake/0.1.53/pdfmake.min.js"></script> ' inlineHtml += '<script type="text/javascript" charset="utf8" src="//cdnjs.cloudflare.com/ajax/libs/pdfmake/0.1.53/vfs_fonts.js"></script> ' inlineHtml += '<script type="text/javascript" charset="utf8" src="//cdn.datatables.net/buttons/2.0.0/js/buttons.html5.min.js"></script> ' inlineHtml += '<script type="text/javascript" charset="utf8" src="//cdn.datatables.net/buttons/2.0.0/js/buttons.print.min.js"></script> ' // Load Bootstrap-Select inlineHtml += '<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap-select@1.13.14/dist/css/bootstrap-select.min.css">'; inlineHtml += '<script src="https://cdn.jsdelivr.net/npm/bootstrap-select@1.13.14/dist/js/bootstrap-select.min.js"></script>'; // Load Netsuite stylesheet and script inlineHtml += '<link rel="stylesheet" href="https://1048144.app.netsuite.com/core/media/media.nl?id=2060796&c=1048144&h=9ee6accfd476c9cae718&_xt=.css"/>'; inlineHtml += '<script src="https://1048144.app.netsuite.com/core/media/media.nl?id=2060797&c=1048144&h=ef2cda20731d146b5e98&_xt=.js"></script>'; inlineHtml += '<link type="text/css" rel="stylesheet" href="https://1048144.app.netsuite.com/core/media/media.nl?id=2090583&c=1048144&h=a0ef6ac4e28f91203dfe&_xt=.css">'; inlineHtml += '<style>.mandatory{color:red;}</style>'; // Title inlineHtml += '<h1 style="font-size: 25px; font-weight: 700; color: #103D39; text-align: center">Debt Collection: Assign (Submitted)</h1>'; // Define alert window. inlineHtml += '<div class="container" style="margin-top:14px;" hidden><div id="alert" class="alert alert-danger fade in"></div></div>'; // Define information window. inlineHtml += '<div class="container" hidden><p id="info" class="alert alert-info"></p></div>'; inlineHtml += '<div style="margin-top: -40px"><br/>'; // inlineHtml += inlineHtml += '<div class="form-group container save_record button_section">'; inlineHtml += '<div class="row">'; inlineHtml += '<div class="col-xs-4 col-xs-offset-4 home_btn">'; inlineHtml += '<input type="button" style="margin-left: 10px; margin-right: 5px; margin-top: 35px; background-color: #FBEA51; color: #103D39; font-weight: 700; border-color: transparent; border-width: 2px; border-radius: 15px; height: 30px; color: #103D39;" class="form-control btn home_btn" id="home_btn" value="Go Home"></input>'; inlineHtml += '</div></div></div>'; inlineHtml += '</div></div>'; form.addField({ id: 'preview_table', label: 'inlinehtml', type: 'inlinehtml' }).updateLayoutType({ layoutType: ui.FieldLayoutType.STARTROW }).defaultValue = inlineHtml; form.clientScriptFileId = 5142730; //5064221 context.response.writePage(form); redirect.toSuitelet({ scriptId: 'customscript_sl_debt_coll_assign', deploymentId: 'customdeploy_sl_debt_coll_assign' }); } } function tabsSection() { var inlineQty = '<div>'; // Tabs headers inlineQty += '<style>.nav > li.active > a, .nav > li.active > a:focus, .nav > li.active > a:hover { background-color: #379E8F; color: #fff }'; inlineQty += '.nav > li > a, .nav > li > a:focus, .nav > li > a:hover { margin-left: 5px; margin-right: 5px; border: 2px solid #379E8F; color: #379E8F; }'; inlineQty += '</style>'; inlineQty += '<div style="width: 95%; margin:auto; margin-bottom: 30px; margin-top: 30px;",><ul class="nav nav-pills nav-justified" style="margin:0%; ">'; inlineQty += '<li role="presentation" class="active"><a data-toggle="tab" href="#reassign"><b>RE-ASSIGN</b></a></li>'; inlineQty += '<li role="presentation" class=""><a data-toggle="tab" href="#split"><b>SPLIT</b></a></li>'; // inlineQty += '<li role="presentation" class="active"><a data-toggle="tab" href="#invoices"><b>INVOICES</b></a></li>'; inlineQty += '</ul></div>'; // Tabs content inlineQty += '<div class="tab-content">'; // if (!isFinanceRole(userRole)) { inlineQty += '<div role="tabpanel" class="tab-pane active" id="reassign">'; // inlineQty += dataTablePreview('reassign'); inlineQty += reassign(); inlineQty += '</div>'; inlineQty += '<div role="tabpanel" class="tab-pane" id="split">'; // inlineQty += dataTablePreview('split'); inlineQty += split(); inlineQty += '</div>'; // } inlineQty += '</div>'; //</div> return inlineQty; } function reassign() { var inlineQty = '<div class="form-group container-fluid range_filter_section">'; inlineQty += '<div class="row">'; inlineQty += '<div class="col-xs-5 team_section">'; inlineQty += '<div class="input-group">'; inlineQty += '<span class="input-group-addon" id="team_filter_text">Team Member Selection</span>'; inlineQty += '<select multiple id="team_filter" class="form-control">'; var employeeSearch = search.load({ type: 'employee', id: 'customsearch_debt_coll_employees' }); // inlineQty += '<option value="" selected>- None -</option>'; employeeSearch.run().each(function (res) { var em_id = res.getValue({ name: 'internalid' }) var em_first_name = res.getValue({ name: 'firstname' }); var em_last_name = res.getValue({ name: 'lastname' }); inlineQty += '<option value="' + em_id + '">' + em_first_name + ' ' + em_last_name + '</option>'; return true; }); inlineQty += '</select>'; inlineQty += '</div></div>'; inlineQty += '<div class="col-xs-2">'; inlineQty += '<style>.vl { height: 125px; position: absolute; left: 50%; border-width: px; border-style: solid; border-image: linear-gradient(to bottom, #103D39, rgba(0, 0, 0, 0)) 10; }</style>'; inlineQty += '<div class="vl"></div>'; inlineQty += '</div>' inlineQty += '<div class="col-xs-5 range_section">'; inlineQty += '<div class="form-group">'; inlineQty += '<textarea class="form-control reassignTextArea" id="reassignTextArea" rows="5" disabled></textarea>'; inlineQty += '</div></div>'; inlineQty += '</div>'; inlineQty += '</div>'; // inlineQty = '<div class="form-group container button_section">'; // inlineQty += '<div class="row">'; inlineQty += '<div class="col-xs-4 col-xs-offset-4 send_email_btn">'; inlineQty += '<input type="button" style="margin-left: 10px; margin-right: 5px; background-color: #FBEA51; color: #103D39; font-weight: 700; border-color: transparent; border-width: 2px; border-radius: 15px; height: 30px; color: #103D39;" class="form-control btn" id="submit_arrange" value="Submit"></input>'; inlineQty += '</div>'; // inlineQty += '</div>'; // inlineQty += '</div>'; return inlineQty; } function split() { var inlineQty = '<div class="form-group container-fluid range_filter_section">'; inlineQty += '<div class="row">'; inlineQty += '<div class="col-xs-5 split_team_section">'; inlineQty += '<div class="input-group">'; inlineQty += '<span class="input-group-addon" id="split_employee_filter">Employee Selection</span>'; inlineQty += '<select id="split_team_filter" class="form-control">'; var authSearch = search.load({ type: 'invoice', id: 'customsearch_debt_coll_assign_split' }); authSearch.run().each(function (res) { var auth_id = res.getValue({ name: 'custentity_debt_coll_auth_id', join: 'customer', summary: search.Summary.GROUP }); if (!isNullorEmpty(auth_id)) { var employeeSearch = search.load({ type: 'employee', id: 'customsearch_debt_coll_employees' }); employeeSearch.filters.push(search.createFilter({ name: 'internalid', operator: search.Operator.IS, values: parseInt(auth_id) })); employeeSearch.run().each(function (res) { var em_id = res.getValue({ name: 'internalid' }) var em_first_name = res.getValue({ name: 'firstname' }); var em_last_name = res.getValue({ name: 'lastname' }); inlineQty += '<option value="' + em_id + '">' + em_first_name + ' ' + em_last_name + '</option>'; }); } return true; }); inlineQty += '</select>'; inlineQty += '</div></div>'; inlineQty += '<div class="col-xs-2">'; inlineQty += '<style>.vl { height: 125px; position: absolute; left: 50%; border-width: px; border-style: solid; border-image: linear-gradient(to bottom, #103D39, rgba(0, 0, 0, 0)) 10; }</style>'; inlineQty += '<div class="vl"></div>'; inlineQty += '</div>' inlineQty += '<div class="col-xs-5 split_team_section">'; inlineQty += '<div class="input-group">'; inlineQty += '<span class="input-group-addon" id="split_team_filter_text">Split List Into...</span>'; inlineQty += '<select multiple id="split_member_filter" class="form-control">'; var employeeSearch = search.load({ type: 'employee', id: 'customsearch_debt_coll_employees' }); // inlineQty += '<option value="">- None -</option>'; employeeSearch.run().each(function (res) { var em_id = res.getValue({ name: 'internalid' }) var em_first_name = res.getValue({ name: 'firstname' }); var em_last_name = res.getValue({ name: 'lastname' }); inlineQty += '<option value="' + em_id + '">' + em_first_name + ' ' + em_last_name + '</option>'; return true; }); inlineQty += '</select>'; inlineQty += '</div></div>'; inlineQty += '</div>'; inlineQty += '</div>'; // inlineQty = '<div class="form-group container button_section">'; // inlineQty += '<div class="row">'; inlineQty += '<div class="col-xs-4 col-xs-offset-4 send_email_btn">'; inlineQty += '<input type="button" style="margin-left: 10px; margin-right: 5px; background-color: #FBEA51; color: #103D39; font-weight: 700; border-color: transparent; border-width: 2px; border-radius: 15px; height: 30px; color: #103D39;" class="form-control btn" id="submit_split" value="Submit"></input>'; inlineQty += '</div>'; // inlineQty += '</div>'; // inlineQty += '</div>'; return inlineQty; } /** * The table that will display the differents invoices linked to the franchisee and the time period. * @return {String} inlineQty */ function dataTable() { var inlineQty = '<style>table#debt_preview {font-size: 12px;text-align: center;border: none;}.dataTables_wrapper {font-size: 14px;}table#debt_preview th{text-align: center;} .bolded{font-weight: bold;}</style>'; inlineQty += '<table id="debt_preview" class="table table-responsive table-striped customer tablesorter hide" style="width: 100%;">'; inlineQty += '<thead style="color: white; background-color: #379E8F;">'; inlineQty += '<tr class="text-center">'; inlineQty += '</tr>'; inlineQty += '</thead>'; inlineQty += '<tbody id="result_debt" class="result-debt"></tbody>'; inlineQty += '</table>'; return inlineQty; } /** * Used to pass the values of `date_from` and `date_to` between the scripts and to Netsuite for the records and the search. * @param {String} date_iso "2020-06-01" * @returns {String} date_netsuite "1/6/2020" */ function dateISOToNetsuite(date_iso) { var date_netsuite = ''; if (!isNullorEmpty(date_iso)) { var date_utc = new Date(date_iso); // var date_netsuite = nlapiDateToString(date_utc); var date_netsuite = format.format({ value: date_utc, type: format.Type.DATE }); } return date_netsuite; } function isNullorEmpty(strVal) { return (strVal == null || strVal == '' || strVal == 'null' || strVal == undefined || strVal == 'undefined' || strVal == '- None -'); } return { onRequest: onRequest } } );
818
[{"tag": "KEY", "value": "sha384-aJ21OjlMXNL5UyIl/XNwTMqvzeRMZH2w8c5cRVpzpU8Y5bApTppSuUkhZXN0VxHd", "start": 2110, "end": 2181}, {"tag": "KEY", "value": "sha384-aJ21OjlMXNL5UyIl/XNwTMqvzeRMZH2w8c5cRVpzpU8Y5bApTppSuUkhZXN0VxHd", "start": 11707, "end": 11778}, {"tag": "KEY", "value": "sha384-HSMxcRTRxnN+Bdg0JdbxYKrThecOKuH5zCYotlSAcp1+c8xmyTe9GYg1l9a69psu", "start": 1882, "end": 1953}, {"tag": "KEY", "value": "sha384-HSMxcRTRxnN+Bdg0JdbxYKrThecOKuH5zCYotlSAcp1+c8xmyTe9GYg1l9a69psu", "start": 11479, "end": 11550}, {"tag": "KEY", "value": "sha384-nvAa0+6Qg9clwYCGGPpDQLVpLNn0fRaROjHqs13t4Ggj3Ez50XnGQqc/r8MhnRDZ", "start": 1464, "end": 1535}, {"tag": "KEY", "value": "sha384-nvAa0+6Qg9clwYCGGPpDQLVpLNn0fRaROjHqs13t4Ggj3Ez50XnGQqc/r8MhnRDZ", "start": 11061, "end": 11132}]
true
6
/** * @NApiVersion 2.0 * @NScriptType Suitelet * * Module Description * * NSVersion Date Author * 2.00 2021-09-20 09:33:08 Anesu * * Description: xxxxxxxx * * @Last Modified by: Anesu * @Last Modified time: 2021-09-20 09:33:08 * */ define(['N/ui/serverWidget', 'N/email', 'N/runtime', 'N/search', 'N/record', 'N/http', 'N/log', 'N/redirect', 'N/task', 'N/format'], function (ui, email, runtime, search, record, http, log, redirect, task, format) { var zee = 0; var role = 0; var baseURL = 'https://1048144.app.netsuite.com'; if (runtime.EnvType == "SANDBOX") { baseURL = 'https://1048144-sb3.app.netsuite.com'; } role = runtime.getCurrentUser().role; if (role == 1000) { zee = runtime.getCurrentUser().id; } else if (role == 3) { //Administrator zee = 6; //test } else if (role == 1032) { // System Support zee = 425904; //test-AR } function onRequest(context) { if (context.request.method === 'GET') { var is_params = 'T'; type = context.request.parameters.type; var form = ui.createForm({ title: ' ' }); // Load jQuery var inlineHtml = '<script src="https://code.jquery.com/jquery-1.12.4.min.js" integrity="74t3tndxag9o7h0890bnpfzh4olk2h9x" crossorigin="anonymous"></script>'; // Load Tooltip inlineHtml += '<script src="https://unpkg.com/@popperjs/core@2"></script>'; // Load Bootstrap inlineHtml += '<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/3.4.1/css/bootstrap.min.css" integrity="ax5kh6jaqkcd2tiexxs8v6xjo8yv8a6b" crossorigin="anonymous">'; inlineHtml += '<script src="https://stackpath.bootstrapcdn.com/bootstrap/3.4.1/js/bootstrap.min.js" integrity="74t3tndxag9o7h0890bnpfzh4olk2h9x" crossorigin="anonymous"></script>'; // Load Bootstrap-Select inlineHtml += '<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap-select@1.13.14/dist/css/bootstrap-select.min.css">'; inlineHtml += '<script src="https://cdn.jsdelivr.net/npm/bootstrap-select@1.13.14/dist/js/bootstrap-select.min.js"></script>'; // Load DataTables inlineHtml += '<link rel="stylesheet" type="text/css" href="//cdn.datatables.net/1.10.21/css/jquery.dataTables.min.css">'; inlineHtml += '<script type="text/javascript" charset="utf8" src="//cdn.datatables.net/1.10.21/js/jquery.dataTables.min.js"></script>'; inlineHtml += '<script type="text/javascript" charset="utf8" src="//cdn.datatables.net/rowgroup/1.1.3/js/dataTables.rowGroup.min.js"></script> ' inlineHtml += '<script type="text/javascript" charset="utf8" src="//cdn.datatables.net/buttons/2.0.0/js/dataTables.buttons.min.js"></script> ' inlineHtml += '<script type="text/javascript" charset="utf8" src="//cdnjs.cloudflare.com/ajax/libs/jszip/3.1.3/jszip.min.js"></script> ' inlineHtml += '<script type="text/javascript" charset="utf8" src="//cdnjs.cloudflare.com/ajax/libs/pdfmake/0.1.53/pdfmake.min.js"></script> ' inlineHtml += '<script type="text/javascript" charset="utf8" src="//cdnjs.cloudflare.com/ajax/libs/pdfmake/0.1.53/vfs_fonts.js"></script> ' inlineHtml += '<script type="text/javascript" charset="utf8" src="//cdn.datatables.net/buttons/2.0.0/js/buttons.html5.min.js"></script> ' inlineHtml += '<script type="text/javascript" charset="utf8" src="//cdn.datatables.net/buttons/2.0.0/js/buttons.print.min.js"></script> ' // Load Bootstrap-Select inlineHtml += '<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap-select@1.13.14/dist/css/bootstrap-select.min.css">'; inlineHtml += '<script src="https://cdn.jsdelivr.net/npm/bootstrap-select@1.13.14/dist/js/bootstrap-select.min.js"></script>'; // Load Netsuite stylesheet and script inlineHtml += '<link rel="stylesheet" href="https://1048144.app.netsuite.com/core/media/media.nl?id=2060796&c=1048144&h=9ee6accfd476c9cae718&_xt=.css"/>'; inlineHtml += '<script src="https://1048144.app.netsuite.com/core/media/media.nl?id=2060797&c=1048144&h=ef2cda20731d146b5e98&_xt=.js"></script>'; inlineHtml += '<link type="text/css" rel="stylesheet" href="https://1048144.app.netsuite.com/core/media/media.nl?id=2090583&c=1048144&h=a0ef6ac4e28f91203dfe&_xt=.css">'; inlineHtml += '<style>.mandatory{color:red;}</style>'; // New Website Color Schemes // Main Color: #379E8F // Background Color: #CFE0CE // Button Color: #FBEA51 // Text Color: #103D39 // inlineHtml += '<div class="a" style="width: 100%; background-color: #CFE0CE; padding: 20px; min-height: 100vh; height: 100%; ">'; // margin-top: -40px // inlineHtml += '<style>.nav > li.active > a, .nav > li.active > a:focus, .nav > li.active > a:hover { background-color: #379E8F; color: #fff }'; // inlineHtml += '.nav > li > a, .nav > li > a:focus, .nav > li > a:hover { margin-left: 5px; margin-right: 5px; border: 2px solid #379E8F; color: #379E8F; }'; // inlineHtml += '</style>'; // Title inlineHtml += '<h1 style="font-size: 25px; font-weight: 700; color: #103D39; text-align: center">Debt Collection: Assign Customers</h1>'; // Define alert window. inlineHtml += '<div class="container" style="margin-top:14px;" hidden><div id="alert" class="alert alert-danger fade in"></div></div>'; // Define information window. inlineHtml += '<div class="container" hidden><p id="info" class="alert alert-info"></p></div>'; inlineHtml += '<div style="margin-top: -40px"><br/>'; // Buttons // inlineHtml += '<button style="margin-left: 10px; margin-right: 5px; background-color: #FBEA51; color: #103D39; font-weight: 700; border-color: transparent; border-width: 2px; border-radius: 15px; height: 30px" type="button" id="new_agreement" onclick="">New Franchisee Agreement</button>'; inlineHtml += tabsSection(); // inlineHtml += dataTable(); inlineHtml += '</div></div>' form.addField({ id: 'preview_table', label: 'inlinehtml', type: 'inlinehtml' }).updateLayoutType({ layoutType: ui.FieldLayoutType.STARTROW }).defaultValue = inlineHtml; form.addField({ id: 'custpage_debt_inv_assign_emp_id', label: 'Employee ID', type: ui.FieldType.TEXT }).updateDisplayType({ displayType: ui.FieldDisplayType.HIDDEN }) form.addField({ id: 'custpage_debt_inv_assign_emp_split', label: 'Split', type: ui.FieldType.TEXT }).updateDisplayType({ displayType: ui.FieldDisplayType.HIDDEN }) form.addField({ id: 'custpage_debt_inv_assign_emp_split_id', label: 'Split ID', type: ui.FieldType.TEXT }).updateDisplayType({ displayType: ui.FieldDisplayType.HIDDEN }) form.addField({ id: 'custpage_debt_inv_assign_count', label: 'Count', type: ui.FieldType.TEXT }).updateDisplayType({ displayType: ui.FieldDisplayType.HIDDEN }); form.addSubmitButton({ label: ' ' }); form.clientScriptFileId = 5142730; //5064221 context.response.writePage(form); } else { var params = context.request.parameters; var emp_id = context.request.parameters.custpage_debt_inv_assign_emp_id // Array of Id's for Employees var split_bool = context.request.parameters.custpage_debt_inv_assign_emp_split var emp_split_id = context.request.parameters.custpage_debt_inv_assign_emp_split_id var count = context.request.parameters.custpage_debt_inv_assign_count; log.debug({ title: 'Submitter: Params', details: params }); log.debug({ title: 'Submitter: Params Employee ID', details: params.custpage_debt_inv_assign_emp_id }); log.debug({ title: 'Submitter: Params count', details: params.custpage_debt_inv_assign_count }); // CALL SCHEDULED SCRIPT var params2 = { custscript_debt_inv_assign_emp_id: emp_id, custscript_debt_inv_assign_emp_split: split_bool, custscript_debt_inv_assign_emp_split_id: emp_split_id, custscript_debt_inv_assign_count: count } var scriptTask = task.create({ taskType: task.TaskType.SCHEDULED_SCRIPT, scriptId: 'customscript_ss_debt_coll_assign', deploymentId: 'customdeploy_ss_debt_coll_assign', params: params2 }); var ss_id = scriptTask.submit(); var myTaskStatus = task.checkStatus({ taskId: ss_id }); log.audit({ title: 'Task Status', details: myTaskStatus }); log.audit({ title: 'Task Submit: Params', details: scriptTask.params }) log.audit({ title: 'Task Submit: Params Employee ID', details: scriptTask.params.emp_id }); var form = ui.createForm({ title: ' ', }); var inlineHtml = '<script src="https://code.jquery.com/jquery-1.12.4.min.js" integrity="74t3tndxag9o7h0890bnpfzh4olk2h9x" crossorigin="anonymous"></script>'; // Load Tooltip inlineHtml += '<script src="https://unpkg.com/@popperjs/core@2"></script>'; // Load Bootstrap inlineHtml += '<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/3.4.1/css/bootstrap.min.css" integrity="ax5kh6jaqkcd2tiexxs8v6xjo8yv8a6b" crossorigin="anonymous">'; inlineHtml += '<script src="https://stackpath.bootstrapcdn.com/bootstrap/3.4.1/js/bootstrap.min.js" integrity="74t3tndxag9o7h0890bnpfzh4olk2h9x" crossorigin="anonymous"></script>'; // Load Bootstrap-Select inlineHtml += '<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap-select@1.13.14/dist/css/bootstrap-select.min.css">'; inlineHtml += '<script src="https://cdn.jsdelivr.net/npm/bootstrap-select@1.13.14/dist/js/bootstrap-select.min.js"></script>'; // Load DataTables inlineHtml += '<link rel="stylesheet" type="text/css" href="//cdn.datatables.net/1.10.21/css/jquery.dataTables.min.css">'; inlineHtml += '<script type="text/javascript" charset="utf8" src="//cdn.datatables.net/1.10.21/js/jquery.dataTables.min.js"></script>'; inlineHtml += '<script type="text/javascript" charset="utf8" src="//cdn.datatables.net/rowgroup/1.1.3/js/dataTables.rowGroup.min.js"></script> ' inlineHtml += '<script type="text/javascript" charset="utf8" src="//cdn.datatables.net/buttons/2.0.0/js/dataTables.buttons.min.js"></script> ' inlineHtml += '<script type="text/javascript" charset="utf8" src="//cdnjs.cloudflare.com/ajax/libs/jszip/3.1.3/jszip.min.js"></script> ' inlineHtml += '<script type="text/javascript" charset="utf8" src="//cdnjs.cloudflare.com/ajax/libs/pdfmake/0.1.53/pdfmake.min.js"></script> ' inlineHtml += '<script type="text/javascript" charset="utf8" src="//cdnjs.cloudflare.com/ajax/libs/pdfmake/0.1.53/vfs_fonts.js"></script> ' inlineHtml += '<script type="text/javascript" charset="utf8" src="//cdn.datatables.net/buttons/2.0.0/js/buttons.html5.min.js"></script> ' inlineHtml += '<script type="text/javascript" charset="utf8" src="//cdn.datatables.net/buttons/2.0.0/js/buttons.print.min.js"></script> ' // Load Bootstrap-Select inlineHtml += '<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap-select@1.13.14/dist/css/bootstrap-select.min.css">'; inlineHtml += '<script src="https://cdn.jsdelivr.net/npm/bootstrap-select@1.13.14/dist/js/bootstrap-select.min.js"></script>'; // Load Netsuite stylesheet and script inlineHtml += '<link rel="stylesheet" href="https://1048144.app.netsuite.com/core/media/media.nl?id=2060796&c=1048144&h=9ee6accfd476c9cae718&_xt=.css"/>'; inlineHtml += '<script src="https://1048144.app.netsuite.com/core/media/media.nl?id=2060797&c=1048144&h=ef2cda20731d146b5e98&_xt=.js"></script>'; inlineHtml += '<link type="text/css" rel="stylesheet" href="https://1048144.app.netsuite.com/core/media/media.nl?id=2090583&c=1048144&h=a0ef6ac4e28f91203dfe&_xt=.css">'; inlineHtml += '<style>.mandatory{color:red;}</style>'; // Title inlineHtml += '<h1 style="font-size: 25px; font-weight: 700; color: #103D39; text-align: center">Debt Collection: Assign (Submitted)</h1>'; // Define alert window. inlineHtml += '<div class="container" style="margin-top:14px;" hidden><div id="alert" class="alert alert-danger fade in"></div></div>'; // Define information window. inlineHtml += '<div class="container" hidden><p id="info" class="alert alert-info"></p></div>'; inlineHtml += '<div style="margin-top: -40px"><br/>'; // inlineHtml += inlineHtml += '<div class="form-group container save_record button_section">'; inlineHtml += '<div class="row">'; inlineHtml += '<div class="col-xs-4 col-xs-offset-4 home_btn">'; inlineHtml += '<input type="button" style="margin-left: 10px; margin-right: 5px; margin-top: 35px; background-color: #FBEA51; color: #103D39; font-weight: 700; border-color: transparent; border-width: 2px; border-radius: 15px; height: 30px; color: #103D39;" class="form-control btn home_btn" id="home_btn" value="Go Home"></input>'; inlineHtml += '</div></div></div>'; inlineHtml += '</div></div>'; form.addField({ id: 'preview_table', label: 'inlinehtml', type: 'inlinehtml' }).updateLayoutType({ layoutType: ui.FieldLayoutType.STARTROW }).defaultValue = inlineHtml; form.clientScriptFileId = 5142730; //5064221 context.response.writePage(form); redirect.toSuitelet({ scriptId: 'customscript_sl_debt_coll_assign', deploymentId: 'customdeploy_sl_debt_coll_assign' }); } } function tabsSection() { var inlineQty = '<div>'; // Tabs headers inlineQty += '<style>.nav > li.active > a, .nav > li.active > a:focus, .nav > li.active > a:hover { background-color: #379E8F; color: #fff }'; inlineQty += '.nav > li > a, .nav > li > a:focus, .nav > li > a:hover { margin-left: 5px; margin-right: 5px; border: 2px solid #379E8F; color: #379E8F; }'; inlineQty += '</style>'; inlineQty += '<div style="width: 95%; margin:auto; margin-bottom: 30px; margin-top: 30px;",><ul class="nav nav-pills nav-justified" style="margin:0%; ">'; inlineQty += '<li role="presentation" class="active"><a data-toggle="tab" href="#reassign"><b>RE-ASSIGN</b></a></li>'; inlineQty += '<li role="presentation" class=""><a data-toggle="tab" href="#split"><b>SPLIT</b></a></li>'; // inlineQty += '<li role="presentation" class="active"><a data-toggle="tab" href="#invoices"><b>INVOICES</b></a></li>'; inlineQty += '</ul></div>'; // Tabs content inlineQty += '<div class="tab-content">'; // if (!isFinanceRole(userRole)) { inlineQty += '<div role="tabpanel" class="tab-pane active" id="reassign">'; // inlineQty += dataTablePreview('reassign'); inlineQty += reassign(); inlineQty += '</div>'; inlineQty += '<div role="tabpanel" class="tab-pane" id="split">'; // inlineQty += dataTablePreview('split'); inlineQty += split(); inlineQty += '</div>'; // } inlineQty += '</div>'; //</div> return inlineQty; } function reassign() { var inlineQty = '<div class="form-group container-fluid range_filter_section">'; inlineQty += '<div class="row">'; inlineQty += '<div class="col-xs-5 team_section">'; inlineQty += '<div class="input-group">'; inlineQty += '<span class="input-group-addon" id="team_filter_text">Team Member Selection</span>'; inlineQty += '<select multiple id="team_filter" class="form-control">'; var employeeSearch = search.load({ type: 'employee', id: 'customsearch_debt_coll_employees' }); // inlineQty += '<option value="" selected>- None -</option>'; employeeSearch.run().each(function (res) { var em_id = res.getValue({ name: 'internalid' }) var em_first_name = res.getValue({ name: 'firstname' }); var em_last_name = res.getValue({ name: 'lastname' }); inlineQty += '<option value="' + em_id + '">' + em_first_name + ' ' + em_last_name + '</option>'; return true; }); inlineQty += '</select>'; inlineQty += '</div></div>'; inlineQty += '<div class="col-xs-2">'; inlineQty += '<style>.vl { height: 125px; position: absolute; left: 50%; border-width: px; border-style: solid; border-image: linear-gradient(to bottom, #103D39, rgba(0, 0, 0, 0)) 10; }</style>'; inlineQty += '<div class="vl"></div>'; inlineQty += '</div>' inlineQty += '<div class="col-xs-5 range_section">'; inlineQty += '<div class="form-group">'; inlineQty += '<textarea class="form-control reassignTextArea" id="reassignTextArea" rows="5" disabled></textarea>'; inlineQty += '</div></div>'; inlineQty += '</div>'; inlineQty += '</div>'; // inlineQty = '<div class="form-group container button_section">'; // inlineQty += '<div class="row">'; inlineQty += '<div class="col-xs-4 col-xs-offset-4 send_email_btn">'; inlineQty += '<input type="button" style="margin-left: 10px; margin-right: 5px; background-color: #FBEA51; color: #103D39; font-weight: 700; border-color: transparent; border-width: 2px; border-radius: 15px; height: 30px; color: #103D39;" class="form-control btn" id="submit_arrange" value="Submit"></input>'; inlineQty += '</div>'; // inlineQty += '</div>'; // inlineQty += '</div>'; return inlineQty; } function split() { var inlineQty = '<div class="form-group container-fluid range_filter_section">'; inlineQty += '<div class="row">'; inlineQty += '<div class="col-xs-5 split_team_section">'; inlineQty += '<div class="input-group">'; inlineQty += '<span class="input-group-addon" id="split_employee_filter">Employee Selection</span>'; inlineQty += '<select id="split_team_filter" class="form-control">'; var authSearch = search.load({ type: 'invoice', id: 'customsearch_debt_coll_assign_split' }); authSearch.run().each(function (res) { var auth_id = res.getValue({ name: 'custentity_debt_coll_auth_id', join: 'customer', summary: search.Summary.GROUP }); if (!isNullorEmpty(auth_id)) { var employeeSearch = search.load({ type: 'employee', id: 'customsearch_debt_coll_employees' }); employeeSearch.filters.push(search.createFilter({ name: 'internalid', operator: search.Operator.IS, values: parseInt(auth_id) })); employeeSearch.run().each(function (res) { var em_id = res.getValue({ name: 'internalid' }) var em_first_name = res.getValue({ name: 'firstname' }); var em_last_name = res.getValue({ name: 'lastname' }); inlineQty += '<option value="' + em_id + '">' + em_first_name + ' ' + em_last_name + '</option>'; }); } return true; }); inlineQty += '</select>'; inlineQty += '</div></div>'; inlineQty += '<div class="col-xs-2">'; inlineQty += '<style>.vl { height: 125px; position: absolute; left: 50%; border-width: px; border-style: solid; border-image: linear-gradient(to bottom, #103D39, rgba(0, 0, 0, 0)) 10; }</style>'; inlineQty += '<div class="vl"></div>'; inlineQty += '</div>' inlineQty += '<div class="col-xs-5 split_team_section">'; inlineQty += '<div class="input-group">'; inlineQty += '<span class="input-group-addon" id="split_team_filter_text">Split List Into...</span>'; inlineQty += '<select multiple id="split_member_filter" class="form-control">'; var employeeSearch = search.load({ type: 'employee', id: 'customsearch_debt_coll_employees' }); // inlineQty += '<option value="">- None -</option>'; employeeSearch.run().each(function (res) { var em_id = res.getValue({ name: 'internalid' }) var em_first_name = res.getValue({ name: 'firstname' }); var em_last_name = res.getValue({ name: 'lastname' }); inlineQty += '<option value="' + em_id + '">' + em_first_name + ' ' + em_last_name + '</option>'; return true; }); inlineQty += '</select>'; inlineQty += '</div></div>'; inlineQty += '</div>'; inlineQty += '</div>'; // inlineQty = '<div class="form-group container button_section">'; // inlineQty += '<div class="row">'; inlineQty += '<div class="col-xs-4 col-xs-offset-4 send_email_btn">'; inlineQty += '<input type="button" style="margin-left: 10px; margin-right: 5px; background-color: #FBEA51; color: #103D39; font-weight: 700; border-color: transparent; border-width: 2px; border-radius: 15px; height: 30px; color: #103D39;" class="form-control btn" id="submit_split" value="Submit"></input>'; inlineQty += '</div>'; // inlineQty += '</div>'; // inlineQty += '</div>'; return inlineQty; } /** * The table that will display the differents invoices linked to the franchisee and the time period. * @return {String} inlineQty */ function dataTable() { var inlineQty = '<style>table#debt_preview {font-size: 12px;text-align: center;border: none;}.dataTables_wrapper {font-size: 14px;}table#debt_preview th{text-align: center;} .bolded{font-weight: bold;}</style>'; inlineQty += '<table id="debt_preview" class="table table-responsive table-striped customer tablesorter hide" style="width: 100%;">'; inlineQty += '<thead style="color: white; background-color: #379E8F;">'; inlineQty += '<tr class="text-center">'; inlineQty += '</tr>'; inlineQty += '</thead>'; inlineQty += '<tbody id="result_debt" class="result-debt"></tbody>'; inlineQty += '</table>'; return inlineQty; } /** * Used to pass the values of `date_from` and `date_to` between the scripts and to Netsuite for the records and the search. * @param {String} date_iso "2020-06-01" * @returns {String} date_netsuite "1/6/2020" */ function dateISOToNetsuite(date_iso) { var date_netsuite = ''; if (!isNullorEmpty(date_iso)) { var date_utc = new Date(date_iso); // var date_netsuite = nlapiDateToString(date_utc); var date_netsuite = format.format({ value: date_utc, type: format.Type.DATE }); } return date_netsuite; } function isNullorEmpty(strVal) { return (strVal == null || strVal == '' || strVal == 'null' || strVal == undefined || strVal == 'undefined' || strVal == '- None -'); } return { onRequest: onRequest } } );
true
/** * @NApiVersion 2.0 * @NScriptType Suitelet * * Module Description * * NSVersion Date Author * 2.00 2021-09-20 09:33:08 Anesu * * Description: xxxxxxxx * * @Last Modified by: Anesu * @Last Modified time: 2021-09-20 09:33:08 * */ define(['N/ui/serverWidget', 'N/email', 'N/runtime', 'N/search', 'N/record', 'N/http', 'N/log', 'N/redirect', 'N/task', 'N/format'], function (ui, email, runtime, search, record, http, log, redirect, task, format) { var zee = 0; var role = 0; var baseURL = 'https://1048144.app.netsuite.com'; if (runtime.EnvType == "SANDBOX") { baseURL = 'https://1048144-sb3.app.netsuite.com'; } role = runtime.getCurrentUser().role; if (role == 1000) { zee = runtime.getCurrentUser().id; } else if (role == 3) { //Administrator zee = 6; //test } else if (role == 1032) { // System Support zee = 425904; //test-AR } function onRequest(context) { if (context.request.method === 'GET') { var is_params = 'T'; type = context.request.parameters.type; var form = ui.createForm({ title: ' ' }); // Load jQuery var inlineHtml = '<script src="https://code.jquery.com/jquery-1.12.4.min.js" integrity="PI:KEY:74t3tndxag9o7h0890bnpfzh4olk2h9xEND_PI" crossorigin="anonymous"></script>'; // Load Tooltip inlineHtml += '<script src="https://unpkg.com/@popperjs/core@2"></script>'; // Load Bootstrap inlineHtml += '<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/3.4.1/css/bootstrap.min.css" integrity="PI:KEY:ax5kh6jaqkcd2tiexxs8v6xjo8yv8a6bEND_PI" crossorigin="anonymous">'; inlineHtml += '<script src="https://stackpath.bootstrapcdn.com/bootstrap/3.4.1/js/bootstrap.min.js" integrity="PI:KEY:74t3tndxag9o7h0890bnpfzh4olk2h9xEND_PI" crossorigin="anonymous"></script>'; // Load Bootstrap-Select inlineHtml += '<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap-select@1.13.14/dist/css/bootstrap-select.min.css">'; inlineHtml += '<script src="https://cdn.jsdelivr.net/npm/bootstrap-select@1.13.14/dist/js/bootstrap-select.min.js"></script>'; // Load DataTables inlineHtml += '<link rel="stylesheet" type="text/css" href="//cdn.datatables.net/1.10.21/css/jquery.dataTables.min.css">'; inlineHtml += '<script type="text/javascript" charset="utf8" src="//cdn.datatables.net/1.10.21/js/jquery.dataTables.min.js"></script>'; inlineHtml += '<script type="text/javascript" charset="utf8" src="//cdn.datatables.net/rowgroup/1.1.3/js/dataTables.rowGroup.min.js"></script> ' inlineHtml += '<script type="text/javascript" charset="utf8" src="//cdn.datatables.net/buttons/2.0.0/js/dataTables.buttons.min.js"></script> ' inlineHtml += '<script type="text/javascript" charset="utf8" src="//cdnjs.cloudflare.com/ajax/libs/jszip/3.1.3/jszip.min.js"></script> ' inlineHtml += '<script type="text/javascript" charset="utf8" src="//cdnjs.cloudflare.com/ajax/libs/pdfmake/0.1.53/pdfmake.min.js"></script> ' inlineHtml += '<script type="text/javascript" charset="utf8" src="//cdnjs.cloudflare.com/ajax/libs/pdfmake/0.1.53/vfs_fonts.js"></script> ' inlineHtml += '<script type="text/javascript" charset="utf8" src="//cdn.datatables.net/buttons/2.0.0/js/buttons.html5.min.js"></script> ' inlineHtml += '<script type="text/javascript" charset="utf8" src="//cdn.datatables.net/buttons/2.0.0/js/buttons.print.min.js"></script> ' // Load Bootstrap-Select inlineHtml += '<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap-select@1.13.14/dist/css/bootstrap-select.min.css">'; inlineHtml += '<script src="https://cdn.jsdelivr.net/npm/bootstrap-select@1.13.14/dist/js/bootstrap-select.min.js"></script>'; // Load Netsuite stylesheet and script inlineHtml += '<link rel="stylesheet" href="https://1048144.app.netsuite.com/core/media/media.nl?id=2060796&c=1048144&h=9ee6accfd476c9cae718&_xt=.css"/>'; inlineHtml += '<script src="https://1048144.app.netsuite.com/core/media/media.nl?id=2060797&c=1048144&h=ef2cda20731d146b5e98&_xt=.js"></script>'; inlineHtml += '<link type="text/css" rel="stylesheet" href="https://1048144.app.netsuite.com/core/media/media.nl?id=2090583&c=1048144&h=a0ef6ac4e28f91203dfe&_xt=.css">'; inlineHtml += '<style>.mandatory{color:red;}</style>'; // New Website Color Schemes // Main Color: #379E8F // Background Color: #CFE0CE // Button Color: #FBEA51 // Text Color: #103D39 // inlineHtml += '<div class="a" style="width: 100%; background-color: #CFE0CE; padding: 20px; min-height: 100vh; height: 100%; ">'; // margin-top: -40px // inlineHtml += '<style>.nav > li.active > a, .nav > li.active > a:focus, .nav > li.active > a:hover { background-color: #379E8F; color: #fff }'; // inlineHtml += '.nav > li > a, .nav > li > a:focus, .nav > li > a:hover { margin-left: 5px; margin-right: 5px; border: 2px solid #379E8F; color: #379E8F; }'; // inlineHtml += '</style>'; // Title inlineHtml += '<h1 style="font-size: 25px; font-weight: 700; color: #103D39; text-align: center">Debt Collection: Assign Customers</h1>'; // Define alert window. inlineHtml += '<div class="container" style="margin-top:14px;" hidden><div id="alert" class="alert alert-danger fade in"></div></div>'; // Define information window. inlineHtml += '<div class="container" hidden><p id="info" class="alert alert-info"></p></div>'; inlineHtml += '<div style="margin-top: -40px"><br/>'; // Buttons // inlineHtml += '<button style="margin-left: 10px; margin-right: 5px; background-color: #FBEA51; color: #103D39; font-weight: 700; border-color: transparent; border-width: 2px; border-radius: 15px; height: 30px" type="button" id="new_agreement" onclick="">New Franchisee Agreement</button>'; inlineHtml += tabsSection(); // inlineHtml += dataTable(); inlineHtml += '</div></div>' form.addField({ id: 'preview_table', label: 'inlinehtml', type: 'inlinehtml' }).updateLayoutType({ layoutType: ui.FieldLayoutType.STARTROW }).defaultValue = inlineHtml; form.addField({ id: 'custpage_debt_inv_assign_emp_id', label: 'Employee ID', type: ui.FieldType.TEXT }).updateDisplayType({ displayType: ui.FieldDisplayType.HIDDEN }) form.addField({ id: 'custpage_debt_inv_assign_emp_split', label: 'Split', type: ui.FieldType.TEXT }).updateDisplayType({ displayType: ui.FieldDisplayType.HIDDEN }) form.addField({ id: 'custpage_debt_inv_assign_emp_split_id', label: 'Split ID', type: ui.FieldType.TEXT }).updateDisplayType({ displayType: ui.FieldDisplayType.HIDDEN }) form.addField({ id: 'custpage_debt_inv_assign_count', label: 'Count', type: ui.FieldType.TEXT }).updateDisplayType({ displayType: ui.FieldDisplayType.HIDDEN }); form.addSubmitButton({ label: ' ' }); form.clientScriptFileId = 5142730; //5064221 context.response.writePage(form); } else { var params = context.request.parameters; var emp_id = context.request.parameters.custpage_debt_inv_assign_emp_id // Array of Id's for Employees var split_bool = context.request.parameters.custpage_debt_inv_assign_emp_split var emp_split_id = context.request.parameters.custpage_debt_inv_assign_emp_split_id var count = context.request.parameters.custpage_debt_inv_assign_count; log.debug({ title: 'Submitter: Params', details: params }); log.debug({ title: 'Submitter: Params Employee ID', details: params.custpage_debt_inv_assign_emp_id }); log.debug({ title: 'Submitter: Params count', details: params.custpage_debt_inv_assign_count }); // CALL SCHEDULED SCRIPT var params2 = { custscript_debt_inv_assign_emp_id: emp_id, custscript_debt_inv_assign_emp_split: split_bool, custscript_debt_inv_assign_emp_split_id: emp_split_id, custscript_debt_inv_assign_count: count } var scriptTask = task.create({ taskType: task.TaskType.SCHEDULED_SCRIPT, scriptId: 'customscript_ss_debt_coll_assign', deploymentId: 'customdeploy_ss_debt_coll_assign', params: params2 }); var ss_id = scriptTask.submit(); var myTaskStatus = task.checkStatus({ taskId: ss_id }); log.audit({ title: 'Task Status', details: myTaskStatus }); log.audit({ title: 'Task Submit: Params', details: scriptTask.params }) log.audit({ title: 'Task Submit: Params Employee ID', details: scriptTask.params.emp_id }); var form = ui.createForm({ title: ' ', }); var inlineHtml = '<script src="https://code.jquery.com/jquery-1.12.4.min.js" integrity="PI:KEY:74t3tndxag9o7h0890bnpfzh4olk2h9xEND_PI" crossorigin="anonymous"></script>'; // Load Tooltip inlineHtml += '<script src="https://unpkg.com/@popperjs/core@2"></script>'; // Load Bootstrap inlineHtml += '<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/3.4.1/css/bootstrap.min.css" integrity="PI:KEY:ax5kh6jaqkcd2tiexxs8v6xjo8yv8a6bEND_PI" crossorigin="anonymous">'; inlineHtml += '<script src="https://stackpath.bootstrapcdn.com/bootstrap/3.4.1/js/bootstrap.min.js" integrity="PI:KEY:74t3tndxag9o7h0890bnpfzh4olk2h9xEND_PI" crossorigin="anonymous"></script>'; // Load Bootstrap-Select inlineHtml += '<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap-select@1.13.14/dist/css/bootstrap-select.min.css">'; inlineHtml += '<script src="https://cdn.jsdelivr.net/npm/bootstrap-select@1.13.14/dist/js/bootstrap-select.min.js"></script>'; // Load DataTables inlineHtml += '<link rel="stylesheet" type="text/css" href="//cdn.datatables.net/1.10.21/css/jquery.dataTables.min.css">'; inlineHtml += '<script type="text/javascript" charset="utf8" src="//cdn.datatables.net/1.10.21/js/jquery.dataTables.min.js"></script>'; inlineHtml += '<script type="text/javascript" charset="utf8" src="//cdn.datatables.net/rowgroup/1.1.3/js/dataTables.rowGroup.min.js"></script> ' inlineHtml += '<script type="text/javascript" charset="utf8" src="//cdn.datatables.net/buttons/2.0.0/js/dataTables.buttons.min.js"></script> ' inlineHtml += '<script type="text/javascript" charset="utf8" src="//cdnjs.cloudflare.com/ajax/libs/jszip/3.1.3/jszip.min.js"></script> ' inlineHtml += '<script type="text/javascript" charset="utf8" src="//cdnjs.cloudflare.com/ajax/libs/pdfmake/0.1.53/pdfmake.min.js"></script> ' inlineHtml += '<script type="text/javascript" charset="utf8" src="//cdnjs.cloudflare.com/ajax/libs/pdfmake/0.1.53/vfs_fonts.js"></script> ' inlineHtml += '<script type="text/javascript" charset="utf8" src="//cdn.datatables.net/buttons/2.0.0/js/buttons.html5.min.js"></script> ' inlineHtml += '<script type="text/javascript" charset="utf8" src="//cdn.datatables.net/buttons/2.0.0/js/buttons.print.min.js"></script> ' // Load Bootstrap-Select inlineHtml += '<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap-select@1.13.14/dist/css/bootstrap-select.min.css">'; inlineHtml += '<script src="https://cdn.jsdelivr.net/npm/bootstrap-select@1.13.14/dist/js/bootstrap-select.min.js"></script>'; // Load Netsuite stylesheet and script inlineHtml += '<link rel="stylesheet" href="https://1048144.app.netsuite.com/core/media/media.nl?id=2060796&c=1048144&h=9ee6accfd476c9cae718&_xt=.css"/>'; inlineHtml += '<script src="https://1048144.app.netsuite.com/core/media/media.nl?id=2060797&c=1048144&h=ef2cda20731d146b5e98&_xt=.js"></script>'; inlineHtml += '<link type="text/css" rel="stylesheet" href="https://1048144.app.netsuite.com/core/media/media.nl?id=2090583&c=1048144&h=a0ef6ac4e28f91203dfe&_xt=.css">'; inlineHtml += '<style>.mandatory{color:red;}</style>'; // Title inlineHtml += '<h1 style="font-size: 25px; font-weight: 700; color: #103D39; text-align: center">Debt Collection: Assign (Submitted)</h1>'; // Define alert window. inlineHtml += '<div class="container" style="margin-top:14px;" hidden><div id="alert" class="alert alert-danger fade in"></div></div>'; // Define information window. inlineHtml += '<div class="container" hidden><p id="info" class="alert alert-info"></p></div>'; inlineHtml += '<div style="margin-top: -40px"><br/>'; // inlineHtml += inlineHtml += '<div class="form-group container save_record button_section">'; inlineHtml += '<div class="row">'; inlineHtml += '<div class="col-xs-4 col-xs-offset-4 home_btn">'; inlineHtml += '<input type="button" style="margin-left: 10px; margin-right: 5px; margin-top: 35px; background-color: #FBEA51; color: #103D39; font-weight: 700; border-color: transparent; border-width: 2px; border-radius: 15px; height: 30px; color: #103D39;" class="form-control btn home_btn" id="home_btn" value="Go Home"></input>'; inlineHtml += '</div></div></div>'; inlineHtml += '</div></div>'; form.addField({ id: 'preview_table', label: 'inlinehtml', type: 'inlinehtml' }).updateLayoutType({ layoutType: ui.FieldLayoutType.STARTROW }).defaultValue = inlineHtml; form.clientScriptFileId = 5142730; //5064221 context.response.writePage(form); redirect.toSuitelet({ scriptId: 'customscript_sl_debt_coll_assign', deploymentId: 'customdeploy_sl_debt_coll_assign' }); } } function tabsSection() { var inlineQty = '<div>'; // Tabs headers inlineQty += '<style>.nav > li.active > a, .nav > li.active > a:focus, .nav > li.active > a:hover { background-color: #379E8F; color: #fff }'; inlineQty += '.nav > li > a, .nav > li > a:focus, .nav > li > a:hover { margin-left: 5px; margin-right: 5px; border: 2px solid #379E8F; color: #379E8F; }'; inlineQty += '</style>'; inlineQty += '<div style="width: 95%; margin:auto; margin-bottom: 30px; margin-top: 30px;",><ul class="nav nav-pills nav-justified" style="margin:0%; ">'; inlineQty += '<li role="presentation" class="active"><a data-toggle="tab" href="#reassign"><b>RE-ASSIGN</b></a></li>'; inlineQty += '<li role="presentation" class=""><a data-toggle="tab" href="#split"><b>SPLIT</b></a></li>'; // inlineQty += '<li role="presentation" class="active"><a data-toggle="tab" href="#invoices"><b>INVOICES</b></a></li>'; inlineQty += '</ul></div>'; // Tabs content inlineQty += '<div class="tab-content">'; // if (!isFinanceRole(userRole)) { inlineQty += '<div role="tabpanel" class="tab-pane active" id="reassign">'; // inlineQty += dataTablePreview('reassign'); inlineQty += reassign(); inlineQty += '</div>'; inlineQty += '<div role="tabpanel" class="tab-pane" id="split">'; // inlineQty += dataTablePreview('split'); inlineQty += split(); inlineQty += '</div>'; // } inlineQty += '</div>'; //</div> return inlineQty; } function reassign() { var inlineQty = '<div class="form-group container-fluid range_filter_section">'; inlineQty += '<div class="row">'; inlineQty += '<div class="col-xs-5 team_section">'; inlineQty += '<div class="input-group">'; inlineQty += '<span class="input-group-addon" id="team_filter_text">Team Member Selection</span>'; inlineQty += '<select multiple id="team_filter" class="form-control">'; var employeeSearch = search.load({ type: 'employee', id: 'customsearch_debt_coll_employees' }); // inlineQty += '<option value="" selected>- None -</option>'; employeeSearch.run().each(function (res) { var em_id = res.getValue({ name: 'internalid' }) var em_first_name = res.getValue({ name: 'firstname' }); var em_last_name = res.getValue({ name: 'lastname' }); inlineQty += '<option value="' + em_id + '">' + em_first_name + ' ' + em_last_name + '</option>'; return true; }); inlineQty += '</select>'; inlineQty += '</div></div>'; inlineQty += '<div class="col-xs-2">'; inlineQty += '<style>.vl { height: 125px; position: absolute; left: 50%; border-width: px; border-style: solid; border-image: linear-gradient(to bottom, #103D39, rgba(0, 0, 0, 0)) 10; }</style>'; inlineQty += '<div class="vl"></div>'; inlineQty += '</div>' inlineQty += '<div class="col-xs-5 range_section">'; inlineQty += '<div class="form-group">'; inlineQty += '<textarea class="form-control reassignTextArea" id="reassignTextArea" rows="5" disabled></textarea>'; inlineQty += '</div></div>'; inlineQty += '</div>'; inlineQty += '</div>'; // inlineQty = '<div class="form-group container button_section">'; // inlineQty += '<div class="row">'; inlineQty += '<div class="col-xs-4 col-xs-offset-4 send_email_btn">'; inlineQty += '<input type="button" style="margin-left: 10px; margin-right: 5px; background-color: #FBEA51; color: #103D39; font-weight: 700; border-color: transparent; border-width: 2px; border-radius: 15px; height: 30px; color: #103D39;" class="form-control btn" id="submit_arrange" value="Submit"></input>'; inlineQty += '</div>'; // inlineQty += '</div>'; // inlineQty += '</div>'; return inlineQty; } function split() { var inlineQty = '<div class="form-group container-fluid range_filter_section">'; inlineQty += '<div class="row">'; inlineQty += '<div class="col-xs-5 split_team_section">'; inlineQty += '<div class="input-group">'; inlineQty += '<span class="input-group-addon" id="split_employee_filter">Employee Selection</span>'; inlineQty += '<select id="split_team_filter" class="form-control">'; var authSearch = search.load({ type: 'invoice', id: 'customsearch_debt_coll_assign_split' }); authSearch.run().each(function (res) { var auth_id = res.getValue({ name: 'custentity_debt_coll_auth_id', join: 'customer', summary: search.Summary.GROUP }); if (!isNullorEmpty(auth_id)) { var employeeSearch = search.load({ type: 'employee', id: 'customsearch_debt_coll_employees' }); employeeSearch.filters.push(search.createFilter({ name: 'internalid', operator: search.Operator.IS, values: parseInt(auth_id) })); employeeSearch.run().each(function (res) { var em_id = res.getValue({ name: 'internalid' }) var em_first_name = res.getValue({ name: 'firstname' }); var em_last_name = res.getValue({ name: 'lastname' }); inlineQty += '<option value="' + em_id + '">' + em_first_name + ' ' + em_last_name + '</option>'; }); } return true; }); inlineQty += '</select>'; inlineQty += '</div></div>'; inlineQty += '<div class="col-xs-2">'; inlineQty += '<style>.vl { height: 125px; position: absolute; left: 50%; border-width: px; border-style: solid; border-image: linear-gradient(to bottom, #103D39, rgba(0, 0, 0, 0)) 10; }</style>'; inlineQty += '<div class="vl"></div>'; inlineQty += '</div>' inlineQty += '<div class="col-xs-5 split_team_section">'; inlineQty += '<div class="input-group">'; inlineQty += '<span class="input-group-addon" id="split_team_filter_text">Split List Into...</span>'; inlineQty += '<select multiple id="split_member_filter" class="form-control">'; var employeeSearch = search.load({ type: 'employee', id: 'customsearch_debt_coll_employees' }); // inlineQty += '<option value="">- None -</option>'; employeeSearch.run().each(function (res) { var em_id = res.getValue({ name: 'internalid' }) var em_first_name = res.getValue({ name: 'firstname' }); var em_last_name = res.getValue({ name: 'lastname' }); inlineQty += '<option value="' + em_id + '">' + em_first_name + ' ' + em_last_name + '</option>'; return true; }); inlineQty += '</select>'; inlineQty += '</div></div>'; inlineQty += '</div>'; inlineQty += '</div>'; // inlineQty = '<div class="form-group container button_section">'; // inlineQty += '<div class="row">'; inlineQty += '<div class="col-xs-4 col-xs-offset-4 send_email_btn">'; inlineQty += '<input type="button" style="margin-left: 10px; margin-right: 5px; background-color: #FBEA51; color: #103D39; font-weight: 700; border-color: transparent; border-width: 2px; border-radius: 15px; height: 30px; color: #103D39;" class="form-control btn" id="submit_split" value="Submit"></input>'; inlineQty += '</div>'; // inlineQty += '</div>'; // inlineQty += '</div>'; return inlineQty; } /** * The table that will display the differents invoices linked to the franchisee and the time period. * @return {String} inlineQty */ function dataTable() { var inlineQty = '<style>table#debt_preview {font-size: 12px;text-align: center;border: none;}.dataTables_wrapper {font-size: 14px;}table#debt_preview th{text-align: center;} .bolded{font-weight: bold;}</style>'; inlineQty += '<table id="debt_preview" class="table table-responsive table-striped customer tablesorter hide" style="width: 100%;">'; inlineQty += '<thead style="color: white; background-color: #379E8F;">'; inlineQty += '<tr class="text-center">'; inlineQty += '</tr>'; inlineQty += '</thead>'; inlineQty += '<tbody id="result_debt" class="result-debt"></tbody>'; inlineQty += '</table>'; return inlineQty; } /** * Used to pass the values of `date_from` and `date_to` between the scripts and to Netsuite for the records and the search. * @param {String} date_iso "2020-06-01" * @returns {String} date_netsuite "1/6/2020" */ function dateISOToNetsuite(date_iso) { var date_netsuite = ''; if (!isNullorEmpty(date_iso)) { var date_utc = new Date(date_iso); // var date_netsuite = nlapiDateToString(date_utc); var date_netsuite = format.format({ value: date_utc, type: format.Type.DATE }); } return date_netsuite; } function isNullorEmpty(strVal) { return (strVal == null || strVal == '' || strVal == 'null' || strVal == undefined || strVal == 'undefined' || strVal == '- None -'); } return { onRequest: onRequest } } );
/** * @NApiVersion 2.1 * @NScriptType MapReduceScript * @NModuleScope SameAccount * @NAmdConfig /SuiteScripts/CSV Import/csv_import_configuration.json * * @author Selcuk Dogru * _nse_mr_csv_import * * @description Based on the script parameters, processes the CSV file and notifies user about the outcome. */ define(['N/cache', 'N/currency', 'N/email', 'N/error', 'N/file', 'N/format', 'N/record', 'N/runtime', 'N/search', 'nseLib', 'papaparse'], (cache, currency, email, error, file, format, record, runtime, search, nseLib, Papa) => { const RESERVED_KEYS = ['recType', 'defaultValues', 'lineMapping', 'lineId']; const EMAIL_AUTHOR_ID = -5; const ERROR_FILE_NAME = 'csv_import_errors.csv'; const CACHE_DETAILS = { name: '236e41105efcb76877ea5366a475158f573b7575a14e06283729a26ed3e8c5d5', periodKey: 'b4558708e6706d063135062653bf63ce128a8a3ac6daa3cc3ae714966097bfa8', permissionKey: 'c45686a8e67d6d074135c63653cf60cb128a6a3ac6dab3cb3ae714265087bfa1' }; const SCRIPT_PARAMS = { fileId: 'custscript_nse_mr_csv_import_fileid', mapping: 'custscript_nse_mr_csv_import_map', options: 'custscript_nse_mr_csv_import_option', user: 'custscript_nse_mr_csv_import_user', subsidiary: 'custscript_nse_mr_csv_import_sub' }; /** * @function getInputData * @description Parses the CSV file and creates cache that stores employee permissions. * * @returns {array} - Parsed CSV file */ let getInputData = () => { let scriptParams = nseLib.getScriptParams(SCRIPT_PARAMS); let options = JSON.parse(scriptParams.options); let csvFile = file.load({ id: parseInt(scriptParams.fileId) }); let parsedData = Papa.parse(csvFile.getContents(), { header: true, delimiter: options.csvDelimiter, skipEmptyLines: 'greedy' }); let csvFileParseErrors = ''; for (let e in parsedData.errors) { csvFileParseErrors += parsedData.errors[e].row + ',' + parsedData.errors[e].message + '\n'; } if (!nseLib.isEmpty(csvFileParseErrors)) { throw error.create({ name: 'NSE_CSV_PRS_ERR', message: csvFileParseErrors, notifyOff: true }); } let lpCache = cache.getCache({ name: CACHE_DETAILS.name, scope: cache.Scope.PRIVATE }); lpCache.put({ key: CACHE_DETAILS.permissionKey, value: getEmployeeCreatePermissions(scriptParams.user, scriptParams.subsidiary) }); if (!options.postToLockedPeriod) { lpCache.put({ key: CACHE_DETAILS.periodKey, value: getLockedPeriods() }); } return parsedData.data; } /** * @function map * @description Matches the CSV line with the related record mapping. Prepares object to be processed as a NetSuite record. * * @param context * @returns null */ let map = (context) => { let lineData = JSON.parse(context.value); log.debug('lineData', lineData); let recordMapping = getRecordMapping(lineData.Type); log.debug('recordMapping', recordMapping); if (nseLib.isEmpty(recordMapping)) throw error.create({ name: 'NSE_CSV_IMP_NO_REC_MAP', message: 'No record mapping found for record type ' + lineData.Type, notifyOff: true }); let recordData = { type: recordMapping.recType }; for (let key in recordMapping) { if (!RESERVED_KEYS.includes(key)) { if (!nseLib.isEmpty(lineData[key])) recordData[recordMapping[key]] = lineData[key]; } else if (key === RESERVED_KEYS[2]) { recordData.lines = { sublistId: recordMapping[key].lineId }; for (let lineKey in recordMapping[key]) { if (!RESERVED_KEYS.includes(lineKey)) { if (!nseLib.isEmpty(lineData[lineKey])) recordData.lines[recordMapping[key][lineKey]] = lineData[lineKey]; } else if (lineKey === RESERVED_KEYS[1]) { for (let defaultLineKey in recordMapping[key][lineKey]) { if (!nseLib.isEmpty(recordMapping[key][lineKey][defaultLineKey])) recordData.lines[defaultLineKey] = recordMapping[key][lineKey][defaultLineKey]; } } } } else if (key === RESERVED_KEYS[1]) { for (let defaultKey in recordMapping[key]) { if (!nseLib.isEmpty(recordMapping[key][defaultKey])) recordData[defaultKey] = recordMapping[key][defaultKey]; } } } log.debug('recordData', recordData); context.write(recordData.externalid, recordData); } /** * @function reduce * @description Processes the JSON record data and creates NetSuite record based on the options. User triggered the process must have permission to create the record. * * @param context * @returns null */ let reduce = (context) => { let scriptParams = nseLib.getScriptParams(SCRIPT_PARAMS); let recordChecks = { checkApplySublist: false, transactionApplied: false }; let options = JSON.parse(scriptParams.options); let recordObject = { lines: [] }; for (let v in context.values) { let recordData = JSON.parse(context.values[v]); for (let key in recordData) { if (key !== 'lines') { recordObject[key] = recordData[key]; } } if (!nseLib.isEmpty(recordData.lines)) recordObject.lines.push(recordData.lines); } let lpCache = cache.getCache({ name: CACHE_DETAILS.name, scope: cache.Scope.PRIVATE }); let userCreatePermissions = JSON.parse(lpCache.get({ key: CACHE_DETAILS.permissionKey, loader: getEmployeeCreatePermissions(scriptParams.user, scriptParams.subsidiary) })); if (!userCreatePermissions.includes(options.permissionMap[recordObject.type])) throw error.create({ name: 'NSE_REC_PERM_ERR', message: 'Your assigned roles do not allow you to create this type of transactions.', notifyOff: true }); if ([record.Type.CUSTOMER_PAYMENT, record.Type.VENDOR_PAYMENT].includes(recordObject.type)) recordChecks.checkApplySublist = true; let nsRecord = record.create({ type: record.Type[recordObject.type], isDynamic: true }); setBodyFields(recordObject, nsRecord, options, recordChecks); setLineFields(recordObject, nsRecord, options, recordChecks); let subsidiaryId = parseInt(scriptParams.subsidiary); let nsRecordSubsidiaryId; let nsRecordSubsidiary = nsRecord.getValue({fieldId: 'subsidiary'}); if (util.isArray(nsRecordSubsidiary)) { if (nsRecordSubsidiary.length === 1) nsRecordSubsidiaryId = parseInt(nsRecordSubsidiary[0]); } else { nsRecordSubsidiaryId = parseInt(nsRecordSubsidiary); } if (!nseLib.isEmpty(subsidiaryId) && nsRecordSubsidiaryId !== subsidiaryId) { throw error.create({ name: 'NSE_WRG_SUB_ERR', message: 'Script was not initiated for the subsidiary of this record.', notifyOff: true }); } if (!options.setExternalId) { nsRecord.setValue({ fieldId: 'externalid', value: null }); } if (!options.postToLockedPeriod) { setPostingPeriod(nsRecord, lpCache); } let recordId = nsRecord.save(); if (recordChecks.checkApplySublist && !recordChecks.transactionApplied) { context.write({ key: recordObject.externalid, value: 'Payment record ' + recordId + 'created but not applied to any transaction.' }); } else { context.write({ key: recordObject.externalid, value: 'SUCCESS' }); } } /** * @function summarize * @description Removes cached data. Prepares and sends informational email to the user triggered the process. Updates related CSV Import Queue record. * * @param summary * @returns null */ let summarize = (summary) => { let scriptParams = nseLib.getScriptParams(SCRIPT_PARAMS); let userId = scriptParams.user; let importQueueRecordDetails = nseLib.getImportQueueRecords({fileId: scriptParams.fileId})[scriptParams.subsidiary][0]; let lpCache = cache.getCache({ name: CACHE_DETAILS.name, scope: cache.Scope.PRIVATE }); lpCache.remove({ key: CACHE_DETAILS.periodKey }); lpCache.remove({ key: CACHE_DETAILS.permissionKey }); let recordCounts = { success: 0, warning: 0, error: 0, mapError: 0 }; if (!nseLib.isEmpty(summary.inputSummary.error)) { record.submitFields({ type: 'customrecord_nse_csv_import_queue', id: importQueueRecordDetails.internalId, values: { custrecord_nse_csv_import_status: 4 } }); let inputErrorDetails = JSON.parse(summary.inputSummary.error); let inputErrorMessageDetails = {}; try { inputErrorMessageDetails = JSON.parse(inputErrorDetails.message); } catch (err) { } email.send({ author: EMAIL_AUTHOR_ID, recipients: [userId], subject: 'Error While Processing Uploaded CSV File', body: 'Hello,\n\n' + 'An error occurred while parsing the uploaded CSV file (File ID: ' + scriptParams.fileId + '). ' + 'Please find the details below.\n' + 'You will need to upload the related file again after correcting.\n\n' + 'Error Code: ' + inputErrorDetails.name + '\n' + 'Error Message: ' + inputErrorMessageDetails.message + '\n\n' + 'Regards,\n' + 'NetSuite Service Desk' }); return null; } let errorDetails = ''; summary.mapSummary.errors.iterator().each((key, error) => { recordCounts.mapError++; let errorObject = JSON.parse(error); errorDetails += 'ERROR,' + key + ',' + errorObject.name + ',' + errorObject.message + '\n'; return true; }); summary.reduceSummary.errors.iterator().each((key, error) => { recordCounts.error++; let errorObject = JSON.parse(error); try { let messageDetails = JSON.parse(errorObject.message); errorDetails += 'ERROR,' + key + ',' + messageDetails.name + ',' + messageDetails.message + '\n'; } catch (e) { errorDetails += 'ERROR,' + key + ',' + errorObject.name + ',' + errorObject.message + '\n'; } return true; }); summary.output.iterator().each((key, value) => { if (value === 'SUCCESS') recordCounts.success++; else { recordCounts.warning++ errorDetails += 'WARNING,' + key + ',,' + value + '\n'; } return true; }); record.submitFields({ type: 'customrecord_nse_csv_import_queue', id: importQueueRecordDetails.internalId, values: { custrecord_nse_csv_import_status: 3, custrecord_nse_csv_import_success_count: recordCounts.success, custrecord_nse_csv_import_warning_count: recordCounts.warning, custrecord_nse_csv_import_error_count: recordCounts.error, custrecord_nse_csv_import_map_errors: recordCounts.mapError } }); if (!nseLib.isEmpty(errorDetails)) { errorDetails = 'Type,External ID,Code,Details\n' + errorDetails; email.send({ author: EMAIL_AUTHOR_ID, recipients: [userId], subject: 'CSV File Processing Completed with Errors', body: 'Hello,\n\n' + 'An error occurred while processing the CSV file (File ID: ' + scriptParams.fileId + ').' + 'Please find the details for the failed lines attached.\n' + 'After correcting the CSV file, please upload only the failed lines for processing.\n\n' + 'Regards,\n' + 'NetSuite Service Desk', attachments: [file.create({ name: ERROR_FILE_NAME, fileType: file.Type.CSV, contents: errorDetails })] }); } else { email.send({ author: EMAIL_AUTHOR_ID, recipients: [userId], subject: 'CSV File Processing Completed Successfully', body: 'Hello,\n\n' + 'The CSV file (File ID: ' + scriptParams.fileId + ') was successfully imported. ' + 'If you encounter any inconsistency, please contact us.\n\n' + 'Regards,\n' + 'NetSuite Service Desk' }); } nseLib.initiateQueueScheduler(); } /** * @function getRecordMapping * @description Reads the record mapping from the Script Deployment. * * @param {string }type - Related mapping type from the CSV line * @returns {object} - Record mapping details */ let getRecordMapping = (type) => { let currentScript = runtime.getCurrentScript(); let mappingData = JSON.parse(currentScript.getParameter({ name: 'custscript_nse_mr_csv_import_map' })); return mappingData[type]; } /** * @function getLockedPeriods * @description Queries all open periods and for each open period retrieves locked tasks per subsidiary including the next open posting period. * * @returns {object} - Details of the locked accounting periods */ let getLockedPeriods = () => { let openAccountingPeriods = {}; let accountingPeriodSearch = search.create({ type: search.Type.ACCOUNTING_PERIOD, filters: [ ['closed', search.Operator.IS, false], 'AND', ['isadjust', search.Operator.IS, false], 'AND', ['isinactive', search.Operator.IS, false], 'AND', ['isquarter', search.Operator.IS, false], 'AND', ['isyear', search.Operator.IS, false], 'AND', ['startdate', search.Operator.ONORBEFORE, 'today'] ], columns: ['periodname', 'startdate', 'enddate'] }); accountingPeriodSearch.run().each((result) => { if (openAccountingPeriods[result.id] === undefined) openAccountingPeriods[result.id] = { periodId: result.id, periodName: result.getValue({name: 'periodname'}), startDate: result.getValue({name: 'startdate'}), endDate: result.getValue({name: 'enddate'}) }; return true; }); let lockedAccountingPeriods = {}; for (let o in openAccountingPeriods) { let taskItemStatusSearch = search.create({ type: 'taskitemstatus', filters: [ ['period', 'abs', o], 'AND', ['itemtype', 'anyof', ['PCP_LOCK_AR', 'PCP_LOCK_AP', 'PCP_LOCK_ALL']], 'AND', ['complete', 'is', true] ], columns: ['period', 'subsidiary', 'itemtype'] }); taskItemStatusSearch.run().each((result) => { let periodId = result.getValue({name: 'period'}); let subsidiaryId = result.getValue({name: 'subsidiary'}); let lockedItem = result.getValue({name: 'itemtype'}); if (lockedAccountingPeriods[periodId] === undefined) { lockedAccountingPeriods[periodId] = { details: openAccountingPeriods[o], nextPeriod: getNextPeriodDetails(format.parse({ value: openAccountingPeriods[o].endDate, type: format.Type.DATE })) }; } if (lockedAccountingPeriods[periodId][subsidiaryId] === undefined) lockedAccountingPeriods[periodId][subsidiaryId] = {}; lockedAccountingPeriods[periodId][subsidiaryId][lockedItem] = true; return true; }); } return lockedAccountingPeriods; } /** * @function setBodyFields * @description Sets record body field values. * * @param {object} recObj - Details of the record to be used * @param {object} nsRec - NetSuite record that is being created * @param {object} recOpt - Options for record processing * @param {object} recChecks - Record checks for creating warning messages * @returns null */ let setBodyFields = (recObj, nsRec, recOpt, recChecks) => { for (let bif in recOpt.bodyInitialFields) { if (!nseLib.isEmpty(recObj[recOpt.bodyInitialFields[bif]])) { if (recOpt.textValueFields.includes(recOpt.bodyInitialFields[bif])) { nsRec.setText({ fieldId: recOpt.bodyInitialFields[bif], text: recObj[recOpt.bodyInitialFields[bif]] }); } else { nsRec.setValue({ fieldId: recOpt.bodyInitialFields[bif], value: recObj[recOpt.bodyInitialFields[bif]] }); } } } for (let ro in recObj) { if (ro !== 'type' && !recOpt.bodyInitialFields.includes(ro)) { if (recOpt.textValueFields.includes(ro)) { nsRec.setText({ fieldId: ro, text: recObj[ro] }); } else { nsRec.setValue({ fieldId: ro, value: recOpt.dateValueFields.includes(ro) ? format.parse({ value: recObj[ro], type: format.Type.DATE }) : recObj[ro] }); } } } } /** * @function setLineFields * @description Creates record lines and sets line field values. * * @param {object} recObj - Details of the record to be used * @param {object} nsRec - NetSuite record that is being created * @param {object} recOpt - Options for record processing * @param {object} recChecks - Record checks for creating warning messages * @returns null */ let setLineFields = (recObj, nsRec, recOpt, recChecks) => { for (let l in recObj.lines) { if (!recOpt.applySublists.includes(recObj.lines[l].sublistId)) { nsRec.selectNewLine({ sublistId: recObj.lines[l].sublistId }); for (let lif in recOpt.lineInitialFields) { if (!nseLib.isEmpty(recObj.lines[l][recOpt.lineInitialFields[lif]])) { if (recOpt.textValueFields.includes(recOpt.lineInitialFields[lif])) { nsRec.setCurrentSublistText({ sublistId: recObj.lines[l].sublistId, fieldId: recOpt.lineInitialFields[lif], text: recObj.lines[l][recOpt.lineInitialFields[lif]] }); } else { nsRec.setCurrentSublistValue({ sublistId: recObj.lines[l].sublistId, fieldId: recOpt.lineInitialFields[lif], value: recObj.lines[l][recOpt.lineInitialFields[lif]] }); } } } for (let lo in recObj.lines[l]) { if (lo !== 'sublistId' && !recOpt.lineInitialFields.includes(lo)) { if (recOpt.textValueFields.includes(lo)) { nsRec.setCurrentSublistText({ sublistId: recObj.lines[l].sublistId, fieldId: lo, text: recObj.lines[l][lo] }); } else { nsRec.setCurrentSublistValue({ sublistId: recObj.lines[l].sublistId, fieldId: lo, value: recOpt.dateValueFields.includes(lo) ? format.parse({ value: recObj.lines[l][lo], type: format.Type.DATE }) : recObj.lines[l][lo] }); } } } nsRec.commitLine({ sublistId: recObj.lines[l].sublistId }); } else { let lineId = -1; if (!nseLib.isEmpty(recObj.lines[l].internalid)) lineId = nsRec.findSublistLineWithValue({ sublistId: recObj.lines[l].sublistId, fieldId: 'internalid', value: recObj.lines[l].internalid }); else lineId = nsRec.findSublistLineWithValue({ sublistId: recObj.lines[l].sublistId, fieldId: 'refnum', value: recObj.lines[l].tranid }); if (lineId !== -1 && recObj.lines[l].amount > 0) { recChecks.transactionApplied = true; nsRec.selectLine({ sublistId: recObj.lines[l].sublistId, line: lineId }); nsRec.setCurrentSublistValue({ sublistId: recObj.lines[l].sublistId, fieldId: 'amount', value: recObj.lines[l].amount }); nsRec.commitLine({ sublistId: recObj.lines[l].sublistId }); } } } } /** * @function setPostingPeriod * @description Creates record lines and sets line field values. * * @param {object} nsRec - NetSuite record object that is being created * @param {object} lockedPeriodCache - Locked accounting period details from cache * @returns null */ let setPostingPeriod = (nsRec, lockedPeriodCache) => { let currentPeriodName = nsRec.getText({ fieldId: 'postingperiod' }); let nsRecordSubsidiaryName = nsRec.getText({ fieldId: 'subsidiary' }); if (!nseLib.isEmpty(currentPeriodName)) { let lockedPeriods = JSON.parse(lockedPeriodCache.get({ key: CACHE_DETAILS.periodKey, loader: getLockedPeriods() })); let newPeriodId = -1; while (true) { if (!nseLib.isEmpty(lockedPeriods) && !nseLib.isEmpty(lockedPeriods[currentPeriodName]) && !nseLib.isEmpty(lockedPeriods[currentPeriodName][nsRecordSubsidiaryName])) { if (lockedPeriods[currentPeriodName][nsRecordSubsidiaryName]['Lock All']) { newPeriodId = lockedPeriods[currentPeriodName].nextPeriod.periodId; currentPeriodName = lockedPeriods[currentPeriodName].nextPeriod.periodName; } else break; } else break; } if (newPeriodId !== -1) { nsRec.setValue({ fieldId: 'postingperiod', value: newPeriodId }); } } } /** * @function getNextPeriodDetails * @description Finds the next open posting period based on a given date. * * @param {date} afterDate - Date reference for the search * @returns {object} - Details of the accounting period */ let getNextPeriodDetails = (afterDate) => { let nextPeriodDetails = {}; let periodStartDate = format.format({ value: new Date(afterDate.getTime() + 86400000), type: format.Type.DATE }); let accountingPeriodSearch = search.create({ type: search.Type.ACCOUNTING_PERIOD, filters: [ ['closed', 'is', false], 'AND', ['isadjust', 'is', false], 'AND', ['isinactive', 'is', false], 'AND', ['isquarter', 'is', false], 'AND', ['isyear', 'is', false], 'AND', ['startdate', 'on', periodStartDate] ], columns: ['periodname'] }); let nextPeriods = accountingPeriodSearch.run().getRange({ start: 0, end: 1 }); if (nextPeriods.length > 0) nextPeriodDetails = { periodId: nextPeriods[0].id, periodName: nextPeriods[0].getValue({ name: 'periodname' }) }; return nextPeriodDetails; } /** * @function getEmployeeCreatePermissions * @description Retrieves the record create permissions of the employee from assigned roles. * * @param {number} employeeId - Internal ID of the employee * @param {number} subsidiaryId - Internal ID of the subsidiary * @returns {object} - Details of the user permissions for the subsidiary */ let getEmployeeCreatePermissions = (employeeId, subsidiaryId) => { let permissions = []; let searchFilters = [ ['internalid', search.Operator.ANYOF, employeeId], 'AND', ['level', search.Operator.ANYOF, ['2', '3', '4']] ]; if (!nseLib.isEmpty(subsidiaryId)) { searchFilters.push('AND'); searchFilters.push(['role.subsidiaries', search.Operator.ANYOF, [subsidiaryId]]); } let employeeSearch = search.create({ type: search.Type.EMPLOYEE, filters: searchFilters, columns: ['permission'] }); employeeSearch.run().each(function (result) { permissions.push(result.getValue({ name: 'permission' })); return true; }); return permissions; } return { getInputData: getInputData, map: map, reduce: reduce, summarize: summarize }; });
785
[{"tag": "KEY", "value": "236e41105efcb76877ea5366a475158f573b7575a14e06283729a26ed3e8c5d5", "start": 780, "end": 844}, {"tag": "KEY", "value": "b4558708e6706d063135062653bf63ce128a8a3ac6daa3cc3ae714966097bfa8", "start": 871, "end": 935}, {"tag": "KEY", "value": "c45686a8e67d6d074135c63653cf60cb128a6a3ac6dab3cb3ae714265087bfa1", "start": 966, "end": 1030}]
true
3
/** * @NApiVersion 2.1 * @NScriptType MapReduceScript * @NModuleScope SameAccount * @NAmdConfig /SuiteScripts/CSV Import/csv_import_configuration.json * * @author Selcuk Dogru * _nse_mr_csv_import * * @description Based on the script parameters, processes the CSV file and notifies user about the outcome. */ define(['N/cache', 'N/currency', 'N/email', 'N/error', 'N/file', 'N/format', 'N/record', 'N/runtime', 'N/search', 'nseLib', 'papaparse'], (cache, currency, email, error, file, format, record, runtime, search, nseLib, Papa) => { const RESERVED_KEYS = ['recType', 'defaultValues', 'lineMapping', 'lineId']; const EMAIL_AUTHOR_ID = -5; const ERROR_FILE_NAME = 'csv_import_errors.csv'; const CACHE_DETAILS = { name: '9jnerlff23u8ed01np9g6ysbhsh0dvcs', periodKey: 'vqbpgud2ghvjgm1n5hdgjnn5818fzsf2', permissionKey: 'ax5kh6jaqkcd2tiexxs8v6xjo8yv8a6b' }; const SCRIPT_PARAMS = { fileId: 'custscript_nse_mr_csv_import_fileid', mapping: 'custscript_nse_mr_csv_import_map', options: 'custscript_nse_mr_csv_import_option', user: 'custscript_nse_mr_csv_import_user', subsidiary: 'custscript_nse_mr_csv_import_sub' }; /** * @function getInputData * @description Parses the CSV file and creates cache that stores employee permissions. * * @returns {array} - Parsed CSV file */ let getInputData = () => { let scriptParams = nseLib.getScriptParams(SCRIPT_PARAMS); let options = JSON.parse(scriptParams.options); let csvFile = file.load({ id: parseInt(scriptParams.fileId) }); let parsedData = Papa.parse(csvFile.getContents(), { header: true, delimiter: options.csvDelimiter, skipEmptyLines: 'greedy' }); let csvFileParseErrors = ''; for (let e in parsedData.errors) { csvFileParseErrors += parsedData.errors[e].row + ',' + parsedData.errors[e].message + '\n'; } if (!nseLib.isEmpty(csvFileParseErrors)) { throw error.create({ name: 'NSE_CSV_PRS_ERR', message: csvFileParseErrors, notifyOff: true }); } let lpCache = cache.getCache({ name: CACHE_DETAILS.name, scope: cache.Scope.PRIVATE }); lpCache.put({ key: CACHE_DETAILS.permissionKey, value: getEmployeeCreatePermissions(scriptParams.user, scriptParams.subsidiary) }); if (!options.postToLockedPeriod) { lpCache.put({ key: CACHE_DETAILS.periodKey, value: getLockedPeriods() }); } return parsedData.data; } /** * @function map * @description Matches the CSV line with the related record mapping. Prepares object to be processed as a NetSuite record. * * @param context * @returns null */ let map = (context) => { let lineData = JSON.parse(context.value); log.debug('lineData', lineData); let recordMapping = getRecordMapping(lineData.Type); log.debug('recordMapping', recordMapping); if (nseLib.isEmpty(recordMapping)) throw error.create({ name: 'NSE_CSV_IMP_NO_REC_MAP', message: 'No record mapping found for record type ' + lineData.Type, notifyOff: true }); let recordData = { type: recordMapping.recType }; for (let key in recordMapping) { if (!RESERVED_KEYS.includes(key)) { if (!nseLib.isEmpty(lineData[key])) recordData[recordMapping[key]] = lineData[key]; } else if (key === RESERVED_KEYS[2]) { recordData.lines = { sublistId: recordMapping[key].lineId }; for (let lineKey in recordMapping[key]) { if (!RESERVED_KEYS.includes(lineKey)) { if (!nseLib.isEmpty(lineData[lineKey])) recordData.lines[recordMapping[key][lineKey]] = lineData[lineKey]; } else if (lineKey === RESERVED_KEYS[1]) { for (let defaultLineKey in recordMapping[key][lineKey]) { if (!nseLib.isEmpty(recordMapping[key][lineKey][defaultLineKey])) recordData.lines[defaultLineKey] = recordMapping[key][lineKey][defaultLineKey]; } } } } else if (key === RESERVED_KEYS[1]) { for (let defaultKey in recordMapping[key]) { if (!nseLib.isEmpty(recordMapping[key][defaultKey])) recordData[defaultKey] = recordMapping[key][defaultKey]; } } } log.debug('recordData', recordData); context.write(recordData.externalid, recordData); } /** * @function reduce * @description Processes the JSON record data and creates NetSuite record based on the options. User triggered the process must have permission to create the record. * * @param context * @returns null */ let reduce = (context) => { let scriptParams = nseLib.getScriptParams(SCRIPT_PARAMS); let recordChecks = { checkApplySublist: false, transactionApplied: false }; let options = JSON.parse(scriptParams.options); let recordObject = { lines: [] }; for (let v in context.values) { let recordData = JSON.parse(context.values[v]); for (let key in recordData) { if (key !== 'lines') { recordObject[key] = recordData[key]; } } if (!nseLib.isEmpty(recordData.lines)) recordObject.lines.push(recordData.lines); } let lpCache = cache.getCache({ name: CACHE_DETAILS.name, scope: cache.Scope.PRIVATE }); let userCreatePermissions = JSON.parse(lpCache.get({ key: CACHE_DETAILS.permissionKey, loader: getEmployeeCreatePermissions(scriptParams.user, scriptParams.subsidiary) })); if (!userCreatePermissions.includes(options.permissionMap[recordObject.type])) throw error.create({ name: 'NSE_REC_PERM_ERR', message: 'Your assigned roles do not allow you to create this type of transactions.', notifyOff: true }); if ([record.Type.CUSTOMER_PAYMENT, record.Type.VENDOR_PAYMENT].includes(recordObject.type)) recordChecks.checkApplySublist = true; let nsRecord = record.create({ type: record.Type[recordObject.type], isDynamic: true }); setBodyFields(recordObject, nsRecord, options, recordChecks); setLineFields(recordObject, nsRecord, options, recordChecks); let subsidiaryId = parseInt(scriptParams.subsidiary); let nsRecordSubsidiaryId; let nsRecordSubsidiary = nsRecord.getValue({fieldId: 'subsidiary'}); if (util.isArray(nsRecordSubsidiary)) { if (nsRecordSubsidiary.length === 1) nsRecordSubsidiaryId = parseInt(nsRecordSubsidiary[0]); } else { nsRecordSubsidiaryId = parseInt(nsRecordSubsidiary); } if (!nseLib.isEmpty(subsidiaryId) && nsRecordSubsidiaryId !== subsidiaryId) { throw error.create({ name: 'NSE_WRG_SUB_ERR', message: 'Script was not initiated for the subsidiary of this record.', notifyOff: true }); } if (!options.setExternalId) { nsRecord.setValue({ fieldId: 'externalid', value: null }); } if (!options.postToLockedPeriod) { setPostingPeriod(nsRecord, lpCache); } let recordId = nsRecord.save(); if (recordChecks.checkApplySublist && !recordChecks.transactionApplied) { context.write({ key: recordObject.externalid, value: 'Payment record ' + recordId + 'created but not applied to any transaction.' }); } else { context.write({ key: recordObject.externalid, value: 'SUCCESS' }); } } /** * @function summarize * @description Removes cached data. Prepares and sends informational email to the user triggered the process. Updates related CSV Import Queue record. * * @param summary * @returns null */ let summarize = (summary) => { let scriptParams = nseLib.getScriptParams(SCRIPT_PARAMS); let userId = scriptParams.user; let importQueueRecordDetails = nseLib.getImportQueueRecords({fileId: scriptParams.fileId})[scriptParams.subsidiary][0]; let lpCache = cache.getCache({ name: CACHE_DETAILS.name, scope: cache.Scope.PRIVATE }); lpCache.remove({ key: CACHE_DETAILS.periodKey }); lpCache.remove({ key: CACHE_DETAILS.permissionKey }); let recordCounts = { success: 0, warning: 0, error: 0, mapError: 0 }; if (!nseLib.isEmpty(summary.inputSummary.error)) { record.submitFields({ type: 'customrecord_nse_csv_import_queue', id: importQueueRecordDetails.internalId, values: { custrecord_nse_csv_import_status: 4 } }); let inputErrorDetails = JSON.parse(summary.inputSummary.error); let inputErrorMessageDetails = {}; try { inputErrorMessageDetails = JSON.parse(inputErrorDetails.message); } catch (err) { } email.send({ author: EMAIL_AUTHOR_ID, recipients: [userId], subject: 'Error While Processing Uploaded CSV File', body: 'Hello,\n\n' + 'An error occurred while parsing the uploaded CSV file (File ID: ' + scriptParams.fileId + '). ' + 'Please find the details below.\n' + 'You will need to upload the related file again after correcting.\n\n' + 'Error Code: ' + inputErrorDetails.name + '\n' + 'Error Message: ' + inputErrorMessageDetails.message + '\n\n' + 'Regards,\n' + 'NetSuite Service Desk' }); return null; } let errorDetails = ''; summary.mapSummary.errors.iterator().each((key, error) => { recordCounts.mapError++; let errorObject = JSON.parse(error); errorDetails += 'ERROR,' + key + ',' + errorObject.name + ',' + errorObject.message + '\n'; return true; }); summary.reduceSummary.errors.iterator().each((key, error) => { recordCounts.error++; let errorObject = JSON.parse(error); try { let messageDetails = JSON.parse(errorObject.message); errorDetails += 'ERROR,' + key + ',' + messageDetails.name + ',' + messageDetails.message + '\n'; } catch (e) { errorDetails += 'ERROR,' + key + ',' + errorObject.name + ',' + errorObject.message + '\n'; } return true; }); summary.output.iterator().each((key, value) => { if (value === 'SUCCESS') recordCounts.success++; else { recordCounts.warning++ errorDetails += 'WARNING,' + key + ',,' + value + '\n'; } return true; }); record.submitFields({ type: 'customrecord_nse_csv_import_queue', id: importQueueRecordDetails.internalId, values: { custrecord_nse_csv_import_status: 3, custrecord_nse_csv_import_success_count: recordCounts.success, custrecord_nse_csv_import_warning_count: recordCounts.warning, custrecord_nse_csv_import_error_count: recordCounts.error, custrecord_nse_csv_import_map_errors: recordCounts.mapError } }); if (!nseLib.isEmpty(errorDetails)) { errorDetails = 'Type,External ID,Code,Details\n' + errorDetails; email.send({ author: EMAIL_AUTHOR_ID, recipients: [userId], subject: 'CSV File Processing Completed with Errors', body: 'Hello,\n\n' + 'An error occurred while processing the CSV file (File ID: ' + scriptParams.fileId + ').' + 'Please find the details for the failed lines attached.\n' + 'After correcting the CSV file, please upload only the failed lines for processing.\n\n' + 'Regards,\n' + 'NetSuite Service Desk', attachments: [file.create({ name: ERROR_FILE_NAME, fileType: file.Type.CSV, contents: errorDetails })] }); } else { email.send({ author: EMAIL_AUTHOR_ID, recipients: [userId], subject: 'CSV File Processing Completed Successfully', body: 'Hello,\n\n' + 'The CSV file (File ID: ' + scriptParams.fileId + ') was successfully imported. ' + 'If you encounter any inconsistency, please contact us.\n\n' + 'Regards,\n' + 'NetSuite Service Desk' }); } nseLib.initiateQueueScheduler(); } /** * @function getRecordMapping * @description Reads the record mapping from the Script Deployment. * * @param {string }type - Related mapping type from the CSV line * @returns {object} - Record mapping details */ let getRecordMapping = (type) => { let currentScript = runtime.getCurrentScript(); let mappingData = JSON.parse(currentScript.getParameter({ name: 'custscript_nse_mr_csv_import_map' })); return mappingData[type]; } /** * @function getLockedPeriods * @description Queries all open periods and for each open period retrieves locked tasks per subsidiary including the next open posting period. * * @returns {object} - Details of the locked accounting periods */ let getLockedPeriods = () => { let openAccountingPeriods = {}; let accountingPeriodSearch = search.create({ type: search.Type.ACCOUNTING_PERIOD, filters: [ ['closed', search.Operator.IS, false], 'AND', ['isadjust', search.Operator.IS, false], 'AND', ['isinactive', search.Operator.IS, false], 'AND', ['isquarter', search.Operator.IS, false], 'AND', ['isyear', search.Operator.IS, false], 'AND', ['startdate', search.Operator.ONORBEFORE, 'today'] ], columns: ['periodname', 'startdate', 'enddate'] }); accountingPeriodSearch.run().each((result) => { if (openAccountingPeriods[result.id] === undefined) openAccountingPeriods[result.id] = { periodId: result.id, periodName: result.getValue({name: 'periodname'}), startDate: result.getValue({name: 'startdate'}), endDate: result.getValue({name: 'enddate'}) }; return true; }); let lockedAccountingPeriods = {}; for (let o in openAccountingPeriods) { let taskItemStatusSearch = search.create({ type: 'taskitemstatus', filters: [ ['period', 'abs', o], 'AND', ['itemtype', 'anyof', ['PCP_LOCK_AR', 'PCP_LOCK_AP', 'PCP_LOCK_ALL']], 'AND', ['complete', 'is', true] ], columns: ['period', 'subsidiary', 'itemtype'] }); taskItemStatusSearch.run().each((result) => { let periodId = result.getValue({name: 'period'}); let subsidiaryId = result.getValue({name: 'subsidiary'}); let lockedItem = result.getValue({name: 'itemtype'}); if (lockedAccountingPeriods[periodId] === undefined) { lockedAccountingPeriods[periodId] = { details: openAccountingPeriods[o], nextPeriod: getNextPeriodDetails(format.parse({ value: openAccountingPeriods[o].endDate, type: format.Type.DATE })) }; } if (lockedAccountingPeriods[periodId][subsidiaryId] === undefined) lockedAccountingPeriods[periodId][subsidiaryId] = {}; lockedAccountingPeriods[periodId][subsidiaryId][lockedItem] = true; return true; }); } return lockedAccountingPeriods; } /** * @function setBodyFields * @description Sets record body field values. * * @param {object} recObj - Details of the record to be used * @param {object} nsRec - NetSuite record that is being created * @param {object} recOpt - Options for record processing * @param {object} recChecks - Record checks for creating warning messages * @returns null */ let setBodyFields = (recObj, nsRec, recOpt, recChecks) => { for (let bif in recOpt.bodyInitialFields) { if (!nseLib.isEmpty(recObj[recOpt.bodyInitialFields[bif]])) { if (recOpt.textValueFields.includes(recOpt.bodyInitialFields[bif])) { nsRec.setText({ fieldId: recOpt.bodyInitialFields[bif], text: recObj[recOpt.bodyInitialFields[bif]] }); } else { nsRec.setValue({ fieldId: recOpt.bodyInitialFields[bif], value: recObj[recOpt.bodyInitialFields[bif]] }); } } } for (let ro in recObj) { if (ro !== 'type' && !recOpt.bodyInitialFields.includes(ro)) { if (recOpt.textValueFields.includes(ro)) { nsRec.setText({ fieldId: ro, text: recObj[ro] }); } else { nsRec.setValue({ fieldId: ro, value: recOpt.dateValueFields.includes(ro) ? format.parse({ value: recObj[ro], type: format.Type.DATE }) : recObj[ro] }); } } } } /** * @function setLineFields * @description Creates record lines and sets line field values. * * @param {object} recObj - Details of the record to be used * @param {object} nsRec - NetSuite record that is being created * @param {object} recOpt - Options for record processing * @param {object} recChecks - Record checks for creating warning messages * @returns null */ let setLineFields = (recObj, nsRec, recOpt, recChecks) => { for (let l in recObj.lines) { if (!recOpt.applySublists.includes(recObj.lines[l].sublistId)) { nsRec.selectNewLine({ sublistId: recObj.lines[l].sublistId }); for (let lif in recOpt.lineInitialFields) { if (!nseLib.isEmpty(recObj.lines[l][recOpt.lineInitialFields[lif]])) { if (recOpt.textValueFields.includes(recOpt.lineInitialFields[lif])) { nsRec.setCurrentSublistText({ sublistId: recObj.lines[l].sublistId, fieldId: recOpt.lineInitialFields[lif], text: recObj.lines[l][recOpt.lineInitialFields[lif]] }); } else { nsRec.setCurrentSublistValue({ sublistId: recObj.lines[l].sublistId, fieldId: recOpt.lineInitialFields[lif], value: recObj.lines[l][recOpt.lineInitialFields[lif]] }); } } } for (let lo in recObj.lines[l]) { if (lo !== 'sublistId' && !recOpt.lineInitialFields.includes(lo)) { if (recOpt.textValueFields.includes(lo)) { nsRec.setCurrentSublistText({ sublistId: recObj.lines[l].sublistId, fieldId: lo, text: recObj.lines[l][lo] }); } else { nsRec.setCurrentSublistValue({ sublistId: recObj.lines[l].sublistId, fieldId: lo, value: recOpt.dateValueFields.includes(lo) ? format.parse({ value: recObj.lines[l][lo], type: format.Type.DATE }) : recObj.lines[l][lo] }); } } } nsRec.commitLine({ sublistId: recObj.lines[l].sublistId }); } else { let lineId = -1; if (!nseLib.isEmpty(recObj.lines[l].internalid)) lineId = nsRec.findSublistLineWithValue({ sublistId: recObj.lines[l].sublistId, fieldId: 'internalid', value: recObj.lines[l].internalid }); else lineId = nsRec.findSublistLineWithValue({ sublistId: recObj.lines[l].sublistId, fieldId: 'refnum', value: recObj.lines[l].tranid }); if (lineId !== -1 && recObj.lines[l].amount > 0) { recChecks.transactionApplied = true; nsRec.selectLine({ sublistId: recObj.lines[l].sublistId, line: lineId }); nsRec.setCurrentSublistValue({ sublistId: recObj.lines[l].sublistId, fieldId: 'amount', value: recObj.lines[l].amount }); nsRec.commitLine({ sublistId: recObj.lines[l].sublistId }); } } } } /** * @function setPostingPeriod * @description Creates record lines and sets line field values. * * @param {object} nsRec - NetSuite record object that is being created * @param {object} lockedPeriodCache - Locked accounting period details from cache * @returns null */ let setPostingPeriod = (nsRec, lockedPeriodCache) => { let currentPeriodName = nsRec.getText({ fieldId: 'postingperiod' }); let nsRecordSubsidiaryName = nsRec.getText({ fieldId: 'subsidiary' }); if (!nseLib.isEmpty(currentPeriodName)) { let lockedPeriods = JSON.parse(lockedPeriodCache.get({ key: CACHE_DETAILS.periodKey, loader: getLockedPeriods() })); let newPeriodId = -1; while (true) { if (!nseLib.isEmpty(lockedPeriods) && !nseLib.isEmpty(lockedPeriods[currentPeriodName]) && !nseLib.isEmpty(lockedPeriods[currentPeriodName][nsRecordSubsidiaryName])) { if (lockedPeriods[currentPeriodName][nsRecordSubsidiaryName]['Lock All']) { newPeriodId = lockedPeriods[currentPeriodName].nextPeriod.periodId; currentPeriodName = lockedPeriods[currentPeriodName].nextPeriod.periodName; } else break; } else break; } if (newPeriodId !== -1) { nsRec.setValue({ fieldId: 'postingperiod', value: newPeriodId }); } } } /** * @function getNextPeriodDetails * @description Finds the next open posting period based on a given date. * * @param {date} afterDate - Date reference for the search * @returns {object} - Details of the accounting period */ let getNextPeriodDetails = (afterDate) => { let nextPeriodDetails = {}; let periodStartDate = format.format({ value: new Date(afterDate.getTime() + 86400000), type: format.Type.DATE }); let accountingPeriodSearch = search.create({ type: search.Type.ACCOUNTING_PERIOD, filters: [ ['closed', 'is', false], 'AND', ['isadjust', 'is', false], 'AND', ['isinactive', 'is', false], 'AND', ['isquarter', 'is', false], 'AND', ['isyear', 'is', false], 'AND', ['startdate', 'on', periodStartDate] ], columns: ['periodname'] }); let nextPeriods = accountingPeriodSearch.run().getRange({ start: 0, end: 1 }); if (nextPeriods.length > 0) nextPeriodDetails = { periodId: nextPeriods[0].id, periodName: nextPeriods[0].getValue({ name: 'periodname' }) }; return nextPeriodDetails; } /** * @function getEmployeeCreatePermissions * @description Retrieves the record create permissions of the employee from assigned roles. * * @param {number} employeeId - Internal ID of the employee * @param {number} subsidiaryId - Internal ID of the subsidiary * @returns {object} - Details of the user permissions for the subsidiary */ let getEmployeeCreatePermissions = (employeeId, subsidiaryId) => { let permissions = []; let searchFilters = [ ['internalid', search.Operator.ANYOF, employeeId], 'AND', ['level', search.Operator.ANYOF, ['2', '3', '4']] ]; if (!nseLib.isEmpty(subsidiaryId)) { searchFilters.push('AND'); searchFilters.push(['role.subsidiaries', search.Operator.ANYOF, [subsidiaryId]]); } let employeeSearch = search.create({ type: search.Type.EMPLOYEE, filters: searchFilters, columns: ['permission'] }); employeeSearch.run().each(function (result) { permissions.push(result.getValue({ name: 'permission' })); return true; }); return permissions; } return { getInputData: getInputData, map: map, reduce: reduce, summarize: summarize }; });
true
/** * @NApiVersion 2.1 * @NScriptType MapReduceScript * @NModuleScope SameAccount * @NAmdConfig /SuiteScripts/CSV Import/csv_import_configuration.json * * @author Selcuk Dogru * _nse_mr_csv_import * * @description Based on the script parameters, processes the CSV file and notifies user about the outcome. */ define(['N/cache', 'N/currency', 'N/email', 'N/error', 'N/file', 'N/format', 'N/record', 'N/runtime', 'N/search', 'nseLib', 'papaparse'], (cache, currency, email, error, file, format, record, runtime, search, nseLib, Papa) => { const RESERVED_KEYS = ['recType', 'defaultValues', 'lineMapping', 'lineId']; const EMAIL_AUTHOR_ID = -5; const ERROR_FILE_NAME = 'csv_import_errors.csv'; const CACHE_DETAILS = { name: 'PI:KEY:9jnerlff23u8ed01np9g6ysbhsh0dvcsEND_PI', periodKey: 'PI:KEY:vqbpgud2ghvjgm1n5hdgjnn5818fzsf2END_PI', permissionKey: 'PI:KEY:ax5kh6jaqkcd2tiexxs8v6xjo8yv8a6bEND_PI' }; const SCRIPT_PARAMS = { fileId: 'custscript_nse_mr_csv_import_fileid', mapping: 'custscript_nse_mr_csv_import_map', options: 'custscript_nse_mr_csv_import_option', user: 'custscript_nse_mr_csv_import_user', subsidiary: 'custscript_nse_mr_csv_import_sub' }; /** * @function getInputData * @description Parses the CSV file and creates cache that stores employee permissions. * * @returns {array} - Parsed CSV file */ let getInputData = () => { let scriptParams = nseLib.getScriptParams(SCRIPT_PARAMS); let options = JSON.parse(scriptParams.options); let csvFile = file.load({ id: parseInt(scriptParams.fileId) }); let parsedData = Papa.parse(csvFile.getContents(), { header: true, delimiter: options.csvDelimiter, skipEmptyLines: 'greedy' }); let csvFileParseErrors = ''; for (let e in parsedData.errors) { csvFileParseErrors += parsedData.errors[e].row + ',' + parsedData.errors[e].message + '\n'; } if (!nseLib.isEmpty(csvFileParseErrors)) { throw error.create({ name: 'NSE_CSV_PRS_ERR', message: csvFileParseErrors, notifyOff: true }); } let lpCache = cache.getCache({ name: CACHE_DETAILS.name, scope: cache.Scope.PRIVATE }); lpCache.put({ key: CACHE_DETAILS.permissionKey, value: getEmployeeCreatePermissions(scriptParams.user, scriptParams.subsidiary) }); if (!options.postToLockedPeriod) { lpCache.put({ key: CACHE_DETAILS.periodKey, value: getLockedPeriods() }); } return parsedData.data; } /** * @function map * @description Matches the CSV line with the related record mapping. Prepares object to be processed as a NetSuite record. * * @param context * @returns null */ let map = (context) => { let lineData = JSON.parse(context.value); log.debug('lineData', lineData); let recordMapping = getRecordMapping(lineData.Type); log.debug('recordMapping', recordMapping); if (nseLib.isEmpty(recordMapping)) throw error.create({ name: 'NSE_CSV_IMP_NO_REC_MAP', message: 'No record mapping found for record type ' + lineData.Type, notifyOff: true }); let recordData = { type: recordMapping.recType }; for (let key in recordMapping) { if (!RESERVED_KEYS.includes(key)) { if (!nseLib.isEmpty(lineData[key])) recordData[recordMapping[key]] = lineData[key]; } else if (key === RESERVED_KEYS[2]) { recordData.lines = { sublistId: recordMapping[key].lineId }; for (let lineKey in recordMapping[key]) { if (!RESERVED_KEYS.includes(lineKey)) { if (!nseLib.isEmpty(lineData[lineKey])) recordData.lines[recordMapping[key][lineKey]] = lineData[lineKey]; } else if (lineKey === RESERVED_KEYS[1]) { for (let defaultLineKey in recordMapping[key][lineKey]) { if (!nseLib.isEmpty(recordMapping[key][lineKey][defaultLineKey])) recordData.lines[defaultLineKey] = recordMapping[key][lineKey][defaultLineKey]; } } } } else if (key === RESERVED_KEYS[1]) { for (let defaultKey in recordMapping[key]) { if (!nseLib.isEmpty(recordMapping[key][defaultKey])) recordData[defaultKey] = recordMapping[key][defaultKey]; } } } log.debug('recordData', recordData); context.write(recordData.externalid, recordData); } /** * @function reduce * @description Processes the JSON record data and creates NetSuite record based on the options. User triggered the process must have permission to create the record. * * @param context * @returns null */ let reduce = (context) => { let scriptParams = nseLib.getScriptParams(SCRIPT_PARAMS); let recordChecks = { checkApplySublist: false, transactionApplied: false }; let options = JSON.parse(scriptParams.options); let recordObject = { lines: [] }; for (let v in context.values) { let recordData = JSON.parse(context.values[v]); for (let key in recordData) { if (key !== 'lines') { recordObject[key] = recordData[key]; } } if (!nseLib.isEmpty(recordData.lines)) recordObject.lines.push(recordData.lines); } let lpCache = cache.getCache({ name: CACHE_DETAILS.name, scope: cache.Scope.PRIVATE }); let userCreatePermissions = JSON.parse(lpCache.get({ key: CACHE_DETAILS.permissionKey, loader: getEmployeeCreatePermissions(scriptParams.user, scriptParams.subsidiary) })); if (!userCreatePermissions.includes(options.permissionMap[recordObject.type])) throw error.create({ name: 'NSE_REC_PERM_ERR', message: 'Your assigned roles do not allow you to create this type of transactions.', notifyOff: true }); if ([record.Type.CUSTOMER_PAYMENT, record.Type.VENDOR_PAYMENT].includes(recordObject.type)) recordChecks.checkApplySublist = true; let nsRecord = record.create({ type: record.Type[recordObject.type], isDynamic: true }); setBodyFields(recordObject, nsRecord, options, recordChecks); setLineFields(recordObject, nsRecord, options, recordChecks); let subsidiaryId = parseInt(scriptParams.subsidiary); let nsRecordSubsidiaryId; let nsRecordSubsidiary = nsRecord.getValue({fieldId: 'subsidiary'}); if (util.isArray(nsRecordSubsidiary)) { if (nsRecordSubsidiary.length === 1) nsRecordSubsidiaryId = parseInt(nsRecordSubsidiary[0]); } else { nsRecordSubsidiaryId = parseInt(nsRecordSubsidiary); } if (!nseLib.isEmpty(subsidiaryId) && nsRecordSubsidiaryId !== subsidiaryId) { throw error.create({ name: 'NSE_WRG_SUB_ERR', message: 'Script was not initiated for the subsidiary of this record.', notifyOff: true }); } if (!options.setExternalId) { nsRecord.setValue({ fieldId: 'externalid', value: null }); } if (!options.postToLockedPeriod) { setPostingPeriod(nsRecord, lpCache); } let recordId = nsRecord.save(); if (recordChecks.checkApplySublist && !recordChecks.transactionApplied) { context.write({ key: recordObject.externalid, value: 'Payment record ' + recordId + 'created but not applied to any transaction.' }); } else { context.write({ key: recordObject.externalid, value: 'SUCCESS' }); } } /** * @function summarize * @description Removes cached data. Prepares and sends informational email to the user triggered the process. Updates related CSV Import Queue record. * * @param summary * @returns null */ let summarize = (summary) => { let scriptParams = nseLib.getScriptParams(SCRIPT_PARAMS); let userId = scriptParams.user; let importQueueRecordDetails = nseLib.getImportQueueRecords({fileId: scriptParams.fileId})[scriptParams.subsidiary][0]; let lpCache = cache.getCache({ name: CACHE_DETAILS.name, scope: cache.Scope.PRIVATE }); lpCache.remove({ key: CACHE_DETAILS.periodKey }); lpCache.remove({ key: CACHE_DETAILS.permissionKey }); let recordCounts = { success: 0, warning: 0, error: 0, mapError: 0 }; if (!nseLib.isEmpty(summary.inputSummary.error)) { record.submitFields({ type: 'customrecord_nse_csv_import_queue', id: importQueueRecordDetails.internalId, values: { custrecord_nse_csv_import_status: 4 } }); let inputErrorDetails = JSON.parse(summary.inputSummary.error); let inputErrorMessageDetails = {}; try { inputErrorMessageDetails = JSON.parse(inputErrorDetails.message); } catch (err) { } email.send({ author: EMAIL_AUTHOR_ID, recipients: [userId], subject: 'Error While Processing Uploaded CSV File', body: 'Hello,\n\n' + 'An error occurred while parsing the uploaded CSV file (File ID: ' + scriptParams.fileId + '). ' + 'Please find the details below.\n' + 'You will need to upload the related file again after correcting.\n\n' + 'Error Code: ' + inputErrorDetails.name + '\n' + 'Error Message: ' + inputErrorMessageDetails.message + '\n\n' + 'Regards,\n' + 'NetSuite Service Desk' }); return null; } let errorDetails = ''; summary.mapSummary.errors.iterator().each((key, error) => { recordCounts.mapError++; let errorObject = JSON.parse(error); errorDetails += 'ERROR,' + key + ',' + errorObject.name + ',' + errorObject.message + '\n'; return true; }); summary.reduceSummary.errors.iterator().each((key, error) => { recordCounts.error++; let errorObject = JSON.parse(error); try { let messageDetails = JSON.parse(errorObject.message); errorDetails += 'ERROR,' + key + ',' + messageDetails.name + ',' + messageDetails.message + '\n'; } catch (e) { errorDetails += 'ERROR,' + key + ',' + errorObject.name + ',' + errorObject.message + '\n'; } return true; }); summary.output.iterator().each((key, value) => { if (value === 'SUCCESS') recordCounts.success++; else { recordCounts.warning++ errorDetails += 'WARNING,' + key + ',,' + value + '\n'; } return true; }); record.submitFields({ type: 'customrecord_nse_csv_import_queue', id: importQueueRecordDetails.internalId, values: { custrecord_nse_csv_import_status: 3, custrecord_nse_csv_import_success_count: recordCounts.success, custrecord_nse_csv_import_warning_count: recordCounts.warning, custrecord_nse_csv_import_error_count: recordCounts.error, custrecord_nse_csv_import_map_errors: recordCounts.mapError } }); if (!nseLib.isEmpty(errorDetails)) { errorDetails = 'Type,External ID,Code,Details\n' + errorDetails; email.send({ author: EMAIL_AUTHOR_ID, recipients: [userId], subject: 'CSV File Processing Completed with Errors', body: 'Hello,\n\n' + 'An error occurred while processing the CSV file (File ID: ' + scriptParams.fileId + ').' + 'Please find the details for the failed lines attached.\n' + 'After correcting the CSV file, please upload only the failed lines for processing.\n\n' + 'Regards,\n' + 'NetSuite Service Desk', attachments: [file.create({ name: ERROR_FILE_NAME, fileType: file.Type.CSV, contents: errorDetails })] }); } else { email.send({ author: EMAIL_AUTHOR_ID, recipients: [userId], subject: 'CSV File Processing Completed Successfully', body: 'Hello,\n\n' + 'The CSV file (File ID: ' + scriptParams.fileId + ') was successfully imported. ' + 'If you encounter any inconsistency, please contact us.\n\n' + 'Regards,\n' + 'NetSuite Service Desk' }); } nseLib.initiateQueueScheduler(); } /** * @function getRecordMapping * @description Reads the record mapping from the Script Deployment. * * @param {string }type - Related mapping type from the CSV line * @returns {object} - Record mapping details */ let getRecordMapping = (type) => { let currentScript = runtime.getCurrentScript(); let mappingData = JSON.parse(currentScript.getParameter({ name: 'custscript_nse_mr_csv_import_map' })); return mappingData[type]; } /** * @function getLockedPeriods * @description Queries all open periods and for each open period retrieves locked tasks per subsidiary including the next open posting period. * * @returns {object} - Details of the locked accounting periods */ let getLockedPeriods = () => { let openAccountingPeriods = {}; let accountingPeriodSearch = search.create({ type: search.Type.ACCOUNTING_PERIOD, filters: [ ['closed', search.Operator.IS, false], 'AND', ['isadjust', search.Operator.IS, false], 'AND', ['isinactive', search.Operator.IS, false], 'AND', ['isquarter', search.Operator.IS, false], 'AND', ['isyear', search.Operator.IS, false], 'AND', ['startdate', search.Operator.ONORBEFORE, 'today'] ], columns: ['periodname', 'startdate', 'enddate'] }); accountingPeriodSearch.run().each((result) => { if (openAccountingPeriods[result.id] === undefined) openAccountingPeriods[result.id] = { periodId: result.id, periodName: result.getValue({name: 'periodname'}), startDate: result.getValue({name: 'startdate'}), endDate: result.getValue({name: 'enddate'}) }; return true; }); let lockedAccountingPeriods = {}; for (let o in openAccountingPeriods) { let taskItemStatusSearch = search.create({ type: 'taskitemstatus', filters: [ ['period', 'abs', o], 'AND', ['itemtype', 'anyof', ['PCP_LOCK_AR', 'PCP_LOCK_AP', 'PCP_LOCK_ALL']], 'AND', ['complete', 'is', true] ], columns: ['period', 'subsidiary', 'itemtype'] }); taskItemStatusSearch.run().each((result) => { let periodId = result.getValue({name: 'period'}); let subsidiaryId = result.getValue({name: 'subsidiary'}); let lockedItem = result.getValue({name: 'itemtype'}); if (lockedAccountingPeriods[periodId] === undefined) { lockedAccountingPeriods[periodId] = { details: openAccountingPeriods[o], nextPeriod: getNextPeriodDetails(format.parse({ value: openAccountingPeriods[o].endDate, type: format.Type.DATE })) }; } if (lockedAccountingPeriods[periodId][subsidiaryId] === undefined) lockedAccountingPeriods[periodId][subsidiaryId] = {}; lockedAccountingPeriods[periodId][subsidiaryId][lockedItem] = true; return true; }); } return lockedAccountingPeriods; } /** * @function setBodyFields * @description Sets record body field values. * * @param {object} recObj - Details of the record to be used * @param {object} nsRec - NetSuite record that is being created * @param {object} recOpt - Options for record processing * @param {object} recChecks - Record checks for creating warning messages * @returns null */ let setBodyFields = (recObj, nsRec, recOpt, recChecks) => { for (let bif in recOpt.bodyInitialFields) { if (!nseLib.isEmpty(recObj[recOpt.bodyInitialFields[bif]])) { if (recOpt.textValueFields.includes(recOpt.bodyInitialFields[bif])) { nsRec.setText({ fieldId: recOpt.bodyInitialFields[bif], text: recObj[recOpt.bodyInitialFields[bif]] }); } else { nsRec.setValue({ fieldId: recOpt.bodyInitialFields[bif], value: recObj[recOpt.bodyInitialFields[bif]] }); } } } for (let ro in recObj) { if (ro !== 'type' && !recOpt.bodyInitialFields.includes(ro)) { if (recOpt.textValueFields.includes(ro)) { nsRec.setText({ fieldId: ro, text: recObj[ro] }); } else { nsRec.setValue({ fieldId: ro, value: recOpt.dateValueFields.includes(ro) ? format.parse({ value: recObj[ro], type: format.Type.DATE }) : recObj[ro] }); } } } } /** * @function setLineFields * @description Creates record lines and sets line field values. * * @param {object} recObj - Details of the record to be used * @param {object} nsRec - NetSuite record that is being created * @param {object} recOpt - Options for record processing * @param {object} recChecks - Record checks for creating warning messages * @returns null */ let setLineFields = (recObj, nsRec, recOpt, recChecks) => { for (let l in recObj.lines) { if (!recOpt.applySublists.includes(recObj.lines[l].sublistId)) { nsRec.selectNewLine({ sublistId: recObj.lines[l].sublistId }); for (let lif in recOpt.lineInitialFields) { if (!nseLib.isEmpty(recObj.lines[l][recOpt.lineInitialFields[lif]])) { if (recOpt.textValueFields.includes(recOpt.lineInitialFields[lif])) { nsRec.setCurrentSublistText({ sublistId: recObj.lines[l].sublistId, fieldId: recOpt.lineInitialFields[lif], text: recObj.lines[l][recOpt.lineInitialFields[lif]] }); } else { nsRec.setCurrentSublistValue({ sublistId: recObj.lines[l].sublistId, fieldId: recOpt.lineInitialFields[lif], value: recObj.lines[l][recOpt.lineInitialFields[lif]] }); } } } for (let lo in recObj.lines[l]) { if (lo !== 'sublistId' && !recOpt.lineInitialFields.includes(lo)) { if (recOpt.textValueFields.includes(lo)) { nsRec.setCurrentSublistText({ sublistId: recObj.lines[l].sublistId, fieldId: lo, text: recObj.lines[l][lo] }); } else { nsRec.setCurrentSublistValue({ sublistId: recObj.lines[l].sublistId, fieldId: lo, value: recOpt.dateValueFields.includes(lo) ? format.parse({ value: recObj.lines[l][lo], type: format.Type.DATE }) : recObj.lines[l][lo] }); } } } nsRec.commitLine({ sublistId: recObj.lines[l].sublistId }); } else { let lineId = -1; if (!nseLib.isEmpty(recObj.lines[l].internalid)) lineId = nsRec.findSublistLineWithValue({ sublistId: recObj.lines[l].sublistId, fieldId: 'internalid', value: recObj.lines[l].internalid }); else lineId = nsRec.findSublistLineWithValue({ sublistId: recObj.lines[l].sublistId, fieldId: 'refnum', value: recObj.lines[l].tranid }); if (lineId !== -1 && recObj.lines[l].amount > 0) { recChecks.transactionApplied = true; nsRec.selectLine({ sublistId: recObj.lines[l].sublistId, line: lineId }); nsRec.setCurrentSublistValue({ sublistId: recObj.lines[l].sublistId, fieldId: 'amount', value: recObj.lines[l].amount }); nsRec.commitLine({ sublistId: recObj.lines[l].sublistId }); } } } } /** * @function setPostingPeriod * @description Creates record lines and sets line field values. * * @param {object} nsRec - NetSuite record object that is being created * @param {object} lockedPeriodCache - Locked accounting period details from cache * @returns null */ let setPostingPeriod = (nsRec, lockedPeriodCache) => { let currentPeriodName = nsRec.getText({ fieldId: 'postingperiod' }); let nsRecordSubsidiaryName = nsRec.getText({ fieldId: 'subsidiary' }); if (!nseLib.isEmpty(currentPeriodName)) { let lockedPeriods = JSON.parse(lockedPeriodCache.get({ key: CACHE_DETAILS.periodKey, loader: getLockedPeriods() })); let newPeriodId = -1; while (true) { if (!nseLib.isEmpty(lockedPeriods) && !nseLib.isEmpty(lockedPeriods[currentPeriodName]) && !nseLib.isEmpty(lockedPeriods[currentPeriodName][nsRecordSubsidiaryName])) { if (lockedPeriods[currentPeriodName][nsRecordSubsidiaryName]['Lock All']) { newPeriodId = lockedPeriods[currentPeriodName].nextPeriod.periodId; currentPeriodName = lockedPeriods[currentPeriodName].nextPeriod.periodName; } else break; } else break; } if (newPeriodId !== -1) { nsRec.setValue({ fieldId: 'postingperiod', value: newPeriodId }); } } } /** * @function getNextPeriodDetails * @description Finds the next open posting period based on a given date. * * @param {date} afterDate - Date reference for the search * @returns {object} - Details of the accounting period */ let getNextPeriodDetails = (afterDate) => { let nextPeriodDetails = {}; let periodStartDate = format.format({ value: new Date(afterDate.getTime() + 86400000), type: format.Type.DATE }); let accountingPeriodSearch = search.create({ type: search.Type.ACCOUNTING_PERIOD, filters: [ ['closed', 'is', false], 'AND', ['isadjust', 'is', false], 'AND', ['isinactive', 'is', false], 'AND', ['isquarter', 'is', false], 'AND', ['isyear', 'is', false], 'AND', ['startdate', 'on', periodStartDate] ], columns: ['periodname'] }); let nextPeriods = accountingPeriodSearch.run().getRange({ start: 0, end: 1 }); if (nextPeriods.length > 0) nextPeriodDetails = { periodId: nextPeriods[0].id, periodName: nextPeriods[0].getValue({ name: 'periodname' }) }; return nextPeriodDetails; } /** * @function getEmployeeCreatePermissions * @description Retrieves the record create permissions of the employee from assigned roles. * * @param {number} employeeId - Internal ID of the employee * @param {number} subsidiaryId - Internal ID of the subsidiary * @returns {object} - Details of the user permissions for the subsidiary */ let getEmployeeCreatePermissions = (employeeId, subsidiaryId) => { let permissions = []; let searchFilters = [ ['internalid', search.Operator.ANYOF, employeeId], 'AND', ['level', search.Operator.ANYOF, ['2', '3', '4']] ]; if (!nseLib.isEmpty(subsidiaryId)) { searchFilters.push('AND'); searchFilters.push(['role.subsidiaries', search.Operator.ANYOF, [subsidiaryId]]); } let employeeSearch = search.create({ type: search.Type.EMPLOYEE, filters: searchFilters, columns: ['permission'] }); employeeSearch.run().each(function (result) { permissions.push(result.getValue({ name: 'permission' })); return true; }); return permissions; } return { getInputData: getInputData, map: map, reduce: reduce, summarize: summarize }; });
/** * @NApiVersion 2.0 * @NScriptType Suitelet * * Module Description * * NSVersion Date Author * 2.00 2020-10-22 09:33:08 Anesu * * Description: Automation of Debt Collection Process * * @Last Modified by: Anesu * @Last Modified time: 2020-10-22 16:49:26 * */ define(['N/ui/serverWidget', 'N/email', 'N/runtime', 'N/search', 'N/record', 'N/http', 'N/log', 'N/redirect', 'N/task', 'N/format'], function(ui, email, runtime, search, record, http, log, redirect, task, format) { var zee = 0; var role = 0; var baseURL = 'https://1048144.app.netsuite.com'; if (runtime.EnvType == "SANDBOX") { baseURL = 'https://1048144-sb3.app.netsuite.com'; } role = runtime.getCurrentUser().role; if (role == 1000) { zee = runtime.getCurrentUser().id; } else if (role == 3) { //Administrator zee = 6; //test } else if (role == 1032) { // System Support zee = 425904; //test-AR } function onRequest(context) { if (context.request.method === 'GET') { var params = context.request.parameters; var is_params = false; var invoice_id = params.invid; var date; var period; var record_id; var viewed; if (!isNullorEmpty(invoice_id)) { is_params = true; invoice_id = params.invid; date = params.date; period = params.period; record_id = params.recordid; viewed = params.viewed; cust_id = params.custid; multi_viewed = params.multiviewed; } log.debug({ title: 'invoice_id', details: invoice_id }) log.debug({ title: 'date', details: date }) log.debug({ title: 'period', details: period }) log.debug({ title: 'record_id', details: record_id }); log.debug({ title: 'viewed', details: viewed }); log.debug({ title: 'Customer ID', details: cust_id }) var form = ui.createForm({ title: 'Debt Collection - Snooze' }); // Load jQuery var inlineHtml = '<script src="https://code.jquery.com/jquery-1.12.4.min.js" integrity="sha384-nvAa0+6Qg9clwYCGGPpDQLVpLNn0fRaROjHqs13t4Ggj3Ez50XnGQqc/r8MhnRDZ" crossorigin="anonymous"></script>'; // Load Tooltip inlineHtml += '<script src="https://unpkg.com/@popperjs/core@2"></script>'; // Load Bootstrap inlineHtml += '<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/3.4.1/css/bootstrap.min.css" integrity="sha384-HSMxcRTRxnN+Bdg0JdbxYKrThecOKuH5zCYotlSAcp1+c8xmyTe9GYg1l9a69psu" crossorigin="anonymous">'; inlineHtml += '<script src="https://stackpath.bootstrapcdn.com/bootstrap/3.4.1/js/bootstrap.min.js" integrity="sha384-aJ21OjlMXNL5UyIl/XNwTMqvzeRMZH2w8c5cRVpzpU8Y5bApTppSuUkhZXN0VxHd" crossorigin="anonymous"></script>'; // Load DataTables inlineHtml += '<link rel="stylesheet" type="text/css" href="//cdn.datatables.net/1.10.21/css/jquery.dataTables.min.css">'; inlineHtml += '<script type="text/javascript" charset="utf8" src="//cdn.datatables.net/1.10.21/js/jquery.dataTables.min.js"></script>'; // Load Bootstrap-Select inlineHtml += '<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap-select@1.13.14/dist/css/bootstrap-select.min.css">'; inlineHtml += '<script src="https://cdn.jsdelivr.net/npm/bootstrap-select@1.13.14/dist/js/bootstrap-select.min.js"></script>'; // Load Netsuite stylesheet and script inlineHtml += '<link rel="stylesheet" href="https://1048144.app.netsuite.com/core/media/media.nl?id=2060796&c=1048144&h=9ee6accfd476c9cae718&_xt=.css"/>'; inlineHtml += '<script src="https://1048144.app.netsuite.com/core/media/media.nl?id=2060797&c=1048144&h=ef2cda20731d146b5e98&_xt=.js"></script>'; inlineHtml += '<link type="text/css" rel="stylesheet" href="https://1048144.app.netsuite.com/core/media/media.nl?id=2090583&c=1048144&h=a0ef6ac4e28f91203dfe&_xt=.css">'; inlineHtml += '<style>.mandatory{color:red;}</style>'; if (is_params == true) { if (isNullorEmpty(period)) { inlineHtml += '<div><h4 style="text-align: center">Invoice has been set as viewed!</h4></div><br>'; } else { inlineHtml += '<div><h4 style="text-align: center">Invoice has successfully been snoozed for a period of ' + period + '!</h4></div><br>'; } } else { inlineHtml += '<div><h4 style="text-align: center">Invalid Parameters. Please Go Back to Debt Collections Page and Try Again</h4></div>' } if (!isNullorEmpty(invoice_id) && !isNullorEmpty(record_id) && !isNullorEmpty(date)) { inlineHtml += invoiceDetailsSection(invoice_id, period, record_id, date); } if (!isNullorEmpty(period)) { saveSnooze(invoice_id, period, record_id, date); } if (!isNullorEmpty(viewed)) { saveViewed(invoice_id, period, viewed, date) } if (!isNullorEmpty(multi_viewed)) { multiViewed(invoice_id, period, multi_viewed, date, cust_id); period = 'Multi Snooze 1 Week' } form.addField({ id: 'preview_table', label: 'inlinehtml', type: 'inlinehtml' }).updateLayoutType({ layoutType: ui.FieldLayoutType.STARTROW }).defaultValue = inlineHtml; form.addButton({ id: 'close', label: 'Close' }) form.addField({ id: 'custpage_debt_coll_invoice_id', type: ui.FieldType.TEXT, label: 'invoice_id' }).updateDisplayType({ displayType: ui.FieldDisplayType.HIDDEN }).defaultValue = invoice_id; form.addField({ id: 'custpage_debt_coll_date', type: ui.FieldType.TEXT, label: 'date' }).updateDisplayType({ displayType: ui.FieldDisplayType.HIDDEN }).defaultValue = date; form.addField({ id: 'custpage_debt_coll_period', type: ui.FieldType.TEXT, label: 'period' }).updateDisplayType({ displayType: ui.FieldDisplayType.HIDDEN }).defaultValue = period; form.addField({ id: 'custpage_debt_coll_record_id', type: ui.FieldType.TEXT, label: 'recordid' }).updateDisplayType({ displayType: ui.FieldDisplayType.HIDDEN }).defaultValue = record_id; form.clientScriptFileId = 4686514; context.response.writePage(form); } else { // } } function invoiceDetailsSection(invoice_id, period, record_id, date) { var inlineQty = ''; inlineQty = '<div class="form-group container invoice_section">'; inlineQty += '<div class="row">'; inlineQty += '<div class="col-xs-12 heading1"><h4><span class="label label-default col-xs-12">SNOOZED INVOICE DETAILS</span></h4></div>'; inlineQty += '</div>'; inlineQty += '</div>'; inlineQty += '<div class="form-group container invoice_id_section">'; inlineQty += '<div class="row">'; inlineQty += '<div class="col-xs-6 invoice_id"><div class="input-group"><span class="input-group-addon" id="invoice_id_text">Invoice ID</span><input id="invoice_id" class="form-control invoice_id" value="' + invoice_id + '" data-oldvalue="' + invoice_id + '"/></div></div>'; inlineQty += '<div class="col-xs-6 record_id"><div class="input-group"><span class="input-group-addon" id="record_id_text">Record ID</span><input id="record_id" class="form-control record_id" value="' + record_id + '" data-oldvalue="' + record_id + '"/></div></div>'; inlineQty += '</div></div>'; inlineQty += '</div>'; inlineQty += '</div>'; inlineQty += '<div class="form-group container _section">'; inlineQty += '<div class="row">'; inlineQty += '<div class="col-xs-6 period"><div class="input-group"><span class="input-group-addon" id="period_text">Period Duration</span><input id="period" class="form-control period" value="' + period + '" data-oldvalue="' + period + '"/></div></div>'; inlineQty += '<div class="col-xs-6 date"><div class="input-group"><span class="input-group-addon" id="date_text">Invoice Date</span><input id="date" class="form-control date" value="' + date + '" data-oldvalue="' + date + '"/></div></div>'; inlineQty += '</div></div>'; inlineQty += '</div>'; inlineQty += '</div>'; inlineQty += '</select></div></div>'; inlineQty += '</div>'; inlineQty += '</div>'; return inlineQty; } function saveSnooze(invoice_id, period, record_id) { var today = new Date(); var today_year = today.getFullYear(); var today_month = today.getMonth(); var today_day = today.getDate() + 1; log.debug({ title: 'today', details: today }) log.debug({ title: 'today_year', details: today_year }) log.debug({ title: 'today_month', details: today_month }) log.debug({ title: 'today_day', details: today_day }); var today_in_day = new Date(Date.UTC(parseInt(today_year), parseInt(today_month), parseInt(today_day) + 1)); today_in_day.toLocaleString('en-AU', { timeZone: 'Australia/Sydney' }); today_in_day = today_in_day.toISOString().split('T')[0]; // Split Date String to get the date. today_in_day = dateISOToNetsuite(today_in_day); // Convert from 2021-01-28 to 28/1/2021 today_in_day = format.parse({ value: today_in_day, type: format.Type.DATE }); // Date Object var today_in_2day = new Date(Date.UTC(today_year, today_month, today_day + 2)); today_in_2day.toLocaleString('en-AU', { timeZone: 'Australia/Sydney' }) today_in_2day = today_in_2day.toISOString().split('T')[0]; today_in_2day = dateISOToNetsuite(today_in_2day); today_in_2day = format.parse({ value: today_in_2day, type: format.Type.DATE }); // Date Object var today_in_week = new Date(Date.UTC(today_year, today_month, today_day + 7)); today_in_week.toLocaleString('en-AU', { timeZone: 'Australia/Sydney' }) today_in_week = today_in_week.toISOString().split('T')[0]; today_in_week = dateISOToNetsuite(today_in_week); today_in_week = format.parse({ value: today_in_week, type: format.Type.DATE }); // Date Object var today_in_2week = new Date(Date.UTC(today_year, today_month, today_day + 14)); today_in_2week.toLocaleString('en-AU', { timeZone: 'Australia/Sydney' }) today_in_2week = today_in_2week.toISOString().split('T')[0]; today_in_2week = dateISOToNetsuite(today_in_2week); today_in_2week = format.parse({ value: today_in_2week, type: format.Type.DATE }); // Date Object var one_year = new Date(Date.UTC(today_year + 1, today_month, today_day)); one_year.toLocaleString('en-AU', { timeZone: 'Australia/Sydney' }) one_year = one_year.toISOString().split('T')[0]; one_year = dateISOToNetsuite(one_year); one_year = format.parse({ value: one_year, type: format.Type.DATE }); // Date Object switch (period) { case '1day': log.debug({ title: '1 Day', details: '1 Day' }); var snoozeRecord = record.load({ type: 'invoice', id: invoice_id }); var date = snoozeRecord.getValue({ fieldId: 'custbody_invoice_snooze_date' }); log.debug({ title: 'Date on Invoice Record', details: today_in_day }); snoozeRecord.setValue({ fieldId: 'custbody_invoice_snooze_date', value: today_in_day }); snoozeRecord.save(); var snoozeDelete = record.delete({ type: 'customrecord_debt_coll_inv', id: record_id }); log.debug({ title: 'Delete initiated - Record ID: ' + record_id, details: 'Delete initiated - Record ID: ' + record_id }); break; case '2day': log.debug({ title: '2 Day', details: '2 Day' }); var snoozeRecord = record.load({ type: 'invoice', id: invoice_id }); var date = snoozeRecord.getValue({ fieldId: 'custbody_invoice_snooze_date' }); log.debug({ title: 'Date for Snooze ' + date, details: 'Date for Snooze ' + date }); snoozeRecord.setValue({ fieldId: 'custbody_invoice_snooze_date', value: today_in_2day }); snoozeRecord.save(); var snoozeDelete = record.delete({ type: 'customrecord_debt_coll_inv', id: record_id }); log.debug({ title: 'Delete initiated - Record ID: ' + record_id, details: 'Delete initiated - Record ID: ' + record_id }); break; case '1week': log.debug({ title: '1 Week', details: '1 Week' }); var snoozeRecord = record.load({ type: 'invoice', id: invoice_id }); var date = snoozeRecord.getValue({ fieldId: 'custbody_invoice_snooze_date' }); log.debug({ title: 'Date for Snooze ' + date, details: 'Date for Snooze ' + date, }) snoozeRecord.setValue({ fieldId: 'custbody_invoice_snooze_date', value: today_in_week }); snoozeRecord.save(); var snoozeDelete = record.delete({ type: 'customrecord_debt_coll_inv', id: record_id }); log.debug({ title: 'Delete initiated - Record ID: ' + record_id, details: 'Delete initiated - Record ID: ' + record_id }); break; case '2week': log.debug({ title: '2 Week', details: '2 Week' }); var snoozeRecord = record.load({ type: 'invoice', id: invoice_id }); var date = snoozeRecord.getValue({ fieldId: 'custbody_invoice_snooze_date' }); log.debug({ title: 'Date for Snooze ' + date, details: 'Date for Snooze ' + date }) snoozeRecord.setValue({ fieldId: 'custbody_invoice_snooze_date', value: today_in_2week }); snoozeRecord.save(); var snoozeDelete = record.delete({ type: 'customrecord_debt_coll_inv', id: record_id }); log.debug({ title: 'Delete initiated - Record ID: ' + record_id, details: 'Delete initiated - Record ID: ' + record_id }); break; case 'permanent': log.debug({ title: 'Permanent', details: 'Permanent' }); var snoozeRecord = record.load({ type: 'invoice', id: invoice_id }); var date = snoozeRecord.getValue({ fieldId: 'custbody_invoice_snooze_date' }); log.debug({ title: 'Date for Snooze ' + date, details: 'Date for Snooze ' + date }) snoozeRecord.setValue({ fieldId: 'custbody_invoice_snooze_date', value: one_year }); snoozeRecord.save(); var snoozeDelete = record.delete({ type: 'customrecord_debt_coll_inv', id: record_id }); log.debug({ title: 'Delete initiated - Record ID: ' + record_id, details: 'Delete initiated - Record ID: ' + record_id }); default: log.debug({ title: "No Snooze Date Note Saved", details: period }); } return true; } function saveViewed(invoice_id, period, viewed) { // 1 Week Snooze var today = new Date(); var today_year = today.getFullYear(); var today_month = today.getMonth(); var today_day = today.getDate() + 1; var today_in_week = new Date(Date.UTC(today_year, today_month, today_day + 7)); today_in_week.toLocaleString('en-AU', { timeZone: 'Australia/Sydney' }) today_in_week = today_in_week.toISOString().split('T')[0]; today_in_week = dateISOToNetsuite(today_in_week); today_in_week = format.parse({ value: today_in_week, type: format.Type.DATE }); // Date Object var invoiceRecord = record.load({ type: 'invoice', id: invoice_id }); var new_date = invoiceRecord.setValue({ fieldId: 'custbody_invoice_snooze_date', value: today_in_week }); var custID = invoiceRecord.getValue({ fieldId: 'entity' }); var custRecord = record.load({ type: 'customer', id: custID }); var custStatusVal = custRecord.getValue({ fieldId: 'entitystatus' }); // Purple for All Customers with the same customer name // Purple for Invoice for 1 Week - DONE // Purple All Invoices under Customer - In Progress // Search of All Customers, Send to Yassine - DONE log.debug({ title: 'new_date record ID', details: new_date }) var viewed = invoiceRecord.getValue({ fieldId: 'custbody_invoice_viewed' }); log.debug({ title: 'viewed', details: viewed }); viewed = invoiceRecord.setValue({ fieldId: 'custbody_invoice_viewed', value: true }); invoiceRecord.save(); custRecord.setValue({ fieldId: 'entitystatus', value: custStatusVal }); custRecord.save(); return true; } function multiViewed(invoice_id, period, multi_viewed, date, cust_id) { log.debug({ title: 'Multiple Invoices Viewed', details: multi_viewed }); var today = new Date(); var today_year = today.getFullYear(); var today_month = today.getMonth(); var today_day = today.getDate() + 1; var six_months_ago = new Date(today_year, today_month - 6, today_day); six_months_ago.toLocaleString('en-AU', { timeZone: 'Australia/Sydney' }) six_months_ago = six_months_ago.toISOString().split('T')[0]; six_months_ago = dateISOToNetsuite(six_months_ago); // six_months_ago = format.format({ value: six_months_ago, type: format.Type.DATE, timezone: format.Timezone.AUSTRALIA_SYDNEY}); // Date Object var date_from = six_months_ago; var date_to = date; var today_in_week = new Date(Date.UTC(today_year, today_month, today_day + 7)); today_in_week.toLocaleString('en-AU', { timeZone: 'Australia/Sydney' }) today_in_week = today_in_week.toISOString().split('T')[0]; today_in_week = dateISOToNetsuite(today_in_week); today_in_week = format.parse({ value: today_in_week, type: format.Type.DATE }); // Date Object var paidInvoiceSearch = search.load({ type: 'invoice', id: 'customsearch_debt_coll_inv' }); var filterExpression = []; filterExpression.push(['customer.internalid', search.Operator.IS, cust_id]) filterExpression.push('AND', ['trandate', search.Operator.ONORBEFORE, date_to]); filterExpression.push('AND', ['trandate', search.Operator.ONORAFTER, date_from]); filterExpression.push('AND', ['memorized', search.Operator.IS, false]); paidInvoiceSearch.filterExpression = filterExpression; var paidInvoiceResult = paidInvoiceSearch.run().getRange({ start: 0, end: 10 }); log.debug({ title: 'TEST', details: paidInvoiceResult }) log.debug({ title: 'TEST2', details: JSON.stringify(paidInvoiceResult) }) paidInvoiceResult.forEach(function(res, index) { // Store original status and then update status after script runs. var invoiceid = res.getValue({ name: 'internalid' }); log.debug({ title: 'Search Invoice ID', details: invoiceid }); var custID = res.getValue({ name: 'internalid', join: 'customer' }); var custRecord = record.load({ type: 'customer', id: custID }); var custStatusVal = custRecord.getValue({ fieldId: 'entitystatus' }); var invoiceRecord = record.load({ type: 'invoice', id: invoiceid }); log.audit({ title: 'New Snooze Date Set - Multi Invoices', details: today_in_week }) var new_date = invoiceRecord.setValue({ fieldId: 'custbody_invoice_snooze_date', value: today_in_week }); // Purple for All Customers with the same customer name // Purple All Invoices under Customer - In Progress log.debug({ title: 'Snooze Invoice ' + invoiceid + ' for 1 Week', details: today_in_week }) var viewed = invoiceRecord.setValue({ fieldId: 'custbody_invoice_viewed', value: true }); var invTableSearch = search.load({ id: 'customsearch_debt_coll_table', type: 'customrecord_debt_coll_inv' }); invTableSearch.filters.push(search.createFilter({ name: 'custrecord_debt_coll_inv_cust_id', operator: search.Operator.IS, values: parseInt(cust_id) })); invTableSearch.run().each(function(invTableRes) { var tableID = invTableRes.getValue({ name: 'internalid' }); log.audit({ title: 'Invoice Table Set to True', details: tableID }) var tableRec = record.load({ type: 'customrecord_debt_coll_inv', id: tableID }); tableRec.setValue({ fieldId: 'custrecord_debt_coll_viewed', value: true }); tableRec.save(); }); var saveRecord = invoiceRecord.save(); custRecord.setValue({ fieldId: 'entitystatus', value: custStatusVal }) custRecord.save(); log.audit({ title: 'Invoice Saved', details: saveRecord }) return true; }) log.debug({ title: 'TEST3', details: 'test3' }) // var invoiceRecord2 = record.load({ // type: 'invoice', // id: invoice_id // }); // var new_date = invoiceRecord2.setValue({ // fieldId: 'custbody_invoice_snooze_date', // value: today_in_week // }); // invoiceRecord2.save(); } /** * Used to pass the values of `date_from` and `date_to` between the scripts and to Netsuite for the records and the search. * @param {String} date_iso "2020-06-01" * @returns {String} date_netsuite "1/6/2020" */ function dateISOToNetsuite(date_iso) { var parts = date_iso.split('-'); if (!isNullorEmpty(date_iso)) { var date_utc = new Date(parts[0], parts[1] - 1, parts[2]); // var date_netsuite = nlapiDateToString(date_utc); var date_netsuite = format.format({ value: date_utc, type: format.Type.DATE }); } return date_netsuite; } /** * [getDate description] - Get the current date * @return {[String]} [description] - return the string date */ function getDate() { var date = new Date(); date = format.format({ value: date, type: format.Type.DATE, timezone: format.Timezone.AUSTRALIA_SYDNEY }); return date; } function isNullorEmpty(val) { if (val == '' || val == null) { return true; } else { return false; } } return { onRequest: onRequest } });
688
[{"tag": "KEY", "value": "sha384-aJ21OjlMXNL5UyIl/XNwTMqvzeRMZH2w8c5cRVpzpU8Y5bApTppSuUkhZXN0VxHd", "start": 3579, "end": 3650}, {"tag": "KEY", "value": "sha384-HSMxcRTRxnN+Bdg0JdbxYKrThecOKuH5zCYotlSAcp1+c8xmyTe9GYg1l9a69psu", "start": 3351, "end": 3422}, {"tag": "KEY", "value": "sha384-nvAa0+6Qg9clwYCGGPpDQLVpLNn0fRaROjHqs13t4Ggj3Ez50XnGQqc/r8MhnRDZ", "start": 2933, "end": 3004}]
true
3
/** * @NApiVersion 2.0 * @NScriptType Suitelet * * Module Description * * NSVersion Date Author * 2.00 2020-10-22 09:33:08 Anesu * * Description: Automation of Debt Collection Process * * @Last Modified by: Anesu * @Last Modified time: 2020-10-22 16:49:26 * */ define(['N/ui/serverWidget', 'N/email', 'N/runtime', 'N/search', 'N/record', 'N/http', 'N/log', 'N/redirect', 'N/task', 'N/format'], function(ui, email, runtime, search, record, http, log, redirect, task, format) { var zee = 0; var role = 0; var baseURL = 'https://1048144.app.netsuite.com'; if (runtime.EnvType == "SANDBOX") { baseURL = 'https://1048144-sb3.app.netsuite.com'; } role = runtime.getCurrentUser().role; if (role == 1000) { zee = runtime.getCurrentUser().id; } else if (role == 3) { //Administrator zee = 6; //test } else if (role == 1032) { // System Support zee = 425904; //test-AR } function onRequest(context) { if (context.request.method === 'GET') { var params = context.request.parameters; var is_params = false; var invoice_id = params.invid; var date; var period; var record_id; var viewed; if (!isNullorEmpty(invoice_id)) { is_params = true; invoice_id = params.invid; date = params.date; period = params.period; record_id = params.recordid; viewed = params.viewed; cust_id = params.custid; multi_viewed = params.multiviewed; } log.debug({ title: 'invoice_id', details: invoice_id }) log.debug({ title: 'date', details: date }) log.debug({ title: 'period', details: period }) log.debug({ title: 'record_id', details: record_id }); log.debug({ title: 'viewed', details: viewed }); log.debug({ title: 'Customer ID', details: cust_id }) var form = ui.createForm({ title: 'Debt Collection - Snooze' }); // Load jQuery var inlineHtml = '<script src="https://code.jquery.com/jquery-1.12.4.min.js" integrity="caf86f4uutaoxfysmf7anj01xl6sv3ps" crossorigin="anonymous"></script>'; // Load Tooltip inlineHtml += '<script src="https://unpkg.com/@popperjs/core@2"></script>'; // Load Bootstrap inlineHtml += '<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/3.4.1/css/bootstrap.min.css" integrity="vqbpgud2ghvjgm1n5hdgjnn5818fzsf2" crossorigin="anonymous">'; inlineHtml += '<script src="https://stackpath.bootstrapcdn.com/bootstrap/3.4.1/js/bootstrap.min.js" integrity="74t3tndxag9o7h0890bnpfzh4olk2h9x" crossorigin="anonymous"></script>'; // Load DataTables inlineHtml += '<link rel="stylesheet" type="text/css" href="//cdn.datatables.net/1.10.21/css/jquery.dataTables.min.css">'; inlineHtml += '<script type="text/javascript" charset="utf8" src="//cdn.datatables.net/1.10.21/js/jquery.dataTables.min.js"></script>'; // Load Bootstrap-Select inlineHtml += '<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap-select@1.13.14/dist/css/bootstrap-select.min.css">'; inlineHtml += '<script src="https://cdn.jsdelivr.net/npm/bootstrap-select@1.13.14/dist/js/bootstrap-select.min.js"></script>'; // Load Netsuite stylesheet and script inlineHtml += '<link rel="stylesheet" href="https://1048144.app.netsuite.com/core/media/media.nl?id=2060796&c=1048144&h=9ee6accfd476c9cae718&_xt=.css"/>'; inlineHtml += '<script src="https://1048144.app.netsuite.com/core/media/media.nl?id=2060797&c=1048144&h=ef2cda20731d146b5e98&_xt=.js"></script>'; inlineHtml += '<link type="text/css" rel="stylesheet" href="https://1048144.app.netsuite.com/core/media/media.nl?id=2090583&c=1048144&h=a0ef6ac4e28f91203dfe&_xt=.css">'; inlineHtml += '<style>.mandatory{color:red;}</style>'; if (is_params == true) { if (isNullorEmpty(period)) { inlineHtml += '<div><h4 style="text-align: center">Invoice has been set as viewed!</h4></div><br>'; } else { inlineHtml += '<div><h4 style="text-align: center">Invoice has successfully been snoozed for a period of ' + period + '!</h4></div><br>'; } } else { inlineHtml += '<div><h4 style="text-align: center">Invalid Parameters. Please Go Back to Debt Collections Page and Try Again</h4></div>' } if (!isNullorEmpty(invoice_id) && !isNullorEmpty(record_id) && !isNullorEmpty(date)) { inlineHtml += invoiceDetailsSection(invoice_id, period, record_id, date); } if (!isNullorEmpty(period)) { saveSnooze(invoice_id, period, record_id, date); } if (!isNullorEmpty(viewed)) { saveViewed(invoice_id, period, viewed, date) } if (!isNullorEmpty(multi_viewed)) { multiViewed(invoice_id, period, multi_viewed, date, cust_id); period = 'Multi Snooze 1 Week' } form.addField({ id: 'preview_table', label: 'inlinehtml', type: 'inlinehtml' }).updateLayoutType({ layoutType: ui.FieldLayoutType.STARTROW }).defaultValue = inlineHtml; form.addButton({ id: 'close', label: 'Close' }) form.addField({ id: 'custpage_debt_coll_invoice_id', type: ui.FieldType.TEXT, label: 'invoice_id' }).updateDisplayType({ displayType: ui.FieldDisplayType.HIDDEN }).defaultValue = invoice_id; form.addField({ id: 'custpage_debt_coll_date', type: ui.FieldType.TEXT, label: 'date' }).updateDisplayType({ displayType: ui.FieldDisplayType.HIDDEN }).defaultValue = date; form.addField({ id: 'custpage_debt_coll_period', type: ui.FieldType.TEXT, label: 'period' }).updateDisplayType({ displayType: ui.FieldDisplayType.HIDDEN }).defaultValue = period; form.addField({ id: 'custpage_debt_coll_record_id', type: ui.FieldType.TEXT, label: 'recordid' }).updateDisplayType({ displayType: ui.FieldDisplayType.HIDDEN }).defaultValue = record_id; form.clientScriptFileId = 4686514; context.response.writePage(form); } else { // } } function invoiceDetailsSection(invoice_id, period, record_id, date) { var inlineQty = ''; inlineQty = '<div class="form-group container invoice_section">'; inlineQty += '<div class="row">'; inlineQty += '<div class="col-xs-12 heading1"><h4><span class="label label-default col-xs-12">SNOOZED INVOICE DETAILS</span></h4></div>'; inlineQty += '</div>'; inlineQty += '</div>'; inlineQty += '<div class="form-group container invoice_id_section">'; inlineQty += '<div class="row">'; inlineQty += '<div class="col-xs-6 invoice_id"><div class="input-group"><span class="input-group-addon" id="invoice_id_text">Invoice ID</span><input id="invoice_id" class="form-control invoice_id" value="' + invoice_id + '" data-oldvalue="' + invoice_id + '"/></div></div>'; inlineQty += '<div class="col-xs-6 record_id"><div class="input-group"><span class="input-group-addon" id="record_id_text">Record ID</span><input id="record_id" class="form-control record_id" value="' + record_id + '" data-oldvalue="' + record_id + '"/></div></div>'; inlineQty += '</div></div>'; inlineQty += '</div>'; inlineQty += '</div>'; inlineQty += '<div class="form-group container _section">'; inlineQty += '<div class="row">'; inlineQty += '<div class="col-xs-6 period"><div class="input-group"><span class="input-group-addon" id="period_text">Period Duration</span><input id="period" class="form-control period" value="' + period + '" data-oldvalue="' + period + '"/></div></div>'; inlineQty += '<div class="col-xs-6 date"><div class="input-group"><span class="input-group-addon" id="date_text">Invoice Date</span><input id="date" class="form-control date" value="' + date + '" data-oldvalue="' + date + '"/></div></div>'; inlineQty += '</div></div>'; inlineQty += '</div>'; inlineQty += '</div>'; inlineQty += '</select></div></div>'; inlineQty += '</div>'; inlineQty += '</div>'; return inlineQty; } function saveSnooze(invoice_id, period, record_id) { var today = new Date(); var today_year = today.getFullYear(); var today_month = today.getMonth(); var today_day = today.getDate() + 1; log.debug({ title: 'today', details: today }) log.debug({ title: 'today_year', details: today_year }) log.debug({ title: 'today_month', details: today_month }) log.debug({ title: 'today_day', details: today_day }); var today_in_day = new Date(Date.UTC(parseInt(today_year), parseInt(today_month), parseInt(today_day) + 1)); today_in_day.toLocaleString('en-AU', { timeZone: 'Australia/Sydney' }); today_in_day = today_in_day.toISOString().split('T')[0]; // Split Date String to get the date. today_in_day = dateISOToNetsuite(today_in_day); // Convert from 2021-01-28 to 28/1/2021 today_in_day = format.parse({ value: today_in_day, type: format.Type.DATE }); // Date Object var today_in_2day = new Date(Date.UTC(today_year, today_month, today_day + 2)); today_in_2day.toLocaleString('en-AU', { timeZone: 'Australia/Sydney' }) today_in_2day = today_in_2day.toISOString().split('T')[0]; today_in_2day = dateISOToNetsuite(today_in_2day); today_in_2day = format.parse({ value: today_in_2day, type: format.Type.DATE }); // Date Object var today_in_week = new Date(Date.UTC(today_year, today_month, today_day + 7)); today_in_week.toLocaleString('en-AU', { timeZone: 'Australia/Sydney' }) today_in_week = today_in_week.toISOString().split('T')[0]; today_in_week = dateISOToNetsuite(today_in_week); today_in_week = format.parse({ value: today_in_week, type: format.Type.DATE }); // Date Object var today_in_2week = new Date(Date.UTC(today_year, today_month, today_day + 14)); today_in_2week.toLocaleString('en-AU', { timeZone: 'Australia/Sydney' }) today_in_2week = today_in_2week.toISOString().split('T')[0]; today_in_2week = dateISOToNetsuite(today_in_2week); today_in_2week = format.parse({ value: today_in_2week, type: format.Type.DATE }); // Date Object var one_year = new Date(Date.UTC(today_year + 1, today_month, today_day)); one_year.toLocaleString('en-AU', { timeZone: 'Australia/Sydney' }) one_year = one_year.toISOString().split('T')[0]; one_year = dateISOToNetsuite(one_year); one_year = format.parse({ value: one_year, type: format.Type.DATE }); // Date Object switch (period) { case '1day': log.debug({ title: '1 Day', details: '1 Day' }); var snoozeRecord = record.load({ type: 'invoice', id: invoice_id }); var date = snoozeRecord.getValue({ fieldId: 'custbody_invoice_snooze_date' }); log.debug({ title: 'Date on Invoice Record', details: today_in_day }); snoozeRecord.setValue({ fieldId: 'custbody_invoice_snooze_date', value: today_in_day }); snoozeRecord.save(); var snoozeDelete = record.delete({ type: 'customrecord_debt_coll_inv', id: record_id }); log.debug({ title: 'Delete initiated - Record ID: ' + record_id, details: 'Delete initiated - Record ID: ' + record_id }); break; case '2day': log.debug({ title: '2 Day', details: '2 Day' }); var snoozeRecord = record.load({ type: 'invoice', id: invoice_id }); var date = snoozeRecord.getValue({ fieldId: 'custbody_invoice_snooze_date' }); log.debug({ title: 'Date for Snooze ' + date, details: 'Date for Snooze ' + date }); snoozeRecord.setValue({ fieldId: 'custbody_invoice_snooze_date', value: today_in_2day }); snoozeRecord.save(); var snoozeDelete = record.delete({ type: 'customrecord_debt_coll_inv', id: record_id }); log.debug({ title: 'Delete initiated - Record ID: ' + record_id, details: 'Delete initiated - Record ID: ' + record_id }); break; case '1week': log.debug({ title: '1 Week', details: '1 Week' }); var snoozeRecord = record.load({ type: 'invoice', id: invoice_id }); var date = snoozeRecord.getValue({ fieldId: 'custbody_invoice_snooze_date' }); log.debug({ title: 'Date for Snooze ' + date, details: 'Date for Snooze ' + date, }) snoozeRecord.setValue({ fieldId: 'custbody_invoice_snooze_date', value: today_in_week }); snoozeRecord.save(); var snoozeDelete = record.delete({ type: 'customrecord_debt_coll_inv', id: record_id }); log.debug({ title: 'Delete initiated - Record ID: ' + record_id, details: 'Delete initiated - Record ID: ' + record_id }); break; case '2week': log.debug({ title: '2 Week', details: '2 Week' }); var snoozeRecord = record.load({ type: 'invoice', id: invoice_id }); var date = snoozeRecord.getValue({ fieldId: 'custbody_invoice_snooze_date' }); log.debug({ title: 'Date for Snooze ' + date, details: 'Date for Snooze ' + date }) snoozeRecord.setValue({ fieldId: 'custbody_invoice_snooze_date', value: today_in_2week }); snoozeRecord.save(); var snoozeDelete = record.delete({ type: 'customrecord_debt_coll_inv', id: record_id }); log.debug({ title: 'Delete initiated - Record ID: ' + record_id, details: 'Delete initiated - Record ID: ' + record_id }); break; case 'permanent': log.debug({ title: 'Permanent', details: 'Permanent' }); var snoozeRecord = record.load({ type: 'invoice', id: invoice_id }); var date = snoozeRecord.getValue({ fieldId: 'custbody_invoice_snooze_date' }); log.debug({ title: 'Date for Snooze ' + date, details: 'Date for Snooze ' + date }) snoozeRecord.setValue({ fieldId: 'custbody_invoice_snooze_date', value: one_year }); snoozeRecord.save(); var snoozeDelete = record.delete({ type: 'customrecord_debt_coll_inv', id: record_id }); log.debug({ title: 'Delete initiated - Record ID: ' + record_id, details: 'Delete initiated - Record ID: ' + record_id }); default: log.debug({ title: "No Snooze Date Note Saved", details: period }); } return true; } function saveViewed(invoice_id, period, viewed) { // 1 Week Snooze var today = new Date(); var today_year = today.getFullYear(); var today_month = today.getMonth(); var today_day = today.getDate() + 1; var today_in_week = new Date(Date.UTC(today_year, today_month, today_day + 7)); today_in_week.toLocaleString('en-AU', { timeZone: 'Australia/Sydney' }) today_in_week = today_in_week.toISOString().split('T')[0]; today_in_week = dateISOToNetsuite(today_in_week); today_in_week = format.parse({ value: today_in_week, type: format.Type.DATE }); // Date Object var invoiceRecord = record.load({ type: 'invoice', id: invoice_id }); var new_date = invoiceRecord.setValue({ fieldId: 'custbody_invoice_snooze_date', value: today_in_week }); var custID = invoiceRecord.getValue({ fieldId: 'entity' }); var custRecord = record.load({ type: 'customer', id: custID }); var custStatusVal = custRecord.getValue({ fieldId: 'entitystatus' }); // Purple for All Customers with the same customer name // Purple for Invoice for 1 Week - DONE // Purple All Invoices under Customer - In Progress // Search of All Customers, Send to Yassine - DONE log.debug({ title: 'new_date record ID', details: new_date }) var viewed = invoiceRecord.getValue({ fieldId: 'custbody_invoice_viewed' }); log.debug({ title: 'viewed', details: viewed }); viewed = invoiceRecord.setValue({ fieldId: 'custbody_invoice_viewed', value: true }); invoiceRecord.save(); custRecord.setValue({ fieldId: 'entitystatus', value: custStatusVal }); custRecord.save(); return true; } function multiViewed(invoice_id, period, multi_viewed, date, cust_id) { log.debug({ title: 'Multiple Invoices Viewed', details: multi_viewed }); var today = new Date(); var today_year = today.getFullYear(); var today_month = today.getMonth(); var today_day = today.getDate() + 1; var six_months_ago = new Date(today_year, today_month - 6, today_day); six_months_ago.toLocaleString('en-AU', { timeZone: 'Australia/Sydney' }) six_months_ago = six_months_ago.toISOString().split('T')[0]; six_months_ago = dateISOToNetsuite(six_months_ago); // six_months_ago = format.format({ value: six_months_ago, type: format.Type.DATE, timezone: format.Timezone.AUSTRALIA_SYDNEY}); // Date Object var date_from = six_months_ago; var date_to = date; var today_in_week = new Date(Date.UTC(today_year, today_month, today_day + 7)); today_in_week.toLocaleString('en-AU', { timeZone: 'Australia/Sydney' }) today_in_week = today_in_week.toISOString().split('T')[0]; today_in_week = dateISOToNetsuite(today_in_week); today_in_week = format.parse({ value: today_in_week, type: format.Type.DATE }); // Date Object var paidInvoiceSearch = search.load({ type: 'invoice', id: 'customsearch_debt_coll_inv' }); var filterExpression = []; filterExpression.push(['customer.internalid', search.Operator.IS, cust_id]) filterExpression.push('AND', ['trandate', search.Operator.ONORBEFORE, date_to]); filterExpression.push('AND', ['trandate', search.Operator.ONORAFTER, date_from]); filterExpression.push('AND', ['memorized', search.Operator.IS, false]); paidInvoiceSearch.filterExpression = filterExpression; var paidInvoiceResult = paidInvoiceSearch.run().getRange({ start: 0, end: 10 }); log.debug({ title: 'TEST', details: paidInvoiceResult }) log.debug({ title: 'TEST2', details: JSON.stringify(paidInvoiceResult) }) paidInvoiceResult.forEach(function(res, index) { // Store original status and then update status after script runs. var invoiceid = res.getValue({ name: 'internalid' }); log.debug({ title: 'Search Invoice ID', details: invoiceid }); var custID = res.getValue({ name: 'internalid', join: 'customer' }); var custRecord = record.load({ type: 'customer', id: custID }); var custStatusVal = custRecord.getValue({ fieldId: 'entitystatus' }); var invoiceRecord = record.load({ type: 'invoice', id: invoiceid }); log.audit({ title: 'New Snooze Date Set - Multi Invoices', details: today_in_week }) var new_date = invoiceRecord.setValue({ fieldId: 'custbody_invoice_snooze_date', value: today_in_week }); // Purple for All Customers with the same customer name // Purple All Invoices under Customer - In Progress log.debug({ title: 'Snooze Invoice ' + invoiceid + ' for 1 Week', details: today_in_week }) var viewed = invoiceRecord.setValue({ fieldId: 'custbody_invoice_viewed', value: true }); var invTableSearch = search.load({ id: 'customsearch_debt_coll_table', type: 'customrecord_debt_coll_inv' }); invTableSearch.filters.push(search.createFilter({ name: 'custrecord_debt_coll_inv_cust_id', operator: search.Operator.IS, values: parseInt(cust_id) })); invTableSearch.run().each(function(invTableRes) { var tableID = invTableRes.getValue({ name: 'internalid' }); log.audit({ title: 'Invoice Table Set to True', details: tableID }) var tableRec = record.load({ type: 'customrecord_debt_coll_inv', id: tableID }); tableRec.setValue({ fieldId: 'custrecord_debt_coll_viewed', value: true }); tableRec.save(); }); var saveRecord = invoiceRecord.save(); custRecord.setValue({ fieldId: 'entitystatus', value: custStatusVal }) custRecord.save(); log.audit({ title: 'Invoice Saved', details: saveRecord }) return true; }) log.debug({ title: 'TEST3', details: 'test3' }) // var invoiceRecord2 = record.load({ // type: 'invoice', // id: invoice_id // }); // var new_date = invoiceRecord2.setValue({ // fieldId: 'custbody_invoice_snooze_date', // value: today_in_week // }); // invoiceRecord2.save(); } /** * Used to pass the values of `date_from` and `date_to` between the scripts and to Netsuite for the records and the search. * @param {String} date_iso "2020-06-01" * @returns {String} date_netsuite "1/6/2020" */ function dateISOToNetsuite(date_iso) { var parts = date_iso.split('-'); if (!isNullorEmpty(date_iso)) { var date_utc = new Date(parts[0], parts[1] - 1, parts[2]); // var date_netsuite = nlapiDateToString(date_utc); var date_netsuite = format.format({ value: date_utc, type: format.Type.DATE }); } return date_netsuite; } /** * [getDate description] - Get the current date * @return {[String]} [description] - return the string date */ function getDate() { var date = new Date(); date = format.format({ value: date, type: format.Type.DATE, timezone: format.Timezone.AUSTRALIA_SYDNEY }); return date; } function isNullorEmpty(val) { if (val == '' || val == null) { return true; } else { return false; } } return { onRequest: onRequest } });
true
/** * @NApiVersion 2.0 * @NScriptType Suitelet * * Module Description * * NSVersion Date Author * 2.00 2020-10-22 09:33:08 Anesu * * Description: Automation of Debt Collection Process * * @Last Modified by: Anesu * @Last Modified time: 2020-10-22 16:49:26 * */ define(['N/ui/serverWidget', 'N/email', 'N/runtime', 'N/search', 'N/record', 'N/http', 'N/log', 'N/redirect', 'N/task', 'N/format'], function(ui, email, runtime, search, record, http, log, redirect, task, format) { var zee = 0; var role = 0; var baseURL = 'https://1048144.app.netsuite.com'; if (runtime.EnvType == "SANDBOX") { baseURL = 'https://1048144-sb3.app.netsuite.com'; } role = runtime.getCurrentUser().role; if (role == 1000) { zee = runtime.getCurrentUser().id; } else if (role == 3) { //Administrator zee = 6; //test } else if (role == 1032) { // System Support zee = 425904; //test-AR } function onRequest(context) { if (context.request.method === 'GET') { var params = context.request.parameters; var is_params = false; var invoice_id = params.invid; var date; var period; var record_id; var viewed; if (!isNullorEmpty(invoice_id)) { is_params = true; invoice_id = params.invid; date = params.date; period = params.period; record_id = params.recordid; viewed = params.viewed; cust_id = params.custid; multi_viewed = params.multiviewed; } log.debug({ title: 'invoice_id', details: invoice_id }) log.debug({ title: 'date', details: date }) log.debug({ title: 'period', details: period }) log.debug({ title: 'record_id', details: record_id }); log.debug({ title: 'viewed', details: viewed }); log.debug({ title: 'Customer ID', details: cust_id }) var form = ui.createForm({ title: 'Debt Collection - Snooze' }); // Load jQuery var inlineHtml = '<script src="https://code.jquery.com/jquery-1.12.4.min.js" integrity="PI:KEY:caf86f4uutaoxfysmf7anj01xl6sv3psEND_PI" crossorigin="anonymous"></script>'; // Load Tooltip inlineHtml += '<script src="https://unpkg.com/@popperjs/core@2"></script>'; // Load Bootstrap inlineHtml += '<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/3.4.1/css/bootstrap.min.css" integrity="PI:KEY:vqbpgud2ghvjgm1n5hdgjnn5818fzsf2END_PI" crossorigin="anonymous">'; inlineHtml += '<script src="https://stackpath.bootstrapcdn.com/bootstrap/3.4.1/js/bootstrap.min.js" integrity="PI:KEY:74t3tndxag9o7h0890bnpfzh4olk2h9xEND_PI" crossorigin="anonymous"></script>'; // Load DataTables inlineHtml += '<link rel="stylesheet" type="text/css" href="//cdn.datatables.net/1.10.21/css/jquery.dataTables.min.css">'; inlineHtml += '<script type="text/javascript" charset="utf8" src="//cdn.datatables.net/1.10.21/js/jquery.dataTables.min.js"></script>'; // Load Bootstrap-Select inlineHtml += '<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap-select@1.13.14/dist/css/bootstrap-select.min.css">'; inlineHtml += '<script src="https://cdn.jsdelivr.net/npm/bootstrap-select@1.13.14/dist/js/bootstrap-select.min.js"></script>'; // Load Netsuite stylesheet and script inlineHtml += '<link rel="stylesheet" href="https://1048144.app.netsuite.com/core/media/media.nl?id=2060796&c=1048144&h=9ee6accfd476c9cae718&_xt=.css"/>'; inlineHtml += '<script src="https://1048144.app.netsuite.com/core/media/media.nl?id=2060797&c=1048144&h=ef2cda20731d146b5e98&_xt=.js"></script>'; inlineHtml += '<link type="text/css" rel="stylesheet" href="https://1048144.app.netsuite.com/core/media/media.nl?id=2090583&c=1048144&h=a0ef6ac4e28f91203dfe&_xt=.css">'; inlineHtml += '<style>.mandatory{color:red;}</style>'; if (is_params == true) { if (isNullorEmpty(period)) { inlineHtml += '<div><h4 style="text-align: center">Invoice has been set as viewed!</h4></div><br>'; } else { inlineHtml += '<div><h4 style="text-align: center">Invoice has successfully been snoozed for a period of ' + period + '!</h4></div><br>'; } } else { inlineHtml += '<div><h4 style="text-align: center">Invalid Parameters. Please Go Back to Debt Collections Page and Try Again</h4></div>' } if (!isNullorEmpty(invoice_id) && !isNullorEmpty(record_id) && !isNullorEmpty(date)) { inlineHtml += invoiceDetailsSection(invoice_id, period, record_id, date); } if (!isNullorEmpty(period)) { saveSnooze(invoice_id, period, record_id, date); } if (!isNullorEmpty(viewed)) { saveViewed(invoice_id, period, viewed, date) } if (!isNullorEmpty(multi_viewed)) { multiViewed(invoice_id, period, multi_viewed, date, cust_id); period = 'Multi Snooze 1 Week' } form.addField({ id: 'preview_table', label: 'inlinehtml', type: 'inlinehtml' }).updateLayoutType({ layoutType: ui.FieldLayoutType.STARTROW }).defaultValue = inlineHtml; form.addButton({ id: 'close', label: 'Close' }) form.addField({ id: 'custpage_debt_coll_invoice_id', type: ui.FieldType.TEXT, label: 'invoice_id' }).updateDisplayType({ displayType: ui.FieldDisplayType.HIDDEN }).defaultValue = invoice_id; form.addField({ id: 'custpage_debt_coll_date', type: ui.FieldType.TEXT, label: 'date' }).updateDisplayType({ displayType: ui.FieldDisplayType.HIDDEN }).defaultValue = date; form.addField({ id: 'custpage_debt_coll_period', type: ui.FieldType.TEXT, label: 'period' }).updateDisplayType({ displayType: ui.FieldDisplayType.HIDDEN }).defaultValue = period; form.addField({ id: 'custpage_debt_coll_record_id', type: ui.FieldType.TEXT, label: 'recordid' }).updateDisplayType({ displayType: ui.FieldDisplayType.HIDDEN }).defaultValue = record_id; form.clientScriptFileId = 4686514; context.response.writePage(form); } else { // } } function invoiceDetailsSection(invoice_id, period, record_id, date) { var inlineQty = ''; inlineQty = '<div class="form-group container invoice_section">'; inlineQty += '<div class="row">'; inlineQty += '<div class="col-xs-12 heading1"><h4><span class="label label-default col-xs-12">SNOOZED INVOICE DETAILS</span></h4></div>'; inlineQty += '</div>'; inlineQty += '</div>'; inlineQty += '<div class="form-group container invoice_id_section">'; inlineQty += '<div class="row">'; inlineQty += '<div class="col-xs-6 invoice_id"><div class="input-group"><span class="input-group-addon" id="invoice_id_text">Invoice ID</span><input id="invoice_id" class="form-control invoice_id" value="' + invoice_id + '" data-oldvalue="' + invoice_id + '"/></div></div>'; inlineQty += '<div class="col-xs-6 record_id"><div class="input-group"><span class="input-group-addon" id="record_id_text">Record ID</span><input id="record_id" class="form-control record_id" value="' + record_id + '" data-oldvalue="' + record_id + '"/></div></div>'; inlineQty += '</div></div>'; inlineQty += '</div>'; inlineQty += '</div>'; inlineQty += '<div class="form-group container _section">'; inlineQty += '<div class="row">'; inlineQty += '<div class="col-xs-6 period"><div class="input-group"><span class="input-group-addon" id="period_text">Period Duration</span><input id="period" class="form-control period" value="' + period + '" data-oldvalue="' + period + '"/></div></div>'; inlineQty += '<div class="col-xs-6 date"><div class="input-group"><span class="input-group-addon" id="date_text">Invoice Date</span><input id="date" class="form-control date" value="' + date + '" data-oldvalue="' + date + '"/></div></div>'; inlineQty += '</div></div>'; inlineQty += '</div>'; inlineQty += '</div>'; inlineQty += '</select></div></div>'; inlineQty += '</div>'; inlineQty += '</div>'; return inlineQty; } function saveSnooze(invoice_id, period, record_id) { var today = new Date(); var today_year = today.getFullYear(); var today_month = today.getMonth(); var today_day = today.getDate() + 1; log.debug({ title: 'today', details: today }) log.debug({ title: 'today_year', details: today_year }) log.debug({ title: 'today_month', details: today_month }) log.debug({ title: 'today_day', details: today_day }); var today_in_day = new Date(Date.UTC(parseInt(today_year), parseInt(today_month), parseInt(today_day) + 1)); today_in_day.toLocaleString('en-AU', { timeZone: 'Australia/Sydney' }); today_in_day = today_in_day.toISOString().split('T')[0]; // Split Date String to get the date. today_in_day = dateISOToNetsuite(today_in_day); // Convert from 2021-01-28 to 28/1/2021 today_in_day = format.parse({ value: today_in_day, type: format.Type.DATE }); // Date Object var today_in_2day = new Date(Date.UTC(today_year, today_month, today_day + 2)); today_in_2day.toLocaleString('en-AU', { timeZone: 'Australia/Sydney' }) today_in_2day = today_in_2day.toISOString().split('T')[0]; today_in_2day = dateISOToNetsuite(today_in_2day); today_in_2day = format.parse({ value: today_in_2day, type: format.Type.DATE }); // Date Object var today_in_week = new Date(Date.UTC(today_year, today_month, today_day + 7)); today_in_week.toLocaleString('en-AU', { timeZone: 'Australia/Sydney' }) today_in_week = today_in_week.toISOString().split('T')[0]; today_in_week = dateISOToNetsuite(today_in_week); today_in_week = format.parse({ value: today_in_week, type: format.Type.DATE }); // Date Object var today_in_2week = new Date(Date.UTC(today_year, today_month, today_day + 14)); today_in_2week.toLocaleString('en-AU', { timeZone: 'Australia/Sydney' }) today_in_2week = today_in_2week.toISOString().split('T')[0]; today_in_2week = dateISOToNetsuite(today_in_2week); today_in_2week = format.parse({ value: today_in_2week, type: format.Type.DATE }); // Date Object var one_year = new Date(Date.UTC(today_year + 1, today_month, today_day)); one_year.toLocaleString('en-AU', { timeZone: 'Australia/Sydney' }) one_year = one_year.toISOString().split('T')[0]; one_year = dateISOToNetsuite(one_year); one_year = format.parse({ value: one_year, type: format.Type.DATE }); // Date Object switch (period) { case '1day': log.debug({ title: '1 Day', details: '1 Day' }); var snoozeRecord = record.load({ type: 'invoice', id: invoice_id }); var date = snoozeRecord.getValue({ fieldId: 'custbody_invoice_snooze_date' }); log.debug({ title: 'Date on Invoice Record', details: today_in_day }); snoozeRecord.setValue({ fieldId: 'custbody_invoice_snooze_date', value: today_in_day }); snoozeRecord.save(); var snoozeDelete = record.delete({ type: 'customrecord_debt_coll_inv', id: record_id }); log.debug({ title: 'Delete initiated - Record ID: ' + record_id, details: 'Delete initiated - Record ID: ' + record_id }); break; case '2day': log.debug({ title: '2 Day', details: '2 Day' }); var snoozeRecord = record.load({ type: 'invoice', id: invoice_id }); var date = snoozeRecord.getValue({ fieldId: 'custbody_invoice_snooze_date' }); log.debug({ title: 'Date for Snooze ' + date, details: 'Date for Snooze ' + date }); snoozeRecord.setValue({ fieldId: 'custbody_invoice_snooze_date', value: today_in_2day }); snoozeRecord.save(); var snoozeDelete = record.delete({ type: 'customrecord_debt_coll_inv', id: record_id }); log.debug({ title: 'Delete initiated - Record ID: ' + record_id, details: 'Delete initiated - Record ID: ' + record_id }); break; case '1week': log.debug({ title: '1 Week', details: '1 Week' }); var snoozeRecord = record.load({ type: 'invoice', id: invoice_id }); var date = snoozeRecord.getValue({ fieldId: 'custbody_invoice_snooze_date' }); log.debug({ title: 'Date for Snooze ' + date, details: 'Date for Snooze ' + date, }) snoozeRecord.setValue({ fieldId: 'custbody_invoice_snooze_date', value: today_in_week }); snoozeRecord.save(); var snoozeDelete = record.delete({ type: 'customrecord_debt_coll_inv', id: record_id }); log.debug({ title: 'Delete initiated - Record ID: ' + record_id, details: 'Delete initiated - Record ID: ' + record_id }); break; case '2week': log.debug({ title: '2 Week', details: '2 Week' }); var snoozeRecord = record.load({ type: 'invoice', id: invoice_id }); var date = snoozeRecord.getValue({ fieldId: 'custbody_invoice_snooze_date' }); log.debug({ title: 'Date for Snooze ' + date, details: 'Date for Snooze ' + date }) snoozeRecord.setValue({ fieldId: 'custbody_invoice_snooze_date', value: today_in_2week }); snoozeRecord.save(); var snoozeDelete = record.delete({ type: 'customrecord_debt_coll_inv', id: record_id }); log.debug({ title: 'Delete initiated - Record ID: ' + record_id, details: 'Delete initiated - Record ID: ' + record_id }); break; case 'permanent': log.debug({ title: 'Permanent', details: 'Permanent' }); var snoozeRecord = record.load({ type: 'invoice', id: invoice_id }); var date = snoozeRecord.getValue({ fieldId: 'custbody_invoice_snooze_date' }); log.debug({ title: 'Date for Snooze ' + date, details: 'Date for Snooze ' + date }) snoozeRecord.setValue({ fieldId: 'custbody_invoice_snooze_date', value: one_year }); snoozeRecord.save(); var snoozeDelete = record.delete({ type: 'customrecord_debt_coll_inv', id: record_id }); log.debug({ title: 'Delete initiated - Record ID: ' + record_id, details: 'Delete initiated - Record ID: ' + record_id }); default: log.debug({ title: "No Snooze Date Note Saved", details: period }); } return true; } function saveViewed(invoice_id, period, viewed) { // 1 Week Snooze var today = new Date(); var today_year = today.getFullYear(); var today_month = today.getMonth(); var today_day = today.getDate() + 1; var today_in_week = new Date(Date.UTC(today_year, today_month, today_day + 7)); today_in_week.toLocaleString('en-AU', { timeZone: 'Australia/Sydney' }) today_in_week = today_in_week.toISOString().split('T')[0]; today_in_week = dateISOToNetsuite(today_in_week); today_in_week = format.parse({ value: today_in_week, type: format.Type.DATE }); // Date Object var invoiceRecord = record.load({ type: 'invoice', id: invoice_id }); var new_date = invoiceRecord.setValue({ fieldId: 'custbody_invoice_snooze_date', value: today_in_week }); var custID = invoiceRecord.getValue({ fieldId: 'entity' }); var custRecord = record.load({ type: 'customer', id: custID }); var custStatusVal = custRecord.getValue({ fieldId: 'entitystatus' }); // Purple for All Customers with the same customer name // Purple for Invoice for 1 Week - DONE // Purple All Invoices under Customer - In Progress // Search of All Customers, Send to Yassine - DONE log.debug({ title: 'new_date record ID', details: new_date }) var viewed = invoiceRecord.getValue({ fieldId: 'custbody_invoice_viewed' }); log.debug({ title: 'viewed', details: viewed }); viewed = invoiceRecord.setValue({ fieldId: 'custbody_invoice_viewed', value: true }); invoiceRecord.save(); custRecord.setValue({ fieldId: 'entitystatus', value: custStatusVal }); custRecord.save(); return true; } function multiViewed(invoice_id, period, multi_viewed, date, cust_id) { log.debug({ title: 'Multiple Invoices Viewed', details: multi_viewed }); var today = new Date(); var today_year = today.getFullYear(); var today_month = today.getMonth(); var today_day = today.getDate() + 1; var six_months_ago = new Date(today_year, today_month - 6, today_day); six_months_ago.toLocaleString('en-AU', { timeZone: 'Australia/Sydney' }) six_months_ago = six_months_ago.toISOString().split('T')[0]; six_months_ago = dateISOToNetsuite(six_months_ago); // six_months_ago = format.format({ value: six_months_ago, type: format.Type.DATE, timezone: format.Timezone.AUSTRALIA_SYDNEY}); // Date Object var date_from = six_months_ago; var date_to = date; var today_in_week = new Date(Date.UTC(today_year, today_month, today_day + 7)); today_in_week.toLocaleString('en-AU', { timeZone: 'Australia/Sydney' }) today_in_week = today_in_week.toISOString().split('T')[0]; today_in_week = dateISOToNetsuite(today_in_week); today_in_week = format.parse({ value: today_in_week, type: format.Type.DATE }); // Date Object var paidInvoiceSearch = search.load({ type: 'invoice', id: 'customsearch_debt_coll_inv' }); var filterExpression = []; filterExpression.push(['customer.internalid', search.Operator.IS, cust_id]) filterExpression.push('AND', ['trandate', search.Operator.ONORBEFORE, date_to]); filterExpression.push('AND', ['trandate', search.Operator.ONORAFTER, date_from]); filterExpression.push('AND', ['memorized', search.Operator.IS, false]); paidInvoiceSearch.filterExpression = filterExpression; var paidInvoiceResult = paidInvoiceSearch.run().getRange({ start: 0, end: 10 }); log.debug({ title: 'TEST', details: paidInvoiceResult }) log.debug({ title: 'TEST2', details: JSON.stringify(paidInvoiceResult) }) paidInvoiceResult.forEach(function(res, index) { // Store original status and then update status after script runs. var invoiceid = res.getValue({ name: 'internalid' }); log.debug({ title: 'Search Invoice ID', details: invoiceid }); var custID = res.getValue({ name: 'internalid', join: 'customer' }); var custRecord = record.load({ type: 'customer', id: custID }); var custStatusVal = custRecord.getValue({ fieldId: 'entitystatus' }); var invoiceRecord = record.load({ type: 'invoice', id: invoiceid }); log.audit({ title: 'New Snooze Date Set - Multi Invoices', details: today_in_week }) var new_date = invoiceRecord.setValue({ fieldId: 'custbody_invoice_snooze_date', value: today_in_week }); // Purple for All Customers with the same customer name // Purple All Invoices under Customer - In Progress log.debug({ title: 'Snooze Invoice ' + invoiceid + ' for 1 Week', details: today_in_week }) var viewed = invoiceRecord.setValue({ fieldId: 'custbody_invoice_viewed', value: true }); var invTableSearch = search.load({ id: 'customsearch_debt_coll_table', type: 'customrecord_debt_coll_inv' }); invTableSearch.filters.push(search.createFilter({ name: 'custrecord_debt_coll_inv_cust_id', operator: search.Operator.IS, values: parseInt(cust_id) })); invTableSearch.run().each(function(invTableRes) { var tableID = invTableRes.getValue({ name: 'internalid' }); log.audit({ title: 'Invoice Table Set to True', details: tableID }) var tableRec = record.load({ type: 'customrecord_debt_coll_inv', id: tableID }); tableRec.setValue({ fieldId: 'custrecord_debt_coll_viewed', value: true }); tableRec.save(); }); var saveRecord = invoiceRecord.save(); custRecord.setValue({ fieldId: 'entitystatus', value: custStatusVal }) custRecord.save(); log.audit({ title: 'Invoice Saved', details: saveRecord }) return true; }) log.debug({ title: 'TEST3', details: 'test3' }) // var invoiceRecord2 = record.load({ // type: 'invoice', // id: invoice_id // }); // var new_date = invoiceRecord2.setValue({ // fieldId: 'custbody_invoice_snooze_date', // value: today_in_week // }); // invoiceRecord2.save(); } /** * Used to pass the values of `date_from` and `date_to` between the scripts and to Netsuite for the records and the search. * @param {String} date_iso "2020-06-01" * @returns {String} date_netsuite "1/6/2020" */ function dateISOToNetsuite(date_iso) { var parts = date_iso.split('-'); if (!isNullorEmpty(date_iso)) { var date_utc = new Date(parts[0], parts[1] - 1, parts[2]); // var date_netsuite = nlapiDateToString(date_utc); var date_netsuite = format.format({ value: date_utc, type: format.Type.DATE }); } return date_netsuite; } /** * [getDate description] - Get the current date * @return {[String]} [description] - return the string date */ function getDate() { var date = new Date(); date = format.format({ value: date, type: format.Type.DATE, timezone: format.Timezone.AUSTRALIA_SYDNEY }); return date; } function isNullorEmpty(val) { if (val == '' || val == null) { return true; } else { return false; } } return { onRequest: onRequest } });
/** * @NApiVersion 2.0 * @NScriptType MapReduceScript */ define(['N/record', 'N/search', 'N/email', 'N/runtime'], /** * @param{record} record * @param{search} search */ function(record, search, email, runtime){ /** * Defines the function that is executed at the beginning of the map/reduce process and generates the input data. * @param {Object} inputContext * @param {boolean} inputContext.isRestarted - Indicates whether the current invocation of this function is the first * invocation (if true, the current invocation is not the first invocation and this function has been restarted) * @param {Object} inputContext.ObjectRef - Object that references the input data * @typedef {Object} ObjectRef * @property {string|number} ObjectRef.id - Internal ID of the record instance that contains the input data * @property {string} ObjectRef.type - Type of the record instance that contains the input data * @returns {Array|Object|Search|ObjectRef|File|Query} The input data to use in the map/reduce process * @since 2015.2 */ /*Global Variables*/ var departmentD; var classD; var locationD; function getInputData(inputContext){ var loadSearch = search.load({ id: 'customsearch_time_entry_to_post' }); return loadSearch; } /** * Defines the function that is executed when the map entry point is triggered. This entry point is triggered automatically * when the associated getInputData stage is complete. This function is applied to each key-value pair in the provided * context. * @param {Object} mapContext - Data collection containing the key-value pairs to process in the map stage. This parameter * is provided automatically based on the results of the getInputData stage. * @param {Iterator} mapContext.errors - Serialized errors that were thrown during previous attempts to execute the map * function on the current key-value pair * @param {number} mapContext.executionNo - Number of times the map function has been executed on the current key-value * pair * @param {boolean} mapContext.isRestarted - Indicates whether the current invocation of this function is the first * invocation (if true, the current invocation is not the first invocation and this function has been restarted) * @param {string} mapContext.key - Key to be processed during the map stage * @param {string} mapContext.value - Value to be processed during the map stage * @since 2015.2 */ function map(mapContext) { try { var accountCr = runtime.getCurrentScript().getParameter("custscript_proj_var_acct"); var currentUser = 239241; var currentUserEmail = 'rubykumari413@gmail.com' var data = JSON.parse(mapContext.value); //log.debug('data',data) var id = data.id; var empName = data.values.employee.value; var custName = data.values.customer.value; var jrnalMemo = data.values.memo; var hours = data.values.hours; log.debug('Time sheet enterted for - ',id) hours = ''+hours.split(':')[0]+'.'+hours.split(':')[1]+''; var timebillCheck = search.lookupFields({ type:'timebill', id: id, columns: ['isbillable'] }); var billCbk = timebillCheck['isbillable']; var transactionCheck = search.lookupFields({ type:'employee', id: empName, columns: ['subsidiary','department','class','location','custentity_laborcost_usd'] }); var subsidaryD = transactionCheck['subsidiary'][0].value; var subsidaryText = transactionCheck['subsidiary'][0].text; try{ departmentD = transactionCheck['department'][0].value; classD = transactionCheck['class'][0].value; locationD = transactionCheck['location'][0].value; }catch(e){ log.debug('e',e) } var labourCost = transactionCheck['custentity_laborcost_usd']; var finalAmount = (Number(Number(hours)*Number(labourCost))).toFixed(2); var finalLineMemo = 'Time Entry for '+subsidaryText+'; memo:'+jrnalMemo+''; var jobCheck = search.lookupFields({ type:'job', id: custName, columns: ['currency','projectexpensetype'] }); var lvCurrency = jobCheck['currency'][0].value; var accountDr = jobCheck['projectexpensetype'][0].value; if(accountDr == '1'){accountDr = 913;}else if(accountDr == '2'){accountDr = 914;}else if(accountDr == -3){accountDr = 885;}else{accountDr = 884;} /* //// @@@@@@@@@@@@ Account Map @@@@@@@@@@@ //// Direct Salary == 61190 Project Direct Salary (895/913) Indirect Salary == Project Indirect Salary (896/914) Overhead == Indirect Labor (885) Regular == Direct Labor (884) //// @@@@@@@@@@@@ Account Map END @@@@@@@@@@@ ////*/ //creating journal record journalRecordCreate = record.create({ type: 'journalentry', isDynamic: true }); journalRecordCreate.setValue({ fieldId : 'subsidiary', value : subsidaryD }); journalRecordCreate.setValue({ fieldId : 'currency', value : lvCurrency }); journalRecordCreate.setValue({ fieldId : 'trandate', value : new Date() }); journalRecordCreate.setValue({ fieldId : 'approved', value : true }); journalRecordCreate.setValue({ fieldId : 'timebillflag', value : 'T' }); journalRecordCreate.setValue({ fieldId : 'custbody_sr_time_track_link', value : id }); var type = 'debit'; addLineDataOnJournalRecord(finalLineMemo,accountDr,finalAmount,type); var type = 'credit'; addLineDataOnJournalRecord(finalLineMemo,accountCr,finalAmount,type); try{ if(billCbk == false || billCbk == 'F' || billCbk == ''){ var journalRecordId = journalRecordCreate.save({ enableSourcing: true, ignoreMandatoryFields: true }); log.debug('journalRecordId',journalRecordId) /*var rec = record.load({type:'timebill',id:id}); rec.setValue({fieldId:'transactionid',value:Number(journalRecordId)}); rec.setValue({fieldId:'posted',value:true}); var recordSubmit = rec.save()*/ var recordSubmit = record.submitFields({ type: 'timebill', id: id, values: { 'posted': 'T', 'transactionid':Number(journalRecordId) }, options: { enableSourcing: true, ignoreMandatoryFields : true } }); log.debug('recordSubmit',recordSubmit) }else{ log.debug('its charges') } }catch(journalRecordSubmitError){ record.submitFields({ type: 'timebill', id: id, values: { 'posted': 'F' } }); log.error({title:'Error in journal Creation: ', details:journalRecordSubmitError}); email.send({author: currentUser, recipients: currentUserEmail, subject: 'Error while submitting journal for Time sheet: '+id+'', body: 'Hi,\n Error is:\n '+journalRecordSubmitError+'' }); } }catch(e){ log.debug('Error', e); } } function addLineDataOnJournalRecord(memo,account,ammount,type){ if(ammount != '' && ammount != undefined || ammount != null){ if(account != '' && account != undefined){ if(type == 'credit'){ var line = journalRecordCreate.getLineCount({ sublistId: 'line' }); journalRecordCreate.selectLine({ sublistId: 'line', line: line }); journalRecordCreate.setCurrentSublistValue({ sublistId: 'line', fieldId: 'account', value: account }); journalRecordCreate.setCurrentSublistValue({ sublistId: 'line', fieldId: 'credit', value: ammount }); journalRecordCreate.setCurrentSublistValue({ sublistId: 'line', fieldId: 'memo', value: memo }); try{ journalRecordCreate.setCurrentSublistValue({ sublistId: 'line', fieldId: 'department', value: departmentD }); journalRecordCreate.setCurrentSublistValue({ sublistId: 'line', fieldId: 'class', value: classD }); journalRecordCreate.setCurrentSublistValue({ sublistId: 'line', fieldId: 'location', value: locationD }); }catch(e){ log.debug("issue with department") } journalRecordCreate.commitLine({ sublistId: 'line'}); }else if(type == 'debit'){ var line = journalRecordCreate.getLineCount({ sublistId: 'line' }); journalRecordCreate.selectLine({ sublistId: 'line', line: line }); journalRecordCreate.setCurrentSublistValue({ sublistId: 'line', fieldId: 'account', value: account }); journalRecordCreate.setCurrentSublistValue({ sublistId: 'line', fieldId: 'debit', value: ammount }); journalRecordCreate.setCurrentSublistValue({ sublistId: 'line', fieldId: 'memo', value: memo }); try{ journalRecordCreate.setCurrentSublistValue({ sublistId: 'line', fieldId: 'department', value: departmentD }); journalRecordCreate.setCurrentSublistValue({ sublistId: 'line', fieldId: 'class', value: classD }); journalRecordCreate.setCurrentSublistValue({ sublistId: 'line', fieldId: 'location', value: locationD }); }catch(e){ log.debug("issue with department") } journalRecordCreate.commitLine({sublistId: 'line'}); } } } } /** * Defines the function that is executed when the reduce entry point is triggered. This entry point is triggered * automatically when the associated map stage is complete. This function is applied to each group in the provided context. * @param {Object} reduceContext - Data collection containing the groups to process in the reduce stage. This parameter is * provided automatically based on the results of the map stage. * @param {Iterator} reduceContext.errors - Serialized errors that were thrown during previous attempts to execute the * reduce function on the current group * @param {number} reduceContext.executionNo - Number of times the reduce function has been executed on the current group * @param {boolean} reduceContext.isRestarted - Indicates whether the current invocation of this function is the first * invocation (if true, the current invocation is not the first invocation and this function has been restarted) * @param {string} reduceContext.key - Key to be processed during the reduce stage * @param {List<String>} reduceContext.values - All values associated with a unique key that was passed to the reduce stage * for processing * @since 2015.2 */ function reduce (reduceContext) { } /** * Defines the function that is executed when the summarize entry point is triggered. This entry point is triggered * automatically when the associated reduce stage is complete. This function is applied to the entire result set. * @param {Object} summaryContext - Statistics about the execution of a map/reduce script * @param {number} summaryContext.concurrency - Maximum concurrency number when executing parallel tasks for the map/reduce * script * @param {Date} summaryContext.dateCreated - The date and time when the map/reduce script began running * @param {boolean} summaryContext.isRestarted - Indicates whether the current invocation of this function is the first * invocation (if true, the current invocation is not the first invocation and this function has been restarted) * @param {Iterator} summaryContext.output - Serialized keys and values that were saved as output during the reduce stage * @param {number} summaryContext.seconds - Total seconds elapsed when running the map/reduce script * @param {number} summaryContext.usage - Total number of governance usage units consumed when running the map/reduce * script * @param {number} summaryContext.yields - Total number of yields when running the map/reduce script * @param {Object} summaryContext.inputSummary - Statistics about the input stage * @param {Object} summaryContext.mapSummary - Statistics about the map stage * @param {Object} summaryContext.reduceSummary - Statistics about the reduce stage * @since 2015.2 */ function summarize (summaryContext) { } return { getInputData:getInputData, map:map, summarize:summarize } });
496
[{"tag": "EMAIL", "value": "rubykumari413@gmail.com", "start": 2993, "end": 3016}]
true
1
/** * @NApiVersion 2.0 * @NScriptType MapReduceScript */ define(['N/record', 'N/search', 'N/email', 'N/runtime'], /** * @param{record} record * @param{search} search */ function(record, search, email, runtime){ /** * Defines the function that is executed at the beginning of the map/reduce process and generates the input data. * @param {Object} inputContext * @param {boolean} inputContext.isRestarted - Indicates whether the current invocation of this function is the first * invocation (if true, the current invocation is not the first invocation and this function has been restarted) * @param {Object} inputContext.ObjectRef - Object that references the input data * @typedef {Object} ObjectRef * @property {string|number} ObjectRef.id - Internal ID of the record instance that contains the input data * @property {string} ObjectRef.type - Type of the record instance that contains the input data * @returns {Array|Object|Search|ObjectRef|File|Query} The input data to use in the map/reduce process * @since 2015.2 */ /*Global Variables*/ var departmentD; var classD; var locationD; function getInputData(inputContext){ var loadSearch = search.load({ id: 'customsearch_time_entry_to_post' }); return loadSearch; } /** * Defines the function that is executed when the map entry point is triggered. This entry point is triggered automatically * when the associated getInputData stage is complete. This function is applied to each key-value pair in the provided * context. * @param {Object} mapContext - Data collection containing the key-value pairs to process in the map stage. This parameter * is provided automatically based on the results of the getInputData stage. * @param {Iterator} mapContext.errors - Serialized errors that were thrown during previous attempts to execute the map * function on the current key-value pair * @param {number} mapContext.executionNo - Number of times the map function has been executed on the current key-value * pair * @param {boolean} mapContext.isRestarted - Indicates whether the current invocation of this function is the first * invocation (if true, the current invocation is not the first invocation and this function has been restarted) * @param {string} mapContext.key - Key to be processed during the map stage * @param {string} mapContext.value - Value to be processed during the map stage * @since 2015.2 */ function map(mapContext) { try { var accountCr = runtime.getCurrentScript().getParameter("custscript_proj_var_acct"); var currentUser = 239241; var currentUserEmail = 'hzdkv@example.com' var data = JSON.parse(mapContext.value); //log.debug('data',data) var id = data.id; var empName = data.values.employee.value; var custName = data.values.customer.value; var jrnalMemo = data.values.memo; var hours = data.values.hours; log.debug('Time sheet enterted for - ',id) hours = ''+hours.split(':')[0]+'.'+hours.split(':')[1]+''; var timebillCheck = search.lookupFields({ type:'timebill', id: id, columns: ['isbillable'] }); var billCbk = timebillCheck['isbillable']; var transactionCheck = search.lookupFields({ type:'employee', id: empName, columns: ['subsidiary','department','class','location','custentity_laborcost_usd'] }); var subsidaryD = transactionCheck['subsidiary'][0].value; var subsidaryText = transactionCheck['subsidiary'][0].text; try{ departmentD = transactionCheck['department'][0].value; classD = transactionCheck['class'][0].value; locationD = transactionCheck['location'][0].value; }catch(e){ log.debug('e',e) } var labourCost = transactionCheck['custentity_laborcost_usd']; var finalAmount = (Number(Number(hours)*Number(labourCost))).toFixed(2); var finalLineMemo = 'Time Entry for '+subsidaryText+'; memo:'+jrnalMemo+''; var jobCheck = search.lookupFields({ type:'job', id: custName, columns: ['currency','projectexpensetype'] }); var lvCurrency = jobCheck['currency'][0].value; var accountDr = jobCheck['projectexpensetype'][0].value; if(accountDr == '1'){accountDr = 913;}else if(accountDr == '2'){accountDr = 914;}else if(accountDr == -3){accountDr = 885;}else{accountDr = 884;} /* //// @@@@@@@@@@@@ Account Map @@@@@@@@@@@ //// Direct Salary == 61190 Project Direct Salary (895/913) Indirect Salary == Project Indirect Salary (896/914) Overhead == Indirect Labor (885) Regular == Direct Labor (884) //// @@@@@@@@@@@@ Account Map END @@@@@@@@@@@ ////*/ //creating journal record journalRecordCreate = record.create({ type: 'journalentry', isDynamic: true }); journalRecordCreate.setValue({ fieldId : 'subsidiary', value : subsidaryD }); journalRecordCreate.setValue({ fieldId : 'currency', value : lvCurrency }); journalRecordCreate.setValue({ fieldId : 'trandate', value : new Date() }); journalRecordCreate.setValue({ fieldId : 'approved', value : true }); journalRecordCreate.setValue({ fieldId : 'timebillflag', value : 'T' }); journalRecordCreate.setValue({ fieldId : 'custbody_sr_time_track_link', value : id }); var type = 'debit'; addLineDataOnJournalRecord(finalLineMemo,accountDr,finalAmount,type); var type = 'credit'; addLineDataOnJournalRecord(finalLineMemo,accountCr,finalAmount,type); try{ if(billCbk == false || billCbk == 'F' || billCbk == ''){ var journalRecordId = journalRecordCreate.save({ enableSourcing: true, ignoreMandatoryFields: true }); log.debug('journalRecordId',journalRecordId) /*var rec = record.load({type:'timebill',id:id}); rec.setValue({fieldId:'transactionid',value:Number(journalRecordId)}); rec.setValue({fieldId:'posted',value:true}); var recordSubmit = rec.save()*/ var recordSubmit = record.submitFields({ type: 'timebill', id: id, values: { 'posted': 'T', 'transactionid':Number(journalRecordId) }, options: { enableSourcing: true, ignoreMandatoryFields : true } }); log.debug('recordSubmit',recordSubmit) }else{ log.debug('its charges') } }catch(journalRecordSubmitError){ record.submitFields({ type: 'timebill', id: id, values: { 'posted': 'F' } }); log.error({title:'Error in journal Creation: ', details:journalRecordSubmitError}); email.send({author: currentUser, recipients: currentUserEmail, subject: 'Error while submitting journal for Time sheet: '+id+'', body: 'Hi,\n Error is:\n '+journalRecordSubmitError+'' }); } }catch(e){ log.debug('Error', e); } } function addLineDataOnJournalRecord(memo,account,ammount,type){ if(ammount != '' && ammount != undefined || ammount != null){ if(account != '' && account != undefined){ if(type == 'credit'){ var line = journalRecordCreate.getLineCount({ sublistId: 'line' }); journalRecordCreate.selectLine({ sublistId: 'line', line: line }); journalRecordCreate.setCurrentSublistValue({ sublistId: 'line', fieldId: 'account', value: account }); journalRecordCreate.setCurrentSublistValue({ sublistId: 'line', fieldId: 'credit', value: ammount }); journalRecordCreate.setCurrentSublistValue({ sublistId: 'line', fieldId: 'memo', value: memo }); try{ journalRecordCreate.setCurrentSublistValue({ sublistId: 'line', fieldId: 'department', value: departmentD }); journalRecordCreate.setCurrentSublistValue({ sublistId: 'line', fieldId: 'class', value: classD }); journalRecordCreate.setCurrentSublistValue({ sublistId: 'line', fieldId: 'location', value: locationD }); }catch(e){ log.debug("issue with department") } journalRecordCreate.commitLine({ sublistId: 'line'}); }else if(type == 'debit'){ var line = journalRecordCreate.getLineCount({ sublistId: 'line' }); journalRecordCreate.selectLine({ sublistId: 'line', line: line }); journalRecordCreate.setCurrentSublistValue({ sublistId: 'line', fieldId: 'account', value: account }); journalRecordCreate.setCurrentSublistValue({ sublistId: 'line', fieldId: 'debit', value: ammount }); journalRecordCreate.setCurrentSublistValue({ sublistId: 'line', fieldId: 'memo', value: memo }); try{ journalRecordCreate.setCurrentSublistValue({ sublistId: 'line', fieldId: 'department', value: departmentD }); journalRecordCreate.setCurrentSublistValue({ sublistId: 'line', fieldId: 'class', value: classD }); journalRecordCreate.setCurrentSublistValue({ sublistId: 'line', fieldId: 'location', value: locationD }); }catch(e){ log.debug("issue with department") } journalRecordCreate.commitLine({sublistId: 'line'}); } } } } /** * Defines the function that is executed when the reduce entry point is triggered. This entry point is triggered * automatically when the associated map stage is complete. This function is applied to each group in the provided context. * @param {Object} reduceContext - Data collection containing the groups to process in the reduce stage. This parameter is * provided automatically based on the results of the map stage. * @param {Iterator} reduceContext.errors - Serialized errors that were thrown during previous attempts to execute the * reduce function on the current group * @param {number} reduceContext.executionNo - Number of times the reduce function has been executed on the current group * @param {boolean} reduceContext.isRestarted - Indicates whether the current invocation of this function is the first * invocation (if true, the current invocation is not the first invocation and this function has been restarted) * @param {string} reduceContext.key - Key to be processed during the reduce stage * @param {List<String>} reduceContext.values - All values associated with a unique key that was passed to the reduce stage * for processing * @since 2015.2 */ function reduce (reduceContext) { } /** * Defines the function that is executed when the summarize entry point is triggered. This entry point is triggered * automatically when the associated reduce stage is complete. This function is applied to the entire result set. * @param {Object} summaryContext - Statistics about the execution of a map/reduce script * @param {number} summaryContext.concurrency - Maximum concurrency number when executing parallel tasks for the map/reduce * script * @param {Date} summaryContext.dateCreated - The date and time when the map/reduce script began running * @param {boolean} summaryContext.isRestarted - Indicates whether the current invocation of this function is the first * invocation (if true, the current invocation is not the first invocation and this function has been restarted) * @param {Iterator} summaryContext.output - Serialized keys and values that were saved as output during the reduce stage * @param {number} summaryContext.seconds - Total seconds elapsed when running the map/reduce script * @param {number} summaryContext.usage - Total number of governance usage units consumed when running the map/reduce * script * @param {number} summaryContext.yields - Total number of yields when running the map/reduce script * @param {Object} summaryContext.inputSummary - Statistics about the input stage * @param {Object} summaryContext.mapSummary - Statistics about the map stage * @param {Object} summaryContext.reduceSummary - Statistics about the reduce stage * @since 2015.2 */ function summarize (summaryContext) { } return { getInputData:getInputData, map:map, summarize:summarize } });
true
/** * @NApiVersion 2.0 * @NScriptType MapReduceScript */ define(['N/record', 'N/search', 'N/email', 'N/runtime'], /** * @param{record} record * @param{search} search */ function(record, search, email, runtime){ /** * Defines the function that is executed at the beginning of the map/reduce process and generates the input data. * @param {Object} inputContext * @param {boolean} inputContext.isRestarted - Indicates whether the current invocation of this function is the first * invocation (if true, the current invocation is not the first invocation and this function has been restarted) * @param {Object} inputContext.ObjectRef - Object that references the input data * @typedef {Object} ObjectRef * @property {string|number} ObjectRef.id - Internal ID of the record instance that contains the input data * @property {string} ObjectRef.type - Type of the record instance that contains the input data * @returns {Array|Object|Search|ObjectRef|File|Query} The input data to use in the map/reduce process * @since 2015.2 */ /*Global Variables*/ var departmentD; var classD; var locationD; function getInputData(inputContext){ var loadSearch = search.load({ id: 'customsearch_time_entry_to_post' }); return loadSearch; } /** * Defines the function that is executed when the map entry point is triggered. This entry point is triggered automatically * when the associated getInputData stage is complete. This function is applied to each key-value pair in the provided * context. * @param {Object} mapContext - Data collection containing the key-value pairs to process in the map stage. This parameter * is provided automatically based on the results of the getInputData stage. * @param {Iterator} mapContext.errors - Serialized errors that were thrown during previous attempts to execute the map * function on the current key-value pair * @param {number} mapContext.executionNo - Number of times the map function has been executed on the current key-value * pair * @param {boolean} mapContext.isRestarted - Indicates whether the current invocation of this function is the first * invocation (if true, the current invocation is not the first invocation and this function has been restarted) * @param {string} mapContext.key - Key to be processed during the map stage * @param {string} mapContext.value - Value to be processed during the map stage * @since 2015.2 */ function map(mapContext) { try { var accountCr = runtime.getCurrentScript().getParameter("custscript_proj_var_acct"); var currentUser = 239241; var currentUserEmail = 'PI:EMAIL:hzdkv@example.comEND_PI' var data = JSON.parse(mapContext.value); //log.debug('data',data) var id = data.id; var empName = data.values.employee.value; var custName = data.values.customer.value; var jrnalMemo = data.values.memo; var hours = data.values.hours; log.debug('Time sheet enterted for - ',id) hours = ''+hours.split(':')[0]+'.'+hours.split(':')[1]+''; var timebillCheck = search.lookupFields({ type:'timebill', id: id, columns: ['isbillable'] }); var billCbk = timebillCheck['isbillable']; var transactionCheck = search.lookupFields({ type:'employee', id: empName, columns: ['subsidiary','department','class','location','custentity_laborcost_usd'] }); var subsidaryD = transactionCheck['subsidiary'][0].value; var subsidaryText = transactionCheck['subsidiary'][0].text; try{ departmentD = transactionCheck['department'][0].value; classD = transactionCheck['class'][0].value; locationD = transactionCheck['location'][0].value; }catch(e){ log.debug('e',e) } var labourCost = transactionCheck['custentity_laborcost_usd']; var finalAmount = (Number(Number(hours)*Number(labourCost))).toFixed(2); var finalLineMemo = 'Time Entry for '+subsidaryText+'; memo:'+jrnalMemo+''; var jobCheck = search.lookupFields({ type:'job', id: custName, columns: ['currency','projectexpensetype'] }); var lvCurrency = jobCheck['currency'][0].value; var accountDr = jobCheck['projectexpensetype'][0].value; if(accountDr == '1'){accountDr = 913;}else if(accountDr == '2'){accountDr = 914;}else if(accountDr == -3){accountDr = 885;}else{accountDr = 884;} /* //// @@@@@@@@@@@@ Account Map @@@@@@@@@@@ //// Direct Salary == 61190 Project Direct Salary (895/913) Indirect Salary == Project Indirect Salary (896/914) Overhead == Indirect Labor (885) Regular == Direct Labor (884) //// @@@@@@@@@@@@ Account Map END @@@@@@@@@@@ ////*/ //creating journal record journalRecordCreate = record.create({ type: 'journalentry', isDynamic: true }); journalRecordCreate.setValue({ fieldId : 'subsidiary', value : subsidaryD }); journalRecordCreate.setValue({ fieldId : 'currency', value : lvCurrency }); journalRecordCreate.setValue({ fieldId : 'trandate', value : new Date() }); journalRecordCreate.setValue({ fieldId : 'approved', value : true }); journalRecordCreate.setValue({ fieldId : 'timebillflag', value : 'T' }); journalRecordCreate.setValue({ fieldId : 'custbody_sr_time_track_link', value : id }); var type = 'debit'; addLineDataOnJournalRecord(finalLineMemo,accountDr,finalAmount,type); var type = 'credit'; addLineDataOnJournalRecord(finalLineMemo,accountCr,finalAmount,type); try{ if(billCbk == false || billCbk == 'F' || billCbk == ''){ var journalRecordId = journalRecordCreate.save({ enableSourcing: true, ignoreMandatoryFields: true }); log.debug('journalRecordId',journalRecordId) /*var rec = record.load({type:'timebill',id:id}); rec.setValue({fieldId:'transactionid',value:Number(journalRecordId)}); rec.setValue({fieldId:'posted',value:true}); var recordSubmit = rec.save()*/ var recordSubmit = record.submitFields({ type: 'timebill', id: id, values: { 'posted': 'T', 'transactionid':Number(journalRecordId) }, options: { enableSourcing: true, ignoreMandatoryFields : true } }); log.debug('recordSubmit',recordSubmit) }else{ log.debug('its charges') } }catch(journalRecordSubmitError){ record.submitFields({ type: 'timebill', id: id, values: { 'posted': 'F' } }); log.error({title:'Error in journal Creation: ', details:journalRecordSubmitError}); email.send({author: currentUser, recipients: currentUserEmail, subject: 'Error while submitting journal for Time sheet: '+id+'', body: 'Hi,\n Error is:\n '+journalRecordSubmitError+'' }); } }catch(e){ log.debug('Error', e); } } function addLineDataOnJournalRecord(memo,account,ammount,type){ if(ammount != '' && ammount != undefined || ammount != null){ if(account != '' && account != undefined){ if(type == 'credit'){ var line = journalRecordCreate.getLineCount({ sublistId: 'line' }); journalRecordCreate.selectLine({ sublistId: 'line', line: line }); journalRecordCreate.setCurrentSublistValue({ sublistId: 'line', fieldId: 'account', value: account }); journalRecordCreate.setCurrentSublistValue({ sublistId: 'line', fieldId: 'credit', value: ammount }); journalRecordCreate.setCurrentSublistValue({ sublistId: 'line', fieldId: 'memo', value: memo }); try{ journalRecordCreate.setCurrentSublistValue({ sublistId: 'line', fieldId: 'department', value: departmentD }); journalRecordCreate.setCurrentSublistValue({ sublistId: 'line', fieldId: 'class', value: classD }); journalRecordCreate.setCurrentSublistValue({ sublistId: 'line', fieldId: 'location', value: locationD }); }catch(e){ log.debug("issue with department") } journalRecordCreate.commitLine({ sublistId: 'line'}); }else if(type == 'debit'){ var line = journalRecordCreate.getLineCount({ sublistId: 'line' }); journalRecordCreate.selectLine({ sublistId: 'line', line: line }); journalRecordCreate.setCurrentSublistValue({ sublistId: 'line', fieldId: 'account', value: account }); journalRecordCreate.setCurrentSublistValue({ sublistId: 'line', fieldId: 'debit', value: ammount }); journalRecordCreate.setCurrentSublistValue({ sublistId: 'line', fieldId: 'memo', value: memo }); try{ journalRecordCreate.setCurrentSublistValue({ sublistId: 'line', fieldId: 'department', value: departmentD }); journalRecordCreate.setCurrentSublistValue({ sublistId: 'line', fieldId: 'class', value: classD }); journalRecordCreate.setCurrentSublistValue({ sublistId: 'line', fieldId: 'location', value: locationD }); }catch(e){ log.debug("issue with department") } journalRecordCreate.commitLine({sublistId: 'line'}); } } } } /** * Defines the function that is executed when the reduce entry point is triggered. This entry point is triggered * automatically when the associated map stage is complete. This function is applied to each group in the provided context. * @param {Object} reduceContext - Data collection containing the groups to process in the reduce stage. This parameter is * provided automatically based on the results of the map stage. * @param {Iterator} reduceContext.errors - Serialized errors that were thrown during previous attempts to execute the * reduce function on the current group * @param {number} reduceContext.executionNo - Number of times the reduce function has been executed on the current group * @param {boolean} reduceContext.isRestarted - Indicates whether the current invocation of this function is the first * invocation (if true, the current invocation is not the first invocation and this function has been restarted) * @param {string} reduceContext.key - Key to be processed during the reduce stage * @param {List<String>} reduceContext.values - All values associated with a unique key that was passed to the reduce stage * for processing * @since 2015.2 */ function reduce (reduceContext) { } /** * Defines the function that is executed when the summarize entry point is triggered. This entry point is triggered * automatically when the associated reduce stage is complete. This function is applied to the entire result set. * @param {Object} summaryContext - Statistics about the execution of a map/reduce script * @param {number} summaryContext.concurrency - Maximum concurrency number when executing parallel tasks for the map/reduce * script * @param {Date} summaryContext.dateCreated - The date and time when the map/reduce script began running * @param {boolean} summaryContext.isRestarted - Indicates whether the current invocation of this function is the first * invocation (if true, the current invocation is not the first invocation and this function has been restarted) * @param {Iterator} summaryContext.output - Serialized keys and values that were saved as output during the reduce stage * @param {number} summaryContext.seconds - Total seconds elapsed when running the map/reduce script * @param {number} summaryContext.usage - Total number of governance usage units consumed when running the map/reduce * script * @param {number} summaryContext.yields - Total number of yields when running the map/reduce script * @param {Object} summaryContext.inputSummary - Statistics about the input stage * @param {Object} summaryContext.mapSummary - Statistics about the map stage * @param {Object} summaryContext.reduceSummary - Statistics about the reduce stage * @since 2015.2 */ function summarize (summaryContext) { } return { getInputData:getInputData, map:map, summarize:summarize } });
/** * @NScriptName Geocoding Script * @NApiVersion 2.x * @NScriptType Suitelet * @NModuleScope SameAccount */ define(["require", "exports", "N/search", "N/ui/serverWidget"], function (require, exports, search, ui) { Object.defineProperty(exports, "__esModule", { value: true }); function onRequest(context) { if (context.request.method === "GET") { var chartOptions = { //backgroundColor: '#5786ff', //datalessRegionColor: "#F5F5F5", colorAxis: { minValue: 0, /*colors: ['yellow', 'red']*/ } }; var savedSearch = search.load({ id: 'customsearch_da_students_by_country_of_b', }).run(); var tempResults = void 0, results = [], lastIndex = 0; do { tempResults = savedSearch.getRange({ start: lastIndex, end: lastIndex + 1000 }); if (tempResults) { results = results.concat(tempResults); lastIndex += 1000; } } while (tempResults && tempResults.length === 1000); var data = []; data.push(["Country", "Popularity"]); // Header for (var i = 0; i < results.length; i++) { var values = results[i].getAllValues(); var countryName = values["GROUP(custentity_da_nationality_geo_code)"][0]["text"]; var countryCode = values["GROUP(custentity_da_nationality_geo_code)"][0]["value"]; var count = Number(values["COUNT(internalid)"]); data.push([countryName, count]); } var html = "\n <script type=\"text/javascript\" src=\"https://www.gstatic.com/charts/loader.js\"></script>\n <div id=\"map_regions_div\" style=\"width: 80%; height: 500px; margin: 0 auto;\"></div>\n <script type=\"text/javascript\">\n google.charts.load('current', {\n 'packages':['geochart'],\n 'mapsApiKey': 'AIzaSyD-9tSrke72PouQMnMX-a7eZSW0jkFMBWY'\n });\n google.charts.setOnLoadCallback(drawRegionsMap);\n \n function drawRegionsMap() {\n var data = google.visualization.arrayToDataTable(" + JSON.stringify(data) + ");\n \n var options = " + JSON.stringify(chartOptions) + ";\n \n var chart = new google.visualization.GeoChart(document.getElementById('map_regions_div'));\n\n chart.draw(data, options);\n }\n </script>"; var form = ui.createForm({ title: 'Students by Country of Birth', hideNavBar: true }); var chartField = form.addField({ id: 'google_map_chart_html', label: 'Students by Country of Birth', type: ui.FieldType.INLINEHTML }); chartField.defaultValue = html; context.response.writePage(form); } } exports.onRequest = onRequest; });
781
[{"tag": "KEY", "value": "AIzaSyD-9tSrke72PouQMnMX-a7eZSW0jkFMBWY", "start": 2080, "end": 2119}]
true
1
/** * @NScriptName Geocoding Script * @NApiVersion 2.x * @NScriptType Suitelet * @NModuleScope SameAccount */ define(["require", "exports", "N/search", "N/ui/serverWidget"], function (require, exports, search, ui) { Object.defineProperty(exports, "__esModule", { value: true }); function onRequest(context) { if (context.request.method === "GET") { var chartOptions = { //backgroundColor: '#5786ff', //datalessRegionColor: "#F5F5F5", colorAxis: { minValue: 0, /*colors: ['yellow', 'red']*/ } }; var savedSearch = search.load({ id: 'customsearch_da_students_by_country_of_b', }).run(); var tempResults = void 0, results = [], lastIndex = 0; do { tempResults = savedSearch.getRange({ start: lastIndex, end: lastIndex + 1000 }); if (tempResults) { results = results.concat(tempResults); lastIndex += 1000; } } while (tempResults && tempResults.length === 1000); var data = []; data.push(["Country", "Popularity"]); // Header for (var i = 0; i < results.length; i++) { var values = results[i].getAllValues(); var countryName = values["GROUP(custentity_da_nationality_geo_code)"][0]["text"]; var countryCode = values["GROUP(custentity_da_nationality_geo_code)"][0]["value"]; var count = Number(values["COUNT(internalid)"]); data.push([countryName, count]); } var html = "\n <script type=\"text/javascript\" src=\"https://www.gstatic.com/charts/loader.js\"></script>\n <div id=\"map_regions_div\" style=\"width: 80%; height: 500px; margin: 0 auto;\"></div>\n <script type=\"text/javascript\">\n google.charts.load('current', {\n 'packages':['geochart'],\n 'mapsApiKey': '74t3tndxag9o7h0890bnpfzh4olk2h9x'\n });\n google.charts.setOnLoadCallback(drawRegionsMap);\n \n function drawRegionsMap() {\n var data = google.visualization.arrayToDataTable(" + JSON.stringify(data) + ");\n \n var options = " + JSON.stringify(chartOptions) + ";\n \n var chart = new google.visualization.GeoChart(document.getElementById('map_regions_div'));\n\n chart.draw(data, options);\n }\n </script>"; var form = ui.createForm({ title: 'Students by Country of Birth', hideNavBar: true }); var chartField = form.addField({ id: 'google_map_chart_html', label: 'Students by Country of Birth', type: ui.FieldType.INLINEHTML }); chartField.defaultValue = html; context.response.writePage(form); } } exports.onRequest = onRequest; });
true
/** * @NScriptName Geocoding Script * @NApiVersion 2.x * @NScriptType Suitelet * @NModuleScope SameAccount */ define(["require", "exports", "N/search", "N/ui/serverWidget"], function (require, exports, search, ui) { Object.defineProperty(exports, "__esModule", { value: true }); function onRequest(context) { if (context.request.method === "GET") { var chartOptions = { //backgroundColor: '#5786ff', //datalessRegionColor: "#F5F5F5", colorAxis: { minValue: 0, /*colors: ['yellow', 'red']*/ } }; var savedSearch = search.load({ id: 'customsearch_da_students_by_country_of_b', }).run(); var tempResults = void 0, results = [], lastIndex = 0; do { tempResults = savedSearch.getRange({ start: lastIndex, end: lastIndex + 1000 }); if (tempResults) { results = results.concat(tempResults); lastIndex += 1000; } } while (tempResults && tempResults.length === 1000); var data = []; data.push(["Country", "Popularity"]); // Header for (var i = 0; i < results.length; i++) { var values = results[i].getAllValues(); var countryName = values["GROUP(custentity_da_nationality_geo_code)"][0]["text"]; var countryCode = values["GROUP(custentity_da_nationality_geo_code)"][0]["value"]; var count = Number(values["COUNT(internalid)"]); data.push([countryName, count]); } var html = "\n <script type=\"text/javascript\" src=\"https://www.gstatic.com/charts/loader.js\"></script>\n <div id=\"map_regions_div\" style=\"width: 80%; height: 500px; margin: 0 auto;\"></div>\n <script type=\"text/javascript\">\n google.charts.load('current', {\n 'packages':['geochart'],\n 'mapsApiKey': 'PI:KEY:74t3tndxag9o7h0890bnpfzh4olk2h9xEND_PI'\n });\n google.charts.setOnLoadCallback(drawRegionsMap);\n \n function drawRegionsMap() {\n var data = google.visualization.arrayToDataTable(" + JSON.stringify(data) + ");\n \n var options = " + JSON.stringify(chartOptions) + ";\n \n var chart = new google.visualization.GeoChart(document.getElementById('map_regions_div'));\n\n chart.draw(data, options);\n }\n </script>"; var form = ui.createForm({ title: 'Students by Country of Birth', hideNavBar: true }); var chartField = form.addField({ id: 'google_map_chart_html', label: 'Students by Country of Birth', type: ui.FieldType.INLINEHTML }); chartField.defaultValue = html; context.response.writePage(form); } } exports.onRequest = onRequest; });
/** * REST API for R+L CARRIERS * * @NApiVersion 2.x * @NScriptType Restlet * @author trungpv <trung@lexor.com> */ define(["N/https", "N/search", "N/xml", "/SuiteScripts/Module/Utils"], function( https, search, xml, _U ) { /** VARS **/ const ADDITIONAL_FEES = 10; // 10% const API_KEY = "xxx"; /** * POST * @param {*} context */ function postAction(context) { var result = {}; result.success = false; try { const validation = doValidation( [context.locationId, context.customer, context.weight], ["locationId", "customer", "weight"], "POST" ); if (validation.length === 0) { const originAddress = search.lookupFields({ type: search.Type.LOCATION, id: context.locationId, columns: ["city", "country", "zip", "state"] }); // Set countryCode if (originAddress.country === "US") { originAddress.countryCode = "USA"; } else if (originAddress.country === "CA") { originAddress.countryCode = "CAN"; } // Check State if (originAddress.state.length > 2) { originAddress.state = _U.abbrRegion(originAddress.state, "abbr"); } if (context.customer.state.length > 2) { context.customer.state = _U.abbrRegion( context.customer.state, "abbr" ); } const freightRate = getFreightRate( originAddress, context.customer, context.weight ); result.data = { freightRate: freightRate }; result.success = true; result.message = "Success!"; } else { result.message = "Something went wrong with your params."; result.errors = validation; } } catch (err) { result.message = err.message; } return JSON.stringify(result); } /** HEPPER FUNCTIONS **/ /** * Validation params * @param {*} args * @param {*} argNames * @param {*} methodName */ function doValidation(args, argNames, methodName) { const result = []; for (var i = 0; i < args.length; i++) { if (!args[i] && args[i] !== 0) { result.push( "Missing a required argument: [" + argNames[i] + "] for method: " + methodName ); } } return result; } /** * Build Payload Shipping Method https://api.rlcarriers.com/1.0.3/RateQuoteService.asmx */ function requestPayload(origin, destination, weight) { var payload = '<soapenv:Envelope xmlns:soapenv="http://schemas.xmlsoap.org/soap/envelope/" xmlns:rlc="http://www.rlcarriers.com/">'; payload += "<soapenv:Header/>"; payload += "<soapenv:Body>"; payload += " <rlc:GetRateQuote>"; payload += " <rlc:APIKey>" + API_KEY + "</rlc:APIKey>"; payload += " <rlc:request>"; payload += " <rlc:QuoteType>Domestic</rlc:QuoteType>"; payload += " <rlc:CODAmount>0</rlc:CODAmount>"; payload += " <rlc:Origin>"; payload += " <rlc:City>" + origin.city + "</rlc:City>"; payload += " <rlc:StateOrProvince>" + origin.state + "</rlc:StateOrProvince>"; payload += " <rlc:ZipOrPostalCode>" + origin.zip + "</rlc:ZipOrPostalCode>"; payload += " <rlc:CountryCode>" + origin.countryCode + "</rlc:CountryCode>"; payload += " </rlc:Origin>"; payload += " <rlc:Destination>"; payload += " <rlc:City>" + destination.city + "</rlc:City>"; payload += " <rlc:StateOrProvince>" + destination.state + "</rlc:StateOrProvince>"; payload += " <rlc:ZipOrPostalCode>" + destination.zip + "</rlc:ZipOrPostalCode>"; payload += " <rlc:CountryCode>" + destination.countryCode + "</rlc:CountryCode>"; payload += " </rlc:Destination>"; payload += " <rlc:Items>"; payload += " <rlc:Item>"; payload += " <rlc:Class>200.0</rlc:Class>"; payload += " <rlc:Weight>" + weight + "</rlc:Weight>"; payload += " <rlc:Width>0</rlc:Width>"; payload += " <rlc:Height>0</rlc:Height>"; payload += " <rlc:Length>0</rlc:Length>"; payload += " </rlc:Item>"; payload += " </rlc:Items>"; payload += " <rlc:DeclaredValue>0</rlc:DeclaredValue>"; payload += " <rlc:Accessorials></rlc:Accessorials>"; payload += " <rlc:OverDimensionList></rlc:OverDimensionList>"; payload += " <rlc:Pallets></rlc:Pallets>"; payload += " </rlc:request>"; payload += " </rlc:GetRateQuote>"; payload += " </soapenv:Body>"; payload += "</soapenv:Envelope>"; return payload; } /** * get Freight Rate * @param {*} origin * @param {*} destination * @param {*} weight */ function getFreightRate(origin, destination, weight) { const payload = requestPayload(origin, destination, weight); try { var res = https.post({ url: "https://api.rlcarriers.com/1.0.3/RateQuoteService.asmx", body: payload, headers: { "Content-Type": "text/xml; charset=UTF-8" } }); if (res.code === 200) { var resXML = xml.Parser.fromString({ text: res.body }); var ServiceLevels = resXML.getElementsByTagName({ tagName: "ServiceLevels" }); if (ServiceLevels.length > 0) { var NetCharge = ServiceLevels[0].getElementsByTagName({ tagName: "NetCharge" }); if (NetCharge.length > 0) { var nCharge = NetCharge[0].textContent.replace("$", "").replace(",", ""); nCharge = parseFloat(nCharge) + parseFloat(nCharge) * (ADDITIONAL_FEES / 100); nCharge = parseFloat(nCharge).toFixed(2); return nCharge; } } } } catch (error) { return 0; } return 0; } /** * Export Events */ var exports = {}; exports.post = postAction; return exports; });
593
[{"tag": "EMAIL", "value": "trung@lexor.com", "start": 100, "end": 115}]
true
1
/** * REST API for R+L CARRIERS * * @NApiVersion 2.x * @NScriptType Restlet * @author trungpv <efpyi@example.com> */ define(["N/https", "N/search", "N/xml", "/SuiteScripts/Module/Utils"], function( https, search, xml, _U ) { /** VARS **/ const ADDITIONAL_FEES = 10; // 10% const API_KEY = "xxx"; /** * POST * @param {*} context */ function postAction(context) { var result = {}; result.success = false; try { const validation = doValidation( [context.locationId, context.customer, context.weight], ["locationId", "customer", "weight"], "POST" ); if (validation.length === 0) { const originAddress = search.lookupFields({ type: search.Type.LOCATION, id: context.locationId, columns: ["city", "country", "zip", "state"] }); // Set countryCode if (originAddress.country === "US") { originAddress.countryCode = "USA"; } else if (originAddress.country === "CA") { originAddress.countryCode = "CAN"; } // Check State if (originAddress.state.length > 2) { originAddress.state = _U.abbrRegion(originAddress.state, "abbr"); } if (context.customer.state.length > 2) { context.customer.state = _U.abbrRegion( context.customer.state, "abbr" ); } const freightRate = getFreightRate( originAddress, context.customer, context.weight ); result.data = { freightRate: freightRate }; result.success = true; result.message = "Success!"; } else { result.message = "Something went wrong with your params."; result.errors = validation; } } catch (err) { result.message = err.message; } return JSON.stringify(result); } /** HEPPER FUNCTIONS **/ /** * Validation params * @param {*} args * @param {*} argNames * @param {*} methodName */ function doValidation(args, argNames, methodName) { const result = []; for (var i = 0; i < args.length; i++) { if (!args[i] && args[i] !== 0) { result.push( "Missing a required argument: [" + argNames[i] + "] for method: " + methodName ); } } return result; } /** * Build Payload Shipping Method https://api.rlcarriers.com/1.0.3/RateQuoteService.asmx */ function requestPayload(origin, destination, weight) { var payload = '<soapenv:Envelope xmlns:soapenv="http://schemas.xmlsoap.org/soap/envelope/" xmlns:rlc="http://www.rlcarriers.com/">'; payload += "<soapenv:Header/>"; payload += "<soapenv:Body>"; payload += " <rlc:GetRateQuote>"; payload += " <rlc:APIKey>" + API_KEY + "</rlc:APIKey>"; payload += " <rlc:request>"; payload += " <rlc:QuoteType>Domestic</rlc:QuoteType>"; payload += " <rlc:CODAmount>0</rlc:CODAmount>"; payload += " <rlc:Origin>"; payload += " <rlc:City>" + origin.city + "</rlc:City>"; payload += " <rlc:StateOrProvince>" + origin.state + "</rlc:StateOrProvince>"; payload += " <rlc:ZipOrPostalCode>" + origin.zip + "</rlc:ZipOrPostalCode>"; payload += " <rlc:CountryCode>" + origin.countryCode + "</rlc:CountryCode>"; payload += " </rlc:Origin>"; payload += " <rlc:Destination>"; payload += " <rlc:City>" + destination.city + "</rlc:City>"; payload += " <rlc:StateOrProvince>" + destination.state + "</rlc:StateOrProvince>"; payload += " <rlc:ZipOrPostalCode>" + destination.zip + "</rlc:ZipOrPostalCode>"; payload += " <rlc:CountryCode>" + destination.countryCode + "</rlc:CountryCode>"; payload += " </rlc:Destination>"; payload += " <rlc:Items>"; payload += " <rlc:Item>"; payload += " <rlc:Class>200.0</rlc:Class>"; payload += " <rlc:Weight>" + weight + "</rlc:Weight>"; payload += " <rlc:Width>0</rlc:Width>"; payload += " <rlc:Height>0</rlc:Height>"; payload += " <rlc:Length>0</rlc:Length>"; payload += " </rlc:Item>"; payload += " </rlc:Items>"; payload += " <rlc:DeclaredValue>0</rlc:DeclaredValue>"; payload += " <rlc:Accessorials></rlc:Accessorials>"; payload += " <rlc:OverDimensionList></rlc:OverDimensionList>"; payload += " <rlc:Pallets></rlc:Pallets>"; payload += " </rlc:request>"; payload += " </rlc:GetRateQuote>"; payload += " </soapenv:Body>"; payload += "</soapenv:Envelope>"; return payload; } /** * get Freight Rate * @param {*} origin * @param {*} destination * @param {*} weight */ function getFreightRate(origin, destination, weight) { const payload = requestPayload(origin, destination, weight); try { var res = https.post({ url: "https://api.rlcarriers.com/1.0.3/RateQuoteService.asmx", body: payload, headers: { "Content-Type": "text/xml; charset=UTF-8" } }); if (res.code === 200) { var resXML = xml.Parser.fromString({ text: res.body }); var ServiceLevels = resXML.getElementsByTagName({ tagName: "ServiceLevels" }); if (ServiceLevels.length > 0) { var NetCharge = ServiceLevels[0].getElementsByTagName({ tagName: "NetCharge" }); if (NetCharge.length > 0) { var nCharge = NetCharge[0].textContent.replace("$", "").replace(",", ""); nCharge = parseFloat(nCharge) + parseFloat(nCharge) * (ADDITIONAL_FEES / 100); nCharge = parseFloat(nCharge).toFixed(2); return nCharge; } } } } catch (error) { return 0; } return 0; } /** * Export Events */ var exports = {}; exports.post = postAction; return exports; });
true
/** * REST API for R+L CARRIERS * * @NApiVersion 2.x * @NScriptType Restlet * @author trungpv <PI:EMAIL:efpyi@example.comEND_PI> */ define(["N/https", "N/search", "N/xml", "/SuiteScripts/Module/Utils"], function( https, search, xml, _U ) { /** VARS **/ const ADDITIONAL_FEES = 10; // 10% const API_KEY = "xxx"; /** * POST * @param {*} context */ function postAction(context) { var result = {}; result.success = false; try { const validation = doValidation( [context.locationId, context.customer, context.weight], ["locationId", "customer", "weight"], "POST" ); if (validation.length === 0) { const originAddress = search.lookupFields({ type: search.Type.LOCATION, id: context.locationId, columns: ["city", "country", "zip", "state"] }); // Set countryCode if (originAddress.country === "US") { originAddress.countryCode = "USA"; } else if (originAddress.country === "CA") { originAddress.countryCode = "CAN"; } // Check State if (originAddress.state.length > 2) { originAddress.state = _U.abbrRegion(originAddress.state, "abbr"); } if (context.customer.state.length > 2) { context.customer.state = _U.abbrRegion( context.customer.state, "abbr" ); } const freightRate = getFreightRate( originAddress, context.customer, context.weight ); result.data = { freightRate: freightRate }; result.success = true; result.message = "Success!"; } else { result.message = "Something went wrong with your params."; result.errors = validation; } } catch (err) { result.message = err.message; } return JSON.stringify(result); } /** HEPPER FUNCTIONS **/ /** * Validation params * @param {*} args * @param {*} argNames * @param {*} methodName */ function doValidation(args, argNames, methodName) { const result = []; for (var i = 0; i < args.length; i++) { if (!args[i] && args[i] !== 0) { result.push( "Missing a required argument: [" + argNames[i] + "] for method: " + methodName ); } } return result; } /** * Build Payload Shipping Method https://api.rlcarriers.com/1.0.3/RateQuoteService.asmx */ function requestPayload(origin, destination, weight) { var payload = '<soapenv:Envelope xmlns:soapenv="http://schemas.xmlsoap.org/soap/envelope/" xmlns:rlc="http://www.rlcarriers.com/">'; payload += "<soapenv:Header/>"; payload += "<soapenv:Body>"; payload += " <rlc:GetRateQuote>"; payload += " <rlc:APIKey>" + API_KEY + "</rlc:APIKey>"; payload += " <rlc:request>"; payload += " <rlc:QuoteType>Domestic</rlc:QuoteType>"; payload += " <rlc:CODAmount>0</rlc:CODAmount>"; payload += " <rlc:Origin>"; payload += " <rlc:City>" + origin.city + "</rlc:City>"; payload += " <rlc:StateOrProvince>" + origin.state + "</rlc:StateOrProvince>"; payload += " <rlc:ZipOrPostalCode>" + origin.zip + "</rlc:ZipOrPostalCode>"; payload += " <rlc:CountryCode>" + origin.countryCode + "</rlc:CountryCode>"; payload += " </rlc:Origin>"; payload += " <rlc:Destination>"; payload += " <rlc:City>" + destination.city + "</rlc:City>"; payload += " <rlc:StateOrProvince>" + destination.state + "</rlc:StateOrProvince>"; payload += " <rlc:ZipOrPostalCode>" + destination.zip + "</rlc:ZipOrPostalCode>"; payload += " <rlc:CountryCode>" + destination.countryCode + "</rlc:CountryCode>"; payload += " </rlc:Destination>"; payload += " <rlc:Items>"; payload += " <rlc:Item>"; payload += " <rlc:Class>200.0</rlc:Class>"; payload += " <rlc:Weight>" + weight + "</rlc:Weight>"; payload += " <rlc:Width>0</rlc:Width>"; payload += " <rlc:Height>0</rlc:Height>"; payload += " <rlc:Length>0</rlc:Length>"; payload += " </rlc:Item>"; payload += " </rlc:Items>"; payload += " <rlc:DeclaredValue>0</rlc:DeclaredValue>"; payload += " <rlc:Accessorials></rlc:Accessorials>"; payload += " <rlc:OverDimensionList></rlc:OverDimensionList>"; payload += " <rlc:Pallets></rlc:Pallets>"; payload += " </rlc:request>"; payload += " </rlc:GetRateQuote>"; payload += " </soapenv:Body>"; payload += "</soapenv:Envelope>"; return payload; } /** * get Freight Rate * @param {*} origin * @param {*} destination * @param {*} weight */ function getFreightRate(origin, destination, weight) { const payload = requestPayload(origin, destination, weight); try { var res = https.post({ url: "https://api.rlcarriers.com/1.0.3/RateQuoteService.asmx", body: payload, headers: { "Content-Type": "text/xml; charset=UTF-8" } }); if (res.code === 200) { var resXML = xml.Parser.fromString({ text: res.body }); var ServiceLevels = resXML.getElementsByTagName({ tagName: "ServiceLevels" }); if (ServiceLevels.length > 0) { var NetCharge = ServiceLevels[0].getElementsByTagName({ tagName: "NetCharge" }); if (NetCharge.length > 0) { var nCharge = NetCharge[0].textContent.replace("$", "").replace(",", ""); nCharge = parseFloat(nCharge) + parseFloat(nCharge) * (ADDITIONAL_FEES / 100); nCharge = parseFloat(nCharge).toFixed(2); return nCharge; } } } } catch (error) { return 0; } return 0; } /** * Export Events */ var exports = {}; exports.post = postAction; return exports; });
/** * @NApiVersion 2.0 * @NScriptType Suitelet * * Module Description * * NSVersion Date Author * 2.00 2021-09-20 09:33:08 Anesu * * Description: xxxxxxxx * * @Last Modified by: Anesu * @Last Modified time: 2021-09-20 09:33:08 * */ define(['N/ui/serverWidget', 'N/email', 'N/runtime', 'N/search', 'N/record', 'N/http', 'N/log', 'N/redirect', 'N/task', 'N/format'], function(ui, email, runtime, search, record, http, log, redirect, task, format) { var zee = 0; var role = 0; var baseURL = 'https://1048144.app.netsuite.com'; if (runtime.EnvType == "SANDBOX") { baseURL = 'https://1048144-sb3.app.netsuite.com'; } role = runtime.getCurrentUser().role; if (role == 1000) { zee = runtime.getCurrentUser().id; } else if (role == 3) { //Administrator zee = 6; //test } else if (role == 1032) { // System Support zee = 425904; //test-AR } function onRequest(context) { if (context.request.method === 'GET') { type = context.request.parameters.type; var params_params = context.request.parameters; if (!isNullorEmpty(params_params.custparam_params)) { var params = JSON.parse(context.request.parameters.custparam_params); log.debug({ title: 'Params', details: params }) } var zee_id = 0; var commReg = 0; var cust_id = 0; var new_commReg = false; var header = 'Edit'; if (!isNullorEmpty(params)) { zee_id = parseInt(params.zeeid); commReg = parseInt(params.commreg); cust_id = parseInt(params.custid) new_commReg = Boolean(params.new); } if (new_commReg == true) { commReg = 0; header = 'New' } var form = ui.createForm({ title: " " }); // Load jQuery // var inlineHtml = '<script src="https://code.jquery.com/jquery-1.12.4.min.js" integrity="sha384-nvAa0+6Qg9clwYCGGPpDQLVpLNn0fRaROjHqs13t4Ggj3Ez50XnGQqc/r8MhnRDZ" crossorigin="anonymous"></script>'; var inlineHtml = '<script src="https://code.jquery.com/jquery-3.5.0.js" crossorigin="anonymous"></script>'; // Load Tooltip inlineHtml += '<script src="https://unpkg.com/@popperjs/core@2"></script>'; // Load Bootstrap inlineHtml += '<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/3.4.1/css/bootstrap.min.css" integrity="sha384-HSMxcRTRxnN+Bdg0JdbxYKrThecOKuH5zCYotlSAcp1+c8xmyTe9GYg1l9a69psu" crossorigin="anonymous">'; inlineHtml += '<script src="https://stackpath.bootstrapcdn.com/bootstrap/3.4.1/js/bootstrap.min.js" integrity="sha384-aJ21OjlMXNL5UyIl/XNwTMqvzeRMZH2w8c5cRVpzpU8Y5bApTppSuUkhZXN0VxHd" crossorigin="anonymous"></script>'; // Load DataTables inlineHtml += '<link rel="stylesheet" type="text/css" href="//cdn.datatables.net/1.10.21/css/jquery.dataTables.min.css">'; inlineHtml += '<script type="text/javascript" charset="utf8" src="//cdn.datatables.net/1.10.21/js/jquery.dataTables.min.js"></script>'; inlineHtml += '<script type="text/javascript" charset="utf8" src="//cdn.datatables.net/rowgroup/1.1.3/js/dataTables.rowGroup.min.js"></script> '; inlineHtml += '<script type="text/javascript" charset="utf8" src="//cdn.datatables.net/buttons/2.0.0/js/dataTables.buttons.min.js"></script> '; inlineHtml += '<script type="text/javascript" charset="utf8" src="//cdnjs.cloudflare.com/ajax/libs/jszip/3.1.3/jszip.min.js"></script> '; inlineHtml += '<script type="text/javascript" charset="utf8" src="//cdnjs.cloudflare.com/ajax/libs/pdfmake/0.1.53/pdfmake.min.js"></script> '; inlineHtml += '<script type="text/javascript" charset="utf8" src="//cdnjs.cloudflare.com/ajax/libs/pdfmake/0.1.53/vfs_fonts.js"></script> '; inlineHtml += '<script type="text/javascript" charset="utf8" src="//cdn.datatables.net/buttons/2.0.0/js/buttons.html5.min.js"></script> '; inlineHtml += '<script type="text/javascript" charset="utf8" src="//cdn.datatables.net/buttons/2.0.0/js/buttons.print.min.js"></script> '; // Load Netsuite stylesheet and script inlineHtml += '<link rel="stylesheet" href="https://1048144.app.netsuite.com/core/media/media.nl?id=2060796&c=1048144&h=9ee6accfd476c9cae718&_xt=.css"/>'; inlineHtml += '<script src="https://1048144.app.netsuite.com/core/media/media.nl?id=2060797&c=1048144&h=ef2cda20731d146b5e98&_xt=.js"></script>'; inlineHtml += '<link type="text/css" rel="stylesheet" href="https://1048144.app.netsuite.com/core/media/media.nl?id=2090583&c=1048144&h=a0ef6ac4e28f91203dfe&_xt=.css">'; inlineHtml += "<style>.mandatory{color:red;}</style>"; // Load Bootstrap-Select inlineHtml += '<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap-select@1.13.14/dist/css/bootstrap-select.min.css">'; inlineHtml += '<script src="https://cdn.jsdelivr.net/npm/bootstrap-select@1.13.14/dist/js/bootstrap-select.min.js"></script>'; // Semantic Select inlineHtml += '<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/semantic-ui/2.2.13/semantic.min.css">'; inlineHtml += '<script src="https://cdnjs.cloudflare.com/ajax/libs/semantic-ui/2.2.13/semantic.min.js"></script>'; // Load Search In Dropdown // inlineHtml += '<link href="https://cdnjs.cloudflare.com/ajax/libs/select2/4.0.6-rc.0/css/select2.min.css" rel="stylesheet" />'; // inlineHtml += '<script src="https://cdnjs.cloudflare.com/ajax/libs/select2/4.0.6-rc.0/js/select2.min.js"></script>'; // New Website Color Schemes // Main Color: #379E8F // Background Color: #CFE0CE // Button Color: #FBEA51 // Text Color: #103D39 inlineHtml += '<div class="a" style="width: 100%; background-color: #CFE0CE; padding: 20px; min-height: 100vh; height: 100%; ">'; // margin-top: -40px // inlineHtml += '<h1 style="text-align: center; color: #103D39; display: inline-block; font-size: 22px; font-weight: bold; line-height: 33px; vertical-align: top; margin-bottom: 4px;">Scheduled Price Change: Finance Team</h1>'; inlineHtml += '<style>.nav > li.active > a, .nav > li.active > a:focus, .nav > li.active > a:hover { background-color: #379E8F; color: #fff }'; inlineHtml += '.nav > li > a, .nav > li > a:focus, .nav > li > a:hover { margin-left: 5px; margin-right: 5px; border: 2px solid #379E8F; color: #379E8F; }'; inlineHtml += '</style>'; // // Define alert window. // inlineHtml +='<div class="container" style="margin-top:14px;" hidden><div id="alert" class="alert alert-danger fade in"></div></div>'; // // Define information window. // inlineHtml +='<div class="container" hidden><p id="info" class="alert alert-info"></p></div>'; // inlineHtml += '<div style="margin-top: -40px"><br/>'; // Buttons inlineHtml += '<button style="margin-left: 10px; margin-right: 5px; background-color: #FBEA51; color: #103D39; font-weight: 700; border-color: transparent; border-width: 2px; border-radius: 15px; height: 30px" type="button" id="smc" onclick="">Service Management Console</button>'; inlineHtml += '<h1 style="font-size: 25px; font-weight: 700; color: #103D39; text-align: center">Scheduled Price Change: ' + header + '</h1>'; // Click for Instructions // inlineHtml += '<button type="button" class="btn btn-sm btn-info instruction_button" data-toggle="collapse" data-target="#demo" style="background-color: #FBEA51; color: #103D39;">Click for Instructions</button><div id="demo" style="background-color: #cfeefc !important;border: 1px solid #417ed9;padding: 10px 10px 10px 20px;width:96%;position:absolute" class="collapse"><b><u>IMPORTANT INSTRUCTIONS:</u></b>'; // inlineHtml += '<ul><li><input type="button" class="btn-xs" style="background-color: #fff; color: black;" disabled value="Submit Search" /> - <ul><li>Click "Submit Search" to load Datatable using current parameters</li></ul></li>' // inlineHtml += '<li>Functionalities available on the Table Collections Table:<ul><li><b>Sort</b><ul><li>Click on column headers to sort collections invoices according to the values in the columns. This is default to "Days Overdue".</li><li>Hold "Shift" and click another column to sort according to multiple columns.</li></ul></li><li><b>Search</b><ul><li>You can search for specific Customer or Invoice by typing into the "Search" field</li></ul></li></ul></li>'; // inlineHtml += '<li>Table Filters:<ul><li><b>Matching MAAP Allocation</b><ul><li><button type="button" class="btn-xs btn-success " disabled><span class="glyphicon glyphicon-plus"></span></button> - Click to apply MAAP Allocation filters search filters on table. ONLY click once. </li><li><button type="button" class="btn-xs btn-danger " disabled><span class="glyphicon glyphicon-minus"></span></button> - Click to remove MAAP Allocation search filter from table. This is set default to "Days Overdue".</li></ul></li> <li><b>MP Ticket Column</b><ul><button type="button" class="btn-xs btn-success" disabled><span class="glyphicon glyphicon-plus"></span></button> - Click to apply MAAP Allocation filters search filters on table. ONLY click once. </li></ul></li></ul></li><li>Clickable Actions Available Per Invoice in DataTable:</li>'; // inlineHtml += '<ul><li><button type="button" class="btn-xs" disabled><span class="span_class glyphicon glyphicon-pencil"></span></button> - Click to open Notes Section for Selected Invoice. (Notes Section is seperate from User Notes)</li>'; // inlineHtml += '<li><button type="button" class="btn-xs btn-secondary" disabled><span class="glyphicon glyphicon-eye-open"></span></button> - Click to Set Invoice has "Viewed" by a member of the Finance Team.</li>'; // inlineHtml += '<li><button type="button" class="btn-xs btn-info" disabled><span class="glyphicon glyphicon-time"></span></button> - Click to view Snooze Timers</li><li><button type="button" class="timer-1day form=control btn-xs btn-info" disabled><span class="span_class">1 Day</span></button> - Click to select Snooze duration of invoice from Table Collections Page.</li>'; // inlineHtml += '</li></ul></div>'; // inlineHtml += '<button type="button" class="btn btn-sm btn-info instruction_button" data-toggle="collapse" data-target="#demo">Click for Instructions</button><div id="demo" style="background-color: #cfeefc !important;border: 1px solid #417ed9;padding: 10px 10px 10px 20px;width:96%;position:absolute" class="collapse"><b><u>IMPORTANT INSTRUCTIONS:</u></b><ul><li>Functionalities available on the Customer listing/table:<ul><li><b>Sort</b><ul><li>Click on column headers to sort customer list according to the values in the columns. This is default to "Customer Name".</li><li>Hold "Shift" and click another column to sort according to multiple columns.</li></ul></li><li><b>Search</b><ul><li>You can search for specific customer by typing into the "Search" field</li></ul></li></ul></li><li>Clickable Actions available per customer:</li><ul><li><button class="btn-xs btn-default" disabled>UPLOAD SCF</button> - <ul><li>Available for customers with missing Service Commencement Forms (SCF) in the system. You will need to upload the latest signed SCF for each relevant customers which outlines the service commencement date along with the Service(s) and Price(s).</li></ul></li><li><button class="btn-xs btn-warning" disabled>REVIEW</button> / <button class="btn-xs btn-primary" disabled>EDIT</button> - <ul><li>Review or Edit customer details (eg. Addresses, Service and Pricing, Packages) to set them up for Run Digitalisation.</li></ul></li><li><button class="btn-xs btn-danger" disabled>CANCEL</button> - <ul><li>You may Cancel non-active customers providing details and reasons around the Cancellation.</li><li>You <b><u>DO NOT NEED</u></b> to cancel customers with <b><u>Adhoc</u></b> arrangements.</li></ul></li><li><button class="btn-xs btn-default" disabled>Duplicate COMMREG</button> - <ul><li>Please contact <b><u>Head Office</u></b> if you see this Action against any customer</li></ul></li></ul></li></ul></ul></div>'; // inlineHtml = '<div class="form-group container loading_section"></div>'; // inlineHtml += '<style> .loading_section { border: 14px solid #f3f3f3; border-radius: 50%; border-top: 14px solid #379E8F; width: 90px; height: 90px; -webkit-animation: spin 2s linear infinite; /* Safari */ animation: spin 2s linear infinite;'; // inlineHtml += 'left: 50%; }' //position: fixed; z-index: 1000; // /* Safari */ // inlineHtml += '@-webkit-keyframes spin {0% { -webkit-transform: rotate(0deg); } 100% { -webkit-transform: rotate(360deg); } }'; // inlineHtml += '@keyframes spin { 0% { transform: rotate(0deg); } 100% { transform: rotate(360deg); } }'; // inlineHtml += '</style>'; // Comm Reg inlineHtml += commRegSection(commReg); inlineHtml += "<br>"; inlineHtml += "<br>"; // Tab Selection inlineHtml += '<div class="tabSection hide">'; // inlineHtml += editTab(); inlineHtml += "</div>"; inlineHtml += "</div></div>"; // </div> form.addField({ id: "preview_table", label: "inlinehtml", type: "inlinehtml", }).updateLayoutType({ layoutType: ui.FieldLayoutType.STARTROW, }).defaultValue = inlineHtml; form.addField({ id: "custpage_price_change_edit_zee_id", label: "Zee ID", type: ui.FieldType.TEXT, }).updateDisplayType({ displayType: ui.FieldDisplayType.HIDDEN, }).defaultValue = zee_id; form.addField({ id: "custpage_price_change_edit_cust_id", label: "Customer ID", type: ui.FieldType.TEXT, }).updateDisplayType({ displayType: ui.FieldDisplayType.HIDDEN, }).defaultValue = cust_id; form.addField({ id: "custpage_price_change_edit_comm_reg", label: "Commencement Register", type: ui.FieldType.TEXT, }).updateDisplayType({ displayType: ui.FieldDisplayType.HIDDEN, }).defaultValue = commReg; form.clientScriptFileId = 5606277 //5595961; // context.response.writePage(form); } else { } } function commRegSection(commReg) { var inlineQty = '<style>table#comm_reg_preview {font-size: 12px;text-align: center;border: none;}.dataTables_wrapper {font-size: 14px;}table#comm_reg_preview th{text-align: center;} .bolded{font-weight: bold;}</style>'; /** * Comm Reg Header */ inlineQty += '<div class="form-group container comm_header_section">'; inlineQty += '<div class="row">'; inlineQty += '<div class="col-xs-12 heading1"><h4><span class="label label-default col-xs-12" style="background-color: #379E8F; color: white;">Commencement Register</span></h4></div>'; inlineQty += '</div>'; inlineQty += '</div>'; inlineQty += '<table id="comm_reg_preview" class="table table-responsive table-striped customer tablesorter" style="width: 100%;">'; inlineQty += '<thead style="color: white; background-color: #379E8F;">'; inlineQty += '<tr class="text-center">'; // inlineQty += '<th>Commencement Register</th>'; inlineQty += '</tr>'; inlineQty += '</thead>'; inlineQty += '<tbody id="result_data_comm_reg" class="result-data-comm-reg">'; inlineQty += '</tbody>'; inlineQty += '</table>'; // inlineQty += '<div class="form-row container comm_reg_section">' // inlineQty += '<div class="row">' // inlineQty += '<div class="col-xs-2"></div>' // Blank Placeholder // inlineQty += '<div class="col-xs-4 schedule_change_section"><input type="button" id="create_new" class="form-control btn btn-success btn-xs create_new" value="New Scheduled Change" data-toggle="tooltip" data-placement="right" title="NEW SCHEDULED CHANGE" /></div>'; // inlineQty += '<div class="col-xs-4 cancel_service_section"><input type="button" id="cancel_service" class="form-control btn btn-danger btn-xs cancel_service" value="Cancel Service" data-toggle="tooltip" data-placement="right" title="CANCEL SERVICE" /></div>'; // inlineQty += '<div class="col-xs-2"></div>' // Blank Placeholder // inlineQty += '</div>' // inlineQty += '</div>' return inlineQty; } /** * The table that will display the differents invoices linked to the franchisee and the time period. * @return {String} inlineQty */ function editTab() { var inlineQty = '<style>table#data_preview {font-size: 12px;text-align: center;border: none;}.dataTables_wrapper {font-size: 14px;}table#data_preview th{text-align: center;} .bolded{font-weight: bold;}</style>'; /** * Edit Header */ inlineQty += '<div class="form-group container edit_header_section">'; inlineQty += '<div class="row">'; inlineQty += '<div class="col-xs-12 heading1">'; inlineQty += '<h4><span style="background-color: #379E8F" class="form-group label label-default col-xs-12">Edit</span></h4>'; inlineQty += '</div></div></div>'; /** * Date Effective */ inlineQty += '<div class="form-group container date_effective_section">'; inlineQty += '<div class="row">'; // if (isNullorEmpty(dateEffective)) { inlineQty += '<div class="col-xs-6"><div class="input-group"><span style="background-color: #379E8F; color: white;" class="input-group-addon">Date Effective <span class="mandatory">*</span></span><input type="date" id="date_effective" value="" class="form-control date_effective" disabled/></div></div>'; // } else { // start_date = GetFormattedDate(dateEffective); // inlineQty += '<div class="col-xs-7 "><div class="input-group"><span class="input-group-addon">DATE EFFECTIVE <span class="mandatory">*</span></span><input type="date" id="date_effective" value="' + start_date + '" data-olddate="' + dateEffective + '" class="form-control date_effective"/></div></div>'; // } /** * Sales Type */ inlineQty += '<div class="col-xs-6 commencementtype"><div class="input-group"><span style="background-color: #379E8F; color: white;" class="input-group-addon" id="commencementtype_text">Sale Type <span class="mandatory">*</span></span><select id="commencementtype" class="form-control commencementtype" disabled><option></option>'; var col = new Array(); col[0] = search.createColumn({ name: 'name', }) col[1] = search.createColumn({ name: 'internalId', }); var results = search.create({ type: 'customlist_sale_type', columns: col }); results.run().each(function(res) { var listValue = res.getValue({ name: 'name' }); var listID = res.getValue({ name: 'internalId' }); // if (!isNullorEmpty(sale_type) && sale_type == listID) { // inlineQty += '<option value="' + listID + '" selected>' + listValue + '</option>'; // } else { inlineQty += '<option value="' + listID + '">' + listValue + '</option>'; // } return true; }) inlineQty += '</select></div></div>'; inlineQty += '</div>'; inlineQty += '</div>'; /** * DataTable */ inlineQty += '<table id="data_preview" class="table table-responsive table-striped customer tablesorter" style="width: 100%;">'; inlineQty += '<thead style="color: white; background-color: #379E8F;">'; inlineQty += '<tr class="text-center">'; inlineQty += '</tr>'; inlineQty += '</thead>'; inlineQty += '<tbody id="result_data" class="result-data"></tbody>'; inlineQty += '</table>'; inlineQty += '<div class="form-row container edit_submit_section">' inlineQty += '<div class="row">' inlineQty += '<div class="col-xs-2"></div>' // Blank Placeholder inlineQty += '<div class="col-xs-4 schedule_change_section"><input type="button" id="sumbit_edit" style="color: #103D39;" class="form-control btn btn-warning btn-xs sumbit_edit" value="Submit" data-toggle="tooltip" data-placement="right" title="Submit" /></div>'; inlineQty += '<div class="col-xs-4 cancel_service_section"><input type="button" id="next_customer" style="color: #103D39;" class="form-control btn btn-warning btn-xs next_customer" value="Next Customer" data-toggle="tooltip" data-placement="right" title="Next Customer" /></div>'; inlineQty += '<div class="col-xs-2"></div>' // Blank Placeholder inlineQty += '</div>' inlineQty += '</div>' return inlineQty; } /** * The period dropdown field. * @param {String} date_from * @param {String} date_to * @return {String} `inlineQty` */ function periodDropdownSection(date_from, date_to) { var selected_option = (isNullorEmpty(date_from) && isNullorEmpty(date_to)) ? 'selected' : ''; var inlineQty = '<div class="form-group container period_dropdown_section">'; inlineQty += '<div class="row">'; // Period dropdown field inlineQty += '<div class="col-xs-12 period_dropdown_div">'; inlineQty += '<div class="input-group">'; inlineQty += '<span class="input-group-addon" id="period_dropdown_text">Period</span>'; inlineQty += '<select id="period_dropdown" class="form-control">'; inlineQty += '<option ' + selected_option + '></option>'; inlineQty += '<option value="this_week">This Week</option>'; inlineQty += '<option value="last_week">Last Week</option>'; inlineQty += '<option value="this_month">This Month</option>'; inlineQty += '<option value="last_month">Last Month</option>'; inlineQty += '<option value="full_year">Full Year (1 Jan -)</option>'; inlineQty += '<option value="financial_year">Financial Year (1 Jul -)</option>'; inlineQty += '</select>'; inlineQty += '</div></div></div></div>'; return inlineQty; } /** * Used to pass the values of `date_from` and `date_to` between the scripts and to Netsuite for the records and the search. * @param {String} date_iso "2020-06-01" * @returns {String} date_netsuite "1/6/2020" */ function dateISOToNetsuite(date_iso) { var date_netsuite = ''; if (!isNullorEmpty(date_iso)) { var date_utc = new Date(date_iso); // var date_netsuite = nlapiDateToString(date_utc); var date_netsuite = format.format({ value: date_utc, type: format.Type.DATE }); } return date_netsuite; } function isNullorEmpty(strVal) { return (strVal == null || strVal == '' || strVal == 'null' || strVal == undefined || strVal == 'undefined' || strVal == '- None -'); } return { onRequest: onRequest } });
903
[{"tag": "KEY", "value": "sha384-HSMxcRTRxnN+Bdg0JdbxYKrThecOKuH5zCYotlSAcp1+c8xmyTe9GYg1l9a69psu", "start": 2952, "end": 3023}, {"tag": "KEY", "value": "sha384-nvAa0+6Qg9clwYCGGPpDQLVpLNn0fRaROjHqs13t4Ggj3Ez50XnGQqc/r8MhnRDZ", "start": 2354, "end": 2425}, {"tag": "KEY", "value": "sha384-aJ21OjlMXNL5UyIl/XNwTMqvzeRMZH2w8c5cRVpzpU8Y5bApTppSuUkhZXN0VxHd", "start": 3199, "end": 3270}]
true
3
/** * @NApiVersion 2.0 * @NScriptType Suitelet * * Module Description * * NSVersion Date Author * 2.00 2021-09-20 09:33:08 Anesu * * Description: xxxxxxxx * * @Last Modified by: Anesu * @Last Modified time: 2021-09-20 09:33:08 * */ define(['N/ui/serverWidget', 'N/email', 'N/runtime', 'N/search', 'N/record', 'N/http', 'N/log', 'N/redirect', 'N/task', 'N/format'], function(ui, email, runtime, search, record, http, log, redirect, task, format) { var zee = 0; var role = 0; var baseURL = 'https://1048144.app.netsuite.com'; if (runtime.EnvType == "SANDBOX") { baseURL = 'https://1048144-sb3.app.netsuite.com'; } role = runtime.getCurrentUser().role; if (role == 1000) { zee = runtime.getCurrentUser().id; } else if (role == 3) { //Administrator zee = 6; //test } else if (role == 1032) { // System Support zee = 425904; //test-AR } function onRequest(context) { if (context.request.method === 'GET') { type = context.request.parameters.type; var params_params = context.request.parameters; if (!isNullorEmpty(params_params.custparam_params)) { var params = JSON.parse(context.request.parameters.custparam_params); log.debug({ title: 'Params', details: params }) } var zee_id = 0; var commReg = 0; var cust_id = 0; var new_commReg = false; var header = 'Edit'; if (!isNullorEmpty(params)) { zee_id = parseInt(params.zeeid); commReg = parseInt(params.commreg); cust_id = parseInt(params.custid) new_commReg = Boolean(params.new); } if (new_commReg == true) { commReg = 0; header = 'New' } var form = ui.createForm({ title: " " }); // Load jQuery // var inlineHtml = '<script src="https://code.jquery.com/jquery-1.12.4.min.js" integrity="se2xy1bknelxn4y8xzxu3trosptip3q5" crossorigin="anonymous"></script>'; var inlineHtml = '<script src="https://code.jquery.com/jquery-3.5.0.js" crossorigin="anonymous"></script>'; // Load Tooltip inlineHtml += '<script src="https://unpkg.com/@popperjs/core@2"></script>'; // Load Bootstrap inlineHtml += '<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/3.4.1/css/bootstrap.min.css" integrity="ngw6fo1pu3tjgnp9jnlp7vnwvfqb9yn7" crossorigin="anonymous">'; inlineHtml += '<script src="https://stackpath.bootstrapcdn.com/bootstrap/3.4.1/js/bootstrap.min.js" integrity="9q3vfhm7l33rus21toc8fndupq76itje" crossorigin="anonymous"></script>'; // Load DataTables inlineHtml += '<link rel="stylesheet" type="text/css" href="//cdn.datatables.net/1.10.21/css/jquery.dataTables.min.css">'; inlineHtml += '<script type="text/javascript" charset="utf8" src="//cdn.datatables.net/1.10.21/js/jquery.dataTables.min.js"></script>'; inlineHtml += '<script type="text/javascript" charset="utf8" src="//cdn.datatables.net/rowgroup/1.1.3/js/dataTables.rowGroup.min.js"></script> '; inlineHtml += '<script type="text/javascript" charset="utf8" src="//cdn.datatables.net/buttons/2.0.0/js/dataTables.buttons.min.js"></script> '; inlineHtml += '<script type="text/javascript" charset="utf8" src="//cdnjs.cloudflare.com/ajax/libs/jszip/3.1.3/jszip.min.js"></script> '; inlineHtml += '<script type="text/javascript" charset="utf8" src="//cdnjs.cloudflare.com/ajax/libs/pdfmake/0.1.53/pdfmake.min.js"></script> '; inlineHtml += '<script type="text/javascript" charset="utf8" src="//cdnjs.cloudflare.com/ajax/libs/pdfmake/0.1.53/vfs_fonts.js"></script> '; inlineHtml += '<script type="text/javascript" charset="utf8" src="//cdn.datatables.net/buttons/2.0.0/js/buttons.html5.min.js"></script> '; inlineHtml += '<script type="text/javascript" charset="utf8" src="//cdn.datatables.net/buttons/2.0.0/js/buttons.print.min.js"></script> '; // Load Netsuite stylesheet and script inlineHtml += '<link rel="stylesheet" href="https://1048144.app.netsuite.com/core/media/media.nl?id=2060796&c=1048144&h=9ee6accfd476c9cae718&_xt=.css"/>'; inlineHtml += '<script src="https://1048144.app.netsuite.com/core/media/media.nl?id=2060797&c=1048144&h=ef2cda20731d146b5e98&_xt=.js"></script>'; inlineHtml += '<link type="text/css" rel="stylesheet" href="https://1048144.app.netsuite.com/core/media/media.nl?id=2090583&c=1048144&h=a0ef6ac4e28f91203dfe&_xt=.css">'; inlineHtml += "<style>.mandatory{color:red;}</style>"; // Load Bootstrap-Select inlineHtml += '<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap-select@1.13.14/dist/css/bootstrap-select.min.css">'; inlineHtml += '<script src="https://cdn.jsdelivr.net/npm/bootstrap-select@1.13.14/dist/js/bootstrap-select.min.js"></script>'; // Semantic Select inlineHtml += '<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/semantic-ui/2.2.13/semantic.min.css">'; inlineHtml += '<script src="https://cdnjs.cloudflare.com/ajax/libs/semantic-ui/2.2.13/semantic.min.js"></script>'; // Load Search In Dropdown // inlineHtml += '<link href="https://cdnjs.cloudflare.com/ajax/libs/select2/4.0.6-rc.0/css/select2.min.css" rel="stylesheet" />'; // inlineHtml += '<script src="https://cdnjs.cloudflare.com/ajax/libs/select2/4.0.6-rc.0/js/select2.min.js"></script>'; // New Website Color Schemes // Main Color: #379E8F // Background Color: #CFE0CE // Button Color: #FBEA51 // Text Color: #103D39 inlineHtml += '<div class="a" style="width: 100%; background-color: #CFE0CE; padding: 20px; min-height: 100vh; height: 100%; ">'; // margin-top: -40px // inlineHtml += '<h1 style="text-align: center; color: #103D39; display: inline-block; font-size: 22px; font-weight: bold; line-height: 33px; vertical-align: top; margin-bottom: 4px;">Scheduled Price Change: Finance Team</h1>'; inlineHtml += '<style>.nav > li.active > a, .nav > li.active > a:focus, .nav > li.active > a:hover { background-color: #379E8F; color: #fff }'; inlineHtml += '.nav > li > a, .nav > li > a:focus, .nav > li > a:hover { margin-left: 5px; margin-right: 5px; border: 2px solid #379E8F; color: #379E8F; }'; inlineHtml += '</style>'; // // Define alert window. // inlineHtml +='<div class="container" style="margin-top:14px;" hidden><div id="alert" class="alert alert-danger fade in"></div></div>'; // // Define information window. // inlineHtml +='<div class="container" hidden><p id="info" class="alert alert-info"></p></div>'; // inlineHtml += '<div style="margin-top: -40px"><br/>'; // Buttons inlineHtml += '<button style="margin-left: 10px; margin-right: 5px; background-color: #FBEA51; color: #103D39; font-weight: 700; border-color: transparent; border-width: 2px; border-radius: 15px; height: 30px" type="button" id="smc" onclick="">Service Management Console</button>'; inlineHtml += '<h1 style="font-size: 25px; font-weight: 700; color: #103D39; text-align: center">Scheduled Price Change: ' + header + '</h1>'; // Click for Instructions // inlineHtml += '<button type="button" class="btn btn-sm btn-info instruction_button" data-toggle="collapse" data-target="#demo" style="background-color: #FBEA51; color: #103D39;">Click for Instructions</button><div id="demo" style="background-color: #cfeefc !important;border: 1px solid #417ed9;padding: 10px 10px 10px 20px;width:96%;position:absolute" class="collapse"><b><u>IMPORTANT INSTRUCTIONS:</u></b>'; // inlineHtml += '<ul><li><input type="button" class="btn-xs" style="background-color: #fff; color: black;" disabled value="Submit Search" /> - <ul><li>Click "Submit Search" to load Datatable using current parameters</li></ul></li>' // inlineHtml += '<li>Functionalities available on the Table Collections Table:<ul><li><b>Sort</b><ul><li>Click on column headers to sort collections invoices according to the values in the columns. This is default to "Days Overdue".</li><li>Hold "Shift" and click another column to sort according to multiple columns.</li></ul></li><li><b>Search</b><ul><li>You can search for specific Customer or Invoice by typing into the "Search" field</li></ul></li></ul></li>'; // inlineHtml += '<li>Table Filters:<ul><li><b>Matching MAAP Allocation</b><ul><li><button type="button" class="btn-xs btn-success " disabled><span class="glyphicon glyphicon-plus"></span></button> - Click to apply MAAP Allocation filters search filters on table. ONLY click once. </li><li><button type="button" class="btn-xs btn-danger " disabled><span class="glyphicon glyphicon-minus"></span></button> - Click to remove MAAP Allocation search filter from table. This is set default to "Days Overdue".</li></ul></li> <li><b>MP Ticket Column</b><ul><button type="button" class="btn-xs btn-success" disabled><span class="glyphicon glyphicon-plus"></span></button> - Click to apply MAAP Allocation filters search filters on table. ONLY click once. </li></ul></li></ul></li><li>Clickable Actions Available Per Invoice in DataTable:</li>'; // inlineHtml += '<ul><li><button type="button" class="btn-xs" disabled><span class="span_class glyphicon glyphicon-pencil"></span></button> - Click to open Notes Section for Selected Invoice. (Notes Section is seperate from User Notes)</li>'; // inlineHtml += '<li><button type="button" class="btn-xs btn-secondary" disabled><span class="glyphicon glyphicon-eye-open"></span></button> - Click to Set Invoice has "Viewed" by a member of the Finance Team.</li>'; // inlineHtml += '<li><button type="button" class="btn-xs btn-info" disabled><span class="glyphicon glyphicon-time"></span></button> - Click to view Snooze Timers</li><li><button type="button" class="timer-1day form=control btn-xs btn-info" disabled><span class="span_class">1 Day</span></button> - Click to select Snooze duration of invoice from Table Collections Page.</li>'; // inlineHtml += '</li></ul></div>'; // inlineHtml += '<button type="button" class="btn btn-sm btn-info instruction_button" data-toggle="collapse" data-target="#demo">Click for Instructions</button><div id="demo" style="background-color: #cfeefc !important;border: 1px solid #417ed9;padding: 10px 10px 10px 20px;width:96%;position:absolute" class="collapse"><b><u>IMPORTANT INSTRUCTIONS:</u></b><ul><li>Functionalities available on the Customer listing/table:<ul><li><b>Sort</b><ul><li>Click on column headers to sort customer list according to the values in the columns. This is default to "Customer Name".</li><li>Hold "Shift" and click another column to sort according to multiple columns.</li></ul></li><li><b>Search</b><ul><li>You can search for specific customer by typing into the "Search" field</li></ul></li></ul></li><li>Clickable Actions available per customer:</li><ul><li><button class="btn-xs btn-default" disabled>UPLOAD SCF</button> - <ul><li>Available for customers with missing Service Commencement Forms (SCF) in the system. You will need to upload the latest signed SCF for each relevant customers which outlines the service commencement date along with the Service(s) and Price(s).</li></ul></li><li><button class="btn-xs btn-warning" disabled>REVIEW</button> / <button class="btn-xs btn-primary" disabled>EDIT</button> - <ul><li>Review or Edit customer details (eg. Addresses, Service and Pricing, Packages) to set them up for Run Digitalisation.</li></ul></li><li><button class="btn-xs btn-danger" disabled>CANCEL</button> - <ul><li>You may Cancel non-active customers providing details and reasons around the Cancellation.</li><li>You <b><u>DO NOT NEED</u></b> to cancel customers with <b><u>Adhoc</u></b> arrangements.</li></ul></li><li><button class="btn-xs btn-default" disabled>Duplicate COMMREG</button> - <ul><li>Please contact <b><u>Head Office</u></b> if you see this Action against any customer</li></ul></li></ul></li></ul></ul></div>'; // inlineHtml = '<div class="form-group container loading_section"></div>'; // inlineHtml += '<style> .loading_section { border: 14px solid #f3f3f3; border-radius: 50%; border-top: 14px solid #379E8F; width: 90px; height: 90px; -webkit-animation: spin 2s linear infinite; /* Safari */ animation: spin 2s linear infinite;'; // inlineHtml += 'left: 50%; }' //position: fixed; z-index: 1000; // /* Safari */ // inlineHtml += '@-webkit-keyframes spin {0% { -webkit-transform: rotate(0deg); } 100% { -webkit-transform: rotate(360deg); } }'; // inlineHtml += '@keyframes spin { 0% { transform: rotate(0deg); } 100% { transform: rotate(360deg); } }'; // inlineHtml += '</style>'; // Comm Reg inlineHtml += commRegSection(commReg); inlineHtml += "<br>"; inlineHtml += "<br>"; // Tab Selection inlineHtml += '<div class="tabSection hide">'; // inlineHtml += editTab(); inlineHtml += "</div>"; inlineHtml += "</div></div>"; // </div> form.addField({ id: "preview_table", label: "inlinehtml", type: "inlinehtml", }).updateLayoutType({ layoutType: ui.FieldLayoutType.STARTROW, }).defaultValue = inlineHtml; form.addField({ id: "custpage_price_change_edit_zee_id", label: "Zee ID", type: ui.FieldType.TEXT, }).updateDisplayType({ displayType: ui.FieldDisplayType.HIDDEN, }).defaultValue = zee_id; form.addField({ id: "custpage_price_change_edit_cust_id", label: "Customer ID", type: ui.FieldType.TEXT, }).updateDisplayType({ displayType: ui.FieldDisplayType.HIDDEN, }).defaultValue = cust_id; form.addField({ id: "custpage_price_change_edit_comm_reg", label: "Commencement Register", type: ui.FieldType.TEXT, }).updateDisplayType({ displayType: ui.FieldDisplayType.HIDDEN, }).defaultValue = commReg; form.clientScriptFileId = 5606277 //5595961; // context.response.writePage(form); } else { } } function commRegSection(commReg) { var inlineQty = '<style>table#comm_reg_preview {font-size: 12px;text-align: center;border: none;}.dataTables_wrapper {font-size: 14px;}table#comm_reg_preview th{text-align: center;} .bolded{font-weight: bold;}</style>'; /** * Comm Reg Header */ inlineQty += '<div class="form-group container comm_header_section">'; inlineQty += '<div class="row">'; inlineQty += '<div class="col-xs-12 heading1"><h4><span class="label label-default col-xs-12" style="background-color: #379E8F; color: white;">Commencement Register</span></h4></div>'; inlineQty += '</div>'; inlineQty += '</div>'; inlineQty += '<table id="comm_reg_preview" class="table table-responsive table-striped customer tablesorter" style="width: 100%;">'; inlineQty += '<thead style="color: white; background-color: #379E8F;">'; inlineQty += '<tr class="text-center">'; // inlineQty += '<th>Commencement Register</th>'; inlineQty += '</tr>'; inlineQty += '</thead>'; inlineQty += '<tbody id="result_data_comm_reg" class="result-data-comm-reg">'; inlineQty += '</tbody>'; inlineQty += '</table>'; // inlineQty += '<div class="form-row container comm_reg_section">' // inlineQty += '<div class="row">' // inlineQty += '<div class="col-xs-2"></div>' // Blank Placeholder // inlineQty += '<div class="col-xs-4 schedule_change_section"><input type="button" id="create_new" class="form-control btn btn-success btn-xs create_new" value="New Scheduled Change" data-toggle="tooltip" data-placement="right" title="NEW SCHEDULED CHANGE" /></div>'; // inlineQty += '<div class="col-xs-4 cancel_service_section"><input type="button" id="cancel_service" class="form-control btn btn-danger btn-xs cancel_service" value="Cancel Service" data-toggle="tooltip" data-placement="right" title="CANCEL SERVICE" /></div>'; // inlineQty += '<div class="col-xs-2"></div>' // Blank Placeholder // inlineQty += '</div>' // inlineQty += '</div>' return inlineQty; } /** * The table that will display the differents invoices linked to the franchisee and the time period. * @return {String} inlineQty */ function editTab() { var inlineQty = '<style>table#data_preview {font-size: 12px;text-align: center;border: none;}.dataTables_wrapper {font-size: 14px;}table#data_preview th{text-align: center;} .bolded{font-weight: bold;}</style>'; /** * Edit Header */ inlineQty += '<div class="form-group container edit_header_section">'; inlineQty += '<div class="row">'; inlineQty += '<div class="col-xs-12 heading1">'; inlineQty += '<h4><span style="background-color: #379E8F" class="form-group label label-default col-xs-12">Edit</span></h4>'; inlineQty += '</div></div></div>'; /** * Date Effective */ inlineQty += '<div class="form-group container date_effective_section">'; inlineQty += '<div class="row">'; // if (isNullorEmpty(dateEffective)) { inlineQty += '<div class="col-xs-6"><div class="input-group"><span style="background-color: #379E8F; color: white;" class="input-group-addon">Date Effective <span class="mandatory">*</span></span><input type="date" id="date_effective" value="" class="form-control date_effective" disabled/></div></div>'; // } else { // start_date = GetFormattedDate(dateEffective); // inlineQty += '<div class="col-xs-7 "><div class="input-group"><span class="input-group-addon">DATE EFFECTIVE <span class="mandatory">*</span></span><input type="date" id="date_effective" value="' + start_date + '" data-olddate="' + dateEffective + '" class="form-control date_effective"/></div></div>'; // } /** * Sales Type */ inlineQty += '<div class="col-xs-6 commencementtype"><div class="input-group"><span style="background-color: #379E8F; color: white;" class="input-group-addon" id="commencementtype_text">Sale Type <span class="mandatory">*</span></span><select id="commencementtype" class="form-control commencementtype" disabled><option></option>'; var col = new Array(); col[0] = search.createColumn({ name: 'name', }) col[1] = search.createColumn({ name: 'internalId', }); var results = search.create({ type: 'customlist_sale_type', columns: col }); results.run().each(function(res) { var listValue = res.getValue({ name: 'name' }); var listID = res.getValue({ name: 'internalId' }); // if (!isNullorEmpty(sale_type) && sale_type == listID) { // inlineQty += '<option value="' + listID + '" selected>' + listValue + '</option>'; // } else { inlineQty += '<option value="' + listID + '">' + listValue + '</option>'; // } return true; }) inlineQty += '</select></div></div>'; inlineQty += '</div>'; inlineQty += '</div>'; /** * DataTable */ inlineQty += '<table id="data_preview" class="table table-responsive table-striped customer tablesorter" style="width: 100%;">'; inlineQty += '<thead style="color: white; background-color: #379E8F;">'; inlineQty += '<tr class="text-center">'; inlineQty += '</tr>'; inlineQty += '</thead>'; inlineQty += '<tbody id="result_data" class="result-data"></tbody>'; inlineQty += '</table>'; inlineQty += '<div class="form-row container edit_submit_section">' inlineQty += '<div class="row">' inlineQty += '<div class="col-xs-2"></div>' // Blank Placeholder inlineQty += '<div class="col-xs-4 schedule_change_section"><input type="button" id="sumbit_edit" style="color: #103D39;" class="form-control btn btn-warning btn-xs sumbit_edit" value="Submit" data-toggle="tooltip" data-placement="right" title="Submit" /></div>'; inlineQty += '<div class="col-xs-4 cancel_service_section"><input type="button" id="next_customer" style="color: #103D39;" class="form-control btn btn-warning btn-xs next_customer" value="Next Customer" data-toggle="tooltip" data-placement="right" title="Next Customer" /></div>'; inlineQty += '<div class="col-xs-2"></div>' // Blank Placeholder inlineQty += '</div>' inlineQty += '</div>' return inlineQty; } /** * The period dropdown field. * @param {String} date_from * @param {String} date_to * @return {String} `inlineQty` */ function periodDropdownSection(date_from, date_to) { var selected_option = (isNullorEmpty(date_from) && isNullorEmpty(date_to)) ? 'selected' : ''; var inlineQty = '<div class="form-group container period_dropdown_section">'; inlineQty += '<div class="row">'; // Period dropdown field inlineQty += '<div class="col-xs-12 period_dropdown_div">'; inlineQty += '<div class="input-group">'; inlineQty += '<span class="input-group-addon" id="period_dropdown_text">Period</span>'; inlineQty += '<select id="period_dropdown" class="form-control">'; inlineQty += '<option ' + selected_option + '></option>'; inlineQty += '<option value="this_week">This Week</option>'; inlineQty += '<option value="last_week">Last Week</option>'; inlineQty += '<option value="this_month">This Month</option>'; inlineQty += '<option value="last_month">Last Month</option>'; inlineQty += '<option value="full_year">Full Year (1 Jan -)</option>'; inlineQty += '<option value="financial_year">Financial Year (1 Jul -)</option>'; inlineQty += '</select>'; inlineQty += '</div></div></div></div>'; return inlineQty; } /** * Used to pass the values of `date_from` and `date_to` between the scripts and to Netsuite for the records and the search. * @param {String} date_iso "2020-06-01" * @returns {String} date_netsuite "1/6/2020" */ function dateISOToNetsuite(date_iso) { var date_netsuite = ''; if (!isNullorEmpty(date_iso)) { var date_utc = new Date(date_iso); // var date_netsuite = nlapiDateToString(date_utc); var date_netsuite = format.format({ value: date_utc, type: format.Type.DATE }); } return date_netsuite; } function isNullorEmpty(strVal) { return (strVal == null || strVal == '' || strVal == 'null' || strVal == undefined || strVal == 'undefined' || strVal == '- None -'); } return { onRequest: onRequest } });
true
/** * @NApiVersion 2.0 * @NScriptType Suitelet * * Module Description * * NSVersion Date Author * 2.00 2021-09-20 09:33:08 Anesu * * Description: xxxxxxxx * * @Last Modified by: Anesu * @Last Modified time: 2021-09-20 09:33:08 * */ define(['N/ui/serverWidget', 'N/email', 'N/runtime', 'N/search', 'N/record', 'N/http', 'N/log', 'N/redirect', 'N/task', 'N/format'], function(ui, email, runtime, search, record, http, log, redirect, task, format) { var zee = 0; var role = 0; var baseURL = 'https://1048144.app.netsuite.com'; if (runtime.EnvType == "SANDBOX") { baseURL = 'https://1048144-sb3.app.netsuite.com'; } role = runtime.getCurrentUser().role; if (role == 1000) { zee = runtime.getCurrentUser().id; } else if (role == 3) { //Administrator zee = 6; //test } else if (role == 1032) { // System Support zee = 425904; //test-AR } function onRequest(context) { if (context.request.method === 'GET') { type = context.request.parameters.type; var params_params = context.request.parameters; if (!isNullorEmpty(params_params.custparam_params)) { var params = JSON.parse(context.request.parameters.custparam_params); log.debug({ title: 'Params', details: params }) } var zee_id = 0; var commReg = 0; var cust_id = 0; var new_commReg = false; var header = 'Edit'; if (!isNullorEmpty(params)) { zee_id = parseInt(params.zeeid); commReg = parseInt(params.commreg); cust_id = parseInt(params.custid) new_commReg = Boolean(params.new); } if (new_commReg == true) { commReg = 0; header = 'New' } var form = ui.createForm({ title: " " }); // Load jQuery // var inlineHtml = '<script src="https://code.jquery.com/jquery-1.12.4.min.js" integrity="PI:KEY:se2xy1bknelxn4y8xzxu3trosptip3q5END_PI" crossorigin="anonymous"></script>'; var inlineHtml = '<script src="https://code.jquery.com/jquery-3.5.0.js" crossorigin="anonymous"></script>'; // Load Tooltip inlineHtml += '<script src="https://unpkg.com/@popperjs/core@2"></script>'; // Load Bootstrap inlineHtml += '<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/3.4.1/css/bootstrap.min.css" integrity="PI:KEY:ngw6fo1pu3tjgnp9jnlp7vnwvfqb9yn7END_PI" crossorigin="anonymous">'; inlineHtml += '<script src="https://stackpath.bootstrapcdn.com/bootstrap/3.4.1/js/bootstrap.min.js" integrity="PI:KEY:9q3vfhm7l33rus21toc8fndupq76itjeEND_PI" crossorigin="anonymous"></script>'; // Load DataTables inlineHtml += '<link rel="stylesheet" type="text/css" href="//cdn.datatables.net/1.10.21/css/jquery.dataTables.min.css">'; inlineHtml += '<script type="text/javascript" charset="utf8" src="//cdn.datatables.net/1.10.21/js/jquery.dataTables.min.js"></script>'; inlineHtml += '<script type="text/javascript" charset="utf8" src="//cdn.datatables.net/rowgroup/1.1.3/js/dataTables.rowGroup.min.js"></script> '; inlineHtml += '<script type="text/javascript" charset="utf8" src="//cdn.datatables.net/buttons/2.0.0/js/dataTables.buttons.min.js"></script> '; inlineHtml += '<script type="text/javascript" charset="utf8" src="//cdnjs.cloudflare.com/ajax/libs/jszip/3.1.3/jszip.min.js"></script> '; inlineHtml += '<script type="text/javascript" charset="utf8" src="//cdnjs.cloudflare.com/ajax/libs/pdfmake/0.1.53/pdfmake.min.js"></script> '; inlineHtml += '<script type="text/javascript" charset="utf8" src="//cdnjs.cloudflare.com/ajax/libs/pdfmake/0.1.53/vfs_fonts.js"></script> '; inlineHtml += '<script type="text/javascript" charset="utf8" src="//cdn.datatables.net/buttons/2.0.0/js/buttons.html5.min.js"></script> '; inlineHtml += '<script type="text/javascript" charset="utf8" src="//cdn.datatables.net/buttons/2.0.0/js/buttons.print.min.js"></script> '; // Load Netsuite stylesheet and script inlineHtml += '<link rel="stylesheet" href="https://1048144.app.netsuite.com/core/media/media.nl?id=2060796&c=1048144&h=9ee6accfd476c9cae718&_xt=.css"/>'; inlineHtml += '<script src="https://1048144.app.netsuite.com/core/media/media.nl?id=2060797&c=1048144&h=ef2cda20731d146b5e98&_xt=.js"></script>'; inlineHtml += '<link type="text/css" rel="stylesheet" href="https://1048144.app.netsuite.com/core/media/media.nl?id=2090583&c=1048144&h=a0ef6ac4e28f91203dfe&_xt=.css">'; inlineHtml += "<style>.mandatory{color:red;}</style>"; // Load Bootstrap-Select inlineHtml += '<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap-select@1.13.14/dist/css/bootstrap-select.min.css">'; inlineHtml += '<script src="https://cdn.jsdelivr.net/npm/bootstrap-select@1.13.14/dist/js/bootstrap-select.min.js"></script>'; // Semantic Select inlineHtml += '<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/semantic-ui/2.2.13/semantic.min.css">'; inlineHtml += '<script src="https://cdnjs.cloudflare.com/ajax/libs/semantic-ui/2.2.13/semantic.min.js"></script>'; // Load Search In Dropdown // inlineHtml += '<link href="https://cdnjs.cloudflare.com/ajax/libs/select2/4.0.6-rc.0/css/select2.min.css" rel="stylesheet" />'; // inlineHtml += '<script src="https://cdnjs.cloudflare.com/ajax/libs/select2/4.0.6-rc.0/js/select2.min.js"></script>'; // New Website Color Schemes // Main Color: #379E8F // Background Color: #CFE0CE // Button Color: #FBEA51 // Text Color: #103D39 inlineHtml += '<div class="a" style="width: 100%; background-color: #CFE0CE; padding: 20px; min-height: 100vh; height: 100%; ">'; // margin-top: -40px // inlineHtml += '<h1 style="text-align: center; color: #103D39; display: inline-block; font-size: 22px; font-weight: bold; line-height: 33px; vertical-align: top; margin-bottom: 4px;">Scheduled Price Change: Finance Team</h1>'; inlineHtml += '<style>.nav > li.active > a, .nav > li.active > a:focus, .nav > li.active > a:hover { background-color: #379E8F; color: #fff }'; inlineHtml += '.nav > li > a, .nav > li > a:focus, .nav > li > a:hover { margin-left: 5px; margin-right: 5px; border: 2px solid #379E8F; color: #379E8F; }'; inlineHtml += '</style>'; // // Define alert window. // inlineHtml +='<div class="container" style="margin-top:14px;" hidden><div id="alert" class="alert alert-danger fade in"></div></div>'; // // Define information window. // inlineHtml +='<div class="container" hidden><p id="info" class="alert alert-info"></p></div>'; // inlineHtml += '<div style="margin-top: -40px"><br/>'; // Buttons inlineHtml += '<button style="margin-left: 10px; margin-right: 5px; background-color: #FBEA51; color: #103D39; font-weight: 700; border-color: transparent; border-width: 2px; border-radius: 15px; height: 30px" type="button" id="smc" onclick="">Service Management Console</button>'; inlineHtml += '<h1 style="font-size: 25px; font-weight: 700; color: #103D39; text-align: center">Scheduled Price Change: ' + header + '</h1>'; // Click for Instructions // inlineHtml += '<button type="button" class="btn btn-sm btn-info instruction_button" data-toggle="collapse" data-target="#demo" style="background-color: #FBEA51; color: #103D39;">Click for Instructions</button><div id="demo" style="background-color: #cfeefc !important;border: 1px solid #417ed9;padding: 10px 10px 10px 20px;width:96%;position:absolute" class="collapse"><b><u>IMPORTANT INSTRUCTIONS:</u></b>'; // inlineHtml += '<ul><li><input type="button" class="btn-xs" style="background-color: #fff; color: black;" disabled value="Submit Search" /> - <ul><li>Click "Submit Search" to load Datatable using current parameters</li></ul></li>' // inlineHtml += '<li>Functionalities available on the Table Collections Table:<ul><li><b>Sort</b><ul><li>Click on column headers to sort collections invoices according to the values in the columns. This is default to "Days Overdue".</li><li>Hold "Shift" and click another column to sort according to multiple columns.</li></ul></li><li><b>Search</b><ul><li>You can search for specific Customer or Invoice by typing into the "Search" field</li></ul></li></ul></li>'; // inlineHtml += '<li>Table Filters:<ul><li><b>Matching MAAP Allocation</b><ul><li><button type="button" class="btn-xs btn-success " disabled><span class="glyphicon glyphicon-plus"></span></button> - Click to apply MAAP Allocation filters search filters on table. ONLY click once. </li><li><button type="button" class="btn-xs btn-danger " disabled><span class="glyphicon glyphicon-minus"></span></button> - Click to remove MAAP Allocation search filter from table. This is set default to "Days Overdue".</li></ul></li> <li><b>MP Ticket Column</b><ul><button type="button" class="btn-xs btn-success" disabled><span class="glyphicon glyphicon-plus"></span></button> - Click to apply MAAP Allocation filters search filters on table. ONLY click once. </li></ul></li></ul></li><li>Clickable Actions Available Per Invoice in DataTable:</li>'; // inlineHtml += '<ul><li><button type="button" class="btn-xs" disabled><span class="span_class glyphicon glyphicon-pencil"></span></button> - Click to open Notes Section for Selected Invoice. (Notes Section is seperate from User Notes)</li>'; // inlineHtml += '<li><button type="button" class="btn-xs btn-secondary" disabled><span class="glyphicon glyphicon-eye-open"></span></button> - Click to Set Invoice has "Viewed" by a member of the Finance Team.</li>'; // inlineHtml += '<li><button type="button" class="btn-xs btn-info" disabled><span class="glyphicon glyphicon-time"></span></button> - Click to view Snooze Timers</li><li><button type="button" class="timer-1day form=control btn-xs btn-info" disabled><span class="span_class">1 Day</span></button> - Click to select Snooze duration of invoice from Table Collections Page.</li>'; // inlineHtml += '</li></ul></div>'; // inlineHtml += '<button type="button" class="btn btn-sm btn-info instruction_button" data-toggle="collapse" data-target="#demo">Click for Instructions</button><div id="demo" style="background-color: #cfeefc !important;border: 1px solid #417ed9;padding: 10px 10px 10px 20px;width:96%;position:absolute" class="collapse"><b><u>IMPORTANT INSTRUCTIONS:</u></b><ul><li>Functionalities available on the Customer listing/table:<ul><li><b>Sort</b><ul><li>Click on column headers to sort customer list according to the values in the columns. This is default to "Customer Name".</li><li>Hold "Shift" and click another column to sort according to multiple columns.</li></ul></li><li><b>Search</b><ul><li>You can search for specific customer by typing into the "Search" field</li></ul></li></ul></li><li>Clickable Actions available per customer:</li><ul><li><button class="btn-xs btn-default" disabled>UPLOAD SCF</button> - <ul><li>Available for customers with missing Service Commencement Forms (SCF) in the system. You will need to upload the latest signed SCF for each relevant customers which outlines the service commencement date along with the Service(s) and Price(s).</li></ul></li><li><button class="btn-xs btn-warning" disabled>REVIEW</button> / <button class="btn-xs btn-primary" disabled>EDIT</button> - <ul><li>Review or Edit customer details (eg. Addresses, Service and Pricing, Packages) to set them up for Run Digitalisation.</li></ul></li><li><button class="btn-xs btn-danger" disabled>CANCEL</button> - <ul><li>You may Cancel non-active customers providing details and reasons around the Cancellation.</li><li>You <b><u>DO NOT NEED</u></b> to cancel customers with <b><u>Adhoc</u></b> arrangements.</li></ul></li><li><button class="btn-xs btn-default" disabled>Duplicate COMMREG</button> - <ul><li>Please contact <b><u>Head Office</u></b> if you see this Action against any customer</li></ul></li></ul></li></ul></ul></div>'; // inlineHtml = '<div class="form-group container loading_section"></div>'; // inlineHtml += '<style> .loading_section { border: 14px solid #f3f3f3; border-radius: 50%; border-top: 14px solid #379E8F; width: 90px; height: 90px; -webkit-animation: spin 2s linear infinite; /* Safari */ animation: spin 2s linear infinite;'; // inlineHtml += 'left: 50%; }' //position: fixed; z-index: 1000; // /* Safari */ // inlineHtml += '@-webkit-keyframes spin {0% { -webkit-transform: rotate(0deg); } 100% { -webkit-transform: rotate(360deg); } }'; // inlineHtml += '@keyframes spin { 0% { transform: rotate(0deg); } 100% { transform: rotate(360deg); } }'; // inlineHtml += '</style>'; // Comm Reg inlineHtml += commRegSection(commReg); inlineHtml += "<br>"; inlineHtml += "<br>"; // Tab Selection inlineHtml += '<div class="tabSection hide">'; // inlineHtml += editTab(); inlineHtml += "</div>"; inlineHtml += "</div></div>"; // </div> form.addField({ id: "preview_table", label: "inlinehtml", type: "inlinehtml", }).updateLayoutType({ layoutType: ui.FieldLayoutType.STARTROW, }).defaultValue = inlineHtml; form.addField({ id: "custpage_price_change_edit_zee_id", label: "Zee ID", type: ui.FieldType.TEXT, }).updateDisplayType({ displayType: ui.FieldDisplayType.HIDDEN, }).defaultValue = zee_id; form.addField({ id: "custpage_price_change_edit_cust_id", label: "Customer ID", type: ui.FieldType.TEXT, }).updateDisplayType({ displayType: ui.FieldDisplayType.HIDDEN, }).defaultValue = cust_id; form.addField({ id: "custpage_price_change_edit_comm_reg", label: "Commencement Register", type: ui.FieldType.TEXT, }).updateDisplayType({ displayType: ui.FieldDisplayType.HIDDEN, }).defaultValue = commReg; form.clientScriptFileId = 5606277 //5595961; // context.response.writePage(form); } else { } } function commRegSection(commReg) { var inlineQty = '<style>table#comm_reg_preview {font-size: 12px;text-align: center;border: none;}.dataTables_wrapper {font-size: 14px;}table#comm_reg_preview th{text-align: center;} .bolded{font-weight: bold;}</style>'; /** * Comm Reg Header */ inlineQty += '<div class="form-group container comm_header_section">'; inlineQty += '<div class="row">'; inlineQty += '<div class="col-xs-12 heading1"><h4><span class="label label-default col-xs-12" style="background-color: #379E8F; color: white;">Commencement Register</span></h4></div>'; inlineQty += '</div>'; inlineQty += '</div>'; inlineQty += '<table id="comm_reg_preview" class="table table-responsive table-striped customer tablesorter" style="width: 100%;">'; inlineQty += '<thead style="color: white; background-color: #379E8F;">'; inlineQty += '<tr class="text-center">'; // inlineQty += '<th>Commencement Register</th>'; inlineQty += '</tr>'; inlineQty += '</thead>'; inlineQty += '<tbody id="result_data_comm_reg" class="result-data-comm-reg">'; inlineQty += '</tbody>'; inlineQty += '</table>'; // inlineQty += '<div class="form-row container comm_reg_section">' // inlineQty += '<div class="row">' // inlineQty += '<div class="col-xs-2"></div>' // Blank Placeholder // inlineQty += '<div class="col-xs-4 schedule_change_section"><input type="button" id="create_new" class="form-control btn btn-success btn-xs create_new" value="New Scheduled Change" data-toggle="tooltip" data-placement="right" title="NEW SCHEDULED CHANGE" /></div>'; // inlineQty += '<div class="col-xs-4 cancel_service_section"><input type="button" id="cancel_service" class="form-control btn btn-danger btn-xs cancel_service" value="Cancel Service" data-toggle="tooltip" data-placement="right" title="CANCEL SERVICE" /></div>'; // inlineQty += '<div class="col-xs-2"></div>' // Blank Placeholder // inlineQty += '</div>' // inlineQty += '</div>' return inlineQty; } /** * The table that will display the differents invoices linked to the franchisee and the time period. * @return {String} inlineQty */ function editTab() { var inlineQty = '<style>table#data_preview {font-size: 12px;text-align: center;border: none;}.dataTables_wrapper {font-size: 14px;}table#data_preview th{text-align: center;} .bolded{font-weight: bold;}</style>'; /** * Edit Header */ inlineQty += '<div class="form-group container edit_header_section">'; inlineQty += '<div class="row">'; inlineQty += '<div class="col-xs-12 heading1">'; inlineQty += '<h4><span style="background-color: #379E8F" class="form-group label label-default col-xs-12">Edit</span></h4>'; inlineQty += '</div></div></div>'; /** * Date Effective */ inlineQty += '<div class="form-group container date_effective_section">'; inlineQty += '<div class="row">'; // if (isNullorEmpty(dateEffective)) { inlineQty += '<div class="col-xs-6"><div class="input-group"><span style="background-color: #379E8F; color: white;" class="input-group-addon">Date Effective <span class="mandatory">*</span></span><input type="date" id="date_effective" value="" class="form-control date_effective" disabled/></div></div>'; // } else { // start_date = GetFormattedDate(dateEffective); // inlineQty += '<div class="col-xs-7 "><div class="input-group"><span class="input-group-addon">DATE EFFECTIVE <span class="mandatory">*</span></span><input type="date" id="date_effective" value="' + start_date + '" data-olddate="' + dateEffective + '" class="form-control date_effective"/></div></div>'; // } /** * Sales Type */ inlineQty += '<div class="col-xs-6 commencementtype"><div class="input-group"><span style="background-color: #379E8F; color: white;" class="input-group-addon" id="commencementtype_text">Sale Type <span class="mandatory">*</span></span><select id="commencementtype" class="form-control commencementtype" disabled><option></option>'; var col = new Array(); col[0] = search.createColumn({ name: 'name', }) col[1] = search.createColumn({ name: 'internalId', }); var results = search.create({ type: 'customlist_sale_type', columns: col }); results.run().each(function(res) { var listValue = res.getValue({ name: 'name' }); var listID = res.getValue({ name: 'internalId' }); // if (!isNullorEmpty(sale_type) && sale_type == listID) { // inlineQty += '<option value="' + listID + '" selected>' + listValue + '</option>'; // } else { inlineQty += '<option value="' + listID + '">' + listValue + '</option>'; // } return true; }) inlineQty += '</select></div></div>'; inlineQty += '</div>'; inlineQty += '</div>'; /** * DataTable */ inlineQty += '<table id="data_preview" class="table table-responsive table-striped customer tablesorter" style="width: 100%;">'; inlineQty += '<thead style="color: white; background-color: #379E8F;">'; inlineQty += '<tr class="text-center">'; inlineQty += '</tr>'; inlineQty += '</thead>'; inlineQty += '<tbody id="result_data" class="result-data"></tbody>'; inlineQty += '</table>'; inlineQty += '<div class="form-row container edit_submit_section">' inlineQty += '<div class="row">' inlineQty += '<div class="col-xs-2"></div>' // Blank Placeholder inlineQty += '<div class="col-xs-4 schedule_change_section"><input type="button" id="sumbit_edit" style="color: #103D39;" class="form-control btn btn-warning btn-xs sumbit_edit" value="Submit" data-toggle="tooltip" data-placement="right" title="Submit" /></div>'; inlineQty += '<div class="col-xs-4 cancel_service_section"><input type="button" id="next_customer" style="color: #103D39;" class="form-control btn btn-warning btn-xs next_customer" value="Next Customer" data-toggle="tooltip" data-placement="right" title="Next Customer" /></div>'; inlineQty += '<div class="col-xs-2"></div>' // Blank Placeholder inlineQty += '</div>' inlineQty += '</div>' return inlineQty; } /** * The period dropdown field. * @param {String} date_from * @param {String} date_to * @return {String} `inlineQty` */ function periodDropdownSection(date_from, date_to) { var selected_option = (isNullorEmpty(date_from) && isNullorEmpty(date_to)) ? 'selected' : ''; var inlineQty = '<div class="form-group container period_dropdown_section">'; inlineQty += '<div class="row">'; // Period dropdown field inlineQty += '<div class="col-xs-12 period_dropdown_div">'; inlineQty += '<div class="input-group">'; inlineQty += '<span class="input-group-addon" id="period_dropdown_text">Period</span>'; inlineQty += '<select id="period_dropdown" class="form-control">'; inlineQty += '<option ' + selected_option + '></option>'; inlineQty += '<option value="this_week">This Week</option>'; inlineQty += '<option value="last_week">Last Week</option>'; inlineQty += '<option value="this_month">This Month</option>'; inlineQty += '<option value="last_month">Last Month</option>'; inlineQty += '<option value="full_year">Full Year (1 Jan -)</option>'; inlineQty += '<option value="financial_year">Financial Year (1 Jul -)</option>'; inlineQty += '</select>'; inlineQty += '</div></div></div></div>'; return inlineQty; } /** * Used to pass the values of `date_from` and `date_to` between the scripts and to Netsuite for the records and the search. * @param {String} date_iso "2020-06-01" * @returns {String} date_netsuite "1/6/2020" */ function dateISOToNetsuite(date_iso) { var date_netsuite = ''; if (!isNullorEmpty(date_iso)) { var date_utc = new Date(date_iso); // var date_netsuite = nlapiDateToString(date_utc); var date_netsuite = format.format({ value: date_utc, type: format.Type.DATE }); } return date_netsuite; } function isNullorEmpty(strVal) { return (strVal == null || strVal == '' || strVal == 'null' || strVal == undefined || strVal == 'undefined' || strVal == '- None -'); } return { onRequest: onRequest } });
/** * @NScriptName Geocoding Script * @NApiVersion 2.x * @NScriptType Suitelet * @NModuleScope SameAccount */ define(["require", "exports", "N/search", "N/ui/serverWidget", "N/log"], function (require, exports, search, ui, log) { Object.defineProperty(exports, "__esModule", { value: true }); function onRequest(context) { if (context.request.method === "GET") { var customerSearch = search.create({ type: search.Type.CUSTOMER, columns: ["country"] }).run().getRange({ start: 0, end: 999 }); log.debug("customers' search", customerSearch); // let dataTable = [ // ['Country', 'Popularity'], // ['Egypt', 800], // ['Germany', 200], // ['United States', 300], // ['Brazil', 400], // ['Canada', 500], // ['France', 600] // ]; // dataTable.push(['China', 1000]); var html = "\n <script type=\"text/javascript\" src=\"https://www.gstatic.com/charts/loader.js\"></script>\n <div id=\"map_regions_div\" style=\"width: 900px; height: 500px;\"></div>\n <script type=\"text/javascript\">\n google.charts.load('current', {\n 'packages':['geochart'],\n 'mapsApiKey': 'AIzaSyD-9tSrke72PouQMnMX-a7eZSW0jkFMBWY'\n });\n google.charts.setOnLoadCallback(drawRegionsMap);\n \n function drawRegionsMap() {\n var data = google.visualization.arrayToDataTable([\n ['Country', 'Popularity'],\n ['Germany', 200],\n ['United States', 300],\n ['Brazil', 400],\n ['Canada', 500],\n ['France', 600],\n ['RU', 700]\n ]);\n \n var options = {};\n \n var chart = new google.visualization.GeoChart(document.getElementById('map_regions_div'));\n \n chart.draw(data, options);\n }\n </script>"; var form = ui.createForm({ title: 'Google Map Chart' }); var chartField = form.addField({ id: 'google_map_chart_html', label: 'Google Map Chart', type: ui.FieldType.INLINEHTML }); chartField.defaultValue = html; context.response.writePage(form); } } exports.onRequest = onRequest; });
343
[{"tag": "KEY", "value": "AIzaSyD-9tSrke72PouQMnMX-a7eZSW0jkFMBWY", "start": 1367, "end": 1406}]
true
1
/** * @NScriptName Geocoding Script * @NApiVersion 2.x * @NScriptType Suitelet * @NModuleScope SameAccount */ define(["require", "exports", "N/search", "N/ui/serverWidget", "N/log"], function (require, exports, search, ui, log) { Object.defineProperty(exports, "__esModule", { value: true }); function onRequest(context) { if (context.request.method === "GET") { var customerSearch = search.create({ type: search.Type.CUSTOMER, columns: ["country"] }).run().getRange({ start: 0, end: 999 }); log.debug("customers' search", customerSearch); // let dataTable = [ // ['Country', 'Popularity'], // ['Egypt', 800], // ['Germany', 200], // ['United States', 300], // ['Brazil', 400], // ['Canada', 500], // ['France', 600] // ]; // dataTable.push(['China', 1000]); var html = "\n <script type=\"text/javascript\" src=\"https://www.gstatic.com/charts/loader.js\"></script>\n <div id=\"map_regions_div\" style=\"width: 900px; height: 500px;\"></div>\n <script type=\"text/javascript\">\n google.charts.load('current', {\n 'packages':['geochart'],\n 'mapsApiKey': 'se2xy1bknelxn4y8xzxu3trosptip3q5'\n });\n google.charts.setOnLoadCallback(drawRegionsMap);\n \n function drawRegionsMap() {\n var data = google.visualization.arrayToDataTable([\n ['Country', 'Popularity'],\n ['Germany', 200],\n ['United States', 300],\n ['Brazil', 400],\n ['Canada', 500],\n ['France', 600],\n ['RU', 700]\n ]);\n \n var options = {};\n \n var chart = new google.visualization.GeoChart(document.getElementById('map_regions_div'));\n \n chart.draw(data, options);\n }\n </script>"; var form = ui.createForm({ title: 'Google Map Chart' }); var chartField = form.addField({ id: 'google_map_chart_html', label: 'Google Map Chart', type: ui.FieldType.INLINEHTML }); chartField.defaultValue = html; context.response.writePage(form); } } exports.onRequest = onRequest; });
true
/** * @NScriptName Geocoding Script * @NApiVersion 2.x * @NScriptType Suitelet * @NModuleScope SameAccount */ define(["require", "exports", "N/search", "N/ui/serverWidget", "N/log"], function (require, exports, search, ui, log) { Object.defineProperty(exports, "__esModule", { value: true }); function onRequest(context) { if (context.request.method === "GET") { var customerSearch = search.create({ type: search.Type.CUSTOMER, columns: ["country"] }).run().getRange({ start: 0, end: 999 }); log.debug("customers' search", customerSearch); // let dataTable = [ // ['Country', 'Popularity'], // ['Egypt', 800], // ['Germany', 200], // ['United States', 300], // ['Brazil', 400], // ['Canada', 500], // ['France', 600] // ]; // dataTable.push(['China', 1000]); var html = "\n <script type=\"text/javascript\" src=\"https://www.gstatic.com/charts/loader.js\"></script>\n <div id=\"map_regions_div\" style=\"width: 900px; height: 500px;\"></div>\n <script type=\"text/javascript\">\n google.charts.load('current', {\n 'packages':['geochart'],\n 'mapsApiKey': 'PI:KEY:se2xy1bknelxn4y8xzxu3trosptip3q5END_PI'\n });\n google.charts.setOnLoadCallback(drawRegionsMap);\n \n function drawRegionsMap() {\n var data = google.visualization.arrayToDataTable([\n ['Country', 'Popularity'],\n ['Germany', 200],\n ['United States', 300],\n ['Brazil', 400],\n ['Canada', 500],\n ['France', 600],\n ['RU', 700]\n ]);\n \n var options = {};\n \n var chart = new google.visualization.GeoChart(document.getElementById('map_regions_div'));\n \n chart.draw(data, options);\n }\n </script>"; var form = ui.createForm({ title: 'Google Map Chart' }); var chartField = form.addField({ id: 'google_map_chart_html', label: 'Google Map Chart', type: ui.FieldType.INLINEHTML }); chartField.defaultValue = html; context.response.writePage(form); } } exports.onRequest = onRequest; });
/** * @NApiVersion 2.x * @NScriptType Suitelet * @NModuleScope SameAccount */ define(['N/file', 'N/record', 'N/render', 'N/ui/serverWidget', 'SuiteScripts/CustomScripts/SuitePDF/api/estimate', 'SuiteScripts/CustomScripts/SuiteBox/api/suitebox', '../../Library/handlebars', '../../Library/handlebars/handlebarshelper'], /** * @param {file} file * @param {record} record * @param {render} render */ function (file, record, render, serverWidget, estimate, suitebox, handlebars, handlebarshelper) { /** * Definition of the Suitelet script trigger point. * * @param {Object} context * @param {ServerRequest} context.request - Encapsulation of the incoming request * @param {ServerResponse} context.response - Encapsulation of the Suitelet response * @Since 2015.2 */ function onRequest(context) { var paramReq = context.request.parameters; var idRec = paramReq.recid; var sType = paramReq.rectype; var sAction = paramReq.action; var sPdfTemplate = ''; var sTemplate = file.load({ id: 'SuiteScripts/CustomScripts/SuiteBox/template/pdfobject.html' }).getContents(); var retMe = { status: '', response: '' }; var idFolder = '156766524816'; var idSignedFolder = '156767063747'; var sEmail = ''; if (sAction == 'upload') { var pdfFile = render.xmlToPdf({ xmlString: 'Test Box Sign' }); pdfFile.name = 'TestBoxSign2.pdf'; var stbxFolder = suitebox.updateFolder({ data: { 'folder_upload_email': { 'access': 'open' }, id: idFolder } }); if (stbxFolder.status == 'SUCCESS') { sEmail = stbxFolder.response.data.folder_upload_email.email; log.audit({ title: 'sEmail', details: 'sEmail: ' + sEmail }); } else if (stbxFolder.status == 'FAILED') { log.audit({ title: 'stbxFolder', details: 'FAILED' }); } var stbxUpload = suitebox.emailUpload2({ data: { author: 171596, email: sEmail, subject: 'subject', body: 'body', attachments: [pdfFile] } }); if (stbxUpload.status == 'SUCCESS') { retMe.status = 'SUCCESS'; retMe.response = { message: 'Uploading in Progress.' }; } else{ retMe.status = 'FAILED'; retMe.response = { message : stbxUpload.response.message }; } context.response.setHeader({ name: 'Content-Type', value: 'application/json' }); context.response.write(JSON.stringify(retMe)); } else if (sAction == 'checkfile') { var stbxItems = suitebox.folderItems({ data: { 'folder': idFolder, 'name': 'TestBoxSign2.pdf' } }); if (stbxItems.status == 'SUCCESS') { var objFile = stbxItems.response.data.filter( function(file){ return file.name == 'TestBoxSign2.pdf'; } ); if(objFile.length > 0){ retMe.status = 'SUCCESS'; retMe.response = { id : objFile[0].id } } else{ retMe.status = 'SUCCESS'; retMe.response = { message: 'Uploading in Progress.' }; } } else{ retMe.status = 'FAILED'; retMe.response = { message : stbxItems.response.message } } context.response.setHeader({ name: 'Content-Type', value: 'application/json' }); context.response.write(JSON.stringify(retMe)); } else if (sAction == 'sign') { var stbxSign = suitebox.requestSign({ data: { 'signers': [{ 'role': 'signer', 'email': 'patrick.alcomendas@servicerocket.com' } ], 'source_files': [{ 'type': 'file', 'id': stbxItems.response.data[0].id } ], 'parent_folder': { 'type': 'folder', 'id': idSignedFolder } } }); if (stbxSign.status == 'SUCCESS') { retMe.status = 'SUCCESS'; retMe.response.message = 'Sign Request Created.'; } else{ retMe.status = 'FAILED'; retMe.response.message = stbxSign.response.message; } context.response.setHeader({ name: 'Content-Type', value: 'application/json' }); context.response.write(JSON.stringify(retMe)); var x = 1; } else{ var objForm = serverWidget.createForm({ title: 'BoxSign 1.0' }); var fldHtml = objForm.addField({ id: 'custpage_htmlfield', type: serverWidget.FieldType.INLINEHTML, label: 'HTML' }); var sHandlebar = handlebars.compile(sTemplate); handlebars = handlebarshelper.register(handlebars); var sHtmlTemplate = sHandlebar({ type: sType, id: idRec }); fldHtml.defaultValue = sHtmlTemplate; context.response.writePage(objForm); } } return { onRequest: onRequest }; });
809
[{"tag": "EMAIL", "value": "patrick.alcomendas@servicerocket.com", "start": 4419, "end": 4455}]
true
1
/** * @NApiVersion 2.x * @NScriptType Suitelet * @NModuleScope SameAccount */ define(['N/file', 'N/record', 'N/render', 'N/ui/serverWidget', 'SuiteScripts/CustomScripts/SuitePDF/api/estimate', 'SuiteScripts/CustomScripts/SuiteBox/api/suitebox', '../../Library/handlebars', '../../Library/handlebars/handlebarshelper'], /** * @param {file} file * @param {record} record * @param {render} render */ function (file, record, render, serverWidget, estimate, suitebox, handlebars, handlebarshelper) { /** * Definition of the Suitelet script trigger point. * * @param {Object} context * @param {ServerRequest} context.request - Encapsulation of the incoming request * @param {ServerResponse} context.response - Encapsulation of the Suitelet response * @Since 2015.2 */ function onRequest(context) { var paramReq = context.request.parameters; var idRec = paramReq.recid; var sType = paramReq.rectype; var sAction = paramReq.action; var sPdfTemplate = ''; var sTemplate = file.load({ id: 'SuiteScripts/CustomScripts/SuiteBox/template/pdfobject.html' }).getContents(); var retMe = { status: '', response: '' }; var idFolder = '156766524816'; var idSignedFolder = '156767063747'; var sEmail = ''; if (sAction == 'upload') { var pdfFile = render.xmlToPdf({ xmlString: 'Test Box Sign' }); pdfFile.name = 'TestBoxSign2.pdf'; var stbxFolder = suitebox.updateFolder({ data: { 'folder_upload_email': { 'access': 'open' }, id: idFolder } }); if (stbxFolder.status == 'SUCCESS') { sEmail = stbxFolder.response.data.folder_upload_email.email; log.audit({ title: 'sEmail', details: 'sEmail: ' + sEmail }); } else if (stbxFolder.status == 'FAILED') { log.audit({ title: 'stbxFolder', details: 'FAILED' }); } var stbxUpload = suitebox.emailUpload2({ data: { author: 171596, email: sEmail, subject: 'subject', body: 'body', attachments: [pdfFile] } }); if (stbxUpload.status == 'SUCCESS') { retMe.status = 'SUCCESS'; retMe.response = { message: 'Uploading in Progress.' }; } else{ retMe.status = 'FAILED'; retMe.response = { message : stbxUpload.response.message }; } context.response.setHeader({ name: 'Content-Type', value: 'application/json' }); context.response.write(JSON.stringify(retMe)); } else if (sAction == 'checkfile') { var stbxItems = suitebox.folderItems({ data: { 'folder': idFolder, 'name': 'TestBoxSign2.pdf' } }); if (stbxItems.status == 'SUCCESS') { var objFile = stbxItems.response.data.filter( function(file){ return file.name == 'TestBoxSign2.pdf'; } ); if(objFile.length > 0){ retMe.status = 'SUCCESS'; retMe.response = { id : objFile[0].id } } else{ retMe.status = 'SUCCESS'; retMe.response = { message: 'Uploading in Progress.' }; } } else{ retMe.status = 'FAILED'; retMe.response = { message : stbxItems.response.message } } context.response.setHeader({ name: 'Content-Type', value: 'application/json' }); context.response.write(JSON.stringify(retMe)); } else if (sAction == 'sign') { var stbxSign = suitebox.requestSign({ data: { 'signers': [{ 'role': 'signer', 'email': 'hzdkv@example.com' } ], 'source_files': [{ 'type': 'file', 'id': stbxItems.response.data[0].id } ], 'parent_folder': { 'type': 'folder', 'id': idSignedFolder } } }); if (stbxSign.status == 'SUCCESS') { retMe.status = 'SUCCESS'; retMe.response.message = 'Sign Request Created.'; } else{ retMe.status = 'FAILED'; retMe.response.message = stbxSign.response.message; } context.response.setHeader({ name: 'Content-Type', value: 'application/json' }); context.response.write(JSON.stringify(retMe)); var x = 1; } else{ var objForm = serverWidget.createForm({ title: 'BoxSign 1.0' }); var fldHtml = objForm.addField({ id: 'custpage_htmlfield', type: serverWidget.FieldType.INLINEHTML, label: 'HTML' }); var sHandlebar = handlebars.compile(sTemplate); handlebars = handlebarshelper.register(handlebars); var sHtmlTemplate = sHandlebar({ type: sType, id: idRec }); fldHtml.defaultValue = sHtmlTemplate; context.response.writePage(objForm); } } return { onRequest: onRequest }; });
true
/** * @NApiVersion 2.x * @NScriptType Suitelet * @NModuleScope SameAccount */ define(['N/file', 'N/record', 'N/render', 'N/ui/serverWidget', 'SuiteScripts/CustomScripts/SuitePDF/api/estimate', 'SuiteScripts/CustomScripts/SuiteBox/api/suitebox', '../../Library/handlebars', '../../Library/handlebars/handlebarshelper'], /** * @param {file} file * @param {record} record * @param {render} render */ function (file, record, render, serverWidget, estimate, suitebox, handlebars, handlebarshelper) { /** * Definition of the Suitelet script trigger point. * * @param {Object} context * @param {ServerRequest} context.request - Encapsulation of the incoming request * @param {ServerResponse} context.response - Encapsulation of the Suitelet response * @Since 2015.2 */ function onRequest(context) { var paramReq = context.request.parameters; var idRec = paramReq.recid; var sType = paramReq.rectype; var sAction = paramReq.action; var sPdfTemplate = ''; var sTemplate = file.load({ id: 'SuiteScripts/CustomScripts/SuiteBox/template/pdfobject.html' }).getContents(); var retMe = { status: '', response: '' }; var idFolder = '156766524816'; var idSignedFolder = '156767063747'; var sEmail = ''; if (sAction == 'upload') { var pdfFile = render.xmlToPdf({ xmlString: 'Test Box Sign' }); pdfFile.name = 'TestBoxSign2.pdf'; var stbxFolder = suitebox.updateFolder({ data: { 'folder_upload_email': { 'access': 'open' }, id: idFolder } }); if (stbxFolder.status == 'SUCCESS') { sEmail = stbxFolder.response.data.folder_upload_email.email; log.audit({ title: 'sEmail', details: 'sEmail: ' + sEmail }); } else if (stbxFolder.status == 'FAILED') { log.audit({ title: 'stbxFolder', details: 'FAILED' }); } var stbxUpload = suitebox.emailUpload2({ data: { author: 171596, email: sEmail, subject: 'subject', body: 'body', attachments: [pdfFile] } }); if (stbxUpload.status == 'SUCCESS') { retMe.status = 'SUCCESS'; retMe.response = { message: 'Uploading in Progress.' }; } else{ retMe.status = 'FAILED'; retMe.response = { message : stbxUpload.response.message }; } context.response.setHeader({ name: 'Content-Type', value: 'application/json' }); context.response.write(JSON.stringify(retMe)); } else if (sAction == 'checkfile') { var stbxItems = suitebox.folderItems({ data: { 'folder': idFolder, 'name': 'TestBoxSign2.pdf' } }); if (stbxItems.status == 'SUCCESS') { var objFile = stbxItems.response.data.filter( function(file){ return file.name == 'TestBoxSign2.pdf'; } ); if(objFile.length > 0){ retMe.status = 'SUCCESS'; retMe.response = { id : objFile[0].id } } else{ retMe.status = 'SUCCESS'; retMe.response = { message: 'Uploading in Progress.' }; } } else{ retMe.status = 'FAILED'; retMe.response = { message : stbxItems.response.message } } context.response.setHeader({ name: 'Content-Type', value: 'application/json' }); context.response.write(JSON.stringify(retMe)); } else if (sAction == 'sign') { var stbxSign = suitebox.requestSign({ data: { 'signers': [{ 'role': 'signer', 'email': 'PI:EMAIL:hzdkv@example.comEND_PI' } ], 'source_files': [{ 'type': 'file', 'id': stbxItems.response.data[0].id } ], 'parent_folder': { 'type': 'folder', 'id': idSignedFolder } } }); if (stbxSign.status == 'SUCCESS') { retMe.status = 'SUCCESS'; retMe.response.message = 'Sign Request Created.'; } else{ retMe.status = 'FAILED'; retMe.response.message = stbxSign.response.message; } context.response.setHeader({ name: 'Content-Type', value: 'application/json' }); context.response.write(JSON.stringify(retMe)); var x = 1; } else{ var objForm = serverWidget.createForm({ title: 'BoxSign 1.0' }); var fldHtml = objForm.addField({ id: 'custpage_htmlfield', type: serverWidget.FieldType.INLINEHTML, label: 'HTML' }); var sHandlebar = handlebars.compile(sTemplate); handlebars = handlebarshelper.register(handlebars); var sHtmlTemplate = sHandlebar({ type: sType, id: idRec }); fldHtml.defaultValue = sHtmlTemplate; context.response.writePage(objForm); } } return { onRequest: onRequest }; });
/** * Sales Reps Restlet API * * @NApiVersion 2.x * @NScriptType Restlet * @author trungpv <trung@lexor.com> */ define(['N/search', 'N/record'], function(search, record) { function _get(context) { try { var roleList = { internalid: 1036 }; var salesReps = search.create({ type: search.Type.EMPLOYEE, filters: [ { name: 'salesrep', operator: search.Operator.IS, values: 'T' }, { name: 'isinactive', operator: search.Operator.IS, values: 'F' }, { name: 'internalid', join: 'role', operator: search.Operator.ANYOF, values: JSON.parse(JSON.stringify(roleList)) } ], columns: ['internalid', 'firstname', 'middlename', 'lastname', 'email'] }); var searchResults = salesReps.run().getRange({ start: 0, end: 1000 }); return searchResults; } catch (error) { return error; } } function _post(context) {} function _put(context) {} function _delete(context) {} return { get: _get, post: _post, put: _put, delete: _delete }; });
232
[{"tag": "EMAIL", "value": "trung@lexor.com", "start": 97, "end": 112}]
true
1
/** * Sales Reps Restlet API * * @NApiVersion 2.x * @NScriptType Restlet * @author trungpv <hzdkv@example.com> */ define(['N/search', 'N/record'], function(search, record) { function _get(context) { try { var roleList = { internalid: 1036 }; var salesReps = search.create({ type: search.Type.EMPLOYEE, filters: [ { name: 'salesrep', operator: search.Operator.IS, values: 'T' }, { name: 'isinactive', operator: search.Operator.IS, values: 'F' }, { name: 'internalid', join: 'role', operator: search.Operator.ANYOF, values: JSON.parse(JSON.stringify(roleList)) } ], columns: ['internalid', 'firstname', 'middlename', 'lastname', 'email'] }); var searchResults = salesReps.run().getRange({ start: 0, end: 1000 }); return searchResults; } catch (error) { return error; } } function _post(context) {} function _put(context) {} function _delete(context) {} return { get: _get, post: _post, put: _put, delete: _delete }; });
true
/** * Sales Reps Restlet API * * @NApiVersion 2.x * @NScriptType Restlet * @author trungpv <PI:EMAIL:hzdkv@example.comEND_PI> */ define(['N/search', 'N/record'], function(search, record) { function _get(context) { try { var roleList = { internalid: 1036 }; var salesReps = search.create({ type: search.Type.EMPLOYEE, filters: [ { name: 'salesrep', operator: search.Operator.IS, values: 'T' }, { name: 'isinactive', operator: search.Operator.IS, values: 'F' }, { name: 'internalid', join: 'role', operator: search.Operator.ANYOF, values: JSON.parse(JSON.stringify(roleList)) } ], columns: ['internalid', 'firstname', 'middlename', 'lastname', 'email'] }); var searchResults = salesReps.run().getRange({ start: 0, end: 1000 }); return searchResults; } catch (error) { return error; } } function _post(context) {} function _put(context) {} function _delete(context) {} return { get: _get, post: _post, put: _put, delete: _delete }; });
ο»Ώ/// <reference path="../lib/N/scriptcontext.js" /> /// <reference path="../lib/N/modules/search.js" /> /// <reference path="../lib/N/modules/runtime.js" /> /// <reference path="../lib/N/modules/record.js" /> /// <reference path="../lib/N/modules/log.js" /> /// <reference path="../lib/N/modules/email.js" /> /// <reference path="../lib/N/modules/error.js" /> /** * @NApiVersion 2.0 * @NScriptType MapReduceScript */ 'use strict'; define(['N/search', 'N/record', 'N/email', 'N/runtime', 'N/error'], /** * @param {N.search.module} search * @param {N.record.module} record * @param {N.email.module} email * @param {N.runtime.module} runtime * @param {N.error.module} error */ function (search, record, email, runtime, error) { function handleErrorAndSendNotification(e, stage) { log.error('Stage: ' + stage + ' failed', e); var author = -5; var recipients = 'notify@company.com'; var subject = 'Map/Reduce script ' + runtime.getCurrentScript().id + ' failed for stage: ' + stage; var body = 'An error occurred with the following information:\n' + 'Error code: ' + e.name + '\n' + 'Error msg: ' + e.message; email.send({ author: author, recipients: recipients, subject: subject, body: body }); } /** * @param {N.scriptContext.MR.Summary} summary */ function handleErrorIfAny(summary) { var inputSummary = summary.inputSummary; var mapSummary = summary.mapSummary; var reduceSummary = summary.reduceSummary; if (inputSummary.error) { var e = error.create({ name: 'INPUT_STAGE_FAILED', message: inputSummary.error }); handleErrorAndSendNotification(e, 'getInputData'); } handleErrorInStage('map', mapSummary); handleErrorInStage('reduce', reduceSummary); } /** * @param {String} stage * @param {N.scriptContext.MR.MapSummary} summary */ function handleErrorInStage(stage, summary) { var errorMsg = []; summary.errors.iterator().each(function (key, value) { var msg = 'Failure to accept payment from customer id: ' + key + '. Error was: ' + JSON.parse(value).message + '\n'; errorMsg.push(msg); return true; }); if (errorMsg.length > 0) { var e = error.create({ name: 'RECORD_TRANSFORM_FAILED', message: JSON.stringify(errorMsg) }); handleErrorAndSendNotification(e, stage); } } function createSummaryRecord(summary) { try { var seconds = summary.seconds; var usage = summary.usage; var yields = summary.yields; var rec = record.create({ type: 'customrecord_summary', }); rec.setValue({ fieldId: 'name', value: 'Summary for M/R script: ' + runtime.getCurrentScript().id }); rec.setValue({ fieldId: 'custrecord_time', value: seconds }); rec.setValue({ fieldId: 'custrecord_usage', value: usage }); rec.setValue({ fieldId: 'custrecord_yields', value: yields }); rec.save(); } catch (e) { handleErrorAndSendNotification(e, 'summarize'); } } function applyLocationDiscountToInvoice(recordId) { var invoice = record.load({ type: record.Type.INVOICE, id: recordId, isDynamic: true }); var location = invoice.getText({ fieldId: 'location' }); var discount; if (location === 'East Coast') { discount = 'Eight Percent'; } else if (location === 'West Coast') { discount = 'Five Percent'; } else if (location === 'United Kingdom') { discount = 'Nine Percent'; } else { discount = ''; } invoice.setText({ fieldId: 'discountitem', text: discount, ignoreFieldChange: false }); log.debug(recordId + ' has been updated with location-based discount.'); invoice.save(); } /** * @param {N.scriptContext.MR.GetInputContext} context */ function getInputData(context) { return search.create({ type: record.Type.INVOICE, filters: [['status', search.Operator.IS, 'open']], columns: ['entity'], title: 'Open Invoice Search' }); } /** * @param {N.scriptContext.MR.MapContext} context */ function map(context) { var searchResult = JSON.parse(context.value); var invoiceId = searchResult.id; var entityId = searchResult.values.entity.value; applyLocationDiscountToInvoice(invoiceId); context.write(entityId, invoiceId); } /** * @param {N.scriptContext.MR.ReduceContext} context */ function reduce(context) { var customerId = context.key; var custPayment = record.transform({ fromType: record.Type.CUSTOMER, fromId: customerId, toType: record.Type.CUSTOMER_PAYMENT, isDynamic: true }); var lineCount = custPayment.getLineCount('apply'); for (var j = 0; j < lineCount; j += 1) { custPayment.selectLine({ sublistId: 'apply', line: j }); custPayment.setCurrentSublistValue({ sublistId: 'apply', fieldId: 'apply', value: true }); } var custPaymentId = custPayment.save(); context.write(custPaymentId); } /** * @param {N.scriptContext.MR.Summary} summary */ function summarize(summary) { handleErrorIfAny(summary); createSummaryRecord(summary); } return { getInputData: getInputData, map: map, reduce: reduce, summarize: summarize }; });
485
[{"tag": "EMAIL", "value": "notify@company.com", "start": 940, "end": 958}]
true
1
ο»Ώ/// <reference path="../lib/N/scriptcontext.js" /> /// <reference path="../lib/N/modules/search.js" /> /// <reference path="../lib/N/modules/runtime.js" /> /// <reference path="../lib/N/modules/record.js" /> /// <reference path="../lib/N/modules/log.js" /> /// <reference path="../lib/N/modules/email.js" /> /// <reference path="../lib/N/modules/error.js" /> /** * @NApiVersion 2.0 * @NScriptType MapReduceScript */ 'use strict'; define(['N/search', 'N/record', 'N/email', 'N/runtime', 'N/error'], /** * @param {N.search.module} search * @param {N.record.module} record * @param {N.email.module} email * @param {N.runtime.module} runtime * @param {N.error.module} error */ function (search, record, email, runtime, error) { function handleErrorAndSendNotification(e, stage) { log.error('Stage: ' + stage + ' failed', e); var author = -5; var recipients = 'dycjh@example.com'; var subject = 'Map/Reduce script ' + runtime.getCurrentScript().id + ' failed for stage: ' + stage; var body = 'An error occurred with the following information:\n' + 'Error code: ' + e.name + '\n' + 'Error msg: ' + e.message; email.send({ author: author, recipients: recipients, subject: subject, body: body }); } /** * @param {N.scriptContext.MR.Summary} summary */ function handleErrorIfAny(summary) { var inputSummary = summary.inputSummary; var mapSummary = summary.mapSummary; var reduceSummary = summary.reduceSummary; if (inputSummary.error) { var e = error.create({ name: 'INPUT_STAGE_FAILED', message: inputSummary.error }); handleErrorAndSendNotification(e, 'getInputData'); } handleErrorInStage('map', mapSummary); handleErrorInStage('reduce', reduceSummary); } /** * @param {String} stage * @param {N.scriptContext.MR.MapSummary} summary */ function handleErrorInStage(stage, summary) { var errorMsg = []; summary.errors.iterator().each(function (key, value) { var msg = 'Failure to accept payment from customer id: ' + key + '. Error was: ' + JSON.parse(value).message + '\n'; errorMsg.push(msg); return true; }); if (errorMsg.length > 0) { var e = error.create({ name: 'RECORD_TRANSFORM_FAILED', message: JSON.stringify(errorMsg) }); handleErrorAndSendNotification(e, stage); } } function createSummaryRecord(summary) { try { var seconds = summary.seconds; var usage = summary.usage; var yields = summary.yields; var rec = record.create({ type: 'customrecord_summary', }); rec.setValue({ fieldId: 'name', value: 'Summary for M/R script: ' + runtime.getCurrentScript().id }); rec.setValue({ fieldId: 'custrecord_time', value: seconds }); rec.setValue({ fieldId: 'custrecord_usage', value: usage }); rec.setValue({ fieldId: 'custrecord_yields', value: yields }); rec.save(); } catch (e) { handleErrorAndSendNotification(e, 'summarize'); } } function applyLocationDiscountToInvoice(recordId) { var invoice = record.load({ type: record.Type.INVOICE, id: recordId, isDynamic: true }); var location = invoice.getText({ fieldId: 'location' }); var discount; if (location === 'East Coast') { discount = 'Eight Percent'; } else if (location === 'West Coast') { discount = 'Five Percent'; } else if (location === 'United Kingdom') { discount = 'Nine Percent'; } else { discount = ''; } invoice.setText({ fieldId: 'discountitem', text: discount, ignoreFieldChange: false }); log.debug(recordId + ' has been updated with location-based discount.'); invoice.save(); } /** * @param {N.scriptContext.MR.GetInputContext} context */ function getInputData(context) { return search.create({ type: record.Type.INVOICE, filters: [['status', search.Operator.IS, 'open']], columns: ['entity'], title: 'Open Invoice Search' }); } /** * @param {N.scriptContext.MR.MapContext} context */ function map(context) { var searchResult = JSON.parse(context.value); var invoiceId = searchResult.id; var entityId = searchResult.values.entity.value; applyLocationDiscountToInvoice(invoiceId); context.write(entityId, invoiceId); } /** * @param {N.scriptContext.MR.ReduceContext} context */ function reduce(context) { var customerId = context.key; var custPayment = record.transform({ fromType: record.Type.CUSTOMER, fromId: customerId, toType: record.Type.CUSTOMER_PAYMENT, isDynamic: true }); var lineCount = custPayment.getLineCount('apply'); for (var j = 0; j < lineCount; j += 1) { custPayment.selectLine({ sublistId: 'apply', line: j }); custPayment.setCurrentSublistValue({ sublistId: 'apply', fieldId: 'apply', value: true }); } var custPaymentId = custPayment.save(); context.write(custPaymentId); } /** * @param {N.scriptContext.MR.Summary} summary */ function summarize(summary) { handleErrorIfAny(summary); createSummaryRecord(summary); } return { getInputData: getInputData, map: map, reduce: reduce, summarize: summarize }; });
true
ο»Ώ/// <reference path="../lib/N/scriptcontext.js" /> /// <reference path="../lib/N/modules/search.js" /> /// <reference path="../lib/N/modules/runtime.js" /> /// <reference path="../lib/N/modules/record.js" /> /// <reference path="../lib/N/modules/log.js" /> /// <reference path="../lib/N/modules/email.js" /> /// <reference path="../lib/N/modules/error.js" /> /** * @NApiVersion 2.0 * @NScriptType MapReduceScript */ 'use strict'; define(['N/search', 'N/record', 'N/email', 'N/runtime', 'N/error'], /** * @param {N.search.module} search * @param {N.record.module} record * @param {N.email.module} email * @param {N.runtime.module} runtime * @param {N.error.module} error */ function (search, record, email, runtime, error) { function handleErrorAndSendNotification(e, stage) { log.error('Stage: ' + stage + ' failed', e); var author = -5; var recipients = 'PI:EMAIL:dycjh@example.comEND_PI'; var subject = 'Map/Reduce script ' + runtime.getCurrentScript().id + ' failed for stage: ' + stage; var body = 'An error occurred with the following information:\n' + 'Error code: ' + e.name + '\n' + 'Error msg: ' + e.message; email.send({ author: author, recipients: recipients, subject: subject, body: body }); } /** * @param {N.scriptContext.MR.Summary} summary */ function handleErrorIfAny(summary) { var inputSummary = summary.inputSummary; var mapSummary = summary.mapSummary; var reduceSummary = summary.reduceSummary; if (inputSummary.error) { var e = error.create({ name: 'INPUT_STAGE_FAILED', message: inputSummary.error }); handleErrorAndSendNotification(e, 'getInputData'); } handleErrorInStage('map', mapSummary); handleErrorInStage('reduce', reduceSummary); } /** * @param {String} stage * @param {N.scriptContext.MR.MapSummary} summary */ function handleErrorInStage(stage, summary) { var errorMsg = []; summary.errors.iterator().each(function (key, value) { var msg = 'Failure to accept payment from customer id: ' + key + '. Error was: ' + JSON.parse(value).message + '\n'; errorMsg.push(msg); return true; }); if (errorMsg.length > 0) { var e = error.create({ name: 'RECORD_TRANSFORM_FAILED', message: JSON.stringify(errorMsg) }); handleErrorAndSendNotification(e, stage); } } function createSummaryRecord(summary) { try { var seconds = summary.seconds; var usage = summary.usage; var yields = summary.yields; var rec = record.create({ type: 'customrecord_summary', }); rec.setValue({ fieldId: 'name', value: 'Summary for M/R script: ' + runtime.getCurrentScript().id }); rec.setValue({ fieldId: 'custrecord_time', value: seconds }); rec.setValue({ fieldId: 'custrecord_usage', value: usage }); rec.setValue({ fieldId: 'custrecord_yields', value: yields }); rec.save(); } catch (e) { handleErrorAndSendNotification(e, 'summarize'); } } function applyLocationDiscountToInvoice(recordId) { var invoice = record.load({ type: record.Type.INVOICE, id: recordId, isDynamic: true }); var location = invoice.getText({ fieldId: 'location' }); var discount; if (location === 'East Coast') { discount = 'Eight Percent'; } else if (location === 'West Coast') { discount = 'Five Percent'; } else if (location === 'United Kingdom') { discount = 'Nine Percent'; } else { discount = ''; } invoice.setText({ fieldId: 'discountitem', text: discount, ignoreFieldChange: false }); log.debug(recordId + ' has been updated with location-based discount.'); invoice.save(); } /** * @param {N.scriptContext.MR.GetInputContext} context */ function getInputData(context) { return search.create({ type: record.Type.INVOICE, filters: [['status', search.Operator.IS, 'open']], columns: ['entity'], title: 'Open Invoice Search' }); } /** * @param {N.scriptContext.MR.MapContext} context */ function map(context) { var searchResult = JSON.parse(context.value); var invoiceId = searchResult.id; var entityId = searchResult.values.entity.value; applyLocationDiscountToInvoice(invoiceId); context.write(entityId, invoiceId); } /** * @param {N.scriptContext.MR.ReduceContext} context */ function reduce(context) { var customerId = context.key; var custPayment = record.transform({ fromType: record.Type.CUSTOMER, fromId: customerId, toType: record.Type.CUSTOMER_PAYMENT, isDynamic: true }); var lineCount = custPayment.getLineCount('apply'); for (var j = 0; j < lineCount; j += 1) { custPayment.selectLine({ sublistId: 'apply', line: j }); custPayment.setCurrentSublistValue({ sublistId: 'apply', fieldId: 'apply', value: true }); } var custPaymentId = custPayment.save(); context.write(custPaymentId); } /** * @param {N.scriptContext.MR.Summary} summary */ function summarize(summary) { handleErrorIfAny(summary); createSummaryRecord(summary); } return { getInputData: getInputData, map: map, reduce: reduce, summarize: summarize }; });
/** * * @NApiVersion 2.0 * @NScriptType Suitelet * @NAmdConfig ./custom_modules_config.json * Description: Calendar view page of the run * * @Last Modified by: Sruti Desai * */ define(['N/ui/serverWidget', 'N/email', 'N/runtime', 'N/search', 'N/record', 'N/http', 'N/log', 'N/redirect', 'N/format', 'moment'], function(ui, email, runtime, search, record, http, log, redirect, format, moment) { var baseURL = 'https://1048144.app.netsuite.com'; if (runtime.EnvType == "SANDBOX") { baseURL = 'https://1048144-sb3.app.netsuite.com'; } var zee = 0; var role = runtime.getCurrentUser().role; if (role == 1000) { //Franchisee zee = runtime.getCurrentUser(); } function onRequest(context) { if (context.request.method === 'GET') { var run = 0; var form = ui.createForm({ title: 'Run Scheduler' }); form.addField({ id: 'save_button', type: ui.FieldType.TEXT, label: 'save_button' }).updateDisplayType({ displayType: ui.FieldDisplayType.HIDDEN }).defaultValue = 'F'; form.addField({ id: 'stops', type: ui.FieldType.TEXT, label: 'stops' }).updateDisplayType({ displayType: ui.FieldDisplayType.HIDDEN }); form.addField({ id: 'duration', type: ui.FieldType.TEXT, label: 'duration' }).updateDisplayType({ displayType: ui.FieldDisplayType.HIDDEN }); form.addField({ id: 'freqs', type: ui.FieldType.TEXT, label: 'freqs' }).updateDisplayType({ displayType: ui.FieldDisplayType.HIDDEN }); form.addField({ id: 'start_times', type: ui.FieldType.TEXT, label: 'start_times' }).updateDisplayType({ displayType: ui.FieldDisplayType.HIDDEN }); log.debug({ title: 'zee', details: zee }); log.debug({ title: 'role', details: role }); run = context.request.parameters.run; var inlineQty = ''; inlineQty += '<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"><script type="text/javascript" src="//cdnjs.cloudflare.com/ajax/libs/jquery/2.2.1/jquery.min.js"></script><link href="//netdna.bootstrapcdn.com/bootstrap/3.3.2/css/bootstrap.min.css" rel="stylesheet"><script src="//netdna.bootstrapcdn.com/bootstrap/3.3.2/js/bootstrap.min.js"></script><script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.6.4/angular.min.js"></script><script src="https://cdnjs.cloudflare.com/ajax/libs/jspdf/1.5.1/jspdf.debug.js" integrity="sha384-THVO/sM0mFD9h7dfSndI6TS0PgAGavwKvB5hAxRRvc0o9cPLohB0wb/PTA7LdUHs" crossorigin="anonymous"></script><link rel="stylesheet" href="https://1048144.app.netsuite.com/core/media/media.nl?id=2060796&c=1048144&h=9ee6accfd476c9cae718&_xt=.css"/><script sr'; inlineQty += 'c="https://1048144.app.netsuite.com/core/media/media.nl?id=2060797&c=1048144&h=ef2cda20731d146b5e98&_xt=.js"></script><link type="text/css" rel="stylesheet" href="https://1048144.app.netsuite.com/core/media/media.nl?id=2090583&c=1048144&h=a0ef6ac4e28f91203dfe&_xt=.css">'; inlineQty += '<script type="text/javascript" src="//cdnjs.cloudflare.com/ajax/libs/moment.js/2.12.0/moment.min.js"></script><script type="text/javascript" src="https://1048144.app.netsuite.com/core/media/media.nl?id=2392604&c=1048144&h=6a28cec4ec4cd48e6a16&_xt=.js"></script> <link rel="stylesheet" type="text/css" href=https://1048144.app.netsuite.com/core/media/media.nl?id=2392605&c=1048144&h=3060708076f338e371ff&_xt=.css"><link rel="stylesheet" type="text/css" media="print" href="https://1048144.app.netsuite.com/core/media/media.nl?id=2392601&c=1048144&h=4e40a20752aed954e459&_xt=.css">'; inlineQty += '<script type="text/javascript" src="//cdnjs.cloudflare.com/ajax/libs/moment.js/2.12.0/moment.min.js"></script><link rel="stylesheet" type="text/css" href="https://cdnjs.cloudflare.com/ajax/libs/qtip2/3.0.3/jquery.qtip.min.css"><script type="text/javascript" src="https://cdnjs.cloudflare.com/ajax/libs/qtip2/3.0.3/jquery.qtip.min.js"></script>' inlineQty += '<div id="alert" class="alert alert-danger fade in"></div><div id="myModal" class="modal fade bs-example-modal-sm" tabindex="-1" role="dialog" aria-labelledby="mySmallModalLabel" aria-hidden="true"><div class="modal-dialog modal-sm" role="document" style="width :max-content"><div class="modal-content" style="width :max-content"><div class="modal-header"><button type="button" class="close" data-dismiss="modal" aria-label="Close"><span aria-hidden="true">&times;</span></button><h4 class="modal-title panel panel-info" id="exampleModalLabel">Information</h4><br> </div><div class="modal-body"></div><div class="modal-footer"><button type="button" class="btn btn-primary save_run" data-dismiss="modal">SAVE</button><button type="button" class="btn btn-default" data-dismiss="modal">Close</button></div></div></div></div>'; if (role != 1000) { inlineQty += '<div class="container" style="padding-top: 3%;"><div class="form-group container"><div class="row"><div class="input-group"><span class="input-group-addon">SELECT ZEE</span><select class="form-control zee_dropdown" >'; var searched_zee = search.load({ id: 'customsearch_job_inv_process_zee', type: search.Type.PARTNER }); var resultSet_zee = searched_zee.run(); var count_zee = 0; inlineQty += '<option value=""></option>' resultSet_zee.each(function(searchResult_zee) { zeeid = searchResult_zee.getValue('internalid'); zee_name = searchResult_zee.getValue('entityid'); if (context.request.parameters.zee == zeeid) { inlineQty += '<option value="' + zeeid + '" selected="selected">' + zee_name + '</option>'; } else { inlineQty += '<option value="' + zeeid + '">' + zee_name + '</option>'; } return true; }); inlineQty += '</select></div></div></div></div>'; zee = context.request.parameters.zee; } form.addField({ id: 'zee', type: ui.FieldType.TEXT, label: 'zee' }).updateDisplayType({ displayType: ui.FieldDisplayType.HIDDEN }).defaultValue = zee; if (zee != 0 && !isNullorEmpty(zee)) { var zee_record = record.load({ type: record.Type.PARTNER, id: parseInt(zee), isDynamic: true, }); var multi = zee_record.getValue({ fieldId: 'custentity_zee_multiple_territory' }); var multi_text = zee_record.getText({ fieldId: 'custentity_zee_multiple_territory' }); if (!isNullorEmpty(multi)) { var multi_zee_text = ''; form.addField({ id: 'multi_zee', type: ui.FieldType.TEXT, label: 'multi_zee' }).updateDisplayType({ displayType: ui.FieldDisplayType.HIDDEN }); if (multi.length > 1) { inlineQty += '<div class="container" style="padding-top: 3%;"><div class="form-group container"><div class="row"><div class="input-group"><span class="input-group-addon">MULTIPLE TERRITORIES OWNED</span><select readonly class = "form-control zee_dropdown" > '; for (var x = 0; x < multi.length; x++) { if (zee == multi[x]) { inlineQty += '<option selected="selected" value="' + multi[x] + '" data-right="" >' + multi_text[x] + '</option>'; } else { inlineQty += '<option value="' + multi[x] + '" data-right="" >' + multi_text[x] + '</option>'; } if (x != (multi.length - 1)) { multi_zee_text += multi_text[x] + ','; } else { multi_zee_text += multi_text[x]; } } } form.addField({ id: 'multi_zee_text', type: ui.FieldType.TEXT, label: 'multi_zee_text' }).updateDisplayType({ displayType: ui.FieldDisplayType.HIDDEN }).defaultValue = multi_zee_text; inlineQty += '</select></div></div></div></div>'; } else { form.addField({ id: 'multi_zee', type: ui.FieldType.TEXT, label: 'multi_zee' }).updateDisplayType({ displayType: ui.FieldDisplayType.HIDDEN }); form.addField({ id: 'multi_zee_text', type: ui.FieldType.TEXT, label: 'multi_zee_text' }).updateDisplayType({ displayType: ui.FieldDisplayType.HIDDEN }); } inlineQty += '<div class="container select_run" style="padding-top: 3%;"><div class="form-group container"><div class="row"><div class="input-group"><span class="input-group-addon">SELECT RUN</span><select class="form-control run_dropdown" >'; var runPlanSearch = search.load({ id: 'customsearch_app_run_plan_active', type: 'customrecord_run_plan' }) if (!isNullorEmpty(multi)) { runPlanSearch.filters.push(search.createFilter({ name: 'custrecord_run_franchisee', operator: search.Operator.ANYOF, values: zee })); } else { runPlanSearch.filters.push(search.createFilter({ name: 'custrecord_run_franchisee', operator: search.Operator.IS, values: zee })); } var resultSet_runPlan = runPlanSearch.run(); var count_zee = 0; inlineQty += '<option value="' + 0 + '">ALL</option>' resultSet_runPlan.each(function(searchResult_runPlan) { runinternalid = searchResult_runPlan.getValue('internalid'); runname = searchResult_runPlan.getValue('name'); if (context.request.parameters.run == runinternalid) { inlineQty += '<option value="' + runinternalid + '" selected="selected">' + runname + '</option>'; } else { inlineQty += '<option value="' + runinternalid + '">' + runname + '</option>'; } return true; }); inlineQty += '</select></div></div></div></div>'; log.debug({ title: 'zee', details: zee }); log.debug({ title: 'run', details: run }); var serviceLegSearch = search.load({ id: 'customsearch_rp_leg_freq_all_2', type: 'customrecord_service_leg' }); serviceLegSearch.filters.push(search.createFilter({ name: 'custrecord_service_leg_franchisee', operator: search.Operator.ANYOF, values: zee })); if (!isNullorEmpty(run) && run != 0) { serviceLegSearch.filters.push(search.createFilter({ name: 'custrecord_service_freq_run_plan', join: 'custrecord_service_freq_stop', operator: search.Operator.IS, values: run })); } var resultSet = serviceLegSearch.run(); var stop_count = 0; var freq_count = 0; var old_stop_name = null; var service_id_array = []; var service_name_array = []; var service_descp_array = []; var old_customer_id_array = []; var old_customer_text_array = []; var old_customer_zee_array = []; var old_run_plan_array = []; var old_run_plan_text_array = []; var old_closing_day = []; var old_opening_day = []; var old_service_notes = []; var old_stop_duration = []; var stop_id; var stop_name; var address; var stop_duration; var stop_notes; var stop_lat; var stop_lon; var service_id; var service_text; var customer_id; var customer_text; var customer_zee; var ncl; var freq_id; var freq_mon; var freq_tue; var freq_wed; var freq_thu; var freq_fri; var freq_adhoc; var freq_time_current; var freq_time_start; var freq_time_end; var freq_run_plan; var old_stop_id = []; var old_stop_name; var old_service_time; var old_address; var old_stop_notes = ''; var old_stop_lat; var old_stop_lon; var old_service_id; var old_service_text; var old_customer_id; var old_customer_text; var old_customer_zee; var old_ncl; var old_freq_id = []; var old_freq_mon; var old_freq_tue; var old_freq_wed; var old_freq_thu; var old_freq_fri; var old_freq_adhoc; var old_freq_time_current; var old_freq_time_start; var old_freq_time_end; var old_freq_run_plan; var freq = []; var old_freq = []; var stop_freq_json_array = ['{ "data": [']; resultSet.each(function(searchResult) { stop_id = searchResult.getValue({ name: 'internalid', join: null, summary: search.Summary.GROUP }); stop_name = searchResult.getValue({ name: 'name', join: null, summary: search.Summary.GROUP }); stop_duration = parseInt(searchResult.getValue({ name: 'custrecord_service_leg_duration', join: null, summary: search.Summary.GROUP })); stop_notes = searchResult.getValue({ name: 'custrecord_service_leg_notes', join: null, summary: search.Summary.GROUP }); stop_lat = searchResult.getValue({ name: "custrecord_service_leg_addr_lat", join: null, summary: search.Summary.GROUP }); stop_lon = searchResult.getValue({ name: "custrecord_service_leg_addr_lon", join: null, summary: search.Summary.GROUP }); service_id = searchResult.getValue({ name: 'custrecord_service_leg_service', join: null, summary: search.Summary.GROUP }); service_text = searchResult.getText({ name: 'custrecord_service_leg_service', join: null, summary: search.Summary.GROUP }); customer_id = searchResult.getValue({ name: 'custrecord_service_leg_customer', join: null, summary: search.Summary.GROUP }); customer_text = searchResult.getText({ name: 'custrecord_service_leg_customer', join: null, summary: search.Summary.GROUP }); customer_zee = searchResult.getValue({ name: "partner", join: "CUSTRECORD_SERVICE_LEG_CUSTOMER", summary: search.Summary.GROUP }); customer_id_text = searchResult.getValue({ name: "entityid", join: "CUSTRECORD_SERVICE_LEG_CUSTOMER", summary: search.Summary.GROUP }); customer_name_text = searchResult.getValue({ name: "companyname", join: "CUSTRECORD_SERVICE_LEG_CUSTOMER", summary: search.Summary.GROUP }); ncl = searchResult.getValue({ name: 'custrecord_service_leg_non_cust_location', join: null, summary: search.Summary.GROUP }); freq_id = searchResult.getValue({ name: "internalid", join: "CUSTRECORD_SERVICE_FREQ_STOP", summary: search.Summary.GROUP }); freq_mon = searchResult.getValue({ name: "custrecord_service_freq_day_mon", join: "CUSTRECORD_SERVICE_FREQ_STOP", summary: search.Summary.GROUP }); freq_tue = searchResult.getValue({ name: "custrecord_service_freq_day_tue", join: "CUSTRECORD_SERVICE_FREQ_STOP", summary: search.Summary.GROUP }); freq_wed = searchResult.getValue({ name: "custrecord_service_freq_day_wed", join: "CUSTRECORD_SERVICE_FREQ_STOP", summary: search.Summary.GROUP }); freq_thu = searchResult.getValue({ name: "custrecord_service_freq_day_thu", join: "CUSTRECORD_SERVICE_FREQ_STOP", summary: search.Summary.GROUP }); freq_fri = searchResult.getValue({ name: "custrecord_service_freq_day_fri", join: "CUSTRECORD_SERVICE_FREQ_STOP", summary: search.Summary.GROUP }); freq_adhoc = searchResult.getValue({ name: "custrecord_service_freq_day_adhoc", join: "CUSTRECORD_SERVICE_FREQ_STOP", summary: search.Summary.GROUP }); freq_time_current = convertTo24Hour(searchResult.getValue({ name: "custrecord_service_freq_time_current", join: "CUSTRECORD_SERVICE_FREQ_STOP", summary: search.Summary.GROUP })); freq_time_start = convertTo24Hour(searchResult.getValue({ name: "custrecord_service_freq_time_start", join: "CUSTRECORD_SERVICE_FREQ_STOP", summary: search.Summary.GROUP })); freq_time_end = convertTo24Hour(searchResult.getValue({ name: "custrecord_service_freq_time_end", join: "CUSTRECORD_SERVICE_FREQ_STOP", summary: search.Summary.GROUP })); freq_run_plan = searchResult.getValue({ name: "custrecord_service_freq_run_plan", join: "CUSTRECORD_SERVICE_FREQ_STOP", summary: search.Summary.GROUP }); closing_day = searchResult.getValue({ name: "custrecord_service_leg_closing_date", join: null, summary: search.Summary.GROUP }); opening_day = searchResult.getValue({ name: "custrecord_service_leg_opening_date", join: null, summary: search.Summary.GROUP }); freq_run_plan_text = searchResult.getText({ name: "custrecord_service_freq_run_plan", join: "CUSTRECORD_SERVICE_FREQ_STOP", summary: search.Summary.GROUP }); freq_run_st_no = searchResult.getValue({ name: "custrecord_service_leg_addr_st_num_name", join: null, summary: search.Summary.GROUP }); freq_run_suburb = searchResult.getValue({ name: "custrecord_service_leg_addr_suburb", join: null, summary: search.Summary.GROUP }); freq_run_state = searchResult.getValue({ name: "custrecord_service_leg_addr_state", join: null, summary: search.Summary.GROUP }); freq_run_postcode = searchResult.getValue({ name: "custrecord_service_leg_addr_postcode", join: null, summary: search.Summary.GROUP }); if (!isNullorEmpty(freq_run_st_no)) { address = freq_run_st_no + ', ' + freq_run_suburb + ', ' + freq_run_state + ' - ' + freq_run_postcode; } else { address = freq_run_suburb + ', ' + freq_run_state + ' - ' + freq_run_postcode; } freq = []; if (freq_mon == 'T') { freq[freq.length] = 1 } if (freq_tue == 'T') { freq[freq.length] = 2 } if (freq_wed == 'T') { freq[freq.length] = 3 } if (freq_thu == 'T') { freq[freq.length] = 4 } if (freq_fri == 'T') { freq[freq.length] = 5 } if (isNullorEmpty(ncl)) { stop_name = customer_name_text + ' \\n Address: ' + address; } if (stop_count != 0 && old_stop_name != stop_name) { if (!isNullorEmpty(old_freq_id.length)) { log.debug({ title: 'dd', details: stop_freq_json_array }); if (stop_freq_json_array[stop_freq_json_array.length - 1].length < 900000) { stop_freq_json_array[stop_freq_json_array.length - 1] += updateJSON(old_stop_name, old_freq_time_current, old_stop_duration, old_stop_id, old_closing_day, old_opening_day, old_stop_lat, old_stop_lon, old_stop_notes, old_ncl, old_freq_id, old_customer_id_array, old_customer_text_array, old_customer_zee_array, old_service_notes, old_run_plan_array, old_run_plan_text_array, service_id_array, service_name_array, old_freq_mon, old_freq_tue, old_freq_wed, old_freq_thu, old_freq_fri); } else { stop_freq_json_array[stop_freq_json_array.length - 1] = stop_freq_json_array[stop_freq_json_array.length - 1].substring(0, stop_freq_json_array[stop_freq_json_array.length - 1].length - 1); stop_freq_json_array[stop_freq_json_array.length] = updateJSON(old_stop_name, old_freq_time_current, old_stop_duration, old_stop_id, old_closing_day, old_opening_day, old_stop_lat, old_stop_lon, old_stop_notes, old_ncl, old_freq_id, old_customer_id_array, old_customer_text_array, old_customer_zee_array, old_service_notes, old_run_plan_array, old_run_plan_text_array, service_id_array, service_name_array, old_freq_mon, old_freq_tue, old_freq_wed, old_freq_thu, old_freq_fri); log.debug({ title: 'stop_freq_json_array', details: stop_freq_json_array[stop_freq_json_array.length - 1] }); } old_stop_name = null; old_stop_lat; old_stop_lon; old_stop_id = []; old_closing_day = []; old_opening_day = []; service_id_array = []; service_name_array = []; old_customer_id_array = []; old_customer_text_array = []; old_customer_zee_array = []; old_freq_id = []; old_run_plan_array = []; old_run_plan_text_array = []; old_stop_notes = ''; old_service_notes = []; old_stop_duration = []; old_freq = []; freq = []; if (freq_mon == 'T') { freq[freq.length] = 1 } if (freq_tue == 'T') { freq[freq.length] = 2 } if (freq_wed == 'T') { freq[freq.length] = 3 } if (freq_thu == 'T') { freq[freq.length] = 4 } if (freq_fri == 'T') { freq[freq.length] = 5 } service_id_array[service_id_array.length] = service_id; old_service_notes[old_service_notes.length] = stop_notes; service_name_array[service_name_array.length] = service_text; old_customer_id_array[old_customer_id_array.length] = customer_id; old_customer_text_array[old_customer_text_array.length] = customer_id_text + ' ' + customer_name_text; old_customer_zee_array[old_customer_zee_array.length] = customer_zee; old_run_plan_array[old_run_plan_array.length] = freq_run_plan; old_run_plan_text_array[old_run_plan_text_array.length] = freq_run_plan_text; old_closing_day[old_closing_day.length] = closing_day; old_opening_day[old_opening_day.length] = opening_day; old_stop_duration[old_stop_duration.length] = stop_duration; } } else { var result = arraysEqual(freq, old_freq); if (old_service_time != freq_time_current && stop_count != 0) { if (!isNullorEmpty(old_freq_id.length)) { log.debug({ title: 'cc', details: stop_freq_json_array }); if (stop_freq_json_array[stop_freq_json_array.length - 1].length < 900000) { stop_freq_json_array[stop_freq_json_array.length - 1] += updateJSON(old_stop_name, old_freq_time_current, old_stop_duration, old_stop_id, old_closing_day, old_opening_day, old_stop_lat, old_stop_lon, old_stop_notes, old_ncl, old_freq_id, old_customer_id_array, old_customer_text_array, old_customer_zee_array, old_service_notes, old_run_plan_array, old_run_plan_text_array, service_id_array, service_name_array, old_freq_mon, old_freq_tue, old_freq_wed, old_freq_thu, old_freq_fri); } else { stop_freq_json_array[stop_freq_json_array.length - 1] = stop_freq_json_array[stop_freq_json_array.length - 1].substring(0, stop_freq_json_array[stop_freq_json_array.length - 1].length - 1); stop_freq_json_array[stop_freq_json_array.length] = updateJSON(old_stop_name, old_freq_time_current, old_stop_duration, old_stop_id, old_closing_day, old_opening_day, old_stop_lat, old_stop_lon, old_stop_notes, old_ncl, old_freq_id, old_customer_id_array, old_customer_text_array, old_customer_zee_array, old_service_notes, old_run_plan_array, old_run_plan_text_array, service_id_array, service_name_array, old_freq_mon, old_freq_tue, old_freq_wed, old_freq_thu, old_freq_fri); log.debug({ title: 'stop_freq_json_array[stop_freq_json_array.length - 1]', details: stop_freq_json_array[stop_freq_json_array.length - 1] }); } old_stop_name = null; old_service_time = null; old_stop_id = []; old_closing_day = []; old_opening_day = []; service_id_array = []; service_name_array = []; old_customer_id_array = []; old_customer_text_array = []; old_customer_zee_array = []; old_run_plan_array = []; old_run_plan_text_array = []; old_freq_id = []; old_freq = []; freq = []; old_stop_notes = ''; old_closing_day = []; old_opening_day = []; old_service_notes = []; old_stop_duration = []; if (freq_mon == 'T') { freq[freq.length] = 1 } if (freq_tue == 'T') { freq[freq.length] = 2 } if (freq_wed == 'T') { freq[freq.length] = 3 } if (freq_thu == 'T') { freq[freq.length] = 4 } if (freq_fri == 'T') { freq[freq.length] = 5 } service_id_array[service_id_array.length] = service_id; old_service_notes[old_service_notes.length] = stop_notes; service_name_array[service_name_array.length] = service_text; old_customer_id_array[old_customer_id_array.length] = customer_id; old_customer_text_array[old_customer_text_array.length] = customer_id_text + ' ' + customer_name_text; old_customer_zee_array[old_customer_zee_array.length] = customer_zee; old_run_plan_array[old_run_plan_array.length] = freq_run_plan; old_run_plan_text_array[old_run_plan_text_array.length] = freq_run_plan_text; old_closing_day[old_closing_day.length] = closing_day; old_opening_day[old_opening_day.length] = opening_day; old_stop_duration[old_stop_duration.length] = stop_duration; } } else if (result == false && stop_count != 0) { if (!isNullorEmpty(old_freq_id.length)) { log.debug({ title: 'bb', details: stop_freq_json_array }); if (stop_freq_json_array[stop_freq_json_array.length - 1].length < 900000) { stop_freq_json_array[stop_freq_json_array.length - 1] += updateJSON(old_stop_name, old_freq_time_current, old_stop_duration, old_stop_id, old_closing_day, old_opening_day, old_stop_lat, old_stop_lon, old_stop_notes, old_ncl, old_freq_id, old_customer_id_array, old_customer_text_array, old_customer_zee_array, old_service_notes, old_run_plan_array, old_run_plan_text_array, service_id_array, service_name_array, old_freq_mon, old_freq_tue, old_freq_wed, old_freq_thu, old_freq_fri); } else { stop_freq_json_array[stop_freq_json_array.length - 1] = stop_freq_json_array[stop_freq_json_array.length - 1].substring(0, stop_freq_json_array[stop_freq_json_array.length - 1].length - 1); stop_freq_json_array[stop_freq_json_array.length] = updateJSON(old_stop_name, old_freq_time_current, old_stop_duration, old_stop_id, old_closing_day, old_opening_day, old_stop_lat, old_stop_lon, old_stop_notes, old_ncl, old_freq_id, old_customer_id_array, old_customer_text_array, old_customer_zee_array, old_service_notes, old_run_plan_array, old_run_plan_text_array, service_id_array, service_name_array, old_freq_mon, old_freq_tue, old_freq_wed, old_freq_thu, old_freq_fri); log.debug({ title: 'stop_freq_json_array[stop_freq_json_array.length - 1]', details: stop_freq_json_array[stop_freq_json_array.length - 1] }); } old_stop_name = null; old_service_time = null; old_stop_id = []; old_stop_lat; old_stop_lon; old_closing_day = []; old_opening_day = []; service_id_array = []; service_name_array = []; old_customer_id_array = []; old_customer_text_array = []; old_customer_zee_array = []; old_run_plan_array = []; old_run_plan_text_array = []; old_freq_id = []; old_freq = []; freq = []; old_stop_notes = ''; old_closing_day = []; old_opening_day = []; old_service_notes = []; old_stop_duration = []; if (freq_mon == 'T') { freq[freq.length] = 1 } if (freq_tue == 'T') { freq[freq.length] = 2 } if (freq_wed == 'T') { freq[freq.length] = 3 } if (freq_thu == 'T') { freq[freq.length] = 4 } if (freq_fri == 'T') { freq[freq.length] = 5 } service_id_array[service_id_array.length] = service_id; old_service_notes[old_service_notes.length] = stop_notes; service_name_array[service_name_array.length] = service_text; old_customer_id_array[old_customer_id_array.length] = customer_id; old_customer_text_array[old_customer_text_array.length] = customer_id_text + ' ' + customer_name_text; old_customer_zee_array[old_customer_zee_array.length] = customer_zee; old_run_plan_array[old_run_plan_array.length] = freq_run_plan; old_run_plan_text_array[old_run_plan_text_array.length] = freq_run_plan_text; old_closing_day[old_closing_day.length] = closing_day; old_opening_day[old_opening_day.length] = opening_day; old_stop_duration[old_stop_duration.length] = stop_duration; } } else { service_id_array[service_id_array.length] = service_id; old_service_notes[old_service_notes.length] = stop_notes; service_name_array[service_name_array.length] = service_text; old_customer_id_array[old_customer_id_array.length] = customer_id; old_customer_text_array[old_customer_text_array.length] = customer_id_text + ' ' + customer_name_text; old_customer_zee_array[old_customer_zee_array.length] = customer_zee; old_run_plan_array[old_run_plan_array.length] = freq_run_plan; old_run_plan_text_array[old_run_plan_text_array.length] = freq_run_plan_text; old_closing_day[old_closing_day.length] = closing_day; old_opening_day[old_opening_day.length] = opening_day; old_stop_duration[old_stop_duration.length] = stop_duration; } } old_stop_name = stop_name; old_service_time = freq_time_current; old_address = address; old_stop_id[old_stop_id.length] = stop_id; old_stop_lat = stop_lat; old_stop_lon = stop_lon; old_stop_notes += stop_notes; old_ncl = ncl; old_freq_id[old_freq_id.length] = freq_id; old_freq_mon = freq_mon; old_freq_tue = freq_tue; old_freq_wed = freq_wed; old_freq_thu = freq_thu; old_freq_fri = freq_fri; old_freq_adhoc = freq_adhoc; old_freq_time_current = freq_time_current; old_freq_time_start = freq_time_start; old_freq_time_end = freq_time_end; old_freq_run_plan = freq_run_plan; old_freq = freq; stop_count++; return true; }); if (stop_count > 0) { if (stop_freq_json_array[stop_freq_json_array.length - 1].length < 900000) { log.debug({ title: 'aa', details: stop_freq_json_array }); stop_freq_json_array[stop_freq_json_array.length - 1] += updateJSON(old_stop_name, old_freq_time_current, old_stop_duration, old_stop_id, old_closing_day, old_opening_day, old_stop_lat, old_stop_lon, old_stop_notes, old_ncl, old_freq_id, old_customer_id_array, old_customer_text_array, old_customer_zee_array, old_service_notes, old_run_plan_array, old_run_plan_text_array, service_id_array, service_name_array, old_freq_mon, old_freq_tue, old_freq_wed, old_freq_thu, old_freq_fri); } else { stop_freq_json_array[stop_freq_json_array.length - 1] = stop_freq_json_array[stop_freq_json_array.length - 1].substring(0, stop_freq_json_array[stop_freq_json_array.length - 1].length - 1); stop_freq_json_array[stop_freq_json_array.length] = updateJSON(old_stop_name, old_freq_time_current, old_stop_duration, old_stop_id, old_closing_day, old_opening_day, old_stop_lat, old_stop_lon, old_stop_notes, old_ncl, old_freq_id, old_customer_id_array, old_customer_text_array, old_customer_zee_array, old_service_notes, old_run_plan_array, old_run_plan_text_array, service_id_array, service_name_array, old_freq_mon, old_freq_tue, old_freq_wed, old_freq_thu, old_freq_fri); log.debug({ title: 'stop_freq_json_array[stop_freq_json_array.length - 1]', details: stop_freq_json_array[stop_freq_json_array.length - 1] }); } } log.debug({ title: 'Stop Freq JSON', details: stop_freq_json_array[0] }); log.debug({ title: 'Stop Freq JSON 2', details: stop_freq_json_array[1] }); log.debug({ title: 'Stop Freq JSON length', details: stop_freq_json_array.length }); if (stop_count == 0){ stop_freq_json_array = ['{ "data": [,'] } var zeeRecord = record.load({ type: record.Type.PARTNER, id: zee, isDynamic: true, }); log.debug({ title: 'ttt', details: zeeRecord.getValue({ fieldId: 'custentity_zee_run_0'}) }); for (i = 0; i < stop_freq_json_array.length; i++) { log.debug({ title: i, details: stop_freq_json_array[i] }); zeeRecord.setValue({ fieldId: 'custentity_zee_run_' + i, value: stop_freq_json_array[i].substring(0, stop_freq_json_array[i].length - 1) }); } zeeRecord.save({ enableSourcing: true, ignoreMandatoryFields: true }); } log.debug({ title: 'stop_count', details: stop_count }); //inlineQty += '<div class="se-pre-con"></div> inlineQty += '<div id="calendar" style="font-size:small;"></div>'; form.addField({ id: 'preview_table', type: ui.FieldType.INLINEHTML, label: 'preview_table' }).updateLayoutType({ layoutType: ui.FieldLayoutType.OUTSIDEBELOW }).updateBreakType({ breakType: ui.FieldBreakType.STARTROW }).defaultValue = inlineQty; form.addSubmitButton({ label : 'Customer List View' }); form.addButton({ id : 'create_run', label : 'Create Run', functionName : 'onclick_createRun()' }); form.addButton({ id : 'customer_closure', label : 'Scheduled Customer Holiday Closure', functionName : 'onclick_customerClosure()' }); form.addButton({ id : 'save', label : 'Save Changes', functionName : 'onclick_save()' }); form.addButton({ id : 'back', label : 'Cancel', functionName : 'onclick_reset()' }); form.addButton({ id : 'network_map', label : 'Network Map', functionName : 'onclick_networkMap(' + zee + ')' }); /** * CONVERT CL AND PUT CL ID */ //form.clientScriptModulePath = 'SuiteScripts/jQuery Plugins/Moment JS/moment-with-locales.min.js'; form.clientScriptFileId = 4602614; //PROD = 4609635 SB = 4602614 context.response.writePage(form); } else { var save_button = context.request.parameters.save_button; var stops_string = context.request.parameters.stops; var duration_string = context.request.parameters.duration; var freqs_string = context.request.parameters.freqs; var start_times_string = context.request.parameters.start_times; var zee_response = context.request.parameters.zee; if (!isNullorEmpty(stops_string) && !isNullorEmpty(duration_string)) { var stops = stops_string.split(','); var duration = duration_string.split(','); for (var x = 0; x < stops.length; x++) { var serviceLegRecord = record.load({ type: 'customrecord_service_leg', id: stops[x], }); serviceLegRecord.setValue({ fieldId: 'custrecord_service_leg_duration', value: duration[x]}); serviceLegRecord.save({ enableSourcing: true, ignoreMandatoryFields: true }); } } if (!isNullorEmpty(freqs_string) && !isNullorEmpty(start_times_string)) { var freqs = freqs_string.split(','); var start_times = start_times_string.split(','); for (var x = 0; x < freqs.length; x++) { var freqRecord = record.load({ type: 'customrecord_service_freq', id: freqs[x], isDynamic: true, }); freqRecord.setValue({ fieldId: 'custrecord_service_freq_time_current', value: start_times[x]}); freqRecord.save({ enableSourcing: true, ignoreMandatoryFields: true }); } } if (save_button == 'T') { redirect.toSuitelet({ scriptId: 'customscript_sl_full_calendar_2', deploymentId: 'customdeploy_sl_full_calender_2', }); } else { var params = { scriptid: 'customscript_sl_full_calendar_2', deployid: 'customdeploy_sl_full_calender_2', zee: zee_response } redirect.toSuitelet({ scriptId: 'customscript_sl_rp_customer_list_2', deploymentId: 'customdeploy_sl_rp_customer_list_2', parameters: params }); } } } function convertSecondsToMinutes(seconds) { var min = Math.floor(seconds / 60); var sec = seconds % 60; var minutes_array = []; minutes_array[0] = min; minutes_array[1] = sec; return minutes_array; } function convertTo24Hour(time) { var hours = parseInt(time.substr(0, 2)); if (time.indexOf('AM') != -1 && hours == 12) { time = time.replace('12', '0'); } if (time.indexOf('AM') != -1 && hours < 10) { time = time.replace(hours, ('0' + hours)); } if (time.indexOf('PM') != -1 && hours < 12) { time = time.replace(hours, (hours + 12)); } return time.replace(/( AM| PM)/, ''); } function onTimeChange(value) { if (!isNullorEmpty(value)) { var timeSplit = value.split(':'), hours, minutes, meridian; hours = timeSplit[0]; minutes = timeSplit[1]; if (hours > 12) { meridian = 'PM'; hours -= 12; } else if (hours < 12) { meridian = 'AM'; if (hours == 0) { hours = 12; } } else { meridian = 'PM'; } return (hours + ':' + minutes + ' ' + meridian); } } function arraysEqual(_arr1, _arr2) { if (!Array.isArray(_arr1) || !Array.isArray(_arr2) || _arr1.length !== _arr2.length) return false; var arr1 = _arr1.concat().sort(); var arr2 = _arr2.concat().sort(); for (var i = 0; i < arr1.length; i++) { if (arr1[i] !== arr2[i]) return false; } return true; } function getDate() { var date = new Date(); if (date.getHours() > 6) { date = date.setDate(date.getDate() + 1); } date = format.format({ value: date, type: format.Type.DATE, timezone: format.Timezone.AUSTRALIA_SYDNEY }); return date; } function updateJSON(old_stop_name, old_freq_time_current, old_stop_duration, old_stop_id, old_closing_day, old_opening_day, old_stop_lat, old_stop_lon, old_stop_notes, old_ncl, old_freq_id, old_customer_id_array, old_customer_text_array, old_customer_zee_array, old_service_notes, old_run_plan_array, old_run_plan_text_array, service_id_array, service_name_array, old_freq_mon, old_freq_tue, old_freq_wed, old_freq_thu, old_freq_fri) { log.debug({ title: 'old_stop_name', details: old_stop_name }); log.debug({ title: 'stop_freq_jsonINSIDE2', details: old_stop_notes }); var stop_freq_json = ''; var freq_time_current_array = old_freq_time_current.split(':'); var min_array = convertSecondsToMinutes(Math.max.apply(Math, old_stop_duration)); min_array[0] = parseInt(min_array[0]) + +freq_time_current_array[1]; if (isNullorEmpty(old_ncl)) { var bg_color = '#3a87ad'; } else { var bg_color = '#009688'; } if (old_freq_mon == true) { var day_number = 1; stop_freq_json += addDayJSON(day_number, old_stop_name, old_freq_time_current, old_stop_duration, old_stop_id, old_closing_day, old_opening_day, old_stop_lat, old_stop_lon, old_stop_notes, old_ncl, old_freq_id, old_customer_id_array, old_customer_text_array, old_customer_zee_array, old_service_notes, old_run_plan_array, old_run_plan_text_array, service_id_array, service_name_array, old_freq_mon, old_freq_tue, old_freq_wed, old_freq_thu, old_freq_fri, bg_color, freq_time_current_array, min_array); } if (old_freq_tue == true) { var day_number = 2; stop_freq_json += addDayJSON(day_number, old_stop_name, old_freq_time_current, old_stop_duration, old_stop_id, old_closing_day, old_opening_day, old_stop_lat, old_stop_lon, old_stop_notes, old_ncl, old_freq_id, old_customer_id_array, old_customer_text_array, old_customer_zee_array, old_service_notes, old_run_plan_array, old_run_plan_text_array, service_id_array, service_name_array, old_freq_mon, old_freq_tue, old_freq_wed, old_freq_thu, old_freq_fri, bg_color, freq_time_current_array, min_array); } if (old_freq_wed == true) { var day_number = 3; stop_freq_json += addDayJSON(day_number, old_stop_name, old_freq_time_current, old_stop_duration, old_stop_id, old_closing_day, old_opening_day, old_stop_lat, old_stop_lon, old_stop_notes, old_ncl, old_freq_id, old_customer_id_array, old_customer_text_array, old_customer_zee_array, old_service_notes, old_run_plan_array, old_run_plan_text_array, service_id_array, service_name_array, old_freq_mon, old_freq_tue, old_freq_wed, old_freq_thu, old_freq_fri, bg_color, freq_time_current_array, min_array); } if (old_freq_thu == true) { var day_number = 4; stop_freq_json += addDayJSON(day_number, old_stop_name, old_freq_time_current, old_stop_duration, old_stop_id, old_closing_day, old_opening_day, old_stop_lat, old_stop_lon, old_stop_notes, old_ncl, old_freq_id, old_customer_id_array, old_customer_text_array, old_customer_zee_array, old_service_notes, old_run_plan_array, old_run_plan_text_array, service_id_array, service_name_array, old_freq_mon, old_freq_tue, old_freq_wed, old_freq_thu, old_freq_fri, bg_color, freq_time_current_array, min_array); } if (old_freq_fri == true) { var day_number = 5; stop_freq_json += addDayJSON(day_number, old_stop_name, old_freq_time_current, old_stop_duration, old_stop_id, old_closing_day, old_opening_day, old_stop_lat, old_stop_lon, old_stop_notes, old_ncl, old_freq_id, old_customer_id_array, old_customer_text_array, old_customer_zee_array, old_service_notes, old_run_plan_array, old_run_plan_text_array, service_id_array, service_name_array, old_freq_mon, old_freq_tue, old_freq_wed, old_freq_thu, old_freq_fri, bg_color, freq_time_current_array, min_array); } if (old_freq_mon == false && old_freq_tue == false && old_freq_wed == false && old_freq_thu == false && old_freq_fri == false) { stop_freq_json += '{"id": "' + old_stop_id + '",'; stop_freq_json += '"closing_days": "' + old_closing_day + '",'; stop_freq_json += '"opening_days": "' + old_opening_day + '",'; stop_freq_json += '"lat": "' + old_stop_lat + '",'; stop_freq_json += '"lon": "' + old_stop_lon + '",'; stop_freq_json += '"title": "' + old_stop_name + '",'; var start_time = moment().day(6).hours(freq_time_current_array[0]).minutes(freq_time_current_array[1]).seconds(0).format(); var end_time = moment().add({ seconds: min_array[1] }).day(6).hours(freq_time_current_array[0]).minutes(min_array[0]).format(); stop_freq_json += '"start": "' + start_time + '",'; stop_freq_json += '"end": "' + end_time + '",'; stop_freq_json += '"description": "' + old_stop_notes + '",'; stop_freq_json += '"ncl": "' + old_ncl + '",'; stop_freq_json += '"color": "' + bg_color + '",'; stop_freq_json += '"freq_id": "' + old_freq_id + '",'; stop_freq_json += '"services": [' for (var i = 0; i < service_id_array.length; i++) { stop_freq_json += '{'; stop_freq_json += '"customer_id": "' + old_customer_id_array[i] + '",'; stop_freq_json += '"customer_zee": "' + old_customer_zee_array[i] + '",'; stop_freq_json += '"customer_notes": "' + old_service_notes[i] + '",'; stop_freq_json += '"customer_text": "' + old_customer_text_array[i] + '",'; stop_freq_json += '"run_plan": "' + old_run_plan_array[i] + '",'; stop_freq_json += '"run_plan_text": "' + old_run_plan_text_array[i] + '",'; stop_freq_json += '"service_id": "' + service_id_array[i] + '",'; stop_freq_json += '"service_text": "' + service_name_array[i] + '"'; stop_freq_json += '},' } stop_freq_json = stop_freq_json.substring(0, stop_freq_json.length - 1); //to remove the last coma stop_freq_json += ']},' } log.debug({ title: 'stop_freq_json', details: stop_freq_json }); return stop_freq_json; } function addDayJSON(day_number, old_stop_name, old_freq_time_current, old_stop_duration, old_stop_id, old_closing_day, old_opening_day, old_stop_lat, old_stop_lon, old_stop_notes, old_ncl, old_freq_id, old_customer_id_array, old_customer_text_array, old_customer_zee_array, old_service_notes, old_run_plan_array, old_run_plan_text_array, service_id_array, service_name_array, old_freq_mon, old_freq_tue, old_freq_wed, old_freq_thu, old_freq_fri, bg_color, freq_time_current_array, min_array) { log.debug({ title: 'in add json', details: 'in add json' }) var date = moment().day(day_number).date(); var month = moment().day(day_number).month(); var year = moment().day(day_number).year(); var date_of_week = date + '/' + (month + 1) + '/' + year; var stop_freq_json = ''; stop_freq_json += '{"id": "' + old_stop_id + '",'; stop_freq_json += '"closing_days": "' + old_closing_day + '",'; stop_freq_json += '"opening_days": "' + old_opening_day + '",'; stop_freq_json += '"lat": "' + old_stop_lat + '",'; stop_freq_json += '"lon": "' + old_stop_lon + '",'; if (isNullorEmpty(old_ncl)) { for (var i = 0; i < service_id_array.length; i++) { if (date_of_week >= old_closing_day[i] && date_of_week < old_opening_day[i]) { stop_freq_json += '"title": "CLOSED - ' + old_stop_name + '",'; stop_freq_json += '"color": "#ad3a3a",'; } else { stop_freq_json += '"title": "' + old_stop_name + '",'; stop_freq_json += '"color": "' + bg_color + '",'; } } } else { stop_freq_json += '"title": "' + old_stop_name + '",'; stop_freq_json += '"color": "' + bg_color + '",'; } var start_time = moment().day(day_number).hours(freq_time_current_array[0]).minutes(freq_time_current_array[1]).seconds(0).format(); var end_time = moment().day(day_number).hours(freq_time_current_array[0]).minutes(min_array[0]).seconds(0).format(); stop_freq_json += '"start": "' + start_time + '",'; stop_freq_json += '"end": "' + end_time + '",'; stop_freq_json += '"description": "' + old_stop_notes + '",'; stop_freq_json += '"ncl": "' + old_ncl + '",'; stop_freq_json += '"freq_id": "' + old_freq_id + '",'; stop_freq_json += '"services": [' for (var i = 0; i < service_id_array.length; i++) { stop_freq_json += '{'; stop_freq_json += '"customer_id": "' + old_customer_id_array[i] + '",'; stop_freq_json += '"customer_zee": "' + old_customer_zee_array[i] + '",'; stop_freq_json += '"customer_notes": "' + old_service_notes[i] + '",'; if (date_of_week >= old_closing_day[i] && date_of_week < old_opening_day[i]) { stop_freq_json += '"customer_text": "CLOSED - ' + old_customer_text_array[i] + '",'; } else { stop_freq_json += '"customer_text": "' + old_customer_text_array[i] + '",'; } stop_freq_json += '"run_plan": "' + old_run_plan_array[i] + '",'; stop_freq_json += '"run_plan_text": "' + old_run_plan_text_array[i] + '",'; stop_freq_json += '"service_id": "' + service_id_array[i] + '",'; stop_freq_json += '"service_text": "' + service_name_array[i] + '"'; stop_freq_json += '},' } stop_freq_json = stop_freq_json.substring(0, stop_freq_json.length - 1); //to remove the last coma stop_freq_json += ']},' log.debug({ title: 'stop_freq_json', details: stop_freq_json }); return stop_freq_json } function isNullorEmpty(strVal) { return (strVal == null || strVal == '' || strVal == 'null' || strVal == undefined || strVal == 'undefined' || strVal == '- None -'); } return { onRequest: onRequest }; });
1,104
[{"tag": "KEY", "value": "sha384-THVO/sM0mFD9h7dfSndI6TS0PgAGavwKvB5hAxRRvc0o9cPLohB0wb/PTA7LdUHs", "start": 3036, "end": 3107}]
true
1
/** * * @NApiVersion 2.0 * @NScriptType Suitelet * @NAmdConfig ./custom_modules_config.json * Description: Calendar view page of the run * * @Last Modified by: Sruti Desai * */ define(['N/ui/serverWidget', 'N/email', 'N/runtime', 'N/search', 'N/record', 'N/http', 'N/log', 'N/redirect', 'N/format', 'moment'], function(ui, email, runtime, search, record, http, log, redirect, format, moment) { var baseURL = 'https://1048144.app.netsuite.com'; if (runtime.EnvType == "SANDBOX") { baseURL = 'https://1048144-sb3.app.netsuite.com'; } var zee = 0; var role = runtime.getCurrentUser().role; if (role == 1000) { //Franchisee zee = runtime.getCurrentUser(); } function onRequest(context) { if (context.request.method === 'GET') { var run = 0; var form = ui.createForm({ title: 'Run Scheduler' }); form.addField({ id: 'save_button', type: ui.FieldType.TEXT, label: 'save_button' }).updateDisplayType({ displayType: ui.FieldDisplayType.HIDDEN }).defaultValue = 'F'; form.addField({ id: 'stops', type: ui.FieldType.TEXT, label: 'stops' }).updateDisplayType({ displayType: ui.FieldDisplayType.HIDDEN }); form.addField({ id: 'duration', type: ui.FieldType.TEXT, label: 'duration' }).updateDisplayType({ displayType: ui.FieldDisplayType.HIDDEN }); form.addField({ id: 'freqs', type: ui.FieldType.TEXT, label: 'freqs' }).updateDisplayType({ displayType: ui.FieldDisplayType.HIDDEN }); form.addField({ id: 'start_times', type: ui.FieldType.TEXT, label: 'start_times' }).updateDisplayType({ displayType: ui.FieldDisplayType.HIDDEN }); log.debug({ title: 'zee', details: zee }); log.debug({ title: 'role', details: role }); run = context.request.parameters.run; var inlineQty = ''; inlineQty += '<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"><script type="text/javascript" src="//cdnjs.cloudflare.com/ajax/libs/jquery/2.2.1/jquery.min.js"></script><link href="//netdna.bootstrapcdn.com/bootstrap/3.3.2/css/bootstrap.min.css" rel="stylesheet"><script src="//netdna.bootstrapcdn.com/bootstrap/3.3.2/js/bootstrap.min.js"></script><script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.6.4/angular.min.js"></script><script src="https://cdnjs.cloudflare.com/ajax/libs/jspdf/1.5.1/jspdf.debug.js" integrity="949d1u22cbffbrarjh182eig55721odj" crossorigin="anonymous"></script><link rel="stylesheet" href="https://1048144.app.netsuite.com/core/media/media.nl?id=2060796&c=1048144&h=9ee6accfd476c9cae718&_xt=.css"/><script sr'; inlineQty += 'c="https://1048144.app.netsuite.com/core/media/media.nl?id=2060797&c=1048144&h=ef2cda20731d146b5e98&_xt=.js"></script><link type="text/css" rel="stylesheet" href="https://1048144.app.netsuite.com/core/media/media.nl?id=2090583&c=1048144&h=a0ef6ac4e28f91203dfe&_xt=.css">'; inlineQty += '<script type="text/javascript" src="//cdnjs.cloudflare.com/ajax/libs/moment.js/2.12.0/moment.min.js"></script><script type="text/javascript" src="https://1048144.app.netsuite.com/core/media/media.nl?id=2392604&c=1048144&h=6a28cec4ec4cd48e6a16&_xt=.js"></script> <link rel="stylesheet" type="text/css" href=https://1048144.app.netsuite.com/core/media/media.nl?id=2392605&c=1048144&h=3060708076f338e371ff&_xt=.css"><link rel="stylesheet" type="text/css" media="print" href="https://1048144.app.netsuite.com/core/media/media.nl?id=2392601&c=1048144&h=4e40a20752aed954e459&_xt=.css">'; inlineQty += '<script type="text/javascript" src="//cdnjs.cloudflare.com/ajax/libs/moment.js/2.12.0/moment.min.js"></script><link rel="stylesheet" type="text/css" href="https://cdnjs.cloudflare.com/ajax/libs/qtip2/3.0.3/jquery.qtip.min.css"><script type="text/javascript" src="https://cdnjs.cloudflare.com/ajax/libs/qtip2/3.0.3/jquery.qtip.min.js"></script>' inlineQty += '<div id="alert" class="alert alert-danger fade in"></div><div id="myModal" class="modal fade bs-example-modal-sm" tabindex="-1" role="dialog" aria-labelledby="mySmallModalLabel" aria-hidden="true"><div class="modal-dialog modal-sm" role="document" style="width :max-content"><div class="modal-content" style="width :max-content"><div class="modal-header"><button type="button" class="close" data-dismiss="modal" aria-label="Close"><span aria-hidden="true">&times;</span></button><h4 class="modal-title panel panel-info" id="exampleModalLabel">Information</h4><br> </div><div class="modal-body"></div><div class="modal-footer"><button type="button" class="btn btn-primary save_run" data-dismiss="modal">SAVE</button><button type="button" class="btn btn-default" data-dismiss="modal">Close</button></div></div></div></div>'; if (role != 1000) { inlineQty += '<div class="container" style="padding-top: 3%;"><div class="form-group container"><div class="row"><div class="input-group"><span class="input-group-addon">SELECT ZEE</span><select class="form-control zee_dropdown" >'; var searched_zee = search.load({ id: 'customsearch_job_inv_process_zee', type: search.Type.PARTNER }); var resultSet_zee = searched_zee.run(); var count_zee = 0; inlineQty += '<option value=""></option>' resultSet_zee.each(function(searchResult_zee) { zeeid = searchResult_zee.getValue('internalid'); zee_name = searchResult_zee.getValue('entityid'); if (context.request.parameters.zee == zeeid) { inlineQty += '<option value="' + zeeid + '" selected="selected">' + zee_name + '</option>'; } else { inlineQty += '<option value="' + zeeid + '">' + zee_name + '</option>'; } return true; }); inlineQty += '</select></div></div></div></div>'; zee = context.request.parameters.zee; } form.addField({ id: 'zee', type: ui.FieldType.TEXT, label: 'zee' }).updateDisplayType({ displayType: ui.FieldDisplayType.HIDDEN }).defaultValue = zee; if (zee != 0 && !isNullorEmpty(zee)) { var zee_record = record.load({ type: record.Type.PARTNER, id: parseInt(zee), isDynamic: true, }); var multi = zee_record.getValue({ fieldId: 'custentity_zee_multiple_territory' }); var multi_text = zee_record.getText({ fieldId: 'custentity_zee_multiple_territory' }); if (!isNullorEmpty(multi)) { var multi_zee_text = ''; form.addField({ id: 'multi_zee', type: ui.FieldType.TEXT, label: 'multi_zee' }).updateDisplayType({ displayType: ui.FieldDisplayType.HIDDEN }); if (multi.length > 1) { inlineQty += '<div class="container" style="padding-top: 3%;"><div class="form-group container"><div class="row"><div class="input-group"><span class="input-group-addon">MULTIPLE TERRITORIES OWNED</span><select readonly class = "form-control zee_dropdown" > '; for (var x = 0; x < multi.length; x++) { if (zee == multi[x]) { inlineQty += '<option selected="selected" value="' + multi[x] + '" data-right="" >' + multi_text[x] + '</option>'; } else { inlineQty += '<option value="' + multi[x] + '" data-right="" >' + multi_text[x] + '</option>'; } if (x != (multi.length - 1)) { multi_zee_text += multi_text[x] + ','; } else { multi_zee_text += multi_text[x]; } } } form.addField({ id: 'multi_zee_text', type: ui.FieldType.TEXT, label: 'multi_zee_text' }).updateDisplayType({ displayType: ui.FieldDisplayType.HIDDEN }).defaultValue = multi_zee_text; inlineQty += '</select></div></div></div></div>'; } else { form.addField({ id: 'multi_zee', type: ui.FieldType.TEXT, label: 'multi_zee' }).updateDisplayType({ displayType: ui.FieldDisplayType.HIDDEN }); form.addField({ id: 'multi_zee_text', type: ui.FieldType.TEXT, label: 'multi_zee_text' }).updateDisplayType({ displayType: ui.FieldDisplayType.HIDDEN }); } inlineQty += '<div class="container select_run" style="padding-top: 3%;"><div class="form-group container"><div class="row"><div class="input-group"><span class="input-group-addon">SELECT RUN</span><select class="form-control run_dropdown" >'; var runPlanSearch = search.load({ id: 'customsearch_app_run_plan_active', type: 'customrecord_run_plan' }) if (!isNullorEmpty(multi)) { runPlanSearch.filters.push(search.createFilter({ name: 'custrecord_run_franchisee', operator: search.Operator.ANYOF, values: zee })); } else { runPlanSearch.filters.push(search.createFilter({ name: 'custrecord_run_franchisee', operator: search.Operator.IS, values: zee })); } var resultSet_runPlan = runPlanSearch.run(); var count_zee = 0; inlineQty += '<option value="' + 0 + '">ALL</option>' resultSet_runPlan.each(function(searchResult_runPlan) { runinternalid = searchResult_runPlan.getValue('internalid'); runname = searchResult_runPlan.getValue('name'); if (context.request.parameters.run == runinternalid) { inlineQty += '<option value="' + runinternalid + '" selected="selected">' + runname + '</option>'; } else { inlineQty += '<option value="' + runinternalid + '">' + runname + '</option>'; } return true; }); inlineQty += '</select></div></div></div></div>'; log.debug({ title: 'zee', details: zee }); log.debug({ title: 'run', details: run }); var serviceLegSearch = search.load({ id: 'customsearch_rp_leg_freq_all_2', type: 'customrecord_service_leg' }); serviceLegSearch.filters.push(search.createFilter({ name: 'custrecord_service_leg_franchisee', operator: search.Operator.ANYOF, values: zee })); if (!isNullorEmpty(run) && run != 0) { serviceLegSearch.filters.push(search.createFilter({ name: 'custrecord_service_freq_run_plan', join: 'custrecord_service_freq_stop', operator: search.Operator.IS, values: run })); } var resultSet = serviceLegSearch.run(); var stop_count = 0; var freq_count = 0; var old_stop_name = null; var service_id_array = []; var service_name_array = []; var service_descp_array = []; var old_customer_id_array = []; var old_customer_text_array = []; var old_customer_zee_array = []; var old_run_plan_array = []; var old_run_plan_text_array = []; var old_closing_day = []; var old_opening_day = []; var old_service_notes = []; var old_stop_duration = []; var stop_id; var stop_name; var address; var stop_duration; var stop_notes; var stop_lat; var stop_lon; var service_id; var service_text; var customer_id; var customer_text; var customer_zee; var ncl; var freq_id; var freq_mon; var freq_tue; var freq_wed; var freq_thu; var freq_fri; var freq_adhoc; var freq_time_current; var freq_time_start; var freq_time_end; var freq_run_plan; var old_stop_id = []; var old_stop_name; var old_service_time; var old_address; var old_stop_notes = ''; var old_stop_lat; var old_stop_lon; var old_service_id; var old_service_text; var old_customer_id; var old_customer_text; var old_customer_zee; var old_ncl; var old_freq_id = []; var old_freq_mon; var old_freq_tue; var old_freq_wed; var old_freq_thu; var old_freq_fri; var old_freq_adhoc; var old_freq_time_current; var old_freq_time_start; var old_freq_time_end; var old_freq_run_plan; var freq = []; var old_freq = []; var stop_freq_json_array = ['{ "data": [']; resultSet.each(function(searchResult) { stop_id = searchResult.getValue({ name: 'internalid', join: null, summary: search.Summary.GROUP }); stop_name = searchResult.getValue({ name: 'name', join: null, summary: search.Summary.GROUP }); stop_duration = parseInt(searchResult.getValue({ name: 'custrecord_service_leg_duration', join: null, summary: search.Summary.GROUP })); stop_notes = searchResult.getValue({ name: 'custrecord_service_leg_notes', join: null, summary: search.Summary.GROUP }); stop_lat = searchResult.getValue({ name: "custrecord_service_leg_addr_lat", join: null, summary: search.Summary.GROUP }); stop_lon = searchResult.getValue({ name: "custrecord_service_leg_addr_lon", join: null, summary: search.Summary.GROUP }); service_id = searchResult.getValue({ name: 'custrecord_service_leg_service', join: null, summary: search.Summary.GROUP }); service_text = searchResult.getText({ name: 'custrecord_service_leg_service', join: null, summary: search.Summary.GROUP }); customer_id = searchResult.getValue({ name: 'custrecord_service_leg_customer', join: null, summary: search.Summary.GROUP }); customer_text = searchResult.getText({ name: 'custrecord_service_leg_customer', join: null, summary: search.Summary.GROUP }); customer_zee = searchResult.getValue({ name: "partner", join: "CUSTRECORD_SERVICE_LEG_CUSTOMER", summary: search.Summary.GROUP }); customer_id_text = searchResult.getValue({ name: "entityid", join: "CUSTRECORD_SERVICE_LEG_CUSTOMER", summary: search.Summary.GROUP }); customer_name_text = searchResult.getValue({ name: "companyname", join: "CUSTRECORD_SERVICE_LEG_CUSTOMER", summary: search.Summary.GROUP }); ncl = searchResult.getValue({ name: 'custrecord_service_leg_non_cust_location', join: null, summary: search.Summary.GROUP }); freq_id = searchResult.getValue({ name: "internalid", join: "CUSTRECORD_SERVICE_FREQ_STOP", summary: search.Summary.GROUP }); freq_mon = searchResult.getValue({ name: "custrecord_service_freq_day_mon", join: "CUSTRECORD_SERVICE_FREQ_STOP", summary: search.Summary.GROUP }); freq_tue = searchResult.getValue({ name: "custrecord_service_freq_day_tue", join: "CUSTRECORD_SERVICE_FREQ_STOP", summary: search.Summary.GROUP }); freq_wed = searchResult.getValue({ name: "custrecord_service_freq_day_wed", join: "CUSTRECORD_SERVICE_FREQ_STOP", summary: search.Summary.GROUP }); freq_thu = searchResult.getValue({ name: "custrecord_service_freq_day_thu", join: "CUSTRECORD_SERVICE_FREQ_STOP", summary: search.Summary.GROUP }); freq_fri = searchResult.getValue({ name: "custrecord_service_freq_day_fri", join: "CUSTRECORD_SERVICE_FREQ_STOP", summary: search.Summary.GROUP }); freq_adhoc = searchResult.getValue({ name: "custrecord_service_freq_day_adhoc", join: "CUSTRECORD_SERVICE_FREQ_STOP", summary: search.Summary.GROUP }); freq_time_current = convertTo24Hour(searchResult.getValue({ name: "custrecord_service_freq_time_current", join: "CUSTRECORD_SERVICE_FREQ_STOP", summary: search.Summary.GROUP })); freq_time_start = convertTo24Hour(searchResult.getValue({ name: "custrecord_service_freq_time_start", join: "CUSTRECORD_SERVICE_FREQ_STOP", summary: search.Summary.GROUP })); freq_time_end = convertTo24Hour(searchResult.getValue({ name: "custrecord_service_freq_time_end", join: "CUSTRECORD_SERVICE_FREQ_STOP", summary: search.Summary.GROUP })); freq_run_plan = searchResult.getValue({ name: "custrecord_service_freq_run_plan", join: "CUSTRECORD_SERVICE_FREQ_STOP", summary: search.Summary.GROUP }); closing_day = searchResult.getValue({ name: "custrecord_service_leg_closing_date", join: null, summary: search.Summary.GROUP }); opening_day = searchResult.getValue({ name: "custrecord_service_leg_opening_date", join: null, summary: search.Summary.GROUP }); freq_run_plan_text = searchResult.getText({ name: "custrecord_service_freq_run_plan", join: "CUSTRECORD_SERVICE_FREQ_STOP", summary: search.Summary.GROUP }); freq_run_st_no = searchResult.getValue({ name: "custrecord_service_leg_addr_st_num_name", join: null, summary: search.Summary.GROUP }); freq_run_suburb = searchResult.getValue({ name: "custrecord_service_leg_addr_suburb", join: null, summary: search.Summary.GROUP }); freq_run_state = searchResult.getValue({ name: "custrecord_service_leg_addr_state", join: null, summary: search.Summary.GROUP }); freq_run_postcode = searchResult.getValue({ name: "custrecord_service_leg_addr_postcode", join: null, summary: search.Summary.GROUP }); if (!isNullorEmpty(freq_run_st_no)) { address = freq_run_st_no + ', ' + freq_run_suburb + ', ' + freq_run_state + ' - ' + freq_run_postcode; } else { address = freq_run_suburb + ', ' + freq_run_state + ' - ' + freq_run_postcode; } freq = []; if (freq_mon == 'T') { freq[freq.length] = 1 } if (freq_tue == 'T') { freq[freq.length] = 2 } if (freq_wed == 'T') { freq[freq.length] = 3 } if (freq_thu == 'T') { freq[freq.length] = 4 } if (freq_fri == 'T') { freq[freq.length] = 5 } if (isNullorEmpty(ncl)) { stop_name = customer_name_text + ' \\n Address: ' + address; } if (stop_count != 0 && old_stop_name != stop_name) { if (!isNullorEmpty(old_freq_id.length)) { log.debug({ title: 'dd', details: stop_freq_json_array }); if (stop_freq_json_array[stop_freq_json_array.length - 1].length < 900000) { stop_freq_json_array[stop_freq_json_array.length - 1] += updateJSON(old_stop_name, old_freq_time_current, old_stop_duration, old_stop_id, old_closing_day, old_opening_day, old_stop_lat, old_stop_lon, old_stop_notes, old_ncl, old_freq_id, old_customer_id_array, old_customer_text_array, old_customer_zee_array, old_service_notes, old_run_plan_array, old_run_plan_text_array, service_id_array, service_name_array, old_freq_mon, old_freq_tue, old_freq_wed, old_freq_thu, old_freq_fri); } else { stop_freq_json_array[stop_freq_json_array.length - 1] = stop_freq_json_array[stop_freq_json_array.length - 1].substring(0, stop_freq_json_array[stop_freq_json_array.length - 1].length - 1); stop_freq_json_array[stop_freq_json_array.length] = updateJSON(old_stop_name, old_freq_time_current, old_stop_duration, old_stop_id, old_closing_day, old_opening_day, old_stop_lat, old_stop_lon, old_stop_notes, old_ncl, old_freq_id, old_customer_id_array, old_customer_text_array, old_customer_zee_array, old_service_notes, old_run_plan_array, old_run_plan_text_array, service_id_array, service_name_array, old_freq_mon, old_freq_tue, old_freq_wed, old_freq_thu, old_freq_fri); log.debug({ title: 'stop_freq_json_array', details: stop_freq_json_array[stop_freq_json_array.length - 1] }); } old_stop_name = null; old_stop_lat; old_stop_lon; old_stop_id = []; old_closing_day = []; old_opening_day = []; service_id_array = []; service_name_array = []; old_customer_id_array = []; old_customer_text_array = []; old_customer_zee_array = []; old_freq_id = []; old_run_plan_array = []; old_run_plan_text_array = []; old_stop_notes = ''; old_service_notes = []; old_stop_duration = []; old_freq = []; freq = []; if (freq_mon == 'T') { freq[freq.length] = 1 } if (freq_tue == 'T') { freq[freq.length] = 2 } if (freq_wed == 'T') { freq[freq.length] = 3 } if (freq_thu == 'T') { freq[freq.length] = 4 } if (freq_fri == 'T') { freq[freq.length] = 5 } service_id_array[service_id_array.length] = service_id; old_service_notes[old_service_notes.length] = stop_notes; service_name_array[service_name_array.length] = service_text; old_customer_id_array[old_customer_id_array.length] = customer_id; old_customer_text_array[old_customer_text_array.length] = customer_id_text + ' ' + customer_name_text; old_customer_zee_array[old_customer_zee_array.length] = customer_zee; old_run_plan_array[old_run_plan_array.length] = freq_run_plan; old_run_plan_text_array[old_run_plan_text_array.length] = freq_run_plan_text; old_closing_day[old_closing_day.length] = closing_day; old_opening_day[old_opening_day.length] = opening_day; old_stop_duration[old_stop_duration.length] = stop_duration; } } else { var result = arraysEqual(freq, old_freq); if (old_service_time != freq_time_current && stop_count != 0) { if (!isNullorEmpty(old_freq_id.length)) { log.debug({ title: 'cc', details: stop_freq_json_array }); if (stop_freq_json_array[stop_freq_json_array.length - 1].length < 900000) { stop_freq_json_array[stop_freq_json_array.length - 1] += updateJSON(old_stop_name, old_freq_time_current, old_stop_duration, old_stop_id, old_closing_day, old_opening_day, old_stop_lat, old_stop_lon, old_stop_notes, old_ncl, old_freq_id, old_customer_id_array, old_customer_text_array, old_customer_zee_array, old_service_notes, old_run_plan_array, old_run_plan_text_array, service_id_array, service_name_array, old_freq_mon, old_freq_tue, old_freq_wed, old_freq_thu, old_freq_fri); } else { stop_freq_json_array[stop_freq_json_array.length - 1] = stop_freq_json_array[stop_freq_json_array.length - 1].substring(0, stop_freq_json_array[stop_freq_json_array.length - 1].length - 1); stop_freq_json_array[stop_freq_json_array.length] = updateJSON(old_stop_name, old_freq_time_current, old_stop_duration, old_stop_id, old_closing_day, old_opening_day, old_stop_lat, old_stop_lon, old_stop_notes, old_ncl, old_freq_id, old_customer_id_array, old_customer_text_array, old_customer_zee_array, old_service_notes, old_run_plan_array, old_run_plan_text_array, service_id_array, service_name_array, old_freq_mon, old_freq_tue, old_freq_wed, old_freq_thu, old_freq_fri); log.debug({ title: 'stop_freq_json_array[stop_freq_json_array.length - 1]', details: stop_freq_json_array[stop_freq_json_array.length - 1] }); } old_stop_name = null; old_service_time = null; old_stop_id = []; old_closing_day = []; old_opening_day = []; service_id_array = []; service_name_array = []; old_customer_id_array = []; old_customer_text_array = []; old_customer_zee_array = []; old_run_plan_array = []; old_run_plan_text_array = []; old_freq_id = []; old_freq = []; freq = []; old_stop_notes = ''; old_closing_day = []; old_opening_day = []; old_service_notes = []; old_stop_duration = []; if (freq_mon == 'T') { freq[freq.length] = 1 } if (freq_tue == 'T') { freq[freq.length] = 2 } if (freq_wed == 'T') { freq[freq.length] = 3 } if (freq_thu == 'T') { freq[freq.length] = 4 } if (freq_fri == 'T') { freq[freq.length] = 5 } service_id_array[service_id_array.length] = service_id; old_service_notes[old_service_notes.length] = stop_notes; service_name_array[service_name_array.length] = service_text; old_customer_id_array[old_customer_id_array.length] = customer_id; old_customer_text_array[old_customer_text_array.length] = customer_id_text + ' ' + customer_name_text; old_customer_zee_array[old_customer_zee_array.length] = customer_zee; old_run_plan_array[old_run_plan_array.length] = freq_run_plan; old_run_plan_text_array[old_run_plan_text_array.length] = freq_run_plan_text; old_closing_day[old_closing_day.length] = closing_day; old_opening_day[old_opening_day.length] = opening_day; old_stop_duration[old_stop_duration.length] = stop_duration; } } else if (result == false && stop_count != 0) { if (!isNullorEmpty(old_freq_id.length)) { log.debug({ title: 'bb', details: stop_freq_json_array }); if (stop_freq_json_array[stop_freq_json_array.length - 1].length < 900000) { stop_freq_json_array[stop_freq_json_array.length - 1] += updateJSON(old_stop_name, old_freq_time_current, old_stop_duration, old_stop_id, old_closing_day, old_opening_day, old_stop_lat, old_stop_lon, old_stop_notes, old_ncl, old_freq_id, old_customer_id_array, old_customer_text_array, old_customer_zee_array, old_service_notes, old_run_plan_array, old_run_plan_text_array, service_id_array, service_name_array, old_freq_mon, old_freq_tue, old_freq_wed, old_freq_thu, old_freq_fri); } else { stop_freq_json_array[stop_freq_json_array.length - 1] = stop_freq_json_array[stop_freq_json_array.length - 1].substring(0, stop_freq_json_array[stop_freq_json_array.length - 1].length - 1); stop_freq_json_array[stop_freq_json_array.length] = updateJSON(old_stop_name, old_freq_time_current, old_stop_duration, old_stop_id, old_closing_day, old_opening_day, old_stop_lat, old_stop_lon, old_stop_notes, old_ncl, old_freq_id, old_customer_id_array, old_customer_text_array, old_customer_zee_array, old_service_notes, old_run_plan_array, old_run_plan_text_array, service_id_array, service_name_array, old_freq_mon, old_freq_tue, old_freq_wed, old_freq_thu, old_freq_fri); log.debug({ title: 'stop_freq_json_array[stop_freq_json_array.length - 1]', details: stop_freq_json_array[stop_freq_json_array.length - 1] }); } old_stop_name = null; old_service_time = null; old_stop_id = []; old_stop_lat; old_stop_lon; old_closing_day = []; old_opening_day = []; service_id_array = []; service_name_array = []; old_customer_id_array = []; old_customer_text_array = []; old_customer_zee_array = []; old_run_plan_array = []; old_run_plan_text_array = []; old_freq_id = []; old_freq = []; freq = []; old_stop_notes = ''; old_closing_day = []; old_opening_day = []; old_service_notes = []; old_stop_duration = []; if (freq_mon == 'T') { freq[freq.length] = 1 } if (freq_tue == 'T') { freq[freq.length] = 2 } if (freq_wed == 'T') { freq[freq.length] = 3 } if (freq_thu == 'T') { freq[freq.length] = 4 } if (freq_fri == 'T') { freq[freq.length] = 5 } service_id_array[service_id_array.length] = service_id; old_service_notes[old_service_notes.length] = stop_notes; service_name_array[service_name_array.length] = service_text; old_customer_id_array[old_customer_id_array.length] = customer_id; old_customer_text_array[old_customer_text_array.length] = customer_id_text + ' ' + customer_name_text; old_customer_zee_array[old_customer_zee_array.length] = customer_zee; old_run_plan_array[old_run_plan_array.length] = freq_run_plan; old_run_plan_text_array[old_run_plan_text_array.length] = freq_run_plan_text; old_closing_day[old_closing_day.length] = closing_day; old_opening_day[old_opening_day.length] = opening_day; old_stop_duration[old_stop_duration.length] = stop_duration; } } else { service_id_array[service_id_array.length] = service_id; old_service_notes[old_service_notes.length] = stop_notes; service_name_array[service_name_array.length] = service_text; old_customer_id_array[old_customer_id_array.length] = customer_id; old_customer_text_array[old_customer_text_array.length] = customer_id_text + ' ' + customer_name_text; old_customer_zee_array[old_customer_zee_array.length] = customer_zee; old_run_plan_array[old_run_plan_array.length] = freq_run_plan; old_run_plan_text_array[old_run_plan_text_array.length] = freq_run_plan_text; old_closing_day[old_closing_day.length] = closing_day; old_opening_day[old_opening_day.length] = opening_day; old_stop_duration[old_stop_duration.length] = stop_duration; } } old_stop_name = stop_name; old_service_time = freq_time_current; old_address = address; old_stop_id[old_stop_id.length] = stop_id; old_stop_lat = stop_lat; old_stop_lon = stop_lon; old_stop_notes += stop_notes; old_ncl = ncl; old_freq_id[old_freq_id.length] = freq_id; old_freq_mon = freq_mon; old_freq_tue = freq_tue; old_freq_wed = freq_wed; old_freq_thu = freq_thu; old_freq_fri = freq_fri; old_freq_adhoc = freq_adhoc; old_freq_time_current = freq_time_current; old_freq_time_start = freq_time_start; old_freq_time_end = freq_time_end; old_freq_run_plan = freq_run_plan; old_freq = freq; stop_count++; return true; }); if (stop_count > 0) { if (stop_freq_json_array[stop_freq_json_array.length - 1].length < 900000) { log.debug({ title: 'aa', details: stop_freq_json_array }); stop_freq_json_array[stop_freq_json_array.length - 1] += updateJSON(old_stop_name, old_freq_time_current, old_stop_duration, old_stop_id, old_closing_day, old_opening_day, old_stop_lat, old_stop_lon, old_stop_notes, old_ncl, old_freq_id, old_customer_id_array, old_customer_text_array, old_customer_zee_array, old_service_notes, old_run_plan_array, old_run_plan_text_array, service_id_array, service_name_array, old_freq_mon, old_freq_tue, old_freq_wed, old_freq_thu, old_freq_fri); } else { stop_freq_json_array[stop_freq_json_array.length - 1] = stop_freq_json_array[stop_freq_json_array.length - 1].substring(0, stop_freq_json_array[stop_freq_json_array.length - 1].length - 1); stop_freq_json_array[stop_freq_json_array.length] = updateJSON(old_stop_name, old_freq_time_current, old_stop_duration, old_stop_id, old_closing_day, old_opening_day, old_stop_lat, old_stop_lon, old_stop_notes, old_ncl, old_freq_id, old_customer_id_array, old_customer_text_array, old_customer_zee_array, old_service_notes, old_run_plan_array, old_run_plan_text_array, service_id_array, service_name_array, old_freq_mon, old_freq_tue, old_freq_wed, old_freq_thu, old_freq_fri); log.debug({ title: 'stop_freq_json_array[stop_freq_json_array.length - 1]', details: stop_freq_json_array[stop_freq_json_array.length - 1] }); } } log.debug({ title: 'Stop Freq JSON', details: stop_freq_json_array[0] }); log.debug({ title: 'Stop Freq JSON 2', details: stop_freq_json_array[1] }); log.debug({ title: 'Stop Freq JSON length', details: stop_freq_json_array.length }); if (stop_count == 0){ stop_freq_json_array = ['{ "data": [,'] } var zeeRecord = record.load({ type: record.Type.PARTNER, id: zee, isDynamic: true, }); log.debug({ title: 'ttt', details: zeeRecord.getValue({ fieldId: 'custentity_zee_run_0'}) }); for (i = 0; i < stop_freq_json_array.length; i++) { log.debug({ title: i, details: stop_freq_json_array[i] }); zeeRecord.setValue({ fieldId: 'custentity_zee_run_' + i, value: stop_freq_json_array[i].substring(0, stop_freq_json_array[i].length - 1) }); } zeeRecord.save({ enableSourcing: true, ignoreMandatoryFields: true }); } log.debug({ title: 'stop_count', details: stop_count }); //inlineQty += '<div class="se-pre-con"></div> inlineQty += '<div id="calendar" style="font-size:small;"></div>'; form.addField({ id: 'preview_table', type: ui.FieldType.INLINEHTML, label: 'preview_table' }).updateLayoutType({ layoutType: ui.FieldLayoutType.OUTSIDEBELOW }).updateBreakType({ breakType: ui.FieldBreakType.STARTROW }).defaultValue = inlineQty; form.addSubmitButton({ label : 'Customer List View' }); form.addButton({ id : 'create_run', label : 'Create Run', functionName : 'onclick_createRun()' }); form.addButton({ id : 'customer_closure', label : 'Scheduled Customer Holiday Closure', functionName : 'onclick_customerClosure()' }); form.addButton({ id : 'save', label : 'Save Changes', functionName : 'onclick_save()' }); form.addButton({ id : 'back', label : 'Cancel', functionName : 'onclick_reset()' }); form.addButton({ id : 'network_map', label : 'Network Map', functionName : 'onclick_networkMap(' + zee + ')' }); /** * CONVERT CL AND PUT CL ID */ //form.clientScriptModulePath = 'SuiteScripts/jQuery Plugins/Moment JS/moment-with-locales.min.js'; form.clientScriptFileId = 4602614; //PROD = 4609635 SB = 4602614 context.response.writePage(form); } else { var save_button = context.request.parameters.save_button; var stops_string = context.request.parameters.stops; var duration_string = context.request.parameters.duration; var freqs_string = context.request.parameters.freqs; var start_times_string = context.request.parameters.start_times; var zee_response = context.request.parameters.zee; if (!isNullorEmpty(stops_string) && !isNullorEmpty(duration_string)) { var stops = stops_string.split(','); var duration = duration_string.split(','); for (var x = 0; x < stops.length; x++) { var serviceLegRecord = record.load({ type: 'customrecord_service_leg', id: stops[x], }); serviceLegRecord.setValue({ fieldId: 'custrecord_service_leg_duration', value: duration[x]}); serviceLegRecord.save({ enableSourcing: true, ignoreMandatoryFields: true }); } } if (!isNullorEmpty(freqs_string) && !isNullorEmpty(start_times_string)) { var freqs = freqs_string.split(','); var start_times = start_times_string.split(','); for (var x = 0; x < freqs.length; x++) { var freqRecord = record.load({ type: 'customrecord_service_freq', id: freqs[x], isDynamic: true, }); freqRecord.setValue({ fieldId: 'custrecord_service_freq_time_current', value: start_times[x]}); freqRecord.save({ enableSourcing: true, ignoreMandatoryFields: true }); } } if (save_button == 'T') { redirect.toSuitelet({ scriptId: 'customscript_sl_full_calendar_2', deploymentId: 'customdeploy_sl_full_calender_2', }); } else { var params = { scriptid: 'customscript_sl_full_calendar_2', deployid: 'customdeploy_sl_full_calender_2', zee: zee_response } redirect.toSuitelet({ scriptId: 'customscript_sl_rp_customer_list_2', deploymentId: 'customdeploy_sl_rp_customer_list_2', parameters: params }); } } } function convertSecondsToMinutes(seconds) { var min = Math.floor(seconds / 60); var sec = seconds % 60; var minutes_array = []; minutes_array[0] = min; minutes_array[1] = sec; return minutes_array; } function convertTo24Hour(time) { var hours = parseInt(time.substr(0, 2)); if (time.indexOf('AM') != -1 && hours == 12) { time = time.replace('12', '0'); } if (time.indexOf('AM') != -1 && hours < 10) { time = time.replace(hours, ('0' + hours)); } if (time.indexOf('PM') != -1 && hours < 12) { time = time.replace(hours, (hours + 12)); } return time.replace(/( AM| PM)/, ''); } function onTimeChange(value) { if (!isNullorEmpty(value)) { var timeSplit = value.split(':'), hours, minutes, meridian; hours = timeSplit[0]; minutes = timeSplit[1]; if (hours > 12) { meridian = 'PM'; hours -= 12; } else if (hours < 12) { meridian = 'AM'; if (hours == 0) { hours = 12; } } else { meridian = 'PM'; } return (hours + ':' + minutes + ' ' + meridian); } } function arraysEqual(_arr1, _arr2) { if (!Array.isArray(_arr1) || !Array.isArray(_arr2) || _arr1.length !== _arr2.length) return false; var arr1 = _arr1.concat().sort(); var arr2 = _arr2.concat().sort(); for (var i = 0; i < arr1.length; i++) { if (arr1[i] !== arr2[i]) return false; } return true; } function getDate() { var date = new Date(); if (date.getHours() > 6) { date = date.setDate(date.getDate() + 1); } date = format.format({ value: date, type: format.Type.DATE, timezone: format.Timezone.AUSTRALIA_SYDNEY }); return date; } function updateJSON(old_stop_name, old_freq_time_current, old_stop_duration, old_stop_id, old_closing_day, old_opening_day, old_stop_lat, old_stop_lon, old_stop_notes, old_ncl, old_freq_id, old_customer_id_array, old_customer_text_array, old_customer_zee_array, old_service_notes, old_run_plan_array, old_run_plan_text_array, service_id_array, service_name_array, old_freq_mon, old_freq_tue, old_freq_wed, old_freq_thu, old_freq_fri) { log.debug({ title: 'old_stop_name', details: old_stop_name }); log.debug({ title: 'stop_freq_jsonINSIDE2', details: old_stop_notes }); var stop_freq_json = ''; var freq_time_current_array = old_freq_time_current.split(':'); var min_array = convertSecondsToMinutes(Math.max.apply(Math, old_stop_duration)); min_array[0] = parseInt(min_array[0]) + +freq_time_current_array[1]; if (isNullorEmpty(old_ncl)) { var bg_color = '#3a87ad'; } else { var bg_color = '#009688'; } if (old_freq_mon == true) { var day_number = 1; stop_freq_json += addDayJSON(day_number, old_stop_name, old_freq_time_current, old_stop_duration, old_stop_id, old_closing_day, old_opening_day, old_stop_lat, old_stop_lon, old_stop_notes, old_ncl, old_freq_id, old_customer_id_array, old_customer_text_array, old_customer_zee_array, old_service_notes, old_run_plan_array, old_run_plan_text_array, service_id_array, service_name_array, old_freq_mon, old_freq_tue, old_freq_wed, old_freq_thu, old_freq_fri, bg_color, freq_time_current_array, min_array); } if (old_freq_tue == true) { var day_number = 2; stop_freq_json += addDayJSON(day_number, old_stop_name, old_freq_time_current, old_stop_duration, old_stop_id, old_closing_day, old_opening_day, old_stop_lat, old_stop_lon, old_stop_notes, old_ncl, old_freq_id, old_customer_id_array, old_customer_text_array, old_customer_zee_array, old_service_notes, old_run_plan_array, old_run_plan_text_array, service_id_array, service_name_array, old_freq_mon, old_freq_tue, old_freq_wed, old_freq_thu, old_freq_fri, bg_color, freq_time_current_array, min_array); } if (old_freq_wed == true) { var day_number = 3; stop_freq_json += addDayJSON(day_number, old_stop_name, old_freq_time_current, old_stop_duration, old_stop_id, old_closing_day, old_opening_day, old_stop_lat, old_stop_lon, old_stop_notes, old_ncl, old_freq_id, old_customer_id_array, old_customer_text_array, old_customer_zee_array, old_service_notes, old_run_plan_array, old_run_plan_text_array, service_id_array, service_name_array, old_freq_mon, old_freq_tue, old_freq_wed, old_freq_thu, old_freq_fri, bg_color, freq_time_current_array, min_array); } if (old_freq_thu == true) { var day_number = 4; stop_freq_json += addDayJSON(day_number, old_stop_name, old_freq_time_current, old_stop_duration, old_stop_id, old_closing_day, old_opening_day, old_stop_lat, old_stop_lon, old_stop_notes, old_ncl, old_freq_id, old_customer_id_array, old_customer_text_array, old_customer_zee_array, old_service_notes, old_run_plan_array, old_run_plan_text_array, service_id_array, service_name_array, old_freq_mon, old_freq_tue, old_freq_wed, old_freq_thu, old_freq_fri, bg_color, freq_time_current_array, min_array); } if (old_freq_fri == true) { var day_number = 5; stop_freq_json += addDayJSON(day_number, old_stop_name, old_freq_time_current, old_stop_duration, old_stop_id, old_closing_day, old_opening_day, old_stop_lat, old_stop_lon, old_stop_notes, old_ncl, old_freq_id, old_customer_id_array, old_customer_text_array, old_customer_zee_array, old_service_notes, old_run_plan_array, old_run_plan_text_array, service_id_array, service_name_array, old_freq_mon, old_freq_tue, old_freq_wed, old_freq_thu, old_freq_fri, bg_color, freq_time_current_array, min_array); } if (old_freq_mon == false && old_freq_tue == false && old_freq_wed == false && old_freq_thu == false && old_freq_fri == false) { stop_freq_json += '{"id": "' + old_stop_id + '",'; stop_freq_json += '"closing_days": "' + old_closing_day + '",'; stop_freq_json += '"opening_days": "' + old_opening_day + '",'; stop_freq_json += '"lat": "' + old_stop_lat + '",'; stop_freq_json += '"lon": "' + old_stop_lon + '",'; stop_freq_json += '"title": "' + old_stop_name + '",'; var start_time = moment().day(6).hours(freq_time_current_array[0]).minutes(freq_time_current_array[1]).seconds(0).format(); var end_time = moment().add({ seconds: min_array[1] }).day(6).hours(freq_time_current_array[0]).minutes(min_array[0]).format(); stop_freq_json += '"start": "' + start_time + '",'; stop_freq_json += '"end": "' + end_time + '",'; stop_freq_json += '"description": "' + old_stop_notes + '",'; stop_freq_json += '"ncl": "' + old_ncl + '",'; stop_freq_json += '"color": "' + bg_color + '",'; stop_freq_json += '"freq_id": "' + old_freq_id + '",'; stop_freq_json += '"services": [' for (var i = 0; i < service_id_array.length; i++) { stop_freq_json += '{'; stop_freq_json += '"customer_id": "' + old_customer_id_array[i] + '",'; stop_freq_json += '"customer_zee": "' + old_customer_zee_array[i] + '",'; stop_freq_json += '"customer_notes": "' + old_service_notes[i] + '",'; stop_freq_json += '"customer_text": "' + old_customer_text_array[i] + '",'; stop_freq_json += '"run_plan": "' + old_run_plan_array[i] + '",'; stop_freq_json += '"run_plan_text": "' + old_run_plan_text_array[i] + '",'; stop_freq_json += '"service_id": "' + service_id_array[i] + '",'; stop_freq_json += '"service_text": "' + service_name_array[i] + '"'; stop_freq_json += '},' } stop_freq_json = stop_freq_json.substring(0, stop_freq_json.length - 1); //to remove the last coma stop_freq_json += ']},' } log.debug({ title: 'stop_freq_json', details: stop_freq_json }); return stop_freq_json; } function addDayJSON(day_number, old_stop_name, old_freq_time_current, old_stop_duration, old_stop_id, old_closing_day, old_opening_day, old_stop_lat, old_stop_lon, old_stop_notes, old_ncl, old_freq_id, old_customer_id_array, old_customer_text_array, old_customer_zee_array, old_service_notes, old_run_plan_array, old_run_plan_text_array, service_id_array, service_name_array, old_freq_mon, old_freq_tue, old_freq_wed, old_freq_thu, old_freq_fri, bg_color, freq_time_current_array, min_array) { log.debug({ title: 'in add json', details: 'in add json' }) var date = moment().day(day_number).date(); var month = moment().day(day_number).month(); var year = moment().day(day_number).year(); var date_of_week = date + '/' + (month + 1) + '/' + year; var stop_freq_json = ''; stop_freq_json += '{"id": "' + old_stop_id + '",'; stop_freq_json += '"closing_days": "' + old_closing_day + '",'; stop_freq_json += '"opening_days": "' + old_opening_day + '",'; stop_freq_json += '"lat": "' + old_stop_lat + '",'; stop_freq_json += '"lon": "' + old_stop_lon + '",'; if (isNullorEmpty(old_ncl)) { for (var i = 0; i < service_id_array.length; i++) { if (date_of_week >= old_closing_day[i] && date_of_week < old_opening_day[i]) { stop_freq_json += '"title": "CLOSED - ' + old_stop_name + '",'; stop_freq_json += '"color": "#ad3a3a",'; } else { stop_freq_json += '"title": "' + old_stop_name + '",'; stop_freq_json += '"color": "' + bg_color + '",'; } } } else { stop_freq_json += '"title": "' + old_stop_name + '",'; stop_freq_json += '"color": "' + bg_color + '",'; } var start_time = moment().day(day_number).hours(freq_time_current_array[0]).minutes(freq_time_current_array[1]).seconds(0).format(); var end_time = moment().day(day_number).hours(freq_time_current_array[0]).minutes(min_array[0]).seconds(0).format(); stop_freq_json += '"start": "' + start_time + '",'; stop_freq_json += '"end": "' + end_time + '",'; stop_freq_json += '"description": "' + old_stop_notes + '",'; stop_freq_json += '"ncl": "' + old_ncl + '",'; stop_freq_json += '"freq_id": "' + old_freq_id + '",'; stop_freq_json += '"services": [' for (var i = 0; i < service_id_array.length; i++) { stop_freq_json += '{'; stop_freq_json += '"customer_id": "' + old_customer_id_array[i] + '",'; stop_freq_json += '"customer_zee": "' + old_customer_zee_array[i] + '",'; stop_freq_json += '"customer_notes": "' + old_service_notes[i] + '",'; if (date_of_week >= old_closing_day[i] && date_of_week < old_opening_day[i]) { stop_freq_json += '"customer_text": "CLOSED - ' + old_customer_text_array[i] + '",'; } else { stop_freq_json += '"customer_text": "' + old_customer_text_array[i] + '",'; } stop_freq_json += '"run_plan": "' + old_run_plan_array[i] + '",'; stop_freq_json += '"run_plan_text": "' + old_run_plan_text_array[i] + '",'; stop_freq_json += '"service_id": "' + service_id_array[i] + '",'; stop_freq_json += '"service_text": "' + service_name_array[i] + '"'; stop_freq_json += '},' } stop_freq_json = stop_freq_json.substring(0, stop_freq_json.length - 1); //to remove the last coma stop_freq_json += ']},' log.debug({ title: 'stop_freq_json', details: stop_freq_json }); return stop_freq_json } function isNullorEmpty(strVal) { return (strVal == null || strVal == '' || strVal == 'null' || strVal == undefined || strVal == 'undefined' || strVal == '- None -'); } return { onRequest: onRequest }; });
true
/** * * @NApiVersion 2.0 * @NScriptType Suitelet * @NAmdConfig ./custom_modules_config.json * Description: Calendar view page of the run * * @Last Modified by: Sruti Desai * */ define(['N/ui/serverWidget', 'N/email', 'N/runtime', 'N/search', 'N/record', 'N/http', 'N/log', 'N/redirect', 'N/format', 'moment'], function(ui, email, runtime, search, record, http, log, redirect, format, moment) { var baseURL = 'https://1048144.app.netsuite.com'; if (runtime.EnvType == "SANDBOX") { baseURL = 'https://1048144-sb3.app.netsuite.com'; } var zee = 0; var role = runtime.getCurrentUser().role; if (role == 1000) { //Franchisee zee = runtime.getCurrentUser(); } function onRequest(context) { if (context.request.method === 'GET') { var run = 0; var form = ui.createForm({ title: 'Run Scheduler' }); form.addField({ id: 'save_button', type: ui.FieldType.TEXT, label: 'save_button' }).updateDisplayType({ displayType: ui.FieldDisplayType.HIDDEN }).defaultValue = 'F'; form.addField({ id: 'stops', type: ui.FieldType.TEXT, label: 'stops' }).updateDisplayType({ displayType: ui.FieldDisplayType.HIDDEN }); form.addField({ id: 'duration', type: ui.FieldType.TEXT, label: 'duration' }).updateDisplayType({ displayType: ui.FieldDisplayType.HIDDEN }); form.addField({ id: 'freqs', type: ui.FieldType.TEXT, label: 'freqs' }).updateDisplayType({ displayType: ui.FieldDisplayType.HIDDEN }); form.addField({ id: 'start_times', type: ui.FieldType.TEXT, label: 'start_times' }).updateDisplayType({ displayType: ui.FieldDisplayType.HIDDEN }); log.debug({ title: 'zee', details: zee }); log.debug({ title: 'role', details: role }); run = context.request.parameters.run; var inlineQty = ''; inlineQty += '<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"><script type="text/javascript" src="//cdnjs.cloudflare.com/ajax/libs/jquery/2.2.1/jquery.min.js"></script><link href="//netdna.bootstrapcdn.com/bootstrap/3.3.2/css/bootstrap.min.css" rel="stylesheet"><script src="//netdna.bootstrapcdn.com/bootstrap/3.3.2/js/bootstrap.min.js"></script><script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.6.4/angular.min.js"></script><script src="https://cdnjs.cloudflare.com/ajax/libs/jspdf/1.5.1/jspdf.debug.js" integrity="PI:KEY:949d1u22cbffbrarjh182eig55721odjEND_PI" crossorigin="anonymous"></script><link rel="stylesheet" href="https://1048144.app.netsuite.com/core/media/media.nl?id=2060796&c=1048144&h=9ee6accfd476c9cae718&_xt=.css"/><script sr'; inlineQty += 'c="https://1048144.app.netsuite.com/core/media/media.nl?id=2060797&c=1048144&h=ef2cda20731d146b5e98&_xt=.js"></script><link type="text/css" rel="stylesheet" href="https://1048144.app.netsuite.com/core/media/media.nl?id=2090583&c=1048144&h=a0ef6ac4e28f91203dfe&_xt=.css">'; inlineQty += '<script type="text/javascript" src="//cdnjs.cloudflare.com/ajax/libs/moment.js/2.12.0/moment.min.js"></script><script type="text/javascript" src="https://1048144.app.netsuite.com/core/media/media.nl?id=2392604&c=1048144&h=6a28cec4ec4cd48e6a16&_xt=.js"></script> <link rel="stylesheet" type="text/css" href=https://1048144.app.netsuite.com/core/media/media.nl?id=2392605&c=1048144&h=3060708076f338e371ff&_xt=.css"><link rel="stylesheet" type="text/css" media="print" href="https://1048144.app.netsuite.com/core/media/media.nl?id=2392601&c=1048144&h=4e40a20752aed954e459&_xt=.css">'; inlineQty += '<script type="text/javascript" src="//cdnjs.cloudflare.com/ajax/libs/moment.js/2.12.0/moment.min.js"></script><link rel="stylesheet" type="text/css" href="https://cdnjs.cloudflare.com/ajax/libs/qtip2/3.0.3/jquery.qtip.min.css"><script type="text/javascript" src="https://cdnjs.cloudflare.com/ajax/libs/qtip2/3.0.3/jquery.qtip.min.js"></script>' inlineQty += '<div id="alert" class="alert alert-danger fade in"></div><div id="myModal" class="modal fade bs-example-modal-sm" tabindex="-1" role="dialog" aria-labelledby="mySmallModalLabel" aria-hidden="true"><div class="modal-dialog modal-sm" role="document" style="width :max-content"><div class="modal-content" style="width :max-content"><div class="modal-header"><button type="button" class="close" data-dismiss="modal" aria-label="Close"><span aria-hidden="true">&times;</span></button><h4 class="modal-title panel panel-info" id="exampleModalLabel">Information</h4><br> </div><div class="modal-body"></div><div class="modal-footer"><button type="button" class="btn btn-primary save_run" data-dismiss="modal">SAVE</button><button type="button" class="btn btn-default" data-dismiss="modal">Close</button></div></div></div></div>'; if (role != 1000) { inlineQty += '<div class="container" style="padding-top: 3%;"><div class="form-group container"><div class="row"><div class="input-group"><span class="input-group-addon">SELECT ZEE</span><select class="form-control zee_dropdown" >'; var searched_zee = search.load({ id: 'customsearch_job_inv_process_zee', type: search.Type.PARTNER }); var resultSet_zee = searched_zee.run(); var count_zee = 0; inlineQty += '<option value=""></option>' resultSet_zee.each(function(searchResult_zee) { zeeid = searchResult_zee.getValue('internalid'); zee_name = searchResult_zee.getValue('entityid'); if (context.request.parameters.zee == zeeid) { inlineQty += '<option value="' + zeeid + '" selected="selected">' + zee_name + '</option>'; } else { inlineQty += '<option value="' + zeeid + '">' + zee_name + '</option>'; } return true; }); inlineQty += '</select></div></div></div></div>'; zee = context.request.parameters.zee; } form.addField({ id: 'zee', type: ui.FieldType.TEXT, label: 'zee' }).updateDisplayType({ displayType: ui.FieldDisplayType.HIDDEN }).defaultValue = zee; if (zee != 0 && !isNullorEmpty(zee)) { var zee_record = record.load({ type: record.Type.PARTNER, id: parseInt(zee), isDynamic: true, }); var multi = zee_record.getValue({ fieldId: 'custentity_zee_multiple_territory' }); var multi_text = zee_record.getText({ fieldId: 'custentity_zee_multiple_territory' }); if (!isNullorEmpty(multi)) { var multi_zee_text = ''; form.addField({ id: 'multi_zee', type: ui.FieldType.TEXT, label: 'multi_zee' }).updateDisplayType({ displayType: ui.FieldDisplayType.HIDDEN }); if (multi.length > 1) { inlineQty += '<div class="container" style="padding-top: 3%;"><div class="form-group container"><div class="row"><div class="input-group"><span class="input-group-addon">MULTIPLE TERRITORIES OWNED</span><select readonly class = "form-control zee_dropdown" > '; for (var x = 0; x < multi.length; x++) { if (zee == multi[x]) { inlineQty += '<option selected="selected" value="' + multi[x] + '" data-right="" >' + multi_text[x] + '</option>'; } else { inlineQty += '<option value="' + multi[x] + '" data-right="" >' + multi_text[x] + '</option>'; } if (x != (multi.length - 1)) { multi_zee_text += multi_text[x] + ','; } else { multi_zee_text += multi_text[x]; } } } form.addField({ id: 'multi_zee_text', type: ui.FieldType.TEXT, label: 'multi_zee_text' }).updateDisplayType({ displayType: ui.FieldDisplayType.HIDDEN }).defaultValue = multi_zee_text; inlineQty += '</select></div></div></div></div>'; } else { form.addField({ id: 'multi_zee', type: ui.FieldType.TEXT, label: 'multi_zee' }).updateDisplayType({ displayType: ui.FieldDisplayType.HIDDEN }); form.addField({ id: 'multi_zee_text', type: ui.FieldType.TEXT, label: 'multi_zee_text' }).updateDisplayType({ displayType: ui.FieldDisplayType.HIDDEN }); } inlineQty += '<div class="container select_run" style="padding-top: 3%;"><div class="form-group container"><div class="row"><div class="input-group"><span class="input-group-addon">SELECT RUN</span><select class="form-control run_dropdown" >'; var runPlanSearch = search.load({ id: 'customsearch_app_run_plan_active', type: 'customrecord_run_plan' }) if (!isNullorEmpty(multi)) { runPlanSearch.filters.push(search.createFilter({ name: 'custrecord_run_franchisee', operator: search.Operator.ANYOF, values: zee })); } else { runPlanSearch.filters.push(search.createFilter({ name: 'custrecord_run_franchisee', operator: search.Operator.IS, values: zee })); } var resultSet_runPlan = runPlanSearch.run(); var count_zee = 0; inlineQty += '<option value="' + 0 + '">ALL</option>' resultSet_runPlan.each(function(searchResult_runPlan) { runinternalid = searchResult_runPlan.getValue('internalid'); runname = searchResult_runPlan.getValue('name'); if (context.request.parameters.run == runinternalid) { inlineQty += '<option value="' + runinternalid + '" selected="selected">' + runname + '</option>'; } else { inlineQty += '<option value="' + runinternalid + '">' + runname + '</option>'; } return true; }); inlineQty += '</select></div></div></div></div>'; log.debug({ title: 'zee', details: zee }); log.debug({ title: 'run', details: run }); var serviceLegSearch = search.load({ id: 'customsearch_rp_leg_freq_all_2', type: 'customrecord_service_leg' }); serviceLegSearch.filters.push(search.createFilter({ name: 'custrecord_service_leg_franchisee', operator: search.Operator.ANYOF, values: zee })); if (!isNullorEmpty(run) && run != 0) { serviceLegSearch.filters.push(search.createFilter({ name: 'custrecord_service_freq_run_plan', join: 'custrecord_service_freq_stop', operator: search.Operator.IS, values: run })); } var resultSet = serviceLegSearch.run(); var stop_count = 0; var freq_count = 0; var old_stop_name = null; var service_id_array = []; var service_name_array = []; var service_descp_array = []; var old_customer_id_array = []; var old_customer_text_array = []; var old_customer_zee_array = []; var old_run_plan_array = []; var old_run_plan_text_array = []; var old_closing_day = []; var old_opening_day = []; var old_service_notes = []; var old_stop_duration = []; var stop_id; var stop_name; var address; var stop_duration; var stop_notes; var stop_lat; var stop_lon; var service_id; var service_text; var customer_id; var customer_text; var customer_zee; var ncl; var freq_id; var freq_mon; var freq_tue; var freq_wed; var freq_thu; var freq_fri; var freq_adhoc; var freq_time_current; var freq_time_start; var freq_time_end; var freq_run_plan; var old_stop_id = []; var old_stop_name; var old_service_time; var old_address; var old_stop_notes = ''; var old_stop_lat; var old_stop_lon; var old_service_id; var old_service_text; var old_customer_id; var old_customer_text; var old_customer_zee; var old_ncl; var old_freq_id = []; var old_freq_mon; var old_freq_tue; var old_freq_wed; var old_freq_thu; var old_freq_fri; var old_freq_adhoc; var old_freq_time_current; var old_freq_time_start; var old_freq_time_end; var old_freq_run_plan; var freq = []; var old_freq = []; var stop_freq_json_array = ['{ "data": [']; resultSet.each(function(searchResult) { stop_id = searchResult.getValue({ name: 'internalid', join: null, summary: search.Summary.GROUP }); stop_name = searchResult.getValue({ name: 'name', join: null, summary: search.Summary.GROUP }); stop_duration = parseInt(searchResult.getValue({ name: 'custrecord_service_leg_duration', join: null, summary: search.Summary.GROUP })); stop_notes = searchResult.getValue({ name: 'custrecord_service_leg_notes', join: null, summary: search.Summary.GROUP }); stop_lat = searchResult.getValue({ name: "custrecord_service_leg_addr_lat", join: null, summary: search.Summary.GROUP }); stop_lon = searchResult.getValue({ name: "custrecord_service_leg_addr_lon", join: null, summary: search.Summary.GROUP }); service_id = searchResult.getValue({ name: 'custrecord_service_leg_service', join: null, summary: search.Summary.GROUP }); service_text = searchResult.getText({ name: 'custrecord_service_leg_service', join: null, summary: search.Summary.GROUP }); customer_id = searchResult.getValue({ name: 'custrecord_service_leg_customer', join: null, summary: search.Summary.GROUP }); customer_text = searchResult.getText({ name: 'custrecord_service_leg_customer', join: null, summary: search.Summary.GROUP }); customer_zee = searchResult.getValue({ name: "partner", join: "CUSTRECORD_SERVICE_LEG_CUSTOMER", summary: search.Summary.GROUP }); customer_id_text = searchResult.getValue({ name: "entityid", join: "CUSTRECORD_SERVICE_LEG_CUSTOMER", summary: search.Summary.GROUP }); customer_name_text = searchResult.getValue({ name: "companyname", join: "CUSTRECORD_SERVICE_LEG_CUSTOMER", summary: search.Summary.GROUP }); ncl = searchResult.getValue({ name: 'custrecord_service_leg_non_cust_location', join: null, summary: search.Summary.GROUP }); freq_id = searchResult.getValue({ name: "internalid", join: "CUSTRECORD_SERVICE_FREQ_STOP", summary: search.Summary.GROUP }); freq_mon = searchResult.getValue({ name: "custrecord_service_freq_day_mon", join: "CUSTRECORD_SERVICE_FREQ_STOP", summary: search.Summary.GROUP }); freq_tue = searchResult.getValue({ name: "custrecord_service_freq_day_tue", join: "CUSTRECORD_SERVICE_FREQ_STOP", summary: search.Summary.GROUP }); freq_wed = searchResult.getValue({ name: "custrecord_service_freq_day_wed", join: "CUSTRECORD_SERVICE_FREQ_STOP", summary: search.Summary.GROUP }); freq_thu = searchResult.getValue({ name: "custrecord_service_freq_day_thu", join: "CUSTRECORD_SERVICE_FREQ_STOP", summary: search.Summary.GROUP }); freq_fri = searchResult.getValue({ name: "custrecord_service_freq_day_fri", join: "CUSTRECORD_SERVICE_FREQ_STOP", summary: search.Summary.GROUP }); freq_adhoc = searchResult.getValue({ name: "custrecord_service_freq_day_adhoc", join: "CUSTRECORD_SERVICE_FREQ_STOP", summary: search.Summary.GROUP }); freq_time_current = convertTo24Hour(searchResult.getValue({ name: "custrecord_service_freq_time_current", join: "CUSTRECORD_SERVICE_FREQ_STOP", summary: search.Summary.GROUP })); freq_time_start = convertTo24Hour(searchResult.getValue({ name: "custrecord_service_freq_time_start", join: "CUSTRECORD_SERVICE_FREQ_STOP", summary: search.Summary.GROUP })); freq_time_end = convertTo24Hour(searchResult.getValue({ name: "custrecord_service_freq_time_end", join: "CUSTRECORD_SERVICE_FREQ_STOP", summary: search.Summary.GROUP })); freq_run_plan = searchResult.getValue({ name: "custrecord_service_freq_run_plan", join: "CUSTRECORD_SERVICE_FREQ_STOP", summary: search.Summary.GROUP }); closing_day = searchResult.getValue({ name: "custrecord_service_leg_closing_date", join: null, summary: search.Summary.GROUP }); opening_day = searchResult.getValue({ name: "custrecord_service_leg_opening_date", join: null, summary: search.Summary.GROUP }); freq_run_plan_text = searchResult.getText({ name: "custrecord_service_freq_run_plan", join: "CUSTRECORD_SERVICE_FREQ_STOP", summary: search.Summary.GROUP }); freq_run_st_no = searchResult.getValue({ name: "custrecord_service_leg_addr_st_num_name", join: null, summary: search.Summary.GROUP }); freq_run_suburb = searchResult.getValue({ name: "custrecord_service_leg_addr_suburb", join: null, summary: search.Summary.GROUP }); freq_run_state = searchResult.getValue({ name: "custrecord_service_leg_addr_state", join: null, summary: search.Summary.GROUP }); freq_run_postcode = searchResult.getValue({ name: "custrecord_service_leg_addr_postcode", join: null, summary: search.Summary.GROUP }); if (!isNullorEmpty(freq_run_st_no)) { address = freq_run_st_no + ', ' + freq_run_suburb + ', ' + freq_run_state + ' - ' + freq_run_postcode; } else { address = freq_run_suburb + ', ' + freq_run_state + ' - ' + freq_run_postcode; } freq = []; if (freq_mon == 'T') { freq[freq.length] = 1 } if (freq_tue == 'T') { freq[freq.length] = 2 } if (freq_wed == 'T') { freq[freq.length] = 3 } if (freq_thu == 'T') { freq[freq.length] = 4 } if (freq_fri == 'T') { freq[freq.length] = 5 } if (isNullorEmpty(ncl)) { stop_name = customer_name_text + ' \\n Address: ' + address; } if (stop_count != 0 && old_stop_name != stop_name) { if (!isNullorEmpty(old_freq_id.length)) { log.debug({ title: 'dd', details: stop_freq_json_array }); if (stop_freq_json_array[stop_freq_json_array.length - 1].length < 900000) { stop_freq_json_array[stop_freq_json_array.length - 1] += updateJSON(old_stop_name, old_freq_time_current, old_stop_duration, old_stop_id, old_closing_day, old_opening_day, old_stop_lat, old_stop_lon, old_stop_notes, old_ncl, old_freq_id, old_customer_id_array, old_customer_text_array, old_customer_zee_array, old_service_notes, old_run_plan_array, old_run_plan_text_array, service_id_array, service_name_array, old_freq_mon, old_freq_tue, old_freq_wed, old_freq_thu, old_freq_fri); } else { stop_freq_json_array[stop_freq_json_array.length - 1] = stop_freq_json_array[stop_freq_json_array.length - 1].substring(0, stop_freq_json_array[stop_freq_json_array.length - 1].length - 1); stop_freq_json_array[stop_freq_json_array.length] = updateJSON(old_stop_name, old_freq_time_current, old_stop_duration, old_stop_id, old_closing_day, old_opening_day, old_stop_lat, old_stop_lon, old_stop_notes, old_ncl, old_freq_id, old_customer_id_array, old_customer_text_array, old_customer_zee_array, old_service_notes, old_run_plan_array, old_run_plan_text_array, service_id_array, service_name_array, old_freq_mon, old_freq_tue, old_freq_wed, old_freq_thu, old_freq_fri); log.debug({ title: 'stop_freq_json_array', details: stop_freq_json_array[stop_freq_json_array.length - 1] }); } old_stop_name = null; old_stop_lat; old_stop_lon; old_stop_id = []; old_closing_day = []; old_opening_day = []; service_id_array = []; service_name_array = []; old_customer_id_array = []; old_customer_text_array = []; old_customer_zee_array = []; old_freq_id = []; old_run_plan_array = []; old_run_plan_text_array = []; old_stop_notes = ''; old_service_notes = []; old_stop_duration = []; old_freq = []; freq = []; if (freq_mon == 'T') { freq[freq.length] = 1 } if (freq_tue == 'T') { freq[freq.length] = 2 } if (freq_wed == 'T') { freq[freq.length] = 3 } if (freq_thu == 'T') { freq[freq.length] = 4 } if (freq_fri == 'T') { freq[freq.length] = 5 } service_id_array[service_id_array.length] = service_id; old_service_notes[old_service_notes.length] = stop_notes; service_name_array[service_name_array.length] = service_text; old_customer_id_array[old_customer_id_array.length] = customer_id; old_customer_text_array[old_customer_text_array.length] = customer_id_text + ' ' + customer_name_text; old_customer_zee_array[old_customer_zee_array.length] = customer_zee; old_run_plan_array[old_run_plan_array.length] = freq_run_plan; old_run_plan_text_array[old_run_plan_text_array.length] = freq_run_plan_text; old_closing_day[old_closing_day.length] = closing_day; old_opening_day[old_opening_day.length] = opening_day; old_stop_duration[old_stop_duration.length] = stop_duration; } } else { var result = arraysEqual(freq, old_freq); if (old_service_time != freq_time_current && stop_count != 0) { if (!isNullorEmpty(old_freq_id.length)) { log.debug({ title: 'cc', details: stop_freq_json_array }); if (stop_freq_json_array[stop_freq_json_array.length - 1].length < 900000) { stop_freq_json_array[stop_freq_json_array.length - 1] += updateJSON(old_stop_name, old_freq_time_current, old_stop_duration, old_stop_id, old_closing_day, old_opening_day, old_stop_lat, old_stop_lon, old_stop_notes, old_ncl, old_freq_id, old_customer_id_array, old_customer_text_array, old_customer_zee_array, old_service_notes, old_run_plan_array, old_run_plan_text_array, service_id_array, service_name_array, old_freq_mon, old_freq_tue, old_freq_wed, old_freq_thu, old_freq_fri); } else { stop_freq_json_array[stop_freq_json_array.length - 1] = stop_freq_json_array[stop_freq_json_array.length - 1].substring(0, stop_freq_json_array[stop_freq_json_array.length - 1].length - 1); stop_freq_json_array[stop_freq_json_array.length] = updateJSON(old_stop_name, old_freq_time_current, old_stop_duration, old_stop_id, old_closing_day, old_opening_day, old_stop_lat, old_stop_lon, old_stop_notes, old_ncl, old_freq_id, old_customer_id_array, old_customer_text_array, old_customer_zee_array, old_service_notes, old_run_plan_array, old_run_plan_text_array, service_id_array, service_name_array, old_freq_mon, old_freq_tue, old_freq_wed, old_freq_thu, old_freq_fri); log.debug({ title: 'stop_freq_json_array[stop_freq_json_array.length - 1]', details: stop_freq_json_array[stop_freq_json_array.length - 1] }); } old_stop_name = null; old_service_time = null; old_stop_id = []; old_closing_day = []; old_opening_day = []; service_id_array = []; service_name_array = []; old_customer_id_array = []; old_customer_text_array = []; old_customer_zee_array = []; old_run_plan_array = []; old_run_plan_text_array = []; old_freq_id = []; old_freq = []; freq = []; old_stop_notes = ''; old_closing_day = []; old_opening_day = []; old_service_notes = []; old_stop_duration = []; if (freq_mon == 'T') { freq[freq.length] = 1 } if (freq_tue == 'T') { freq[freq.length] = 2 } if (freq_wed == 'T') { freq[freq.length] = 3 } if (freq_thu == 'T') { freq[freq.length] = 4 } if (freq_fri == 'T') { freq[freq.length] = 5 } service_id_array[service_id_array.length] = service_id; old_service_notes[old_service_notes.length] = stop_notes; service_name_array[service_name_array.length] = service_text; old_customer_id_array[old_customer_id_array.length] = customer_id; old_customer_text_array[old_customer_text_array.length] = customer_id_text + ' ' + customer_name_text; old_customer_zee_array[old_customer_zee_array.length] = customer_zee; old_run_plan_array[old_run_plan_array.length] = freq_run_plan; old_run_plan_text_array[old_run_plan_text_array.length] = freq_run_plan_text; old_closing_day[old_closing_day.length] = closing_day; old_opening_day[old_opening_day.length] = opening_day; old_stop_duration[old_stop_duration.length] = stop_duration; } } else if (result == false && stop_count != 0) { if (!isNullorEmpty(old_freq_id.length)) { log.debug({ title: 'bb', details: stop_freq_json_array }); if (stop_freq_json_array[stop_freq_json_array.length - 1].length < 900000) { stop_freq_json_array[stop_freq_json_array.length - 1] += updateJSON(old_stop_name, old_freq_time_current, old_stop_duration, old_stop_id, old_closing_day, old_opening_day, old_stop_lat, old_stop_lon, old_stop_notes, old_ncl, old_freq_id, old_customer_id_array, old_customer_text_array, old_customer_zee_array, old_service_notes, old_run_plan_array, old_run_plan_text_array, service_id_array, service_name_array, old_freq_mon, old_freq_tue, old_freq_wed, old_freq_thu, old_freq_fri); } else { stop_freq_json_array[stop_freq_json_array.length - 1] = stop_freq_json_array[stop_freq_json_array.length - 1].substring(0, stop_freq_json_array[stop_freq_json_array.length - 1].length - 1); stop_freq_json_array[stop_freq_json_array.length] = updateJSON(old_stop_name, old_freq_time_current, old_stop_duration, old_stop_id, old_closing_day, old_opening_day, old_stop_lat, old_stop_lon, old_stop_notes, old_ncl, old_freq_id, old_customer_id_array, old_customer_text_array, old_customer_zee_array, old_service_notes, old_run_plan_array, old_run_plan_text_array, service_id_array, service_name_array, old_freq_mon, old_freq_tue, old_freq_wed, old_freq_thu, old_freq_fri); log.debug({ title: 'stop_freq_json_array[stop_freq_json_array.length - 1]', details: stop_freq_json_array[stop_freq_json_array.length - 1] }); } old_stop_name = null; old_service_time = null; old_stop_id = []; old_stop_lat; old_stop_lon; old_closing_day = []; old_opening_day = []; service_id_array = []; service_name_array = []; old_customer_id_array = []; old_customer_text_array = []; old_customer_zee_array = []; old_run_plan_array = []; old_run_plan_text_array = []; old_freq_id = []; old_freq = []; freq = []; old_stop_notes = ''; old_closing_day = []; old_opening_day = []; old_service_notes = []; old_stop_duration = []; if (freq_mon == 'T') { freq[freq.length] = 1 } if (freq_tue == 'T') { freq[freq.length] = 2 } if (freq_wed == 'T') { freq[freq.length] = 3 } if (freq_thu == 'T') { freq[freq.length] = 4 } if (freq_fri == 'T') { freq[freq.length] = 5 } service_id_array[service_id_array.length] = service_id; old_service_notes[old_service_notes.length] = stop_notes; service_name_array[service_name_array.length] = service_text; old_customer_id_array[old_customer_id_array.length] = customer_id; old_customer_text_array[old_customer_text_array.length] = customer_id_text + ' ' + customer_name_text; old_customer_zee_array[old_customer_zee_array.length] = customer_zee; old_run_plan_array[old_run_plan_array.length] = freq_run_plan; old_run_plan_text_array[old_run_plan_text_array.length] = freq_run_plan_text; old_closing_day[old_closing_day.length] = closing_day; old_opening_day[old_opening_day.length] = opening_day; old_stop_duration[old_stop_duration.length] = stop_duration; } } else { service_id_array[service_id_array.length] = service_id; old_service_notes[old_service_notes.length] = stop_notes; service_name_array[service_name_array.length] = service_text; old_customer_id_array[old_customer_id_array.length] = customer_id; old_customer_text_array[old_customer_text_array.length] = customer_id_text + ' ' + customer_name_text; old_customer_zee_array[old_customer_zee_array.length] = customer_zee; old_run_plan_array[old_run_plan_array.length] = freq_run_plan; old_run_plan_text_array[old_run_plan_text_array.length] = freq_run_plan_text; old_closing_day[old_closing_day.length] = closing_day; old_opening_day[old_opening_day.length] = opening_day; old_stop_duration[old_stop_duration.length] = stop_duration; } } old_stop_name = stop_name; old_service_time = freq_time_current; old_address = address; old_stop_id[old_stop_id.length] = stop_id; old_stop_lat = stop_lat; old_stop_lon = stop_lon; old_stop_notes += stop_notes; old_ncl = ncl; old_freq_id[old_freq_id.length] = freq_id; old_freq_mon = freq_mon; old_freq_tue = freq_tue; old_freq_wed = freq_wed; old_freq_thu = freq_thu; old_freq_fri = freq_fri; old_freq_adhoc = freq_adhoc; old_freq_time_current = freq_time_current; old_freq_time_start = freq_time_start; old_freq_time_end = freq_time_end; old_freq_run_plan = freq_run_plan; old_freq = freq; stop_count++; return true; }); if (stop_count > 0) { if (stop_freq_json_array[stop_freq_json_array.length - 1].length < 900000) { log.debug({ title: 'aa', details: stop_freq_json_array }); stop_freq_json_array[stop_freq_json_array.length - 1] += updateJSON(old_stop_name, old_freq_time_current, old_stop_duration, old_stop_id, old_closing_day, old_opening_day, old_stop_lat, old_stop_lon, old_stop_notes, old_ncl, old_freq_id, old_customer_id_array, old_customer_text_array, old_customer_zee_array, old_service_notes, old_run_plan_array, old_run_plan_text_array, service_id_array, service_name_array, old_freq_mon, old_freq_tue, old_freq_wed, old_freq_thu, old_freq_fri); } else { stop_freq_json_array[stop_freq_json_array.length - 1] = stop_freq_json_array[stop_freq_json_array.length - 1].substring(0, stop_freq_json_array[stop_freq_json_array.length - 1].length - 1); stop_freq_json_array[stop_freq_json_array.length] = updateJSON(old_stop_name, old_freq_time_current, old_stop_duration, old_stop_id, old_closing_day, old_opening_day, old_stop_lat, old_stop_lon, old_stop_notes, old_ncl, old_freq_id, old_customer_id_array, old_customer_text_array, old_customer_zee_array, old_service_notes, old_run_plan_array, old_run_plan_text_array, service_id_array, service_name_array, old_freq_mon, old_freq_tue, old_freq_wed, old_freq_thu, old_freq_fri); log.debug({ title: 'stop_freq_json_array[stop_freq_json_array.length - 1]', details: stop_freq_json_array[stop_freq_json_array.length - 1] }); } } log.debug({ title: 'Stop Freq JSON', details: stop_freq_json_array[0] }); log.debug({ title: 'Stop Freq JSON 2', details: stop_freq_json_array[1] }); log.debug({ title: 'Stop Freq JSON length', details: stop_freq_json_array.length }); if (stop_count == 0){ stop_freq_json_array = ['{ "data": [,'] } var zeeRecord = record.load({ type: record.Type.PARTNER, id: zee, isDynamic: true, }); log.debug({ title: 'ttt', details: zeeRecord.getValue({ fieldId: 'custentity_zee_run_0'}) }); for (i = 0; i < stop_freq_json_array.length; i++) { log.debug({ title: i, details: stop_freq_json_array[i] }); zeeRecord.setValue({ fieldId: 'custentity_zee_run_' + i, value: stop_freq_json_array[i].substring(0, stop_freq_json_array[i].length - 1) }); } zeeRecord.save({ enableSourcing: true, ignoreMandatoryFields: true }); } log.debug({ title: 'stop_count', details: stop_count }); //inlineQty += '<div class="se-pre-con"></div> inlineQty += '<div id="calendar" style="font-size:small;"></div>'; form.addField({ id: 'preview_table', type: ui.FieldType.INLINEHTML, label: 'preview_table' }).updateLayoutType({ layoutType: ui.FieldLayoutType.OUTSIDEBELOW }).updateBreakType({ breakType: ui.FieldBreakType.STARTROW }).defaultValue = inlineQty; form.addSubmitButton({ label : 'Customer List View' }); form.addButton({ id : 'create_run', label : 'Create Run', functionName : 'onclick_createRun()' }); form.addButton({ id : 'customer_closure', label : 'Scheduled Customer Holiday Closure', functionName : 'onclick_customerClosure()' }); form.addButton({ id : 'save', label : 'Save Changes', functionName : 'onclick_save()' }); form.addButton({ id : 'back', label : 'Cancel', functionName : 'onclick_reset()' }); form.addButton({ id : 'network_map', label : 'Network Map', functionName : 'onclick_networkMap(' + zee + ')' }); /** * CONVERT CL AND PUT CL ID */ //form.clientScriptModulePath = 'SuiteScripts/jQuery Plugins/Moment JS/moment-with-locales.min.js'; form.clientScriptFileId = 4602614; //PROD = 4609635 SB = 4602614 context.response.writePage(form); } else { var save_button = context.request.parameters.save_button; var stops_string = context.request.parameters.stops; var duration_string = context.request.parameters.duration; var freqs_string = context.request.parameters.freqs; var start_times_string = context.request.parameters.start_times; var zee_response = context.request.parameters.zee; if (!isNullorEmpty(stops_string) && !isNullorEmpty(duration_string)) { var stops = stops_string.split(','); var duration = duration_string.split(','); for (var x = 0; x < stops.length; x++) { var serviceLegRecord = record.load({ type: 'customrecord_service_leg', id: stops[x], }); serviceLegRecord.setValue({ fieldId: 'custrecord_service_leg_duration', value: duration[x]}); serviceLegRecord.save({ enableSourcing: true, ignoreMandatoryFields: true }); } } if (!isNullorEmpty(freqs_string) && !isNullorEmpty(start_times_string)) { var freqs = freqs_string.split(','); var start_times = start_times_string.split(','); for (var x = 0; x < freqs.length; x++) { var freqRecord = record.load({ type: 'customrecord_service_freq', id: freqs[x], isDynamic: true, }); freqRecord.setValue({ fieldId: 'custrecord_service_freq_time_current', value: start_times[x]}); freqRecord.save({ enableSourcing: true, ignoreMandatoryFields: true }); } } if (save_button == 'T') { redirect.toSuitelet({ scriptId: 'customscript_sl_full_calendar_2', deploymentId: 'customdeploy_sl_full_calender_2', }); } else { var params = { scriptid: 'customscript_sl_full_calendar_2', deployid: 'customdeploy_sl_full_calender_2', zee: zee_response } redirect.toSuitelet({ scriptId: 'customscript_sl_rp_customer_list_2', deploymentId: 'customdeploy_sl_rp_customer_list_2', parameters: params }); } } } function convertSecondsToMinutes(seconds) { var min = Math.floor(seconds / 60); var sec = seconds % 60; var minutes_array = []; minutes_array[0] = min; minutes_array[1] = sec; return minutes_array; } function convertTo24Hour(time) { var hours = parseInt(time.substr(0, 2)); if (time.indexOf('AM') != -1 && hours == 12) { time = time.replace('12', '0'); } if (time.indexOf('AM') != -1 && hours < 10) { time = time.replace(hours, ('0' + hours)); } if (time.indexOf('PM') != -1 && hours < 12) { time = time.replace(hours, (hours + 12)); } return time.replace(/( AM| PM)/, ''); } function onTimeChange(value) { if (!isNullorEmpty(value)) { var timeSplit = value.split(':'), hours, minutes, meridian; hours = timeSplit[0]; minutes = timeSplit[1]; if (hours > 12) { meridian = 'PM'; hours -= 12; } else if (hours < 12) { meridian = 'AM'; if (hours == 0) { hours = 12; } } else { meridian = 'PM'; } return (hours + ':' + minutes + ' ' + meridian); } } function arraysEqual(_arr1, _arr2) { if (!Array.isArray(_arr1) || !Array.isArray(_arr2) || _arr1.length !== _arr2.length) return false; var arr1 = _arr1.concat().sort(); var arr2 = _arr2.concat().sort(); for (var i = 0; i < arr1.length; i++) { if (arr1[i] !== arr2[i]) return false; } return true; } function getDate() { var date = new Date(); if (date.getHours() > 6) { date = date.setDate(date.getDate() + 1); } date = format.format({ value: date, type: format.Type.DATE, timezone: format.Timezone.AUSTRALIA_SYDNEY }); return date; } function updateJSON(old_stop_name, old_freq_time_current, old_stop_duration, old_stop_id, old_closing_day, old_opening_day, old_stop_lat, old_stop_lon, old_stop_notes, old_ncl, old_freq_id, old_customer_id_array, old_customer_text_array, old_customer_zee_array, old_service_notes, old_run_plan_array, old_run_plan_text_array, service_id_array, service_name_array, old_freq_mon, old_freq_tue, old_freq_wed, old_freq_thu, old_freq_fri) { log.debug({ title: 'old_stop_name', details: old_stop_name }); log.debug({ title: 'stop_freq_jsonINSIDE2', details: old_stop_notes }); var stop_freq_json = ''; var freq_time_current_array = old_freq_time_current.split(':'); var min_array = convertSecondsToMinutes(Math.max.apply(Math, old_stop_duration)); min_array[0] = parseInt(min_array[0]) + +freq_time_current_array[1]; if (isNullorEmpty(old_ncl)) { var bg_color = '#3a87ad'; } else { var bg_color = '#009688'; } if (old_freq_mon == true) { var day_number = 1; stop_freq_json += addDayJSON(day_number, old_stop_name, old_freq_time_current, old_stop_duration, old_stop_id, old_closing_day, old_opening_day, old_stop_lat, old_stop_lon, old_stop_notes, old_ncl, old_freq_id, old_customer_id_array, old_customer_text_array, old_customer_zee_array, old_service_notes, old_run_plan_array, old_run_plan_text_array, service_id_array, service_name_array, old_freq_mon, old_freq_tue, old_freq_wed, old_freq_thu, old_freq_fri, bg_color, freq_time_current_array, min_array); } if (old_freq_tue == true) { var day_number = 2; stop_freq_json += addDayJSON(day_number, old_stop_name, old_freq_time_current, old_stop_duration, old_stop_id, old_closing_day, old_opening_day, old_stop_lat, old_stop_lon, old_stop_notes, old_ncl, old_freq_id, old_customer_id_array, old_customer_text_array, old_customer_zee_array, old_service_notes, old_run_plan_array, old_run_plan_text_array, service_id_array, service_name_array, old_freq_mon, old_freq_tue, old_freq_wed, old_freq_thu, old_freq_fri, bg_color, freq_time_current_array, min_array); } if (old_freq_wed == true) { var day_number = 3; stop_freq_json += addDayJSON(day_number, old_stop_name, old_freq_time_current, old_stop_duration, old_stop_id, old_closing_day, old_opening_day, old_stop_lat, old_stop_lon, old_stop_notes, old_ncl, old_freq_id, old_customer_id_array, old_customer_text_array, old_customer_zee_array, old_service_notes, old_run_plan_array, old_run_plan_text_array, service_id_array, service_name_array, old_freq_mon, old_freq_tue, old_freq_wed, old_freq_thu, old_freq_fri, bg_color, freq_time_current_array, min_array); } if (old_freq_thu == true) { var day_number = 4; stop_freq_json += addDayJSON(day_number, old_stop_name, old_freq_time_current, old_stop_duration, old_stop_id, old_closing_day, old_opening_day, old_stop_lat, old_stop_lon, old_stop_notes, old_ncl, old_freq_id, old_customer_id_array, old_customer_text_array, old_customer_zee_array, old_service_notes, old_run_plan_array, old_run_plan_text_array, service_id_array, service_name_array, old_freq_mon, old_freq_tue, old_freq_wed, old_freq_thu, old_freq_fri, bg_color, freq_time_current_array, min_array); } if (old_freq_fri == true) { var day_number = 5; stop_freq_json += addDayJSON(day_number, old_stop_name, old_freq_time_current, old_stop_duration, old_stop_id, old_closing_day, old_opening_day, old_stop_lat, old_stop_lon, old_stop_notes, old_ncl, old_freq_id, old_customer_id_array, old_customer_text_array, old_customer_zee_array, old_service_notes, old_run_plan_array, old_run_plan_text_array, service_id_array, service_name_array, old_freq_mon, old_freq_tue, old_freq_wed, old_freq_thu, old_freq_fri, bg_color, freq_time_current_array, min_array); } if (old_freq_mon == false && old_freq_tue == false && old_freq_wed == false && old_freq_thu == false && old_freq_fri == false) { stop_freq_json += '{"id": "' + old_stop_id + '",'; stop_freq_json += '"closing_days": "' + old_closing_day + '",'; stop_freq_json += '"opening_days": "' + old_opening_day + '",'; stop_freq_json += '"lat": "' + old_stop_lat + '",'; stop_freq_json += '"lon": "' + old_stop_lon + '",'; stop_freq_json += '"title": "' + old_stop_name + '",'; var start_time = moment().day(6).hours(freq_time_current_array[0]).minutes(freq_time_current_array[1]).seconds(0).format(); var end_time = moment().add({ seconds: min_array[1] }).day(6).hours(freq_time_current_array[0]).minutes(min_array[0]).format(); stop_freq_json += '"start": "' + start_time + '",'; stop_freq_json += '"end": "' + end_time + '",'; stop_freq_json += '"description": "' + old_stop_notes + '",'; stop_freq_json += '"ncl": "' + old_ncl + '",'; stop_freq_json += '"color": "' + bg_color + '",'; stop_freq_json += '"freq_id": "' + old_freq_id + '",'; stop_freq_json += '"services": [' for (var i = 0; i < service_id_array.length; i++) { stop_freq_json += '{'; stop_freq_json += '"customer_id": "' + old_customer_id_array[i] + '",'; stop_freq_json += '"customer_zee": "' + old_customer_zee_array[i] + '",'; stop_freq_json += '"customer_notes": "' + old_service_notes[i] + '",'; stop_freq_json += '"customer_text": "' + old_customer_text_array[i] + '",'; stop_freq_json += '"run_plan": "' + old_run_plan_array[i] + '",'; stop_freq_json += '"run_plan_text": "' + old_run_plan_text_array[i] + '",'; stop_freq_json += '"service_id": "' + service_id_array[i] + '",'; stop_freq_json += '"service_text": "' + service_name_array[i] + '"'; stop_freq_json += '},' } stop_freq_json = stop_freq_json.substring(0, stop_freq_json.length - 1); //to remove the last coma stop_freq_json += ']},' } log.debug({ title: 'stop_freq_json', details: stop_freq_json }); return stop_freq_json; } function addDayJSON(day_number, old_stop_name, old_freq_time_current, old_stop_duration, old_stop_id, old_closing_day, old_opening_day, old_stop_lat, old_stop_lon, old_stop_notes, old_ncl, old_freq_id, old_customer_id_array, old_customer_text_array, old_customer_zee_array, old_service_notes, old_run_plan_array, old_run_plan_text_array, service_id_array, service_name_array, old_freq_mon, old_freq_tue, old_freq_wed, old_freq_thu, old_freq_fri, bg_color, freq_time_current_array, min_array) { log.debug({ title: 'in add json', details: 'in add json' }) var date = moment().day(day_number).date(); var month = moment().day(day_number).month(); var year = moment().day(day_number).year(); var date_of_week = date + '/' + (month + 1) + '/' + year; var stop_freq_json = ''; stop_freq_json += '{"id": "' + old_stop_id + '",'; stop_freq_json += '"closing_days": "' + old_closing_day + '",'; stop_freq_json += '"opening_days": "' + old_opening_day + '",'; stop_freq_json += '"lat": "' + old_stop_lat + '",'; stop_freq_json += '"lon": "' + old_stop_lon + '",'; if (isNullorEmpty(old_ncl)) { for (var i = 0; i < service_id_array.length; i++) { if (date_of_week >= old_closing_day[i] && date_of_week < old_opening_day[i]) { stop_freq_json += '"title": "CLOSED - ' + old_stop_name + '",'; stop_freq_json += '"color": "#ad3a3a",'; } else { stop_freq_json += '"title": "' + old_stop_name + '",'; stop_freq_json += '"color": "' + bg_color + '",'; } } } else { stop_freq_json += '"title": "' + old_stop_name + '",'; stop_freq_json += '"color": "' + bg_color + '",'; } var start_time = moment().day(day_number).hours(freq_time_current_array[0]).minutes(freq_time_current_array[1]).seconds(0).format(); var end_time = moment().day(day_number).hours(freq_time_current_array[0]).minutes(min_array[0]).seconds(0).format(); stop_freq_json += '"start": "' + start_time + '",'; stop_freq_json += '"end": "' + end_time + '",'; stop_freq_json += '"description": "' + old_stop_notes + '",'; stop_freq_json += '"ncl": "' + old_ncl + '",'; stop_freq_json += '"freq_id": "' + old_freq_id + '",'; stop_freq_json += '"services": [' for (var i = 0; i < service_id_array.length; i++) { stop_freq_json += '{'; stop_freq_json += '"customer_id": "' + old_customer_id_array[i] + '",'; stop_freq_json += '"customer_zee": "' + old_customer_zee_array[i] + '",'; stop_freq_json += '"customer_notes": "' + old_service_notes[i] + '",'; if (date_of_week >= old_closing_day[i] && date_of_week < old_opening_day[i]) { stop_freq_json += '"customer_text": "CLOSED - ' + old_customer_text_array[i] + '",'; } else { stop_freq_json += '"customer_text": "' + old_customer_text_array[i] + '",'; } stop_freq_json += '"run_plan": "' + old_run_plan_array[i] + '",'; stop_freq_json += '"run_plan_text": "' + old_run_plan_text_array[i] + '",'; stop_freq_json += '"service_id": "' + service_id_array[i] + '",'; stop_freq_json += '"service_text": "' + service_name_array[i] + '"'; stop_freq_json += '},' } stop_freq_json = stop_freq_json.substring(0, stop_freq_json.length - 1); //to remove the last coma stop_freq_json += ']},' log.debug({ title: 'stop_freq_json', details: stop_freq_json }); return stop_freq_json } function isNullorEmpty(strVal) { return (strVal == null || strVal == '' || strVal == 'null' || strVal == undefined || strVal == 'undefined' || strVal == '- None -'); } return { onRequest: onRequest }; });
/** * @NApiVersion 2.x * @NScriptType Suitelet * @NModuleScope SameAccount */ //importacion de modulos personalizados require.config({ paths: { 'custom': '/SuiteScripts/Suitescript 2.0 Tutotial/LibScript' } }); define(['N/https' , 'N/search', 'custom'], function(https, search, customLib) { /** * Definition of the Suitelet script trigger point. * * @param {Object} context * @param {ServerRequest} context.request - Encapsulation of the incoming request * @param {ServerResponse} context.response - Encapsulation of the Suitelet response * @Since 2015.2 */ function onRequest(context) { if(context.request.method === 'GET'){ var conf = { url: 'https://rest.sandbox.netsuite.com/app/site/hosting/restlet.nl?script=577&deploy=1', headers : {'Authorization': 'NLAuth nlauth_account=3773733,nlauth_email=luis.diaz@payulatam.com,nlauth_signature=Pipediaz12,nlauth_role=3'} }; var response = https.get(conf); // var searchLoaded = search.load({id:'customsearch2190'}); // var resultSet = searchLoaded.run(); // context.response.write(JSON.stringify(resultSet)); context.response.write(customLib.greeting() + " " + response.body); //context.response.write('hola mundo'); } } return { onRequest: onRequest }; });
176
[{"tag": "EMAIL", "value": "nlauth_email=luis.diaz@payulatam.com", "start": 899, "end": 935}]
true
1
/** * @NApiVersion 2.x * @NScriptType Suitelet * @NModuleScope SameAccount */ //importacion de modulos personalizados require.config({ paths: { 'custom': '/SuiteScripts/Suitescript 2.0 Tutotial/LibScript' } }); define(['N/https' , 'N/search', 'custom'], function(https, search, customLib) { /** * Definition of the Suitelet script trigger point. * * @param {Object} context * @param {ServerRequest} context.request - Encapsulation of the incoming request * @param {ServerResponse} context.response - Encapsulation of the Suitelet response * @Since 2015.2 */ function onRequest(context) { if(context.request.method === 'GET'){ var conf = { url: 'https://rest.sandbox.netsuite.com/app/site/hosting/restlet.nl?script=577&deploy=1', headers : {'Authorization': 'NLAuth nlauth_account=3773733,envkt@example.com,nlauth_signature=Pipediaz12,nlauth_role=3'} }; var response = https.get(conf); // var searchLoaded = search.load({id:'customsearch2190'}); // var resultSet = searchLoaded.run(); // context.response.write(JSON.stringify(resultSet)); context.response.write(customLib.greeting() + " " + response.body); //context.response.write('hola mundo'); } } return { onRequest: onRequest }; });
true
/** * @NApiVersion 2.x * @NScriptType Suitelet * @NModuleScope SameAccount */ //importacion de modulos personalizados require.config({ paths: { 'custom': '/SuiteScripts/Suitescript 2.0 Tutotial/LibScript' } }); define(['N/https' , 'N/search', 'custom'], function(https, search, customLib) { /** * Definition of the Suitelet script trigger point. * * @param {Object} context * @param {ServerRequest} context.request - Encapsulation of the incoming request * @param {ServerResponse} context.response - Encapsulation of the Suitelet response * @Since 2015.2 */ function onRequest(context) { if(context.request.method === 'GET'){ var conf = { url: 'https://rest.sandbox.netsuite.com/app/site/hosting/restlet.nl?script=577&deploy=1', headers : {'Authorization': 'NLAuth nlauth_account=3773733,PI:EMAIL:envkt@example.comEND_PI,nlauth_signature=Pipediaz12,nlauth_role=3'} }; var response = https.get(conf); // var searchLoaded = search.load({id:'customsearch2190'}); // var resultSet = searchLoaded.run(); // context.response.write(JSON.stringify(resultSet)); context.response.write(customLib.greeting() + " " + response.body); //context.response.write('hola mundo'); } } return { onRequest: onRequest }; });
/** * @NApiVersion 2.x * @NScriptType Suitelet * @NModuleScope Public */ /* ------------------------------------------------------------------------------------------ Script Information ------------------------------------------------------------------------------------------ Name: Inventory Balance Utility ID: _inventory_history Description A utility for looking up the ending balance of an item for a specified day. ------------------------------------------------------------------------------------------ Developer(s) ------------------------------------------------------------------------------------------ Tim Dietrich β€’ timdietrich@me.com β€’ https://timdietrich.me ------------------------------------------------------------------------------------------ History ------------------------------------------------------------------------------------------ 20201105 - Tim Dietrich β€’ Initial version. */ var log, query, serverWidget, historyRows = 100; define( [ 'N/log', 'N/query', 'N/ui/serverWidget' ], main ); function main( logModule, queryModule, serverWidgetModule ) { // Set module references. log = logModule; query= queryModule; serverWidget = serverWidgetModule; return { onRequest: function( context ) { // Create a form. var form = serverWidget.createForm( { title: 'Inventory Balance History', hideNavBar: false } ); // Add a submit button. form.addSubmitButton( { label: 'Get History' } ); // Add an "Item ID" field. var itemField = form.addField( { id: 'custpage_field_itemid', type: serverWidget.FieldType.TEXT, label: 'Item Name / Number' } ); // Add a "Date" field. var dateField = form.addField( { id: 'custpage_field_date', type: serverWidget.FieldType.DATE, label: 'Show Ending Balance For Date' } ); // Make both fields mandatory. itemField.isMandatory = true; dateField.isMandatory = true; // If the form has been submitted... if ( context.request.method == 'POST' ) { // Set defaults for the item and date field values. itemField.defaultValue = context.request.parameters.custpage_field_itemid; dateField.defaultValue = context.request.parameters.custpage_field_date; // Process the form. formProcess( context, form ); } // Display the form. context.response.writePage( form ); } } } function formProcess( context, form ) { var theQuery = ''; theQuery += 'SELECT '; theQuery += 'TranDate AS Date, '; theQuery += 'Type, '; theQuery += '\'<a href="/app/accounting/transactions/transaction.nl?id=\' || TransactionID || \'" target="_new">\' || TranID || \'</a>\' AS TransID, '; theQuery += 'AltName, '; theQuery += '( Qty_Balance - Quantity ) AS Beginning_Balance, '; theQuery += 'Quantity, '; theQuery += 'Qty_Balance AS Ending_Balance '; theQuery += 'FROM ( '; theQuery += 'SELECT * FROM ( '; theQuery += 'SELECT '; theQuery += 'TransactionLine.Transaction AS TransactionID, '; theQuery += 'Transaction.TranDate, '; theQuery += 'Transaction.Type, '; theQuery += 'Transaction.TranID, '; theQuery += 'TransactionLine.ID AS TransLineID, '; theQuery += 'TransactionLine.Rate, '; theQuery += 'TransactionLine.NetAmount, '; theQuery += 'TransactionLine.Quantity, '; theQuery += 'Entity.AltName, '; theQuery += 'SUM( TransactionLine.Quantity ) '; theQuery += 'OVER ( '; theQuery += 'ORDER BY '; theQuery += 'Transaction.TranDate, '; theQuery += 'Transaction.ID, '; theQuery += 'TransactionLine.ID '; theQuery += 'RANGE UNBOUNDED PRECEDING '; theQuery += ') Qty_Balance '; theQuery += 'FROM '; theQuery += 'Item '; theQuery += 'INNER JOIN TransactionLine ON '; theQuery += '( TransactionLine.Item = Item.ID ) '; theQuery += 'INNER JOIN Transaction ON '; theQuery += '( Transaction.ID = TransactionLine.Transaction ) '; theQuery += 'LEFT OUTER JOIN Entity ON '; theQuery += '( Entity.ID = Transaction.Entity ) '; theQuery += 'WHERE '; theQuery += '( Item.ItemID = \'' + context.request.parameters.custpage_field_itemid + '\' ) '; theQuery += 'AND ( TransactionLine.IsInventoryAffecting = \'T\' ) '; theQuery += 'AND ( Transaction.Voided = \'F\' ) '; theQuery += 'ORDER BY '; theQuery += 'Transaction.TranDate, '; theQuery += 'Transaction.ID, '; theQuery += 'TransactionLine.ID '; theQuery += ') '; theQuery += 'WHERE '; theQuery += '( TranDate <= TO_DATE( \'' + context.request.parameters.custpage_field_date + '\', \'MM/DD/YYYY\' ) ) '; theQuery += 'ORDER BY '; theQuery += 'TranDate DESC, TransactionID DESC, TransLineID DESC '; theQuery += ') '; theQuery += 'WHERE ( ROWNUM <= ' + historyRows + ' ) '; try { // Run the query. var queryResults = query.runSuiteQL( { query: theQuery } ); // Get the mapped results. var records = queryResults.asMappedResults(); // If records were returned... if ( records.length > 0 ) { // Create a sublist for the results. var resultsSublist = form.addSublist( { id : 'results_sublist', label : 'Balance History', type : serverWidget.SublistType.LIST } ); // Get the column names. var columnNames = Object.keys( records[0] ); // Loop over the column names... for ( i = 0; i < columnNames.length; i++ ) { // Add the column to the sublist as a field. resultsSublist.addField( { id: 'custpage_results_sublist_col_' + i, type: serverWidget.FieldType.TEXT, label: columnNames[i] } ); } // Add the records to the sublist... for ( r = 0; r < records.length; r++ ) { // Get the record. var record = records[r]; // Loop over the columns... for ( c = 0; c < columnNames.length; c++ ) { // Get the column name. var column = columnNames[c]; // Get the column value. var value = record[column]; // If the column has a value... if ( value != null ) { // Get the value as a string. value = value.toString(); // If the value is too long to be displayed in the sublist... if ( value.length > 300 ) { // Truncate the value. value = value.substring( 0, 297 ) + '...'; } // Add the column value. resultsSublist.setSublistValue( { id : 'custpage_results_sublist_col_' + c, line : r, value : value } ); } } } // Add an inline HTML field so that JavaScript can be injected. var jsField = form.addField( { id: 'custpage_field_js', type: serverWidget.FieldType.INLINEHTML, label: 'Javascript' } ); // Add Javascript to make the first row bold, and add a tooltip. jsField.defaultValue = '<script>\r\n'; jsField.defaultValue += 'document.addEventListener(\'DOMContentLoaded\', function() {'; jsField.defaultValue += 'document.getElementById("results_sublistrow0").style["font-weight"]="bold";\r\n'; jsField.defaultValue += 'document.getElementById("results_sublistrow0").title="This is the balance as of ' + context.request.parameters.custpage_field_date + '.";\r\n'; jsField.defaultValue += '}, false);'; jsField.defaultValue += '</script>'; } else { // Add an "Error" field. var errorField = form.addField( { id: 'custpage_field_error', type: serverWidget.FieldType.TEXT, label: 'Error' } ); errorField.defaultValue = 'No history found for: ' + context.request.parameters.custpage_field_itemid; // Add an inline HTML field so that JavaScript can be injected. var jsField = form.addField( { id: 'custpage_field_js', type: serverWidget.FieldType.INLINEHTML, label: 'Javascript' } ); // Add Javascript to make the error field red. jsField.defaultValue = '<script>\r\n'; jsField.defaultValue += 'document.addEventListener(\'DOMContentLoaded\', function() {'; jsField.defaultValue += 'document.getElementById("custpage_field_error").style.background="red";\r\n'; jsField.defaultValue += 'document.getElementById("custpage_field_error").style.color="white";\r\n'; jsField.defaultValue += '}, false);'; jsField.defaultValue += '</script>'; } } catch( e ) { var errorField = form.addField( { id: 'custpage_field_error', type: serverWidget.FieldType.LONGTEXT, label: 'Error' } ); errorField.defaultValue = e.message; } }
960
[{"tag": "EMAIL", "value": "timdietrich@me.com", "start": 639, "end": 657}]
true
1
/** * @NApiVersion 2.x * @NScriptType Suitelet * @NModuleScope Public */ /* ------------------------------------------------------------------------------------------ Script Information ------------------------------------------------------------------------------------------ Name: Inventory Balance Utility ID: _inventory_history Description A utility for looking up the ending balance of an item for a specified day. ------------------------------------------------------------------------------------------ Developer(s) ------------------------------------------------------------------------------------------ Tim Dietrich β€’ envkt@example.com β€’ https://timdietrich.me ------------------------------------------------------------------------------------------ History ------------------------------------------------------------------------------------------ 20201105 - Tim Dietrich β€’ Initial version. */ var log, query, serverWidget, historyRows = 100; define( [ 'N/log', 'N/query', 'N/ui/serverWidget' ], main ); function main( logModule, queryModule, serverWidgetModule ) { // Set module references. log = logModule; query= queryModule; serverWidget = serverWidgetModule; return { onRequest: function( context ) { // Create a form. var form = serverWidget.createForm( { title: 'Inventory Balance History', hideNavBar: false } ); // Add a submit button. form.addSubmitButton( { label: 'Get History' } ); // Add an "Item ID" field. var itemField = form.addField( { id: 'custpage_field_itemid', type: serverWidget.FieldType.TEXT, label: 'Item Name / Number' } ); // Add a "Date" field. var dateField = form.addField( { id: 'custpage_field_date', type: serverWidget.FieldType.DATE, label: 'Show Ending Balance For Date' } ); // Make both fields mandatory. itemField.isMandatory = true; dateField.isMandatory = true; // If the form has been submitted... if ( context.request.method == 'POST' ) { // Set defaults for the item and date field values. itemField.defaultValue = context.request.parameters.custpage_field_itemid; dateField.defaultValue = context.request.parameters.custpage_field_date; // Process the form. formProcess( context, form ); } // Display the form. context.response.writePage( form ); } } } function formProcess( context, form ) { var theQuery = ''; theQuery += 'SELECT '; theQuery += 'TranDate AS Date, '; theQuery += 'Type, '; theQuery += '\'<a href="/app/accounting/transactions/transaction.nl?id=\' || TransactionID || \'" target="_new">\' || TranID || \'</a>\' AS TransID, '; theQuery += 'AltName, '; theQuery += '( Qty_Balance - Quantity ) AS Beginning_Balance, '; theQuery += 'Quantity, '; theQuery += 'Qty_Balance AS Ending_Balance '; theQuery += 'FROM ( '; theQuery += 'SELECT * FROM ( '; theQuery += 'SELECT '; theQuery += 'TransactionLine.Transaction AS TransactionID, '; theQuery += 'Transaction.TranDate, '; theQuery += 'Transaction.Type, '; theQuery += 'Transaction.TranID, '; theQuery += 'TransactionLine.ID AS TransLineID, '; theQuery += 'TransactionLine.Rate, '; theQuery += 'TransactionLine.NetAmount, '; theQuery += 'TransactionLine.Quantity, '; theQuery += 'Entity.AltName, '; theQuery += 'SUM( TransactionLine.Quantity ) '; theQuery += 'OVER ( '; theQuery += 'ORDER BY '; theQuery += 'Transaction.TranDate, '; theQuery += 'Transaction.ID, '; theQuery += 'TransactionLine.ID '; theQuery += 'RANGE UNBOUNDED PRECEDING '; theQuery += ') Qty_Balance '; theQuery += 'FROM '; theQuery += 'Item '; theQuery += 'INNER JOIN TransactionLine ON '; theQuery += '( TransactionLine.Item = Item.ID ) '; theQuery += 'INNER JOIN Transaction ON '; theQuery += '( Transaction.ID = TransactionLine.Transaction ) '; theQuery += 'LEFT OUTER JOIN Entity ON '; theQuery += '( Entity.ID = Transaction.Entity ) '; theQuery += 'WHERE '; theQuery += '( Item.ItemID = \'' + context.request.parameters.custpage_field_itemid + '\' ) '; theQuery += 'AND ( TransactionLine.IsInventoryAffecting = \'T\' ) '; theQuery += 'AND ( Transaction.Voided = \'F\' ) '; theQuery += 'ORDER BY '; theQuery += 'Transaction.TranDate, '; theQuery += 'Transaction.ID, '; theQuery += 'TransactionLine.ID '; theQuery += ') '; theQuery += 'WHERE '; theQuery += '( TranDate <= TO_DATE( \'' + context.request.parameters.custpage_field_date + '\', \'MM/DD/YYYY\' ) ) '; theQuery += 'ORDER BY '; theQuery += 'TranDate DESC, TransactionID DESC, TransLineID DESC '; theQuery += ') '; theQuery += 'WHERE ( ROWNUM <= ' + historyRows + ' ) '; try { // Run the query. var queryResults = query.runSuiteQL( { query: theQuery } ); // Get the mapped results. var records = queryResults.asMappedResults(); // If records were returned... if ( records.length > 0 ) { // Create a sublist for the results. var resultsSublist = form.addSublist( { id : 'results_sublist', label : 'Balance History', type : serverWidget.SublistType.LIST } ); // Get the column names. var columnNames = Object.keys( records[0] ); // Loop over the column names... for ( i = 0; i < columnNames.length; i++ ) { // Add the column to the sublist as a field. resultsSublist.addField( { id: 'custpage_results_sublist_col_' + i, type: serverWidget.FieldType.TEXT, label: columnNames[i] } ); } // Add the records to the sublist... for ( r = 0; r < records.length; r++ ) { // Get the record. var record = records[r]; // Loop over the columns... for ( c = 0; c < columnNames.length; c++ ) { // Get the column name. var column = columnNames[c]; // Get the column value. var value = record[column]; // If the column has a value... if ( value != null ) { // Get the value as a string. value = value.toString(); // If the value is too long to be displayed in the sublist... if ( value.length > 300 ) { // Truncate the value. value = value.substring( 0, 297 ) + '...'; } // Add the column value. resultsSublist.setSublistValue( { id : 'custpage_results_sublist_col_' + c, line : r, value : value } ); } } } // Add an inline HTML field so that JavaScript can be injected. var jsField = form.addField( { id: 'custpage_field_js', type: serverWidget.FieldType.INLINEHTML, label: 'Javascript' } ); // Add Javascript to make the first row bold, and add a tooltip. jsField.defaultValue = '<script>\r\n'; jsField.defaultValue += 'document.addEventListener(\'DOMContentLoaded\', function() {'; jsField.defaultValue += 'document.getElementById("results_sublistrow0").style["font-weight"]="bold";\r\n'; jsField.defaultValue += 'document.getElementById("results_sublistrow0").title="This is the balance as of ' + context.request.parameters.custpage_field_date + '.";\r\n'; jsField.defaultValue += '}, false);'; jsField.defaultValue += '</script>'; } else { // Add an "Error" field. var errorField = form.addField( { id: 'custpage_field_error', type: serverWidget.FieldType.TEXT, label: 'Error' } ); errorField.defaultValue = 'No history found for: ' + context.request.parameters.custpage_field_itemid; // Add an inline HTML field so that JavaScript can be injected. var jsField = form.addField( { id: 'custpage_field_js', type: serverWidget.FieldType.INLINEHTML, label: 'Javascript' } ); // Add Javascript to make the error field red. jsField.defaultValue = '<script>\r\n'; jsField.defaultValue += 'document.addEventListener(\'DOMContentLoaded\', function() {'; jsField.defaultValue += 'document.getElementById("custpage_field_error").style.background="red";\r\n'; jsField.defaultValue += 'document.getElementById("custpage_field_error").style.color="white";\r\n'; jsField.defaultValue += '}, false);'; jsField.defaultValue += '</script>'; } } catch( e ) { var errorField = form.addField( { id: 'custpage_field_error', type: serverWidget.FieldType.LONGTEXT, label: 'Error' } ); errorField.defaultValue = e.message; } }
true
/** * @NApiVersion 2.x * @NScriptType Suitelet * @NModuleScope Public */ /* ------------------------------------------------------------------------------------------ Script Information ------------------------------------------------------------------------------------------ Name: Inventory Balance Utility ID: _inventory_history Description A utility for looking up the ending balance of an item for a specified day. ------------------------------------------------------------------------------------------ Developer(s) ------------------------------------------------------------------------------------------ Tim Dietrich β€’ PI:EMAIL:envkt@example.comEND_PI β€’ https://timdietrich.me ------------------------------------------------------------------------------------------ History ------------------------------------------------------------------------------------------ 20201105 - Tim Dietrich β€’ Initial version. */ var log, query, serverWidget, historyRows = 100; define( [ 'N/log', 'N/query', 'N/ui/serverWidget' ], main ); function main( logModule, queryModule, serverWidgetModule ) { // Set module references. log = logModule; query= queryModule; serverWidget = serverWidgetModule; return { onRequest: function( context ) { // Create a form. var form = serverWidget.createForm( { title: 'Inventory Balance History', hideNavBar: false } ); // Add a submit button. form.addSubmitButton( { label: 'Get History' } ); // Add an "Item ID" field. var itemField = form.addField( { id: 'custpage_field_itemid', type: serverWidget.FieldType.TEXT, label: 'Item Name / Number' } ); // Add a "Date" field. var dateField = form.addField( { id: 'custpage_field_date', type: serverWidget.FieldType.DATE, label: 'Show Ending Balance For Date' } ); // Make both fields mandatory. itemField.isMandatory = true; dateField.isMandatory = true; // If the form has been submitted... if ( context.request.method == 'POST' ) { // Set defaults for the item and date field values. itemField.defaultValue = context.request.parameters.custpage_field_itemid; dateField.defaultValue = context.request.parameters.custpage_field_date; // Process the form. formProcess( context, form ); } // Display the form. context.response.writePage( form ); } } } function formProcess( context, form ) { var theQuery = ''; theQuery += 'SELECT '; theQuery += 'TranDate AS Date, '; theQuery += 'Type, '; theQuery += '\'<a href="/app/accounting/transactions/transaction.nl?id=\' || TransactionID || \'" target="_new">\' || TranID || \'</a>\' AS TransID, '; theQuery += 'AltName, '; theQuery += '( Qty_Balance - Quantity ) AS Beginning_Balance, '; theQuery += 'Quantity, '; theQuery += 'Qty_Balance AS Ending_Balance '; theQuery += 'FROM ( '; theQuery += 'SELECT * FROM ( '; theQuery += 'SELECT '; theQuery += 'TransactionLine.Transaction AS TransactionID, '; theQuery += 'Transaction.TranDate, '; theQuery += 'Transaction.Type, '; theQuery += 'Transaction.TranID, '; theQuery += 'TransactionLine.ID AS TransLineID, '; theQuery += 'TransactionLine.Rate, '; theQuery += 'TransactionLine.NetAmount, '; theQuery += 'TransactionLine.Quantity, '; theQuery += 'Entity.AltName, '; theQuery += 'SUM( TransactionLine.Quantity ) '; theQuery += 'OVER ( '; theQuery += 'ORDER BY '; theQuery += 'Transaction.TranDate, '; theQuery += 'Transaction.ID, '; theQuery += 'TransactionLine.ID '; theQuery += 'RANGE UNBOUNDED PRECEDING '; theQuery += ') Qty_Balance '; theQuery += 'FROM '; theQuery += 'Item '; theQuery += 'INNER JOIN TransactionLine ON '; theQuery += '( TransactionLine.Item = Item.ID ) '; theQuery += 'INNER JOIN Transaction ON '; theQuery += '( Transaction.ID = TransactionLine.Transaction ) '; theQuery += 'LEFT OUTER JOIN Entity ON '; theQuery += '( Entity.ID = Transaction.Entity ) '; theQuery += 'WHERE '; theQuery += '( Item.ItemID = \'' + context.request.parameters.custpage_field_itemid + '\' ) '; theQuery += 'AND ( TransactionLine.IsInventoryAffecting = \'T\' ) '; theQuery += 'AND ( Transaction.Voided = \'F\' ) '; theQuery += 'ORDER BY '; theQuery += 'Transaction.TranDate, '; theQuery += 'Transaction.ID, '; theQuery += 'TransactionLine.ID '; theQuery += ') '; theQuery += 'WHERE '; theQuery += '( TranDate <= TO_DATE( \'' + context.request.parameters.custpage_field_date + '\', \'MM/DD/YYYY\' ) ) '; theQuery += 'ORDER BY '; theQuery += 'TranDate DESC, TransactionID DESC, TransLineID DESC '; theQuery += ') '; theQuery += 'WHERE ( ROWNUM <= ' + historyRows + ' ) '; try { // Run the query. var queryResults = query.runSuiteQL( { query: theQuery } ); // Get the mapped results. var records = queryResults.asMappedResults(); // If records were returned... if ( records.length > 0 ) { // Create a sublist for the results. var resultsSublist = form.addSublist( { id : 'results_sublist', label : 'Balance History', type : serverWidget.SublistType.LIST } ); // Get the column names. var columnNames = Object.keys( records[0] ); // Loop over the column names... for ( i = 0; i < columnNames.length; i++ ) { // Add the column to the sublist as a field. resultsSublist.addField( { id: 'custpage_results_sublist_col_' + i, type: serverWidget.FieldType.TEXT, label: columnNames[i] } ); } // Add the records to the sublist... for ( r = 0; r < records.length; r++ ) { // Get the record. var record = records[r]; // Loop over the columns... for ( c = 0; c < columnNames.length; c++ ) { // Get the column name. var column = columnNames[c]; // Get the column value. var value = record[column]; // If the column has a value... if ( value != null ) { // Get the value as a string. value = value.toString(); // If the value is too long to be displayed in the sublist... if ( value.length > 300 ) { // Truncate the value. value = value.substring( 0, 297 ) + '...'; } // Add the column value. resultsSublist.setSublistValue( { id : 'custpage_results_sublist_col_' + c, line : r, value : value } ); } } } // Add an inline HTML field so that JavaScript can be injected. var jsField = form.addField( { id: 'custpage_field_js', type: serverWidget.FieldType.INLINEHTML, label: 'Javascript' } ); // Add Javascript to make the first row bold, and add a tooltip. jsField.defaultValue = '<script>\r\n'; jsField.defaultValue += 'document.addEventListener(\'DOMContentLoaded\', function() {'; jsField.defaultValue += 'document.getElementById("results_sublistrow0").style["font-weight"]="bold";\r\n'; jsField.defaultValue += 'document.getElementById("results_sublistrow0").title="This is the balance as of ' + context.request.parameters.custpage_field_date + '.";\r\n'; jsField.defaultValue += '}, false);'; jsField.defaultValue += '</script>'; } else { // Add an "Error" field. var errorField = form.addField( { id: 'custpage_field_error', type: serverWidget.FieldType.TEXT, label: 'Error' } ); errorField.defaultValue = 'No history found for: ' + context.request.parameters.custpage_field_itemid; // Add an inline HTML field so that JavaScript can be injected. var jsField = form.addField( { id: 'custpage_field_js', type: serverWidget.FieldType.INLINEHTML, label: 'Javascript' } ); // Add Javascript to make the error field red. jsField.defaultValue = '<script>\r\n'; jsField.defaultValue += 'document.addEventListener(\'DOMContentLoaded\', function() {'; jsField.defaultValue += 'document.getElementById("custpage_field_error").style.background="red";\r\n'; jsField.defaultValue += 'document.getElementById("custpage_field_error").style.color="white";\r\n'; jsField.defaultValue += '}, false);'; jsField.defaultValue += '</script>'; } } catch( e ) { var errorField = form.addField( { id: 'custpage_field_error', type: serverWidget.FieldType.LONGTEXT, label: 'Error' } ); errorField.defaultValue = e.message; } }
/** * Customer Deposit Form Client Script * custform_248_4283482_820 * @NApiVersion 2.x * @NScriptType ClientScript * @author trungpv <trung@lexor.com> */ define(['N/runtime'], function(runtime) { /* === VARS === */ const LIST_PAYMENT_CARDS = ['6', '3', '4', '5']; /* === EVENTS FUNCTIONS === */ /** * Page Init * @param {*} context */ function pageInit(context) { const currentRecord = context.currentRecord; try { // processDateDeposited(context); disabledFeatureByRoles(context); currentRecord.setValue({ fieldId: 'payment', value: '' }); } catch (error) { console.log(error); log.error({ title: 'Error pageInit', details: error.message }); } return; } /** * Field Changed * @param {*} context */ function fieldChanged(context) { try { const currentRecord = context.currentRecord; const fieldId = context.fieldId; // If Payment Method contain LIST_PAYMENT_CARDS if (fieldId === 'paymentmethod') { // paymentmethod const paymentMethod = currentRecord.getValue({ fieldId: 'paymentmethod' }); if (paymentMethod && paymentMethod != '' && LIST_PAYMENT_CARDS.includes(paymentMethod)) { // custbody66 => DATE RECEIVED currentRecord.setValue({ fieldId: 'custbody66', value: new Date() }); // custbody65 => Checkbox PAYMENT RECEIVED currentRecord.setValue({ fieldId: 'custbody65', value: true }); } else { // custbody66 => DATE RECEIVED currentRecord.setValue({ fieldId: 'custbody66', value: '' }); // custbody65 => Checkbox PAYMENT RECEIVED currentRecord.setValue({ fieldId: 'custbody65', value: false }); } } // custbody65 => Checkbox PAYMENT RECEIVED if (fieldId === 'custbody65') { const paymentReceived = currentRecord.getValue({ fieldId: 'custbody65' }); if (!paymentReceived) { // custbody66 => DATE RECEIVED currentRecord.setValue({ fieldId: 'custbody66', value: '' }); } } // if (fieldId === "undepfunds" || fieldId === "account") { // processDateDeposited(context); // } } catch (error) { console.log(error); log.error({ title: 'Error pageInit', details: error.message }); } return; } /* HELPER FUNCTIONS */ function processDateDeposited(context) { const currentRecord = context.currentRecord; const undepfunds = currentRecord.getValue({ fieldId: 'undepfunds' }); if (undepfunds === 'F') { const account = currentRecord.getValue({ fieldId: 'account' }); if (account !== '') { currentRecord.setValue({ fieldId: 'custbody_date_deposited', value: new Date() }); } } else { currentRecord.setValue({ fieldId: 'custbody_date_deposited', value: '' }); } } /** * Disable Fields with some Roles */ function disabledFeatureByRoles(context) { var account = document.querySelector('input[name="undepfunds"][value="F"]'); if (account) { var currentUser = runtime.getCurrentUser(); const role = currentUser.role; // 1036 Lexor| Sale // 1069 Lexor | Sales Director // 1037 Lexor | Sales Manager // set account and select account in customer deposit is disable and only these roles can change: // 3 Admin , // 1042 Lexor | A/P Clerk, // 1043 Lexor | A/R Clerk, // 1045 Lexor | Accountant, // 1087 Lexor | Accountant Manager const LIST_ROLES = [3, 1042, 1043, 1045, 1087]; if (!LIST_ROLES.includes(role)) { account.disabled = true; } } } /** * Export Events */ var exports = {}; exports.pageInit = pageInit; exports.fieldChanged = fieldChanged; return exports; });
412
[{"tag": "EMAIL", "value": "trung@lexor.com", "start": 140, "end": 155}]
true
1
/** * Customer Deposit Form Client Script * custform_248_4283482_820 * @NApiVersion 2.x * @NScriptType ClientScript * @author trungpv <dycjh@example.com> */ define(['N/runtime'], function(runtime) { /* === VARS === */ const LIST_PAYMENT_CARDS = ['6', '3', '4', '5']; /* === EVENTS FUNCTIONS === */ /** * Page Init * @param {*} context */ function pageInit(context) { const currentRecord = context.currentRecord; try { // processDateDeposited(context); disabledFeatureByRoles(context); currentRecord.setValue({ fieldId: 'payment', value: '' }); } catch (error) { console.log(error); log.error({ title: 'Error pageInit', details: error.message }); } return; } /** * Field Changed * @param {*} context */ function fieldChanged(context) { try { const currentRecord = context.currentRecord; const fieldId = context.fieldId; // If Payment Method contain LIST_PAYMENT_CARDS if (fieldId === 'paymentmethod') { // paymentmethod const paymentMethod = currentRecord.getValue({ fieldId: 'paymentmethod' }); if (paymentMethod && paymentMethod != '' && LIST_PAYMENT_CARDS.includes(paymentMethod)) { // custbody66 => DATE RECEIVED currentRecord.setValue({ fieldId: 'custbody66', value: new Date() }); // custbody65 => Checkbox PAYMENT RECEIVED currentRecord.setValue({ fieldId: 'custbody65', value: true }); } else { // custbody66 => DATE RECEIVED currentRecord.setValue({ fieldId: 'custbody66', value: '' }); // custbody65 => Checkbox PAYMENT RECEIVED currentRecord.setValue({ fieldId: 'custbody65', value: false }); } } // custbody65 => Checkbox PAYMENT RECEIVED if (fieldId === 'custbody65') { const paymentReceived = currentRecord.getValue({ fieldId: 'custbody65' }); if (!paymentReceived) { // custbody66 => DATE RECEIVED currentRecord.setValue({ fieldId: 'custbody66', value: '' }); } } // if (fieldId === "undepfunds" || fieldId === "account") { // processDateDeposited(context); // } } catch (error) { console.log(error); log.error({ title: 'Error pageInit', details: error.message }); } return; } /* HELPER FUNCTIONS */ function processDateDeposited(context) { const currentRecord = context.currentRecord; const undepfunds = currentRecord.getValue({ fieldId: 'undepfunds' }); if (undepfunds === 'F') { const account = currentRecord.getValue({ fieldId: 'account' }); if (account !== '') { currentRecord.setValue({ fieldId: 'custbody_date_deposited', value: new Date() }); } } else { currentRecord.setValue({ fieldId: 'custbody_date_deposited', value: '' }); } } /** * Disable Fields with some Roles */ function disabledFeatureByRoles(context) { var account = document.querySelector('input[name="undepfunds"][value="F"]'); if (account) { var currentUser = runtime.getCurrentUser(); const role = currentUser.role; // 1036 Lexor| Sale // 1069 Lexor | Sales Director // 1037 Lexor | Sales Manager // set account and select account in customer deposit is disable and only these roles can change: // 3 Admin , // 1042 Lexor | A/P Clerk, // 1043 Lexor | A/R Clerk, // 1045 Lexor | Accountant, // 1087 Lexor | Accountant Manager const LIST_ROLES = [3, 1042, 1043, 1045, 1087]; if (!LIST_ROLES.includes(role)) { account.disabled = true; } } } /** * Export Events */ var exports = {}; exports.pageInit = pageInit; exports.fieldChanged = fieldChanged; return exports; });
true
/** * Customer Deposit Form Client Script * custform_248_4283482_820 * @NApiVersion 2.x * @NScriptType ClientScript * @author trungpv <PI:EMAIL:dycjh@example.comEND_PI> */ define(['N/runtime'], function(runtime) { /* === VARS === */ const LIST_PAYMENT_CARDS = ['6', '3', '4', '5']; /* === EVENTS FUNCTIONS === */ /** * Page Init * @param {*} context */ function pageInit(context) { const currentRecord = context.currentRecord; try { // processDateDeposited(context); disabledFeatureByRoles(context); currentRecord.setValue({ fieldId: 'payment', value: '' }); } catch (error) { console.log(error); log.error({ title: 'Error pageInit', details: error.message }); } return; } /** * Field Changed * @param {*} context */ function fieldChanged(context) { try { const currentRecord = context.currentRecord; const fieldId = context.fieldId; // If Payment Method contain LIST_PAYMENT_CARDS if (fieldId === 'paymentmethod') { // paymentmethod const paymentMethod = currentRecord.getValue({ fieldId: 'paymentmethod' }); if (paymentMethod && paymentMethod != '' && LIST_PAYMENT_CARDS.includes(paymentMethod)) { // custbody66 => DATE RECEIVED currentRecord.setValue({ fieldId: 'custbody66', value: new Date() }); // custbody65 => Checkbox PAYMENT RECEIVED currentRecord.setValue({ fieldId: 'custbody65', value: true }); } else { // custbody66 => DATE RECEIVED currentRecord.setValue({ fieldId: 'custbody66', value: '' }); // custbody65 => Checkbox PAYMENT RECEIVED currentRecord.setValue({ fieldId: 'custbody65', value: false }); } } // custbody65 => Checkbox PAYMENT RECEIVED if (fieldId === 'custbody65') { const paymentReceived = currentRecord.getValue({ fieldId: 'custbody65' }); if (!paymentReceived) { // custbody66 => DATE RECEIVED currentRecord.setValue({ fieldId: 'custbody66', value: '' }); } } // if (fieldId === "undepfunds" || fieldId === "account") { // processDateDeposited(context); // } } catch (error) { console.log(error); log.error({ title: 'Error pageInit', details: error.message }); } return; } /* HELPER FUNCTIONS */ function processDateDeposited(context) { const currentRecord = context.currentRecord; const undepfunds = currentRecord.getValue({ fieldId: 'undepfunds' }); if (undepfunds === 'F') { const account = currentRecord.getValue({ fieldId: 'account' }); if (account !== '') { currentRecord.setValue({ fieldId: 'custbody_date_deposited', value: new Date() }); } } else { currentRecord.setValue({ fieldId: 'custbody_date_deposited', value: '' }); } } /** * Disable Fields with some Roles */ function disabledFeatureByRoles(context) { var account = document.querySelector('input[name="undepfunds"][value="F"]'); if (account) { var currentUser = runtime.getCurrentUser(); const role = currentUser.role; // 1036 Lexor| Sale // 1069 Lexor | Sales Director // 1037 Lexor | Sales Manager // set account and select account in customer deposit is disable and only these roles can change: // 3 Admin , // 1042 Lexor | A/P Clerk, // 1043 Lexor | A/R Clerk, // 1045 Lexor | Accountant, // 1087 Lexor | Accountant Manager const LIST_ROLES = [3, 1042, 1043, 1045, 1087]; if (!LIST_ROLES.includes(role)) { account.disabled = true; } } } /** * Export Events */ var exports = {}; exports.pageInit = pageInit; exports.fieldChanged = fieldChanged; return exports; });
/** * @Author: Ankith Ravindran <ankithravindran> * @Date: 2021-09-15T17:03:03+10:00 * @Filename: mp_sl_product_ordering.js * @Last modified by: ankithravindran * @Last modified time: 2022-01-18T13:25:42+11:00 */ /** *@NApiVersion 2.0 *@NScriptType Suitelet */ define(['N/ui/serverWidget', 'N/email', 'N/runtime', 'N/search', 'N/record', 'N/http', 'N/log', 'N/redirect', 'N/format' ], function(ui, email, runtime, search, record, http, log, redirect, format) { var role = runtime.getCurrentUser().role; function onRequest(context) { var b4 = ''; var g500 = ''; var kg1 = ''; var kg3 = ''; var kg5 = ''; var g500_toll = ''; var kg1_toll = ''; var kg3_toll = ''; var kg5_toll = ''; var test = false; if (context.request.method === 'GET') { // Load jQuery var inlineHtml = '<script src="https://code.jquery.com/jquery-1.12.4.min.js" integrity="sha384-nvAa0+6Qg9clwYCGGPpDQLVpLNn0fRaROjHqs13t4Ggj3Ez50XnGQqc/r8MhnRDZ" crossorigin="anonymous"></script>'; // Load Tooltip inlineHtml += '<script src="https://unpkg.com/@popperjs/core@2"></script>'; // Load Bootstrap inlineHtml += '<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/3.4.1/css/bootstrap.min.css" integrity="sha384-HSMxcRTRxnN+Bdg0JdbxYKrThecOKuH5zCYotlSAcp1+c8xmyTe9GYg1l9a69psu" crossorigin="anonymous">'; inlineHtml += '<script src="https://stackpath.bootstrapcdn.com/bootstrap/3.4.1/js/bootstrap.min.js" integrity="sha384-aJ21OjlMXNL5UyIl/XNwTMqvzeRMZH2w8c5cRVpzpU8Y5bApTppSuUkhZXN0VxHd" crossorigin="anonymous"></script>'; // Load DataTables inlineHtml += '<link rel="stylesheet" type="text/css" href="//cdn.datatables.net/1.10.21/css/jquery.dataTables.min.css">'; inlineHtml += '<script type="text/javascript" charset="utf8" src="//cdn.datatables.net/1.10.21/js/jquery.dataTables.min.js"></script>'; // Load Bootstrap-Select inlineHtml += '<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap-select@1.13.14/dist/css/bootstrap-select.min.css">'; inlineHtml += '<script src="https://cdn.jsdelivr.net/npm/bootstrap-select@1.13.14/dist/js/bootstrap-select.min.js"></script>'; // Load Netsuite stylesheet and script inlineHtml += '<link rel="stylesheet" href="https://1048144.app.netsuite.com/core/media/media.nl?id=2060796&c=1048144&h=9ee6accfd476c9cae718&_xt=.css"/>'; inlineHtml += '<script src="https://1048144.app.netsuite.com/core/media/media.nl?id=2060797&c=1048144&h=ef2cda20731d146b5e98&_xt=.js"></script>'; inlineHtml += '<link type="text/css" rel="stylesheet" href="https://1048144.app.netsuite.com/core/media/media.nl?id=2090583&c=1048144&h=a0ef6ac4e28f91203dfe&_xt=.css">'; inlineHtml += '<style>.mandatory{color:red;}</style>'; var form = ui.createForm({ title: 'MPEX Product Ordering' }); if (!isNullorEmpty(context.request.parameters.zee) || role == 1000) { var zee; if (role == 1000) { zee = runtime.getCurrentUser().id; } else { zee = context.request.parameters.zee; } var zeeSearch = search.load({ id: 'customsearch_mpex_zee_order_search', type: 'customrecord_zee_mpex_order' }); zeeSearch.filters.push(search.createFilter({ name: 'custrecord_mpex_order_franchisee', operator: search.Operator.IS, values: zee })); var zeeResultSet = zeeSearch.run(); var activeOrder = 0; var b4 = ''; var g500 = ''; var kg1 = ''; var kg3 = ''; var kg5 = ''; var g500_toll = ''; var kg1_toll = ''; var kg3_toll = ''; var kg5_toll = ''; zeeResultSet.each(function(searchResult) { var connote = searchResult.getValue({ name: 'custrecord_mpex_order_connote' }); var status = searchResult.getValue({ name: 'custrecord_mpex_order_status' }); if (status == 1 && isNullorEmpty(connote)) { activeOrder = searchResult.getValue({ name: 'id' }); b4 = searchResult.getValue({ name: "custrecord_mpex_order_b4" }); g500 = searchResult.getValue({ name: "custrecord_mpex_order_500_satchel" }); kg1 = searchResult.getValue({ name: "custrecord_mpex_order_1kg_satchel" }); kg3 = searchResult.getValue({ name: "custrecord_mpex_order_3kg_satchel" }); kg5 = searchResult.getValue({ name: "custrecord_mpex_order_5kg_satchel" }); g500_toll = searchResult.getValue({ name: "custrecord_mpex_order_500_satchel_toll" }); kg1_toll = searchResult.getValue({ name: "custrecord_mpex_order_1kg_satchel_toll" }); kg3_toll = searchResult.getValue({ name: "custrecord_mpex_order_3kg_satchel_toll" }); kg5_toll = searchResult.getValue({ name: "custrecord_mpex_order_5kg_satchel_toll" }); test = true; return false; } return true; }); } //Instructions inlineHtml += instructionsBox(); if (role != 1000) { inlineHtml += franchiseeDropdownSection(context.request.parameters.zee); } //Heading inlineHtml += '<div class="form-group container product_order_section">'; inlineHtml += '<div class="row">'; inlineHtml += '<div class="col-xs-12 heading1"><h4><span style="background-color: #379E8F;" class="label label-default col-xs-12">MAILPLUS PRODUCTS</span></h4></div>'; inlineHtml += '</div>'; inlineHtml += '</div>'; inlineHtml += inputFields(b4, g500, kg1, kg3, kg5, test); //Heading inlineHtml += '<div class="form-group container toll_product_order_section">'; inlineHtml += '<div class="row">'; inlineHtml += '<div class="col-xs-12 heading1"><h4><span style="background-color: #379E8F;" class="label label-default col-xs-12">TOLL PRODUCTS</span></h4></div>'; inlineHtml += '</div>'; inlineHtml += '</div>'; inlineHtml += inputFieldsToll(g500_toll, kg1_toll, kg3_toll, kg5_toll, test); if (!isNullorEmpty(context.request.parameters.zee) && context.request .parameters.zee != 0) { form.addField({ id: 'custpage_zee_selected', type: ui.FieldType.TEXT, label: 'zee' }).updateDisplayType({ displayType: ui.FieldDisplayType.HIDDEN }).defaultValue = context.request.parameters.zee; } else { form.addField({ id: 'custpage_zee_selected', type: ui.FieldType.TEXT, label: 'zee' }).updateDisplayType({ displayType: ui.FieldDisplayType.HIDDEN }); } form.addField({ id: 'preview_table', type: ui.FieldType.INLINEHTML, label: 'preview_table' }).updateBreakType({ breakType: ui.FieldBreakType.STARTROW }).defaultValue = inlineHtml; form.addField({ id: 'results', type: ui.FieldType.TEXT, label: 'results' }).updateDisplayType({ displayType: ui.FieldDisplayType.HIDDEN }); form.addField({ id: 'custpage_b4', type: ui.FieldType.TEXT, label: 'b4' }).updateDisplayType({ displayType: ui.FieldDisplayType.HIDDEN }); form.addField({ id: 'custpage_g500', type: ui.FieldType.TEXT, label: 'g500' }).updateDisplayType({ displayType: ui.FieldDisplayType.HIDDEN }); form.addField({ id: 'custpage_kg1', type: ui.FieldType.TEXT, label: 'kg1' }).updateDisplayType({ displayType: ui.FieldDisplayType.HIDDEN }); form.addField({ id: 'custpage_kg3', type: ui.FieldType.TEXT, label: 'kg3' }).updateDisplayType({ displayType: ui.FieldDisplayType.HIDDEN }); form.addField({ id: 'custpage_kg5', type: ui.FieldType.TEXT, label: 'kg5' }).updateDisplayType({ displayType: ui.FieldDisplayType.HIDDEN }); form.addField({ id: 'custpage_g500_toll', type: ui.FieldType.TEXT, label: 'g500_toll' }).updateDisplayType({ displayType: ui.FieldDisplayType.HIDDEN }); form.addField({ id: 'custpage_kg1_toll', type: ui.FieldType.TEXT, label: 'kg1_toll' }).updateDisplayType({ displayType: ui.FieldDisplayType.HIDDEN }); form.addField({ id: 'custpage_kg3_toll', type: ui.FieldType.TEXT, label: 'kg3_toll' }).updateDisplayType({ displayType: ui.FieldDisplayType.HIDDEN }); form.addField({ id: 'custpage_kg5_toll', type: ui.FieldType.TEXT, label: 'kg5_toll' }).updateDisplayType({ displayType: ui.FieldDisplayType.HIDDEN }); form.addSubmitButton({ label: 'SUBMIT ORDER' }); form.clientScriptFileId = 4509791; //SB cl_id =4242817, PROD cl_id = 4509791 context.response.writePage(form); } else { var zee_id = context.request.parameters.custpage_zee_selected; var b4 = context.request.parameters.custpage_b4; var g500 = context.request.parameters.custpage_g500; var kg1 = context.request.parameters.custpage_kg1; var kg3 = context.request.parameters.custpage_kg3; var kg5 = context.request.parameters.custpage_kg5; // var g500_toll = context.request.parameters.custpage_g500_toll; var kg1_toll = context.request.parameters.custpage_kg1_toll; var kg3_toll = context.request.parameters.custpage_kg3_toll; var kg5_toll = context.request.parameters.custpage_kg5_toll; createCustomRecord(zee_id, b4, g500, kg1, kg3, kg5, kg1_toll, kg3_toll, kg5_toll); var form = ui.createForm({ title: 'MPEX Product Order Confirmation' }); // Load jQuery var inlineHtml2 = '<script src="https://code.jquery.com/jquery-1.12.4.min.js" integrity="sha384-nvAa0+6Qg9clwYCGGPpDQLVpLNn0fRaROjHqs13t4Ggj3Ez50XnGQqc/r8MhnRDZ" crossorigin="anonymous"></script>'; // Load Tooltip inlineHtml2 += '<script src="https://unpkg.com/@popperjs/core@2"></script>'; // Load Bootstrap inlineHtml2 += '<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/3.4.1/css/bootstrap.min.css" integrity="sha384-HSMxcRTRxnN+Bdg0JdbxYKrThecOKuH5zCYotlSAcp1+c8xmyTe9GYg1l9a69psu" crossorigin="anonymous">'; inlineHtml2 += '<script src="https://stackpath.bootstrapcdn.com/bootstrap/3.4.1/js/bootstrap.min.js" integrity="sha384-aJ21OjlMXNL5UyIl/XNwTMqvzeRMZH2w8c5cRVpzpU8Y5bApTppSuUkhZXN0VxHd" crossorigin="anonymous"></script>'; // Load DataTables inlineHtml2 += '<link rel="stylesheet" type="text/css" href="//cdn.datatables.net/1.10.21/css/jquery.dataTables.min.css">'; inlineHtml2 += '<script type="text/javascript" charset="utf8" src="//cdn.datatables.net/1.10.21/js/jquery.dataTables.min.js"></script>'; // Load Bootstrap-Select inlineHtml2 += '<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap-select@1.13.14/dist/css/bootstrap-select.min.css">'; inlineHtml2 += '<script src="https://cdn.jsdelivr.net/npm/bootstrap-select@1.13.14/dist/js/bootstrap-select.min.js"></script>'; // Load Netsuite stylesheet and script inlineHtml2 += '<link rel="stylesheet" href="https://1048144.app.netsuite.com/core/media/media.nl?id=2060796&c=1048144&h=9ee6accfd476c9cae718&_xt=.css"/>'; inlineHtml2 += '<script src="https://1048144.app.netsuite.com/core/media/media.nl?id=2060797&c=1048144&h=ef2cda20731d146b5e98&_xt=.js"></script>'; inlineHtml2 += '<link type="text/css" rel="stylesheet" href="https://1048144.app.netsuite.com/core/media/media.nl?id=2090583&c=1048144&h=a0ef6ac4e28f91203dfe&_xt=.css">'; inlineHtml2 += '<style>.mandatory{color:red;}</style>'; inlineHtml2 += dataTable(); // The HTML code for the table is inserted with JQuery in the pageInit function of the mp_cl_product_ordering_page script. var zee_id = ''; if (role != 1000) { zee_id = context.request.parameters.custpage_zee_selected; log.debug({ title: 'zee', details: zee_id }); } else { zee_id = runtime.getCurrentUser().id; } form.addField({ id: 'custpage_zee_selected', type: ui.FieldType.TEXT, label: 'zee' }).updateDisplayType({ displayType: ui.FieldDisplayType.HIDDEN }).defaultValue = zee_id; form.addField({ id: 'results', type: ui.FieldType.TEXT, label: 'results' }).updateDisplayType({ displayType: ui.FieldDisplayType.HIDDEN }).defaultValue = true; form.addField({ id: 'preview_table', type: ui.FieldType.INLINEHTML, label: 'preview_table' }).updateBreakType({ breakType: ui.FieldBreakType.STARTROW }).defaultValue = inlineHtml2; form.addButton({ id: 'submit', label: 'CHANGE ORDER', functionName: 'onclick_submit()' }); form.clientScriptFileId = 4509791; //SB cl_id =4242817, PROD cl_id = 4509791 context.response.writePage(form); } } function createCustomRecord(zee_id, b4, g500, kg1, kg3, kg5, kg1_toll, kg3_toll, kg5_toll) { var activeOrder = checkConnote(zee_id); //Load active order if it exists if (activeOrder != 0) { var mpexOrderRec = record.load({ type: 'customrecord_zee_mpex_order', id: activeOrder }); var date = new Date(); date.setDate(date.getDate() + 1); mpexOrderRec.setValue({ fieldId: 'custrecord_mpex_order_b4', value: b4 }); mpexOrderRec.setValue({ fieldId: 'custrecord_mpex_order_500_satchel', value: g500 }); mpexOrderRec.setValue({ fieldId: 'custrecord_mpex_order_1kg_satchel', value: kg1 }); mpexOrderRec.setValue({ fieldId: 'custrecord_mpex_order_3kg_satchel', value: kg3 }); mpexOrderRec.setValue({ fieldId: 'custrecord_mpex_order_5kg_satchel', value: kg5 }); // mpexOrderRec.setValue({ // fieldId: 'custrecord_mpex_order_500_satchel_toll', // value: g500_toll // }); mpexOrderRec.setValue({ fieldId: 'custrecord_mpex_order_1kg_satchel_toll', value: kg1_toll }); mpexOrderRec.setValue({ fieldId: 'custrecord_mpex_order_3kg_satchel_toll', value: kg3_toll }); mpexOrderRec.setValue({ fieldId: 'custrecord_mpex_order_5kg_satchel_toll', value: kg5_toll }); mpexOrderRec.setValue({ fieldId: 'custrecord_mpex_order_total', value: b4 + g500 + kg1 + kg3 + kg5 + kg1_toll + kg3_toll + kg5_toll }); //mpexOrderRec.setValue({fieldId: 'custrecord_mpex_order_date', value: date}); mpexOrderRec.save({ enableSourcing: true, ignoreMandatoryFields: true }); } else { var zeeSearch = search.load({ id: 'customsearch_zee_mpex_product_order', type: search.Type.PARTNER }); zeeSearch.filters.push(search.createFilter({ name: 'internalid', operator: search.Operator.IS, values: zee_id })); var zeeResultSet = zeeSearch.run(); var tollAcctNum; var dxAddr; var dxExch; var state; var zip; zeeResultSet.each(function(searchResult) { tollAcctNum = searchResult.getValue( 'custentity_toll_acc_number'); dxAddr = searchResult.getValue({ name: "custrecord_ap_lodgement_addr2", join: "CUSTENTITY__TOLL_PICKUP_DX_NO", label: "Address 2" }); dxExch = searchResult.getValue({ name: "custrecord_ap_lodgement_suburb", join: "CUSTENTITY__TOLL_PICKUP_DX_NO", label: "Suburb" }); state = searchResult.getText({ name: "custrecord_ap_lodgement_site_state", join: "CUSTENTITY__TOLL_PICKUP_DX_NO", label: "State" }); zip = searchResult.getValue({ name: "custrecord_ap_lodgement_postcode", join: "CUSTENTITY__TOLL_PICKUP_DX_NO", label: "Post Code" }); }); var mpexOrderRec = record.create({ type: 'customrecord_zee_mpex_order', isDynamic: true, }); var date = new Date(); date.setDate(date.getDate() + 1); //date.toLocaleString('en-AU', 'Australia/Sydney'); //1 = ACTIVE, 2 = PROCESSING, 3 = COMPLETED (if connote) mpexOrderRec.setValue({ fieldId: 'custrecord_mpex_order_status', value: 1 }); mpexOrderRec.setValue({ fieldId: 'custrecord_mpex_order_franchisee', value: zee_id }); mpexOrderRec.setValue({ fieldId: 'custrecord_mpex_order_b4', value: b4 }); mpexOrderRec.setValue({ fieldId: 'custrecord_mpex_order_500_satchel', value: g500 }); mpexOrderRec.setValue({ fieldId: 'custrecord_mpex_order_1kg_satchel', value: kg1 }); mpexOrderRec.setValue({ fieldId: 'custrecord_mpex_order_3kg_satchel', value: kg3 }); mpexOrderRec.setValue({ fieldId: 'custrecord_mpex_order_5kg_satchel', value: kg5 }); // mpexOrderRec.setValue({ // fieldId: 'custrecord_mpex_order_500_satchel_toll', // value: g500_toll // }); mpexOrderRec.setValue({ fieldId: 'custrecord_mpex_order_1kg_satchel_toll', value: kg1_toll }); mpexOrderRec.setValue({ fieldId: 'custrecord_mpex_order_3kg_satchel_toll', value: kg3_toll }); mpexOrderRec.setValue({ fieldId: 'custrecord_mpex_order_5kg_satchel_toll', value: kg5_toll }); mpexOrderRec.setValue({ fieldId: 'custrecord_mpex_order_total', value: b4 + g500 + kg1 + kg3 + kg5 + kg1_toll + kg3_toll + kg5_toll }); //mpexOrderRec.setValue({fieldId: 'custrecord_mpex_order_date', value: date }); mpexOrderRec.setValue({ fieldId: 'custrecord_mpex_order_mp_id', value: zee_id }); mpexOrderRec.setValue({ fieldId: 'custrecord_mpex_order_toll_acc_num', value: tollAcctNum }); mpexOrderRec.setValue({ fieldId: 'custrecord_mpex_order_dx_addr', value: dxAddr }); mpexOrderRec.setValue({ fieldId: 'custrecord_mpex_order_dx_exch', value: dxExch }); mpexOrderRec.setValue({ fieldId: 'custrecord_mpex_order_state', value: state }); mpexOrderRec.setValue({ fieldId: 'custrecord_mpex_order_postcode', value: zip }); mpexOrderRec.save({ enableSourcing: true, ignoreMandatoryFields: true }); } } function checkConnote(zee) { var zeeSearch = search.load({ id: 'customsearch_mpex_zee_order_search', type: 'customrecord_zee_mpex_order' }); zeeSearch.filters.push(search.createFilter({ name: 'custrecord_mpex_order_franchisee', operator: search.Operator.IS, values: zee })); var zeeResultSet = zeeSearch.run(); var activeOrder = 0; zeeResultSet.each(function(searchResult) { var connote = searchResult.getValue({ name: 'custrecord_mpex_order_connote' }); var status = searchResult.getValue({ name: 'custrecord_mpex_order_status' }); if (status == 1 && isNullorEmpty(connote)) { log.debug({ title: 'INSIDE CONNOTEEE', details: 'INSIDE CONNOTEEE' }); activeOrder = searchResult.getValue({ name: 'id' }); return false; } return true; }); return activeOrder; } function instructionsBox() { var inlineQty = '<br></br>'; //Important Instructions box inlineQty += '<div></div>'; inlineQty += '<div class="form-group container test_section">'; inlineQty += '<div style=\"background-color: #CFE0CE !important;border: 1px solid #379E8F;padding: 20px 30px 30px 30px\">'; inlineQty += 'Complete this form to reorder packs of MPEX product stock for MailPlus Products (manual use with pre-printed labels) or TOLL Products, which require the customer to apply a TOLL Common label to shipβ€”interested in biodegradable satchels? You can also direct customers to save up to 36% with our new biodegradable option with BetterPackaging. Find out more here: <a href=\"https://mailplus.com.au/discounted-biodegradable-satchels/\">Biodegradable Satchels</a>. Note the "<b>Dirt bags</b>" must be purchased separately.'; inlineQty += "<br></br><b><u>Form Instructions:</u></b>" inlineQty += '</br><b>Entering Quantities: </b>' inlineQty += '<ul><li>You may only enter numbers into the relevant fields. Entering text will result in an input error, and you will need to re-enter the quantity using numbers only.</li>'; inlineQty += '<li>You may also use the up and down arrows on the far right-hand side of each field to set the number of packs you require</li>'; inlineQty += '<li>You are not required to fill out every box if you don\'t require every product.</li>'; inlineQty += '</ul>'; inlineQty += '</br><b>Product Types and Packs</b>' inlineQty += '<ul><b><u>MailPlus Product</u></b>: All Mailplus products come in a 10-pack. Please enter the number of 10-packs you require for each product type. The minimum number you can order is 10 x 10-pack = 100 items.'; inlineQty += '<b><u>TOLL Product</u></b>: All TOLL products come in a 5-pack. Please enter the number of 5-packs you require for each product type. The minimum number you can order is 10 x 5-pack = 50 items. '; inlineQty += '<p style="color: red;"><b><u>Please note</u></b>: The 500g satchel for TOLL Products is discontinued. Customers can use other product stock to ship a <500g item by applying the 500g TOLL COMMON Label through the MailPlus portal to a different product type like a 1kg satchel. The current 500g rate will apply, provided the item is less than 500g and the 500g rate was selected.</p>'; inlineQty += '</ul>' inlineQty += '</br><b>Placing the Order</b>' inlineQty += '<ul>' inlineQty += '<li><b><u>SUBMIT</u></b>: Press the "SUBMIT Order" button at the top of the screen to submit your order and continue to the confirmation page.</li>' inlineQty += '</ul></div></div><br/>'; return inlineQty; } function inputFields(b4, g500, kg1, kg3, kg5, test) { //Add Break //var inlineQty = '<div class="form-group container break_section"><div class="row"></div></div>' //500g AND B4 Options var inlineQty = '<div class="form-group container g500_section">'; inlineQty += '<div class="row">'; if (test) { inlineQty += '<div class="col-xs-6 g500_env"><div class="input-group"><span class="input-group-addon" id="500g">500G SATCHEL (PACKS OF 10) </span><input id="500g_text" type="number" min="0" step="10" class="form-control 500g" value="' + g500 + '"/></div></div>'; inlineQty += '<div class="col-xs-6 b4_env"><div class="input-group"><span class="input-group-addon" id="b4">B4 ENVELOPE (PACKS OF 10) </span><input id="b4_text" type="number" min="0" step="10" class="form-control b4" value="' + b4 + '"/></div></div>'; } else { inlineQty += '<div class="col-xs-6 g500_env"><div class="input-group"><span class="input-group-addon" id="500g">500G SATCHEL (PACKS OF 10) </span><input id="500g_text" type="number" min="0" step="10" class="form-control 500g" placeholder="Enter quantity" value="' + g500 + '"/></div></div>'; inlineQty += '<div class="col-xs-6 b4_env"><div class="input-group"><span class="input-group-addon" id="b4">B4 ENVELOPE (PACKS OF 10) </span><input id="b4_text" type="number" min="0" step="10" class="form-control b4" placeholder="Enter quantity" value="' + b4 + '"/></div></div>'; } inlineQty += '</div>'; inlineQty += '</div>'; //1KG inlineQty += '<div class="form-group container b4_section">'; inlineQty += '<div class="row">'; if (test) { inlineQty += '<div class="col-xs-6 kg1_env"><div class="input-group"><span class="input-group-addon" id="1kg">1KG SATCHEL (PACKS OF 10) </span><input id="1kg_text" type="number" min="0" step="10" class="form-control 1kg" value="' + kg1 + '"/></div></div>'; } else { inlineQty += '<div class="col-xs-6 kg1_env"><div class="input-group"><span class="input-group-addon" id="1kg">1KG SATCHEL (PACKS OF 10) </span><input id="1kg_text" type="number" min="0" step="10" class="form-control 1kg" placeholder="Enter quantity"value="' + kg1 + '"/></div></div>'; } inlineQty += '</div>'; inlineQty += '</div>'; //3KG options inlineQty += '<div class="form-group container c5_section">'; inlineQty += '<div class="row">'; if (test) { inlineQty += '<div class="col-xs-6 kg3_env"><div class="input-group"><span class="input-group-addon" id="3kg">3KG SATCHEL (PACKS OF 10)</span><input id="3kg_text" type="number" min="0" step="10" class="form-control 3kg" value="' + kg3 + '"/></div></div>'; } else { inlineQty += '<div class="col-xs-6 kg3_env"><div class="input-group"><span class="input-group-addon" id="3kg">3KG SATCHEL (PACKS OF 10)</span><input id="3kg_text" type="number" min="0" step="10" class="form-control 3kg" placeholder="Enter quantity" value="' + kg3 + '"/></div></div>'; } inlineQty += '</div>'; inlineQty += '</div>'; //5KG options inlineQty += '<div class="form-group container c5_section">'; inlineQty += '<div class="row">'; if (test) { inlineQty += '<div class="col-xs-6 kg5_env"><div class="input-group"><span class="input-group-addon" id="5kg">5KG SATCHEL (PACKS OF 10) </span><input id="5kg_text" type="number" min="0" step="10" class="form-control 5kg" value="' + kg5 + '"/></div></div>'; } else { inlineQty += '<div class="col-xs-6 kg5_env"><div class="input-group"><span class="input-group-addon" id="5kg">5KG SATCHEL (PACKS OF 10) </span><input id="5kg_text" type="number" min="0" step="10" class="form-control 5kg" placeholder="Enter quantity" value="' + kg5 + '"/></div></div>'; } inlineQty += '</div>'; inlineQty += '</div>'; return inlineQty; } function inputFieldsToll(g500, kg1, kg3, kg5, test) { //Add Break //var inlineQty = '<div class="form-group container break_section"><div class="row"></div></div>' //500g AND 5KG Options var inlineQty = '<div class="form-group container g500_section_toll">'; inlineQty += '<div class="row">'; if (test) { inlineQty += '<div class="col-xs-6 kg1_env_toll"><div class="input-group"><span class="input-group-addon" id="1kg">1KG SATCHEL </span><input id="1kg_text_toll" type="number" min="0" step="5" class="form-control 1kg" value="' + kg1 + '"/></div></div>'; inlineQty += '<div class="col-xs-6 g500_env_toll"><div class="input-group"><span class="input-group-addon" id="500g">500G SATCHEL </span><input id="500g_text_toll" type="text" class="form-control " value="DISCONTINUED" readonly/></div></div>'; } else { inlineQty += '<div class="col-xs-6 kg1_env_toll"><div class="input-group"><span class="input-group-addon" id="1kg">1KG SATCHEL </span><input id="1kg_text_toll" type="number" min="0" step="5" class="form-control 1kg" placeholder="Enter quantity"value="' + kg1 + '"/></div></div>'; inlineQty += '<div class="col-xs-6 g500_env_toll"><div class="input-group"><span class="input-group-addon" id="500g">500G SATCHEL </span><input id="500g_text_toll" type="text" class="form-control " value="DISCONTINUED" readonly/></div></div>'; } inlineQty += '</div>'; inlineQty += '</div>'; //1KG and B4 options inlineQty += '<div class="form-group container b4_section_toll">'; inlineQty += '<div class="row">'; if (test) { inlineQty += '<div class="col-xs-6 kg3_env_toll"><div class="input-group"><span class="input-group-addon" id="3kg">3KG SATCHEL</span><input id="3kg_text_toll" type="number" min="0" step="5" class="form-control 3kg" value="' + kg3 + '"/></div></div>'; } else { inlineQty += '<div class="col-xs-6 kg3_env_toll"><div class="input-group"><span class="input-group-addon" id="3kg">3KG SATCHEL</span><input id="3kg_text_toll" type="number" min="0" step="5" class="form-control 3kg" placeholder="Enter quantity" value="' + kg3 + '"/></div></div>'; } inlineQty += '</div>'; inlineQty += '</div>'; //1KG and B4 options inlineQty += '<div class="form-group container b4_section_toll">'; inlineQty += '<div class="row">'; if (test) { inlineQty += '<div class="col-xs-6 kg5_env_toll"><div class="input-group"><span class="input-group-addon" id="5kg">5KG SATCHEL </span><input id="5kg_text_toll" type="number" min="0" step="5" class="form-control 5kg" value="' + kg5 + '"/></div></div>'; } else { inlineQty += '<div class="col-xs-6 kg5_env_toll"><div class="input-group"><span class="input-group-addon" id="5kg">5KG SATCHEL </span><input id="5kg_text_toll" type="number" min="0" step="5" class="form-control 5kg" placeholder="Enter quantity" value="' + kg5 + '"/></div></div>'; } inlineQty += '</div>'; inlineQty += '</div>'; return inlineQty; } /** * The table that will display the differents invoices linked to the franchisee and the time period. * @return {String} inlineQty */ function dataTable() { var inlineQty = '<br></br><style>table#mpex_orders {font-size: 12px;text-align: center;border: none;}.dataTables_wrapper {font-size: 14px;}table#mpex_orders th{text-align: center;} .bolded{font-weight: bold;}</style>'; inlineQty += '<table id="mpex_orders" class="table table-responsive table-striped customer tablesorter" style="width: 100%;">'; inlineQty += '<thead style="color: white;background-color: #379E8F;">'; inlineQty += '<tr class="text-center">'; inlineQty += '</tr>'; inlineQty += '</thead>'; inlineQty += '<tbody id="result_import" class="result-import"></tbody>'; inlineQty += '</table>'; return inlineQty; } function formatDate(testDate) { //console.log('testDate: '+testDate); var responseDate = format.format({ value: testDate, type: format.Type.DATE }); //console.log('responseDate: '+responseDate); return responseDate; } /** * The Franchisee dropdown list. * @param {Number} zee_id * @return {String} `inlineQty` */ function franchiseeDropdownSection(params_zee) { var inlineQty = '<div class="form-group container zee_dropdown_section >'; inlineQty += '<div class="row">'; // Franchisee dropdown field inlineQty += '<div class="col-xs-18 zee_dropdown_div">'; inlineQty += '<div class="input-group">'; inlineQty += '<span class="input-group-addon" id="zee_dropdown_text">FRANCHISEE</span>'; inlineQty += '<select id="zee_dropdown" class="form-control zee_dropdown" required>'; inlineQty += '<option></option>'; // Load the franchisees options var zeesSearch = search.load({ id: 'customsearch_job_inv_process_zee', type: search.Type.PARTNER }); var zeesSearchResults = zeesSearch.run(); zeesSearchResults.each(function(zeesSearchResult) { var opt_zee_id = zeesSearchResult.getValue('internalid'); var opt_zee_name = zeesSearchResult.getValue('companyname'); var selected_option = ''; if (role == 1000) { zee_id = runtime.getCurrentUser().id; //Get Franchisee ID-- REMOVE TO TEST selected_option = (opt_zee_id == zee_id) ? 'selected' : ''; } if (!isNullorEmpty(params_zee)) { selected_option = (params_zee == opt_zee_id) ? 'selected' : ''; } inlineQty += '<option value="' + opt_zee_id + '" ' + selected_option + '>' + opt_zee_name + '</option>'; return true; }); inlineQty += '</select>'; inlineQty += '</div></div></div></div>'; return inlineQty; } function isNullorEmpty(strVal) { return (strVal == null || strVal == '' || strVal == 'null' || strVal == undefined || strVal == 'undefined' || strVal == '- None -'); } return { onRequest: onRequest }; } );
837
[{"tag": "KEY", "value": "sha384-nvAa0+6Qg9clwYCGGPpDQLVpLNn0fRaROjHqs13t4Ggj3Ez50XnGQqc/r8MhnRDZ", "start": 969, "end": 1040}, {"tag": "KEY", "value": "sha384-nvAa0+6Qg9clwYCGGPpDQLVpLNn0fRaROjHqs13t4Ggj3Ez50XnGQqc/r8MhnRDZ", "start": 11028, "end": 11099}, {"tag": "KEY", "value": "sha384-aJ21OjlMXNL5UyIl/XNwTMqvzeRMZH2w8c5cRVpzpU8Y5bApTppSuUkhZXN0VxHd", "start": 1599, "end": 1670}, {"tag": "KEY", "value": "sha384-aJ21OjlMXNL5UyIl/XNwTMqvzeRMZH2w8c5cRVpzpU8Y5bApTppSuUkhZXN0VxHd", "start": 11661, "end": 11732}, {"tag": "KEY", "value": "sha384-HSMxcRTRxnN+Bdg0JdbxYKrThecOKuH5zCYotlSAcp1+c8xmyTe9GYg1l9a69psu", "start": 1370, "end": 1441}, {"tag": "KEY", "value": "sha384-HSMxcRTRxnN+Bdg0JdbxYKrThecOKuH5zCYotlSAcp1+c8xmyTe9GYg1l9a69psu", "start": 11431, "end": 11502}]
true
6
/** * @Author: Ankith Ravindran <ankithravindran> * @Date: 2021-09-15T17:03:03+10:00 * @Filename: mp_sl_product_ordering.js * @Last modified by: ankithravindran * @Last modified time: 2022-01-18T13:25:42+11:00 */ /** *@NApiVersion 2.0 *@NScriptType Suitelet */ define(['N/ui/serverWidget', 'N/email', 'N/runtime', 'N/search', 'N/record', 'N/http', 'N/log', 'N/redirect', 'N/format' ], function(ui, email, runtime, search, record, http, log, redirect, format) { var role = runtime.getCurrentUser().role; function onRequest(context) { var b4 = ''; var g500 = ''; var kg1 = ''; var kg3 = ''; var kg5 = ''; var g500_toll = ''; var kg1_toll = ''; var kg3_toll = ''; var kg5_toll = ''; var test = false; if (context.request.method === 'GET') { // Load jQuery var inlineHtml = '<script src="https://code.jquery.com/jquery-1.12.4.min.js" integrity="9q3vfhm7l33rus21toc8fndupq76itje" crossorigin="anonymous"></script>'; // Load Tooltip inlineHtml += '<script src="https://unpkg.com/@popperjs/core@2"></script>'; // Load Bootstrap inlineHtml += '<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/3.4.1/css/bootstrap.min.css" integrity="9jnerlff23u8ed01np9g6ysbhsh0dvcs" crossorigin="anonymous">'; inlineHtml += '<script src="https://stackpath.bootstrapcdn.com/bootstrap/3.4.1/js/bootstrap.min.js" integrity="vqbpgud2ghvjgm1n5hdgjnn5818fzsf2" crossorigin="anonymous"></script>'; // Load DataTables inlineHtml += '<link rel="stylesheet" type="text/css" href="//cdn.datatables.net/1.10.21/css/jquery.dataTables.min.css">'; inlineHtml += '<script type="text/javascript" charset="utf8" src="//cdn.datatables.net/1.10.21/js/jquery.dataTables.min.js"></script>'; // Load Bootstrap-Select inlineHtml += '<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap-select@1.13.14/dist/css/bootstrap-select.min.css">'; inlineHtml += '<script src="https://cdn.jsdelivr.net/npm/bootstrap-select@1.13.14/dist/js/bootstrap-select.min.js"></script>'; // Load Netsuite stylesheet and script inlineHtml += '<link rel="stylesheet" href="https://1048144.app.netsuite.com/core/media/media.nl?id=2060796&c=1048144&h=9ee6accfd476c9cae718&_xt=.css"/>'; inlineHtml += '<script src="https://1048144.app.netsuite.com/core/media/media.nl?id=2060797&c=1048144&h=ef2cda20731d146b5e98&_xt=.js"></script>'; inlineHtml += '<link type="text/css" rel="stylesheet" href="https://1048144.app.netsuite.com/core/media/media.nl?id=2090583&c=1048144&h=a0ef6ac4e28f91203dfe&_xt=.css">'; inlineHtml += '<style>.mandatory{color:red;}</style>'; var form = ui.createForm({ title: 'MPEX Product Ordering' }); if (!isNullorEmpty(context.request.parameters.zee) || role == 1000) { var zee; if (role == 1000) { zee = runtime.getCurrentUser().id; } else { zee = context.request.parameters.zee; } var zeeSearch = search.load({ id: 'customsearch_mpex_zee_order_search', type: 'customrecord_zee_mpex_order' }); zeeSearch.filters.push(search.createFilter({ name: 'custrecord_mpex_order_franchisee', operator: search.Operator.IS, values: zee })); var zeeResultSet = zeeSearch.run(); var activeOrder = 0; var b4 = ''; var g500 = ''; var kg1 = ''; var kg3 = ''; var kg5 = ''; var g500_toll = ''; var kg1_toll = ''; var kg3_toll = ''; var kg5_toll = ''; zeeResultSet.each(function(searchResult) { var connote = searchResult.getValue({ name: 'custrecord_mpex_order_connote' }); var status = searchResult.getValue({ name: 'custrecord_mpex_order_status' }); if (status == 1 && isNullorEmpty(connote)) { activeOrder = searchResult.getValue({ name: 'id' }); b4 = searchResult.getValue({ name: "custrecord_mpex_order_b4" }); g500 = searchResult.getValue({ name: "custrecord_mpex_order_500_satchel" }); kg1 = searchResult.getValue({ name: "custrecord_mpex_order_1kg_satchel" }); kg3 = searchResult.getValue({ name: "custrecord_mpex_order_3kg_satchel" }); kg5 = searchResult.getValue({ name: "custrecord_mpex_order_5kg_satchel" }); g500_toll = searchResult.getValue({ name: "custrecord_mpex_order_500_satchel_toll" }); kg1_toll = searchResult.getValue({ name: "custrecord_mpex_order_1kg_satchel_toll" }); kg3_toll = searchResult.getValue({ name: "custrecord_mpex_order_3kg_satchel_toll" }); kg5_toll = searchResult.getValue({ name: "custrecord_mpex_order_5kg_satchel_toll" }); test = true; return false; } return true; }); } //Instructions inlineHtml += instructionsBox(); if (role != 1000) { inlineHtml += franchiseeDropdownSection(context.request.parameters.zee); } //Heading inlineHtml += '<div class="form-group container product_order_section">'; inlineHtml += '<div class="row">'; inlineHtml += '<div class="col-xs-12 heading1"><h4><span style="background-color: #379E8F;" class="label label-default col-xs-12">MAILPLUS PRODUCTS</span></h4></div>'; inlineHtml += '</div>'; inlineHtml += '</div>'; inlineHtml += inputFields(b4, g500, kg1, kg3, kg5, test); //Heading inlineHtml += '<div class="form-group container toll_product_order_section">'; inlineHtml += '<div class="row">'; inlineHtml += '<div class="col-xs-12 heading1"><h4><span style="background-color: #379E8F;" class="label label-default col-xs-12">TOLL PRODUCTS</span></h4></div>'; inlineHtml += '</div>'; inlineHtml += '</div>'; inlineHtml += inputFieldsToll(g500_toll, kg1_toll, kg3_toll, kg5_toll, test); if (!isNullorEmpty(context.request.parameters.zee) && context.request .parameters.zee != 0) { form.addField({ id: 'custpage_zee_selected', type: ui.FieldType.TEXT, label: 'zee' }).updateDisplayType({ displayType: ui.FieldDisplayType.HIDDEN }).defaultValue = context.request.parameters.zee; } else { form.addField({ id: 'custpage_zee_selected', type: ui.FieldType.TEXT, label: 'zee' }).updateDisplayType({ displayType: ui.FieldDisplayType.HIDDEN }); } form.addField({ id: 'preview_table', type: ui.FieldType.INLINEHTML, label: 'preview_table' }).updateBreakType({ breakType: ui.FieldBreakType.STARTROW }).defaultValue = inlineHtml; form.addField({ id: 'results', type: ui.FieldType.TEXT, label: 'results' }).updateDisplayType({ displayType: ui.FieldDisplayType.HIDDEN }); form.addField({ id: 'custpage_b4', type: ui.FieldType.TEXT, label: 'b4' }).updateDisplayType({ displayType: ui.FieldDisplayType.HIDDEN }); form.addField({ id: 'custpage_g500', type: ui.FieldType.TEXT, label: 'g500' }).updateDisplayType({ displayType: ui.FieldDisplayType.HIDDEN }); form.addField({ id: 'custpage_kg1', type: ui.FieldType.TEXT, label: 'kg1' }).updateDisplayType({ displayType: ui.FieldDisplayType.HIDDEN }); form.addField({ id: 'custpage_kg3', type: ui.FieldType.TEXT, label: 'kg3' }).updateDisplayType({ displayType: ui.FieldDisplayType.HIDDEN }); form.addField({ id: 'custpage_kg5', type: ui.FieldType.TEXT, label: 'kg5' }).updateDisplayType({ displayType: ui.FieldDisplayType.HIDDEN }); form.addField({ id: 'custpage_g500_toll', type: ui.FieldType.TEXT, label: 'g500_toll' }).updateDisplayType({ displayType: ui.FieldDisplayType.HIDDEN }); form.addField({ id: 'custpage_kg1_toll', type: ui.FieldType.TEXT, label: 'kg1_toll' }).updateDisplayType({ displayType: ui.FieldDisplayType.HIDDEN }); form.addField({ id: 'custpage_kg3_toll', type: ui.FieldType.TEXT, label: 'kg3_toll' }).updateDisplayType({ displayType: ui.FieldDisplayType.HIDDEN }); form.addField({ id: 'custpage_kg5_toll', type: ui.FieldType.TEXT, label: 'kg5_toll' }).updateDisplayType({ displayType: ui.FieldDisplayType.HIDDEN }); form.addSubmitButton({ label: 'SUBMIT ORDER' }); form.clientScriptFileId = 4509791; //SB cl_id =4242817, PROD cl_id = 4509791 context.response.writePage(form); } else { var zee_id = context.request.parameters.custpage_zee_selected; var b4 = context.request.parameters.custpage_b4; var g500 = context.request.parameters.custpage_g500; var kg1 = context.request.parameters.custpage_kg1; var kg3 = context.request.parameters.custpage_kg3; var kg5 = context.request.parameters.custpage_kg5; // var g500_toll = context.request.parameters.custpage_g500_toll; var kg1_toll = context.request.parameters.custpage_kg1_toll; var kg3_toll = context.request.parameters.custpage_kg3_toll; var kg5_toll = context.request.parameters.custpage_kg5_toll; createCustomRecord(zee_id, b4, g500, kg1, kg3, kg5, kg1_toll, kg3_toll, kg5_toll); var form = ui.createForm({ title: 'MPEX Product Order Confirmation' }); // Load jQuery var inlineHtml2 = '<script src="https://code.jquery.com/jquery-1.12.4.min.js" integrity="9q3vfhm7l33rus21toc8fndupq76itje" crossorigin="anonymous"></script>'; // Load Tooltip inlineHtml2 += '<script src="https://unpkg.com/@popperjs/core@2"></script>'; // Load Bootstrap inlineHtml2 += '<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/3.4.1/css/bootstrap.min.css" integrity="9jnerlff23u8ed01np9g6ysbhsh0dvcs" crossorigin="anonymous">'; inlineHtml2 += '<script src="https://stackpath.bootstrapcdn.com/bootstrap/3.4.1/js/bootstrap.min.js" integrity="vqbpgud2ghvjgm1n5hdgjnn5818fzsf2" crossorigin="anonymous"></script>'; // Load DataTables inlineHtml2 += '<link rel="stylesheet" type="text/css" href="//cdn.datatables.net/1.10.21/css/jquery.dataTables.min.css">'; inlineHtml2 += '<script type="text/javascript" charset="utf8" src="//cdn.datatables.net/1.10.21/js/jquery.dataTables.min.js"></script>'; // Load Bootstrap-Select inlineHtml2 += '<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap-select@1.13.14/dist/css/bootstrap-select.min.css">'; inlineHtml2 += '<script src="https://cdn.jsdelivr.net/npm/bootstrap-select@1.13.14/dist/js/bootstrap-select.min.js"></script>'; // Load Netsuite stylesheet and script inlineHtml2 += '<link rel="stylesheet" href="https://1048144.app.netsuite.com/core/media/media.nl?id=2060796&c=1048144&h=9ee6accfd476c9cae718&_xt=.css"/>'; inlineHtml2 += '<script src="https://1048144.app.netsuite.com/core/media/media.nl?id=2060797&c=1048144&h=ef2cda20731d146b5e98&_xt=.js"></script>'; inlineHtml2 += '<link type="text/css" rel="stylesheet" href="https://1048144.app.netsuite.com/core/media/media.nl?id=2090583&c=1048144&h=a0ef6ac4e28f91203dfe&_xt=.css">'; inlineHtml2 += '<style>.mandatory{color:red;}</style>'; inlineHtml2 += dataTable(); // The HTML code for the table is inserted with JQuery in the pageInit function of the mp_cl_product_ordering_page script. var zee_id = ''; if (role != 1000) { zee_id = context.request.parameters.custpage_zee_selected; log.debug({ title: 'zee', details: zee_id }); } else { zee_id = runtime.getCurrentUser().id; } form.addField({ id: 'custpage_zee_selected', type: ui.FieldType.TEXT, label: 'zee' }).updateDisplayType({ displayType: ui.FieldDisplayType.HIDDEN }).defaultValue = zee_id; form.addField({ id: 'results', type: ui.FieldType.TEXT, label: 'results' }).updateDisplayType({ displayType: ui.FieldDisplayType.HIDDEN }).defaultValue = true; form.addField({ id: 'preview_table', type: ui.FieldType.INLINEHTML, label: 'preview_table' }).updateBreakType({ breakType: ui.FieldBreakType.STARTROW }).defaultValue = inlineHtml2; form.addButton({ id: 'submit', label: 'CHANGE ORDER', functionName: 'onclick_submit()' }); form.clientScriptFileId = 4509791; //SB cl_id =4242817, PROD cl_id = 4509791 context.response.writePage(form); } } function createCustomRecord(zee_id, b4, g500, kg1, kg3, kg5, kg1_toll, kg3_toll, kg5_toll) { var activeOrder = checkConnote(zee_id); //Load active order if it exists if (activeOrder != 0) { var mpexOrderRec = record.load({ type: 'customrecord_zee_mpex_order', id: activeOrder }); var date = new Date(); date.setDate(date.getDate() + 1); mpexOrderRec.setValue({ fieldId: 'custrecord_mpex_order_b4', value: b4 }); mpexOrderRec.setValue({ fieldId: 'custrecord_mpex_order_500_satchel', value: g500 }); mpexOrderRec.setValue({ fieldId: 'custrecord_mpex_order_1kg_satchel', value: kg1 }); mpexOrderRec.setValue({ fieldId: 'custrecord_mpex_order_3kg_satchel', value: kg3 }); mpexOrderRec.setValue({ fieldId: 'custrecord_mpex_order_5kg_satchel', value: kg5 }); // mpexOrderRec.setValue({ // fieldId: 'custrecord_mpex_order_500_satchel_toll', // value: g500_toll // }); mpexOrderRec.setValue({ fieldId: 'custrecord_mpex_order_1kg_satchel_toll', value: kg1_toll }); mpexOrderRec.setValue({ fieldId: 'custrecord_mpex_order_3kg_satchel_toll', value: kg3_toll }); mpexOrderRec.setValue({ fieldId: 'custrecord_mpex_order_5kg_satchel_toll', value: kg5_toll }); mpexOrderRec.setValue({ fieldId: 'custrecord_mpex_order_total', value: b4 + g500 + kg1 + kg3 + kg5 + kg1_toll + kg3_toll + kg5_toll }); //mpexOrderRec.setValue({fieldId: 'custrecord_mpex_order_date', value: date}); mpexOrderRec.save({ enableSourcing: true, ignoreMandatoryFields: true }); } else { var zeeSearch = search.load({ id: 'customsearch_zee_mpex_product_order', type: search.Type.PARTNER }); zeeSearch.filters.push(search.createFilter({ name: 'internalid', operator: search.Operator.IS, values: zee_id })); var zeeResultSet = zeeSearch.run(); var tollAcctNum; var dxAddr; var dxExch; var state; var zip; zeeResultSet.each(function(searchResult) { tollAcctNum = searchResult.getValue( 'custentity_toll_acc_number'); dxAddr = searchResult.getValue({ name: "custrecord_ap_lodgement_addr2", join: "CUSTENTITY__TOLL_PICKUP_DX_NO", label: "Address 2" }); dxExch = searchResult.getValue({ name: "custrecord_ap_lodgement_suburb", join: "CUSTENTITY__TOLL_PICKUP_DX_NO", label: "Suburb" }); state = searchResult.getText({ name: "custrecord_ap_lodgement_site_state", join: "CUSTENTITY__TOLL_PICKUP_DX_NO", label: "State" }); zip = searchResult.getValue({ name: "custrecord_ap_lodgement_postcode", join: "CUSTENTITY__TOLL_PICKUP_DX_NO", label: "Post Code" }); }); var mpexOrderRec = record.create({ type: 'customrecord_zee_mpex_order', isDynamic: true, }); var date = new Date(); date.setDate(date.getDate() + 1); //date.toLocaleString('en-AU', 'Australia/Sydney'); //1 = ACTIVE, 2 = PROCESSING, 3 = COMPLETED (if connote) mpexOrderRec.setValue({ fieldId: 'custrecord_mpex_order_status', value: 1 }); mpexOrderRec.setValue({ fieldId: 'custrecord_mpex_order_franchisee', value: zee_id }); mpexOrderRec.setValue({ fieldId: 'custrecord_mpex_order_b4', value: b4 }); mpexOrderRec.setValue({ fieldId: 'custrecord_mpex_order_500_satchel', value: g500 }); mpexOrderRec.setValue({ fieldId: 'custrecord_mpex_order_1kg_satchel', value: kg1 }); mpexOrderRec.setValue({ fieldId: 'custrecord_mpex_order_3kg_satchel', value: kg3 }); mpexOrderRec.setValue({ fieldId: 'custrecord_mpex_order_5kg_satchel', value: kg5 }); // mpexOrderRec.setValue({ // fieldId: 'custrecord_mpex_order_500_satchel_toll', // value: g500_toll // }); mpexOrderRec.setValue({ fieldId: 'custrecord_mpex_order_1kg_satchel_toll', value: kg1_toll }); mpexOrderRec.setValue({ fieldId: 'custrecord_mpex_order_3kg_satchel_toll', value: kg3_toll }); mpexOrderRec.setValue({ fieldId: 'custrecord_mpex_order_5kg_satchel_toll', value: kg5_toll }); mpexOrderRec.setValue({ fieldId: 'custrecord_mpex_order_total', value: b4 + g500 + kg1 + kg3 + kg5 + kg1_toll + kg3_toll + kg5_toll }); //mpexOrderRec.setValue({fieldId: 'custrecord_mpex_order_date', value: date }); mpexOrderRec.setValue({ fieldId: 'custrecord_mpex_order_mp_id', value: zee_id }); mpexOrderRec.setValue({ fieldId: 'custrecord_mpex_order_toll_acc_num', value: tollAcctNum }); mpexOrderRec.setValue({ fieldId: 'custrecord_mpex_order_dx_addr', value: dxAddr }); mpexOrderRec.setValue({ fieldId: 'custrecord_mpex_order_dx_exch', value: dxExch }); mpexOrderRec.setValue({ fieldId: 'custrecord_mpex_order_state', value: state }); mpexOrderRec.setValue({ fieldId: 'custrecord_mpex_order_postcode', value: zip }); mpexOrderRec.save({ enableSourcing: true, ignoreMandatoryFields: true }); } } function checkConnote(zee) { var zeeSearch = search.load({ id: 'customsearch_mpex_zee_order_search', type: 'customrecord_zee_mpex_order' }); zeeSearch.filters.push(search.createFilter({ name: 'custrecord_mpex_order_franchisee', operator: search.Operator.IS, values: zee })); var zeeResultSet = zeeSearch.run(); var activeOrder = 0; zeeResultSet.each(function(searchResult) { var connote = searchResult.getValue({ name: 'custrecord_mpex_order_connote' }); var status = searchResult.getValue({ name: 'custrecord_mpex_order_status' }); if (status == 1 && isNullorEmpty(connote)) { log.debug({ title: 'INSIDE CONNOTEEE', details: 'INSIDE CONNOTEEE' }); activeOrder = searchResult.getValue({ name: 'id' }); return false; } return true; }); return activeOrder; } function instructionsBox() { var inlineQty = '<br></br>'; //Important Instructions box inlineQty += '<div></div>'; inlineQty += '<div class="form-group container test_section">'; inlineQty += '<div style=\"background-color: #CFE0CE !important;border: 1px solid #379E8F;padding: 20px 30px 30px 30px\">'; inlineQty += 'Complete this form to reorder packs of MPEX product stock for MailPlus Products (manual use with pre-printed labels) or TOLL Products, which require the customer to apply a TOLL Common label to shipβ€”interested in biodegradable satchels? You can also direct customers to save up to 36% with our new biodegradable option with BetterPackaging. Find out more here: <a href=\"https://mailplus.com.au/discounted-biodegradable-satchels/\">Biodegradable Satchels</a>. Note the "<b>Dirt bags</b>" must be purchased separately.'; inlineQty += "<br></br><b><u>Form Instructions:</u></b>" inlineQty += '</br><b>Entering Quantities: </b>' inlineQty += '<ul><li>You may only enter numbers into the relevant fields. Entering text will result in an input error, and you will need to re-enter the quantity using numbers only.</li>'; inlineQty += '<li>You may also use the up and down arrows on the far right-hand side of each field to set the number of packs you require</li>'; inlineQty += '<li>You are not required to fill out every box if you don\'t require every product.</li>'; inlineQty += '</ul>'; inlineQty += '</br><b>Product Types and Packs</b>' inlineQty += '<ul><b><u>MailPlus Product</u></b>: All Mailplus products come in a 10-pack. Please enter the number of 10-packs you require for each product type. The minimum number you can order is 10 x 10-pack = 100 items.'; inlineQty += '<b><u>TOLL Product</u></b>: All TOLL products come in a 5-pack. Please enter the number of 5-packs you require for each product type. The minimum number you can order is 10 x 5-pack = 50 items. '; inlineQty += '<p style="color: red;"><b><u>Please note</u></b>: The 500g satchel for TOLL Products is discontinued. Customers can use other product stock to ship a <500g item by applying the 500g TOLL COMMON Label through the MailPlus portal to a different product type like a 1kg satchel. The current 500g rate will apply, provided the item is less than 500g and the 500g rate was selected.</p>'; inlineQty += '</ul>' inlineQty += '</br><b>Placing the Order</b>' inlineQty += '<ul>' inlineQty += '<li><b><u>SUBMIT</u></b>: Press the "SUBMIT Order" button at the top of the screen to submit your order and continue to the confirmation page.</li>' inlineQty += '</ul></div></div><br/>'; return inlineQty; } function inputFields(b4, g500, kg1, kg3, kg5, test) { //Add Break //var inlineQty = '<div class="form-group container break_section"><div class="row"></div></div>' //500g AND B4 Options var inlineQty = '<div class="form-group container g500_section">'; inlineQty += '<div class="row">'; if (test) { inlineQty += '<div class="col-xs-6 g500_env"><div class="input-group"><span class="input-group-addon" id="500g">500G SATCHEL (PACKS OF 10) </span><input id="500g_text" type="number" min="0" step="10" class="form-control 500g" value="' + g500 + '"/></div></div>'; inlineQty += '<div class="col-xs-6 b4_env"><div class="input-group"><span class="input-group-addon" id="b4">B4 ENVELOPE (PACKS OF 10) </span><input id="b4_text" type="number" min="0" step="10" class="form-control b4" value="' + b4 + '"/></div></div>'; } else { inlineQty += '<div class="col-xs-6 g500_env"><div class="input-group"><span class="input-group-addon" id="500g">500G SATCHEL (PACKS OF 10) </span><input id="500g_text" type="number" min="0" step="10" class="form-control 500g" placeholder="Enter quantity" value="' + g500 + '"/></div></div>'; inlineQty += '<div class="col-xs-6 b4_env"><div class="input-group"><span class="input-group-addon" id="b4">B4 ENVELOPE (PACKS OF 10) </span><input id="b4_text" type="number" min="0" step="10" class="form-control b4" placeholder="Enter quantity" value="' + b4 + '"/></div></div>'; } inlineQty += '</div>'; inlineQty += '</div>'; //1KG inlineQty += '<div class="form-group container b4_section">'; inlineQty += '<div class="row">'; if (test) { inlineQty += '<div class="col-xs-6 kg1_env"><div class="input-group"><span class="input-group-addon" id="1kg">1KG SATCHEL (PACKS OF 10) </span><input id="1kg_text" type="number" min="0" step="10" class="form-control 1kg" value="' + kg1 + '"/></div></div>'; } else { inlineQty += '<div class="col-xs-6 kg1_env"><div class="input-group"><span class="input-group-addon" id="1kg">1KG SATCHEL (PACKS OF 10) </span><input id="1kg_text" type="number" min="0" step="10" class="form-control 1kg" placeholder="Enter quantity"value="' + kg1 + '"/></div></div>'; } inlineQty += '</div>'; inlineQty += '</div>'; //3KG options inlineQty += '<div class="form-group container c5_section">'; inlineQty += '<div class="row">'; if (test) { inlineQty += '<div class="col-xs-6 kg3_env"><div class="input-group"><span class="input-group-addon" id="3kg">3KG SATCHEL (PACKS OF 10)</span><input id="3kg_text" type="number" min="0" step="10" class="form-control 3kg" value="' + kg3 + '"/></div></div>'; } else { inlineQty += '<div class="col-xs-6 kg3_env"><div class="input-group"><span class="input-group-addon" id="3kg">3KG SATCHEL (PACKS OF 10)</span><input id="3kg_text" type="number" min="0" step="10" class="form-control 3kg" placeholder="Enter quantity" value="' + kg3 + '"/></div></div>'; } inlineQty += '</div>'; inlineQty += '</div>'; //5KG options inlineQty += '<div class="form-group container c5_section">'; inlineQty += '<div class="row">'; if (test) { inlineQty += '<div class="col-xs-6 kg5_env"><div class="input-group"><span class="input-group-addon" id="5kg">5KG SATCHEL (PACKS OF 10) </span><input id="5kg_text" type="number" min="0" step="10" class="form-control 5kg" value="' + kg5 + '"/></div></div>'; } else { inlineQty += '<div class="col-xs-6 kg5_env"><div class="input-group"><span class="input-group-addon" id="5kg">5KG SATCHEL (PACKS OF 10) </span><input id="5kg_text" type="number" min="0" step="10" class="form-control 5kg" placeholder="Enter quantity" value="' + kg5 + '"/></div></div>'; } inlineQty += '</div>'; inlineQty += '</div>'; return inlineQty; } function inputFieldsToll(g500, kg1, kg3, kg5, test) { //Add Break //var inlineQty = '<div class="form-group container break_section"><div class="row"></div></div>' //500g AND 5KG Options var inlineQty = '<div class="form-group container g500_section_toll">'; inlineQty += '<div class="row">'; if (test) { inlineQty += '<div class="col-xs-6 kg1_env_toll"><div class="input-group"><span class="input-group-addon" id="1kg">1KG SATCHEL </span><input id="1kg_text_toll" type="number" min="0" step="5" class="form-control 1kg" value="' + kg1 + '"/></div></div>'; inlineQty += '<div class="col-xs-6 g500_env_toll"><div class="input-group"><span class="input-group-addon" id="500g">500G SATCHEL </span><input id="500g_text_toll" type="text" class="form-control " value="DISCONTINUED" readonly/></div></div>'; } else { inlineQty += '<div class="col-xs-6 kg1_env_toll"><div class="input-group"><span class="input-group-addon" id="1kg">1KG SATCHEL </span><input id="1kg_text_toll" type="number" min="0" step="5" class="form-control 1kg" placeholder="Enter quantity"value="' + kg1 + '"/></div></div>'; inlineQty += '<div class="col-xs-6 g500_env_toll"><div class="input-group"><span class="input-group-addon" id="500g">500G SATCHEL </span><input id="500g_text_toll" type="text" class="form-control " value="DISCONTINUED" readonly/></div></div>'; } inlineQty += '</div>'; inlineQty += '</div>'; //1KG and B4 options inlineQty += '<div class="form-group container b4_section_toll">'; inlineQty += '<div class="row">'; if (test) { inlineQty += '<div class="col-xs-6 kg3_env_toll"><div class="input-group"><span class="input-group-addon" id="3kg">3KG SATCHEL</span><input id="3kg_text_toll" type="number" min="0" step="5" class="form-control 3kg" value="' + kg3 + '"/></div></div>'; } else { inlineQty += '<div class="col-xs-6 kg3_env_toll"><div class="input-group"><span class="input-group-addon" id="3kg">3KG SATCHEL</span><input id="3kg_text_toll" type="number" min="0" step="5" class="form-control 3kg" placeholder="Enter quantity" value="' + kg3 + '"/></div></div>'; } inlineQty += '</div>'; inlineQty += '</div>'; //1KG and B4 options inlineQty += '<div class="form-group container b4_section_toll">'; inlineQty += '<div class="row">'; if (test) { inlineQty += '<div class="col-xs-6 kg5_env_toll"><div class="input-group"><span class="input-group-addon" id="5kg">5KG SATCHEL </span><input id="5kg_text_toll" type="number" min="0" step="5" class="form-control 5kg" value="' + kg5 + '"/></div></div>'; } else { inlineQty += '<div class="col-xs-6 kg5_env_toll"><div class="input-group"><span class="input-group-addon" id="5kg">5KG SATCHEL </span><input id="5kg_text_toll" type="number" min="0" step="5" class="form-control 5kg" placeholder="Enter quantity" value="' + kg5 + '"/></div></div>'; } inlineQty += '</div>'; inlineQty += '</div>'; return inlineQty; } /** * The table that will display the differents invoices linked to the franchisee and the time period. * @return {String} inlineQty */ function dataTable() { var inlineQty = '<br></br><style>table#mpex_orders {font-size: 12px;text-align: center;border: none;}.dataTables_wrapper {font-size: 14px;}table#mpex_orders th{text-align: center;} .bolded{font-weight: bold;}</style>'; inlineQty += '<table id="mpex_orders" class="table table-responsive table-striped customer tablesorter" style="width: 100%;">'; inlineQty += '<thead style="color: white;background-color: #379E8F;">'; inlineQty += '<tr class="text-center">'; inlineQty += '</tr>'; inlineQty += '</thead>'; inlineQty += '<tbody id="result_import" class="result-import"></tbody>'; inlineQty += '</table>'; return inlineQty; } function formatDate(testDate) { //console.log('testDate: '+testDate); var responseDate = format.format({ value: testDate, type: format.Type.DATE }); //console.log('responseDate: '+responseDate); return responseDate; } /** * The Franchisee dropdown list. * @param {Number} zee_id * @return {String} `inlineQty` */ function franchiseeDropdownSection(params_zee) { var inlineQty = '<div class="form-group container zee_dropdown_section >'; inlineQty += '<div class="row">'; // Franchisee dropdown field inlineQty += '<div class="col-xs-18 zee_dropdown_div">'; inlineQty += '<div class="input-group">'; inlineQty += '<span class="input-group-addon" id="zee_dropdown_text">FRANCHISEE</span>'; inlineQty += '<select id="zee_dropdown" class="form-control zee_dropdown" required>'; inlineQty += '<option></option>'; // Load the franchisees options var zeesSearch = search.load({ id: 'customsearch_job_inv_process_zee', type: search.Type.PARTNER }); var zeesSearchResults = zeesSearch.run(); zeesSearchResults.each(function(zeesSearchResult) { var opt_zee_id = zeesSearchResult.getValue('internalid'); var opt_zee_name = zeesSearchResult.getValue('companyname'); var selected_option = ''; if (role == 1000) { zee_id = runtime.getCurrentUser().id; //Get Franchisee ID-- REMOVE TO TEST selected_option = (opt_zee_id == zee_id) ? 'selected' : ''; } if (!isNullorEmpty(params_zee)) { selected_option = (params_zee == opt_zee_id) ? 'selected' : ''; } inlineQty += '<option value="' + opt_zee_id + '" ' + selected_option + '>' + opt_zee_name + '</option>'; return true; }); inlineQty += '</select>'; inlineQty += '</div></div></div></div>'; return inlineQty; } function isNullorEmpty(strVal) { return (strVal == null || strVal == '' || strVal == 'null' || strVal == undefined || strVal == 'undefined' || strVal == '- None -'); } return { onRequest: onRequest }; } );
true
/** * @Author: Ankith Ravindran <ankithravindran> * @Date: 2021-09-15T17:03:03+10:00 * @Filename: mp_sl_product_ordering.js * @Last modified by: ankithravindran * @Last modified time: 2022-01-18T13:25:42+11:00 */ /** *@NApiVersion 2.0 *@NScriptType Suitelet */ define(['N/ui/serverWidget', 'N/email', 'N/runtime', 'N/search', 'N/record', 'N/http', 'N/log', 'N/redirect', 'N/format' ], function(ui, email, runtime, search, record, http, log, redirect, format) { var role = runtime.getCurrentUser().role; function onRequest(context) { var b4 = ''; var g500 = ''; var kg1 = ''; var kg3 = ''; var kg5 = ''; var g500_toll = ''; var kg1_toll = ''; var kg3_toll = ''; var kg5_toll = ''; var test = false; if (context.request.method === 'GET') { // Load jQuery var inlineHtml = '<script src="https://code.jquery.com/jquery-1.12.4.min.js" integrity="PI:KEY:9q3vfhm7l33rus21toc8fndupq76itjeEND_PI" crossorigin="anonymous"></script>'; // Load Tooltip inlineHtml += '<script src="https://unpkg.com/@popperjs/core@2"></script>'; // Load Bootstrap inlineHtml += '<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/3.4.1/css/bootstrap.min.css" integrity="PI:KEY:9jnerlff23u8ed01np9g6ysbhsh0dvcsEND_PI" crossorigin="anonymous">'; inlineHtml += '<script src="https://stackpath.bootstrapcdn.com/bootstrap/3.4.1/js/bootstrap.min.js" integrity="PI:KEY:vqbpgud2ghvjgm1n5hdgjnn5818fzsf2END_PI" crossorigin="anonymous"></script>'; // Load DataTables inlineHtml += '<link rel="stylesheet" type="text/css" href="//cdn.datatables.net/1.10.21/css/jquery.dataTables.min.css">'; inlineHtml += '<script type="text/javascript" charset="utf8" src="//cdn.datatables.net/1.10.21/js/jquery.dataTables.min.js"></script>'; // Load Bootstrap-Select inlineHtml += '<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap-select@1.13.14/dist/css/bootstrap-select.min.css">'; inlineHtml += '<script src="https://cdn.jsdelivr.net/npm/bootstrap-select@1.13.14/dist/js/bootstrap-select.min.js"></script>'; // Load Netsuite stylesheet and script inlineHtml += '<link rel="stylesheet" href="https://1048144.app.netsuite.com/core/media/media.nl?id=2060796&c=1048144&h=9ee6accfd476c9cae718&_xt=.css"/>'; inlineHtml += '<script src="https://1048144.app.netsuite.com/core/media/media.nl?id=2060797&c=1048144&h=ef2cda20731d146b5e98&_xt=.js"></script>'; inlineHtml += '<link type="text/css" rel="stylesheet" href="https://1048144.app.netsuite.com/core/media/media.nl?id=2090583&c=1048144&h=a0ef6ac4e28f91203dfe&_xt=.css">'; inlineHtml += '<style>.mandatory{color:red;}</style>'; var form = ui.createForm({ title: 'MPEX Product Ordering' }); if (!isNullorEmpty(context.request.parameters.zee) || role == 1000) { var zee; if (role == 1000) { zee = runtime.getCurrentUser().id; } else { zee = context.request.parameters.zee; } var zeeSearch = search.load({ id: 'customsearch_mpex_zee_order_search', type: 'customrecord_zee_mpex_order' }); zeeSearch.filters.push(search.createFilter({ name: 'custrecord_mpex_order_franchisee', operator: search.Operator.IS, values: zee })); var zeeResultSet = zeeSearch.run(); var activeOrder = 0; var b4 = ''; var g500 = ''; var kg1 = ''; var kg3 = ''; var kg5 = ''; var g500_toll = ''; var kg1_toll = ''; var kg3_toll = ''; var kg5_toll = ''; zeeResultSet.each(function(searchResult) { var connote = searchResult.getValue({ name: 'custrecord_mpex_order_connote' }); var status = searchResult.getValue({ name: 'custrecord_mpex_order_status' }); if (status == 1 && isNullorEmpty(connote)) { activeOrder = searchResult.getValue({ name: 'id' }); b4 = searchResult.getValue({ name: "custrecord_mpex_order_b4" }); g500 = searchResult.getValue({ name: "custrecord_mpex_order_500_satchel" }); kg1 = searchResult.getValue({ name: "custrecord_mpex_order_1kg_satchel" }); kg3 = searchResult.getValue({ name: "custrecord_mpex_order_3kg_satchel" }); kg5 = searchResult.getValue({ name: "custrecord_mpex_order_5kg_satchel" }); g500_toll = searchResult.getValue({ name: "custrecord_mpex_order_500_satchel_toll" }); kg1_toll = searchResult.getValue({ name: "custrecord_mpex_order_1kg_satchel_toll" }); kg3_toll = searchResult.getValue({ name: "custrecord_mpex_order_3kg_satchel_toll" }); kg5_toll = searchResult.getValue({ name: "custrecord_mpex_order_5kg_satchel_toll" }); test = true; return false; } return true; }); } //Instructions inlineHtml += instructionsBox(); if (role != 1000) { inlineHtml += franchiseeDropdownSection(context.request.parameters.zee); } //Heading inlineHtml += '<div class="form-group container product_order_section">'; inlineHtml += '<div class="row">'; inlineHtml += '<div class="col-xs-12 heading1"><h4><span style="background-color: #379E8F;" class="label label-default col-xs-12">MAILPLUS PRODUCTS</span></h4></div>'; inlineHtml += '</div>'; inlineHtml += '</div>'; inlineHtml += inputFields(b4, g500, kg1, kg3, kg5, test); //Heading inlineHtml += '<div class="form-group container toll_product_order_section">'; inlineHtml += '<div class="row">'; inlineHtml += '<div class="col-xs-12 heading1"><h4><span style="background-color: #379E8F;" class="label label-default col-xs-12">TOLL PRODUCTS</span></h4></div>'; inlineHtml += '</div>'; inlineHtml += '</div>'; inlineHtml += inputFieldsToll(g500_toll, kg1_toll, kg3_toll, kg5_toll, test); if (!isNullorEmpty(context.request.parameters.zee) && context.request .parameters.zee != 0) { form.addField({ id: 'custpage_zee_selected', type: ui.FieldType.TEXT, label: 'zee' }).updateDisplayType({ displayType: ui.FieldDisplayType.HIDDEN }).defaultValue = context.request.parameters.zee; } else { form.addField({ id: 'custpage_zee_selected', type: ui.FieldType.TEXT, label: 'zee' }).updateDisplayType({ displayType: ui.FieldDisplayType.HIDDEN }); } form.addField({ id: 'preview_table', type: ui.FieldType.INLINEHTML, label: 'preview_table' }).updateBreakType({ breakType: ui.FieldBreakType.STARTROW }).defaultValue = inlineHtml; form.addField({ id: 'results', type: ui.FieldType.TEXT, label: 'results' }).updateDisplayType({ displayType: ui.FieldDisplayType.HIDDEN }); form.addField({ id: 'custpage_b4', type: ui.FieldType.TEXT, label: 'b4' }).updateDisplayType({ displayType: ui.FieldDisplayType.HIDDEN }); form.addField({ id: 'custpage_g500', type: ui.FieldType.TEXT, label: 'g500' }).updateDisplayType({ displayType: ui.FieldDisplayType.HIDDEN }); form.addField({ id: 'custpage_kg1', type: ui.FieldType.TEXT, label: 'kg1' }).updateDisplayType({ displayType: ui.FieldDisplayType.HIDDEN }); form.addField({ id: 'custpage_kg3', type: ui.FieldType.TEXT, label: 'kg3' }).updateDisplayType({ displayType: ui.FieldDisplayType.HIDDEN }); form.addField({ id: 'custpage_kg5', type: ui.FieldType.TEXT, label: 'kg5' }).updateDisplayType({ displayType: ui.FieldDisplayType.HIDDEN }); form.addField({ id: 'custpage_g500_toll', type: ui.FieldType.TEXT, label: 'g500_toll' }).updateDisplayType({ displayType: ui.FieldDisplayType.HIDDEN }); form.addField({ id: 'custpage_kg1_toll', type: ui.FieldType.TEXT, label: 'kg1_toll' }).updateDisplayType({ displayType: ui.FieldDisplayType.HIDDEN }); form.addField({ id: 'custpage_kg3_toll', type: ui.FieldType.TEXT, label: 'kg3_toll' }).updateDisplayType({ displayType: ui.FieldDisplayType.HIDDEN }); form.addField({ id: 'custpage_kg5_toll', type: ui.FieldType.TEXT, label: 'kg5_toll' }).updateDisplayType({ displayType: ui.FieldDisplayType.HIDDEN }); form.addSubmitButton({ label: 'SUBMIT ORDER' }); form.clientScriptFileId = 4509791; //SB cl_id =4242817, PROD cl_id = 4509791 context.response.writePage(form); } else { var zee_id = context.request.parameters.custpage_zee_selected; var b4 = context.request.parameters.custpage_b4; var g500 = context.request.parameters.custpage_g500; var kg1 = context.request.parameters.custpage_kg1; var kg3 = context.request.parameters.custpage_kg3; var kg5 = context.request.parameters.custpage_kg5; // var g500_toll = context.request.parameters.custpage_g500_toll; var kg1_toll = context.request.parameters.custpage_kg1_toll; var kg3_toll = context.request.parameters.custpage_kg3_toll; var kg5_toll = context.request.parameters.custpage_kg5_toll; createCustomRecord(zee_id, b4, g500, kg1, kg3, kg5, kg1_toll, kg3_toll, kg5_toll); var form = ui.createForm({ title: 'MPEX Product Order Confirmation' }); // Load jQuery var inlineHtml2 = '<script src="https://code.jquery.com/jquery-1.12.4.min.js" integrity="PI:KEY:9q3vfhm7l33rus21toc8fndupq76itjeEND_PI" crossorigin="anonymous"></script>'; // Load Tooltip inlineHtml2 += '<script src="https://unpkg.com/@popperjs/core@2"></script>'; // Load Bootstrap inlineHtml2 += '<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/3.4.1/css/bootstrap.min.css" integrity="PI:KEY:9jnerlff23u8ed01np9g6ysbhsh0dvcsEND_PI" crossorigin="anonymous">'; inlineHtml2 += '<script src="https://stackpath.bootstrapcdn.com/bootstrap/3.4.1/js/bootstrap.min.js" integrity="PI:KEY:vqbpgud2ghvjgm1n5hdgjnn5818fzsf2END_PI" crossorigin="anonymous"></script>'; // Load DataTables inlineHtml2 += '<link rel="stylesheet" type="text/css" href="//cdn.datatables.net/1.10.21/css/jquery.dataTables.min.css">'; inlineHtml2 += '<script type="text/javascript" charset="utf8" src="//cdn.datatables.net/1.10.21/js/jquery.dataTables.min.js"></script>'; // Load Bootstrap-Select inlineHtml2 += '<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap-select@1.13.14/dist/css/bootstrap-select.min.css">'; inlineHtml2 += '<script src="https://cdn.jsdelivr.net/npm/bootstrap-select@1.13.14/dist/js/bootstrap-select.min.js"></script>'; // Load Netsuite stylesheet and script inlineHtml2 += '<link rel="stylesheet" href="https://1048144.app.netsuite.com/core/media/media.nl?id=2060796&c=1048144&h=9ee6accfd476c9cae718&_xt=.css"/>'; inlineHtml2 += '<script src="https://1048144.app.netsuite.com/core/media/media.nl?id=2060797&c=1048144&h=ef2cda20731d146b5e98&_xt=.js"></script>'; inlineHtml2 += '<link type="text/css" rel="stylesheet" href="https://1048144.app.netsuite.com/core/media/media.nl?id=2090583&c=1048144&h=a0ef6ac4e28f91203dfe&_xt=.css">'; inlineHtml2 += '<style>.mandatory{color:red;}</style>'; inlineHtml2 += dataTable(); // The HTML code for the table is inserted with JQuery in the pageInit function of the mp_cl_product_ordering_page script. var zee_id = ''; if (role != 1000) { zee_id = context.request.parameters.custpage_zee_selected; log.debug({ title: 'zee', details: zee_id }); } else { zee_id = runtime.getCurrentUser().id; } form.addField({ id: 'custpage_zee_selected', type: ui.FieldType.TEXT, label: 'zee' }).updateDisplayType({ displayType: ui.FieldDisplayType.HIDDEN }).defaultValue = zee_id; form.addField({ id: 'results', type: ui.FieldType.TEXT, label: 'results' }).updateDisplayType({ displayType: ui.FieldDisplayType.HIDDEN }).defaultValue = true; form.addField({ id: 'preview_table', type: ui.FieldType.INLINEHTML, label: 'preview_table' }).updateBreakType({ breakType: ui.FieldBreakType.STARTROW }).defaultValue = inlineHtml2; form.addButton({ id: 'submit', label: 'CHANGE ORDER', functionName: 'onclick_submit()' }); form.clientScriptFileId = 4509791; //SB cl_id =4242817, PROD cl_id = 4509791 context.response.writePage(form); } } function createCustomRecord(zee_id, b4, g500, kg1, kg3, kg5, kg1_toll, kg3_toll, kg5_toll) { var activeOrder = checkConnote(zee_id); //Load active order if it exists if (activeOrder != 0) { var mpexOrderRec = record.load({ type: 'customrecord_zee_mpex_order', id: activeOrder }); var date = new Date(); date.setDate(date.getDate() + 1); mpexOrderRec.setValue({ fieldId: 'custrecord_mpex_order_b4', value: b4 }); mpexOrderRec.setValue({ fieldId: 'custrecord_mpex_order_500_satchel', value: g500 }); mpexOrderRec.setValue({ fieldId: 'custrecord_mpex_order_1kg_satchel', value: kg1 }); mpexOrderRec.setValue({ fieldId: 'custrecord_mpex_order_3kg_satchel', value: kg3 }); mpexOrderRec.setValue({ fieldId: 'custrecord_mpex_order_5kg_satchel', value: kg5 }); // mpexOrderRec.setValue({ // fieldId: 'custrecord_mpex_order_500_satchel_toll', // value: g500_toll // }); mpexOrderRec.setValue({ fieldId: 'custrecord_mpex_order_1kg_satchel_toll', value: kg1_toll }); mpexOrderRec.setValue({ fieldId: 'custrecord_mpex_order_3kg_satchel_toll', value: kg3_toll }); mpexOrderRec.setValue({ fieldId: 'custrecord_mpex_order_5kg_satchel_toll', value: kg5_toll }); mpexOrderRec.setValue({ fieldId: 'custrecord_mpex_order_total', value: b4 + g500 + kg1 + kg3 + kg5 + kg1_toll + kg3_toll + kg5_toll }); //mpexOrderRec.setValue({fieldId: 'custrecord_mpex_order_date', value: date}); mpexOrderRec.save({ enableSourcing: true, ignoreMandatoryFields: true }); } else { var zeeSearch = search.load({ id: 'customsearch_zee_mpex_product_order', type: search.Type.PARTNER }); zeeSearch.filters.push(search.createFilter({ name: 'internalid', operator: search.Operator.IS, values: zee_id })); var zeeResultSet = zeeSearch.run(); var tollAcctNum; var dxAddr; var dxExch; var state; var zip; zeeResultSet.each(function(searchResult) { tollAcctNum = searchResult.getValue( 'custentity_toll_acc_number'); dxAddr = searchResult.getValue({ name: "custrecord_ap_lodgement_addr2", join: "CUSTENTITY__TOLL_PICKUP_DX_NO", label: "Address 2" }); dxExch = searchResult.getValue({ name: "custrecord_ap_lodgement_suburb", join: "CUSTENTITY__TOLL_PICKUP_DX_NO", label: "Suburb" }); state = searchResult.getText({ name: "custrecord_ap_lodgement_site_state", join: "CUSTENTITY__TOLL_PICKUP_DX_NO", label: "State" }); zip = searchResult.getValue({ name: "custrecord_ap_lodgement_postcode", join: "CUSTENTITY__TOLL_PICKUP_DX_NO", label: "Post Code" }); }); var mpexOrderRec = record.create({ type: 'customrecord_zee_mpex_order', isDynamic: true, }); var date = new Date(); date.setDate(date.getDate() + 1); //date.toLocaleString('en-AU', 'Australia/Sydney'); //1 = ACTIVE, 2 = PROCESSING, 3 = COMPLETED (if connote) mpexOrderRec.setValue({ fieldId: 'custrecord_mpex_order_status', value: 1 }); mpexOrderRec.setValue({ fieldId: 'custrecord_mpex_order_franchisee', value: zee_id }); mpexOrderRec.setValue({ fieldId: 'custrecord_mpex_order_b4', value: b4 }); mpexOrderRec.setValue({ fieldId: 'custrecord_mpex_order_500_satchel', value: g500 }); mpexOrderRec.setValue({ fieldId: 'custrecord_mpex_order_1kg_satchel', value: kg1 }); mpexOrderRec.setValue({ fieldId: 'custrecord_mpex_order_3kg_satchel', value: kg3 }); mpexOrderRec.setValue({ fieldId: 'custrecord_mpex_order_5kg_satchel', value: kg5 }); // mpexOrderRec.setValue({ // fieldId: 'custrecord_mpex_order_500_satchel_toll', // value: g500_toll // }); mpexOrderRec.setValue({ fieldId: 'custrecord_mpex_order_1kg_satchel_toll', value: kg1_toll }); mpexOrderRec.setValue({ fieldId: 'custrecord_mpex_order_3kg_satchel_toll', value: kg3_toll }); mpexOrderRec.setValue({ fieldId: 'custrecord_mpex_order_5kg_satchel_toll', value: kg5_toll }); mpexOrderRec.setValue({ fieldId: 'custrecord_mpex_order_total', value: b4 + g500 + kg1 + kg3 + kg5 + kg1_toll + kg3_toll + kg5_toll }); //mpexOrderRec.setValue({fieldId: 'custrecord_mpex_order_date', value: date }); mpexOrderRec.setValue({ fieldId: 'custrecord_mpex_order_mp_id', value: zee_id }); mpexOrderRec.setValue({ fieldId: 'custrecord_mpex_order_toll_acc_num', value: tollAcctNum }); mpexOrderRec.setValue({ fieldId: 'custrecord_mpex_order_dx_addr', value: dxAddr }); mpexOrderRec.setValue({ fieldId: 'custrecord_mpex_order_dx_exch', value: dxExch }); mpexOrderRec.setValue({ fieldId: 'custrecord_mpex_order_state', value: state }); mpexOrderRec.setValue({ fieldId: 'custrecord_mpex_order_postcode', value: zip }); mpexOrderRec.save({ enableSourcing: true, ignoreMandatoryFields: true }); } } function checkConnote(zee) { var zeeSearch = search.load({ id: 'customsearch_mpex_zee_order_search', type: 'customrecord_zee_mpex_order' }); zeeSearch.filters.push(search.createFilter({ name: 'custrecord_mpex_order_franchisee', operator: search.Operator.IS, values: zee })); var zeeResultSet = zeeSearch.run(); var activeOrder = 0; zeeResultSet.each(function(searchResult) { var connote = searchResult.getValue({ name: 'custrecord_mpex_order_connote' }); var status = searchResult.getValue({ name: 'custrecord_mpex_order_status' }); if (status == 1 && isNullorEmpty(connote)) { log.debug({ title: 'INSIDE CONNOTEEE', details: 'INSIDE CONNOTEEE' }); activeOrder = searchResult.getValue({ name: 'id' }); return false; } return true; }); return activeOrder; } function instructionsBox() { var inlineQty = '<br></br>'; //Important Instructions box inlineQty += '<div></div>'; inlineQty += '<div class="form-group container test_section">'; inlineQty += '<div style=\"background-color: #CFE0CE !important;border: 1px solid #379E8F;padding: 20px 30px 30px 30px\">'; inlineQty += 'Complete this form to reorder packs of MPEX product stock for MailPlus Products (manual use with pre-printed labels) or TOLL Products, which require the customer to apply a TOLL Common label to shipβ€”interested in biodegradable satchels? You can also direct customers to save up to 36% with our new biodegradable option with BetterPackaging. Find out more here: <a href=\"https://mailplus.com.au/discounted-biodegradable-satchels/\">Biodegradable Satchels</a>. Note the "<b>Dirt bags</b>" must be purchased separately.'; inlineQty += "<br></br><b><u>Form Instructions:</u></b>" inlineQty += '</br><b>Entering Quantities: </b>' inlineQty += '<ul><li>You may only enter numbers into the relevant fields. Entering text will result in an input error, and you will need to re-enter the quantity using numbers only.</li>'; inlineQty += '<li>You may also use the up and down arrows on the far right-hand side of each field to set the number of packs you require</li>'; inlineQty += '<li>You are not required to fill out every box if you don\'t require every product.</li>'; inlineQty += '</ul>'; inlineQty += '</br><b>Product Types and Packs</b>' inlineQty += '<ul><b><u>MailPlus Product</u></b>: All Mailplus products come in a 10-pack. Please enter the number of 10-packs you require for each product type. The minimum number you can order is 10 x 10-pack = 100 items.'; inlineQty += '<b><u>TOLL Product</u></b>: All TOLL products come in a 5-pack. Please enter the number of 5-packs you require for each product type. The minimum number you can order is 10 x 5-pack = 50 items. '; inlineQty += '<p style="color: red;"><b><u>Please note</u></b>: The 500g satchel for TOLL Products is discontinued. Customers can use other product stock to ship a <500g item by applying the 500g TOLL COMMON Label through the MailPlus portal to a different product type like a 1kg satchel. The current 500g rate will apply, provided the item is less than 500g and the 500g rate was selected.</p>'; inlineQty += '</ul>' inlineQty += '</br><b>Placing the Order</b>' inlineQty += '<ul>' inlineQty += '<li><b><u>SUBMIT</u></b>: Press the "SUBMIT Order" button at the top of the screen to submit your order and continue to the confirmation page.</li>' inlineQty += '</ul></div></div><br/>'; return inlineQty; } function inputFields(b4, g500, kg1, kg3, kg5, test) { //Add Break //var inlineQty = '<div class="form-group container break_section"><div class="row"></div></div>' //500g AND B4 Options var inlineQty = '<div class="form-group container g500_section">'; inlineQty += '<div class="row">'; if (test) { inlineQty += '<div class="col-xs-6 g500_env"><div class="input-group"><span class="input-group-addon" id="500g">500G SATCHEL (PACKS OF 10) </span><input id="500g_text" type="number" min="0" step="10" class="form-control 500g" value="' + g500 + '"/></div></div>'; inlineQty += '<div class="col-xs-6 b4_env"><div class="input-group"><span class="input-group-addon" id="b4">B4 ENVELOPE (PACKS OF 10) </span><input id="b4_text" type="number" min="0" step="10" class="form-control b4" value="' + b4 + '"/></div></div>'; } else { inlineQty += '<div class="col-xs-6 g500_env"><div class="input-group"><span class="input-group-addon" id="500g">500G SATCHEL (PACKS OF 10) </span><input id="500g_text" type="number" min="0" step="10" class="form-control 500g" placeholder="Enter quantity" value="' + g500 + '"/></div></div>'; inlineQty += '<div class="col-xs-6 b4_env"><div class="input-group"><span class="input-group-addon" id="b4">B4 ENVELOPE (PACKS OF 10) </span><input id="b4_text" type="number" min="0" step="10" class="form-control b4" placeholder="Enter quantity" value="' + b4 + '"/></div></div>'; } inlineQty += '</div>'; inlineQty += '</div>'; //1KG inlineQty += '<div class="form-group container b4_section">'; inlineQty += '<div class="row">'; if (test) { inlineQty += '<div class="col-xs-6 kg1_env"><div class="input-group"><span class="input-group-addon" id="1kg">1KG SATCHEL (PACKS OF 10) </span><input id="1kg_text" type="number" min="0" step="10" class="form-control 1kg" value="' + kg1 + '"/></div></div>'; } else { inlineQty += '<div class="col-xs-6 kg1_env"><div class="input-group"><span class="input-group-addon" id="1kg">1KG SATCHEL (PACKS OF 10) </span><input id="1kg_text" type="number" min="0" step="10" class="form-control 1kg" placeholder="Enter quantity"value="' + kg1 + '"/></div></div>'; } inlineQty += '</div>'; inlineQty += '</div>'; //3KG options inlineQty += '<div class="form-group container c5_section">'; inlineQty += '<div class="row">'; if (test) { inlineQty += '<div class="col-xs-6 kg3_env"><div class="input-group"><span class="input-group-addon" id="3kg">3KG SATCHEL (PACKS OF 10)</span><input id="3kg_text" type="number" min="0" step="10" class="form-control 3kg" value="' + kg3 + '"/></div></div>'; } else { inlineQty += '<div class="col-xs-6 kg3_env"><div class="input-group"><span class="input-group-addon" id="3kg">3KG SATCHEL (PACKS OF 10)</span><input id="3kg_text" type="number" min="0" step="10" class="form-control 3kg" placeholder="Enter quantity" value="' + kg3 + '"/></div></div>'; } inlineQty += '</div>'; inlineQty += '</div>'; //5KG options inlineQty += '<div class="form-group container c5_section">'; inlineQty += '<div class="row">'; if (test) { inlineQty += '<div class="col-xs-6 kg5_env"><div class="input-group"><span class="input-group-addon" id="5kg">5KG SATCHEL (PACKS OF 10) </span><input id="5kg_text" type="number" min="0" step="10" class="form-control 5kg" value="' + kg5 + '"/></div></div>'; } else { inlineQty += '<div class="col-xs-6 kg5_env"><div class="input-group"><span class="input-group-addon" id="5kg">5KG SATCHEL (PACKS OF 10) </span><input id="5kg_text" type="number" min="0" step="10" class="form-control 5kg" placeholder="Enter quantity" value="' + kg5 + '"/></div></div>'; } inlineQty += '</div>'; inlineQty += '</div>'; return inlineQty; } function inputFieldsToll(g500, kg1, kg3, kg5, test) { //Add Break //var inlineQty = '<div class="form-group container break_section"><div class="row"></div></div>' //500g AND 5KG Options var inlineQty = '<div class="form-group container g500_section_toll">'; inlineQty += '<div class="row">'; if (test) { inlineQty += '<div class="col-xs-6 kg1_env_toll"><div class="input-group"><span class="input-group-addon" id="1kg">1KG SATCHEL </span><input id="1kg_text_toll" type="number" min="0" step="5" class="form-control 1kg" value="' + kg1 + '"/></div></div>'; inlineQty += '<div class="col-xs-6 g500_env_toll"><div class="input-group"><span class="input-group-addon" id="500g">500G SATCHEL </span><input id="500g_text_toll" type="text" class="form-control " value="DISCONTINUED" readonly/></div></div>'; } else { inlineQty += '<div class="col-xs-6 kg1_env_toll"><div class="input-group"><span class="input-group-addon" id="1kg">1KG SATCHEL </span><input id="1kg_text_toll" type="number" min="0" step="5" class="form-control 1kg" placeholder="Enter quantity"value="' + kg1 + '"/></div></div>'; inlineQty += '<div class="col-xs-6 g500_env_toll"><div class="input-group"><span class="input-group-addon" id="500g">500G SATCHEL </span><input id="500g_text_toll" type="text" class="form-control " value="DISCONTINUED" readonly/></div></div>'; } inlineQty += '</div>'; inlineQty += '</div>'; //1KG and B4 options inlineQty += '<div class="form-group container b4_section_toll">'; inlineQty += '<div class="row">'; if (test) { inlineQty += '<div class="col-xs-6 kg3_env_toll"><div class="input-group"><span class="input-group-addon" id="3kg">3KG SATCHEL</span><input id="3kg_text_toll" type="number" min="0" step="5" class="form-control 3kg" value="' + kg3 + '"/></div></div>'; } else { inlineQty += '<div class="col-xs-6 kg3_env_toll"><div class="input-group"><span class="input-group-addon" id="3kg">3KG SATCHEL</span><input id="3kg_text_toll" type="number" min="0" step="5" class="form-control 3kg" placeholder="Enter quantity" value="' + kg3 + '"/></div></div>'; } inlineQty += '</div>'; inlineQty += '</div>'; //1KG and B4 options inlineQty += '<div class="form-group container b4_section_toll">'; inlineQty += '<div class="row">'; if (test) { inlineQty += '<div class="col-xs-6 kg5_env_toll"><div class="input-group"><span class="input-group-addon" id="5kg">5KG SATCHEL </span><input id="5kg_text_toll" type="number" min="0" step="5" class="form-control 5kg" value="' + kg5 + '"/></div></div>'; } else { inlineQty += '<div class="col-xs-6 kg5_env_toll"><div class="input-group"><span class="input-group-addon" id="5kg">5KG SATCHEL </span><input id="5kg_text_toll" type="number" min="0" step="5" class="form-control 5kg" placeholder="Enter quantity" value="' + kg5 + '"/></div></div>'; } inlineQty += '</div>'; inlineQty += '</div>'; return inlineQty; } /** * The table that will display the differents invoices linked to the franchisee and the time period. * @return {String} inlineQty */ function dataTable() { var inlineQty = '<br></br><style>table#mpex_orders {font-size: 12px;text-align: center;border: none;}.dataTables_wrapper {font-size: 14px;}table#mpex_orders th{text-align: center;} .bolded{font-weight: bold;}</style>'; inlineQty += '<table id="mpex_orders" class="table table-responsive table-striped customer tablesorter" style="width: 100%;">'; inlineQty += '<thead style="color: white;background-color: #379E8F;">'; inlineQty += '<tr class="text-center">'; inlineQty += '</tr>'; inlineQty += '</thead>'; inlineQty += '<tbody id="result_import" class="result-import"></tbody>'; inlineQty += '</table>'; return inlineQty; } function formatDate(testDate) { //console.log('testDate: '+testDate); var responseDate = format.format({ value: testDate, type: format.Type.DATE }); //console.log('responseDate: '+responseDate); return responseDate; } /** * The Franchisee dropdown list. * @param {Number} zee_id * @return {String} `inlineQty` */ function franchiseeDropdownSection(params_zee) { var inlineQty = '<div class="form-group container zee_dropdown_section >'; inlineQty += '<div class="row">'; // Franchisee dropdown field inlineQty += '<div class="col-xs-18 zee_dropdown_div">'; inlineQty += '<div class="input-group">'; inlineQty += '<span class="input-group-addon" id="zee_dropdown_text">FRANCHISEE</span>'; inlineQty += '<select id="zee_dropdown" class="form-control zee_dropdown" required>'; inlineQty += '<option></option>'; // Load the franchisees options var zeesSearch = search.load({ id: 'customsearch_job_inv_process_zee', type: search.Type.PARTNER }); var zeesSearchResults = zeesSearch.run(); zeesSearchResults.each(function(zeesSearchResult) { var opt_zee_id = zeesSearchResult.getValue('internalid'); var opt_zee_name = zeesSearchResult.getValue('companyname'); var selected_option = ''; if (role == 1000) { zee_id = runtime.getCurrentUser().id; //Get Franchisee ID-- REMOVE TO TEST selected_option = (opt_zee_id == zee_id) ? 'selected' : ''; } if (!isNullorEmpty(params_zee)) { selected_option = (params_zee == opt_zee_id) ? 'selected' : ''; } inlineQty += '<option value="' + opt_zee_id + '" ' + selected_option + '>' + opt_zee_name + '</option>'; return true; }); inlineQty += '</select>'; inlineQty += '</div></div></div></div>'; return inlineQty; } function isNullorEmpty(strVal) { return (strVal == null || strVal == '' || strVal == 'null' || strVal == undefined || strVal == 'undefined' || strVal == '- None -'); } return { onRequest: onRequest }; } );
/** * @NApiVersion 2.x * @NScriptType ScheduledScript * @Author: Ankith Ravindran <ankithravindran> * @Date: 2021-11-05T10:16:06+11:00 * @Last modified by: ankithravindran * @Last modified time: 2021-11-11T08:52:21+11:00 */ define(['N/email', 'N/runtime', 'N/search', 'N/record'], function(email, runtime, search, record) { function execute(context) { //MPEX Customers - Commencing Today or Not Onboarded var custListCommenceTodayResults = search.load({ type: 'customer', id: 'customsearch_cust_list_commence_today' }); var count = 0; custListCommenceTodayResults.run().each(function( custListCommenceTodaySet) { count++; return true; }); if (count > 0) { var reportLink = '<a href="https://1048144.app.netsuite.com/app/site/hosting/scriptlet.nl?script=1381&deploy=1">MPEX Customers - Day 1 Onboarding Customer Service Call</a>'; //Email subject var subject = 'Day 1 - MPEX Customers Onboarding Call'; //Email Body var emailBody = 'Dear Account Manager,</br></br>Please review customers and place a customer service call. </br>'; emailBody += '<b><u>CUSTOMER COUNT</u></b>: ' + count + '</br>'; emailBody += '<b><u>LINK</u></b>: ' + reportLink; emailBody += '</br></br><b><u>Note</u></b>: If above link not clickable, please copy and paste in browser.' //Send email to the Sales Rep email.send({ author: 112209, recipients: ['belinda.urbani@mailplus.com.au'], subject: subject, body: emailBody, cc: ['luke.forbes@mailplus.com.au', 'ankith.ravindran@mailplus.com.au'] }); } } function isNullorEmpty(val) { if (val == '' || val == null) { return true; } else { return false; } } return { execute: execute }; });
942
[{"tag": "EMAIL", "value": "belinda.urbani@mailplus.com.au", "start": 1587, "end": 1617}, {"tag": "EMAIL", "value": "luke.forbes@mailplus.com.au", "start": 1692, "end": 1719}, {"tag": "EMAIL", "value": "ankith.ravindran@mailplus.com.au", "start": 1723, "end": 1755}]
true
3
/** * @NApiVersion 2.x * @NScriptType ScheduledScript * @Author: Ankith Ravindran <ankithravindran> * @Date: 2021-11-05T10:16:06+11:00 * @Last modified by: ankithravindran * @Last modified time: 2021-11-11T08:52:21+11:00 */ define(['N/email', 'N/runtime', 'N/search', 'N/record'], function(email, runtime, search, record) { function execute(context) { //MPEX Customers - Commencing Today or Not Onboarded var custListCommenceTodayResults = search.load({ type: 'customer', id: 'customsearch_cust_list_commence_today' }); var count = 0; custListCommenceTodayResults.run().each(function( custListCommenceTodaySet) { count++; return true; }); if (count > 0) { var reportLink = '<a href="https://1048144.app.netsuite.com/app/site/hosting/scriptlet.nl?script=1381&deploy=1">MPEX Customers - Day 1 Onboarding Customer Service Call</a>'; //Email subject var subject = 'Day 1 - MPEX Customers Onboarding Call'; //Email Body var emailBody = 'Dear Account Manager,</br></br>Please review customers and place a customer service call. </br>'; emailBody += '<b><u>CUSTOMER COUNT</u></b>: ' + count + '</br>'; emailBody += '<b><u>LINK</u></b>: ' + reportLink; emailBody += '</br></br><b><u>Note</u></b>: If above link not clickable, please copy and paste in browser.' //Send email to the Sales Rep email.send({ author: 112209, recipients: ['efpyi@example.com'], subject: subject, body: emailBody, cc: ['efpyi@example.com', 'envkt@example.com'] }); } } function isNullorEmpty(val) { if (val == '' || val == null) { return true; } else { return false; } } return { execute: execute }; });
true
/** * @NApiVersion 2.x * @NScriptType ScheduledScript * @Author: Ankith Ravindran <ankithravindran> * @Date: 2021-11-05T10:16:06+11:00 * @Last modified by: ankithravindran * @Last modified time: 2021-11-11T08:52:21+11:00 */ define(['N/email', 'N/runtime', 'N/search', 'N/record'], function(email, runtime, search, record) { function execute(context) { //MPEX Customers - Commencing Today or Not Onboarded var custListCommenceTodayResults = search.load({ type: 'customer', id: 'customsearch_cust_list_commence_today' }); var count = 0; custListCommenceTodayResults.run().each(function( custListCommenceTodaySet) { count++; return true; }); if (count > 0) { var reportLink = '<a href="https://1048144.app.netsuite.com/app/site/hosting/scriptlet.nl?script=1381&deploy=1">MPEX Customers - Day 1 Onboarding Customer Service Call</a>'; //Email subject var subject = 'Day 1 - MPEX Customers Onboarding Call'; //Email Body var emailBody = 'Dear Account Manager,</br></br>Please review customers and place a customer service call. </br>'; emailBody += '<b><u>CUSTOMER COUNT</u></b>: ' + count + '</br>'; emailBody += '<b><u>LINK</u></b>: ' + reportLink; emailBody += '</br></br><b><u>Note</u></b>: If above link not clickable, please copy and paste in browser.' //Send email to the Sales Rep email.send({ author: 112209, recipients: ['PI:EMAIL:efpyi@example.comEND_PI'], subject: subject, body: emailBody, cc: ['PI:EMAIL:efpyi@example.comEND_PI', 'PI:EMAIL:envkt@example.comEND_PI'] }); } } function isNullorEmpty(val) { if (val == '' || val == null) { return true; } else { return false; } } return { execute: execute }; });
/** * @NApiVersion 2.1 */ // This script sends an email with an attachment. require(['N/email', 'N/record', 'N/file'], (email, record, file) => { const senderId = -515; const recipientEmail = 'notify@myCompany.com'; let timeStamp = new Date().getUTCMilliseconds(); let recipient = record.create({ type: record.Type.CUSTOMER, isDynamic: true }); recipient.setValue({ fieldId: 'subsidiary', value: '1' }); recipient.setValue({ fieldId: 'companyname', value: 'Test Company' + timeStamp }); recipient.setValue({ fieldId: 'email', value: recipientEmail }); let recipientId = recipient.save(); let fileObj = file.load({ id: 88 }); email.send({ author: senderId, recipients: recipientId, subject: 'Test Sample Email Module', body: 'email body', attachments: [fileObj], relatedRecords: { entityId: recipientId, customRecord: { id: recordId, recordType: recordTypeId } } }); });
239
[{"tag": "EMAIL", "value": "notify@myCompany.com", "start": 205, "end": 225}]
true
1
/** * @NApiVersion 2.1 */ // This script sends an email with an attachment. require(['N/email', 'N/record', 'N/file'], (email, record, file) => { const senderId = -515; const recipientEmail = 'kenaa@example.com'; let timeStamp = new Date().getUTCMilliseconds(); let recipient = record.create({ type: record.Type.CUSTOMER, isDynamic: true }); recipient.setValue({ fieldId: 'subsidiary', value: '1' }); recipient.setValue({ fieldId: 'companyname', value: 'Test Company' + timeStamp }); recipient.setValue({ fieldId: 'email', value: recipientEmail }); let recipientId = recipient.save(); let fileObj = file.load({ id: 88 }); email.send({ author: senderId, recipients: recipientId, subject: 'Test Sample Email Module', body: 'email body', attachments: [fileObj], relatedRecords: { entityId: recipientId, customRecord: { id: recordId, recordType: recordTypeId } } }); });
true
/** * @NApiVersion 2.1 */ // This script sends an email with an attachment. require(['N/email', 'N/record', 'N/file'], (email, record, file) => { const senderId = -515; const recipientEmail = 'PI:EMAIL:kenaa@example.comEND_PI'; let timeStamp = new Date().getUTCMilliseconds(); let recipient = record.create({ type: record.Type.CUSTOMER, isDynamic: true }); recipient.setValue({ fieldId: 'subsidiary', value: '1' }); recipient.setValue({ fieldId: 'companyname', value: 'Test Company' + timeStamp }); recipient.setValue({ fieldId: 'email', value: recipientEmail }); let recipientId = recipient.save(); let fileObj = file.load({ id: 88 }); email.send({ author: senderId, recipients: recipientId, subject: 'Test Sample Email Module', body: 'email body', attachments: [fileObj], relatedRecords: { entityId: recipientId, customRecord: { id: recordId, recordType: recordTypeId } } }); });
/** * @NApiVersion 2.0 * @NScriptType Suitelet * @Author: Ankith Ravindran <ankithravindran> * @Date: 2021-11-15T07:25:50+11:00 * @Last modified by: ankithravindran * @Last modified time: 2022-02-24T15:27:26+11:00 */ define(['N/ui/serverWidget', 'N/email', 'N/runtime', 'N/search', 'N/record', 'N/http', 'N/log', 'N/redirect', 'N/format' ], function (ui, email, runtime, search, record, http, log, redirect, format) { var role = 0; var userId = 0; var zee = 0; var franchiseeName = ''; var mainContact = ''; var mainContactFName = ''; var mainContactLName = ''; var mainContactMobile = ''; var franchiseeTypeOfOwner = ''; var primaryEmail = ''; var personalEmail = ''; var dob = ''; var vaccinationStatus = ''; var franchiseeNextOfKinName = ''; var franchiseeNextOfKinMobile = ''; var franchiseeNextOfKinRelationship = ''; var franchiseeABN = ''; var franchiseeAddress = ''; var franchiseeTOLLAccountNumber = ''; var franchiseeTOLLPickupDX = ''; var franchiseeTOLLLodgementDX = ''; var franchiseeSendlePrimaryLocations = ''; var franchiseeLastMileLocations = ''; var franchiseeSendleSecondaryLocations = ''; var franchiseeListedForSale = ''; var color_array = ['blue', 'red', 'green', 'orange', 'black']; function onRequest(context) { var baseURL = 'https://system.na2.netsuite.com'; if (runtime.EnvType == "SANDBOX") { baseURL = 'https://system.sandbox.netsuite.com'; } userId = runtime.getCurrentUser().id; role = runtime.getCurrentUser().role; if (context.request.method === 'GET') { zee = context.request.parameters.zee; if (role == 1000) { zee = userId; var form = ui.createForm({ title: 'Franchisee Management Console' }); } else { var form = ui.createForm({ title: 'Franchisee Sales & Management' }); } //INITIALIZATION OF JQUERY AND BOOTSTRAP var inlineHtml = '<meta name="viewport" content="width=device-width, initial-scale=1.0"><script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"><script src="//code.jquery.com/jquery-1.11.0.min.js"></script><script src="//api.tiles.mapbox.com/mapbox.js/plugins/leaflet-omnivore/v0.3.1/leaflet-omnivore.min.js"></script><script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"><script src="//code.jquery.com/jquery-1.11.0.min.js"></script><script src="https://maps.googleapis.com/maps/api/js?key=AIzaSyA92XGDo8rx11izPYT7z2L-YPMMJ6Ih1s0&callback=initMap&libraries=places"></script><script src="https://cdnjs.cloudflare.com/ajax/libs/OverlappingMarkerSpiderfier/1.0.3/oms.min.js"></script></script><link rel="stylesheet" href="https://unpkg.com/leaflet@1.2.0/dist/leaflet.css" /><script src="https://unpkg.com/leaflet@1.2.0/dist/leaflet.js"></script><link type="text/css" rel="stylesheet" href="https://cdn.datatables.net/1.10.13/css/jquery.dataTables.min.css"><link href="//netdna.bootstrapcdn.com/bootstrap/3.3.2/css/bootstrap.min.css" rel="stylesheet"><script src="//netdna.bootstrapcdn.com/bootstrap/3.3.2/js/bootstrap.min.js"></script><link rel="stylesheet" href="https://system.na2.netsuite.com/core/media/media.nl?id=2060796&amp;c=1048144&amp;h=9ee6accfd476c9cae718&amp;_xt=.css"><script src="https://system.na2.netsuite.com/core/media/media.nl?id=2060797&amp;c=1048144&amp;h=ef2cda20731d146b5e98&amp;_xt=.js"></script><link type="text/css" rel="stylesheet" href="https://system.na2.netsuite.com/core/media/media.nl?id=2090583&amp;c=1048144&amp;h=a0ef6ac4e28f91203dfe&amp;_xt=.css"><script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.6.4/angular.min.js"></script><script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.7/angular-resource.min.js"></script><link type="text/css" rel="stylesheet" href="https://system.na2.netsuite.com/core/media/media.nl?id=2090583&amp;c=1048144&amp;h=a0ef6ac4e28f91203dfe&amp;_xt=.css"><style>.mandatory{color:red;}.clearfix:after {clear: both;content: "";display: block;height: 0;}.wrapper {vertical-align: middle;}.nav {margin-top: 40px;}.pull-right {float: right;}a, a:active {color: #212121;text-decoration: none;}a:hover {color: #999;}.arrow-steps .step {font-size: 14px;text-align: center;color: #fff;cursor: default;margin: 0 3px;padding: 10px 10px 10px 30px;float: left;position: relative;background-color: #379e8f;-webkit-user-select: none;-moz-user-select: none;-ms-user-select: none;user-select: none; transition: background-color 0.2s ease;}.arrow-steps .step:after,.arrow-steps .step:before {content: " ";position: absolute;top: 0;right: -17px;width: 0;height: 40px;border-top: 19px solid transparent;border-bottom: 17px solid transparent;border-left: 17px solid #379e8f; z-index: 2;transition: border-color 0.2s ease;}.arrow-steps .step:before {right: auto;left: 0;border-left: 17px solid #fff; z-index: 0;}.arrow-steps .step:first-child:before {border: none;}.arrow-steps .step:first-child {border-top-left-radius: 4px;border-bottom-left-radius: 4px;}.arrow-steps .step span {position: relative;}.arrow-steps .step span:before {opacity: 0;content: "βœ”";position: absolute;top: -2px;left: -20px;color: #06ac77;}.arrow-steps .step.done span:before {opacity: 1;-webkit-transition: opacity 0.3s ease 0.5s;-moz-transition: opacity 0.3s ease 0.5s;-ms-transition: opacity 0.3s ease 0.5s;transition: opacity 0.3s ease 0.5s;}.arrow-steps .step.current {color: #103d39;font-weight: bold;background-color: #fbea51;}.arrow-steps .step.current:after {border-left: 17px solid #fbea51; }.nav > li.active > a, .nav > li.active > a:focus, .nav > li.active > a:hover { background-color: #379E8F; color: #fff }.nav > li > a, .nav > li > a:focus, .nav > li > a:hover { margin-left: 5px; margin-right: 5px; border: 2px solid #379E8F; color: #379E8F; }</style>'; //ERROR SECTION inlineHtml += '<div class="container" style="padding-top: 3%;"><div id="alert" class="alert alert-danger fade in"></div></div>'; var day = getDay(); if (day == 0 || day == 6) { day = 1; //Monday } //HIDDEN FIELDS form.addField({ id: 'custpage_zee', type: ui.FieldType.TEXT, label: 'Zee' }).updateDisplayType({ displayType: ui.FieldDisplayType.HIDDEN }).defaultValue = zee; form.addField({ id: 'custpage_name', type: ui.FieldType.TEXT, label: 'Zee' }).updateDisplayType({ displayType: ui.FieldDisplayType.HIDDEN }).defaultValue = franchiseeName; form.addField({ id: 'custpage_day', type: ui.FieldType.TEXT, label: 'Day' }).updateDisplayType({ displayType: ui.FieldDisplayType.HIDDEN }).defaultValue = day; //HIDDEN FIELDS TO STORE VALUE TO BE SAVED ON THE FRANCHISE RECORD form.addField({ id: 'custpage_maincontact', type: ui.FieldType.TEXT, label: 'Day' }).updateDisplayType({ displayType: ui.FieldDisplayType.HIDDEN }).defaultValue = mainContact; form.addField({ id: 'custpage_mobilenumber', type: ui.FieldType.TEXT, label: 'Day' }).updateDisplayType({ displayType: ui.FieldDisplayType.HIDDEN }).defaultValue = mainContactMobile; form.addField({ id: 'custpage_typeofowner', type: ui.FieldType.TEXT, label: 'Day' }).updateDisplayType({ displayType: ui.FieldDisplayType.HIDDEN }).defaultValue = franchiseeTypeOfOwner; form.addField({ id: 'custpage_personalemail', type: ui.FieldType.TEXT, label: 'Day' }).updateDisplayType({ displayType: ui.FieldDisplayType.HIDDEN }).defaultValue = primaryEmail; form.addField({ id: 'custpage_dob', type: ui.FieldType.TEXT, label: 'Day' }).updateDisplayType({ displayType: ui.FieldDisplayType.HIDDEN }).defaultValue = dob; form.addField({ id: 'custpage_vaccinationstatus', type: ui.FieldType.TEXT, label: 'Day' }).updateDisplayType({ displayType: ui.FieldDisplayType.HIDDEN }).defaultValue = vaccinationStatus; form.addField({ id: 'custpage_nextofkinname', type: ui.FieldType.TEXT, label: 'Day' }).updateDisplayType({ displayType: ui.FieldDisplayType.HIDDEN }).defaultValue = franchiseeNextOfKinName; form.addField({ id: 'custpage_nextofkinmobile', type: ui.FieldType.TEXT, label: 'Day' }).updateDisplayType({ displayType: ui.FieldDisplayType.HIDDEN }).defaultValue = franchiseeNextOfKinMobile; form.addField({ id: 'custpage_nextofkinrelationship', type: ui.FieldType.TEXT, label: 'Day' }).updateDisplayType({ displayType: ui.FieldDisplayType.HIDDEN }).defaultValue = franchiseeNextOfKinRelationship; //Address Table Hidden Fields form.addField({ id: 'custpage_addressids', type: ui.FieldType.TEXT, label: 'Day' }).updateDisplayType({ displayType: ui.FieldDisplayType.HIDDEN }); form.addField({ id: 'custpage_addressids_delete', type: ui.FieldType.TEXT, label: 'Day' }).updateDisplayType({ displayType: ui.FieldDisplayType.HIDDEN }); form.addField({ id: 'custpage_address1', type: ui.FieldType.TEXT, label: 'Day' }).updateDisplayType({ displayType: ui.FieldDisplayType.HIDDEN }); form.addField({ id: 'custpage_address2', type: ui.FieldType.TEXT, label: 'Day' }).updateDisplayType({ displayType: ui.FieldDisplayType.HIDDEN }); form.addField({ id: 'custpage_suburb', type: ui.FieldType.TEXT, label: 'Day' }).updateDisplayType({ displayType: ui.FieldDisplayType.HIDDEN }); form.addField({ id: 'custpage_state', type: ui.FieldType.TEXT, label: 'Day' }).updateDisplayType({ displayType: ui.FieldDisplayType.HIDDEN }); form.addField({ id: 'custpage_postcode', type: ui.FieldType.TEXT, label: 'Day' }).updateDisplayType({ displayType: ui.FieldDisplayType.HIDDEN }); //Operator Table Hidden Fields form.addField({ id: 'custpage_operatorids', type: ui.FieldType.TEXT, label: 'Day' }).updateDisplayType({ displayType: ui.FieldDisplayType.HIDDEN }); form.addField({ id: 'custpage_operatorids_delete', type: ui.FieldType.TEXT, label: 'Day' }).updateDisplayType({ displayType: ui.FieldDisplayType.HIDDEN }); form.addField({ id: 'custpage_operatorname', type: ui.FieldType.TEXT, label: 'Day' }).updateDisplayType({ displayType: ui.FieldDisplayType.HIDDEN }); form.addField({ id: 'custpage_operatoremail', type: ui.FieldType.TEXT, label: 'Day' }).updateDisplayType({ displayType: ui.FieldDisplayType.HIDDEN }); form.addField({ id: 'custpage_operatormobile', type: ui.FieldType.TEXT, label: 'Day' }).updateDisplayType({ displayType: ui.FieldDisplayType.HIDDEN }); form.addField({ id: 'custpage_operatorrole', type: ui.FieldType.TEXT, label: 'Day' }).updateDisplayType({ displayType: ui.FieldDisplayType.HIDDEN }); form.addField({ id: 'custpage_operatoremploymentype', type: ui.FieldType.TEXT, label: 'Day' }).updateDisplayType({ displayType: ui.FieldDisplayType.HIDDEN }); form.addField({ id: 'custpage_operatordds', type: ui.FieldType.TEXT, label: 'Day' }).updateDisplayType({ displayType: ui.FieldDisplayType.HIDDEN }); form.addField({ id: 'custpage_operatorprimary', type: ui.FieldType.TEXT, label: 'Day' }).updateDisplayType({ displayType: ui.FieldDisplayType.HIDDEN }); form.addField({ id: 'custpage_operatormobiledev', type: ui.FieldType.TEXT, label: 'Day' }).updateDisplayType({ displayType: ui.FieldDisplayType.HIDDEN }); //New Operator Table Hidden Fields form.addField({ id: 'custpage_new_operatorids', type: ui.FieldType.TEXT, label: 'Day' }).updateDisplayType({ displayType: ui.FieldDisplayType.HIDDEN }); form.addField({ id: 'custpage_new_operatorids_delete', type: ui.FieldType.TEXT, label: 'Day' }).updateDisplayType({ displayType: ui.FieldDisplayType.HIDDEN }); form.addField({ id: 'custpage_new_operatorname', type: ui.FieldType.TEXT, label: 'Day' }).updateDisplayType({ displayType: ui.FieldDisplayType.HIDDEN }); form.addField({ id: 'custpage_new_operatoremail', type: ui.FieldType.TEXT, label: 'Day' }).updateDisplayType({ displayType: ui.FieldDisplayType.HIDDEN }); form.addField({ id: 'custpage_new_operatormobile', type: ui.FieldType.TEXT, label: 'Day' }).updateDisplayType({ displayType: ui.FieldDisplayType.HIDDEN }); form.addField({ id: 'custpage_new_operatorrole', type: ui.FieldType.TEXT, label: 'Day' }).updateDisplayType({ displayType: ui.FieldDisplayType.HIDDEN }); form.addField({ id: 'custpage_new_operatoremploymentype', type: ui.FieldType.TEXT, label: 'Day' }).updateDisplayType({ displayType: ui.FieldDisplayType.HIDDEN }); form.addField({ id: 'custpage_new_operatordds', type: ui.FieldType.TEXT, label: 'Day' }).updateDisplayType({ displayType: ui.FieldDisplayType.HIDDEN }); form.addField({ id: 'custpage_new_operatorprimary', type: ui.FieldType.TEXT, label: 'Day' }).updateDisplayType({ displayType: ui.FieldDisplayType.HIDDEN }); form.addField({ id: 'custpage_new_operatormobiledev', type: ui.FieldType.TEXT, label: 'Day' }).updateDisplayType({ displayType: ui.FieldDisplayType.HIDDEN }); //Fleet Table Hidden Details form.addField({ id: 'custpage_fleetids', type: ui.FieldType.TEXT, label: 'Day' }).updateDisplayType({ displayType: ui.FieldDisplayType.HIDDEN }); form.addField({ id: 'custpage_fleetids_delete', type: ui.FieldType.TEXT, label: 'Day' }).updateDisplayType({ displayType: ui.FieldDisplayType.HIDDEN }); form.addField({ id: 'custpage_fleetrego', type: ui.FieldType.TEXT, label: 'Day' }).updateDisplayType({ displayType: ui.FieldDisplayType.HIDDEN }); form.addField({ id: 'custpage_fleetmodel', type: ui.FieldType.TEXT, label: 'Day' }).updateDisplayType({ displayType: ui.FieldDisplayType.HIDDEN }); form.addField({ id: 'custpage_fleetmake', type: ui.FieldType.TEXT, label: 'Day' }).updateDisplayType({ displayType: ui.FieldDisplayType.HIDDEN }); form.addField({ id: 'custpage_fleetcolor', type: ui.FieldType.TEXT, label: 'Day' }).updateDisplayType({ displayType: ui.FieldDisplayType.HIDDEN }); form.addField({ id: 'custpage_fleetyear', type: ui.FieldType.TEXT, label: 'Day' }).updateDisplayType({ displayType: ui.FieldDisplayType.HIDDEN }); form.addField({ id: 'custpage_fleetsignage', type: ui.FieldType.TEXT, label: 'Day' }).updateDisplayType({ displayType: ui.FieldDisplayType.HIDDEN }); form.addField({ id: 'custpage_caregocage', type: ui.FieldType.TEXT, label: 'Day' }).updateDisplayType({ displayType: ui.FieldDisplayType.HIDDEN }); form.addField({ id: 'custpage_owner', type: ui.FieldType.TEXT, label: 'Day' }).updateDisplayType({ displayType: ui.FieldDisplayType.HIDDEN }); form.addField({ id: 'custpage_operator', type: ui.FieldType.TEXT, label: 'Day' }).updateDisplayType({ displayType: ui.FieldDisplayType.HIDDEN }); //New Fleet DETAILS form.addField({ id: 'custpage_new_fleetids', type: ui.FieldType.TEXT, label: 'Day' }).updateDisplayType({ displayType: ui.FieldDisplayType.HIDDEN }); form.addField({ id: 'custpage_new_fleetids_delete', type: ui.FieldType.TEXT, label: 'Day' }).updateDisplayType({ displayType: ui.FieldDisplayType.HIDDEN }); form.addField({ id: 'custpage_new_fleetrego', type: ui.FieldType.TEXT, label: 'Day' }).updateDisplayType({ displayType: ui.FieldDisplayType.HIDDEN }); form.addField({ id: 'custpage_new_fleetmodel', type: ui.FieldType.TEXT, label: 'Day' }).updateDisplayType({ displayType: ui.FieldDisplayType.HIDDEN }); form.addField({ id: 'custpage_new_fleetmake', type: ui.FieldType.TEXT, label: 'Day' }).updateDisplayType({ displayType: ui.FieldDisplayType.HIDDEN }); form.addField({ id: 'custpage_new_fleetcolor', type: ui.FieldType.TEXT, label: 'Day' }).updateDisplayType({ displayType: ui.FieldDisplayType.HIDDEN }); form.addField({ id: 'custpage_new_fleetyear', type: ui.FieldType.TEXT, label: 'Day' }).updateDisplayType({ displayType: ui.FieldDisplayType.HIDDEN }); form.addField({ id: 'custpage_new_fleetsignage', type: ui.FieldType.TEXT, label: 'Day' }).updateDisplayType({ displayType: ui.FieldDisplayType.HIDDEN }); form.addField({ id: 'custpage_new_caregocage', type: ui.FieldType.TEXT, label: 'Day' }).updateDisplayType({ displayType: ui.FieldDisplayType.HIDDEN }); form.addField({ id: 'custpage_new_owner', type: ui.FieldType.TEXT, label: 'Day' }).updateDisplayType({ displayType: ui.FieldDisplayType.HIDDEN }); form.addField({ id: 'custpage_new_operator', type: ui.FieldType.TEXT, label: 'Day' }).updateDisplayType({ displayType: ui.FieldDisplayType.HIDDEN }); form.addField({ id: 'custpage_listforsale', type: ui.FieldType.TEXT, label: 'Day' }).updateDisplayType({ displayType: ui.FieldDisplayType.HIDDEN }).defaultValue = 'F'; inlineHtml += '<div class="se-pre-con"></div><div ng-app="myApp" ng-controller="myCtrl">'; inlineHtml += spacing() if (role != 1000) { inlineHtml += progressBar() inlineHtml += line() inlineHtml += spacing() inlineHtml += selectFranchiseeSection(zee) inlineHtml += spacing() } if (zee != 0 && !isNullorEmpty(zee)) { //NetSuite Search: APP - Operator Load var searchOperators = search.load({ id: 'customsearch_app_operator_load', type: 'customrecord_operator' }); if (!isNullorEmpty(zee)) { searchOperators.filters.push(search.createFilter({ name: 'internalid', join: 'CUSTRECORD_OPERATOR_FRANCHISEE2', operator: search.Operator.IS, values: zee })); } var resultSetOperators = searchOperators.run(); inlineHtml += tabSection(zee, role, resultSetOperators) inlineHtml += spacing() inlineHtml += line() inlineHtml += mainButtons(role) } form.addField({ id: 'preview_table', label: 'inlinehtml', type: 'inlinehtml' }).updateLayoutType({ layoutType: ui.FieldLayoutType.STARTROW }).defaultValue = inlineHtml; form.addSubmitButton({ label: 'SAVE' }); form.clientScriptFileId = 5334734 context.response.writePage(form); } else { var zeeId = parseInt(context.request.parameters.custpage_zee); var franchiseeMainContact = context.request.parameters.custpage_maincontact; var franchiseeMobileNumber = context.request.parameters.custpage_mobilenumber; var franchiseeTypeOfOwner = context.request.parameters.custpage_typeofowner; var franchiseePersonalEmail = context.request.parameters.custpage_personalemail; var FranchiseeDOB = context.request.parameters.custpage_dob; var franchiseeVaccinationStatus = context.request.parameters.custpage_vaccinationstatus; var franchiseeNextOfKinName = context.request.parameters.custpage_nextofkinname; var franchiseeNextOfKinMobile = context.request.parameters.custpage_nextofkinmobile; var franchiseeNextOfKinRelationship = context.request.parameters.custpage_nextofkinrelationship; var addressids = context.request.parameters.custpage_addressids; var addressids_delete = context.request.parameters.custpage_addressids_delete; var address1 = context.request.parameters.custpage_address1; var address2 = context.request.parameters.custpage_address2; var suburb = context.request.parameters.custpage_suburb; var state = context.request.parameters.custpage_state; var postcode = context.request.parameters.custpage_postcode; var listforsale = context.request.parameters.custpage_listforsale; log.debug({ title: 'addressids', details: addressids }) var addressidsArrays = addressids.split(','); var addressidsdeleteArrays = addressids_delete.split(','); var address1Arrays = address1.split(','); var address2Arrays = address2.split(','); var suburbArrays = suburb.split(','); var stateArrays = state.split(','); var postcodeArrays = postcode.split(','); var operatorids = context.request.parameters.custpage_operatorids; var operatorids_delete = context.request.parameters.custpage_operatorids_delete; var operatorname = context.request.parameters.custpage_operatorname; var operatoremail = context.request.parameters.custpage_operatoremail; var operatormobile = context.request.parameters.custpage_operatormobile; var operatorrole = context.request.parameters.custpage_operatorrole; var operatoremploymentype = context.request.parameters.custpage_operatoremploymentype; var operatordds = context.request.parameters.custpage_operatordds; var operatorprimary = context.request.parameters.custpage_operatorprimary; var operatormobiledev = context.request.parameters.custpage_operatormobiledev; var operatoridsArrys = operatorids.split(',') var operatoridsdeleteArrys = operatorids_delete.split(',') var operatornameArrys = operatorname.split(',') var operatoremailArrys = operatoremail.split(',') var operatormobileArrys = operatormobile.split(',') var operatorroleArrys = operatorrole.split(',') var operatoremploymentypeArrys = operatoremploymentype.split(',') var operatorddsArrys = operatordds.split(',') var operatorprimaryArrys = operatorprimary.split(',') var operatormobiledevArrys = operatormobiledev.split(',') //New operator var newoperatorids = context.request.parameters.custpage_new_operatorids; var newoperatorids_delete = context.request.parameters.custpage_new_operatorids_delete; var newoperatorname = context.request.parameters.custpage_new_operatorname; var newoperatoremail = context.request.parameters.custpage_new_operatoremail; var newoperatormobile = context.request.parameters.custpage_new_operatormobile; var newoperatorrole = context.request.parameters.custpage_new_operatorrole; var newoperatoremploymentype = context.request.parameters.custpage_new_operatoremploymentype; var newoperatordds = context.request.parameters.custpage_new_operatordds; var newoperatorprimary = context.request.parameters.custpage_new_operatorprimary; var newoperatormobiledev = context.request.parameters.custpage_new_operatormobiledev; var newoperatoridsArrys = newoperatorids.split(',') var newoperatoridsdeleteArrys = newoperatorids_delete.split(',') var newoperatornameArrys = newoperatorname.split(',') var newoperatoremailArrys = newoperatoremail.split(',') var newoperatormobileArrys = newoperatormobile.split(',') var newoperatorroleArrys = newoperatorrole.split(',') var newoperatoremploymentypeArrys = newoperatoremploymentype.split( ',') var newoperatorddsArrys = newoperatordds.split(',') var newoperatorprimaryArrys = newoperatorprimary.split(',') var newoperatormobiledevArrys = newoperatormobiledev.split(',') var fleetids = context.request.parameters.custpage_fleetids; var fleetids_delete = context.request.parameters.custpage_fleetids_delete; var fleetrego = context.request.parameters.custpage_fleetrego; var fleetmodel = context.request.parameters.custpage_fleetmodel; var fleetmake = context.request.parameters.custpage_fleetmake; var fleetcolor = context.request.parameters.custpage_fleetcolor; var fleetyear = context.request.parameters.custpage_fleetyear; var fleetsignage = context.request.parameters.custpage_fleetsignage; var caregocage = context.request.parameters.custpage_caregocage; var owner = context.request.parameters.custpage_owner; var operator = context.request.parameters.custpage_operator; var fleetidsArrys = fleetids.split(',') var fleetidsdeleteArrys = fleetids_delete.split(',') var fleetregoArrys = fleetrego.split(',') var fleetmodelArrys = fleetmodel.split(',') var fleetmakeArrys = fleetmake.split(',') var fleetcolorArrys = fleetcolor.split(',') var fleetyearArrys = fleetyear.split(',') var fleetsignageArrys = fleetsignage.split(',') var caregocageArrys = caregocage.split(',') var ownerArrys = owner.split(',') var operatorArrys = operator.split(',') //New Fleet details var newfleetids = context.request.parameters.custpage_new_fleetids; var newfleetids_delete = context.request.parameters.custpage_new_fleetids_delete; var newfleetrego = context.request.parameters.custpage_new_fleetrego; var newfleetmodel = context.request.parameters.custpage_new_fleetmodel; var newfleetmake = context.request.parameters.custpage_new_fleetmake; var newfleetcolor = context.request.parameters.custpage_new_fleetcolor; var newfleetyear = context.request.parameters.custpage_new_fleetyear; var newfleetsignage = context.request.parameters.custpage_new_fleetsignage; var newcaregocage = context.request.parameters.custpage_new_caregocage; var newowner = context.request.parameters.custpage_new_owner; var newoperator = context.request.parameters.custpage_new_operator; var newfleetidsArrys = newfleetids.split(',') var newfleetidsdeleteArrys = newfleetids_delete.split(',') var newfleetregoArrys = newfleetrego.split(',') var newfleetmodelArrys = newfleetmodel.split(',') var newfleetmakeArrys = newfleetmake.split(',') var newfleetcolorArrys = newfleetcolor.split(',') var newfleetyearArrys = newfleetyear.split(',') var newfleetsignageArrys = newfleetsignage.split(',') var newcaregocageArrys = newcaregocage.split(',') var newownerArrys = newowner.split(',') var newoperatorArrys = newoperator.split(',') //Load Partner Record & Save the main details var zeeRecord = record.load({ type: record.Type.PARTNER, id: zeeId }); var zeeName = zeeRecord.getValue({ fieldId: 'companyname' }); zeeRecord.setValue({ fieldId: 'custentity3', value: franchiseeMainContact }) zeeRecord.setValue({ fieldId: 'custentity2', value: franchiseeMobileNumber }) if (franchiseeTypeOfOwner != 0) { zeeRecord.setValue({ fieldId: 'custentity_type_of_owner', value: franchiseeTypeOfOwner }) } zeeRecord.setValue({ fieldId: 'custentity_personal_email_address', value: franchiseePersonalEmail }); log.debug({ title: 'dobArray', details: dobArray }) if (!isNullorEmpty(dobArray)) { var dobArray = FranchiseeDOB.split('-') var dobString = dobArray[1] + '/' + dobArray[2] + '/' + dobArray[0] zeeRecord.setValue({ fieldId: 'custentity_zee_dob', value: getDate(dobString) }) } if (franchiseeVaccinationStatus != 0) { zeeRecord.setValue({ fieldId: 'custentity_vacc_status', value: franchiseeVaccinationStatus }) } zeeRecord.setValue({ fieldId: 'custentity_kin_name', value: franchiseeNextOfKinName }) zeeRecord.setValue({ fieldId: 'custentity_kin_mobile', value: franchiseeNextOfKinMobile }) if (franchiseeNextOfKinRelationship != 0) { zeeRecord.setValue({ fieldId: 'custentity_kin_relationship', value: franchiseeNextOfKinRelationship }) } if (listforsale == 'T') { zeeRecord.setValue({ fieldId: 'custentity_listed_for_sale', value: 1 }); zeeRecord.setValue({ fieldId: 'custentity_date_listed_for_sale', value: getDateToday() }); var email_body = ' Franchisee NS ID: ' + zeeId + '</br> Franchisee Name: ' + zeeName + '</br> Date: ' + getDateToday() + '</br> Franchisee NS ID: ' + zeeRecordId; email.send({ author: 112209, recipients: ['michael.mcdaid@mailplus.com.au'], subject: 'Listed for Sale - ' + zeeName + ' Franchisee', body: email_body, cc: ['ankith.ravindran@mailplus.com.au'] }); } log.debug({ title: 'isDynamic', details: zeeRecord.isDynamic }) //ADD/UPDATE ADDRESS if (!isNullorEmptyExcZero(addressidsArrays)) { for (var x = 0; x < addressidsArrays.length; x++) { log.debug({ title: 'addressidsArrays[x]', details: addressidsArrays[x] }) if (addressidsArrays[x] == 0 || addressidsArrays[x] == '0') { log.debug({ title: 'inside new' }) zeeRecord.insertLine({ sublistId: 'addressbook', line: 0 }) var lineIndex = 0; } else { var lineIndex = zeeRecord.findSublistLineWithValue({ sublistId: 'addressbook', fieldId: 'internalid', value: addressidsArrays[x] }); log.debug({ title: "lineIndex", details: lineIndex }); } var updateAddress = zeeRecord.getSublistSubrecord({ sublistId: 'addressbook', fieldId: 'addressbookaddress', line: lineIndex }) updateAddress.setValue({ fieldId: 'country', value: 'AU' }); updateAddress.setValue({ fieldId: 'addressee', value: franchiseeMainContact }); updateAddress.setValue({ fieldId: 'addr1', value: address1Arrays[x] }); updateAddress.setValue({ fieldId: 'addr2', value: address2Arrays[x] }); updateAddress.setValue({ fieldId: 'city', value: suburbArrays[x] }); updateAddress.setValue({ fieldId: 'state', value: stateArrays[x] }); updateAddress.setValue({ fieldId: 'zip', value: postcodeArrays[x] }); updateAddress.setValue({ fieldId: 'isresidential', value: 'T' }); } } if (!isNullorEmpty(addressidsdeleteArrays)) { for (var x = 0; x < addressidsdeleteArrays.length; x++) { var lineIndex = zeeRecord.findSublistLineWithValue({ sublistId: 'addressbook', fieldId: 'internalid', value: addressidsdeleteArrays[x] }); var deleteAddress = zeeRecord.removeSublistSubrecord({ sublistId: 'addressbook', fieldId: 'addressbookaddress', line: lineIndex }) // // deleteAddress.setValue({ // fieldId: 'country', // value: 'AU' // }); } } var zeeRecordId = zeeRecord.save({ ignoreMandatoryFields: true }); //ADD/UPDATE OPREATOR DETAILS if (!isNullorEmpty(operatoridsArrys)) { for (var y = 0; y < operatoridsArrys.length; y++) { var operatorRecord = record.load({ type: 'customrecord_operator', id: operatoridsArrys[y] }); var spliName = operatornameArrys[y].split(" "); operatorRecord.setValue({ fieldId: 'custrecord_operator_givennames', value: spliName[0] }) operatorRecord.setValue({ fieldId: 'custrecord_operator_surname', value: spliName[1] }) operatorRecord.setValue({ fieldId: 'name', value: operatornameArrys[y] }) operatorRecord.setValue({ fieldId: 'custrecord_operator_email', value: operatoremailArrys[y] }) operatorRecord.setValue({ fieldId: 'custrecord_operator_date_reviewed', value: getDateToday() }) operatorRecord.setValue({ fieldId: 'custrecord_operator_phone', value: operatormobileArrys[y] }) operatorRecord.setValue({ fieldId: 'custrecord_operator_role', value: operatorroleArrys[y] }) operatorRecord.setValue({ fieldId: 'custrecord_operator_employment', value: operatoremploymentypeArrys[y] }) operatorRecord.setValue({ fieldId: 'custrecord_dds_operator', value: operatorddsArrys[y] }) operatorRecord.setValue({ fieldId: 'custrecord_primary_operator', value: operatorprimaryArrys[y] }) if (!isNullorEmpty(operatormobiledevArrys[y])) { operatorRecord.setValue({ fieldId: 'custrecord_operator_mobdev_platform', value: operatormobiledevArrys[y] }) } operatorRecord.save() } } //NEW OPERATOR DETAILS if (!isNullorEmpty(newoperatoridsArrys)) { log.debug({ title: 'newoperatoridsArrys.length', details: newoperatoridsArrys.length }) for (var y = 0; y < newoperatoridsArrys.length; y++) { var operatorRecord = record.create({ type: 'customrecord_operator' }); if (!isNullorEmpty(newoperatornameArrys[y])) { var spliName = newoperatornameArrys[y].split(" "); operatorRecord.setValue({ fieldId: 'custrecord_operator_givennames', value: spliName[0] }) if (isNullorEmpty(spliName[1])) { operatorRecord.setValue({ fieldId: 'custrecord_operator_surname', value: spliName[0] }) } else { operatorRecord.setValue({ fieldId: 'custrecord_operator_surname', value: spliName[1] }) } } operatorRecord.setValue({ fieldId: 'name', value: newoperatornameArrys[y] }) operatorRecord.setValue({ fieldId: 'custrecord_operator_email', value: newoperatoremailArrys[y] }) operatorRecord.setValue({ fieldId: 'custrecord_operator_franchisee', value: zeeRecordId }) operatorRecord.setValue({ fieldId: 'custrecord_operator_franchisee2', value: zeeRecordId }) operatorRecord.setValue({ fieldId: 'custrecord_operator_salutation', value: 1 }) operatorRecord.setValue({ fieldId: 'custrecord_operator_status', value: 4 }) operatorRecord.setValue({ fieldId: 'custrecord_operator_app_date_link_sent', value: getDateToday() }) operatorRecord.setValue({ fieldId: 'custrecord_operator_date_reviewed', value: getDateToday() }) operatorRecord.setValue({ fieldId: 'custrecord_operator_phone', value: newoperatormobileArrys[y] }) operatorRecord.setValue({ fieldId: 'custrecord_operator_role', value: newoperatorroleArrys[y] }) operatorRecord.setValue({ fieldId: 'custrecord_operator_employment', value: newoperatoremploymentypeArrys[y] }) operatorRecord.setValue({ fieldId: 'custrecord_dds_operator', value: newoperatorddsArrys[y] }) operatorRecord.setValue({ fieldId: 'custrecord_primary_operator', value: newoperatorprimaryArrys[y] }) if (!isNullorEmpty(operatormobiledevArrys[y])) { operatorRecord.setValue({ fieldId: 'custrecord_operator_mobdev_platform', value: newoperatormobiledevArrys[y] }) } var operatorIdNew = operatorRecord.save() var email_body = ' New Operator NS ID: ' + operatorIdNew + '</br> New Operator Name: ' + newoperatornameArrys[y] + '</br> New Operator Email: ' + newoperatoremailArrys[y] + '</br> New Operator Mobile: ' + newoperatormobileArrys[y] + '</br> Franchisee NS ID: ' + zeeRecordId; email.send({ author: 112209, recipients: ['mailplussupport@protechly.com'], subject: 'MP Operator Access - New Operator', body: email_body, cc: ['raine.giderson@mailplus.com.au', 'ankith.ravindran@mailplus.com.au', 'fiona.harrison@mailplus.com.au', 'popie.popie@mailplus.com.au' ] }); } } if (!isNullorEmpty(operatoridsdeleteArrys)) { for (var y = 0; y < operatoridsdeleteArrys.length; y++) { var deleteOperatorRecord = record.load({ type: 'customrecord_operator', id: operatoridsdeleteArrys[y] }); deleteOperatorRecord.setValue({ fieldId: 'isinactive', value: true }) deleteOperatorRecord.setValue({ fieldId: 'custrecord_operator_status', value: 3 }) var getOperatorEmail = deleteOperatorRecord.getValue({ fieldId: 'custrecord_operator_email' }) var getOperatorName = deleteOperatorRecord.getValue({ fieldId: 'name' }) deleteOperatorRecord.save(); var email_body = ' Delete Operator NS ID: ' + operatoridsdeleteArrys[y] + '</br> Franchisee NS ID: ' + zeeRecordId + '</br> Operator Name: ' + getOperatorName + '</br> Operator Email: ' + getOperatorEmail; email.send({ author: 112209, recipients: ['mailplussupport@protechly.com'], subject: 'MP Operator Access - Delete/Inactive Operator', body: email_body, cc: ['raine.giderson@mailplus.com.au', 'ankith.ravindran@mailplus.com.au', 'fiona.harrison@mailplus.com.au', 'popie.popie@mailplus.com.au' ] }); } } //ADD/EDIT FLEET DETAILS if (!isNullorEmpty(fleetidsArrys)) { for (var w = 0; w < fleetidsArrys.length; w++) { var vehicleRecord = record.load({ type: 'customrecord_vehicle', id: fleetidsArrys[w] }); vehicleRecord.setValue({ fieldId: 'name', value: fleetregoArrys[w] }) vehicleRecord.setValue({ fieldId: 'custrecord_vehicle_model_text', value: fleetmodelArrys[w] }) vehicleRecord.setValue({ fieldId: 'custrecord_vehicle_make', value: fleetmakeArrys[w] }) vehicleRecord.setValue({ fieldId: 'custrecord_vehicle_colour', value: fleetcolorArrys[w] }) vehicleRecord.setValue({ fieldId: 'custrecord_vehicle_year', value: fleetyearArrys[w] }) if (fleetsignageArrys[w] == 1 || fleetsignageArrys[w] == '1') { vehicleRecord.setValue({ fieldId: 'custrecord_vehicle_signage', value: true }) } vehicleRecord.setValue({ fieldId: 'custrecord_cargo_cage', value: caregocageArrys[w] }) vehicleRecord.setValue({ fieldId: 'custrecord_vehicle_owner', value: ownerArrys[w] }) vehicleRecord.setValue({ fieldId: 'custrecord_vehicle_date_reviewed', value: getDateToday() }) var newFleetID = vehicleRecord.save() //SAVE FLEET DETAILS ON THE OPERATOR RECORD var operatorRecord = record.load({ type: 'customrecord_operator', id: operatorArrys[w] }); operatorRecord.setValue({ fieldId: 'custrecord_operator_vehicle', value: newFleetID }) operatorRecord.save(); } } //CREATE NEW FLEET DETAILS if (!isNullorEmpty(newfleetidsArrys)) { for (var w = 0; w < newfleetidsArrys.length; w++) { var vehicleRecord = record.create({ type: 'customrecord_vehicle' }); vehicleRecord.setValue({ fieldId: 'name', value: newfleetregoArrys[w] }) vehicleRecord.setValue({ fieldId: 'custrecord_vehicle_franchisee', value: zeeRecordId }) vehicleRecord.setValue({ fieldId: 'custrecord_vehicle_model_text', value: newfleetmodelArrys[w] }) vehicleRecord.setValue({ fieldId: 'custrecord_vehicle_make', value: newfleetmakeArrys[w] }) vehicleRecord.setValue({ fieldId: 'custrecord_vehicle_colour', value: newfleetcolorArrys[w] }) vehicleRecord.setValue({ fieldId: 'custrecord_vehicle_year', value: newfleetyearArrys[w] }) if (newfleetsignageArrys[w] == 1 || newfleetsignageArrys[w] == '1') { vehicleRecord.setValue({ fieldId: 'custrecord_vehicle_signage', value: true }) } vehicleRecord.setValue({ fieldId: 'custrecord_cargo_cage', value: newcaregocageArrys[w] }) vehicleRecord.setValue({ fieldId: 'custrecord_vehicle_owner', value: newownerArrys[w] }) vehicleRecord.setValue({ fieldId: 'custrecord_vehicle_date_reviewed', value: getDateToday() }) var newFleetID = vehicleRecord.save() //SAVE FLEET DETAILS ON THE OPERATOR RECORD var operatorRecord = record.load({ type: 'customrecord_operator', id: newoperatorArrys[w] }); operatorRecord.setValue({ fieldId: 'custrecord_operator_vehicle', value: newFleetID }) operatorRecord.save() } } if (!isNullorEmpty(fleetidsdeleteArrys)) { for (var y = 0; y < fleetidsdeleteArrys.length; y++) { var deleteFleetRecord = record.load({ type: 'customrecord_vehicle', id: fleetidsdeleteArrys[y] }); deleteFleetRecord.setValue({ fieldId: 'isinactive', value: true }) deleteFleetRecord.save() } } redirect.toSuitelet({ scriptId: 'customscript_sl2_zee_management_console', deploymentId: 'customdeploy1', }); } } /* * PURPOSE : ADDS SPACING * PARAMS : * RETURNS : INLINEHTML * NOTES : */ function spacing() { var inlineHtml = '<div class="form-group spacing_section">'; inlineHtml += '<div class="row">'; inlineHtml += '</div>'; inlineHtml += '</div>'; return inlineHtml; } /* * PURPOSE : ADDS HORIZONTAL LINE TO DIVIDE SECTIONS * PARAMS : * RETURNS : INLINEHTML * NOTES : */ function line() { var inlineHtml = '<hr style="height:5px; width:100%; border-width:0; color:red; background-color:#fff">' return inlineHtml } /* * PURPOSE : PROGRESS BAR AT THE TOP OF THE PAGE TO SHOW AT WHAT STAGE THE FRANCHISE SALES & MANAGEMENT WORKFLOW IS AT. ONLY SEEN TO THE HEADOFFICE USERS NOT AVAILABLE TO THE FRANCHISEES * PARAMS : * RETURNS : INLINEHTML * NOTES : */ function progressBar() { var inlineHtml = '<div class="form-group progress_section">'; inlineHtml += '<div class="row">'; inlineHtml += '<div class=""> <div class="wrapper"> <div class="arrow-steps clearfix"><div class="step"> <span>SALES PROCESS</span> </div><div class="step"> <span>FINANCIALS</span> </div><div class="step"> <span>PRESENTATIONS & INTERVIEW</span> </div><div class="step"> <span>SETTLEMENT</span> </div><div class="step"> <span><span class="glyphicon glyphicon-ok" style="color: #fff"></span>TRAINING</span> </div><div class="step"> <span>FRANCHISE AGREEMENTS</span> </div><div class="step"> <span>NETSUITE SETUP</span> </div><div class="step"> <span>ONBOARDING</span> </div><div class="step current"> <span>UPDATE/EDIT DETAILS</span> </div></div>'; // inlineHtml += '<div class="nav clearfix"><a href="#" class="prev">Previous</a><a href="#" class="next pull-right">Next</a></div></div></div>' inlineHtml += '</div></div>' inlineHtml += '</div>'; inlineHtml += '</div>'; return inlineHtml } /* * PURPOSE : BUTTONS SECTION AT THE END OF THE PAGE. * PARAMS : USER ROLE * RETURNS : INLINEHTML * NOTES : */ function mainButtons(role) { var inlineHtml = '' if (role != 1000) { inlineHtml += '<div class="form-group container zee_available_buttons_section">'; inlineHtml += '<div class="row">'; inlineHtml += '<div class="col-xs-6 updateDetails"><input type="button" value="UPDATE DETAILS" class="form-control btn btn-primary" id="updateDetails" /></div>' if (franchiseeListedForSale != 1) { inlineHtml += '<div class="col-xs-6 listForSale"><input type="button" value="LIST FOR SALE" class="form-control btn btn-success" id="listForSale" /></div>' } else { inlineHtml += '<div class="col-xs-6 listForSale"><input type="button" value="LISTED FOR SALE" class="form-control btn btn-success" id="" disabled/></div>' } inlineHtml += '</div>'; inlineHtml += '</div>'; inlineHtml += '<div class="form-group container zee_admin_section">'; inlineHtml += '<div class="row">'; inlineHtml += '<div class="col-xs-3 sendEmail"><input type="button" value="Send Email" class="form-control btn btn-primary" id="sendEmail" /></div>' inlineHtml += '<div class="col-xs-3 sendSMS"><input type="button" value="Send SMS" class="form-control btn btn-primary" id="sendSMS" /></div>' inlineHtml += '<div class="col-xs-3 breachNotice"><input type="button" value="Breach Notice" class="form-control btn btn-warning" id="breachNotice" /></div>' inlineHtml += '<div class="col-xs-3 termination"><input type="button" value="Termination" class="form-control btn btn-danger" id="termination" /></div>' inlineHtml += '</div>'; inlineHtml += '</div>'; } else { inlineHtml += '<div class="form-group container zee_available_buttons_section">'; inlineHtml += '<div class="row">'; inlineHtml += '<div class="col-xs-6 updateDetails"><input type="button" value="UPDATE DETAILS" class="form-control btn btn-primary" id="updateDetails" /></div>' if (franchiseeListedForSale != 1) { inlineHtml += '<div class="col-xs-6 listForSale"><input type="button" value="LIST FOR SALE" class="form-control btn btn-success" id="listForSale" /></div>' } else { inlineHtml += '<div class="col-xs-6 listForSale"><input type="button" value="LISTED FOR SALE" class="form-control btn btn-success" id="" disabled/></div>' } inlineHtml += '</div>'; inlineHtml += '</div>'; } return inlineHtml } /* * PURPOSE : CREATES THE TAB SECTION FOR THE PAGE * PARAMS : ZEE ID, USER ROLE & OPERATOR SEARCH RESULT * RETURNS : INLINEHTML * NOTES : */ function tabSection(zee, role, resultSetOperators) { //TAB HEADERS var inlineHtml = '<div>' inlineHtml += '<div style="width: 95%; margin:auto; margin-bottom: 30px"><ul class="nav nav-tabs nav-justified main-tabs-sections " style="margin:0%;border-bottom-color: #fbea50 !important;border-bottom-width: 5px !important;border-bottom-style: solid;">'; inlineHtml += '<li role="presentation" class="active"><a data-toggle="tab" href="#zeeDetails"><b>MAIN DETAILS</b></a></li>'; inlineHtml += '<li role="presentation" class=""><a data-toggle="tab" href="#operatorDetails"><b>OPERATION DETAILS</b></a></li>'; inlineHtml += '<li role="presentation" class=""><a data-toggle="tab" href="#tollMPEX"><b>PICKUP & LODGEMENT LOCATIONS</b></a></li>'; if (role != 1000) { inlineHtml += '<li role="presentation" class=""><a data-toggle="tab" href="#zeeAgreements"><b>AGREEMENTS</b></a></li>'; inlineHtml += '<li role="presentation" class=""><a data-toggle="tab" href="#breachDetails"><b>BREACH & TERMINATION DETAILS</b></a></li>'; } inlineHtml += '</ul></div>'; //TAB CONTENT inlineHtml += '<div class="tab-content">'; inlineHtml += '<div role="tabpanel" class="tab-pane active" id="zeeDetails">'; inlineHtml += franchiseeMainDetails(zee) inlineHtml += franchiseeNextOfKin() inlineHtml += '</div>'; inlineHtml += '<div role="tabpanel" class="tab-pane " id="zeeAgreements">'; inlineHtml += franchiseeAgreements(zee, role) inlineHtml += '</div>'; inlineHtml += '<div role="tabpanel" class="tab-pane " id="operatorDetails">'; inlineHtml += franchiseeOperatorDetails(zee, resultSetOperators) inlineHtml += franchiseeFleetDetails(zee, resultSetOperators) inlineHtml += '</div>'; inlineHtml += '<div role="tabpanel" class="tab-pane " id="tollMPEX">'; inlineHtml += franchiseeTOLLMPEX() inlineHtml += franchiseeAdhoc() inlineHtml += '</div>'; //BREACH NOTICE & TERMINATION ONLY SEEN BY HEAD OFFICE USERS if (role != 1000) { inlineHtml += '<div role="tabpanel" class="tab-pane " id="breachDetails">'; inlineHtml += franchiseeBreachDetails() inlineHtml += franchiseeTerminationDetails() inlineHtml += '</div>'; } inlineHtml += '</div></div>'; return inlineHtml; } /* * PURPOSE : SELECT FRANCHISEE TO UPDATE. ONLY AVAILABLE FOR HEADOFFICE USERS * PARAMS : ZEE ID * RETURNS : INLINEHTML * NOTES : */ function selectFranchiseeSection(zee) { var inlineHtml = '<div class="form-group container zee_section">'; inlineHtml += '<div class="row">'; inlineHtml += '<div class="col-xs-12 heading1"><h4><span class="label label-default col-xs-12" style="background-color: #103D39;">SELECT FRANCHISEE</span></h4></div>'; inlineHtml += '</div>'; inlineHtml += '</div>'; inlineHtml += '<div class="form-group container zee_select_section">'; inlineHtml += '<div class="row">'; inlineHtml += '<div class="col-xs-12 zee"><div class="input-group"><span class="input-group-addon" id="zee_text">FRANCHISEE <span class="mandatory">*</span></span><select id="zee_dropdown" class="form-control zee" ><option value=0></option>'; //NetSuite Search: Zee Management Console - Franchisees var searchZees = search.load({ id: 'customsearch_zee_management_console_zee', type: 'partner' }); var resultSetZees = searchZees.run(); resultSetZees.each(function (searchResultZees) { zeeId = searchResultZees.getValue('internalid'); franchiseeName = searchResultZees.getValue('companyname'); mainContact = searchResultZees.getValue('custentity3'); mainContactFName = searchResultZees.getValue( 'custentity_franchisee_firstname'); mainContactLName = searchResultZees.getValue( 'custentity_franchisee_lastname'); primaryEmail = searchResultZees.getValue('email'); personalEmail = searchResultZees.getValue( 'custentity_personal_email_address'); mainContactMobile = searchResultZees.getValue( 'custentity2'); franchiseeABN = searchResultZees.getValue( 'custentity_abn_franchiserecord'); franchiseeAddress = searchResultZees.getValue( 'shipaddress'); if (zeeId == zee) { inlineHtml += '<option value="' + zeeId + '" selected>' + franchiseeName + '</option>'; } else { inlineHtml += '<option value="' + zeeId + '">' + franchiseeName + '</option>'; } return true; }); inlineHtml += '</select></div></div>'; inlineHtml += '</div>'; inlineHtml += '</div>'; return inlineHtml; } /* * PURPOSE : FRANCHISE MAIN DETAILS TAB * PARAMS : ZEE ID * RETURNS : INLINEHTML * NOTES : */ function franchiseeMainDetails(zee) { //NetSuite Search: Zee Management Console - Franchisees var searchZees = search.load({ id: 'customsearch_zee_management_console_zee', type: 'partner' }); if (!isNullorEmpty(zee)) { searchZees.filters.push(search.createFilter({ name: 'internalid', join: null, operator: search.Operator.IS, values: zee })); } var resultSetZees = searchZees.run(); resultSetZees.each(function (searchResultZees) { zeeId = searchResultZees.getValue('internalid'); franchiseeName = searchResultZees.getValue('companyname'); mainContact = searchResultZees.getValue('custentity3'); mainContactFName = searchResultZees.getValue( 'custentity_franchisee_firstname'); mainContactLName = searchResultZees.getValue( 'custentity_franchisee_lastname'); primaryEmail = searchResultZees.getValue('email'); personalEmail = searchResultZees.getValue( 'custentity_personal_email_address'); mainContactMobile = searchResultZees.getValue( 'custentity2'); franchiseeABN = searchResultZees.getValue( 'custentity_abn_franchiserecord'); franchiseeAddress = searchResultZees.getValue( 'shipaddress'); franchiseeTOLLAccountNumber = searchResultZees.getValue( 'custentity_toll_acc_number'); franchiseeTOLLPickupDX = searchResultZees.getText( 'custentity__toll_pickup_dx_no'); franchiseeTOLLLodgementDX = searchResultZees.getText( 'custentity_toll_lodge_dx_no'); franchiseeSendlePrimaryLocations = searchResultZees.getText( 'custentity_sendle_hubbed_locations'); franchiseeLastMileLocations = searchResultZees.getText( 'custentity_lastmile_suburb'); franchiseeSendleSecondaryLocations = searchResultZees.getText( 'custentity_sendle_hubbed_location_sec'); franchiseeTypeOfOwner = searchResultZees.getValue( 'custentity_type_of_owner'); vaccinationStatus = searchResultZees.getValue( 'custentity_vacc_status'); dob = searchResultZees.getValue( 'custentity_zee_dob'); personalEmail = searchResultZees.getValue( 'custentity_personal_email_address'); franchiseeNextOfKinMobile = searchResultZees.getValue( 'custentity_kin_mobile'); franchiseeNextOfKinName = searchResultZees.getValue( 'custentity_kin_name'); franchiseeNextOfKinRelationship = searchResultZees.getValue( 'custentity_kin_relationship'); franchiseeListedForSale = searchResultZees.getValue( 'custentity_listed_for_sale'); return true; }); //NetSuite Search: SALESP - Addresses var searched_addresses = search.load({ id: 'customsearch_salesp_address', type: 'customer' }); searched_addresses.filters.push(search.createFilter({ name: 'internalid', operator: search.Operator.ANYOF, values: zee })); resultSetAddresses = searched_addresses.run(); var inlineHtml = '<div class="form-group container">'; inlineHtml += '<div class="row">'; inlineHtml += '<div class="col-xs-12 heading1"><h4><span class="label label-default col-xs-12" style="background-color: #103D39;">FRANCHISEE DETAILS</span></h4></div>'; inlineHtml += '</div>'; inlineHtml += '</div>'; inlineHtml += '<div class="form-group container">'; inlineHtml += '<div class="row">'; inlineHtml += '<div class="col-xs-12 name_section"><div class="input-group"><span class="input-group-addon">FRANCHISE NAME</span><input id="franchiseeName" class="form-control franchiseeName" value="' + franchiseeName + '" readonly/></div></div>'; inlineHtml += '</div>'; inlineHtml += '</div>'; inlineHtml += '<div class="form-group container">'; inlineHtml += '<div class="row">'; inlineHtml += '<div class="col-xs-6 name_section"><div class="input-group"><span class="input-group-addon">MAIN CONTACT</span><input id="mainContact" data-old="' + mainContact + '" class="form-control mainContact" value="' + mainContact + '" /></div></div>'; inlineHtml += '<div class="col-xs-6 name_section"><div class="input-group"><span class="input-group-addon">MOBILE NUMBER <span class="mandatory">*</span></span><input id="mainContactMobile" class="form-control mainContact" value="' + mainContactMobile + '" data-old="' + mainContactMobile + '"/></div></div>'; inlineHtml += '</div>'; inlineHtml += '</div>'; inlineHtml += '<div class="form-group container">'; inlineHtml += '<div class="row">'; inlineHtml += '<div class="col-xs-6 zee"><div class="input-group"><span class="input-group-addon" id="zee_text">TYPE OF OWNER <span class="mandatory">*</span></span><select id="franchiseeTypeOfOwner" class="form-control franchiseeTypeOfOwner" data-old="' + franchiseeTypeOfOwner + '">'; if (franchiseeTypeOfOwner == 0 || isNullorEmpty(franchiseeTypeOfOwner)) { inlineHtml += '<option value=0></option><option value=1>COMPANY OWNED</option><option value=2>INVESTOR</option><option value=3>Owner / Operator</option>'; } else if (franchiseeTypeOfOwner == 1) { inlineHtml += '<option value=0></option><option value=1 selected>COMPANY OWNED</option><option value=2>INVESTOR</option><option value=3>Owner / Operator</option>'; } else if (franchiseeTypeOfOwner == 2) { inlineHtml += '<option value=0></option><option value=1>COMPANY OWNED</option><option value=2 selected>INVESTOR</option><option value=3>Owner / Operator</option>'; } else if (franchiseeTypeOfOwner == 3) { inlineHtml += '<option value=0></option><option value=1>COMPANY OWNED</option><option value=2>INVESTOR</option><option value=3 selected>Owner / Operator</option>'; } inlineHtml += '</select></div></div>'; inlineHtml += '<div class="col-xs-6 name_section"><div class="input-group"><span class="input-group-addon">ABN</span><input id="franchiseeABN" class="form-control franchiseeABN" readonly value="' + franchiseeABN + '" /></div></div>'; inlineHtml += '</div>'; inlineHtml += '</div>'; inlineHtml += '<div class="form-group container">'; inlineHtml += '<div class="row">'; inlineHtml += '<div class="col-xs-6 name_section"><div class="input-group"><span class="input-group-addon">PRIMARY EMAIL</span><input id="primaryEmail" class="form-control primaryEmail" value="' + primaryEmail + '" readonly/></div></div>'; inlineHtml += '<div class="col-xs-6 name_section"><div class="input-group"><span class="input-group-addon">PERSONAL EMAIL <span class="mandatory">*</span></span><input id="personalEmail" class="form-control personalEmail" value="' + personalEmail + '" data-old="' + personalEmail + '" /></div></div>'; inlineHtml += '</div>'; inlineHtml += '</div>'; inlineHtml += '<div class="form-group container company_name_section">'; inlineHtml += '<div class="row">'; var dobArray = dob.split('/'); if (dobArray[1] < 10) { dobArray[1] = '0' + dobArray[1]; } if (dobArray[0] < 10) { dobArray[0] = '0' + dobArray[0]; } var formattedDOB = dobArray[2] + '-' + dobArray[1] + '-' + dobArray[0] inlineHtml += '<div class="col-xs-6 name_section"><div class="input-group"><span class="input-group-addon">DATE OF BIRTH <span class="mandatory">*</span></span><input id="dob" type="date" class="form-control dob" value="' + formattedDOB + '" data-old="' + formattedDOB + '"/></div></div>'; inlineHtml += '<div class="col-xs-6 zee"><div class="input-group"><span class="input-group-addon" id="zee_text">VACCINATION STATUS <span class="mandatory">*</span></span><select id="vaccinationStatus" class="form-control vaccinationStatus" data-old="' + vaccinationStatus + '">'; if (vaccinationStatus == 1) { inlineHtml += '<option value=0></option><option value=1 selected>YES</option><option value=2>NO</option>'; } else if (vaccinationStatus == 2) { inlineHtml += '<option value=0></option><option value=1>YES</option><option value=2 selected>NO</option>'; } else { inlineHtml += '<option value=0 selected></option><option value=1>YES</option><option value=2>NO</option>'; } inlineHtml += '</select></div></div>'; inlineHtml += '</div>'; inlineHtml += '</div>'; inlineHtml += '<div class="form-group container">'; inlineHtml += '<div class="row">'; inlineHtml += '<div class="col-xs-12 heading1"><h4><span class="label label-default col-xs-12" style="background-color: #103D39;">ADDRESS DETAILS</span></h4></div>'; inlineHtml += '</div>'; inlineHtml += '</div>'; //HIDDEN SECTION TO ADD/EDIT ADDRESS DETAILS inlineHtml += '<div class="form-group container row_address1 hide">' inlineHtml += '<div class="row">'; inlineHtml += '<input id="internalid" value="" type="hidden"/>' inlineHtml += '<div class="col-xs-6 address1_section"><div class="input-group"><span class="input-group-addon">UNIT/LEVEL/SUITE</span><input id="address1" class="form-control address1" /></div></div>'; inlineHtml += '<div class="col-xs-6 address2_section"><div class="input-group"><span class="input-group-addon">STREET NO. & NAME <span class="mandatory">*</span></span><input id="address2" class="form-control address2" /></div></div>'; inlineHtml += '</div>'; inlineHtml += '</div>'; inlineHtml += '<div class="form-group container city_state_postcode hide">' inlineHtml += '<div class="row">'; inlineHtml += '<div class="col-xs-6"><div class="input-group"><span class="input-group-addon">CITY</span><input id="city" readonly class="form-control city" /></div></div>'; inlineHtml += '<div class="col-xs-3"><div class="input-group"><span class="input-group-addon">STATE</span><input id="state" readonly class="form-control state" /></div></div>'; inlineHtml += '<div class="col-xs-3 post_code_section"><div class="input-group"><span class="input-group-addon">POSTCODE</span><input id="postcode" readonly class="form-control postcode" /></div></div>'; inlineHtml += '</div>'; inlineHtml += '</div>'; inlineHtml += '<div class="form-group container saveaddress_section hide">'; inlineHtml += '<div class="row">'; inlineHtml += '<div class="col-xs-2 "></div>'; inlineHtml += '<div class="col-xs-4 reviewaddress"><input type="button" value="SAVE ADDRESSES" class="form-control btn btn-success" id="saveAddress" /></div>'; inlineHtml += '<div class="col-xs-4 cancel"><input type="button" value="CANCEL" class="form-control btn btn-secondary" id="cancel" /></div>'; inlineHtml += '<div class="col-xs-2 "></div>'; inlineHtml += '</div>'; inlineHtml += '</div>'; //ADDRESS TABLE inlineHtml += addressContactsSection(resultSetAddresses); return inlineHtml } /* * PURPOSE : LIST OF FRANCHISEE AGREEMENTS RELATED TO THE ZEE * PARAMS : ZEE ID & USER ROLE * RETURNS : INLINEHTML * NOTES : */ function franchiseeAgreements(zee, role) { //NetSuite Search: Zee Agreement - Search var searchZeeAgreements = search.load({ id: 'customsearch_zee_agree_search', type: 'customrecord_fr_agreements' }); if (!isNullorEmpty(zee)) { searchZeeAgreements.filters.push(search.createFilter({ name: 'internalid', join: 'CUSTRECORD_FR_AGREEMENT_FRANCHISEE', operator: search.Operator.IS, values: zee })); } var resultSetZeeAgreements = searchZeeAgreements.run(); var inlineHtml = '<div class="form-group container">'; inlineHtml += '<div class="row">'; inlineHtml += '<div class="col-xs-12 heading1"><h4><span class="label label-default col-xs-12" style="background-color: #103D39;">FRANCHISE AGREEMENTS</span></h4></div>'; inlineHtml += '</div>'; inlineHtml += '</div>'; inlineHtml += '<div class="form-group container">'; inlineHtml += '<div class="row">'; inlineHtml += '<style>table#zeeAgreementsTable {color: #103D39 !important; font-size: 12px;text-align: center;border: none;}.dataTables_wrapper {font-size: 14px;}table#zeeAgreementsTable th{text-align: center;} .bolded{font-weight: bold;}</style>'; inlineHtml += '<table id="zeeAgreementsTable" class="table table-responsive table-striped zeeAgreementsTable tablesorter" style="width: 100%;border: 1px solid #103d39;">'; inlineHtml += '<thead style="color: white;background-color: #379E8F;font-weight: bold;">'; inlineHtml += '<tr class="text-center">'; //ABILITY TO ADD/EDIT ONLY FOR HEADOFFICE USERS if (role != 1000) { inlineHtml += '<td>LINK</td>' } inlineHtml += '<td>NS ID</td>' inlineHtml += '<td>NAME</td>' inlineHtml += '<td>COMMENCEMENT DATE</td>' inlineHtml += '<td>EXPIRY DATE</td>' inlineHtml += '<td>ULTIMATE EXPIRY DATE</td>' inlineHtml += '<td>RENEWAL TERMS</td>' inlineHtml += '<td>AGREEMENT</td>' inlineHtml += '<td>AGREEMENT STATUS</td>' inlineHtml += '</tr>'; inlineHtml += '</thead>'; inlineHtml += '<tbody id="resultOperatorTable" class="">'; resultSetZeeAgreements.each(function (searchResultZeeAgreements) { zeeAgreementID = searchResultZeeAgreements.getValue('internalid'); zeeAgreementName = searchResultZeeAgreements.getValue('name'); zeeAgreementCommDate = searchResultZeeAgreements.getValue( 'custrecord_fr_agreement_comm_date'); zeeAgreementExpiryDate = searchResultZeeAgreements.getValue( 'custrecord_fr_agreement_expiry_date'); zeeAgreementUltExpiryDate = searchResultZeeAgreements.getValue( 'custrecord_fr_agreement_ult_expiry_date'); zeeAgreementStatus = searchResultZeeAgreements.getText( 'custrecord_fr_agreement_status'); zeeAgreementYearsExtended = searchResultZeeAgreements.getValue( 'custrecord_fr_agreement_yrs_extended'); zeeAgreementDeed = searchResultZeeAgreements.getValue( 'custrecord_fr_agreement_deed'); 1182 inlineHtml += '<tr>' //SHOW EDIT/DELETE LINKS TO ONLY HEADOFFICE USERS if (role != 1000) { inlineHtml += '<td><button class="form-control btn btn-xs btn-primary glyphicon glyphicon-pencil" style="cursor: not-allowed !important;width: fit-content;"><a data-id="' + zeeAgreementID + '" class="editOperator" style="cursor: pointer !important;color: white;"></a></button> <button class="form-control btn btn-xs btn-danger glyphicon glyphicon-trash" style="cursor: not-allowed !important;width: fit-content;"><a data-id="' + zeeAgreementID + '" class="deleteOperator" style="cursor: pointer !important;color: white;"></a></button></td>' } inlineHtml += '<td>' + zeeAgreementID + '</td>' inlineHtml += '<td><b><a href="https://1048144.app.netsuite.com/app/common/custom/custrecordentry.nl?rectype=384&id=' + zeeAgreementID + '">' + zeeAgreementName + '</a></b></td>' inlineHtml += '<td>' + zeeAgreementCommDate + '</td>' inlineHtml += '<td>' + zeeAgreementExpiryDate + '</td>' inlineHtml += '<td>' + zeeAgreementUltExpiryDate + '</td>' inlineHtml += '<td>' + zeeAgreementYearsExtended + '</td>' inlineHtml += '<td>' + zeeAgreementDeed + '</td>' inlineHtml += '<td>' + zeeAgreementStatus + '</td>' inlineHtml += '</tr>'; return true; }); inlineHtml += '</tbody></table>'; inlineHtml += '</div>'; inlineHtml += '</div>'; //ABILITY TO CREATE NEW AGREEMENT TO ONLY HEADOFFICE USERS if (role != 1000) { inlineHtml += franchiseeNewAgreement() } return inlineHtml; } /* * PURPOSE : TOLL MPEX RELATED DATA. * PARAMS : * RETURNS : INLINEHTML * NOTES : */ function franchiseeTOLLMPEX() { var inlineHtml = '<div class="form-group container">'; inlineHtml += '<div class="row">'; inlineHtml += '<div class="col-xs-12 heading1"><h4><span class="label label-default col-xs-12" style="background-color: #103D39;">TOLL - MPEX</span></h4></div>'; inlineHtml += '</div>'; inlineHtml += '</div>'; inlineHtml += '<div class="form-group container">'; inlineHtml += '<div class="row">'; inlineHtml += '<div class="col-xs-6 name_section"><div class="input-group"><span class="input-group-addon">TOLL Account Number</span><input id="franchiseeTOLLAccountNumber" class="form-control franchiseeTOLLAccountNumber" value="' + franchiseeTOLLAccountNumber + '" readonly/></div></div>'; inlineHtml += '</div>'; inlineHtml += '</div>'; inlineHtml += '<div class="form-group container">'; inlineHtml += '<div class="row">'; inlineHtml += '<div class="col-xs-6 name_section"><div class="input-group"><span class="input-group-addon">TOLL Pickup DX </span><input id="franchiseeTOLLPickupDX" class="form-control franchiseeTOLLPickupDX" readonly value="' + franchiseeTOLLPickupDX + '" /></div></div>'; inlineHtml += '<div class="col-xs-6 name_section"><div class="input-group"><span class="input-group-addon">TOLL Lodgement DX </span><input id="franchiseeTOLLLodgementDX" class="form-control franchiseeTOLLLodgementDX" readonly value="' + franchiseeTOLLLodgementDX + '" /></div></div>'; inlineHtml += '</div>'; inlineHtml += '</div>'; return inlineHtml; } /* * PURPOSE : FRANCHISE NEXT OF KIN DETAILS * PARAMS : * RETURNS : INLINEHTML * NOTES : */ function franchiseeNextOfKin() { var inlineHtml = '<div class="form-group container">'; inlineHtml += '<div class="row">'; inlineHtml += '<div class="col-xs-12 heading1"><h4><span class="label label-default col-xs-12" style="background-color: #103D39;">NEXT OF KIN</span></h4></div>'; inlineHtml += '</div>'; inlineHtml += '</div>'; inlineHtml += '<div class="form-group container">'; inlineHtml += '<div class="row">'; inlineHtml += '<div class="col-xs-4 name_section"><div class="input-group"><span class="input-group-addon">NAME <span class="mandatory">*</span></span><input id="franchiseeNextOfKinName" type="text" class="form-control franchiseeNextOfKinName" value="' + franchiseeNextOfKinName + '" data-old="' + franchiseeNextOfKinName + '"/></div></div>'; inlineHtml += '<div class="col-xs-3 name_section"><div class="input-group"><span class="input-group-addon">MOBILE NUMBER <span class="mandatory">*</span></span><input id="franchiseeNextOfKinMobile" class="form-control franchiseeNextOfKinMobile" value="' + franchiseeNextOfKinMobile + '" data-old="' + franchiseeNextOfKinMobile + '"/></div></div>'; inlineHtml += '<div class="col-xs-5 zee"><div class="input-group"><span class="input-group-addon" id="zee_text">RELATIONSHIP <span class="mandatory">*</span></span><select id="franchiseeNextOfKinRelationship" class="form-control franchiseeNextOfKinRelationship" data-old="' + franchiseeNextOfKinRelationship + '"><option value=0></option>'; /* Brother 5 Daughter 7 Father 1 Friend 9 Mother 2 Other 10 Partner 4 Sister 8 Son 6 Spouse 3 */ log.debug({ title: 'franchiseeNextOfKinRelationship', details: franchiseeNextOfKinRelationship }) switch (parseInt(franchiseeNextOfKinRelationship)) { case 5: inlineHtml += '<option value=0></option>'; inlineHtml += '<option value=5 selected>Brother</option>'; inlineHtml += '<option value=7>Daughter</option>'; inlineHtml += '<option value=1>Father</option>'; inlineHtml += '<option value=9>Friend</option>'; inlineHtml += '<option value=2>Mother</option>'; inlineHtml += '<option value=4>Partner</option>'; inlineHtml += '<option value=8>Sister</option>'; inlineHtml += '<option value=6>Son</option>'; inlineHtml += '<option value=3>Spouse</option>'; inlineHtml += '<option value=10>Other</option>'; break; case 7: inlineHtml += '<option value=0></option>'; inlineHtml += '<option value=5>Brother</option>'; inlineHtml += '<option value=7 selected>Daughter</option>'; inlineHtml += '<option value=1>Father</option>'; inlineHtml += '<option value=9>Friend</option>'; inlineHtml += '<option value=2>Mother</option>'; inlineHtml += '<option value=4>Partner</option>'; inlineHtml += '<option value=8>Sister</option>'; inlineHtml += '<option value=6>Son</option>'; inlineHtml += '<option value=3>Spouse</option>'; inlineHtml += '<option value=10>Other</option>'; break; case 1: inlineHtml += '<option value=0></option>'; inlineHtml += '<option value=5>Brother</option>'; inlineHtml += '<option value=7>Daughter</option>'; inlineHtml += '<option value=1 selected>Father</option>'; inlineHtml += '<option value=9>Friend</option>'; inlineHtml += '<option value=2>Mother</option>'; inlineHtml += '<option value=4>Partner</option>'; inlineHtml += '<option value=8>Sister</option>'; inlineHtml += '<option value=6>Son</option>'; inlineHtml += '<option value=3>Spouse</option>'; inlineHtml += '<option value=10>Other</option>'; break; case 9: inlineHtml += '<option value=0></option>'; inlineHtml += '<option value=5>Brother</option>'; inlineHtml += '<option value=7>Daughter</option>'; inlineHtml += '<option value=1>Father</option>'; inlineHtml += '<option value=9 selected>Friend</option>'; inlineHtml += '<option value=2>Mother</option>'; inlineHtml += '<option value=4>Partner</option>'; inlineHtml += '<option value=8>Sister</option>'; inlineHtml += '<option value=6>Son</option>'; inlineHtml += '<option value=3>Spouse</option>'; inlineHtml += '<option value=10>Other</option>'; break; case 2: inlineHtml += '<option value=0></option>'; inlineHtml += '<option value=5>Brother</option>'; inlineHtml += '<option value=7>Daughter</option>'; inlineHtml += '<option value=1>Father</option>'; inlineHtml += '<option value=9>Friend</option>'; inlineHtml += '<option value=2 selected>Mother</option>'; inlineHtml += '<option value=4>Partner</option>'; inlineHtml += '<option value=8>Sister</option>'; inlineHtml += '<option value=6>Son</option>'; inlineHtml += '<option value=3>Spouse</option>'; inlineHtml += '<option value=10>Other</option>'; break; case 10: inlineHtml += '<option value=0></option>'; inlineHtml += '<option value=5>Brother</option>'; inlineHtml += '<option value=7>Daughter</option>'; inlineHtml += '<option value=1>Father</option>'; inlineHtml += '<option value=9>Friend</option>'; inlineHtml += '<option value=2>Mother</option>'; inlineHtml += '<option value=4>Partner</option>'; inlineHtml += '<option value=8>Sister</option>'; inlineHtml += '<option value=6>Son</option>'; inlineHtml += '<option value=3>Spouse</option>'; inlineHtml += '<option value=10 selected>Other</option>'; break; case 4: inlineHtml += '<option value=0></option>'; inlineHtml += '<option value=5>Brother</option>'; inlineHtml += '<option value=7>Daughter</option>'; inlineHtml += '<option value=1>Father</option>'; inlineHtml += '<option value=9>Friend</option>'; inlineHtml += '<option value=2>Mother</option>'; inlineHtml += '<option value=4 selected>Partner</option>'; inlineHtml += '<option value=8>Sister</option>'; inlineHtml += '<option value=6>Son</option>'; inlineHtml += '<option value=3>Spouse</option>'; inlineHtml += '<option value=10>Other</option>'; break; case 8: inlineHtml += '<option value=0></option>'; inlineHtml += '<option value=5>Brother</option>'; inlineHtml += '<option value=7>Daughter</option>'; inlineHtml += '<option value=1>Father</option>'; inlineHtml += '<option value=9>Friend</option>'; inlineHtml += '<option value=2>Mother</option>'; inlineHtml += '<option value=4>Partner</option>'; inlineHtml += '<option value=8 selected>Sister</option>'; inlineHtml += '<option value=6>Son</option>'; inlineHtml += '<option value=3>Spouse</option>'; inlineHtml += '<option value=10>Other</option>'; break; case 6: inlineHtml += '<option value=0></option>'; inlineHtml += '<option value=5>Brother</option>'; inlineHtml += '<option value=7>Daughter</option>'; inlineHtml += '<option value=1>Father</option>'; inlineHtml += '<option value=9>Friend</option>'; inlineHtml += '<option value=2>Mother</option>'; inlineHtml += '<option value=4>Partner</option>'; inlineHtml += '<option value=8>Sister</option>'; inlineHtml += '<option value=6 selected>Son</option>'; inlineHtml += '<option value=3>Spouse</option>'; inlineHtml += '<option value=10>Other</option>'; break; case 3: inlineHtml += '<option value=0></option>'; inlineHtml += '<option value=5>Brother</option>'; inlineHtml += '<option value=7>Daughter</option>'; inlineHtml += '<option value=1>Father</option>'; inlineHtml += '<option value=9>Friend</option>'; inlineHtml += '<option value=2>Mother</option>'; inlineHtml += '<option value=4>Partner</option>'; inlineHtml += '<option value=8>Sister</option>'; inlineHtml += '<option value=6>Son</option>'; inlineHtml += '<option value=3 selected>Spouse</option>'; inlineHtml += '<option value=10>Other</option>'; break; default: inlineHtml += '<option value=0 selected></option>'; inlineHtml += '<option value=5>Brother</option>'; inlineHtml += '<option value=7>Daughter</option>'; inlineHtml += '<option value=1>Father</option>'; inlineHtml += '<option value=9>Friend</option>'; inlineHtml += '<option value=2>Mother</option>'; inlineHtml += '<option value=4>Partner</option>'; inlineHtml += '<option value=8>Sister</option>'; inlineHtml += '<option value=6>Son</option>'; inlineHtml += '<option value=3>Spouse</option>'; inlineHtml += '<option value=10>Other</option>'; break; } inlineHtml += '</select></div></div>'; inlineHtml += '</div>'; inlineHtml += '</div>'; return inlineHtml; } /* * PURPOSE : FRANCHISEE FIRST & LAST MILE DETAILS * PARAMS : * RETURNS : INLINEHTML * NOTES : */ function franchiseeAdhoc() { var inlineHtml = '<div class="form-group container">'; inlineHtml += '<div class="row">'; inlineHtml += '<div class="col-xs-12 heading1"><h4><span class="label label-default col-xs-12" style="background-color: #103D39;">ADHOC</span></h4></div>'; inlineHtml += '</div>'; inlineHtml += '</div>'; inlineHtml += '<div class="form-group container">'; inlineHtml += '<div class="row">'; inlineHtml += '<div class="col-xs-6 name_section"><div class="input-group"><span class="input-group-addon">First Mile Primary Location</span><input id="franchiseeSendlePrimaryLocations" class="form-control franchiseeSendlePrimaryLocations" value="' + franchiseeSendlePrimaryLocations + '" readonly/></div></div>'; inlineHtml += '<div class="col-xs-6 name_section"><div class="input-group"><span class="input-group-addon">First Mile Secondary Location</span><input id="franchiseeSendleSecondaryLocations" class="form-control franchiseeSendleSecondaryLocations" value="' + franchiseeSendleSecondaryLocations + '" readonly/></div></div>'; inlineHtml += '</div>'; inlineHtml += '</div>'; //ABILITY TO ADD/EDIT FIRST MILE SUBURBS inlineHtml += franchiseeAddEditFirstMile() inlineHtml += '<div class="form-group container">'; inlineHtml += '<div class="row">'; inlineHtml += '<div class="col-xs-12 name_section"><div class="input-group"><span class="input-group-addon">Last Mile Primary Location</span><input id="franchiseeLastMileLocations" class="form-control franchiseeLastMileLocations" value="' + franchiseeLastMileLocations + '" readonly/></div></div>'; inlineHtml += '</div>'; inlineHtml += '</div>'; //BUTTON TO ADD/EDIT LAST MILE SUBURBS inlineHtml += franchiseeAddEditLastMile() return inlineHtml; } /* * PURPOSE : BUTTON TO REDIRECT PAGE TO FRANCHISE SERVICE NETWORK * PARAMS : * RETURNS : INLINEHTML * NOTES : */ function franchiseeServiceNetwork() { var inlineHtml = '<div class="form-group container company_name_section">'; inlineHtml += '<div class="row">'; inlineHtml += '<div class="col-xs-3 heading1"></div>' inlineHtml += '<div class="col-xs-6 heading1"><input type="button" value="Your Franchise Service Network" class="form-control btn btn-primary" id="serviceNetwork" style="background-color: #287587;"/></div>' inlineHtml += '<div class="col-xs-3 heading1"></div>' inlineHtml += '</div>'; inlineHtml += '</div>'; return inlineHtml } /* * PURPOSE : BUTTON TO REDIRECT PAGE TO CREATION OF NEW AGREEMENT * PARAMS : * RETURNS : INLINEHTML * NOTES : */ function franchiseeNewAgreement() { var inlineHtml = '<div class="form-group container company_name_section">'; inlineHtml += '<div class="row">'; inlineHtml += '<div class="col-xs-3 heading1"></div>' inlineHtml += '<div class="col-xs-6 heading1"><input type="button" value="New Agreement" class="form-control btn btn-primary" id="newAgreement" style="background-color: #287587;"/></div>' inlineHtml += '<div class="col-xs-3 heading1"></div>' inlineHtml += '</div>'; inlineHtml += '</div>'; return inlineHtml } /* * PURPOSE : BUTTON TO ADD NEW OPERATOR TO THE TABLE * PARAMS : * RETURNS : INLINEHTML * NOTES : */ function franchiseeAddOperator() { var inlineHtml = '<div class="form-group container company_name_section">'; inlineHtml += '<div class="row">'; inlineHtml += '<div class="col-xs-3 heading1"></div>' inlineHtml += '<div class="col-xs-6 heading1"><input type="button" value="Add New Operator" class="form-control btn btn-primary" id="addOperator" style="background-color: #287587;"/></div>' inlineHtml += '<div class="col-xs-3 heading1"></div>' inlineHtml += '</div>'; inlineHtml += '</div>'; return inlineHtml } /* * PURPOSE : BUTTON TO ADD NEW VEHICLE TO THE TABLE * PARAMS : * RETURNS : INLINEHTML * NOTES : */ function franchiseeAddFleet() { var inlineHtml = '<div class="form-group container company_name_section">'; inlineHtml += '<div class="row">'; inlineHtml += '<div class="col-xs-3 heading1"></div>' inlineHtml += '<div class="col-xs-6 heading1"><input type="button" value="Add New Fleet" class="form-control btn btn-primary" id="addFleet" style="background-color: #287587;"/></div>' inlineHtml += '<div class="col-xs-3 heading1"></div>' inlineHtml += '</div>'; inlineHtml += '</div>'; return inlineHtml } /* * PURPOSE : BUTTON TO REDIRECT PAGE TO FIRST MILE SUBURB SELECTION * PARAMS : * RETURNS : INLINEHTML * NOTES : */ function franchiseeAddEditFirstMile() { var inlineHtml = '<div class="form-group container company_name_section">'; inlineHtml += '<div class="row">'; inlineHtml += '<div class="col-xs-3 heading1"></div>' inlineHtml += '<div class="col-xs-6 heading1"><input type="button" value="Add/Edit First-Mile Suburbs" class="form-control btn btn-primary" id="firstMile" style="background-color: #287587;"/></div>' inlineHtml += '<div class="col-xs-3 heading1"></div>' inlineHtml += '</div>'; inlineHtml += '</div>'; return inlineHtml } /* * PURPOSE : BUTTON TO REDIRECT PAGE TO LAST MILE SUBURB SELECTION * PARAMS : * RETURNS : INLINEHTML * NOTES : */ function franchiseeAddEditLastMile() { var inlineHtml = '<div class="form-group container company_name_section">'; inlineHtml += '<div class="row">'; inlineHtml += '<div class="col-xs-3 heading1"></div>' inlineHtml += '<div class="col-xs-6 heading1"><input type="button" value="Add/Edit Last-Mile Suburbs" class="form-control btn btn-primary" id="lastMile" style="background-color: #287587;"/></div>' inlineHtml += '<div class="col-xs-3 heading1"></div>' inlineHtml += '</div>'; inlineHtml += '</div>'; return inlineHtml } /* * PURPOSE : Autogenerates function contract comments * PARAMS : functio - * RETURNS : - * NOTES : */ function franchiseeOperatorDetails(zee, resultSetOperators) { var operatorID = ''; var operatorName = ''; var operatorPhone = ''; var operatorEmail = ''; var operatorEmploymentType = ''; var operatorRole = ''; var operatorMobileDev = ''; var operatorDDS = ''; var operatorPrimaryOperator = ''; var inlineHtml = '<div class="form-group container">'; inlineHtml += '<div class="row">'; inlineHtml += '<div class="col-xs-12 heading1"><h4><span class="label label-default col-xs-12" style="background-color: #103D39;">SERVICE NETWORK</span></h4></div>'; inlineHtml += '</div>'; inlineHtml += '</div>'; var directionsPanel_html = ''; var print_section = ''; //show the directionsPanel only if one zee selected directionsPanel_html += '<div class="col-sm-6 " id="directionsPanel" style="height:500px; overflow:auto"></div>'; print_section += '</br><div class="row print_section hide"><div class="col-xs-10"></div><div class="col-xs-2"><input type="button" class="btn btn-info" id="printDirections" value="PRINT DIRECTIONS" style="width: 100%;"/></div></div></div>'; inlineHtml += '</br>'; inlineHtml += '<div class="container map_section "><div class="row">'; inlineHtml += '<div class="col-sm-12" id="map" style="height: 500px"><div id="loader"><img src="https://1048144.app.netsuite.com/core/media/media.nl?id=2089999&c=1048144&h=e0aef405c22b65dfe546" alt="loader" /></div></div>'; inlineHtml += '<div id="legend">'; inlineHtml += '<div class="hide legend_icons" style="background-color: rgb(255, 255, 255);box-shadow: rgba(0, 0, 0, 0.3) 0px 1px 4px -1px;border-radius: 2px;left: 0px;margin-left: 5px;padding: 3px;"><div><svg height="23" width="32"><path d="M12 2C8.13 2 5 5.13 5 9c0 5.25 7 13 7 13s7-7.75 7-13c0-3.87-3.13-7-7-7z" stroke="black" fill="#575756"/></svg><span style="font-family: sans-serif;">Non Customer Location</span></div><div><svg height="23" width="32"><path d="M12 2C8.13 2 5 5.13 5 9c0 5.25 7 13 7 13s7-7.75 7-13c0-3.87-3.13-7-7-7z" stroke="black" fill="#008675"/></svg><span style="font-family: sans-serif;">Customer Location</span></div>'; for (i = 0; i < 1; i++) { inlineHtml += '<div><svg height="15" width="32"><line x1="2" y1="10" x2="25" y2="10" style="stroke:' + color_array[i] + ';stroke-width:2" /></svg><span style="font-family: sans-serif;">' + franchiseeName + '</span></div>'; } inlineHtml += '</div>'; inlineHtml += '<div style="background-color: rgb(255, 255, 255);box-shadow: rgba(0, 0, 0, 0.3) 0px 1px 4px -1px;border-radius: 2px;left: 0px;margin-left: 5px;padding: 3px;"><input class="form-control" type="textarea" placeholder="Territory" id="zee_territory"/></div>'; inlineHtml += '</div>'; // inlineHtml += directionsPanel_html; inlineHtml += '</div>'; inlineHtml += print_section; inlineHtml += franchiseeServiceNetwork(); inlineHtml += '<div class="form-group container">'; inlineHtml += '<div class="row">'; inlineHtml += '<div class="col-xs-12 heading1"><h4><span class="label label-default col-xs-12" style="background-color: #103D39;">OPERATOR DETAILS</span></h4></div>'; inlineHtml += '</div>'; inlineHtml += '</div>'; inlineHtml += '<div class="form-group container row_operator_details hide">' inlineHtml += '<div class="row">'; inlineHtml += '<input id="operatorInternalId" value="" type="hidden"/>' inlineHtml += '<div class="col-xs-3 operatorName_section"><div class="input-group"><span class="input-group-addon">Name <span class="mandatory">*</span></span><input id="operatorName" class="form-control operatorName" /></div></div>'; inlineHtml += '<div class="col-xs-3 operatorEmail_section"><div class="input-group"><span class="input-group-addon">EMAIL <span class="mandatory">*</span></span><input id="operatorEmail" class="form-control operatorEmail" /></div></div>'; inlineHtml += '<div class="col-xs-3 operatorMobile_section"><div class="input-group"><span class="input-group-addon">MOBILE NO. <span class="mandatory">*</span></span><input id="operatorMobile" class="form-control operatorMobile" /></div></div>'; inlineHtml += '<div class="col-xs-3"><div class="input-group"><span class="input-group-addon">MOBILE DEV </span><select id="operatorMobileDev" class="form-control operatorMobileDev" >'; /* iOS 1 Android 2 Other 5 */ inlineHtml += '<option value=0></option><option value=1>iOS</option><option value=2>Android</option><option value=5>Other</option>'; inlineHtml += '</select></div></div>'; inlineHtml += '</div>'; inlineHtml += '</div>'; inlineHtml += '<div class="form-group container row_operatorRole hide">' inlineHtml += '<div class="row">'; /* Driver 2 Trolley/ Foot Courier 3 Franchisee 5 */ inlineHtml += '<div class="col-xs-3"><div class="input-group"><span class="input-group-addon">ROLE <span class="mandatory">*</span></span><select id="operatorRole" class="form-control operatorRole" >'; inlineHtml += '<option value=0></option><option value=2>Driver</option><option value=3>Trolley/ Foot Courier</option><option value=5>Franchisee</option>'; inlineHtml += '</select></div></div>'; /* Employee 1 Contractor 2 Franchise Owner 4 */ inlineHtml += '<div class="col-xs-3"><div class="input-group"><span class="input-group-addon">EMPLOYEMENT TYPE <span class="mandatory">*</span></span><select id="operatorEmploymentType" class="form-control operatorEmploymentType" >'; inlineHtml += '<option value=0></option><option value=1>Employee</option><option value=2>Contractor</option><option value=4>Franchise Owner</option>'; inlineHtml += '</select></div></div>'; /* Yes 1 No 2 */ inlineHtml += '<div class="col-xs-3"><div class="input-group"><span class="input-group-addon">PRIMARY OPERATOR <span class="mandatory">*</span></span><select id="operatorPrimaryOperator" class="form-control operatorPrimaryOperator" >'; inlineHtml += '<option value=0></option><option value=1>Yes</option><option value=2>No</option>'; inlineHtml += '</select></div></div>'; inlineHtml += '<div class="col-xs-3"><div class="input-group"><span class="input-group-addon">CONTINGENCY DRIVER <span class="mandatory">*</span></span><select id="operatorContingency" class="form-control operatorContingency" >'; inlineHtml += '<option value=0></option><option value=1>Yes</option><option value=2>No</option>'; inlineHtml += '</select></div></div>'; inlineHtml += '</div>'; inlineHtml += '</div>'; inlineHtml += '<div class="form-group container saveoperator_section hide">'; inlineHtml += '<div class="row">'; inlineHtml += '<div class="col-xs-2 "></div>'; inlineHtml += '<div class="col-xs-4 reviewaddress"><input type="button" value="SAVE OPERATOR" class="form-control btn btn-success" id="saveOperator" /></div>'; inlineHtml += '<div class="col-xs-4 cancel"><input type="button" value="CANCEL" class="form-control btn btn-secondary" id="cancel" /></div>'; inlineHtml += '<div class="col-xs-2 "></div>'; inlineHtml += '</div>'; inlineHtml += '</div>'; inlineHtml += '<div class="form-group container" style="width: 100% !important;">'; inlineHtml += '<div class="row">'; inlineHtml += '<style>table#operatorTable {color: #103D39 !important; font-size: 12px;text-align: center;border: none;}.dataTables_wrapper {font-size: 14px;}table#operatorTable th{text-align: center;} .bolded{font-weight: bold;}</style>'; inlineHtml += '<table id="operatorTable" class="table table-responsive table-striped operatorTable tablesorter" style="width: 100%;border: 1px solid #103d39;">'; inlineHtml += '<thead style="color: white;background-color: #379E8F;font-weight: bold;">'; inlineHtml += '<tr class="text-center">'; inlineHtml += '<td>LINK</td>' inlineHtml += '<td>NAME</td>' inlineHtml += '<td class="col-xs-2">EMAIL</td>' inlineHtml += '<td>PHONE</td>' inlineHtml += '<td>ROLE</td>' inlineHtml += '<td>EMPLOYMENT TYPE</td>' inlineHtml += '<td>CONTINGENCY DRIVER</td>' inlineHtml += '<td>PRIMARY DRIVER</td>' inlineHtml += '<td>MOBILE DEVICE</td>' inlineHtml += '</tr>'; inlineHtml += '</thead>'; inlineHtml += '<tbody id="resultOperatorTable" class="">'; resultSetOperators.each(function (searchResultOperators) { operatorID = searchResultOperators.getValue('internalid'); operatorName = searchResultOperators.getValue('name'); operatorPhone = searchResultOperators.getValue( 'custrecord_operator_phone'); operatorEmail = searchResultOperators.getValue( 'custrecord_operator_email'); operatorEmploymentType = searchResultOperators.getText( 'custrecord_operator_employment'); var operatorEmploymentTypeID = searchResultOperators.getValue( 'custrecord_operator_employment'); operatorRole = searchResultOperators.getText( 'custrecord_operator_role'); var operatorRoleID = searchResultOperators.getValue( 'custrecord_operator_role'); operatorMobileDev = searchResultOperators.getText( 'custrecord_operator_mobdev_platform'); var operatorMobileDevID = searchResultOperators.getValue( 'custrecord_operator_mobdev_platform'); operatorDDS = searchResultOperators.getText( 'custrecord_dds_operator'); var operatorDDSID = searchResultOperators.getValue( 'custrecord_dds_operator'); operatorPrimaryOperator = searchResultOperators.getText( 'custrecord_primary_operator'); var operatorPrimaryOperatorID = searchResultOperators.getValue( 'custrecord_primary_operator'); log.debug({ title: 'operatorEmploymentType', details: operatorEmploymentType }) log.debug({ title: 'operatorEmploymentTypeID', details: operatorEmploymentTypeID }) log.debug({ title: 'operatorRole', details: operatorRole }) log.debug({ title: 'operatorRoleID', details: operatorRoleID }) log.debug({ title: 'operatorMobileDevID', details: operatorMobileDevID }) log.debug({ title: 'operatorDDS', details: operatorDDS }) log.debug({ title: 'operatorDDSID', details: operatorDDSID }) log.debug({ title: 'operatorPrimaryOperator', details: operatorPrimaryOperator }) log.debug({ title: 'operatorPrimaryOperatorID', details: operatorPrimaryOperatorID }) inlineHtml += '<tr>' inlineHtml += '<td><a data-id="' + operatorID + '" class="btn btn-md btn-primary editOperatorTable" data-changed="notchanged">EDIT</a> <a data-id="' + operatorID + '" class="btn btn-md btn-danger deleteOperatorTable" >DELETE</a></td>' inlineHtml += '<td><input value="' + operatorName + '" readonly class="form-control operatorNameTable" /></td>' inlineHtml += '<td><input value="' + operatorEmail + '" readonly class="form-control operatorEmailTable" /></td>' inlineHtml += '<td><input value="' + operatorPhone + '" readonly class="form-control operatorPhoneTable" /></td>' inlineHtml += '<td><input value="' + operatorRole + '" readonly class="form-control operatorRoleTable" /><input id="" class="operatorRoleID" value="' + operatorRoleID + '" type="hidden"/></td>' inlineHtml += '<td><input value="' + operatorEmploymentType + '" readonly class="form-control operatorEmploymentTypeTable"/><input id="" class="operatorEmploymentTypeID" value="' + operatorEmploymentTypeID + '" type="hidden"/></td>' inlineHtml += '<td><input value="' + operatorDDS + '" readonly class="form-control operatorDDSTable" /><input id="" class="operatorDDSID" value="' + operatorDDSID + '" type="hidden"/></td>' inlineHtml += '<td><input value="' + operatorPrimaryOperator + '" readonly class="form-control operatorPrimaryOperatorTable" /><input id="" class="operatorPrimaryOperatorID" value="' + operatorPrimaryOperatorID + '" type="hidden"/></td>' inlineHtml += '<td><input value="' + operatorMobileDev + '" readonly class="form-control operatorMobileDevTable" /><input id="" class="operatorMobileDevID" value="' + operatorMobileDevID + '" type="hidden"/></td>' inlineHtml += '</tr>'; return true; }); inlineHtml += '</tbody></table>'; inlineHtml += '</div>'; inlineHtml += '</div>'; inlineHtml += franchiseeAddOperator() return inlineHtml; } function franchiseeFleetDetails(zee, resultSetOperators) { //NetSuite Search: Franchisee - Operator Vehicle Details var searchZeeVehicles = search.load({ id: 'customsearch1912', type: 'customrecord_vehicle' }); if (!isNullorEmpty(zee)) { searchZeeVehicles.filters.push(search.createFilter({ name: 'internalid', join: 'CUSTRECORD_VEHICLE_FRANCHISEE', operator: search.Operator.IS, values: zee })); } var resultSetZeeVehicles = searchZeeVehicles.run(); var inlineHtml = '<div class="form-group container">'; inlineHtml += '<div class="row">'; inlineHtml += '<div class="col-xs-12 heading1"><h4><span class="label label-default col-xs-12" style="background-color: #103D39;">FLEET DETAILS</span></h4></div>'; inlineHtml += '</div>'; inlineHtml += '</div>'; inlineHtml += '<div class="form-group container row_fleet_details hide">' inlineHtml += '<div class="row">'; inlineHtml += '<input id="vehicleInternalId" value="" type="hidden"/>' inlineHtml += '<div class="col-xs-6 vehicleRego_section"><div class="input-group"><span class="input-group-addon">REGISTRATION <span class="mandatory">*</span></span><input id="vehicleRegistration" class="form-control vehicleRegistration" /></div></div>'; inlineHtml += '</div>'; inlineHtml += '</div>'; inlineHtml += '<div class="form-group container row_fleet_details2 hide">' inlineHtml += '<div class="row">'; inlineHtml += '<div class="col-xs-3 operatorEmail_section"><div class="input-group"><span class="input-group-addon">MODEL <span class="mandatory">*</span></span><input id="vehicleModel" class="form-control vehicleModel" /></div></div>'; inlineHtml += '<div class="col-xs-3 operatorMobile_section"><div class="input-group"><span class="input-group-addon">MAKE<span class="mandatory">*</span></span><input id="vehicleMake" class="form-control vehicleMake" /></div></div>'; inlineHtml += '<div class="col-xs-3 operatorMobile_section"><div class="input-group"><span class="input-group-addon">COLOR <span class="mandatory">*</span></span><input id="vehicleColor" class="form-control vehicleColor" /></div></div>'; inlineHtml += '<div class="col-xs-3 operatorMobile_section"><div class="input-group"><span class="input-group-addon">YEAR <span class="mandatory">*</span></span><input id="vehicleYear" class="form-control vehicleYear" /></div></div>'; inlineHtml += '</div>'; inlineHtml += '</div>'; inlineHtml += '<div class="form-group container row_fleet_details3 hide">' inlineHtml += '<div class="row">'; inlineHtml += '<div class="col-xs-3"><div class="input-group"><span class="input-group-addon">SIGNAGE <span class="mandatory">*</span></span><select id="vehicleSignage" class="form-control vehicleSignage" >'; inlineHtml += '<option value=0></option><option value=1>Yes</option><option value=2>No</option>'; inlineHtml += '</select></div></div>'; inlineHtml += '<div class="col-xs-3"><div class="input-group"><span class="input-group-addon">CARGO CAGE <span class="mandatory">*</span></span><select id="vehicleCargoCage" class="form-control vehicleCargoCage" >'; inlineHtml += '<option value=0></option><option value=1>Yes</option><option value=2>No</option>'; inlineHtml += '</select></div></div>'; /* Employee 1 Contractor 2 Franchise Owner 4 */ inlineHtml += '<div class="col-xs-3"><div class="input-group"><span class="input-group-addon">ONWER <span class="mandatory">*</span></span><select id="vehicleOwner" class="form-control vehicleOwner" >'; inlineHtml += '<option value=0></option><option value=2>Driver</option><option value=3>Trolley/ Foot Courier</option><option value=5>Franchisee</option>'; inlineHtml += '</select></div></div>'; inlineHtml += '<div class="col-xs-3"><div class="input-group"><span class="input-group-addon">OPERATOR <span class="mandatory">*</span></span><select id="vehicleOperator" class="form-control vehicleOperator" ><option value=0></option>'; resultSetOperators.each(function (searchResultOperators) { operatorID = searchResultOperators.getValue('internalid'); operatorName = searchResultOperators.getValue('name'); inlineHtml += '<option value=' + operatorID + '>' + operatorName + '</option>'; return true; }); inlineHtml += '</select></div></div>'; inlineHtml += '</div>'; inlineHtml += '</div>'; inlineHtml += '<div class="form-group container savefleet_section hide">'; inlineHtml += '<div class="row">'; inlineHtml += '<div class="col-xs-2 "></div>'; inlineHtml += '<div class="col-xs-4 reviewaddress"><input type="button" value="SAVE FLEET" class="form-control btn btn-success" id="saveVehicle" /></div>'; inlineHtml += '<div class="col-xs-4 cancel"><input type="button" value="CANCEL" class="form-control btn btn-secondary" id="cancel" /></div>'; inlineHtml += '<div class="col-xs-2 "></div>'; inlineHtml += '</div>'; inlineHtml += '</div>'; inlineHtml += '<div class="form-group container" style="width: 100% !important;">'; inlineHtml += '<div class="row">'; inlineHtml += '<style>table#fleetTable {color: #103D39 !important; font-size: 12px;text-align: center;border: none;}.dataTables_wrapper {font-size: 14px;}table#fleetTable th{text-align: center;} .bolded{font-weight: bold;}</style>'; inlineHtml += '<table id="fleetTable" class="table table-responsive table-striped fleetTable tablesorter" style="width: 100%;border: 1px solid #103d39;">'; inlineHtml += '<thead style="color: white;background-color: #379E8F;font-weight: bold;">'; inlineHtml += '<tr class="text-center">'; inlineHtml += '<td>LINK</td>' inlineHtml += '<td>REGISTRATION</td>' inlineHtml += '<td>MODEL</td>' inlineHtml += '<td>MAKE</td>' inlineHtml += '<td>COLOR</td>' inlineHtml += '<td>YEAR</td>' inlineHtml += '<td>SIGNAGE</td>' inlineHtml += '<td>CARGO CAGE</td>' inlineHtml += '<td>OWNER</td>' inlineHtml += '<td>OPERATOR NAME</td>' inlineHtml += '</tr>'; inlineHtml += '</thead>'; inlineHtml += '<tbody id="resultOperatorTable" class="">'; resultSetZeeVehicles.each(function (searchResultZeeVehicles) { vehicleID = searchResultZeeVehicles.getValue('internalid'); vehicleRegistration = searchResultZeeVehicles.getValue('name'); vehicleModel = searchResultZeeVehicles.getValue( 'custrecord_vehicle_model_text'); vehicleMake = searchResultZeeVehicles.getValue( 'custrecord_vehicle_make'); vehicleYear = searchResultZeeVehicles.getValue( 'custrecord_vehicle_year'); vehicleColor = searchResultZeeVehicles.getValue( 'custrecord_vehicle_colour'); vehicleSignage = searchResultZeeVehicles.getValue( 'custrecord_vehicle_signage'); vehicleOwnerID = searchResultZeeVehicles.getValue( 'custrecord_vehicle_owner'); vehicleOwner = searchResultZeeVehicles.getText( 'custrecord_vehicle_owner'); vehicleCargoCageID = searchResultZeeVehicles.getValue( 'custrecord_cargo_cage'); vehicleCargoCage = searchResultZeeVehicles.getText( 'custrecord_cargo_cage'); vehicleOperatorInternalID = searchResultZeeVehicles.getValue({ name: "internalid", join: "CUSTRECORD_OPERATOR_VEHICLE" }); vehicleOperatorName = searchResultZeeVehicles.getValue({ name: "custrecord_operator_givennames", join: "CUSTRECORD_OPERATOR_VEHICLE" }); inlineHtml += '<tr>' inlineHtml += '<td><a data-id="' + vehicleID + '" class=" btn btn-md btn-primary editFleetTable" data-changed="notchanged">EDIT</a> <a data-id="' + vehicleID + '" class=" btn btn-md btn-danger deleteFleetTable" >DELETE</a></td>' inlineHtml += '<td><input value="' + vehicleRegistration + '" readonly class="form-control vehicleRegistrationTable"/></td>' inlineHtml += '<td><input value="' + vehicleModel + '" readonly class="form-control vehicleModelTable"/></td>' inlineHtml += '<td><input value="' + vehicleMake + '" readonly class="form-control vehicleMakeTable"/></td>' inlineHtml += '<td><input value="' + vehicleColor + '" readonly class="form-control vehicleColorTable"/></td>' inlineHtml += '<td><input value="' + vehicleYear + '" readonly class="form-control vehicleYearTable"/></td>' inlineHtml += '<td><input value="' + vehicleSignage + '" readonly class="form-control vehicleSignageTable"/><input id="vehicleSignageID" class="vehicleSignageID" value="' + vehicleSignage + '" type="hidden"/></td>' inlineHtml += '<td><input value="' + vehicleCargoCage + '" readonly class="form-control vehicleCargoCageTable"/><input id="vehicleCargoCageID" class="vehicleCargoCageID" value="' + vehicleCargoCageID + '" type="hidden"/></td>' inlineHtml += '<td><input value="' + vehicleOwner + '" readonly class="form-control vehicleOwnerTable"/><input id="vehicleOwnerID" class="vehicleOwnerID" value="' + vehicleOwnerID + '" type="hidden"/></td>' inlineHtml += '<td><input value="' + vehicleOperatorName + '" readonly class="form-control vehicleOperatorNameTable"/><input id="vehicleOperatorID" class="vehicleOperatorID" value="' + vehicleOperatorInternalID + '" type="hidden"/></td>' inlineHtml += '</tr>'; return true; }); inlineHtml += '</tbody></table>'; inlineHtml += '</div>'; inlineHtml += '</div>'; inlineHtml += franchiseeAddFleet() return inlineHtml; } function franchiseeBreachDetails() { var inlineHtml = '<div class="form-group container">'; inlineHtml += '<div class="row">'; inlineHtml += '<div class="col-xs-12 heading1"><h4><span class="label label-default col-xs-12" style="background-color: #103D39;">BREACH DETAILS</span></h4></div>'; inlineHtml += '</div>'; inlineHtml += '</div>'; return inlineHtml; } function franchiseeTerminationDetails() { var inlineHtml = '<div class="form-group container">'; inlineHtml += '<div class="row">'; inlineHtml += '<div class="col-xs-12 heading1"><h4><span class="label label-default col-xs-12" style="background-color: #103D39;">TERMINATION DETAILS</span></h4></div>'; inlineHtml += '</div>'; inlineHtml += '</div>'; return inlineHtml; } function addressContactsSection(resultSetAddresses) { var inlineQty = '<div class="form-group container contacts_section" style="font-size: xx-small;">'; inlineQty += '<div class="row">'; inlineQty += '<div class="col-xs-12 address_div">'; inlineQty += '<table border="0" cellpadding="15" id="address" class="table table-responsive table-striped address tablesorter" cellspacing="0" style="width: 100%;border: 1px solid #103d39;font-size: 12px;text-align: center;"><thead style="color: white;background-color: #379E8F;"><tr><th style="vertical-align: middle;text-align: center;">LINK</th><th style="vertical-align: middle;text-align: center;">ID</th><th style="vertical-align: middle;text-align: center;"><b>SUIT/LEVEL/UNIT </b></th><th style="vertical-align: middle;text-align: center;"><b>STREET NO. & NAME </b></th><th style="vertical-align: middle;text-align: center;"><b>SUBURB </b></th><th style="vertical-align: middle;text-align: center;"><b>STATE </b></th><th style="vertical-align: middle;text-align: center;"><b>POSTCODE </b></th></tr></thead><tbody>'; if (!isNullorEmpty(resultSetAddresses)) { //console.log("addresses work"); resultSetAddresses.each(function (searchResultAddresses) { var id = searchResultAddresses.getValue({ name: 'addressinternalid', join: 'Address' }); var addr1 = searchResultAddresses.getValue({ name: 'address1', join: 'Address' }); var addr2 = searchResultAddresses.getValue({ name: 'address2', join: 'Address' }); var city = searchResultAddresses.getValue({ name: 'city', join: 'Address' }); var state = searchResultAddresses.getValue({ name: 'state', join: 'Address' }); var zip = searchResultAddresses.getValue({ name: 'zipcode', join: 'Address' }); var lat = searchResultAddresses.getValue({ name: 'custrecord_address_lat', join: 'Address' }); var lon = searchResultAddresses.getValue({ name: 'custrecord_address_lon', join: 'Address' }); var default_shipping = searchResultAddresses.getValue({ name: 'isdefaultshipping', join: 'Address' }); var default_billing = searchResultAddresses.getValue({ name: 'isdefaultbilling', join: 'Address' }); var default_residential = searchResultAddresses.getValue({ name: 'isresidential', join: 'Address' }); if (isNullorEmpty(addr1) && isNullorEmpty(addr2)) { var full_address = city + ', ' + state + ' - ' + zip; } else if (isNullorEmpty(addr1) && !isNullorEmpty(addr2)) { var full_address = addr2 + ', ' + city + ', ' + state + ' - ' + zip; } else if (!isNullorEmpty(addr1) && isNullorEmpty(addr2)) { var full_address = addr1 + ', ' + city + ', ' + state + ' - ' + zip; } else { var full_address = addr1 + ', ' + addr2 + ', ' + city + ', ' + state + ' - ' + zip; } if (default_shipping == 'T') { shipping_state = state; } inlineQty += '<tr><td><a data-id="' + id + '" class="btn btn-md btn-primary editAddressTable" data-changed="notchanged">EDIT</a> <a data-id="' + id + '" class="btn btn-md btn-danger deleteAddressTable" >DELETE</a></td>'; inlineQty += '<td><input value="' + id + '" readonly class="form-control id"/></td>'; inlineQty += '<td><input value="' + addr1 + '" readonly class="form-control addr1Table"/></td>'; inlineQty += '<td><input value="' + addr2 + '" readonly class="form-control addr2Table"/></td>'; inlineQty += '<td><input value="' + city + '" readonly class="form-control cityTable"/></td>'; inlineQty += '<td><input value="' + state + '" readonly class="form-control stateTable"/></td>'; inlineQty += '<td><input value="' + zip + '" readonly class="form-control zipTable"/></td>'; return true; }); } inlineQty += '</tbody></table>'; inlineQty += '</div>'; inlineQty += '</div>'; inlineQty += '</div>'; inlineQty += '<div class="form-group container reviewaddress_section">'; inlineQty += '<div class="row">'; inlineQty += '<div class="col-xs-3 "></div>'; inlineQty += '<div class="col-xs-6 reviewaddress"><input type="button" value="ADD ADDRESSES" class="form-control btn btn-primary" style="background-color: #287587;" id="reviewaddress" /></div>'; inlineQty += '<div class="col-xs-3 "></div>'; inlineQty += '</div>'; inlineQty += '</div>'; return inlineQty; } function isNullorEmpty(strVal) { return (strVal == null || strVal == '' || strVal == 'null' || strVal == undefined || strVal == 'undefined' || strVal == '- None -' || strVal == '0'); } function isNullorEmptyExcZero(strVal) { return (strVal == null || strVal == '' || strVal == 'null' || strVal == undefined || strVal == 'undefined' || strVal == '- None -'); } /** * The header showing that the results are loading. * @returns {String} `inlineQty` */ function loadingSection() { var inlineHtml = '<div id="loading_section" class="form-group container loading_section " style="text-align:center">'; inlineHtml += '<div class="row">'; inlineHtml += '<div class="col-xs-12 loading_div">'; inlineHtml += '<h1>Loading...</h1>'; inlineHtml += '</div></div></div>'; return inlineHtml; } function getDateToday() { var date = new Date(); log.debug({ title: 'date', details: date }) format.format({ value: date, type: format.Type.DATE, timezone: format.Timezone.AUSTRALIA_SYDNEY }) return date; } function getDate(inputDate) { var date = new Date(inputDate); format.format({ value: date, type: format.Type.DATE, timezone: format.Timezone.AUSTRALIA_SYDNEY }) return date; } function getDay() { var date = new Date(); if (date.getHours() > 6) { date.setDate(date.getDate() + 1); } var day = date.getDay(); return day; } /** * Used to pass the values of `date_from` and `date_to` between the scripts and to Netsuite for the records and the search. * @param {String} date_iso "2020-06-01" * @returns {String} date_netsuite "1/6/2020" */ function dateISOToNetsuite(date_iso) { var date_netsuite = ''; if (!isNullorEmpty(date_iso)) { var date_utc = new Date(date_iso); // var date_netsuite = nlapiDateToString(date_utc); var date_netsuite = format.format({ value: date_utc, type: format.Type.DATE }); } return date_netsuite; } return { onRequest: onRequest }; });
510
[{"tag": "EMAIL", "value": "michael.mcdaid@mailplus.com.au", "start": 31973, "end": 32003}, {"tag": "EMAIL", "value": "ankith.ravindran@mailplus.com.au", "start": 32124, "end": 32156}, {"tag": "EMAIL", "value": "mailplussupport@protechly.com", "start": 41031, "end": 41060}, {"tag": "EMAIL", "value": "raine.giderson@mailplus.com.au", "start": 41176, "end": 41206}, {"tag": "EMAIL", "value": "ankith.ravindran@mailplus.com.au", "start": 41226, "end": 41258}, {"tag": "EMAIL", "value": "fiona.harrison@mailplus.com.au", "start": 41278, "end": 41308}, {"tag": "EMAIL", "value": "popie.popie@mailplus.com.au", "start": 41328, "end": 41355}, {"tag": "EMAIL", "value": "mailplussupport@protechly.com", "start": 42597, "end": 42626}, {"tag": "EMAIL", "value": "raine.giderson@mailplus.com.au", "start": 42754, "end": 42784}, {"tag": "EMAIL", "value": "ankith.ravindran@mailplus.com.au", "start": 42804, "end": 42836}, {"tag": "EMAIL", "value": "fiona.harrison@mailplus.com.au", "start": 42856, "end": 42886}, {"tag": "EMAIL", "value": "popie.popie@mailplus.com.au", "start": 42906, "end": 42933}]
true
12
/** * @NApiVersion 2.0 * @NScriptType Suitelet * @Author: Ankith Ravindran <ankithravindran> * @Date: 2021-11-15T07:25:50+11:00 * @Last modified by: ankithravindran * @Last modified time: 2022-02-24T15:27:26+11:00 */ define(['N/ui/serverWidget', 'N/email', 'N/runtime', 'N/search', 'N/record', 'N/http', 'N/log', 'N/redirect', 'N/format' ], function (ui, email, runtime, search, record, http, log, redirect, format) { var role = 0; var userId = 0; var zee = 0; var franchiseeName = ''; var mainContact = ''; var mainContactFName = ''; var mainContactLName = ''; var mainContactMobile = ''; var franchiseeTypeOfOwner = ''; var primaryEmail = ''; var personalEmail = ''; var dob = ''; var vaccinationStatus = ''; var franchiseeNextOfKinName = ''; var franchiseeNextOfKinMobile = ''; var franchiseeNextOfKinRelationship = ''; var franchiseeABN = ''; var franchiseeAddress = ''; var franchiseeTOLLAccountNumber = ''; var franchiseeTOLLPickupDX = ''; var franchiseeTOLLLodgementDX = ''; var franchiseeSendlePrimaryLocations = ''; var franchiseeLastMileLocations = ''; var franchiseeSendleSecondaryLocations = ''; var franchiseeListedForSale = ''; var color_array = ['blue', 'red', 'green', 'orange', 'black']; function onRequest(context) { var baseURL = 'https://system.na2.netsuite.com'; if (runtime.EnvType == "SANDBOX") { baseURL = 'https://system.sandbox.netsuite.com'; } userId = runtime.getCurrentUser().id; role = runtime.getCurrentUser().role; if (context.request.method === 'GET') { zee = context.request.parameters.zee; if (role == 1000) { zee = userId; var form = ui.createForm({ title: 'Franchisee Management Console' }); } else { var form = ui.createForm({ title: 'Franchisee Sales & Management' }); } //INITIALIZATION OF JQUERY AND BOOTSTRAP var inlineHtml = '<meta name="viewport" content="width=device-width, initial-scale=1.0"><script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"><script src="//code.jquery.com/jquery-1.11.0.min.js"></script><script src="//api.tiles.mapbox.com/mapbox.js/plugins/leaflet-omnivore/v0.3.1/leaflet-omnivore.min.js"></script><script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"><script src="//code.jquery.com/jquery-1.11.0.min.js"></script><script src="https://maps.googleapis.com/maps/api/js?key=AIzaSyA92XGDo8rx11izPYT7z2L-YPMMJ6Ih1s0&callback=initMap&libraries=places"></script><script src="https://cdnjs.cloudflare.com/ajax/libs/OverlappingMarkerSpiderfier/1.0.3/oms.min.js"></script></script><link rel="stylesheet" href="https://unpkg.com/leaflet@1.2.0/dist/leaflet.css" /><script src="https://unpkg.com/leaflet@1.2.0/dist/leaflet.js"></script><link type="text/css" rel="stylesheet" href="https://cdn.datatables.net/1.10.13/css/jquery.dataTables.min.css"><link href="//netdna.bootstrapcdn.com/bootstrap/3.3.2/css/bootstrap.min.css" rel="stylesheet"><script src="//netdna.bootstrapcdn.com/bootstrap/3.3.2/js/bootstrap.min.js"></script><link rel="stylesheet" href="https://system.na2.netsuite.com/core/media/media.nl?id=2060796&amp;c=1048144&amp;h=9ee6accfd476c9cae718&amp;_xt=.css"><script src="https://system.na2.netsuite.com/core/media/media.nl?id=2060797&amp;c=1048144&amp;h=ef2cda20731d146b5e98&amp;_xt=.js"></script><link type="text/css" rel="stylesheet" href="https://system.na2.netsuite.com/core/media/media.nl?id=2090583&amp;c=1048144&amp;h=a0ef6ac4e28f91203dfe&amp;_xt=.css"><script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.6.4/angular.min.js"></script><script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.7/angular-resource.min.js"></script><link type="text/css" rel="stylesheet" href="https://system.na2.netsuite.com/core/media/media.nl?id=2090583&amp;c=1048144&amp;h=a0ef6ac4e28f91203dfe&amp;_xt=.css"><style>.mandatory{color:red;}.clearfix:after {clear: both;content: "";display: block;height: 0;}.wrapper {vertical-align: middle;}.nav {margin-top: 40px;}.pull-right {float: right;}a, a:active {color: #212121;text-decoration: none;}a:hover {color: #999;}.arrow-steps .step {font-size: 14px;text-align: center;color: #fff;cursor: default;margin: 0 3px;padding: 10px 10px 10px 30px;float: left;position: relative;background-color: #379e8f;-webkit-user-select: none;-moz-user-select: none;-ms-user-select: none;user-select: none; transition: background-color 0.2s ease;}.arrow-steps .step:after,.arrow-steps .step:before {content: " ";position: absolute;top: 0;right: -17px;width: 0;height: 40px;border-top: 19px solid transparent;border-bottom: 17px solid transparent;border-left: 17px solid #379e8f; z-index: 2;transition: border-color 0.2s ease;}.arrow-steps .step:before {right: auto;left: 0;border-left: 17px solid #fff; z-index: 0;}.arrow-steps .step:first-child:before {border: none;}.arrow-steps .step:first-child {border-top-left-radius: 4px;border-bottom-left-radius: 4px;}.arrow-steps .step span {position: relative;}.arrow-steps .step span:before {opacity: 0;content: "βœ”";position: absolute;top: -2px;left: -20px;color: #06ac77;}.arrow-steps .step.done span:before {opacity: 1;-webkit-transition: opacity 0.3s ease 0.5s;-moz-transition: opacity 0.3s ease 0.5s;-ms-transition: opacity 0.3s ease 0.5s;transition: opacity 0.3s ease 0.5s;}.arrow-steps .step.current {color: #103d39;font-weight: bold;background-color: #fbea51;}.arrow-steps .step.current:after {border-left: 17px solid #fbea51; }.nav > li.active > a, .nav > li.active > a:focus, .nav > li.active > a:hover { background-color: #379E8F; color: #fff }.nav > li > a, .nav > li > a:focus, .nav > li > a:hover { margin-left: 5px; margin-right: 5px; border: 2px solid #379E8F; color: #379E8F; }</style>'; //ERROR SECTION inlineHtml += '<div class="container" style="padding-top: 3%;"><div id="alert" class="alert alert-danger fade in"></div></div>'; var day = getDay(); if (day == 0 || day == 6) { day = 1; //Monday } //HIDDEN FIELDS form.addField({ id: 'custpage_zee', type: ui.FieldType.TEXT, label: 'Zee' }).updateDisplayType({ displayType: ui.FieldDisplayType.HIDDEN }).defaultValue = zee; form.addField({ id: 'custpage_name', type: ui.FieldType.TEXT, label: 'Zee' }).updateDisplayType({ displayType: ui.FieldDisplayType.HIDDEN }).defaultValue = franchiseeName; form.addField({ id: 'custpage_day', type: ui.FieldType.TEXT, label: 'Day' }).updateDisplayType({ displayType: ui.FieldDisplayType.HIDDEN }).defaultValue = day; //HIDDEN FIELDS TO STORE VALUE TO BE SAVED ON THE FRANCHISE RECORD form.addField({ id: 'custpage_maincontact', type: ui.FieldType.TEXT, label: 'Day' }).updateDisplayType({ displayType: ui.FieldDisplayType.HIDDEN }).defaultValue = mainContact; form.addField({ id: 'custpage_mobilenumber', type: ui.FieldType.TEXT, label: 'Day' }).updateDisplayType({ displayType: ui.FieldDisplayType.HIDDEN }).defaultValue = mainContactMobile; form.addField({ id: 'custpage_typeofowner', type: ui.FieldType.TEXT, label: 'Day' }).updateDisplayType({ displayType: ui.FieldDisplayType.HIDDEN }).defaultValue = franchiseeTypeOfOwner; form.addField({ id: 'custpage_personalemail', type: ui.FieldType.TEXT, label: 'Day' }).updateDisplayType({ displayType: ui.FieldDisplayType.HIDDEN }).defaultValue = primaryEmail; form.addField({ id: 'custpage_dob', type: ui.FieldType.TEXT, label: 'Day' }).updateDisplayType({ displayType: ui.FieldDisplayType.HIDDEN }).defaultValue = dob; form.addField({ id: 'custpage_vaccinationstatus', type: ui.FieldType.TEXT, label: 'Day' }).updateDisplayType({ displayType: ui.FieldDisplayType.HIDDEN }).defaultValue = vaccinationStatus; form.addField({ id: 'custpage_nextofkinname', type: ui.FieldType.TEXT, label: 'Day' }).updateDisplayType({ displayType: ui.FieldDisplayType.HIDDEN }).defaultValue = franchiseeNextOfKinName; form.addField({ id: 'custpage_nextofkinmobile', type: ui.FieldType.TEXT, label: 'Day' }).updateDisplayType({ displayType: ui.FieldDisplayType.HIDDEN }).defaultValue = franchiseeNextOfKinMobile; form.addField({ id: 'custpage_nextofkinrelationship', type: ui.FieldType.TEXT, label: 'Day' }).updateDisplayType({ displayType: ui.FieldDisplayType.HIDDEN }).defaultValue = franchiseeNextOfKinRelationship; //Address Table Hidden Fields form.addField({ id: 'custpage_addressids', type: ui.FieldType.TEXT, label: 'Day' }).updateDisplayType({ displayType: ui.FieldDisplayType.HIDDEN }); form.addField({ id: 'custpage_addressids_delete', type: ui.FieldType.TEXT, label: 'Day' }).updateDisplayType({ displayType: ui.FieldDisplayType.HIDDEN }); form.addField({ id: 'custpage_address1', type: ui.FieldType.TEXT, label: 'Day' }).updateDisplayType({ displayType: ui.FieldDisplayType.HIDDEN }); form.addField({ id: 'custpage_address2', type: ui.FieldType.TEXT, label: 'Day' }).updateDisplayType({ displayType: ui.FieldDisplayType.HIDDEN }); form.addField({ id: 'custpage_suburb', type: ui.FieldType.TEXT, label: 'Day' }).updateDisplayType({ displayType: ui.FieldDisplayType.HIDDEN }); form.addField({ id: 'custpage_state', type: ui.FieldType.TEXT, label: 'Day' }).updateDisplayType({ displayType: ui.FieldDisplayType.HIDDEN }); form.addField({ id: 'custpage_postcode', type: ui.FieldType.TEXT, label: 'Day' }).updateDisplayType({ displayType: ui.FieldDisplayType.HIDDEN }); //Operator Table Hidden Fields form.addField({ id: 'custpage_operatorids', type: ui.FieldType.TEXT, label: 'Day' }).updateDisplayType({ displayType: ui.FieldDisplayType.HIDDEN }); form.addField({ id: 'custpage_operatorids_delete', type: ui.FieldType.TEXT, label: 'Day' }).updateDisplayType({ displayType: ui.FieldDisplayType.HIDDEN }); form.addField({ id: 'custpage_operatorname', type: ui.FieldType.TEXT, label: 'Day' }).updateDisplayType({ displayType: ui.FieldDisplayType.HIDDEN }); form.addField({ id: 'custpage_operatoremail', type: ui.FieldType.TEXT, label: 'Day' }).updateDisplayType({ displayType: ui.FieldDisplayType.HIDDEN }); form.addField({ id: 'custpage_operatormobile', type: ui.FieldType.TEXT, label: 'Day' }).updateDisplayType({ displayType: ui.FieldDisplayType.HIDDEN }); form.addField({ id: 'custpage_operatorrole', type: ui.FieldType.TEXT, label: 'Day' }).updateDisplayType({ displayType: ui.FieldDisplayType.HIDDEN }); form.addField({ id: 'custpage_operatoremploymentype', type: ui.FieldType.TEXT, label: 'Day' }).updateDisplayType({ displayType: ui.FieldDisplayType.HIDDEN }); form.addField({ id: 'custpage_operatordds', type: ui.FieldType.TEXT, label: 'Day' }).updateDisplayType({ displayType: ui.FieldDisplayType.HIDDEN }); form.addField({ id: 'custpage_operatorprimary', type: ui.FieldType.TEXT, label: 'Day' }).updateDisplayType({ displayType: ui.FieldDisplayType.HIDDEN }); form.addField({ id: 'custpage_operatormobiledev', type: ui.FieldType.TEXT, label: 'Day' }).updateDisplayType({ displayType: ui.FieldDisplayType.HIDDEN }); //New Operator Table Hidden Fields form.addField({ id: 'custpage_new_operatorids', type: ui.FieldType.TEXT, label: 'Day' }).updateDisplayType({ displayType: ui.FieldDisplayType.HIDDEN }); form.addField({ id: 'custpage_new_operatorids_delete', type: ui.FieldType.TEXT, label: 'Day' }).updateDisplayType({ displayType: ui.FieldDisplayType.HIDDEN }); form.addField({ id: 'custpage_new_operatorname', type: ui.FieldType.TEXT, label: 'Day' }).updateDisplayType({ displayType: ui.FieldDisplayType.HIDDEN }); form.addField({ id: 'custpage_new_operatoremail', type: ui.FieldType.TEXT, label: 'Day' }).updateDisplayType({ displayType: ui.FieldDisplayType.HIDDEN }); form.addField({ id: 'custpage_new_operatormobile', type: ui.FieldType.TEXT, label: 'Day' }).updateDisplayType({ displayType: ui.FieldDisplayType.HIDDEN }); form.addField({ id: 'custpage_new_operatorrole', type: ui.FieldType.TEXT, label: 'Day' }).updateDisplayType({ displayType: ui.FieldDisplayType.HIDDEN }); form.addField({ id: 'custpage_new_operatoremploymentype', type: ui.FieldType.TEXT, label: 'Day' }).updateDisplayType({ displayType: ui.FieldDisplayType.HIDDEN }); form.addField({ id: 'custpage_new_operatordds', type: ui.FieldType.TEXT, label: 'Day' }).updateDisplayType({ displayType: ui.FieldDisplayType.HIDDEN }); form.addField({ id: 'custpage_new_operatorprimary', type: ui.FieldType.TEXT, label: 'Day' }).updateDisplayType({ displayType: ui.FieldDisplayType.HIDDEN }); form.addField({ id: 'custpage_new_operatormobiledev', type: ui.FieldType.TEXT, label: 'Day' }).updateDisplayType({ displayType: ui.FieldDisplayType.HIDDEN }); //Fleet Table Hidden Details form.addField({ id: 'custpage_fleetids', type: ui.FieldType.TEXT, label: 'Day' }).updateDisplayType({ displayType: ui.FieldDisplayType.HIDDEN }); form.addField({ id: 'custpage_fleetids_delete', type: ui.FieldType.TEXT, label: 'Day' }).updateDisplayType({ displayType: ui.FieldDisplayType.HIDDEN }); form.addField({ id: 'custpage_fleetrego', type: ui.FieldType.TEXT, label: 'Day' }).updateDisplayType({ displayType: ui.FieldDisplayType.HIDDEN }); form.addField({ id: 'custpage_fleetmodel', type: ui.FieldType.TEXT, label: 'Day' }).updateDisplayType({ displayType: ui.FieldDisplayType.HIDDEN }); form.addField({ id: 'custpage_fleetmake', type: ui.FieldType.TEXT, label: 'Day' }).updateDisplayType({ displayType: ui.FieldDisplayType.HIDDEN }); form.addField({ id: 'custpage_fleetcolor', type: ui.FieldType.TEXT, label: 'Day' }).updateDisplayType({ displayType: ui.FieldDisplayType.HIDDEN }); form.addField({ id: 'custpage_fleetyear', type: ui.FieldType.TEXT, label: 'Day' }).updateDisplayType({ displayType: ui.FieldDisplayType.HIDDEN }); form.addField({ id: 'custpage_fleetsignage', type: ui.FieldType.TEXT, label: 'Day' }).updateDisplayType({ displayType: ui.FieldDisplayType.HIDDEN }); form.addField({ id: 'custpage_caregocage', type: ui.FieldType.TEXT, label: 'Day' }).updateDisplayType({ displayType: ui.FieldDisplayType.HIDDEN }); form.addField({ id: 'custpage_owner', type: ui.FieldType.TEXT, label: 'Day' }).updateDisplayType({ displayType: ui.FieldDisplayType.HIDDEN }); form.addField({ id: 'custpage_operator', type: ui.FieldType.TEXT, label: 'Day' }).updateDisplayType({ displayType: ui.FieldDisplayType.HIDDEN }); //New Fleet DETAILS form.addField({ id: 'custpage_new_fleetids', type: ui.FieldType.TEXT, label: 'Day' }).updateDisplayType({ displayType: ui.FieldDisplayType.HIDDEN }); form.addField({ id: 'custpage_new_fleetids_delete', type: ui.FieldType.TEXT, label: 'Day' }).updateDisplayType({ displayType: ui.FieldDisplayType.HIDDEN }); form.addField({ id: 'custpage_new_fleetrego', type: ui.FieldType.TEXT, label: 'Day' }).updateDisplayType({ displayType: ui.FieldDisplayType.HIDDEN }); form.addField({ id: 'custpage_new_fleetmodel', type: ui.FieldType.TEXT, label: 'Day' }).updateDisplayType({ displayType: ui.FieldDisplayType.HIDDEN }); form.addField({ id: 'custpage_new_fleetmake', type: ui.FieldType.TEXT, label: 'Day' }).updateDisplayType({ displayType: ui.FieldDisplayType.HIDDEN }); form.addField({ id: 'custpage_new_fleetcolor', type: ui.FieldType.TEXT, label: 'Day' }).updateDisplayType({ displayType: ui.FieldDisplayType.HIDDEN }); form.addField({ id: 'custpage_new_fleetyear', type: ui.FieldType.TEXT, label: 'Day' }).updateDisplayType({ displayType: ui.FieldDisplayType.HIDDEN }); form.addField({ id: 'custpage_new_fleetsignage', type: ui.FieldType.TEXT, label: 'Day' }).updateDisplayType({ displayType: ui.FieldDisplayType.HIDDEN }); form.addField({ id: 'custpage_new_caregocage', type: ui.FieldType.TEXT, label: 'Day' }).updateDisplayType({ displayType: ui.FieldDisplayType.HIDDEN }); form.addField({ id: 'custpage_new_owner', type: ui.FieldType.TEXT, label: 'Day' }).updateDisplayType({ displayType: ui.FieldDisplayType.HIDDEN }); form.addField({ id: 'custpage_new_operator', type: ui.FieldType.TEXT, label: 'Day' }).updateDisplayType({ displayType: ui.FieldDisplayType.HIDDEN }); form.addField({ id: 'custpage_listforsale', type: ui.FieldType.TEXT, label: 'Day' }).updateDisplayType({ displayType: ui.FieldDisplayType.HIDDEN }).defaultValue = 'F'; inlineHtml += '<div class="se-pre-con"></div><div ng-app="myApp" ng-controller="myCtrl">'; inlineHtml += spacing() if (role != 1000) { inlineHtml += progressBar() inlineHtml += line() inlineHtml += spacing() inlineHtml += selectFranchiseeSection(zee) inlineHtml += spacing() } if (zee != 0 && !isNullorEmpty(zee)) { //NetSuite Search: APP - Operator Load var searchOperators = search.load({ id: 'customsearch_app_operator_load', type: 'customrecord_operator' }); if (!isNullorEmpty(zee)) { searchOperators.filters.push(search.createFilter({ name: 'internalid', join: 'CUSTRECORD_OPERATOR_FRANCHISEE2', operator: search.Operator.IS, values: zee })); } var resultSetOperators = searchOperators.run(); inlineHtml += tabSection(zee, role, resultSetOperators) inlineHtml += spacing() inlineHtml += line() inlineHtml += mainButtons(role) } form.addField({ id: 'preview_table', label: 'inlinehtml', type: 'inlinehtml' }).updateLayoutType({ layoutType: ui.FieldLayoutType.STARTROW }).defaultValue = inlineHtml; form.addSubmitButton({ label: 'SAVE' }); form.clientScriptFileId = 5334734 context.response.writePage(form); } else { var zeeId = parseInt(context.request.parameters.custpage_zee); var franchiseeMainContact = context.request.parameters.custpage_maincontact; var franchiseeMobileNumber = context.request.parameters.custpage_mobilenumber; var franchiseeTypeOfOwner = context.request.parameters.custpage_typeofowner; var franchiseePersonalEmail = context.request.parameters.custpage_personalemail; var FranchiseeDOB = context.request.parameters.custpage_dob; var franchiseeVaccinationStatus = context.request.parameters.custpage_vaccinationstatus; var franchiseeNextOfKinName = context.request.parameters.custpage_nextofkinname; var franchiseeNextOfKinMobile = context.request.parameters.custpage_nextofkinmobile; var franchiseeNextOfKinRelationship = context.request.parameters.custpage_nextofkinrelationship; var addressids = context.request.parameters.custpage_addressids; var addressids_delete = context.request.parameters.custpage_addressids_delete; var address1 = context.request.parameters.custpage_address1; var address2 = context.request.parameters.custpage_address2; var suburb = context.request.parameters.custpage_suburb; var state = context.request.parameters.custpage_state; var postcode = context.request.parameters.custpage_postcode; var listforsale = context.request.parameters.custpage_listforsale; log.debug({ title: 'addressids', details: addressids }) var addressidsArrays = addressids.split(','); var addressidsdeleteArrays = addressids_delete.split(','); var address1Arrays = address1.split(','); var address2Arrays = address2.split(','); var suburbArrays = suburb.split(','); var stateArrays = state.split(','); var postcodeArrays = postcode.split(','); var operatorids = context.request.parameters.custpage_operatorids; var operatorids_delete = context.request.parameters.custpage_operatorids_delete; var operatorname = context.request.parameters.custpage_operatorname; var operatoremail = context.request.parameters.custpage_operatoremail; var operatormobile = context.request.parameters.custpage_operatormobile; var operatorrole = context.request.parameters.custpage_operatorrole; var operatoremploymentype = context.request.parameters.custpage_operatoremploymentype; var operatordds = context.request.parameters.custpage_operatordds; var operatorprimary = context.request.parameters.custpage_operatorprimary; var operatormobiledev = context.request.parameters.custpage_operatormobiledev; var operatoridsArrys = operatorids.split(',') var operatoridsdeleteArrys = operatorids_delete.split(',') var operatornameArrys = operatorname.split(',') var operatoremailArrys = operatoremail.split(',') var operatormobileArrys = operatormobile.split(',') var operatorroleArrys = operatorrole.split(',') var operatoremploymentypeArrys = operatoremploymentype.split(',') var operatorddsArrys = operatordds.split(',') var operatorprimaryArrys = operatorprimary.split(',') var operatormobiledevArrys = operatormobiledev.split(',') //New operator var newoperatorids = context.request.parameters.custpage_new_operatorids; var newoperatorids_delete = context.request.parameters.custpage_new_operatorids_delete; var newoperatorname = context.request.parameters.custpage_new_operatorname; var newoperatoremail = context.request.parameters.custpage_new_operatoremail; var newoperatormobile = context.request.parameters.custpage_new_operatormobile; var newoperatorrole = context.request.parameters.custpage_new_operatorrole; var newoperatoremploymentype = context.request.parameters.custpage_new_operatoremploymentype; var newoperatordds = context.request.parameters.custpage_new_operatordds; var newoperatorprimary = context.request.parameters.custpage_new_operatorprimary; var newoperatormobiledev = context.request.parameters.custpage_new_operatormobiledev; var newoperatoridsArrys = newoperatorids.split(',') var newoperatoridsdeleteArrys = newoperatorids_delete.split(',') var newoperatornameArrys = newoperatorname.split(',') var newoperatoremailArrys = newoperatoremail.split(',') var newoperatormobileArrys = newoperatormobile.split(',') var newoperatorroleArrys = newoperatorrole.split(',') var newoperatoremploymentypeArrys = newoperatoremploymentype.split( ',') var newoperatorddsArrys = newoperatordds.split(',') var newoperatorprimaryArrys = newoperatorprimary.split(',') var newoperatormobiledevArrys = newoperatormobiledev.split(',') var fleetids = context.request.parameters.custpage_fleetids; var fleetids_delete = context.request.parameters.custpage_fleetids_delete; var fleetrego = context.request.parameters.custpage_fleetrego; var fleetmodel = context.request.parameters.custpage_fleetmodel; var fleetmake = context.request.parameters.custpage_fleetmake; var fleetcolor = context.request.parameters.custpage_fleetcolor; var fleetyear = context.request.parameters.custpage_fleetyear; var fleetsignage = context.request.parameters.custpage_fleetsignage; var caregocage = context.request.parameters.custpage_caregocage; var owner = context.request.parameters.custpage_owner; var operator = context.request.parameters.custpage_operator; var fleetidsArrys = fleetids.split(',') var fleetidsdeleteArrys = fleetids_delete.split(',') var fleetregoArrys = fleetrego.split(',') var fleetmodelArrys = fleetmodel.split(',') var fleetmakeArrys = fleetmake.split(',') var fleetcolorArrys = fleetcolor.split(',') var fleetyearArrys = fleetyear.split(',') var fleetsignageArrys = fleetsignage.split(',') var caregocageArrys = caregocage.split(',') var ownerArrys = owner.split(',') var operatorArrys = operator.split(',') //New Fleet details var newfleetids = context.request.parameters.custpage_new_fleetids; var newfleetids_delete = context.request.parameters.custpage_new_fleetids_delete; var newfleetrego = context.request.parameters.custpage_new_fleetrego; var newfleetmodel = context.request.parameters.custpage_new_fleetmodel; var newfleetmake = context.request.parameters.custpage_new_fleetmake; var newfleetcolor = context.request.parameters.custpage_new_fleetcolor; var newfleetyear = context.request.parameters.custpage_new_fleetyear; var newfleetsignage = context.request.parameters.custpage_new_fleetsignage; var newcaregocage = context.request.parameters.custpage_new_caregocage; var newowner = context.request.parameters.custpage_new_owner; var newoperator = context.request.parameters.custpage_new_operator; var newfleetidsArrys = newfleetids.split(',') var newfleetidsdeleteArrys = newfleetids_delete.split(',') var newfleetregoArrys = newfleetrego.split(',') var newfleetmodelArrys = newfleetmodel.split(',') var newfleetmakeArrys = newfleetmake.split(',') var newfleetcolorArrys = newfleetcolor.split(',') var newfleetyearArrys = newfleetyear.split(',') var newfleetsignageArrys = newfleetsignage.split(',') var newcaregocageArrys = newcaregocage.split(',') var newownerArrys = newowner.split(',') var newoperatorArrys = newoperator.split(',') //Load Partner Record & Save the main details var zeeRecord = record.load({ type: record.Type.PARTNER, id: zeeId }); var zeeName = zeeRecord.getValue({ fieldId: 'companyname' }); zeeRecord.setValue({ fieldId: 'custentity3', value: franchiseeMainContact }) zeeRecord.setValue({ fieldId: 'custentity2', value: franchiseeMobileNumber }) if (franchiseeTypeOfOwner != 0) { zeeRecord.setValue({ fieldId: 'custentity_type_of_owner', value: franchiseeTypeOfOwner }) } zeeRecord.setValue({ fieldId: 'custentity_personal_email_address', value: franchiseePersonalEmail }); log.debug({ title: 'dobArray', details: dobArray }) if (!isNullorEmpty(dobArray)) { var dobArray = FranchiseeDOB.split('-') var dobString = dobArray[1] + '/' + dobArray[2] + '/' + dobArray[0] zeeRecord.setValue({ fieldId: 'custentity_zee_dob', value: getDate(dobString) }) } if (franchiseeVaccinationStatus != 0) { zeeRecord.setValue({ fieldId: 'custentity_vacc_status', value: franchiseeVaccinationStatus }) } zeeRecord.setValue({ fieldId: 'custentity_kin_name', value: franchiseeNextOfKinName }) zeeRecord.setValue({ fieldId: 'custentity_kin_mobile', value: franchiseeNextOfKinMobile }) if (franchiseeNextOfKinRelationship != 0) { zeeRecord.setValue({ fieldId: 'custentity_kin_relationship', value: franchiseeNextOfKinRelationship }) } if (listforsale == 'T') { zeeRecord.setValue({ fieldId: 'custentity_listed_for_sale', value: 1 }); zeeRecord.setValue({ fieldId: 'custentity_date_listed_for_sale', value: getDateToday() }); var email_body = ' Franchisee NS ID: ' + zeeId + '</br> Franchisee Name: ' + zeeName + '</br> Date: ' + getDateToday() + '</br> Franchisee NS ID: ' + zeeRecordId; email.send({ author: 112209, recipients: ['kenaa@example.com'], subject: 'Listed for Sale - ' + zeeName + ' Franchisee', body: email_body, cc: ['lyhxr@example.com'] }); } log.debug({ title: 'isDynamic', details: zeeRecord.isDynamic }) //ADD/UPDATE ADDRESS if (!isNullorEmptyExcZero(addressidsArrays)) { for (var x = 0; x < addressidsArrays.length; x++) { log.debug({ title: 'addressidsArrays[x]', details: addressidsArrays[x] }) if (addressidsArrays[x] == 0 || addressidsArrays[x] == '0') { log.debug({ title: 'inside new' }) zeeRecord.insertLine({ sublistId: 'addressbook', line: 0 }) var lineIndex = 0; } else { var lineIndex = zeeRecord.findSublistLineWithValue({ sublistId: 'addressbook', fieldId: 'internalid', value: addressidsArrays[x] }); log.debug({ title: "lineIndex", details: lineIndex }); } var updateAddress = zeeRecord.getSublistSubrecord({ sublistId: 'addressbook', fieldId: 'addressbookaddress', line: lineIndex }) updateAddress.setValue({ fieldId: 'country', value: 'AU' }); updateAddress.setValue({ fieldId: 'addressee', value: franchiseeMainContact }); updateAddress.setValue({ fieldId: 'addr1', value: address1Arrays[x] }); updateAddress.setValue({ fieldId: 'addr2', value: address2Arrays[x] }); updateAddress.setValue({ fieldId: 'city', value: suburbArrays[x] }); updateAddress.setValue({ fieldId: 'state', value: stateArrays[x] }); updateAddress.setValue({ fieldId: 'zip', value: postcodeArrays[x] }); updateAddress.setValue({ fieldId: 'isresidential', value: 'T' }); } } if (!isNullorEmpty(addressidsdeleteArrays)) { for (var x = 0; x < addressidsdeleteArrays.length; x++) { var lineIndex = zeeRecord.findSublistLineWithValue({ sublistId: 'addressbook', fieldId: 'internalid', value: addressidsdeleteArrays[x] }); var deleteAddress = zeeRecord.removeSublistSubrecord({ sublistId: 'addressbook', fieldId: 'addressbookaddress', line: lineIndex }) // // deleteAddress.setValue({ // fieldId: 'country', // value: 'AU' // }); } } var zeeRecordId = zeeRecord.save({ ignoreMandatoryFields: true }); //ADD/UPDATE OPREATOR DETAILS if (!isNullorEmpty(operatoridsArrys)) { for (var y = 0; y < operatoridsArrys.length; y++) { var operatorRecord = record.load({ type: 'customrecord_operator', id: operatoridsArrys[y] }); var spliName = operatornameArrys[y].split(" "); operatorRecord.setValue({ fieldId: 'custrecord_operator_givennames', value: spliName[0] }) operatorRecord.setValue({ fieldId: 'custrecord_operator_surname', value: spliName[1] }) operatorRecord.setValue({ fieldId: 'name', value: operatornameArrys[y] }) operatorRecord.setValue({ fieldId: 'custrecord_operator_email', value: operatoremailArrys[y] }) operatorRecord.setValue({ fieldId: 'custrecord_operator_date_reviewed', value: getDateToday() }) operatorRecord.setValue({ fieldId: 'custrecord_operator_phone', value: operatormobileArrys[y] }) operatorRecord.setValue({ fieldId: 'custrecord_operator_role', value: operatorroleArrys[y] }) operatorRecord.setValue({ fieldId: 'custrecord_operator_employment', value: operatoremploymentypeArrys[y] }) operatorRecord.setValue({ fieldId: 'custrecord_dds_operator', value: operatorddsArrys[y] }) operatorRecord.setValue({ fieldId: 'custrecord_primary_operator', value: operatorprimaryArrys[y] }) if (!isNullorEmpty(operatormobiledevArrys[y])) { operatorRecord.setValue({ fieldId: 'custrecord_operator_mobdev_platform', value: operatormobiledevArrys[y] }) } operatorRecord.save() } } //NEW OPERATOR DETAILS if (!isNullorEmpty(newoperatoridsArrys)) { log.debug({ title: 'newoperatoridsArrys.length', details: newoperatoridsArrys.length }) for (var y = 0; y < newoperatoridsArrys.length; y++) { var operatorRecord = record.create({ type: 'customrecord_operator' }); if (!isNullorEmpty(newoperatornameArrys[y])) { var spliName = newoperatornameArrys[y].split(" "); operatorRecord.setValue({ fieldId: 'custrecord_operator_givennames', value: spliName[0] }) if (isNullorEmpty(spliName[1])) { operatorRecord.setValue({ fieldId: 'custrecord_operator_surname', value: spliName[0] }) } else { operatorRecord.setValue({ fieldId: 'custrecord_operator_surname', value: spliName[1] }) } } operatorRecord.setValue({ fieldId: 'name', value: newoperatornameArrys[y] }) operatorRecord.setValue({ fieldId: 'custrecord_operator_email', value: newoperatoremailArrys[y] }) operatorRecord.setValue({ fieldId: 'custrecord_operator_franchisee', value: zeeRecordId }) operatorRecord.setValue({ fieldId: 'custrecord_operator_franchisee2', value: zeeRecordId }) operatorRecord.setValue({ fieldId: 'custrecord_operator_salutation', value: 1 }) operatorRecord.setValue({ fieldId: 'custrecord_operator_status', value: 4 }) operatorRecord.setValue({ fieldId: 'custrecord_operator_app_date_link_sent', value: getDateToday() }) operatorRecord.setValue({ fieldId: 'custrecord_operator_date_reviewed', value: getDateToday() }) operatorRecord.setValue({ fieldId: 'custrecord_operator_phone', value: newoperatormobileArrys[y] }) operatorRecord.setValue({ fieldId: 'custrecord_operator_role', value: newoperatorroleArrys[y] }) operatorRecord.setValue({ fieldId: 'custrecord_operator_employment', value: newoperatoremploymentypeArrys[y] }) operatorRecord.setValue({ fieldId: 'custrecord_dds_operator', value: newoperatorddsArrys[y] }) operatorRecord.setValue({ fieldId: 'custrecord_primary_operator', value: newoperatorprimaryArrys[y] }) if (!isNullorEmpty(operatormobiledevArrys[y])) { operatorRecord.setValue({ fieldId: 'custrecord_operator_mobdev_platform', value: newoperatormobiledevArrys[y] }) } var operatorIdNew = operatorRecord.save() var email_body = ' New Operator NS ID: ' + operatorIdNew + '</br> New Operator Name: ' + newoperatornameArrys[y] + '</br> New Operator Email: ' + newoperatoremailArrys[y] + '</br> New Operator Mobile: ' + newoperatormobileArrys[y] + '</br> Franchisee NS ID: ' + zeeRecordId; email.send({ author: 112209, recipients: ['efpyi@example.com'], subject: 'MP Operator Access - New Operator', body: email_body, cc: ['efpyi@example.com', 'lyhxr@example.com', 'dycjh@example.com', 'envkt@example.com' ] }); } } if (!isNullorEmpty(operatoridsdeleteArrys)) { for (var y = 0; y < operatoridsdeleteArrys.length; y++) { var deleteOperatorRecord = record.load({ type: 'customrecord_operator', id: operatoridsdeleteArrys[y] }); deleteOperatorRecord.setValue({ fieldId: 'isinactive', value: true }) deleteOperatorRecord.setValue({ fieldId: 'custrecord_operator_status', value: 3 }) var getOperatorEmail = deleteOperatorRecord.getValue({ fieldId: 'custrecord_operator_email' }) var getOperatorName = deleteOperatorRecord.getValue({ fieldId: 'name' }) deleteOperatorRecord.save(); var email_body = ' Delete Operator NS ID: ' + operatoridsdeleteArrys[y] + '</br> Franchisee NS ID: ' + zeeRecordId + '</br> Operator Name: ' + getOperatorName + '</br> Operator Email: ' + getOperatorEmail; email.send({ author: 112209, recipients: ['efpyi@example.com'], subject: 'MP Operator Access - Delete/Inactive Operator', body: email_body, cc: ['efpyi@example.com', 'lyhxr@example.com', 'dycjh@example.com', 'envkt@example.com' ] }); } } //ADD/EDIT FLEET DETAILS if (!isNullorEmpty(fleetidsArrys)) { for (var w = 0; w < fleetidsArrys.length; w++) { var vehicleRecord = record.load({ type: 'customrecord_vehicle', id: fleetidsArrys[w] }); vehicleRecord.setValue({ fieldId: 'name', value: fleetregoArrys[w] }) vehicleRecord.setValue({ fieldId: 'custrecord_vehicle_model_text', value: fleetmodelArrys[w] }) vehicleRecord.setValue({ fieldId: 'custrecord_vehicle_make', value: fleetmakeArrys[w] }) vehicleRecord.setValue({ fieldId: 'custrecord_vehicle_colour', value: fleetcolorArrys[w] }) vehicleRecord.setValue({ fieldId: 'custrecord_vehicle_year', value: fleetyearArrys[w] }) if (fleetsignageArrys[w] == 1 || fleetsignageArrys[w] == '1') { vehicleRecord.setValue({ fieldId: 'custrecord_vehicle_signage', value: true }) } vehicleRecord.setValue({ fieldId: 'custrecord_cargo_cage', value: caregocageArrys[w] }) vehicleRecord.setValue({ fieldId: 'custrecord_vehicle_owner', value: ownerArrys[w] }) vehicleRecord.setValue({ fieldId: 'custrecord_vehicle_date_reviewed', value: getDateToday() }) var newFleetID = vehicleRecord.save() //SAVE FLEET DETAILS ON THE OPERATOR RECORD var operatorRecord = record.load({ type: 'customrecord_operator', id: operatorArrys[w] }); operatorRecord.setValue({ fieldId: 'custrecord_operator_vehicle', value: newFleetID }) operatorRecord.save(); } } //CREATE NEW FLEET DETAILS if (!isNullorEmpty(newfleetidsArrys)) { for (var w = 0; w < newfleetidsArrys.length; w++) { var vehicleRecord = record.create({ type: 'customrecord_vehicle' }); vehicleRecord.setValue({ fieldId: 'name', value: newfleetregoArrys[w] }) vehicleRecord.setValue({ fieldId: 'custrecord_vehicle_franchisee', value: zeeRecordId }) vehicleRecord.setValue({ fieldId: 'custrecord_vehicle_model_text', value: newfleetmodelArrys[w] }) vehicleRecord.setValue({ fieldId: 'custrecord_vehicle_make', value: newfleetmakeArrys[w] }) vehicleRecord.setValue({ fieldId: 'custrecord_vehicle_colour', value: newfleetcolorArrys[w] }) vehicleRecord.setValue({ fieldId: 'custrecord_vehicle_year', value: newfleetyearArrys[w] }) if (newfleetsignageArrys[w] == 1 || newfleetsignageArrys[w] == '1') { vehicleRecord.setValue({ fieldId: 'custrecord_vehicle_signage', value: true }) } vehicleRecord.setValue({ fieldId: 'custrecord_cargo_cage', value: newcaregocageArrys[w] }) vehicleRecord.setValue({ fieldId: 'custrecord_vehicle_owner', value: newownerArrys[w] }) vehicleRecord.setValue({ fieldId: 'custrecord_vehicle_date_reviewed', value: getDateToday() }) var newFleetID = vehicleRecord.save() //SAVE FLEET DETAILS ON THE OPERATOR RECORD var operatorRecord = record.load({ type: 'customrecord_operator', id: newoperatorArrys[w] }); operatorRecord.setValue({ fieldId: 'custrecord_operator_vehicle', value: newFleetID }) operatorRecord.save() } } if (!isNullorEmpty(fleetidsdeleteArrys)) { for (var y = 0; y < fleetidsdeleteArrys.length; y++) { var deleteFleetRecord = record.load({ type: 'customrecord_vehicle', id: fleetidsdeleteArrys[y] }); deleteFleetRecord.setValue({ fieldId: 'isinactive', value: true }) deleteFleetRecord.save() } } redirect.toSuitelet({ scriptId: 'customscript_sl2_zee_management_console', deploymentId: 'customdeploy1', }); } } /* * PURPOSE : ADDS SPACING * PARAMS : * RETURNS : INLINEHTML * NOTES : */ function spacing() { var inlineHtml = '<div class="form-group spacing_section">'; inlineHtml += '<div class="row">'; inlineHtml += '</div>'; inlineHtml += '</div>'; return inlineHtml; } /* * PURPOSE : ADDS HORIZONTAL LINE TO DIVIDE SECTIONS * PARAMS : * RETURNS : INLINEHTML * NOTES : */ function line() { var inlineHtml = '<hr style="height:5px; width:100%; border-width:0; color:red; background-color:#fff">' return inlineHtml } /* * PURPOSE : PROGRESS BAR AT THE TOP OF THE PAGE TO SHOW AT WHAT STAGE THE FRANCHISE SALES & MANAGEMENT WORKFLOW IS AT. ONLY SEEN TO THE HEADOFFICE USERS NOT AVAILABLE TO THE FRANCHISEES * PARAMS : * RETURNS : INLINEHTML * NOTES : */ function progressBar() { var inlineHtml = '<div class="form-group progress_section">'; inlineHtml += '<div class="row">'; inlineHtml += '<div class=""> <div class="wrapper"> <div class="arrow-steps clearfix"><div class="step"> <span>SALES PROCESS</span> </div><div class="step"> <span>FINANCIALS</span> </div><div class="step"> <span>PRESENTATIONS & INTERVIEW</span> </div><div class="step"> <span>SETTLEMENT</span> </div><div class="step"> <span><span class="glyphicon glyphicon-ok" style="color: #fff"></span>TRAINING</span> </div><div class="step"> <span>FRANCHISE AGREEMENTS</span> </div><div class="step"> <span>NETSUITE SETUP</span> </div><div class="step"> <span>ONBOARDING</span> </div><div class="step current"> <span>UPDATE/EDIT DETAILS</span> </div></div>'; // inlineHtml += '<div class="nav clearfix"><a href="#" class="prev">Previous</a><a href="#" class="next pull-right">Next</a></div></div></div>' inlineHtml += '</div></div>' inlineHtml += '</div>'; inlineHtml += '</div>'; return inlineHtml } /* * PURPOSE : BUTTONS SECTION AT THE END OF THE PAGE. * PARAMS : USER ROLE * RETURNS : INLINEHTML * NOTES : */ function mainButtons(role) { var inlineHtml = '' if (role != 1000) { inlineHtml += '<div class="form-group container zee_available_buttons_section">'; inlineHtml += '<div class="row">'; inlineHtml += '<div class="col-xs-6 updateDetails"><input type="button" value="UPDATE DETAILS" class="form-control btn btn-primary" id="updateDetails" /></div>' if (franchiseeListedForSale != 1) { inlineHtml += '<div class="col-xs-6 listForSale"><input type="button" value="LIST FOR SALE" class="form-control btn btn-success" id="listForSale" /></div>' } else { inlineHtml += '<div class="col-xs-6 listForSale"><input type="button" value="LISTED FOR SALE" class="form-control btn btn-success" id="" disabled/></div>' } inlineHtml += '</div>'; inlineHtml += '</div>'; inlineHtml += '<div class="form-group container zee_admin_section">'; inlineHtml += '<div class="row">'; inlineHtml += '<div class="col-xs-3 sendEmail"><input type="button" value="Send Email" class="form-control btn btn-primary" id="sendEmail" /></div>' inlineHtml += '<div class="col-xs-3 sendSMS"><input type="button" value="Send SMS" class="form-control btn btn-primary" id="sendSMS" /></div>' inlineHtml += '<div class="col-xs-3 breachNotice"><input type="button" value="Breach Notice" class="form-control btn btn-warning" id="breachNotice" /></div>' inlineHtml += '<div class="col-xs-3 termination"><input type="button" value="Termination" class="form-control btn btn-danger" id="termination" /></div>' inlineHtml += '</div>'; inlineHtml += '</div>'; } else { inlineHtml += '<div class="form-group container zee_available_buttons_section">'; inlineHtml += '<div class="row">'; inlineHtml += '<div class="col-xs-6 updateDetails"><input type="button" value="UPDATE DETAILS" class="form-control btn btn-primary" id="updateDetails" /></div>' if (franchiseeListedForSale != 1) { inlineHtml += '<div class="col-xs-6 listForSale"><input type="button" value="LIST FOR SALE" class="form-control btn btn-success" id="listForSale" /></div>' } else { inlineHtml += '<div class="col-xs-6 listForSale"><input type="button" value="LISTED FOR SALE" class="form-control btn btn-success" id="" disabled/></div>' } inlineHtml += '</div>'; inlineHtml += '</div>'; } return inlineHtml } /* * PURPOSE : CREATES THE TAB SECTION FOR THE PAGE * PARAMS : ZEE ID, USER ROLE & OPERATOR SEARCH RESULT * RETURNS : INLINEHTML * NOTES : */ function tabSection(zee, role, resultSetOperators) { //TAB HEADERS var inlineHtml = '<div>' inlineHtml += '<div style="width: 95%; margin:auto; margin-bottom: 30px"><ul class="nav nav-tabs nav-justified main-tabs-sections " style="margin:0%;border-bottom-color: #fbea50 !important;border-bottom-width: 5px !important;border-bottom-style: solid;">'; inlineHtml += '<li role="presentation" class="active"><a data-toggle="tab" href="#zeeDetails"><b>MAIN DETAILS</b></a></li>'; inlineHtml += '<li role="presentation" class=""><a data-toggle="tab" href="#operatorDetails"><b>OPERATION DETAILS</b></a></li>'; inlineHtml += '<li role="presentation" class=""><a data-toggle="tab" href="#tollMPEX"><b>PICKUP & LODGEMENT LOCATIONS</b></a></li>'; if (role != 1000) { inlineHtml += '<li role="presentation" class=""><a data-toggle="tab" href="#zeeAgreements"><b>AGREEMENTS</b></a></li>'; inlineHtml += '<li role="presentation" class=""><a data-toggle="tab" href="#breachDetails"><b>BREACH & TERMINATION DETAILS</b></a></li>'; } inlineHtml += '</ul></div>'; //TAB CONTENT inlineHtml += '<div class="tab-content">'; inlineHtml += '<div role="tabpanel" class="tab-pane active" id="zeeDetails">'; inlineHtml += franchiseeMainDetails(zee) inlineHtml += franchiseeNextOfKin() inlineHtml += '</div>'; inlineHtml += '<div role="tabpanel" class="tab-pane " id="zeeAgreements">'; inlineHtml += franchiseeAgreements(zee, role) inlineHtml += '</div>'; inlineHtml += '<div role="tabpanel" class="tab-pane " id="operatorDetails">'; inlineHtml += franchiseeOperatorDetails(zee, resultSetOperators) inlineHtml += franchiseeFleetDetails(zee, resultSetOperators) inlineHtml += '</div>'; inlineHtml += '<div role="tabpanel" class="tab-pane " id="tollMPEX">'; inlineHtml += franchiseeTOLLMPEX() inlineHtml += franchiseeAdhoc() inlineHtml += '</div>'; //BREACH NOTICE & TERMINATION ONLY SEEN BY HEAD OFFICE USERS if (role != 1000) { inlineHtml += '<div role="tabpanel" class="tab-pane " id="breachDetails">'; inlineHtml += franchiseeBreachDetails() inlineHtml += franchiseeTerminationDetails() inlineHtml += '</div>'; } inlineHtml += '</div></div>'; return inlineHtml; } /* * PURPOSE : SELECT FRANCHISEE TO UPDATE. ONLY AVAILABLE FOR HEADOFFICE USERS * PARAMS : ZEE ID * RETURNS : INLINEHTML * NOTES : */ function selectFranchiseeSection(zee) { var inlineHtml = '<div class="form-group container zee_section">'; inlineHtml += '<div class="row">'; inlineHtml += '<div class="col-xs-12 heading1"><h4><span class="label label-default col-xs-12" style="background-color: #103D39;">SELECT FRANCHISEE</span></h4></div>'; inlineHtml += '</div>'; inlineHtml += '</div>'; inlineHtml += '<div class="form-group container zee_select_section">'; inlineHtml += '<div class="row">'; inlineHtml += '<div class="col-xs-12 zee"><div class="input-group"><span class="input-group-addon" id="zee_text">FRANCHISEE <span class="mandatory">*</span></span><select id="zee_dropdown" class="form-control zee" ><option value=0></option>'; //NetSuite Search: Zee Management Console - Franchisees var searchZees = search.load({ id: 'customsearch_zee_management_console_zee', type: 'partner' }); var resultSetZees = searchZees.run(); resultSetZees.each(function (searchResultZees) { zeeId = searchResultZees.getValue('internalid'); franchiseeName = searchResultZees.getValue('companyname'); mainContact = searchResultZees.getValue('custentity3'); mainContactFName = searchResultZees.getValue( 'custentity_franchisee_firstname'); mainContactLName = searchResultZees.getValue( 'custentity_franchisee_lastname'); primaryEmail = searchResultZees.getValue('email'); personalEmail = searchResultZees.getValue( 'custentity_personal_email_address'); mainContactMobile = searchResultZees.getValue( 'custentity2'); franchiseeABN = searchResultZees.getValue( 'custentity_abn_franchiserecord'); franchiseeAddress = searchResultZees.getValue( 'shipaddress'); if (zeeId == zee) { inlineHtml += '<option value="' + zeeId + '" selected>' + franchiseeName + '</option>'; } else { inlineHtml += '<option value="' + zeeId + '">' + franchiseeName + '</option>'; } return true; }); inlineHtml += '</select></div></div>'; inlineHtml += '</div>'; inlineHtml += '</div>'; return inlineHtml; } /* * PURPOSE : FRANCHISE MAIN DETAILS TAB * PARAMS : ZEE ID * RETURNS : INLINEHTML * NOTES : */ function franchiseeMainDetails(zee) { //NetSuite Search: Zee Management Console - Franchisees var searchZees = search.load({ id: 'customsearch_zee_management_console_zee', type: 'partner' }); if (!isNullorEmpty(zee)) { searchZees.filters.push(search.createFilter({ name: 'internalid', join: null, operator: search.Operator.IS, values: zee })); } var resultSetZees = searchZees.run(); resultSetZees.each(function (searchResultZees) { zeeId = searchResultZees.getValue('internalid'); franchiseeName = searchResultZees.getValue('companyname'); mainContact = searchResultZees.getValue('custentity3'); mainContactFName = searchResultZees.getValue( 'custentity_franchisee_firstname'); mainContactLName = searchResultZees.getValue( 'custentity_franchisee_lastname'); primaryEmail = searchResultZees.getValue('email'); personalEmail = searchResultZees.getValue( 'custentity_personal_email_address'); mainContactMobile = searchResultZees.getValue( 'custentity2'); franchiseeABN = searchResultZees.getValue( 'custentity_abn_franchiserecord'); franchiseeAddress = searchResultZees.getValue( 'shipaddress'); franchiseeTOLLAccountNumber = searchResultZees.getValue( 'custentity_toll_acc_number'); franchiseeTOLLPickupDX = searchResultZees.getText( 'custentity__toll_pickup_dx_no'); franchiseeTOLLLodgementDX = searchResultZees.getText( 'custentity_toll_lodge_dx_no'); franchiseeSendlePrimaryLocations = searchResultZees.getText( 'custentity_sendle_hubbed_locations'); franchiseeLastMileLocations = searchResultZees.getText( 'custentity_lastmile_suburb'); franchiseeSendleSecondaryLocations = searchResultZees.getText( 'custentity_sendle_hubbed_location_sec'); franchiseeTypeOfOwner = searchResultZees.getValue( 'custentity_type_of_owner'); vaccinationStatus = searchResultZees.getValue( 'custentity_vacc_status'); dob = searchResultZees.getValue( 'custentity_zee_dob'); personalEmail = searchResultZees.getValue( 'custentity_personal_email_address'); franchiseeNextOfKinMobile = searchResultZees.getValue( 'custentity_kin_mobile'); franchiseeNextOfKinName = searchResultZees.getValue( 'custentity_kin_name'); franchiseeNextOfKinRelationship = searchResultZees.getValue( 'custentity_kin_relationship'); franchiseeListedForSale = searchResultZees.getValue( 'custentity_listed_for_sale'); return true; }); //NetSuite Search: SALESP - Addresses var searched_addresses = search.load({ id: 'customsearch_salesp_address', type: 'customer' }); searched_addresses.filters.push(search.createFilter({ name: 'internalid', operator: search.Operator.ANYOF, values: zee })); resultSetAddresses = searched_addresses.run(); var inlineHtml = '<div class="form-group container">'; inlineHtml += '<div class="row">'; inlineHtml += '<div class="col-xs-12 heading1"><h4><span class="label label-default col-xs-12" style="background-color: #103D39;">FRANCHISEE DETAILS</span></h4></div>'; inlineHtml += '</div>'; inlineHtml += '</div>'; inlineHtml += '<div class="form-group container">'; inlineHtml += '<div class="row">'; inlineHtml += '<div class="col-xs-12 name_section"><div class="input-group"><span class="input-group-addon">FRANCHISE NAME</span><input id="franchiseeName" class="form-control franchiseeName" value="' + franchiseeName + '" readonly/></div></div>'; inlineHtml += '</div>'; inlineHtml += '</div>'; inlineHtml += '<div class="form-group container">'; inlineHtml += '<div class="row">'; inlineHtml += '<div class="col-xs-6 name_section"><div class="input-group"><span class="input-group-addon">MAIN CONTACT</span><input id="mainContact" data-old="' + mainContact + '" class="form-control mainContact" value="' + mainContact + '" /></div></div>'; inlineHtml += '<div class="col-xs-6 name_section"><div class="input-group"><span class="input-group-addon">MOBILE NUMBER <span class="mandatory">*</span></span><input id="mainContactMobile" class="form-control mainContact" value="' + mainContactMobile + '" data-old="' + mainContactMobile + '"/></div></div>'; inlineHtml += '</div>'; inlineHtml += '</div>'; inlineHtml += '<div class="form-group container">'; inlineHtml += '<div class="row">'; inlineHtml += '<div class="col-xs-6 zee"><div class="input-group"><span class="input-group-addon" id="zee_text">TYPE OF OWNER <span class="mandatory">*</span></span><select id="franchiseeTypeOfOwner" class="form-control franchiseeTypeOfOwner" data-old="' + franchiseeTypeOfOwner + '">'; if (franchiseeTypeOfOwner == 0 || isNullorEmpty(franchiseeTypeOfOwner)) { inlineHtml += '<option value=0></option><option value=1>COMPANY OWNED</option><option value=2>INVESTOR</option><option value=3>Owner / Operator</option>'; } else if (franchiseeTypeOfOwner == 1) { inlineHtml += '<option value=0></option><option value=1 selected>COMPANY OWNED</option><option value=2>INVESTOR</option><option value=3>Owner / Operator</option>'; } else if (franchiseeTypeOfOwner == 2) { inlineHtml += '<option value=0></option><option value=1>COMPANY OWNED</option><option value=2 selected>INVESTOR</option><option value=3>Owner / Operator</option>'; } else if (franchiseeTypeOfOwner == 3) { inlineHtml += '<option value=0></option><option value=1>COMPANY OWNED</option><option value=2>INVESTOR</option><option value=3 selected>Owner / Operator</option>'; } inlineHtml += '</select></div></div>'; inlineHtml += '<div class="col-xs-6 name_section"><div class="input-group"><span class="input-group-addon">ABN</span><input id="franchiseeABN" class="form-control franchiseeABN" readonly value="' + franchiseeABN + '" /></div></div>'; inlineHtml += '</div>'; inlineHtml += '</div>'; inlineHtml += '<div class="form-group container">'; inlineHtml += '<div class="row">'; inlineHtml += '<div class="col-xs-6 name_section"><div class="input-group"><span class="input-group-addon">PRIMARY EMAIL</span><input id="primaryEmail" class="form-control primaryEmail" value="' + primaryEmail + '" readonly/></div></div>'; inlineHtml += '<div class="col-xs-6 name_section"><div class="input-group"><span class="input-group-addon">PERSONAL EMAIL <span class="mandatory">*</span></span><input id="personalEmail" class="form-control personalEmail" value="' + personalEmail + '" data-old="' + personalEmail + '" /></div></div>'; inlineHtml += '</div>'; inlineHtml += '</div>'; inlineHtml += '<div class="form-group container company_name_section">'; inlineHtml += '<div class="row">'; var dobArray = dob.split('/'); if (dobArray[1] < 10) { dobArray[1] = '0' + dobArray[1]; } if (dobArray[0] < 10) { dobArray[0] = '0' + dobArray[0]; } var formattedDOB = dobArray[2] + '-' + dobArray[1] + '-' + dobArray[0] inlineHtml += '<div class="col-xs-6 name_section"><div class="input-group"><span class="input-group-addon">DATE OF BIRTH <span class="mandatory">*</span></span><input id="dob" type="date" class="form-control dob" value="' + formattedDOB + '" data-old="' + formattedDOB + '"/></div></div>'; inlineHtml += '<div class="col-xs-6 zee"><div class="input-group"><span class="input-group-addon" id="zee_text">VACCINATION STATUS <span class="mandatory">*</span></span><select id="vaccinationStatus" class="form-control vaccinationStatus" data-old="' + vaccinationStatus + '">'; if (vaccinationStatus == 1) { inlineHtml += '<option value=0></option><option value=1 selected>YES</option><option value=2>NO</option>'; } else if (vaccinationStatus == 2) { inlineHtml += '<option value=0></option><option value=1>YES</option><option value=2 selected>NO</option>'; } else { inlineHtml += '<option value=0 selected></option><option value=1>YES</option><option value=2>NO</option>'; } inlineHtml += '</select></div></div>'; inlineHtml += '</div>'; inlineHtml += '</div>'; inlineHtml += '<div class="form-group container">'; inlineHtml += '<div class="row">'; inlineHtml += '<div class="col-xs-12 heading1"><h4><span class="label label-default col-xs-12" style="background-color: #103D39;">ADDRESS DETAILS</span></h4></div>'; inlineHtml += '</div>'; inlineHtml += '</div>'; //HIDDEN SECTION TO ADD/EDIT ADDRESS DETAILS inlineHtml += '<div class="form-group container row_address1 hide">' inlineHtml += '<div class="row">'; inlineHtml += '<input id="internalid" value="" type="hidden"/>' inlineHtml += '<div class="col-xs-6 address1_section"><div class="input-group"><span class="input-group-addon">UNIT/LEVEL/SUITE</span><input id="address1" class="form-control address1" /></div></div>'; inlineHtml += '<div class="col-xs-6 address2_section"><div class="input-group"><span class="input-group-addon">STREET NO. & NAME <span class="mandatory">*</span></span><input id="address2" class="form-control address2" /></div></div>'; inlineHtml += '</div>'; inlineHtml += '</div>'; inlineHtml += '<div class="form-group container city_state_postcode hide">' inlineHtml += '<div class="row">'; inlineHtml += '<div class="col-xs-6"><div class="input-group"><span class="input-group-addon">CITY</span><input id="city" readonly class="form-control city" /></div></div>'; inlineHtml += '<div class="col-xs-3"><div class="input-group"><span class="input-group-addon">STATE</span><input id="state" readonly class="form-control state" /></div></div>'; inlineHtml += '<div class="col-xs-3 post_code_section"><div class="input-group"><span class="input-group-addon">POSTCODE</span><input id="postcode" readonly class="form-control postcode" /></div></div>'; inlineHtml += '</div>'; inlineHtml += '</div>'; inlineHtml += '<div class="form-group container saveaddress_section hide">'; inlineHtml += '<div class="row">'; inlineHtml += '<div class="col-xs-2 "></div>'; inlineHtml += '<div class="col-xs-4 reviewaddress"><input type="button" value="SAVE ADDRESSES" class="form-control btn btn-success" id="saveAddress" /></div>'; inlineHtml += '<div class="col-xs-4 cancel"><input type="button" value="CANCEL" class="form-control btn btn-secondary" id="cancel" /></div>'; inlineHtml += '<div class="col-xs-2 "></div>'; inlineHtml += '</div>'; inlineHtml += '</div>'; //ADDRESS TABLE inlineHtml += addressContactsSection(resultSetAddresses); return inlineHtml } /* * PURPOSE : LIST OF FRANCHISEE AGREEMENTS RELATED TO THE ZEE * PARAMS : ZEE ID & USER ROLE * RETURNS : INLINEHTML * NOTES : */ function franchiseeAgreements(zee, role) { //NetSuite Search: Zee Agreement - Search var searchZeeAgreements = search.load({ id: 'customsearch_zee_agree_search', type: 'customrecord_fr_agreements' }); if (!isNullorEmpty(zee)) { searchZeeAgreements.filters.push(search.createFilter({ name: 'internalid', join: 'CUSTRECORD_FR_AGREEMENT_FRANCHISEE', operator: search.Operator.IS, values: zee })); } var resultSetZeeAgreements = searchZeeAgreements.run(); var inlineHtml = '<div class="form-group container">'; inlineHtml += '<div class="row">'; inlineHtml += '<div class="col-xs-12 heading1"><h4><span class="label label-default col-xs-12" style="background-color: #103D39;">FRANCHISE AGREEMENTS</span></h4></div>'; inlineHtml += '</div>'; inlineHtml += '</div>'; inlineHtml += '<div class="form-group container">'; inlineHtml += '<div class="row">'; inlineHtml += '<style>table#zeeAgreementsTable {color: #103D39 !important; font-size: 12px;text-align: center;border: none;}.dataTables_wrapper {font-size: 14px;}table#zeeAgreementsTable th{text-align: center;} .bolded{font-weight: bold;}</style>'; inlineHtml += '<table id="zeeAgreementsTable" class="table table-responsive table-striped zeeAgreementsTable tablesorter" style="width: 100%;border: 1px solid #103d39;">'; inlineHtml += '<thead style="color: white;background-color: #379E8F;font-weight: bold;">'; inlineHtml += '<tr class="text-center">'; //ABILITY TO ADD/EDIT ONLY FOR HEADOFFICE USERS if (role != 1000) { inlineHtml += '<td>LINK</td>' } inlineHtml += '<td>NS ID</td>' inlineHtml += '<td>NAME</td>' inlineHtml += '<td>COMMENCEMENT DATE</td>' inlineHtml += '<td>EXPIRY DATE</td>' inlineHtml += '<td>ULTIMATE EXPIRY DATE</td>' inlineHtml += '<td>RENEWAL TERMS</td>' inlineHtml += '<td>AGREEMENT</td>' inlineHtml += '<td>AGREEMENT STATUS</td>' inlineHtml += '</tr>'; inlineHtml += '</thead>'; inlineHtml += '<tbody id="resultOperatorTable" class="">'; resultSetZeeAgreements.each(function (searchResultZeeAgreements) { zeeAgreementID = searchResultZeeAgreements.getValue('internalid'); zeeAgreementName = searchResultZeeAgreements.getValue('name'); zeeAgreementCommDate = searchResultZeeAgreements.getValue( 'custrecord_fr_agreement_comm_date'); zeeAgreementExpiryDate = searchResultZeeAgreements.getValue( 'custrecord_fr_agreement_expiry_date'); zeeAgreementUltExpiryDate = searchResultZeeAgreements.getValue( 'custrecord_fr_agreement_ult_expiry_date'); zeeAgreementStatus = searchResultZeeAgreements.getText( 'custrecord_fr_agreement_status'); zeeAgreementYearsExtended = searchResultZeeAgreements.getValue( 'custrecord_fr_agreement_yrs_extended'); zeeAgreementDeed = searchResultZeeAgreements.getValue( 'custrecord_fr_agreement_deed'); 1182 inlineHtml += '<tr>' //SHOW EDIT/DELETE LINKS TO ONLY HEADOFFICE USERS if (role != 1000) { inlineHtml += '<td><button class="form-control btn btn-xs btn-primary glyphicon glyphicon-pencil" style="cursor: not-allowed !important;width: fit-content;"><a data-id="' + zeeAgreementID + '" class="editOperator" style="cursor: pointer !important;color: white;"></a></button> <button class="form-control btn btn-xs btn-danger glyphicon glyphicon-trash" style="cursor: not-allowed !important;width: fit-content;"><a data-id="' + zeeAgreementID + '" class="deleteOperator" style="cursor: pointer !important;color: white;"></a></button></td>' } inlineHtml += '<td>' + zeeAgreementID + '</td>' inlineHtml += '<td><b><a href="https://1048144.app.netsuite.com/app/common/custom/custrecordentry.nl?rectype=384&id=' + zeeAgreementID + '">' + zeeAgreementName + '</a></b></td>' inlineHtml += '<td>' + zeeAgreementCommDate + '</td>' inlineHtml += '<td>' + zeeAgreementExpiryDate + '</td>' inlineHtml += '<td>' + zeeAgreementUltExpiryDate + '</td>' inlineHtml += '<td>' + zeeAgreementYearsExtended + '</td>' inlineHtml += '<td>' + zeeAgreementDeed + '</td>' inlineHtml += '<td>' + zeeAgreementStatus + '</td>' inlineHtml += '</tr>'; return true; }); inlineHtml += '</tbody></table>'; inlineHtml += '</div>'; inlineHtml += '</div>'; //ABILITY TO CREATE NEW AGREEMENT TO ONLY HEADOFFICE USERS if (role != 1000) { inlineHtml += franchiseeNewAgreement() } return inlineHtml; } /* * PURPOSE : TOLL MPEX RELATED DATA. * PARAMS : * RETURNS : INLINEHTML * NOTES : */ function franchiseeTOLLMPEX() { var inlineHtml = '<div class="form-group container">'; inlineHtml += '<div class="row">'; inlineHtml += '<div class="col-xs-12 heading1"><h4><span class="label label-default col-xs-12" style="background-color: #103D39;">TOLL - MPEX</span></h4></div>'; inlineHtml += '</div>'; inlineHtml += '</div>'; inlineHtml += '<div class="form-group container">'; inlineHtml += '<div class="row">'; inlineHtml += '<div class="col-xs-6 name_section"><div class="input-group"><span class="input-group-addon">TOLL Account Number</span><input id="franchiseeTOLLAccountNumber" class="form-control franchiseeTOLLAccountNumber" value="' + franchiseeTOLLAccountNumber + '" readonly/></div></div>'; inlineHtml += '</div>'; inlineHtml += '</div>'; inlineHtml += '<div class="form-group container">'; inlineHtml += '<div class="row">'; inlineHtml += '<div class="col-xs-6 name_section"><div class="input-group"><span class="input-group-addon">TOLL Pickup DX </span><input id="franchiseeTOLLPickupDX" class="form-control franchiseeTOLLPickupDX" readonly value="' + franchiseeTOLLPickupDX + '" /></div></div>'; inlineHtml += '<div class="col-xs-6 name_section"><div class="input-group"><span class="input-group-addon">TOLL Lodgement DX </span><input id="franchiseeTOLLLodgementDX" class="form-control franchiseeTOLLLodgementDX" readonly value="' + franchiseeTOLLLodgementDX + '" /></div></div>'; inlineHtml += '</div>'; inlineHtml += '</div>'; return inlineHtml; } /* * PURPOSE : FRANCHISE NEXT OF KIN DETAILS * PARAMS : * RETURNS : INLINEHTML * NOTES : */ function franchiseeNextOfKin() { var inlineHtml = '<div class="form-group container">'; inlineHtml += '<div class="row">'; inlineHtml += '<div class="col-xs-12 heading1"><h4><span class="label label-default col-xs-12" style="background-color: #103D39;">NEXT OF KIN</span></h4></div>'; inlineHtml += '</div>'; inlineHtml += '</div>'; inlineHtml += '<div class="form-group container">'; inlineHtml += '<div class="row">'; inlineHtml += '<div class="col-xs-4 name_section"><div class="input-group"><span class="input-group-addon">NAME <span class="mandatory">*</span></span><input id="franchiseeNextOfKinName" type="text" class="form-control franchiseeNextOfKinName" value="' + franchiseeNextOfKinName + '" data-old="' + franchiseeNextOfKinName + '"/></div></div>'; inlineHtml += '<div class="col-xs-3 name_section"><div class="input-group"><span class="input-group-addon">MOBILE NUMBER <span class="mandatory">*</span></span><input id="franchiseeNextOfKinMobile" class="form-control franchiseeNextOfKinMobile" value="' + franchiseeNextOfKinMobile + '" data-old="' + franchiseeNextOfKinMobile + '"/></div></div>'; inlineHtml += '<div class="col-xs-5 zee"><div class="input-group"><span class="input-group-addon" id="zee_text">RELATIONSHIP <span class="mandatory">*</span></span><select id="franchiseeNextOfKinRelationship" class="form-control franchiseeNextOfKinRelationship" data-old="' + franchiseeNextOfKinRelationship + '"><option value=0></option>'; /* Brother 5 Daughter 7 Father 1 Friend 9 Mother 2 Other 10 Partner 4 Sister 8 Son 6 Spouse 3 */ log.debug({ title: 'franchiseeNextOfKinRelationship', details: franchiseeNextOfKinRelationship }) switch (parseInt(franchiseeNextOfKinRelationship)) { case 5: inlineHtml += '<option value=0></option>'; inlineHtml += '<option value=5 selected>Brother</option>'; inlineHtml += '<option value=7>Daughter</option>'; inlineHtml += '<option value=1>Father</option>'; inlineHtml += '<option value=9>Friend</option>'; inlineHtml += '<option value=2>Mother</option>'; inlineHtml += '<option value=4>Partner</option>'; inlineHtml += '<option value=8>Sister</option>'; inlineHtml += '<option value=6>Son</option>'; inlineHtml += '<option value=3>Spouse</option>'; inlineHtml += '<option value=10>Other</option>'; break; case 7: inlineHtml += '<option value=0></option>'; inlineHtml += '<option value=5>Brother</option>'; inlineHtml += '<option value=7 selected>Daughter</option>'; inlineHtml += '<option value=1>Father</option>'; inlineHtml += '<option value=9>Friend</option>'; inlineHtml += '<option value=2>Mother</option>'; inlineHtml += '<option value=4>Partner</option>'; inlineHtml += '<option value=8>Sister</option>'; inlineHtml += '<option value=6>Son</option>'; inlineHtml += '<option value=3>Spouse</option>'; inlineHtml += '<option value=10>Other</option>'; break; case 1: inlineHtml += '<option value=0></option>'; inlineHtml += '<option value=5>Brother</option>'; inlineHtml += '<option value=7>Daughter</option>'; inlineHtml += '<option value=1 selected>Father</option>'; inlineHtml += '<option value=9>Friend</option>'; inlineHtml += '<option value=2>Mother</option>'; inlineHtml += '<option value=4>Partner</option>'; inlineHtml += '<option value=8>Sister</option>'; inlineHtml += '<option value=6>Son</option>'; inlineHtml += '<option value=3>Spouse</option>'; inlineHtml += '<option value=10>Other</option>'; break; case 9: inlineHtml += '<option value=0></option>'; inlineHtml += '<option value=5>Brother</option>'; inlineHtml += '<option value=7>Daughter</option>'; inlineHtml += '<option value=1>Father</option>'; inlineHtml += '<option value=9 selected>Friend</option>'; inlineHtml += '<option value=2>Mother</option>'; inlineHtml += '<option value=4>Partner</option>'; inlineHtml += '<option value=8>Sister</option>'; inlineHtml += '<option value=6>Son</option>'; inlineHtml += '<option value=3>Spouse</option>'; inlineHtml += '<option value=10>Other</option>'; break; case 2: inlineHtml += '<option value=0></option>'; inlineHtml += '<option value=5>Brother</option>'; inlineHtml += '<option value=7>Daughter</option>'; inlineHtml += '<option value=1>Father</option>'; inlineHtml += '<option value=9>Friend</option>'; inlineHtml += '<option value=2 selected>Mother</option>'; inlineHtml += '<option value=4>Partner</option>'; inlineHtml += '<option value=8>Sister</option>'; inlineHtml += '<option value=6>Son</option>'; inlineHtml += '<option value=3>Spouse</option>'; inlineHtml += '<option value=10>Other</option>'; break; case 10: inlineHtml += '<option value=0></option>'; inlineHtml += '<option value=5>Brother</option>'; inlineHtml += '<option value=7>Daughter</option>'; inlineHtml += '<option value=1>Father</option>'; inlineHtml += '<option value=9>Friend</option>'; inlineHtml += '<option value=2>Mother</option>'; inlineHtml += '<option value=4>Partner</option>'; inlineHtml += '<option value=8>Sister</option>'; inlineHtml += '<option value=6>Son</option>'; inlineHtml += '<option value=3>Spouse</option>'; inlineHtml += '<option value=10 selected>Other</option>'; break; case 4: inlineHtml += '<option value=0></option>'; inlineHtml += '<option value=5>Brother</option>'; inlineHtml += '<option value=7>Daughter</option>'; inlineHtml += '<option value=1>Father</option>'; inlineHtml += '<option value=9>Friend</option>'; inlineHtml += '<option value=2>Mother</option>'; inlineHtml += '<option value=4 selected>Partner</option>'; inlineHtml += '<option value=8>Sister</option>'; inlineHtml += '<option value=6>Son</option>'; inlineHtml += '<option value=3>Spouse</option>'; inlineHtml += '<option value=10>Other</option>'; break; case 8: inlineHtml += '<option value=0></option>'; inlineHtml += '<option value=5>Brother</option>'; inlineHtml += '<option value=7>Daughter</option>'; inlineHtml += '<option value=1>Father</option>'; inlineHtml += '<option value=9>Friend</option>'; inlineHtml += '<option value=2>Mother</option>'; inlineHtml += '<option value=4>Partner</option>'; inlineHtml += '<option value=8 selected>Sister</option>'; inlineHtml += '<option value=6>Son</option>'; inlineHtml += '<option value=3>Spouse</option>'; inlineHtml += '<option value=10>Other</option>'; break; case 6: inlineHtml += '<option value=0></option>'; inlineHtml += '<option value=5>Brother</option>'; inlineHtml += '<option value=7>Daughter</option>'; inlineHtml += '<option value=1>Father</option>'; inlineHtml += '<option value=9>Friend</option>'; inlineHtml += '<option value=2>Mother</option>'; inlineHtml += '<option value=4>Partner</option>'; inlineHtml += '<option value=8>Sister</option>'; inlineHtml += '<option value=6 selected>Son</option>'; inlineHtml += '<option value=3>Spouse</option>'; inlineHtml += '<option value=10>Other</option>'; break; case 3: inlineHtml += '<option value=0></option>'; inlineHtml += '<option value=5>Brother</option>'; inlineHtml += '<option value=7>Daughter</option>'; inlineHtml += '<option value=1>Father</option>'; inlineHtml += '<option value=9>Friend</option>'; inlineHtml += '<option value=2>Mother</option>'; inlineHtml += '<option value=4>Partner</option>'; inlineHtml += '<option value=8>Sister</option>'; inlineHtml += '<option value=6>Son</option>'; inlineHtml += '<option value=3 selected>Spouse</option>'; inlineHtml += '<option value=10>Other</option>'; break; default: inlineHtml += '<option value=0 selected></option>'; inlineHtml += '<option value=5>Brother</option>'; inlineHtml += '<option value=7>Daughter</option>'; inlineHtml += '<option value=1>Father</option>'; inlineHtml += '<option value=9>Friend</option>'; inlineHtml += '<option value=2>Mother</option>'; inlineHtml += '<option value=4>Partner</option>'; inlineHtml += '<option value=8>Sister</option>'; inlineHtml += '<option value=6>Son</option>'; inlineHtml += '<option value=3>Spouse</option>'; inlineHtml += '<option value=10>Other</option>'; break; } inlineHtml += '</select></div></div>'; inlineHtml += '</div>'; inlineHtml += '</div>'; return inlineHtml; } /* * PURPOSE : FRANCHISEE FIRST & LAST MILE DETAILS * PARAMS : * RETURNS : INLINEHTML * NOTES : */ function franchiseeAdhoc() { var inlineHtml = '<div class="form-group container">'; inlineHtml += '<div class="row">'; inlineHtml += '<div class="col-xs-12 heading1"><h4><span class="label label-default col-xs-12" style="background-color: #103D39;">ADHOC</span></h4></div>'; inlineHtml += '</div>'; inlineHtml += '</div>'; inlineHtml += '<div class="form-group container">'; inlineHtml += '<div class="row">'; inlineHtml += '<div class="col-xs-6 name_section"><div class="input-group"><span class="input-group-addon">First Mile Primary Location</span><input id="franchiseeSendlePrimaryLocations" class="form-control franchiseeSendlePrimaryLocations" value="' + franchiseeSendlePrimaryLocations + '" readonly/></div></div>'; inlineHtml += '<div class="col-xs-6 name_section"><div class="input-group"><span class="input-group-addon">First Mile Secondary Location</span><input id="franchiseeSendleSecondaryLocations" class="form-control franchiseeSendleSecondaryLocations" value="' + franchiseeSendleSecondaryLocations + '" readonly/></div></div>'; inlineHtml += '</div>'; inlineHtml += '</div>'; //ABILITY TO ADD/EDIT FIRST MILE SUBURBS inlineHtml += franchiseeAddEditFirstMile() inlineHtml += '<div class="form-group container">'; inlineHtml += '<div class="row">'; inlineHtml += '<div class="col-xs-12 name_section"><div class="input-group"><span class="input-group-addon">Last Mile Primary Location</span><input id="franchiseeLastMileLocations" class="form-control franchiseeLastMileLocations" value="' + franchiseeLastMileLocations + '" readonly/></div></div>'; inlineHtml += '</div>'; inlineHtml += '</div>'; //BUTTON TO ADD/EDIT LAST MILE SUBURBS inlineHtml += franchiseeAddEditLastMile() return inlineHtml; } /* * PURPOSE : BUTTON TO REDIRECT PAGE TO FRANCHISE SERVICE NETWORK * PARAMS : * RETURNS : INLINEHTML * NOTES : */ function franchiseeServiceNetwork() { var inlineHtml = '<div class="form-group container company_name_section">'; inlineHtml += '<div class="row">'; inlineHtml += '<div class="col-xs-3 heading1"></div>' inlineHtml += '<div class="col-xs-6 heading1"><input type="button" value="Your Franchise Service Network" class="form-control btn btn-primary" id="serviceNetwork" style="background-color: #287587;"/></div>' inlineHtml += '<div class="col-xs-3 heading1"></div>' inlineHtml += '</div>'; inlineHtml += '</div>'; return inlineHtml } /* * PURPOSE : BUTTON TO REDIRECT PAGE TO CREATION OF NEW AGREEMENT * PARAMS : * RETURNS : INLINEHTML * NOTES : */ function franchiseeNewAgreement() { var inlineHtml = '<div class="form-group container company_name_section">'; inlineHtml += '<div class="row">'; inlineHtml += '<div class="col-xs-3 heading1"></div>' inlineHtml += '<div class="col-xs-6 heading1"><input type="button" value="New Agreement" class="form-control btn btn-primary" id="newAgreement" style="background-color: #287587;"/></div>' inlineHtml += '<div class="col-xs-3 heading1"></div>' inlineHtml += '</div>'; inlineHtml += '</div>'; return inlineHtml } /* * PURPOSE : BUTTON TO ADD NEW OPERATOR TO THE TABLE * PARAMS : * RETURNS : INLINEHTML * NOTES : */ function franchiseeAddOperator() { var inlineHtml = '<div class="form-group container company_name_section">'; inlineHtml += '<div class="row">'; inlineHtml += '<div class="col-xs-3 heading1"></div>' inlineHtml += '<div class="col-xs-6 heading1"><input type="button" value="Add New Operator" class="form-control btn btn-primary" id="addOperator" style="background-color: #287587;"/></div>' inlineHtml += '<div class="col-xs-3 heading1"></div>' inlineHtml += '</div>'; inlineHtml += '</div>'; return inlineHtml } /* * PURPOSE : BUTTON TO ADD NEW VEHICLE TO THE TABLE * PARAMS : * RETURNS : INLINEHTML * NOTES : */ function franchiseeAddFleet() { var inlineHtml = '<div class="form-group container company_name_section">'; inlineHtml += '<div class="row">'; inlineHtml += '<div class="col-xs-3 heading1"></div>' inlineHtml += '<div class="col-xs-6 heading1"><input type="button" value="Add New Fleet" class="form-control btn btn-primary" id="addFleet" style="background-color: #287587;"/></div>' inlineHtml += '<div class="col-xs-3 heading1"></div>' inlineHtml += '</div>'; inlineHtml += '</div>'; return inlineHtml } /* * PURPOSE : BUTTON TO REDIRECT PAGE TO FIRST MILE SUBURB SELECTION * PARAMS : * RETURNS : INLINEHTML * NOTES : */ function franchiseeAddEditFirstMile() { var inlineHtml = '<div class="form-group container company_name_section">'; inlineHtml += '<div class="row">'; inlineHtml += '<div class="col-xs-3 heading1"></div>' inlineHtml += '<div class="col-xs-6 heading1"><input type="button" value="Add/Edit First-Mile Suburbs" class="form-control btn btn-primary" id="firstMile" style="background-color: #287587;"/></div>' inlineHtml += '<div class="col-xs-3 heading1"></div>' inlineHtml += '</div>'; inlineHtml += '</div>'; return inlineHtml } /* * PURPOSE : BUTTON TO REDIRECT PAGE TO LAST MILE SUBURB SELECTION * PARAMS : * RETURNS : INLINEHTML * NOTES : */ function franchiseeAddEditLastMile() { var inlineHtml = '<div class="form-group container company_name_section">'; inlineHtml += '<div class="row">'; inlineHtml += '<div class="col-xs-3 heading1"></div>' inlineHtml += '<div class="col-xs-6 heading1"><input type="button" value="Add/Edit Last-Mile Suburbs" class="form-control btn btn-primary" id="lastMile" style="background-color: #287587;"/></div>' inlineHtml += '<div class="col-xs-3 heading1"></div>' inlineHtml += '</div>'; inlineHtml += '</div>'; return inlineHtml } /* * PURPOSE : Autogenerates function contract comments * PARAMS : functio - * RETURNS : - * NOTES : */ function franchiseeOperatorDetails(zee, resultSetOperators) { var operatorID = ''; var operatorName = ''; var operatorPhone = ''; var operatorEmail = ''; var operatorEmploymentType = ''; var operatorRole = ''; var operatorMobileDev = ''; var operatorDDS = ''; var operatorPrimaryOperator = ''; var inlineHtml = '<div class="form-group container">'; inlineHtml += '<div class="row">'; inlineHtml += '<div class="col-xs-12 heading1"><h4><span class="label label-default col-xs-12" style="background-color: #103D39;">SERVICE NETWORK</span></h4></div>'; inlineHtml += '</div>'; inlineHtml += '</div>'; var directionsPanel_html = ''; var print_section = ''; //show the directionsPanel only if one zee selected directionsPanel_html += '<div class="col-sm-6 " id="directionsPanel" style="height:500px; overflow:auto"></div>'; print_section += '</br><div class="row print_section hide"><div class="col-xs-10"></div><div class="col-xs-2"><input type="button" class="btn btn-info" id="printDirections" value="PRINT DIRECTIONS" style="width: 100%;"/></div></div></div>'; inlineHtml += '</br>'; inlineHtml += '<div class="container map_section "><div class="row">'; inlineHtml += '<div class="col-sm-12" id="map" style="height: 500px"><div id="loader"><img src="https://1048144.app.netsuite.com/core/media/media.nl?id=2089999&c=1048144&h=e0aef405c22b65dfe546" alt="loader" /></div></div>'; inlineHtml += '<div id="legend">'; inlineHtml += '<div class="hide legend_icons" style="background-color: rgb(255, 255, 255);box-shadow: rgba(0, 0, 0, 0.3) 0px 1px 4px -1px;border-radius: 2px;left: 0px;margin-left: 5px;padding: 3px;"><div><svg height="23" width="32"><path d="M12 2C8.13 2 5 5.13 5 9c0 5.25 7 13 7 13s7-7.75 7-13c0-3.87-3.13-7-7-7z" stroke="black" fill="#575756"/></svg><span style="font-family: sans-serif;">Non Customer Location</span></div><div><svg height="23" width="32"><path d="M12 2C8.13 2 5 5.13 5 9c0 5.25 7 13 7 13s7-7.75 7-13c0-3.87-3.13-7-7-7z" stroke="black" fill="#008675"/></svg><span style="font-family: sans-serif;">Customer Location</span></div>'; for (i = 0; i < 1; i++) { inlineHtml += '<div><svg height="15" width="32"><line x1="2" y1="10" x2="25" y2="10" style="stroke:' + color_array[i] + ';stroke-width:2" /></svg><span style="font-family: sans-serif;">' + franchiseeName + '</span></div>'; } inlineHtml += '</div>'; inlineHtml += '<div style="background-color: rgb(255, 255, 255);box-shadow: rgba(0, 0, 0, 0.3) 0px 1px 4px -1px;border-radius: 2px;left: 0px;margin-left: 5px;padding: 3px;"><input class="form-control" type="textarea" placeholder="Territory" id="zee_territory"/></div>'; inlineHtml += '</div>'; // inlineHtml += directionsPanel_html; inlineHtml += '</div>'; inlineHtml += print_section; inlineHtml += franchiseeServiceNetwork(); inlineHtml += '<div class="form-group container">'; inlineHtml += '<div class="row">'; inlineHtml += '<div class="col-xs-12 heading1"><h4><span class="label label-default col-xs-12" style="background-color: #103D39;">OPERATOR DETAILS</span></h4></div>'; inlineHtml += '</div>'; inlineHtml += '</div>'; inlineHtml += '<div class="form-group container row_operator_details hide">' inlineHtml += '<div class="row">'; inlineHtml += '<input id="operatorInternalId" value="" type="hidden"/>' inlineHtml += '<div class="col-xs-3 operatorName_section"><div class="input-group"><span class="input-group-addon">Name <span class="mandatory">*</span></span><input id="operatorName" class="form-control operatorName" /></div></div>'; inlineHtml += '<div class="col-xs-3 operatorEmail_section"><div class="input-group"><span class="input-group-addon">EMAIL <span class="mandatory">*</span></span><input id="operatorEmail" class="form-control operatorEmail" /></div></div>'; inlineHtml += '<div class="col-xs-3 operatorMobile_section"><div class="input-group"><span class="input-group-addon">MOBILE NO. <span class="mandatory">*</span></span><input id="operatorMobile" class="form-control operatorMobile" /></div></div>'; inlineHtml += '<div class="col-xs-3"><div class="input-group"><span class="input-group-addon">MOBILE DEV </span><select id="operatorMobileDev" class="form-control operatorMobileDev" >'; /* iOS 1 Android 2 Other 5 */ inlineHtml += '<option value=0></option><option value=1>iOS</option><option value=2>Android</option><option value=5>Other</option>'; inlineHtml += '</select></div></div>'; inlineHtml += '</div>'; inlineHtml += '</div>'; inlineHtml += '<div class="form-group container row_operatorRole hide">' inlineHtml += '<div class="row">'; /* Driver 2 Trolley/ Foot Courier 3 Franchisee 5 */ inlineHtml += '<div class="col-xs-3"><div class="input-group"><span class="input-group-addon">ROLE <span class="mandatory">*</span></span><select id="operatorRole" class="form-control operatorRole" >'; inlineHtml += '<option value=0></option><option value=2>Driver</option><option value=3>Trolley/ Foot Courier</option><option value=5>Franchisee</option>'; inlineHtml += '</select></div></div>'; /* Employee 1 Contractor 2 Franchise Owner 4 */ inlineHtml += '<div class="col-xs-3"><div class="input-group"><span class="input-group-addon">EMPLOYEMENT TYPE <span class="mandatory">*</span></span><select id="operatorEmploymentType" class="form-control operatorEmploymentType" >'; inlineHtml += '<option value=0></option><option value=1>Employee</option><option value=2>Contractor</option><option value=4>Franchise Owner</option>'; inlineHtml += '</select></div></div>'; /* Yes 1 No 2 */ inlineHtml += '<div class="col-xs-3"><div class="input-group"><span class="input-group-addon">PRIMARY OPERATOR <span class="mandatory">*</span></span><select id="operatorPrimaryOperator" class="form-control operatorPrimaryOperator" >'; inlineHtml += '<option value=0></option><option value=1>Yes</option><option value=2>No</option>'; inlineHtml += '</select></div></div>'; inlineHtml += '<div class="col-xs-3"><div class="input-group"><span class="input-group-addon">CONTINGENCY DRIVER <span class="mandatory">*</span></span><select id="operatorContingency" class="form-control operatorContingency" >'; inlineHtml += '<option value=0></option><option value=1>Yes</option><option value=2>No</option>'; inlineHtml += '</select></div></div>'; inlineHtml += '</div>'; inlineHtml += '</div>'; inlineHtml += '<div class="form-group container saveoperator_section hide">'; inlineHtml += '<div class="row">'; inlineHtml += '<div class="col-xs-2 "></div>'; inlineHtml += '<div class="col-xs-4 reviewaddress"><input type="button" value="SAVE OPERATOR" class="form-control btn btn-success" id="saveOperator" /></div>'; inlineHtml += '<div class="col-xs-4 cancel"><input type="button" value="CANCEL" class="form-control btn btn-secondary" id="cancel" /></div>'; inlineHtml += '<div class="col-xs-2 "></div>'; inlineHtml += '</div>'; inlineHtml += '</div>'; inlineHtml += '<div class="form-group container" style="width: 100% !important;">'; inlineHtml += '<div class="row">'; inlineHtml += '<style>table#operatorTable {color: #103D39 !important; font-size: 12px;text-align: center;border: none;}.dataTables_wrapper {font-size: 14px;}table#operatorTable th{text-align: center;} .bolded{font-weight: bold;}</style>'; inlineHtml += '<table id="operatorTable" class="table table-responsive table-striped operatorTable tablesorter" style="width: 100%;border: 1px solid #103d39;">'; inlineHtml += '<thead style="color: white;background-color: #379E8F;font-weight: bold;">'; inlineHtml += '<tr class="text-center">'; inlineHtml += '<td>LINK</td>' inlineHtml += '<td>NAME</td>' inlineHtml += '<td class="col-xs-2">EMAIL</td>' inlineHtml += '<td>PHONE</td>' inlineHtml += '<td>ROLE</td>' inlineHtml += '<td>EMPLOYMENT TYPE</td>' inlineHtml += '<td>CONTINGENCY DRIVER</td>' inlineHtml += '<td>PRIMARY DRIVER</td>' inlineHtml += '<td>MOBILE DEVICE</td>' inlineHtml += '</tr>'; inlineHtml += '</thead>'; inlineHtml += '<tbody id="resultOperatorTable" class="">'; resultSetOperators.each(function (searchResultOperators) { operatorID = searchResultOperators.getValue('internalid'); operatorName = searchResultOperators.getValue('name'); operatorPhone = searchResultOperators.getValue( 'custrecord_operator_phone'); operatorEmail = searchResultOperators.getValue( 'custrecord_operator_email'); operatorEmploymentType = searchResultOperators.getText( 'custrecord_operator_employment'); var operatorEmploymentTypeID = searchResultOperators.getValue( 'custrecord_operator_employment'); operatorRole = searchResultOperators.getText( 'custrecord_operator_role'); var operatorRoleID = searchResultOperators.getValue( 'custrecord_operator_role'); operatorMobileDev = searchResultOperators.getText( 'custrecord_operator_mobdev_platform'); var operatorMobileDevID = searchResultOperators.getValue( 'custrecord_operator_mobdev_platform'); operatorDDS = searchResultOperators.getText( 'custrecord_dds_operator'); var operatorDDSID = searchResultOperators.getValue( 'custrecord_dds_operator'); operatorPrimaryOperator = searchResultOperators.getText( 'custrecord_primary_operator'); var operatorPrimaryOperatorID = searchResultOperators.getValue( 'custrecord_primary_operator'); log.debug({ title: 'operatorEmploymentType', details: operatorEmploymentType }) log.debug({ title: 'operatorEmploymentTypeID', details: operatorEmploymentTypeID }) log.debug({ title: 'operatorRole', details: operatorRole }) log.debug({ title: 'operatorRoleID', details: operatorRoleID }) log.debug({ title: 'operatorMobileDevID', details: operatorMobileDevID }) log.debug({ title: 'operatorDDS', details: operatorDDS }) log.debug({ title: 'operatorDDSID', details: operatorDDSID }) log.debug({ title: 'operatorPrimaryOperator', details: operatorPrimaryOperator }) log.debug({ title: 'operatorPrimaryOperatorID', details: operatorPrimaryOperatorID }) inlineHtml += '<tr>' inlineHtml += '<td><a data-id="' + operatorID + '" class="btn btn-md btn-primary editOperatorTable" data-changed="notchanged">EDIT</a> <a data-id="' + operatorID + '" class="btn btn-md btn-danger deleteOperatorTable" >DELETE</a></td>' inlineHtml += '<td><input value="' + operatorName + '" readonly class="form-control operatorNameTable" /></td>' inlineHtml += '<td><input value="' + operatorEmail + '" readonly class="form-control operatorEmailTable" /></td>' inlineHtml += '<td><input value="' + operatorPhone + '" readonly class="form-control operatorPhoneTable" /></td>' inlineHtml += '<td><input value="' + operatorRole + '" readonly class="form-control operatorRoleTable" /><input id="" class="operatorRoleID" value="' + operatorRoleID + '" type="hidden"/></td>' inlineHtml += '<td><input value="' + operatorEmploymentType + '" readonly class="form-control operatorEmploymentTypeTable"/><input id="" class="operatorEmploymentTypeID" value="' + operatorEmploymentTypeID + '" type="hidden"/></td>' inlineHtml += '<td><input value="' + operatorDDS + '" readonly class="form-control operatorDDSTable" /><input id="" class="operatorDDSID" value="' + operatorDDSID + '" type="hidden"/></td>' inlineHtml += '<td><input value="' + operatorPrimaryOperator + '" readonly class="form-control operatorPrimaryOperatorTable" /><input id="" class="operatorPrimaryOperatorID" value="' + operatorPrimaryOperatorID + '" type="hidden"/></td>' inlineHtml += '<td><input value="' + operatorMobileDev + '" readonly class="form-control operatorMobileDevTable" /><input id="" class="operatorMobileDevID" value="' + operatorMobileDevID + '" type="hidden"/></td>' inlineHtml += '</tr>'; return true; }); inlineHtml += '</tbody></table>'; inlineHtml += '</div>'; inlineHtml += '</div>'; inlineHtml += franchiseeAddOperator() return inlineHtml; } function franchiseeFleetDetails(zee, resultSetOperators) { //NetSuite Search: Franchisee - Operator Vehicle Details var searchZeeVehicles = search.load({ id: 'customsearch1912', type: 'customrecord_vehicle' }); if (!isNullorEmpty(zee)) { searchZeeVehicles.filters.push(search.createFilter({ name: 'internalid', join: 'CUSTRECORD_VEHICLE_FRANCHISEE', operator: search.Operator.IS, values: zee })); } var resultSetZeeVehicles = searchZeeVehicles.run(); var inlineHtml = '<div class="form-group container">'; inlineHtml += '<div class="row">'; inlineHtml += '<div class="col-xs-12 heading1"><h4><span class="label label-default col-xs-12" style="background-color: #103D39;">FLEET DETAILS</span></h4></div>'; inlineHtml += '</div>'; inlineHtml += '</div>'; inlineHtml += '<div class="form-group container row_fleet_details hide">' inlineHtml += '<div class="row">'; inlineHtml += '<input id="vehicleInternalId" value="" type="hidden"/>' inlineHtml += '<div class="col-xs-6 vehicleRego_section"><div class="input-group"><span class="input-group-addon">REGISTRATION <span class="mandatory">*</span></span><input id="vehicleRegistration" class="form-control vehicleRegistration" /></div></div>'; inlineHtml += '</div>'; inlineHtml += '</div>'; inlineHtml += '<div class="form-group container row_fleet_details2 hide">' inlineHtml += '<div class="row">'; inlineHtml += '<div class="col-xs-3 operatorEmail_section"><div class="input-group"><span class="input-group-addon">MODEL <span class="mandatory">*</span></span><input id="vehicleModel" class="form-control vehicleModel" /></div></div>'; inlineHtml += '<div class="col-xs-3 operatorMobile_section"><div class="input-group"><span class="input-group-addon">MAKE<span class="mandatory">*</span></span><input id="vehicleMake" class="form-control vehicleMake" /></div></div>'; inlineHtml += '<div class="col-xs-3 operatorMobile_section"><div class="input-group"><span class="input-group-addon">COLOR <span class="mandatory">*</span></span><input id="vehicleColor" class="form-control vehicleColor" /></div></div>'; inlineHtml += '<div class="col-xs-3 operatorMobile_section"><div class="input-group"><span class="input-group-addon">YEAR <span class="mandatory">*</span></span><input id="vehicleYear" class="form-control vehicleYear" /></div></div>'; inlineHtml += '</div>'; inlineHtml += '</div>'; inlineHtml += '<div class="form-group container row_fleet_details3 hide">' inlineHtml += '<div class="row">'; inlineHtml += '<div class="col-xs-3"><div class="input-group"><span class="input-group-addon">SIGNAGE <span class="mandatory">*</span></span><select id="vehicleSignage" class="form-control vehicleSignage" >'; inlineHtml += '<option value=0></option><option value=1>Yes</option><option value=2>No</option>'; inlineHtml += '</select></div></div>'; inlineHtml += '<div class="col-xs-3"><div class="input-group"><span class="input-group-addon">CARGO CAGE <span class="mandatory">*</span></span><select id="vehicleCargoCage" class="form-control vehicleCargoCage" >'; inlineHtml += '<option value=0></option><option value=1>Yes</option><option value=2>No</option>'; inlineHtml += '</select></div></div>'; /* Employee 1 Contractor 2 Franchise Owner 4 */ inlineHtml += '<div class="col-xs-3"><div class="input-group"><span class="input-group-addon">ONWER <span class="mandatory">*</span></span><select id="vehicleOwner" class="form-control vehicleOwner" >'; inlineHtml += '<option value=0></option><option value=2>Driver</option><option value=3>Trolley/ Foot Courier</option><option value=5>Franchisee</option>'; inlineHtml += '</select></div></div>'; inlineHtml += '<div class="col-xs-3"><div class="input-group"><span class="input-group-addon">OPERATOR <span class="mandatory">*</span></span><select id="vehicleOperator" class="form-control vehicleOperator" ><option value=0></option>'; resultSetOperators.each(function (searchResultOperators) { operatorID = searchResultOperators.getValue('internalid'); operatorName = searchResultOperators.getValue('name'); inlineHtml += '<option value=' + operatorID + '>' + operatorName + '</option>'; return true; }); inlineHtml += '</select></div></div>'; inlineHtml += '</div>'; inlineHtml += '</div>'; inlineHtml += '<div class="form-group container savefleet_section hide">'; inlineHtml += '<div class="row">'; inlineHtml += '<div class="col-xs-2 "></div>'; inlineHtml += '<div class="col-xs-4 reviewaddress"><input type="button" value="SAVE FLEET" class="form-control btn btn-success" id="saveVehicle" /></div>'; inlineHtml += '<div class="col-xs-4 cancel"><input type="button" value="CANCEL" class="form-control btn btn-secondary" id="cancel" /></div>'; inlineHtml += '<div class="col-xs-2 "></div>'; inlineHtml += '</div>'; inlineHtml += '</div>'; inlineHtml += '<div class="form-group container" style="width: 100% !important;">'; inlineHtml += '<div class="row">'; inlineHtml += '<style>table#fleetTable {color: #103D39 !important; font-size: 12px;text-align: center;border: none;}.dataTables_wrapper {font-size: 14px;}table#fleetTable th{text-align: center;} .bolded{font-weight: bold;}</style>'; inlineHtml += '<table id="fleetTable" class="table table-responsive table-striped fleetTable tablesorter" style="width: 100%;border: 1px solid #103d39;">'; inlineHtml += '<thead style="color: white;background-color: #379E8F;font-weight: bold;">'; inlineHtml += '<tr class="text-center">'; inlineHtml += '<td>LINK</td>' inlineHtml += '<td>REGISTRATION</td>' inlineHtml += '<td>MODEL</td>' inlineHtml += '<td>MAKE</td>' inlineHtml += '<td>COLOR</td>' inlineHtml += '<td>YEAR</td>' inlineHtml += '<td>SIGNAGE</td>' inlineHtml += '<td>CARGO CAGE</td>' inlineHtml += '<td>OWNER</td>' inlineHtml += '<td>OPERATOR NAME</td>' inlineHtml += '</tr>'; inlineHtml += '</thead>'; inlineHtml += '<tbody id="resultOperatorTable" class="">'; resultSetZeeVehicles.each(function (searchResultZeeVehicles) { vehicleID = searchResultZeeVehicles.getValue('internalid'); vehicleRegistration = searchResultZeeVehicles.getValue('name'); vehicleModel = searchResultZeeVehicles.getValue( 'custrecord_vehicle_model_text'); vehicleMake = searchResultZeeVehicles.getValue( 'custrecord_vehicle_make'); vehicleYear = searchResultZeeVehicles.getValue( 'custrecord_vehicle_year'); vehicleColor = searchResultZeeVehicles.getValue( 'custrecord_vehicle_colour'); vehicleSignage = searchResultZeeVehicles.getValue( 'custrecord_vehicle_signage'); vehicleOwnerID = searchResultZeeVehicles.getValue( 'custrecord_vehicle_owner'); vehicleOwner = searchResultZeeVehicles.getText( 'custrecord_vehicle_owner'); vehicleCargoCageID = searchResultZeeVehicles.getValue( 'custrecord_cargo_cage'); vehicleCargoCage = searchResultZeeVehicles.getText( 'custrecord_cargo_cage'); vehicleOperatorInternalID = searchResultZeeVehicles.getValue({ name: "internalid", join: "CUSTRECORD_OPERATOR_VEHICLE" }); vehicleOperatorName = searchResultZeeVehicles.getValue({ name: "custrecord_operator_givennames", join: "CUSTRECORD_OPERATOR_VEHICLE" }); inlineHtml += '<tr>' inlineHtml += '<td><a data-id="' + vehicleID + '" class=" btn btn-md btn-primary editFleetTable" data-changed="notchanged">EDIT</a> <a data-id="' + vehicleID + '" class=" btn btn-md btn-danger deleteFleetTable" >DELETE</a></td>' inlineHtml += '<td><input value="' + vehicleRegistration + '" readonly class="form-control vehicleRegistrationTable"/></td>' inlineHtml += '<td><input value="' + vehicleModel + '" readonly class="form-control vehicleModelTable"/></td>' inlineHtml += '<td><input value="' + vehicleMake + '" readonly class="form-control vehicleMakeTable"/></td>' inlineHtml += '<td><input value="' + vehicleColor + '" readonly class="form-control vehicleColorTable"/></td>' inlineHtml += '<td><input value="' + vehicleYear + '" readonly class="form-control vehicleYearTable"/></td>' inlineHtml += '<td><input value="' + vehicleSignage + '" readonly class="form-control vehicleSignageTable"/><input id="vehicleSignageID" class="vehicleSignageID" value="' + vehicleSignage + '" type="hidden"/></td>' inlineHtml += '<td><input value="' + vehicleCargoCage + '" readonly class="form-control vehicleCargoCageTable"/><input id="vehicleCargoCageID" class="vehicleCargoCageID" value="' + vehicleCargoCageID + '" type="hidden"/></td>' inlineHtml += '<td><input value="' + vehicleOwner + '" readonly class="form-control vehicleOwnerTable"/><input id="vehicleOwnerID" class="vehicleOwnerID" value="' + vehicleOwnerID + '" type="hidden"/></td>' inlineHtml += '<td><input value="' + vehicleOperatorName + '" readonly class="form-control vehicleOperatorNameTable"/><input id="vehicleOperatorID" class="vehicleOperatorID" value="' + vehicleOperatorInternalID + '" type="hidden"/></td>' inlineHtml += '</tr>'; return true; }); inlineHtml += '</tbody></table>'; inlineHtml += '</div>'; inlineHtml += '</div>'; inlineHtml += franchiseeAddFleet() return inlineHtml; } function franchiseeBreachDetails() { var inlineHtml = '<div class="form-group container">'; inlineHtml += '<div class="row">'; inlineHtml += '<div class="col-xs-12 heading1"><h4><span class="label label-default col-xs-12" style="background-color: #103D39;">BREACH DETAILS</span></h4></div>'; inlineHtml += '</div>'; inlineHtml += '</div>'; return inlineHtml; } function franchiseeTerminationDetails() { var inlineHtml = '<div class="form-group container">'; inlineHtml += '<div class="row">'; inlineHtml += '<div class="col-xs-12 heading1"><h4><span class="label label-default col-xs-12" style="background-color: #103D39;">TERMINATION DETAILS</span></h4></div>'; inlineHtml += '</div>'; inlineHtml += '</div>'; return inlineHtml; } function addressContactsSection(resultSetAddresses) { var inlineQty = '<div class="form-group container contacts_section" style="font-size: xx-small;">'; inlineQty += '<div class="row">'; inlineQty += '<div class="col-xs-12 address_div">'; inlineQty += '<table border="0" cellpadding="15" id="address" class="table table-responsive table-striped address tablesorter" cellspacing="0" style="width: 100%;border: 1px solid #103d39;font-size: 12px;text-align: center;"><thead style="color: white;background-color: #379E8F;"><tr><th style="vertical-align: middle;text-align: center;">LINK</th><th style="vertical-align: middle;text-align: center;">ID</th><th style="vertical-align: middle;text-align: center;"><b>SUIT/LEVEL/UNIT </b></th><th style="vertical-align: middle;text-align: center;"><b>STREET NO. & NAME </b></th><th style="vertical-align: middle;text-align: center;"><b>SUBURB </b></th><th style="vertical-align: middle;text-align: center;"><b>STATE </b></th><th style="vertical-align: middle;text-align: center;"><b>POSTCODE </b></th></tr></thead><tbody>'; if (!isNullorEmpty(resultSetAddresses)) { //console.log("addresses work"); resultSetAddresses.each(function (searchResultAddresses) { var id = searchResultAddresses.getValue({ name: 'addressinternalid', join: 'Address' }); var addr1 = searchResultAddresses.getValue({ name: 'address1', join: 'Address' }); var addr2 = searchResultAddresses.getValue({ name: 'address2', join: 'Address' }); var city = searchResultAddresses.getValue({ name: 'city', join: 'Address' }); var state = searchResultAddresses.getValue({ name: 'state', join: 'Address' }); var zip = searchResultAddresses.getValue({ name: 'zipcode', join: 'Address' }); var lat = searchResultAddresses.getValue({ name: 'custrecord_address_lat', join: 'Address' }); var lon = searchResultAddresses.getValue({ name: 'custrecord_address_lon', join: 'Address' }); var default_shipping = searchResultAddresses.getValue({ name: 'isdefaultshipping', join: 'Address' }); var default_billing = searchResultAddresses.getValue({ name: 'isdefaultbilling', join: 'Address' }); var default_residential = searchResultAddresses.getValue({ name: 'isresidential', join: 'Address' }); if (isNullorEmpty(addr1) && isNullorEmpty(addr2)) { var full_address = city + ', ' + state + ' - ' + zip; } else if (isNullorEmpty(addr1) && !isNullorEmpty(addr2)) { var full_address = addr2 + ', ' + city + ', ' + state + ' - ' + zip; } else if (!isNullorEmpty(addr1) && isNullorEmpty(addr2)) { var full_address = addr1 + ', ' + city + ', ' + state + ' - ' + zip; } else { var full_address = addr1 + ', ' + addr2 + ', ' + city + ', ' + state + ' - ' + zip; } if (default_shipping == 'T') { shipping_state = state; } inlineQty += '<tr><td><a data-id="' + id + '" class="btn btn-md btn-primary editAddressTable" data-changed="notchanged">EDIT</a> <a data-id="' + id + '" class="btn btn-md btn-danger deleteAddressTable" >DELETE</a></td>'; inlineQty += '<td><input value="' + id + '" readonly class="form-control id"/></td>'; inlineQty += '<td><input value="' + addr1 + '" readonly class="form-control addr1Table"/></td>'; inlineQty += '<td><input value="' + addr2 + '" readonly class="form-control addr2Table"/></td>'; inlineQty += '<td><input value="' + city + '" readonly class="form-control cityTable"/></td>'; inlineQty += '<td><input value="' + state + '" readonly class="form-control stateTable"/></td>'; inlineQty += '<td><input value="' + zip + '" readonly class="form-control zipTable"/></td>'; return true; }); } inlineQty += '</tbody></table>'; inlineQty += '</div>'; inlineQty += '</div>'; inlineQty += '</div>'; inlineQty += '<div class="form-group container reviewaddress_section">'; inlineQty += '<div class="row">'; inlineQty += '<div class="col-xs-3 "></div>'; inlineQty += '<div class="col-xs-6 reviewaddress"><input type="button" value="ADD ADDRESSES" class="form-control btn btn-primary" style="background-color: #287587;" id="reviewaddress" /></div>'; inlineQty += '<div class="col-xs-3 "></div>'; inlineQty += '</div>'; inlineQty += '</div>'; return inlineQty; } function isNullorEmpty(strVal) { return (strVal == null || strVal == '' || strVal == 'null' || strVal == undefined || strVal == 'undefined' || strVal == '- None -' || strVal == '0'); } function isNullorEmptyExcZero(strVal) { return (strVal == null || strVal == '' || strVal == 'null' || strVal == undefined || strVal == 'undefined' || strVal == '- None -'); } /** * The header showing that the results are loading. * @returns {String} `inlineQty` */ function loadingSection() { var inlineHtml = '<div id="loading_section" class="form-group container loading_section " style="text-align:center">'; inlineHtml += '<div class="row">'; inlineHtml += '<div class="col-xs-12 loading_div">'; inlineHtml += '<h1>Loading...</h1>'; inlineHtml += '</div></div></div>'; return inlineHtml; } function getDateToday() { var date = new Date(); log.debug({ title: 'date', details: date }) format.format({ value: date, type: format.Type.DATE, timezone: format.Timezone.AUSTRALIA_SYDNEY }) return date; } function getDate(inputDate) { var date = new Date(inputDate); format.format({ value: date, type: format.Type.DATE, timezone: format.Timezone.AUSTRALIA_SYDNEY }) return date; } function getDay() { var date = new Date(); if (date.getHours() > 6) { date.setDate(date.getDate() + 1); } var day = date.getDay(); return day; } /** * Used to pass the values of `date_from` and `date_to` between the scripts and to Netsuite for the records and the search. * @param {String} date_iso "2020-06-01" * @returns {String} date_netsuite "1/6/2020" */ function dateISOToNetsuite(date_iso) { var date_netsuite = ''; if (!isNullorEmpty(date_iso)) { var date_utc = new Date(date_iso); // var date_netsuite = nlapiDateToString(date_utc); var date_netsuite = format.format({ value: date_utc, type: format.Type.DATE }); } return date_netsuite; } return { onRequest: onRequest }; });
true
/** * @NApiVersion 2.0 * @NScriptType Suitelet * @Author: Ankith Ravindran <ankithravindran> * @Date: 2021-11-15T07:25:50+11:00 * @Last modified by: ankithravindran * @Last modified time: 2022-02-24T15:27:26+11:00 */ define(['N/ui/serverWidget', 'N/email', 'N/runtime', 'N/search', 'N/record', 'N/http', 'N/log', 'N/redirect', 'N/format' ], function (ui, email, runtime, search, record, http, log, redirect, format) { var role = 0; var userId = 0; var zee = 0; var franchiseeName = ''; var mainContact = ''; var mainContactFName = ''; var mainContactLName = ''; var mainContactMobile = ''; var franchiseeTypeOfOwner = ''; var primaryEmail = ''; var personalEmail = ''; var dob = ''; var vaccinationStatus = ''; var franchiseeNextOfKinName = ''; var franchiseeNextOfKinMobile = ''; var franchiseeNextOfKinRelationship = ''; var franchiseeABN = ''; var franchiseeAddress = ''; var franchiseeTOLLAccountNumber = ''; var franchiseeTOLLPickupDX = ''; var franchiseeTOLLLodgementDX = ''; var franchiseeSendlePrimaryLocations = ''; var franchiseeLastMileLocations = ''; var franchiseeSendleSecondaryLocations = ''; var franchiseeListedForSale = ''; var color_array = ['blue', 'red', 'green', 'orange', 'black']; function onRequest(context) { var baseURL = 'https://system.na2.netsuite.com'; if (runtime.EnvType == "SANDBOX") { baseURL = 'https://system.sandbox.netsuite.com'; } userId = runtime.getCurrentUser().id; role = runtime.getCurrentUser().role; if (context.request.method === 'GET') { zee = context.request.parameters.zee; if (role == 1000) { zee = userId; var form = ui.createForm({ title: 'Franchisee Management Console' }); } else { var form = ui.createForm({ title: 'Franchisee Sales & Management' }); } //INITIALIZATION OF JQUERY AND BOOTSTRAP var inlineHtml = '<meta name="viewport" content="width=device-width, initial-scale=1.0"><script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"><script src="//code.jquery.com/jquery-1.11.0.min.js"></script><script src="//api.tiles.mapbox.com/mapbox.js/plugins/leaflet-omnivore/v0.3.1/leaflet-omnivore.min.js"></script><script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"><script src="//code.jquery.com/jquery-1.11.0.min.js"></script><script src="https://maps.googleapis.com/maps/api/js?key=AIzaSyA92XGDo8rx11izPYT7z2L-YPMMJ6Ih1s0&callback=initMap&libraries=places"></script><script src="https://cdnjs.cloudflare.com/ajax/libs/OverlappingMarkerSpiderfier/1.0.3/oms.min.js"></script></script><link rel="stylesheet" href="https://unpkg.com/leaflet@1.2.0/dist/leaflet.css" /><script src="https://unpkg.com/leaflet@1.2.0/dist/leaflet.js"></script><link type="text/css" rel="stylesheet" href="https://cdn.datatables.net/1.10.13/css/jquery.dataTables.min.css"><link href="//netdna.bootstrapcdn.com/bootstrap/3.3.2/css/bootstrap.min.css" rel="stylesheet"><script src="//netdna.bootstrapcdn.com/bootstrap/3.3.2/js/bootstrap.min.js"></script><link rel="stylesheet" href="https://system.na2.netsuite.com/core/media/media.nl?id=2060796&amp;c=1048144&amp;h=9ee6accfd476c9cae718&amp;_xt=.css"><script src="https://system.na2.netsuite.com/core/media/media.nl?id=2060797&amp;c=1048144&amp;h=ef2cda20731d146b5e98&amp;_xt=.js"></script><link type="text/css" rel="stylesheet" href="https://system.na2.netsuite.com/core/media/media.nl?id=2090583&amp;c=1048144&amp;h=a0ef6ac4e28f91203dfe&amp;_xt=.css"><script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.6.4/angular.min.js"></script><script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.7/angular-resource.min.js"></script><link type="text/css" rel="stylesheet" href="https://system.na2.netsuite.com/core/media/media.nl?id=2090583&amp;c=1048144&amp;h=a0ef6ac4e28f91203dfe&amp;_xt=.css"><style>.mandatory{color:red;}.clearfix:after {clear: both;content: "";display: block;height: 0;}.wrapper {vertical-align: middle;}.nav {margin-top: 40px;}.pull-right {float: right;}a, a:active {color: #212121;text-decoration: none;}a:hover {color: #999;}.arrow-steps .step {font-size: 14px;text-align: center;color: #fff;cursor: default;margin: 0 3px;padding: 10px 10px 10px 30px;float: left;position: relative;background-color: #379e8f;-webkit-user-select: none;-moz-user-select: none;-ms-user-select: none;user-select: none; transition: background-color 0.2s ease;}.arrow-steps .step:after,.arrow-steps .step:before {content: " ";position: absolute;top: 0;right: -17px;width: 0;height: 40px;border-top: 19px solid transparent;border-bottom: 17px solid transparent;border-left: 17px solid #379e8f; z-index: 2;transition: border-color 0.2s ease;}.arrow-steps .step:before {right: auto;left: 0;border-left: 17px solid #fff; z-index: 0;}.arrow-steps .step:first-child:before {border: none;}.arrow-steps .step:first-child {border-top-left-radius: 4px;border-bottom-left-radius: 4px;}.arrow-steps .step span {position: relative;}.arrow-steps .step span:before {opacity: 0;content: "βœ”";position: absolute;top: -2px;left: -20px;color: #06ac77;}.arrow-steps .step.done span:before {opacity: 1;-webkit-transition: opacity 0.3s ease 0.5s;-moz-transition: opacity 0.3s ease 0.5s;-ms-transition: opacity 0.3s ease 0.5s;transition: opacity 0.3s ease 0.5s;}.arrow-steps .step.current {color: #103d39;font-weight: bold;background-color: #fbea51;}.arrow-steps .step.current:after {border-left: 17px solid #fbea51; }.nav > li.active > a, .nav > li.active > a:focus, .nav > li.active > a:hover { background-color: #379E8F; color: #fff }.nav > li > a, .nav > li > a:focus, .nav > li > a:hover { margin-left: 5px; margin-right: 5px; border: 2px solid #379E8F; color: #379E8F; }</style>'; //ERROR SECTION inlineHtml += '<div class="container" style="padding-top: 3%;"><div id="alert" class="alert alert-danger fade in"></div></div>'; var day = getDay(); if (day == 0 || day == 6) { day = 1; //Monday } //HIDDEN FIELDS form.addField({ id: 'custpage_zee', type: ui.FieldType.TEXT, label: 'Zee' }).updateDisplayType({ displayType: ui.FieldDisplayType.HIDDEN }).defaultValue = zee; form.addField({ id: 'custpage_name', type: ui.FieldType.TEXT, label: 'Zee' }).updateDisplayType({ displayType: ui.FieldDisplayType.HIDDEN }).defaultValue = franchiseeName; form.addField({ id: 'custpage_day', type: ui.FieldType.TEXT, label: 'Day' }).updateDisplayType({ displayType: ui.FieldDisplayType.HIDDEN }).defaultValue = day; //HIDDEN FIELDS TO STORE VALUE TO BE SAVED ON THE FRANCHISE RECORD form.addField({ id: 'custpage_maincontact', type: ui.FieldType.TEXT, label: 'Day' }).updateDisplayType({ displayType: ui.FieldDisplayType.HIDDEN }).defaultValue = mainContact; form.addField({ id: 'custpage_mobilenumber', type: ui.FieldType.TEXT, label: 'Day' }).updateDisplayType({ displayType: ui.FieldDisplayType.HIDDEN }).defaultValue = mainContactMobile; form.addField({ id: 'custpage_typeofowner', type: ui.FieldType.TEXT, label: 'Day' }).updateDisplayType({ displayType: ui.FieldDisplayType.HIDDEN }).defaultValue = franchiseeTypeOfOwner; form.addField({ id: 'custpage_personalemail', type: ui.FieldType.TEXT, label: 'Day' }).updateDisplayType({ displayType: ui.FieldDisplayType.HIDDEN }).defaultValue = primaryEmail; form.addField({ id: 'custpage_dob', type: ui.FieldType.TEXT, label: 'Day' }).updateDisplayType({ displayType: ui.FieldDisplayType.HIDDEN }).defaultValue = dob; form.addField({ id: 'custpage_vaccinationstatus', type: ui.FieldType.TEXT, label: 'Day' }).updateDisplayType({ displayType: ui.FieldDisplayType.HIDDEN }).defaultValue = vaccinationStatus; form.addField({ id: 'custpage_nextofkinname', type: ui.FieldType.TEXT, label: 'Day' }).updateDisplayType({ displayType: ui.FieldDisplayType.HIDDEN }).defaultValue = franchiseeNextOfKinName; form.addField({ id: 'custpage_nextofkinmobile', type: ui.FieldType.TEXT, label: 'Day' }).updateDisplayType({ displayType: ui.FieldDisplayType.HIDDEN }).defaultValue = franchiseeNextOfKinMobile; form.addField({ id: 'custpage_nextofkinrelationship', type: ui.FieldType.TEXT, label: 'Day' }).updateDisplayType({ displayType: ui.FieldDisplayType.HIDDEN }).defaultValue = franchiseeNextOfKinRelationship; //Address Table Hidden Fields form.addField({ id: 'custpage_addressids', type: ui.FieldType.TEXT, label: 'Day' }).updateDisplayType({ displayType: ui.FieldDisplayType.HIDDEN }); form.addField({ id: 'custpage_addressids_delete', type: ui.FieldType.TEXT, label: 'Day' }).updateDisplayType({ displayType: ui.FieldDisplayType.HIDDEN }); form.addField({ id: 'custpage_address1', type: ui.FieldType.TEXT, label: 'Day' }).updateDisplayType({ displayType: ui.FieldDisplayType.HIDDEN }); form.addField({ id: 'custpage_address2', type: ui.FieldType.TEXT, label: 'Day' }).updateDisplayType({ displayType: ui.FieldDisplayType.HIDDEN }); form.addField({ id: 'custpage_suburb', type: ui.FieldType.TEXT, label: 'Day' }).updateDisplayType({ displayType: ui.FieldDisplayType.HIDDEN }); form.addField({ id: 'custpage_state', type: ui.FieldType.TEXT, label: 'Day' }).updateDisplayType({ displayType: ui.FieldDisplayType.HIDDEN }); form.addField({ id: 'custpage_postcode', type: ui.FieldType.TEXT, label: 'Day' }).updateDisplayType({ displayType: ui.FieldDisplayType.HIDDEN }); //Operator Table Hidden Fields form.addField({ id: 'custpage_operatorids', type: ui.FieldType.TEXT, label: 'Day' }).updateDisplayType({ displayType: ui.FieldDisplayType.HIDDEN }); form.addField({ id: 'custpage_operatorids_delete', type: ui.FieldType.TEXT, label: 'Day' }).updateDisplayType({ displayType: ui.FieldDisplayType.HIDDEN }); form.addField({ id: 'custpage_operatorname', type: ui.FieldType.TEXT, label: 'Day' }).updateDisplayType({ displayType: ui.FieldDisplayType.HIDDEN }); form.addField({ id: 'custpage_operatoremail', type: ui.FieldType.TEXT, label: 'Day' }).updateDisplayType({ displayType: ui.FieldDisplayType.HIDDEN }); form.addField({ id: 'custpage_operatormobile', type: ui.FieldType.TEXT, label: 'Day' }).updateDisplayType({ displayType: ui.FieldDisplayType.HIDDEN }); form.addField({ id: 'custpage_operatorrole', type: ui.FieldType.TEXT, label: 'Day' }).updateDisplayType({ displayType: ui.FieldDisplayType.HIDDEN }); form.addField({ id: 'custpage_operatoremploymentype', type: ui.FieldType.TEXT, label: 'Day' }).updateDisplayType({ displayType: ui.FieldDisplayType.HIDDEN }); form.addField({ id: 'custpage_operatordds', type: ui.FieldType.TEXT, label: 'Day' }).updateDisplayType({ displayType: ui.FieldDisplayType.HIDDEN }); form.addField({ id: 'custpage_operatorprimary', type: ui.FieldType.TEXT, label: 'Day' }).updateDisplayType({ displayType: ui.FieldDisplayType.HIDDEN }); form.addField({ id: 'custpage_operatormobiledev', type: ui.FieldType.TEXT, label: 'Day' }).updateDisplayType({ displayType: ui.FieldDisplayType.HIDDEN }); //New Operator Table Hidden Fields form.addField({ id: 'custpage_new_operatorids', type: ui.FieldType.TEXT, label: 'Day' }).updateDisplayType({ displayType: ui.FieldDisplayType.HIDDEN }); form.addField({ id: 'custpage_new_operatorids_delete', type: ui.FieldType.TEXT, label: 'Day' }).updateDisplayType({ displayType: ui.FieldDisplayType.HIDDEN }); form.addField({ id: 'custpage_new_operatorname', type: ui.FieldType.TEXT, label: 'Day' }).updateDisplayType({ displayType: ui.FieldDisplayType.HIDDEN }); form.addField({ id: 'custpage_new_operatoremail', type: ui.FieldType.TEXT, label: 'Day' }).updateDisplayType({ displayType: ui.FieldDisplayType.HIDDEN }); form.addField({ id: 'custpage_new_operatormobile', type: ui.FieldType.TEXT, label: 'Day' }).updateDisplayType({ displayType: ui.FieldDisplayType.HIDDEN }); form.addField({ id: 'custpage_new_operatorrole', type: ui.FieldType.TEXT, label: 'Day' }).updateDisplayType({ displayType: ui.FieldDisplayType.HIDDEN }); form.addField({ id: 'custpage_new_operatoremploymentype', type: ui.FieldType.TEXT, label: 'Day' }).updateDisplayType({ displayType: ui.FieldDisplayType.HIDDEN }); form.addField({ id: 'custpage_new_operatordds', type: ui.FieldType.TEXT, label: 'Day' }).updateDisplayType({ displayType: ui.FieldDisplayType.HIDDEN }); form.addField({ id: 'custpage_new_operatorprimary', type: ui.FieldType.TEXT, label: 'Day' }).updateDisplayType({ displayType: ui.FieldDisplayType.HIDDEN }); form.addField({ id: 'custpage_new_operatormobiledev', type: ui.FieldType.TEXT, label: 'Day' }).updateDisplayType({ displayType: ui.FieldDisplayType.HIDDEN }); //Fleet Table Hidden Details form.addField({ id: 'custpage_fleetids', type: ui.FieldType.TEXT, label: 'Day' }).updateDisplayType({ displayType: ui.FieldDisplayType.HIDDEN }); form.addField({ id: 'custpage_fleetids_delete', type: ui.FieldType.TEXT, label: 'Day' }).updateDisplayType({ displayType: ui.FieldDisplayType.HIDDEN }); form.addField({ id: 'custpage_fleetrego', type: ui.FieldType.TEXT, label: 'Day' }).updateDisplayType({ displayType: ui.FieldDisplayType.HIDDEN }); form.addField({ id: 'custpage_fleetmodel', type: ui.FieldType.TEXT, label: 'Day' }).updateDisplayType({ displayType: ui.FieldDisplayType.HIDDEN }); form.addField({ id: 'custpage_fleetmake', type: ui.FieldType.TEXT, label: 'Day' }).updateDisplayType({ displayType: ui.FieldDisplayType.HIDDEN }); form.addField({ id: 'custpage_fleetcolor', type: ui.FieldType.TEXT, label: 'Day' }).updateDisplayType({ displayType: ui.FieldDisplayType.HIDDEN }); form.addField({ id: 'custpage_fleetyear', type: ui.FieldType.TEXT, label: 'Day' }).updateDisplayType({ displayType: ui.FieldDisplayType.HIDDEN }); form.addField({ id: 'custpage_fleetsignage', type: ui.FieldType.TEXT, label: 'Day' }).updateDisplayType({ displayType: ui.FieldDisplayType.HIDDEN }); form.addField({ id: 'custpage_caregocage', type: ui.FieldType.TEXT, label: 'Day' }).updateDisplayType({ displayType: ui.FieldDisplayType.HIDDEN }); form.addField({ id: 'custpage_owner', type: ui.FieldType.TEXT, label: 'Day' }).updateDisplayType({ displayType: ui.FieldDisplayType.HIDDEN }); form.addField({ id: 'custpage_operator', type: ui.FieldType.TEXT, label: 'Day' }).updateDisplayType({ displayType: ui.FieldDisplayType.HIDDEN }); //New Fleet DETAILS form.addField({ id: 'custpage_new_fleetids', type: ui.FieldType.TEXT, label: 'Day' }).updateDisplayType({ displayType: ui.FieldDisplayType.HIDDEN }); form.addField({ id: 'custpage_new_fleetids_delete', type: ui.FieldType.TEXT, label: 'Day' }).updateDisplayType({ displayType: ui.FieldDisplayType.HIDDEN }); form.addField({ id: 'custpage_new_fleetrego', type: ui.FieldType.TEXT, label: 'Day' }).updateDisplayType({ displayType: ui.FieldDisplayType.HIDDEN }); form.addField({ id: 'custpage_new_fleetmodel', type: ui.FieldType.TEXT, label: 'Day' }).updateDisplayType({ displayType: ui.FieldDisplayType.HIDDEN }); form.addField({ id: 'custpage_new_fleetmake', type: ui.FieldType.TEXT, label: 'Day' }).updateDisplayType({ displayType: ui.FieldDisplayType.HIDDEN }); form.addField({ id: 'custpage_new_fleetcolor', type: ui.FieldType.TEXT, label: 'Day' }).updateDisplayType({ displayType: ui.FieldDisplayType.HIDDEN }); form.addField({ id: 'custpage_new_fleetyear', type: ui.FieldType.TEXT, label: 'Day' }).updateDisplayType({ displayType: ui.FieldDisplayType.HIDDEN }); form.addField({ id: 'custpage_new_fleetsignage', type: ui.FieldType.TEXT, label: 'Day' }).updateDisplayType({ displayType: ui.FieldDisplayType.HIDDEN }); form.addField({ id: 'custpage_new_caregocage', type: ui.FieldType.TEXT, label: 'Day' }).updateDisplayType({ displayType: ui.FieldDisplayType.HIDDEN }); form.addField({ id: 'custpage_new_owner', type: ui.FieldType.TEXT, label: 'Day' }).updateDisplayType({ displayType: ui.FieldDisplayType.HIDDEN }); form.addField({ id: 'custpage_new_operator', type: ui.FieldType.TEXT, label: 'Day' }).updateDisplayType({ displayType: ui.FieldDisplayType.HIDDEN }); form.addField({ id: 'custpage_listforsale', type: ui.FieldType.TEXT, label: 'Day' }).updateDisplayType({ displayType: ui.FieldDisplayType.HIDDEN }).defaultValue = 'F'; inlineHtml += '<div class="se-pre-con"></div><div ng-app="myApp" ng-controller="myCtrl">'; inlineHtml += spacing() if (role != 1000) { inlineHtml += progressBar() inlineHtml += line() inlineHtml += spacing() inlineHtml += selectFranchiseeSection(zee) inlineHtml += spacing() } if (zee != 0 && !isNullorEmpty(zee)) { //NetSuite Search: APP - Operator Load var searchOperators = search.load({ id: 'customsearch_app_operator_load', type: 'customrecord_operator' }); if (!isNullorEmpty(zee)) { searchOperators.filters.push(search.createFilter({ name: 'internalid', join: 'CUSTRECORD_OPERATOR_FRANCHISEE2', operator: search.Operator.IS, values: zee })); } var resultSetOperators = searchOperators.run(); inlineHtml += tabSection(zee, role, resultSetOperators) inlineHtml += spacing() inlineHtml += line() inlineHtml += mainButtons(role) } form.addField({ id: 'preview_table', label: 'inlinehtml', type: 'inlinehtml' }).updateLayoutType({ layoutType: ui.FieldLayoutType.STARTROW }).defaultValue = inlineHtml; form.addSubmitButton({ label: 'SAVE' }); form.clientScriptFileId = 5334734 context.response.writePage(form); } else { var zeeId = parseInt(context.request.parameters.custpage_zee); var franchiseeMainContact = context.request.parameters.custpage_maincontact; var franchiseeMobileNumber = context.request.parameters.custpage_mobilenumber; var franchiseeTypeOfOwner = context.request.parameters.custpage_typeofowner; var franchiseePersonalEmail = context.request.parameters.custpage_personalemail; var FranchiseeDOB = context.request.parameters.custpage_dob; var franchiseeVaccinationStatus = context.request.parameters.custpage_vaccinationstatus; var franchiseeNextOfKinName = context.request.parameters.custpage_nextofkinname; var franchiseeNextOfKinMobile = context.request.parameters.custpage_nextofkinmobile; var franchiseeNextOfKinRelationship = context.request.parameters.custpage_nextofkinrelationship; var addressids = context.request.parameters.custpage_addressids; var addressids_delete = context.request.parameters.custpage_addressids_delete; var address1 = context.request.parameters.custpage_address1; var address2 = context.request.parameters.custpage_address2; var suburb = context.request.parameters.custpage_suburb; var state = context.request.parameters.custpage_state; var postcode = context.request.parameters.custpage_postcode; var listforsale = context.request.parameters.custpage_listforsale; log.debug({ title: 'addressids', details: addressids }) var addressidsArrays = addressids.split(','); var addressidsdeleteArrays = addressids_delete.split(','); var address1Arrays = address1.split(','); var address2Arrays = address2.split(','); var suburbArrays = suburb.split(','); var stateArrays = state.split(','); var postcodeArrays = postcode.split(','); var operatorids = context.request.parameters.custpage_operatorids; var operatorids_delete = context.request.parameters.custpage_operatorids_delete; var operatorname = context.request.parameters.custpage_operatorname; var operatoremail = context.request.parameters.custpage_operatoremail; var operatormobile = context.request.parameters.custpage_operatormobile; var operatorrole = context.request.parameters.custpage_operatorrole; var operatoremploymentype = context.request.parameters.custpage_operatoremploymentype; var operatordds = context.request.parameters.custpage_operatordds; var operatorprimary = context.request.parameters.custpage_operatorprimary; var operatormobiledev = context.request.parameters.custpage_operatormobiledev; var operatoridsArrys = operatorids.split(',') var operatoridsdeleteArrys = operatorids_delete.split(',') var operatornameArrys = operatorname.split(',') var operatoremailArrys = operatoremail.split(',') var operatormobileArrys = operatormobile.split(',') var operatorroleArrys = operatorrole.split(',') var operatoremploymentypeArrys = operatoremploymentype.split(',') var operatorddsArrys = operatordds.split(',') var operatorprimaryArrys = operatorprimary.split(',') var operatormobiledevArrys = operatormobiledev.split(',') //New operator var newoperatorids = context.request.parameters.custpage_new_operatorids; var newoperatorids_delete = context.request.parameters.custpage_new_operatorids_delete; var newoperatorname = context.request.parameters.custpage_new_operatorname; var newoperatoremail = context.request.parameters.custpage_new_operatoremail; var newoperatormobile = context.request.parameters.custpage_new_operatormobile; var newoperatorrole = context.request.parameters.custpage_new_operatorrole; var newoperatoremploymentype = context.request.parameters.custpage_new_operatoremploymentype; var newoperatordds = context.request.parameters.custpage_new_operatordds; var newoperatorprimary = context.request.parameters.custpage_new_operatorprimary; var newoperatormobiledev = context.request.parameters.custpage_new_operatormobiledev; var newoperatoridsArrys = newoperatorids.split(',') var newoperatoridsdeleteArrys = newoperatorids_delete.split(',') var newoperatornameArrys = newoperatorname.split(',') var newoperatoremailArrys = newoperatoremail.split(',') var newoperatormobileArrys = newoperatormobile.split(',') var newoperatorroleArrys = newoperatorrole.split(',') var newoperatoremploymentypeArrys = newoperatoremploymentype.split( ',') var newoperatorddsArrys = newoperatordds.split(',') var newoperatorprimaryArrys = newoperatorprimary.split(',') var newoperatormobiledevArrys = newoperatormobiledev.split(',') var fleetids = context.request.parameters.custpage_fleetids; var fleetids_delete = context.request.parameters.custpage_fleetids_delete; var fleetrego = context.request.parameters.custpage_fleetrego; var fleetmodel = context.request.parameters.custpage_fleetmodel; var fleetmake = context.request.parameters.custpage_fleetmake; var fleetcolor = context.request.parameters.custpage_fleetcolor; var fleetyear = context.request.parameters.custpage_fleetyear; var fleetsignage = context.request.parameters.custpage_fleetsignage; var caregocage = context.request.parameters.custpage_caregocage; var owner = context.request.parameters.custpage_owner; var operator = context.request.parameters.custpage_operator; var fleetidsArrys = fleetids.split(',') var fleetidsdeleteArrys = fleetids_delete.split(',') var fleetregoArrys = fleetrego.split(',') var fleetmodelArrys = fleetmodel.split(',') var fleetmakeArrys = fleetmake.split(',') var fleetcolorArrys = fleetcolor.split(',') var fleetyearArrys = fleetyear.split(',') var fleetsignageArrys = fleetsignage.split(',') var caregocageArrys = caregocage.split(',') var ownerArrys = owner.split(',') var operatorArrys = operator.split(',') //New Fleet details var newfleetids = context.request.parameters.custpage_new_fleetids; var newfleetids_delete = context.request.parameters.custpage_new_fleetids_delete; var newfleetrego = context.request.parameters.custpage_new_fleetrego; var newfleetmodel = context.request.parameters.custpage_new_fleetmodel; var newfleetmake = context.request.parameters.custpage_new_fleetmake; var newfleetcolor = context.request.parameters.custpage_new_fleetcolor; var newfleetyear = context.request.parameters.custpage_new_fleetyear; var newfleetsignage = context.request.parameters.custpage_new_fleetsignage; var newcaregocage = context.request.parameters.custpage_new_caregocage; var newowner = context.request.parameters.custpage_new_owner; var newoperator = context.request.parameters.custpage_new_operator; var newfleetidsArrys = newfleetids.split(',') var newfleetidsdeleteArrys = newfleetids_delete.split(',') var newfleetregoArrys = newfleetrego.split(',') var newfleetmodelArrys = newfleetmodel.split(',') var newfleetmakeArrys = newfleetmake.split(',') var newfleetcolorArrys = newfleetcolor.split(',') var newfleetyearArrys = newfleetyear.split(',') var newfleetsignageArrys = newfleetsignage.split(',') var newcaregocageArrys = newcaregocage.split(',') var newownerArrys = newowner.split(',') var newoperatorArrys = newoperator.split(',') //Load Partner Record & Save the main details var zeeRecord = record.load({ type: record.Type.PARTNER, id: zeeId }); var zeeName = zeeRecord.getValue({ fieldId: 'companyname' }); zeeRecord.setValue({ fieldId: 'custentity3', value: franchiseeMainContact }) zeeRecord.setValue({ fieldId: 'custentity2', value: franchiseeMobileNumber }) if (franchiseeTypeOfOwner != 0) { zeeRecord.setValue({ fieldId: 'custentity_type_of_owner', value: franchiseeTypeOfOwner }) } zeeRecord.setValue({ fieldId: 'custentity_personal_email_address', value: franchiseePersonalEmail }); log.debug({ title: 'dobArray', details: dobArray }) if (!isNullorEmpty(dobArray)) { var dobArray = FranchiseeDOB.split('-') var dobString = dobArray[1] + '/' + dobArray[2] + '/' + dobArray[0] zeeRecord.setValue({ fieldId: 'custentity_zee_dob', value: getDate(dobString) }) } if (franchiseeVaccinationStatus != 0) { zeeRecord.setValue({ fieldId: 'custentity_vacc_status', value: franchiseeVaccinationStatus }) } zeeRecord.setValue({ fieldId: 'custentity_kin_name', value: franchiseeNextOfKinName }) zeeRecord.setValue({ fieldId: 'custentity_kin_mobile', value: franchiseeNextOfKinMobile }) if (franchiseeNextOfKinRelationship != 0) { zeeRecord.setValue({ fieldId: 'custentity_kin_relationship', value: franchiseeNextOfKinRelationship }) } if (listforsale == 'T') { zeeRecord.setValue({ fieldId: 'custentity_listed_for_sale', value: 1 }); zeeRecord.setValue({ fieldId: 'custentity_date_listed_for_sale', value: getDateToday() }); var email_body = ' Franchisee NS ID: ' + zeeId + '</br> Franchisee Name: ' + zeeName + '</br> Date: ' + getDateToday() + '</br> Franchisee NS ID: ' + zeeRecordId; email.send({ author: 112209, recipients: ['PI:EMAIL:kenaa@example.comEND_PI'], subject: 'Listed for Sale - ' + zeeName + ' Franchisee', body: email_body, cc: ['PI:EMAIL:lyhxr@example.comEND_PI'] }); } log.debug({ title: 'isDynamic', details: zeeRecord.isDynamic }) //ADD/UPDATE ADDRESS if (!isNullorEmptyExcZero(addressidsArrays)) { for (var x = 0; x < addressidsArrays.length; x++) { log.debug({ title: 'addressidsArrays[x]', details: addressidsArrays[x] }) if (addressidsArrays[x] == 0 || addressidsArrays[x] == '0') { log.debug({ title: 'inside new' }) zeeRecord.insertLine({ sublistId: 'addressbook', line: 0 }) var lineIndex = 0; } else { var lineIndex = zeeRecord.findSublistLineWithValue({ sublistId: 'addressbook', fieldId: 'internalid', value: addressidsArrays[x] }); log.debug({ title: "lineIndex", details: lineIndex }); } var updateAddress = zeeRecord.getSublistSubrecord({ sublistId: 'addressbook', fieldId: 'addressbookaddress', line: lineIndex }) updateAddress.setValue({ fieldId: 'country', value: 'AU' }); updateAddress.setValue({ fieldId: 'addressee', value: franchiseeMainContact }); updateAddress.setValue({ fieldId: 'addr1', value: address1Arrays[x] }); updateAddress.setValue({ fieldId: 'addr2', value: address2Arrays[x] }); updateAddress.setValue({ fieldId: 'city', value: suburbArrays[x] }); updateAddress.setValue({ fieldId: 'state', value: stateArrays[x] }); updateAddress.setValue({ fieldId: 'zip', value: postcodeArrays[x] }); updateAddress.setValue({ fieldId: 'isresidential', value: 'T' }); } } if (!isNullorEmpty(addressidsdeleteArrays)) { for (var x = 0; x < addressidsdeleteArrays.length; x++) { var lineIndex = zeeRecord.findSublistLineWithValue({ sublistId: 'addressbook', fieldId: 'internalid', value: addressidsdeleteArrays[x] }); var deleteAddress = zeeRecord.removeSublistSubrecord({ sublistId: 'addressbook', fieldId: 'addressbookaddress', line: lineIndex }) // // deleteAddress.setValue({ // fieldId: 'country', // value: 'AU' // }); } } var zeeRecordId = zeeRecord.save({ ignoreMandatoryFields: true }); //ADD/UPDATE OPREATOR DETAILS if (!isNullorEmpty(operatoridsArrys)) { for (var y = 0; y < operatoridsArrys.length; y++) { var operatorRecord = record.load({ type: 'customrecord_operator', id: operatoridsArrys[y] }); var spliName = operatornameArrys[y].split(" "); operatorRecord.setValue({ fieldId: 'custrecord_operator_givennames', value: spliName[0] }) operatorRecord.setValue({ fieldId: 'custrecord_operator_surname', value: spliName[1] }) operatorRecord.setValue({ fieldId: 'name', value: operatornameArrys[y] }) operatorRecord.setValue({ fieldId: 'custrecord_operator_email', value: operatoremailArrys[y] }) operatorRecord.setValue({ fieldId: 'custrecord_operator_date_reviewed', value: getDateToday() }) operatorRecord.setValue({ fieldId: 'custrecord_operator_phone', value: operatormobileArrys[y] }) operatorRecord.setValue({ fieldId: 'custrecord_operator_role', value: operatorroleArrys[y] }) operatorRecord.setValue({ fieldId: 'custrecord_operator_employment', value: operatoremploymentypeArrys[y] }) operatorRecord.setValue({ fieldId: 'custrecord_dds_operator', value: operatorddsArrys[y] }) operatorRecord.setValue({ fieldId: 'custrecord_primary_operator', value: operatorprimaryArrys[y] }) if (!isNullorEmpty(operatormobiledevArrys[y])) { operatorRecord.setValue({ fieldId: 'custrecord_operator_mobdev_platform', value: operatormobiledevArrys[y] }) } operatorRecord.save() } } //NEW OPERATOR DETAILS if (!isNullorEmpty(newoperatoridsArrys)) { log.debug({ title: 'newoperatoridsArrys.length', details: newoperatoridsArrys.length }) for (var y = 0; y < newoperatoridsArrys.length; y++) { var operatorRecord = record.create({ type: 'customrecord_operator' }); if (!isNullorEmpty(newoperatornameArrys[y])) { var spliName = newoperatornameArrys[y].split(" "); operatorRecord.setValue({ fieldId: 'custrecord_operator_givennames', value: spliName[0] }) if (isNullorEmpty(spliName[1])) { operatorRecord.setValue({ fieldId: 'custrecord_operator_surname', value: spliName[0] }) } else { operatorRecord.setValue({ fieldId: 'custrecord_operator_surname', value: spliName[1] }) } } operatorRecord.setValue({ fieldId: 'name', value: newoperatornameArrys[y] }) operatorRecord.setValue({ fieldId: 'custrecord_operator_email', value: newoperatoremailArrys[y] }) operatorRecord.setValue({ fieldId: 'custrecord_operator_franchisee', value: zeeRecordId }) operatorRecord.setValue({ fieldId: 'custrecord_operator_franchisee2', value: zeeRecordId }) operatorRecord.setValue({ fieldId: 'custrecord_operator_salutation', value: 1 }) operatorRecord.setValue({ fieldId: 'custrecord_operator_status', value: 4 }) operatorRecord.setValue({ fieldId: 'custrecord_operator_app_date_link_sent', value: getDateToday() }) operatorRecord.setValue({ fieldId: 'custrecord_operator_date_reviewed', value: getDateToday() }) operatorRecord.setValue({ fieldId: 'custrecord_operator_phone', value: newoperatormobileArrys[y] }) operatorRecord.setValue({ fieldId: 'custrecord_operator_role', value: newoperatorroleArrys[y] }) operatorRecord.setValue({ fieldId: 'custrecord_operator_employment', value: newoperatoremploymentypeArrys[y] }) operatorRecord.setValue({ fieldId: 'custrecord_dds_operator', value: newoperatorddsArrys[y] }) operatorRecord.setValue({ fieldId: 'custrecord_primary_operator', value: newoperatorprimaryArrys[y] }) if (!isNullorEmpty(operatormobiledevArrys[y])) { operatorRecord.setValue({ fieldId: 'custrecord_operator_mobdev_platform', value: newoperatormobiledevArrys[y] }) } var operatorIdNew = operatorRecord.save() var email_body = ' New Operator NS ID: ' + operatorIdNew + '</br> New Operator Name: ' + newoperatornameArrys[y] + '</br> New Operator Email: ' + newoperatoremailArrys[y] + '</br> New Operator Mobile: ' + newoperatormobileArrys[y] + '</br> Franchisee NS ID: ' + zeeRecordId; email.send({ author: 112209, recipients: ['PI:EMAIL:efpyi@example.comEND_PI'], subject: 'MP Operator Access - New Operator', body: email_body, cc: ['PI:EMAIL:efpyi@example.comEND_PI', 'PI:EMAIL:lyhxr@example.comEND_PI', 'PI:EMAIL:dycjh@example.comEND_PI', 'PI:EMAIL:envkt@example.comEND_PI' ] }); } } if (!isNullorEmpty(operatoridsdeleteArrys)) { for (var y = 0; y < operatoridsdeleteArrys.length; y++) { var deleteOperatorRecord = record.load({ type: 'customrecord_operator', id: operatoridsdeleteArrys[y] }); deleteOperatorRecord.setValue({ fieldId: 'isinactive', value: true }) deleteOperatorRecord.setValue({ fieldId: 'custrecord_operator_status', value: 3 }) var getOperatorEmail = deleteOperatorRecord.getValue({ fieldId: 'custrecord_operator_email' }) var getOperatorName = deleteOperatorRecord.getValue({ fieldId: 'name' }) deleteOperatorRecord.save(); var email_body = ' Delete Operator NS ID: ' + operatoridsdeleteArrys[y] + '</br> Franchisee NS ID: ' + zeeRecordId + '</br> Operator Name: ' + getOperatorName + '</br> Operator Email: ' + getOperatorEmail; email.send({ author: 112209, recipients: ['PI:EMAIL:efpyi@example.comEND_PI'], subject: 'MP Operator Access - Delete/Inactive Operator', body: email_body, cc: ['PI:EMAIL:efpyi@example.comEND_PI', 'PI:EMAIL:lyhxr@example.comEND_PI', 'PI:EMAIL:dycjh@example.comEND_PI', 'PI:EMAIL:envkt@example.comEND_PI' ] }); } } //ADD/EDIT FLEET DETAILS if (!isNullorEmpty(fleetidsArrys)) { for (var w = 0; w < fleetidsArrys.length; w++) { var vehicleRecord = record.load({ type: 'customrecord_vehicle', id: fleetidsArrys[w] }); vehicleRecord.setValue({ fieldId: 'name', value: fleetregoArrys[w] }) vehicleRecord.setValue({ fieldId: 'custrecord_vehicle_model_text', value: fleetmodelArrys[w] }) vehicleRecord.setValue({ fieldId: 'custrecord_vehicle_make', value: fleetmakeArrys[w] }) vehicleRecord.setValue({ fieldId: 'custrecord_vehicle_colour', value: fleetcolorArrys[w] }) vehicleRecord.setValue({ fieldId: 'custrecord_vehicle_year', value: fleetyearArrys[w] }) if (fleetsignageArrys[w] == 1 || fleetsignageArrys[w] == '1') { vehicleRecord.setValue({ fieldId: 'custrecord_vehicle_signage', value: true }) } vehicleRecord.setValue({ fieldId: 'custrecord_cargo_cage', value: caregocageArrys[w] }) vehicleRecord.setValue({ fieldId: 'custrecord_vehicle_owner', value: ownerArrys[w] }) vehicleRecord.setValue({ fieldId: 'custrecord_vehicle_date_reviewed', value: getDateToday() }) var newFleetID = vehicleRecord.save() //SAVE FLEET DETAILS ON THE OPERATOR RECORD var operatorRecord = record.load({ type: 'customrecord_operator', id: operatorArrys[w] }); operatorRecord.setValue({ fieldId: 'custrecord_operator_vehicle', value: newFleetID }) operatorRecord.save(); } } //CREATE NEW FLEET DETAILS if (!isNullorEmpty(newfleetidsArrys)) { for (var w = 0; w < newfleetidsArrys.length; w++) { var vehicleRecord = record.create({ type: 'customrecord_vehicle' }); vehicleRecord.setValue({ fieldId: 'name', value: newfleetregoArrys[w] }) vehicleRecord.setValue({ fieldId: 'custrecord_vehicle_franchisee', value: zeeRecordId }) vehicleRecord.setValue({ fieldId: 'custrecord_vehicle_model_text', value: newfleetmodelArrys[w] }) vehicleRecord.setValue({ fieldId: 'custrecord_vehicle_make', value: newfleetmakeArrys[w] }) vehicleRecord.setValue({ fieldId: 'custrecord_vehicle_colour', value: newfleetcolorArrys[w] }) vehicleRecord.setValue({ fieldId: 'custrecord_vehicle_year', value: newfleetyearArrys[w] }) if (newfleetsignageArrys[w] == 1 || newfleetsignageArrys[w] == '1') { vehicleRecord.setValue({ fieldId: 'custrecord_vehicle_signage', value: true }) } vehicleRecord.setValue({ fieldId: 'custrecord_cargo_cage', value: newcaregocageArrys[w] }) vehicleRecord.setValue({ fieldId: 'custrecord_vehicle_owner', value: newownerArrys[w] }) vehicleRecord.setValue({ fieldId: 'custrecord_vehicle_date_reviewed', value: getDateToday() }) var newFleetID = vehicleRecord.save() //SAVE FLEET DETAILS ON THE OPERATOR RECORD var operatorRecord = record.load({ type: 'customrecord_operator', id: newoperatorArrys[w] }); operatorRecord.setValue({ fieldId: 'custrecord_operator_vehicle', value: newFleetID }) operatorRecord.save() } } if (!isNullorEmpty(fleetidsdeleteArrys)) { for (var y = 0; y < fleetidsdeleteArrys.length; y++) { var deleteFleetRecord = record.load({ type: 'customrecord_vehicle', id: fleetidsdeleteArrys[y] }); deleteFleetRecord.setValue({ fieldId: 'isinactive', value: true }) deleteFleetRecord.save() } } redirect.toSuitelet({ scriptId: 'customscript_sl2_zee_management_console', deploymentId: 'customdeploy1', }); } } /* * PURPOSE : ADDS SPACING * PARAMS : * RETURNS : INLINEHTML * NOTES : */ function spacing() { var inlineHtml = '<div class="form-group spacing_section">'; inlineHtml += '<div class="row">'; inlineHtml += '</div>'; inlineHtml += '</div>'; return inlineHtml; } /* * PURPOSE : ADDS HORIZONTAL LINE TO DIVIDE SECTIONS * PARAMS : * RETURNS : INLINEHTML * NOTES : */ function line() { var inlineHtml = '<hr style="height:5px; width:100%; border-width:0; color:red; background-color:#fff">' return inlineHtml } /* * PURPOSE : PROGRESS BAR AT THE TOP OF THE PAGE TO SHOW AT WHAT STAGE THE FRANCHISE SALES & MANAGEMENT WORKFLOW IS AT. ONLY SEEN TO THE HEADOFFICE USERS NOT AVAILABLE TO THE FRANCHISEES * PARAMS : * RETURNS : INLINEHTML * NOTES : */ function progressBar() { var inlineHtml = '<div class="form-group progress_section">'; inlineHtml += '<div class="row">'; inlineHtml += '<div class=""> <div class="wrapper"> <div class="arrow-steps clearfix"><div class="step"> <span>SALES PROCESS</span> </div><div class="step"> <span>FINANCIALS</span> </div><div class="step"> <span>PRESENTATIONS & INTERVIEW</span> </div><div class="step"> <span>SETTLEMENT</span> </div><div class="step"> <span><span class="glyphicon glyphicon-ok" style="color: #fff"></span>TRAINING</span> </div><div class="step"> <span>FRANCHISE AGREEMENTS</span> </div><div class="step"> <span>NETSUITE SETUP</span> </div><div class="step"> <span>ONBOARDING</span> </div><div class="step current"> <span>UPDATE/EDIT DETAILS</span> </div></div>'; // inlineHtml += '<div class="nav clearfix"><a href="#" class="prev">Previous</a><a href="#" class="next pull-right">Next</a></div></div></div>' inlineHtml += '</div></div>' inlineHtml += '</div>'; inlineHtml += '</div>'; return inlineHtml } /* * PURPOSE : BUTTONS SECTION AT THE END OF THE PAGE. * PARAMS : USER ROLE * RETURNS : INLINEHTML * NOTES : */ function mainButtons(role) { var inlineHtml = '' if (role != 1000) { inlineHtml += '<div class="form-group container zee_available_buttons_section">'; inlineHtml += '<div class="row">'; inlineHtml += '<div class="col-xs-6 updateDetails"><input type="button" value="UPDATE DETAILS" class="form-control btn btn-primary" id="updateDetails" /></div>' if (franchiseeListedForSale != 1) { inlineHtml += '<div class="col-xs-6 listForSale"><input type="button" value="LIST FOR SALE" class="form-control btn btn-success" id="listForSale" /></div>' } else { inlineHtml += '<div class="col-xs-6 listForSale"><input type="button" value="LISTED FOR SALE" class="form-control btn btn-success" id="" disabled/></div>' } inlineHtml += '</div>'; inlineHtml += '</div>'; inlineHtml += '<div class="form-group container zee_admin_section">'; inlineHtml += '<div class="row">'; inlineHtml += '<div class="col-xs-3 sendEmail"><input type="button" value="Send Email" class="form-control btn btn-primary" id="sendEmail" /></div>' inlineHtml += '<div class="col-xs-3 sendSMS"><input type="button" value="Send SMS" class="form-control btn btn-primary" id="sendSMS" /></div>' inlineHtml += '<div class="col-xs-3 breachNotice"><input type="button" value="Breach Notice" class="form-control btn btn-warning" id="breachNotice" /></div>' inlineHtml += '<div class="col-xs-3 termination"><input type="button" value="Termination" class="form-control btn btn-danger" id="termination" /></div>' inlineHtml += '</div>'; inlineHtml += '</div>'; } else { inlineHtml += '<div class="form-group container zee_available_buttons_section">'; inlineHtml += '<div class="row">'; inlineHtml += '<div class="col-xs-6 updateDetails"><input type="button" value="UPDATE DETAILS" class="form-control btn btn-primary" id="updateDetails" /></div>' if (franchiseeListedForSale != 1) { inlineHtml += '<div class="col-xs-6 listForSale"><input type="button" value="LIST FOR SALE" class="form-control btn btn-success" id="listForSale" /></div>' } else { inlineHtml += '<div class="col-xs-6 listForSale"><input type="button" value="LISTED FOR SALE" class="form-control btn btn-success" id="" disabled/></div>' } inlineHtml += '</div>'; inlineHtml += '</div>'; } return inlineHtml } /* * PURPOSE : CREATES THE TAB SECTION FOR THE PAGE * PARAMS : ZEE ID, USER ROLE & OPERATOR SEARCH RESULT * RETURNS : INLINEHTML * NOTES : */ function tabSection(zee, role, resultSetOperators) { //TAB HEADERS var inlineHtml = '<div>' inlineHtml += '<div style="width: 95%; margin:auto; margin-bottom: 30px"><ul class="nav nav-tabs nav-justified main-tabs-sections " style="margin:0%;border-bottom-color: #fbea50 !important;border-bottom-width: 5px !important;border-bottom-style: solid;">'; inlineHtml += '<li role="presentation" class="active"><a data-toggle="tab" href="#zeeDetails"><b>MAIN DETAILS</b></a></li>'; inlineHtml += '<li role="presentation" class=""><a data-toggle="tab" href="#operatorDetails"><b>OPERATION DETAILS</b></a></li>'; inlineHtml += '<li role="presentation" class=""><a data-toggle="tab" href="#tollMPEX"><b>PICKUP & LODGEMENT LOCATIONS</b></a></li>'; if (role != 1000) { inlineHtml += '<li role="presentation" class=""><a data-toggle="tab" href="#zeeAgreements"><b>AGREEMENTS</b></a></li>'; inlineHtml += '<li role="presentation" class=""><a data-toggle="tab" href="#breachDetails"><b>BREACH & TERMINATION DETAILS</b></a></li>'; } inlineHtml += '</ul></div>'; //TAB CONTENT inlineHtml += '<div class="tab-content">'; inlineHtml += '<div role="tabpanel" class="tab-pane active" id="zeeDetails">'; inlineHtml += franchiseeMainDetails(zee) inlineHtml += franchiseeNextOfKin() inlineHtml += '</div>'; inlineHtml += '<div role="tabpanel" class="tab-pane " id="zeeAgreements">'; inlineHtml += franchiseeAgreements(zee, role) inlineHtml += '</div>'; inlineHtml += '<div role="tabpanel" class="tab-pane " id="operatorDetails">'; inlineHtml += franchiseeOperatorDetails(zee, resultSetOperators) inlineHtml += franchiseeFleetDetails(zee, resultSetOperators) inlineHtml += '</div>'; inlineHtml += '<div role="tabpanel" class="tab-pane " id="tollMPEX">'; inlineHtml += franchiseeTOLLMPEX() inlineHtml += franchiseeAdhoc() inlineHtml += '</div>'; //BREACH NOTICE & TERMINATION ONLY SEEN BY HEAD OFFICE USERS if (role != 1000) { inlineHtml += '<div role="tabpanel" class="tab-pane " id="breachDetails">'; inlineHtml += franchiseeBreachDetails() inlineHtml += franchiseeTerminationDetails() inlineHtml += '</div>'; } inlineHtml += '</div></div>'; return inlineHtml; } /* * PURPOSE : SELECT FRANCHISEE TO UPDATE. ONLY AVAILABLE FOR HEADOFFICE USERS * PARAMS : ZEE ID * RETURNS : INLINEHTML * NOTES : */ function selectFranchiseeSection(zee) { var inlineHtml = '<div class="form-group container zee_section">'; inlineHtml += '<div class="row">'; inlineHtml += '<div class="col-xs-12 heading1"><h4><span class="label label-default col-xs-12" style="background-color: #103D39;">SELECT FRANCHISEE</span></h4></div>'; inlineHtml += '</div>'; inlineHtml += '</div>'; inlineHtml += '<div class="form-group container zee_select_section">'; inlineHtml += '<div class="row">'; inlineHtml += '<div class="col-xs-12 zee"><div class="input-group"><span class="input-group-addon" id="zee_text">FRANCHISEE <span class="mandatory">*</span></span><select id="zee_dropdown" class="form-control zee" ><option value=0></option>'; //NetSuite Search: Zee Management Console - Franchisees var searchZees = search.load({ id: 'customsearch_zee_management_console_zee', type: 'partner' }); var resultSetZees = searchZees.run(); resultSetZees.each(function (searchResultZees) { zeeId = searchResultZees.getValue('internalid'); franchiseeName = searchResultZees.getValue('companyname'); mainContact = searchResultZees.getValue('custentity3'); mainContactFName = searchResultZees.getValue( 'custentity_franchisee_firstname'); mainContactLName = searchResultZees.getValue( 'custentity_franchisee_lastname'); primaryEmail = searchResultZees.getValue('email'); personalEmail = searchResultZees.getValue( 'custentity_personal_email_address'); mainContactMobile = searchResultZees.getValue( 'custentity2'); franchiseeABN = searchResultZees.getValue( 'custentity_abn_franchiserecord'); franchiseeAddress = searchResultZees.getValue( 'shipaddress'); if (zeeId == zee) { inlineHtml += '<option value="' + zeeId + '" selected>' + franchiseeName + '</option>'; } else { inlineHtml += '<option value="' + zeeId + '">' + franchiseeName + '</option>'; } return true; }); inlineHtml += '</select></div></div>'; inlineHtml += '</div>'; inlineHtml += '</div>'; return inlineHtml; } /* * PURPOSE : FRANCHISE MAIN DETAILS TAB * PARAMS : ZEE ID * RETURNS : INLINEHTML * NOTES : */ function franchiseeMainDetails(zee) { //NetSuite Search: Zee Management Console - Franchisees var searchZees = search.load({ id: 'customsearch_zee_management_console_zee', type: 'partner' }); if (!isNullorEmpty(zee)) { searchZees.filters.push(search.createFilter({ name: 'internalid', join: null, operator: search.Operator.IS, values: zee })); } var resultSetZees = searchZees.run(); resultSetZees.each(function (searchResultZees) { zeeId = searchResultZees.getValue('internalid'); franchiseeName = searchResultZees.getValue('companyname'); mainContact = searchResultZees.getValue('custentity3'); mainContactFName = searchResultZees.getValue( 'custentity_franchisee_firstname'); mainContactLName = searchResultZees.getValue( 'custentity_franchisee_lastname'); primaryEmail = searchResultZees.getValue('email'); personalEmail = searchResultZees.getValue( 'custentity_personal_email_address'); mainContactMobile = searchResultZees.getValue( 'custentity2'); franchiseeABN = searchResultZees.getValue( 'custentity_abn_franchiserecord'); franchiseeAddress = searchResultZees.getValue( 'shipaddress'); franchiseeTOLLAccountNumber = searchResultZees.getValue( 'custentity_toll_acc_number'); franchiseeTOLLPickupDX = searchResultZees.getText( 'custentity__toll_pickup_dx_no'); franchiseeTOLLLodgementDX = searchResultZees.getText( 'custentity_toll_lodge_dx_no'); franchiseeSendlePrimaryLocations = searchResultZees.getText( 'custentity_sendle_hubbed_locations'); franchiseeLastMileLocations = searchResultZees.getText( 'custentity_lastmile_suburb'); franchiseeSendleSecondaryLocations = searchResultZees.getText( 'custentity_sendle_hubbed_location_sec'); franchiseeTypeOfOwner = searchResultZees.getValue( 'custentity_type_of_owner'); vaccinationStatus = searchResultZees.getValue( 'custentity_vacc_status'); dob = searchResultZees.getValue( 'custentity_zee_dob'); personalEmail = searchResultZees.getValue( 'custentity_personal_email_address'); franchiseeNextOfKinMobile = searchResultZees.getValue( 'custentity_kin_mobile'); franchiseeNextOfKinName = searchResultZees.getValue( 'custentity_kin_name'); franchiseeNextOfKinRelationship = searchResultZees.getValue( 'custentity_kin_relationship'); franchiseeListedForSale = searchResultZees.getValue( 'custentity_listed_for_sale'); return true; }); //NetSuite Search: SALESP - Addresses var searched_addresses = search.load({ id: 'customsearch_salesp_address', type: 'customer' }); searched_addresses.filters.push(search.createFilter({ name: 'internalid', operator: search.Operator.ANYOF, values: zee })); resultSetAddresses = searched_addresses.run(); var inlineHtml = '<div class="form-group container">'; inlineHtml += '<div class="row">'; inlineHtml += '<div class="col-xs-12 heading1"><h4><span class="label label-default col-xs-12" style="background-color: #103D39;">FRANCHISEE DETAILS</span></h4></div>'; inlineHtml += '</div>'; inlineHtml += '</div>'; inlineHtml += '<div class="form-group container">'; inlineHtml += '<div class="row">'; inlineHtml += '<div class="col-xs-12 name_section"><div class="input-group"><span class="input-group-addon">FRANCHISE NAME</span><input id="franchiseeName" class="form-control franchiseeName" value="' + franchiseeName + '" readonly/></div></div>'; inlineHtml += '</div>'; inlineHtml += '</div>'; inlineHtml += '<div class="form-group container">'; inlineHtml += '<div class="row">'; inlineHtml += '<div class="col-xs-6 name_section"><div class="input-group"><span class="input-group-addon">MAIN CONTACT</span><input id="mainContact" data-old="' + mainContact + '" class="form-control mainContact" value="' + mainContact + '" /></div></div>'; inlineHtml += '<div class="col-xs-6 name_section"><div class="input-group"><span class="input-group-addon">MOBILE NUMBER <span class="mandatory">*</span></span><input id="mainContactMobile" class="form-control mainContact" value="' + mainContactMobile + '" data-old="' + mainContactMobile + '"/></div></div>'; inlineHtml += '</div>'; inlineHtml += '</div>'; inlineHtml += '<div class="form-group container">'; inlineHtml += '<div class="row">'; inlineHtml += '<div class="col-xs-6 zee"><div class="input-group"><span class="input-group-addon" id="zee_text">TYPE OF OWNER <span class="mandatory">*</span></span><select id="franchiseeTypeOfOwner" class="form-control franchiseeTypeOfOwner" data-old="' + franchiseeTypeOfOwner + '">'; if (franchiseeTypeOfOwner == 0 || isNullorEmpty(franchiseeTypeOfOwner)) { inlineHtml += '<option value=0></option><option value=1>COMPANY OWNED</option><option value=2>INVESTOR</option><option value=3>Owner / Operator</option>'; } else if (franchiseeTypeOfOwner == 1) { inlineHtml += '<option value=0></option><option value=1 selected>COMPANY OWNED</option><option value=2>INVESTOR</option><option value=3>Owner / Operator</option>'; } else if (franchiseeTypeOfOwner == 2) { inlineHtml += '<option value=0></option><option value=1>COMPANY OWNED</option><option value=2 selected>INVESTOR</option><option value=3>Owner / Operator</option>'; } else if (franchiseeTypeOfOwner == 3) { inlineHtml += '<option value=0></option><option value=1>COMPANY OWNED</option><option value=2>INVESTOR</option><option value=3 selected>Owner / Operator</option>'; } inlineHtml += '</select></div></div>'; inlineHtml += '<div class="col-xs-6 name_section"><div class="input-group"><span class="input-group-addon">ABN</span><input id="franchiseeABN" class="form-control franchiseeABN" readonly value="' + franchiseeABN + '" /></div></div>'; inlineHtml += '</div>'; inlineHtml += '</div>'; inlineHtml += '<div class="form-group container">'; inlineHtml += '<div class="row">'; inlineHtml += '<div class="col-xs-6 name_section"><div class="input-group"><span class="input-group-addon">PRIMARY EMAIL</span><input id="primaryEmail" class="form-control primaryEmail" value="' + primaryEmail + '" readonly/></div></div>'; inlineHtml += '<div class="col-xs-6 name_section"><div class="input-group"><span class="input-group-addon">PERSONAL EMAIL <span class="mandatory">*</span></span><input id="personalEmail" class="form-control personalEmail" value="' + personalEmail + '" data-old="' + personalEmail + '" /></div></div>'; inlineHtml += '</div>'; inlineHtml += '</div>'; inlineHtml += '<div class="form-group container company_name_section">'; inlineHtml += '<div class="row">'; var dobArray = dob.split('/'); if (dobArray[1] < 10) { dobArray[1] = '0' + dobArray[1]; } if (dobArray[0] < 10) { dobArray[0] = '0' + dobArray[0]; } var formattedDOB = dobArray[2] + '-' + dobArray[1] + '-' + dobArray[0] inlineHtml += '<div class="col-xs-6 name_section"><div class="input-group"><span class="input-group-addon">DATE OF BIRTH <span class="mandatory">*</span></span><input id="dob" type="date" class="form-control dob" value="' + formattedDOB + '" data-old="' + formattedDOB + '"/></div></div>'; inlineHtml += '<div class="col-xs-6 zee"><div class="input-group"><span class="input-group-addon" id="zee_text">VACCINATION STATUS <span class="mandatory">*</span></span><select id="vaccinationStatus" class="form-control vaccinationStatus" data-old="' + vaccinationStatus + '">'; if (vaccinationStatus == 1) { inlineHtml += '<option value=0></option><option value=1 selected>YES</option><option value=2>NO</option>'; } else if (vaccinationStatus == 2) { inlineHtml += '<option value=0></option><option value=1>YES</option><option value=2 selected>NO</option>'; } else { inlineHtml += '<option value=0 selected></option><option value=1>YES</option><option value=2>NO</option>'; } inlineHtml += '</select></div></div>'; inlineHtml += '</div>'; inlineHtml += '</div>'; inlineHtml += '<div class="form-group container">'; inlineHtml += '<div class="row">'; inlineHtml += '<div class="col-xs-12 heading1"><h4><span class="label label-default col-xs-12" style="background-color: #103D39;">ADDRESS DETAILS</span></h4></div>'; inlineHtml += '</div>'; inlineHtml += '</div>'; //HIDDEN SECTION TO ADD/EDIT ADDRESS DETAILS inlineHtml += '<div class="form-group container row_address1 hide">' inlineHtml += '<div class="row">'; inlineHtml += '<input id="internalid" value="" type="hidden"/>' inlineHtml += '<div class="col-xs-6 address1_section"><div class="input-group"><span class="input-group-addon">UNIT/LEVEL/SUITE</span><input id="address1" class="form-control address1" /></div></div>'; inlineHtml += '<div class="col-xs-6 address2_section"><div class="input-group"><span class="input-group-addon">STREET NO. & NAME <span class="mandatory">*</span></span><input id="address2" class="form-control address2" /></div></div>'; inlineHtml += '</div>'; inlineHtml += '</div>'; inlineHtml += '<div class="form-group container city_state_postcode hide">' inlineHtml += '<div class="row">'; inlineHtml += '<div class="col-xs-6"><div class="input-group"><span class="input-group-addon">CITY</span><input id="city" readonly class="form-control city" /></div></div>'; inlineHtml += '<div class="col-xs-3"><div class="input-group"><span class="input-group-addon">STATE</span><input id="state" readonly class="form-control state" /></div></div>'; inlineHtml += '<div class="col-xs-3 post_code_section"><div class="input-group"><span class="input-group-addon">POSTCODE</span><input id="postcode" readonly class="form-control postcode" /></div></div>'; inlineHtml += '</div>'; inlineHtml += '</div>'; inlineHtml += '<div class="form-group container saveaddress_section hide">'; inlineHtml += '<div class="row">'; inlineHtml += '<div class="col-xs-2 "></div>'; inlineHtml += '<div class="col-xs-4 reviewaddress"><input type="button" value="SAVE ADDRESSES" class="form-control btn btn-success" id="saveAddress" /></div>'; inlineHtml += '<div class="col-xs-4 cancel"><input type="button" value="CANCEL" class="form-control btn btn-secondary" id="cancel" /></div>'; inlineHtml += '<div class="col-xs-2 "></div>'; inlineHtml += '</div>'; inlineHtml += '</div>'; //ADDRESS TABLE inlineHtml += addressContactsSection(resultSetAddresses); return inlineHtml } /* * PURPOSE : LIST OF FRANCHISEE AGREEMENTS RELATED TO THE ZEE * PARAMS : ZEE ID & USER ROLE * RETURNS : INLINEHTML * NOTES : */ function franchiseeAgreements(zee, role) { //NetSuite Search: Zee Agreement - Search var searchZeeAgreements = search.load({ id: 'customsearch_zee_agree_search', type: 'customrecord_fr_agreements' }); if (!isNullorEmpty(zee)) { searchZeeAgreements.filters.push(search.createFilter({ name: 'internalid', join: 'CUSTRECORD_FR_AGREEMENT_FRANCHISEE', operator: search.Operator.IS, values: zee })); } var resultSetZeeAgreements = searchZeeAgreements.run(); var inlineHtml = '<div class="form-group container">'; inlineHtml += '<div class="row">'; inlineHtml += '<div class="col-xs-12 heading1"><h4><span class="label label-default col-xs-12" style="background-color: #103D39;">FRANCHISE AGREEMENTS</span></h4></div>'; inlineHtml += '</div>'; inlineHtml += '</div>'; inlineHtml += '<div class="form-group container">'; inlineHtml += '<div class="row">'; inlineHtml += '<style>table#zeeAgreementsTable {color: #103D39 !important; font-size: 12px;text-align: center;border: none;}.dataTables_wrapper {font-size: 14px;}table#zeeAgreementsTable th{text-align: center;} .bolded{font-weight: bold;}</style>'; inlineHtml += '<table id="zeeAgreementsTable" class="table table-responsive table-striped zeeAgreementsTable tablesorter" style="width: 100%;border: 1px solid #103d39;">'; inlineHtml += '<thead style="color: white;background-color: #379E8F;font-weight: bold;">'; inlineHtml += '<tr class="text-center">'; //ABILITY TO ADD/EDIT ONLY FOR HEADOFFICE USERS if (role != 1000) { inlineHtml += '<td>LINK</td>' } inlineHtml += '<td>NS ID</td>' inlineHtml += '<td>NAME</td>' inlineHtml += '<td>COMMENCEMENT DATE</td>' inlineHtml += '<td>EXPIRY DATE</td>' inlineHtml += '<td>ULTIMATE EXPIRY DATE</td>' inlineHtml += '<td>RENEWAL TERMS</td>' inlineHtml += '<td>AGREEMENT</td>' inlineHtml += '<td>AGREEMENT STATUS</td>' inlineHtml += '</tr>'; inlineHtml += '</thead>'; inlineHtml += '<tbody id="resultOperatorTable" class="">'; resultSetZeeAgreements.each(function (searchResultZeeAgreements) { zeeAgreementID = searchResultZeeAgreements.getValue('internalid'); zeeAgreementName = searchResultZeeAgreements.getValue('name'); zeeAgreementCommDate = searchResultZeeAgreements.getValue( 'custrecord_fr_agreement_comm_date'); zeeAgreementExpiryDate = searchResultZeeAgreements.getValue( 'custrecord_fr_agreement_expiry_date'); zeeAgreementUltExpiryDate = searchResultZeeAgreements.getValue( 'custrecord_fr_agreement_ult_expiry_date'); zeeAgreementStatus = searchResultZeeAgreements.getText( 'custrecord_fr_agreement_status'); zeeAgreementYearsExtended = searchResultZeeAgreements.getValue( 'custrecord_fr_agreement_yrs_extended'); zeeAgreementDeed = searchResultZeeAgreements.getValue( 'custrecord_fr_agreement_deed'); 1182 inlineHtml += '<tr>' //SHOW EDIT/DELETE LINKS TO ONLY HEADOFFICE USERS if (role != 1000) { inlineHtml += '<td><button class="form-control btn btn-xs btn-primary glyphicon glyphicon-pencil" style="cursor: not-allowed !important;width: fit-content;"><a data-id="' + zeeAgreementID + '" class="editOperator" style="cursor: pointer !important;color: white;"></a></button> <button class="form-control btn btn-xs btn-danger glyphicon glyphicon-trash" style="cursor: not-allowed !important;width: fit-content;"><a data-id="' + zeeAgreementID + '" class="deleteOperator" style="cursor: pointer !important;color: white;"></a></button></td>' } inlineHtml += '<td>' + zeeAgreementID + '</td>' inlineHtml += '<td><b><a href="https://1048144.app.netsuite.com/app/common/custom/custrecordentry.nl?rectype=384&id=' + zeeAgreementID + '">' + zeeAgreementName + '</a></b></td>' inlineHtml += '<td>' + zeeAgreementCommDate + '</td>' inlineHtml += '<td>' + zeeAgreementExpiryDate + '</td>' inlineHtml += '<td>' + zeeAgreementUltExpiryDate + '</td>' inlineHtml += '<td>' + zeeAgreementYearsExtended + '</td>' inlineHtml += '<td>' + zeeAgreementDeed + '</td>' inlineHtml += '<td>' + zeeAgreementStatus + '</td>' inlineHtml += '</tr>'; return true; }); inlineHtml += '</tbody></table>'; inlineHtml += '</div>'; inlineHtml += '</div>'; //ABILITY TO CREATE NEW AGREEMENT TO ONLY HEADOFFICE USERS if (role != 1000) { inlineHtml += franchiseeNewAgreement() } return inlineHtml; } /* * PURPOSE : TOLL MPEX RELATED DATA. * PARAMS : * RETURNS : INLINEHTML * NOTES : */ function franchiseeTOLLMPEX() { var inlineHtml = '<div class="form-group container">'; inlineHtml += '<div class="row">'; inlineHtml += '<div class="col-xs-12 heading1"><h4><span class="label label-default col-xs-12" style="background-color: #103D39;">TOLL - MPEX</span></h4></div>'; inlineHtml += '</div>'; inlineHtml += '</div>'; inlineHtml += '<div class="form-group container">'; inlineHtml += '<div class="row">'; inlineHtml += '<div class="col-xs-6 name_section"><div class="input-group"><span class="input-group-addon">TOLL Account Number</span><input id="franchiseeTOLLAccountNumber" class="form-control franchiseeTOLLAccountNumber" value="' + franchiseeTOLLAccountNumber + '" readonly/></div></div>'; inlineHtml += '</div>'; inlineHtml += '</div>'; inlineHtml += '<div class="form-group container">'; inlineHtml += '<div class="row">'; inlineHtml += '<div class="col-xs-6 name_section"><div class="input-group"><span class="input-group-addon">TOLL Pickup DX </span><input id="franchiseeTOLLPickupDX" class="form-control franchiseeTOLLPickupDX" readonly value="' + franchiseeTOLLPickupDX + '" /></div></div>'; inlineHtml += '<div class="col-xs-6 name_section"><div class="input-group"><span class="input-group-addon">TOLL Lodgement DX </span><input id="franchiseeTOLLLodgementDX" class="form-control franchiseeTOLLLodgementDX" readonly value="' + franchiseeTOLLLodgementDX + '" /></div></div>'; inlineHtml += '</div>'; inlineHtml += '</div>'; return inlineHtml; } /* * PURPOSE : FRANCHISE NEXT OF KIN DETAILS * PARAMS : * RETURNS : INLINEHTML * NOTES : */ function franchiseeNextOfKin() { var inlineHtml = '<div class="form-group container">'; inlineHtml += '<div class="row">'; inlineHtml += '<div class="col-xs-12 heading1"><h4><span class="label label-default col-xs-12" style="background-color: #103D39;">NEXT OF KIN</span></h4></div>'; inlineHtml += '</div>'; inlineHtml += '</div>'; inlineHtml += '<div class="form-group container">'; inlineHtml += '<div class="row">'; inlineHtml += '<div class="col-xs-4 name_section"><div class="input-group"><span class="input-group-addon">NAME <span class="mandatory">*</span></span><input id="franchiseeNextOfKinName" type="text" class="form-control franchiseeNextOfKinName" value="' + franchiseeNextOfKinName + '" data-old="' + franchiseeNextOfKinName + '"/></div></div>'; inlineHtml += '<div class="col-xs-3 name_section"><div class="input-group"><span class="input-group-addon">MOBILE NUMBER <span class="mandatory">*</span></span><input id="franchiseeNextOfKinMobile" class="form-control franchiseeNextOfKinMobile" value="' + franchiseeNextOfKinMobile + '" data-old="' + franchiseeNextOfKinMobile + '"/></div></div>'; inlineHtml += '<div class="col-xs-5 zee"><div class="input-group"><span class="input-group-addon" id="zee_text">RELATIONSHIP <span class="mandatory">*</span></span><select id="franchiseeNextOfKinRelationship" class="form-control franchiseeNextOfKinRelationship" data-old="' + franchiseeNextOfKinRelationship + '"><option value=0></option>'; /* Brother 5 Daughter 7 Father 1 Friend 9 Mother 2 Other 10 Partner 4 Sister 8 Son 6 Spouse 3 */ log.debug({ title: 'franchiseeNextOfKinRelationship', details: franchiseeNextOfKinRelationship }) switch (parseInt(franchiseeNextOfKinRelationship)) { case 5: inlineHtml += '<option value=0></option>'; inlineHtml += '<option value=5 selected>Brother</option>'; inlineHtml += '<option value=7>Daughter</option>'; inlineHtml += '<option value=1>Father</option>'; inlineHtml += '<option value=9>Friend</option>'; inlineHtml += '<option value=2>Mother</option>'; inlineHtml += '<option value=4>Partner</option>'; inlineHtml += '<option value=8>Sister</option>'; inlineHtml += '<option value=6>Son</option>'; inlineHtml += '<option value=3>Spouse</option>'; inlineHtml += '<option value=10>Other</option>'; break; case 7: inlineHtml += '<option value=0></option>'; inlineHtml += '<option value=5>Brother</option>'; inlineHtml += '<option value=7 selected>Daughter</option>'; inlineHtml += '<option value=1>Father</option>'; inlineHtml += '<option value=9>Friend</option>'; inlineHtml += '<option value=2>Mother</option>'; inlineHtml += '<option value=4>Partner</option>'; inlineHtml += '<option value=8>Sister</option>'; inlineHtml += '<option value=6>Son</option>'; inlineHtml += '<option value=3>Spouse</option>'; inlineHtml += '<option value=10>Other</option>'; break; case 1: inlineHtml += '<option value=0></option>'; inlineHtml += '<option value=5>Brother</option>'; inlineHtml += '<option value=7>Daughter</option>'; inlineHtml += '<option value=1 selected>Father</option>'; inlineHtml += '<option value=9>Friend</option>'; inlineHtml += '<option value=2>Mother</option>'; inlineHtml += '<option value=4>Partner</option>'; inlineHtml += '<option value=8>Sister</option>'; inlineHtml += '<option value=6>Son</option>'; inlineHtml += '<option value=3>Spouse</option>'; inlineHtml += '<option value=10>Other</option>'; break; case 9: inlineHtml += '<option value=0></option>'; inlineHtml += '<option value=5>Brother</option>'; inlineHtml += '<option value=7>Daughter</option>'; inlineHtml += '<option value=1>Father</option>'; inlineHtml += '<option value=9 selected>Friend</option>'; inlineHtml += '<option value=2>Mother</option>'; inlineHtml += '<option value=4>Partner</option>'; inlineHtml += '<option value=8>Sister</option>'; inlineHtml += '<option value=6>Son</option>'; inlineHtml += '<option value=3>Spouse</option>'; inlineHtml += '<option value=10>Other</option>'; break; case 2: inlineHtml += '<option value=0></option>'; inlineHtml += '<option value=5>Brother</option>'; inlineHtml += '<option value=7>Daughter</option>'; inlineHtml += '<option value=1>Father</option>'; inlineHtml += '<option value=9>Friend</option>'; inlineHtml += '<option value=2 selected>Mother</option>'; inlineHtml += '<option value=4>Partner</option>'; inlineHtml += '<option value=8>Sister</option>'; inlineHtml += '<option value=6>Son</option>'; inlineHtml += '<option value=3>Spouse</option>'; inlineHtml += '<option value=10>Other</option>'; break; case 10: inlineHtml += '<option value=0></option>'; inlineHtml += '<option value=5>Brother</option>'; inlineHtml += '<option value=7>Daughter</option>'; inlineHtml += '<option value=1>Father</option>'; inlineHtml += '<option value=9>Friend</option>'; inlineHtml += '<option value=2>Mother</option>'; inlineHtml += '<option value=4>Partner</option>'; inlineHtml += '<option value=8>Sister</option>'; inlineHtml += '<option value=6>Son</option>'; inlineHtml += '<option value=3>Spouse</option>'; inlineHtml += '<option value=10 selected>Other</option>'; break; case 4: inlineHtml += '<option value=0></option>'; inlineHtml += '<option value=5>Brother</option>'; inlineHtml += '<option value=7>Daughter</option>'; inlineHtml += '<option value=1>Father</option>'; inlineHtml += '<option value=9>Friend</option>'; inlineHtml += '<option value=2>Mother</option>'; inlineHtml += '<option value=4 selected>Partner</option>'; inlineHtml += '<option value=8>Sister</option>'; inlineHtml += '<option value=6>Son</option>'; inlineHtml += '<option value=3>Spouse</option>'; inlineHtml += '<option value=10>Other</option>'; break; case 8: inlineHtml += '<option value=0></option>'; inlineHtml += '<option value=5>Brother</option>'; inlineHtml += '<option value=7>Daughter</option>'; inlineHtml += '<option value=1>Father</option>'; inlineHtml += '<option value=9>Friend</option>'; inlineHtml += '<option value=2>Mother</option>'; inlineHtml += '<option value=4>Partner</option>'; inlineHtml += '<option value=8 selected>Sister</option>'; inlineHtml += '<option value=6>Son</option>'; inlineHtml += '<option value=3>Spouse</option>'; inlineHtml += '<option value=10>Other</option>'; break; case 6: inlineHtml += '<option value=0></option>'; inlineHtml += '<option value=5>Brother</option>'; inlineHtml += '<option value=7>Daughter</option>'; inlineHtml += '<option value=1>Father</option>'; inlineHtml += '<option value=9>Friend</option>'; inlineHtml += '<option value=2>Mother</option>'; inlineHtml += '<option value=4>Partner</option>'; inlineHtml += '<option value=8>Sister</option>'; inlineHtml += '<option value=6 selected>Son</option>'; inlineHtml += '<option value=3>Spouse</option>'; inlineHtml += '<option value=10>Other</option>'; break; case 3: inlineHtml += '<option value=0></option>'; inlineHtml += '<option value=5>Brother</option>'; inlineHtml += '<option value=7>Daughter</option>'; inlineHtml += '<option value=1>Father</option>'; inlineHtml += '<option value=9>Friend</option>'; inlineHtml += '<option value=2>Mother</option>'; inlineHtml += '<option value=4>Partner</option>'; inlineHtml += '<option value=8>Sister</option>'; inlineHtml += '<option value=6>Son</option>'; inlineHtml += '<option value=3 selected>Spouse</option>'; inlineHtml += '<option value=10>Other</option>'; break; default: inlineHtml += '<option value=0 selected></option>'; inlineHtml += '<option value=5>Brother</option>'; inlineHtml += '<option value=7>Daughter</option>'; inlineHtml += '<option value=1>Father</option>'; inlineHtml += '<option value=9>Friend</option>'; inlineHtml += '<option value=2>Mother</option>'; inlineHtml += '<option value=4>Partner</option>'; inlineHtml += '<option value=8>Sister</option>'; inlineHtml += '<option value=6>Son</option>'; inlineHtml += '<option value=3>Spouse</option>'; inlineHtml += '<option value=10>Other</option>'; break; } inlineHtml += '</select></div></div>'; inlineHtml += '</div>'; inlineHtml += '</div>'; return inlineHtml; } /* * PURPOSE : FRANCHISEE FIRST & LAST MILE DETAILS * PARAMS : * RETURNS : INLINEHTML * NOTES : */ function franchiseeAdhoc() { var inlineHtml = '<div class="form-group container">'; inlineHtml += '<div class="row">'; inlineHtml += '<div class="col-xs-12 heading1"><h4><span class="label label-default col-xs-12" style="background-color: #103D39;">ADHOC</span></h4></div>'; inlineHtml += '</div>'; inlineHtml += '</div>'; inlineHtml += '<div class="form-group container">'; inlineHtml += '<div class="row">'; inlineHtml += '<div class="col-xs-6 name_section"><div class="input-group"><span class="input-group-addon">First Mile Primary Location</span><input id="franchiseeSendlePrimaryLocations" class="form-control franchiseeSendlePrimaryLocations" value="' + franchiseeSendlePrimaryLocations + '" readonly/></div></div>'; inlineHtml += '<div class="col-xs-6 name_section"><div class="input-group"><span class="input-group-addon">First Mile Secondary Location</span><input id="franchiseeSendleSecondaryLocations" class="form-control franchiseeSendleSecondaryLocations" value="' + franchiseeSendleSecondaryLocations + '" readonly/></div></div>'; inlineHtml += '</div>'; inlineHtml += '</div>'; //ABILITY TO ADD/EDIT FIRST MILE SUBURBS inlineHtml += franchiseeAddEditFirstMile() inlineHtml += '<div class="form-group container">'; inlineHtml += '<div class="row">'; inlineHtml += '<div class="col-xs-12 name_section"><div class="input-group"><span class="input-group-addon">Last Mile Primary Location</span><input id="franchiseeLastMileLocations" class="form-control franchiseeLastMileLocations" value="' + franchiseeLastMileLocations + '" readonly/></div></div>'; inlineHtml += '</div>'; inlineHtml += '</div>'; //BUTTON TO ADD/EDIT LAST MILE SUBURBS inlineHtml += franchiseeAddEditLastMile() return inlineHtml; } /* * PURPOSE : BUTTON TO REDIRECT PAGE TO FRANCHISE SERVICE NETWORK * PARAMS : * RETURNS : INLINEHTML * NOTES : */ function franchiseeServiceNetwork() { var inlineHtml = '<div class="form-group container company_name_section">'; inlineHtml += '<div class="row">'; inlineHtml += '<div class="col-xs-3 heading1"></div>' inlineHtml += '<div class="col-xs-6 heading1"><input type="button" value="Your Franchise Service Network" class="form-control btn btn-primary" id="serviceNetwork" style="background-color: #287587;"/></div>' inlineHtml += '<div class="col-xs-3 heading1"></div>' inlineHtml += '</div>'; inlineHtml += '</div>'; return inlineHtml } /* * PURPOSE : BUTTON TO REDIRECT PAGE TO CREATION OF NEW AGREEMENT * PARAMS : * RETURNS : INLINEHTML * NOTES : */ function franchiseeNewAgreement() { var inlineHtml = '<div class="form-group container company_name_section">'; inlineHtml += '<div class="row">'; inlineHtml += '<div class="col-xs-3 heading1"></div>' inlineHtml += '<div class="col-xs-6 heading1"><input type="button" value="New Agreement" class="form-control btn btn-primary" id="newAgreement" style="background-color: #287587;"/></div>' inlineHtml += '<div class="col-xs-3 heading1"></div>' inlineHtml += '</div>'; inlineHtml += '</div>'; return inlineHtml } /* * PURPOSE : BUTTON TO ADD NEW OPERATOR TO THE TABLE * PARAMS : * RETURNS : INLINEHTML * NOTES : */ function franchiseeAddOperator() { var inlineHtml = '<div class="form-group container company_name_section">'; inlineHtml += '<div class="row">'; inlineHtml += '<div class="col-xs-3 heading1"></div>' inlineHtml += '<div class="col-xs-6 heading1"><input type="button" value="Add New Operator" class="form-control btn btn-primary" id="addOperator" style="background-color: #287587;"/></div>' inlineHtml += '<div class="col-xs-3 heading1"></div>' inlineHtml += '</div>'; inlineHtml += '</div>'; return inlineHtml } /* * PURPOSE : BUTTON TO ADD NEW VEHICLE TO THE TABLE * PARAMS : * RETURNS : INLINEHTML * NOTES : */ function franchiseeAddFleet() { var inlineHtml = '<div class="form-group container company_name_section">'; inlineHtml += '<div class="row">'; inlineHtml += '<div class="col-xs-3 heading1"></div>' inlineHtml += '<div class="col-xs-6 heading1"><input type="button" value="Add New Fleet" class="form-control btn btn-primary" id="addFleet" style="background-color: #287587;"/></div>' inlineHtml += '<div class="col-xs-3 heading1"></div>' inlineHtml += '</div>'; inlineHtml += '</div>'; return inlineHtml } /* * PURPOSE : BUTTON TO REDIRECT PAGE TO FIRST MILE SUBURB SELECTION * PARAMS : * RETURNS : INLINEHTML * NOTES : */ function franchiseeAddEditFirstMile() { var inlineHtml = '<div class="form-group container company_name_section">'; inlineHtml += '<div class="row">'; inlineHtml += '<div class="col-xs-3 heading1"></div>' inlineHtml += '<div class="col-xs-6 heading1"><input type="button" value="Add/Edit First-Mile Suburbs" class="form-control btn btn-primary" id="firstMile" style="background-color: #287587;"/></div>' inlineHtml += '<div class="col-xs-3 heading1"></div>' inlineHtml += '</div>'; inlineHtml += '</div>'; return inlineHtml } /* * PURPOSE : BUTTON TO REDIRECT PAGE TO LAST MILE SUBURB SELECTION * PARAMS : * RETURNS : INLINEHTML * NOTES : */ function franchiseeAddEditLastMile() { var inlineHtml = '<div class="form-group container company_name_section">'; inlineHtml += '<div class="row">'; inlineHtml += '<div class="col-xs-3 heading1"></div>' inlineHtml += '<div class="col-xs-6 heading1"><input type="button" value="Add/Edit Last-Mile Suburbs" class="form-control btn btn-primary" id="lastMile" style="background-color: #287587;"/></div>' inlineHtml += '<div class="col-xs-3 heading1"></div>' inlineHtml += '</div>'; inlineHtml += '</div>'; return inlineHtml } /* * PURPOSE : Autogenerates function contract comments * PARAMS : functio - * RETURNS : - * NOTES : */ function franchiseeOperatorDetails(zee, resultSetOperators) { var operatorID = ''; var operatorName = ''; var operatorPhone = ''; var operatorEmail = ''; var operatorEmploymentType = ''; var operatorRole = ''; var operatorMobileDev = ''; var operatorDDS = ''; var operatorPrimaryOperator = ''; var inlineHtml = '<div class="form-group container">'; inlineHtml += '<div class="row">'; inlineHtml += '<div class="col-xs-12 heading1"><h4><span class="label label-default col-xs-12" style="background-color: #103D39;">SERVICE NETWORK</span></h4></div>'; inlineHtml += '</div>'; inlineHtml += '</div>'; var directionsPanel_html = ''; var print_section = ''; //show the directionsPanel only if one zee selected directionsPanel_html += '<div class="col-sm-6 " id="directionsPanel" style="height:500px; overflow:auto"></div>'; print_section += '</br><div class="row print_section hide"><div class="col-xs-10"></div><div class="col-xs-2"><input type="button" class="btn btn-info" id="printDirections" value="PRINT DIRECTIONS" style="width: 100%;"/></div></div></div>'; inlineHtml += '</br>'; inlineHtml += '<div class="container map_section "><div class="row">'; inlineHtml += '<div class="col-sm-12" id="map" style="height: 500px"><div id="loader"><img src="https://1048144.app.netsuite.com/core/media/media.nl?id=2089999&c=1048144&h=e0aef405c22b65dfe546" alt="loader" /></div></div>'; inlineHtml += '<div id="legend">'; inlineHtml += '<div class="hide legend_icons" style="background-color: rgb(255, 255, 255);box-shadow: rgba(0, 0, 0, 0.3) 0px 1px 4px -1px;border-radius: 2px;left: 0px;margin-left: 5px;padding: 3px;"><div><svg height="23" width="32"><path d="M12 2C8.13 2 5 5.13 5 9c0 5.25 7 13 7 13s7-7.75 7-13c0-3.87-3.13-7-7-7z" stroke="black" fill="#575756"/></svg><span style="font-family: sans-serif;">Non Customer Location</span></div><div><svg height="23" width="32"><path d="M12 2C8.13 2 5 5.13 5 9c0 5.25 7 13 7 13s7-7.75 7-13c0-3.87-3.13-7-7-7z" stroke="black" fill="#008675"/></svg><span style="font-family: sans-serif;">Customer Location</span></div>'; for (i = 0; i < 1; i++) { inlineHtml += '<div><svg height="15" width="32"><line x1="2" y1="10" x2="25" y2="10" style="stroke:' + color_array[i] + ';stroke-width:2" /></svg><span style="font-family: sans-serif;">' + franchiseeName + '</span></div>'; } inlineHtml += '</div>'; inlineHtml += '<div style="background-color: rgb(255, 255, 255);box-shadow: rgba(0, 0, 0, 0.3) 0px 1px 4px -1px;border-radius: 2px;left: 0px;margin-left: 5px;padding: 3px;"><input class="form-control" type="textarea" placeholder="Territory" id="zee_territory"/></div>'; inlineHtml += '</div>'; // inlineHtml += directionsPanel_html; inlineHtml += '</div>'; inlineHtml += print_section; inlineHtml += franchiseeServiceNetwork(); inlineHtml += '<div class="form-group container">'; inlineHtml += '<div class="row">'; inlineHtml += '<div class="col-xs-12 heading1"><h4><span class="label label-default col-xs-12" style="background-color: #103D39;">OPERATOR DETAILS</span></h4></div>'; inlineHtml += '</div>'; inlineHtml += '</div>'; inlineHtml += '<div class="form-group container row_operator_details hide">' inlineHtml += '<div class="row">'; inlineHtml += '<input id="operatorInternalId" value="" type="hidden"/>' inlineHtml += '<div class="col-xs-3 operatorName_section"><div class="input-group"><span class="input-group-addon">Name <span class="mandatory">*</span></span><input id="operatorName" class="form-control operatorName" /></div></div>'; inlineHtml += '<div class="col-xs-3 operatorEmail_section"><div class="input-group"><span class="input-group-addon">EMAIL <span class="mandatory">*</span></span><input id="operatorEmail" class="form-control operatorEmail" /></div></div>'; inlineHtml += '<div class="col-xs-3 operatorMobile_section"><div class="input-group"><span class="input-group-addon">MOBILE NO. <span class="mandatory">*</span></span><input id="operatorMobile" class="form-control operatorMobile" /></div></div>'; inlineHtml += '<div class="col-xs-3"><div class="input-group"><span class="input-group-addon">MOBILE DEV </span><select id="operatorMobileDev" class="form-control operatorMobileDev" >'; /* iOS 1 Android 2 Other 5 */ inlineHtml += '<option value=0></option><option value=1>iOS</option><option value=2>Android</option><option value=5>Other</option>'; inlineHtml += '</select></div></div>'; inlineHtml += '</div>'; inlineHtml += '</div>'; inlineHtml += '<div class="form-group container row_operatorRole hide">' inlineHtml += '<div class="row">'; /* Driver 2 Trolley/ Foot Courier 3 Franchisee 5 */ inlineHtml += '<div class="col-xs-3"><div class="input-group"><span class="input-group-addon">ROLE <span class="mandatory">*</span></span><select id="operatorRole" class="form-control operatorRole" >'; inlineHtml += '<option value=0></option><option value=2>Driver</option><option value=3>Trolley/ Foot Courier</option><option value=5>Franchisee</option>'; inlineHtml += '</select></div></div>'; /* Employee 1 Contractor 2 Franchise Owner 4 */ inlineHtml += '<div class="col-xs-3"><div class="input-group"><span class="input-group-addon">EMPLOYEMENT TYPE <span class="mandatory">*</span></span><select id="operatorEmploymentType" class="form-control operatorEmploymentType" >'; inlineHtml += '<option value=0></option><option value=1>Employee</option><option value=2>Contractor</option><option value=4>Franchise Owner</option>'; inlineHtml += '</select></div></div>'; /* Yes 1 No 2 */ inlineHtml += '<div class="col-xs-3"><div class="input-group"><span class="input-group-addon">PRIMARY OPERATOR <span class="mandatory">*</span></span><select id="operatorPrimaryOperator" class="form-control operatorPrimaryOperator" >'; inlineHtml += '<option value=0></option><option value=1>Yes</option><option value=2>No</option>'; inlineHtml += '</select></div></div>'; inlineHtml += '<div class="col-xs-3"><div class="input-group"><span class="input-group-addon">CONTINGENCY DRIVER <span class="mandatory">*</span></span><select id="operatorContingency" class="form-control operatorContingency" >'; inlineHtml += '<option value=0></option><option value=1>Yes</option><option value=2>No</option>'; inlineHtml += '</select></div></div>'; inlineHtml += '</div>'; inlineHtml += '</div>'; inlineHtml += '<div class="form-group container saveoperator_section hide">'; inlineHtml += '<div class="row">'; inlineHtml += '<div class="col-xs-2 "></div>'; inlineHtml += '<div class="col-xs-4 reviewaddress"><input type="button" value="SAVE OPERATOR" class="form-control btn btn-success" id="saveOperator" /></div>'; inlineHtml += '<div class="col-xs-4 cancel"><input type="button" value="CANCEL" class="form-control btn btn-secondary" id="cancel" /></div>'; inlineHtml += '<div class="col-xs-2 "></div>'; inlineHtml += '</div>'; inlineHtml += '</div>'; inlineHtml += '<div class="form-group container" style="width: 100% !important;">'; inlineHtml += '<div class="row">'; inlineHtml += '<style>table#operatorTable {color: #103D39 !important; font-size: 12px;text-align: center;border: none;}.dataTables_wrapper {font-size: 14px;}table#operatorTable th{text-align: center;} .bolded{font-weight: bold;}</style>'; inlineHtml += '<table id="operatorTable" class="table table-responsive table-striped operatorTable tablesorter" style="width: 100%;border: 1px solid #103d39;">'; inlineHtml += '<thead style="color: white;background-color: #379E8F;font-weight: bold;">'; inlineHtml += '<tr class="text-center">'; inlineHtml += '<td>LINK</td>' inlineHtml += '<td>NAME</td>' inlineHtml += '<td class="col-xs-2">EMAIL</td>' inlineHtml += '<td>PHONE</td>' inlineHtml += '<td>ROLE</td>' inlineHtml += '<td>EMPLOYMENT TYPE</td>' inlineHtml += '<td>CONTINGENCY DRIVER</td>' inlineHtml += '<td>PRIMARY DRIVER</td>' inlineHtml += '<td>MOBILE DEVICE</td>' inlineHtml += '</tr>'; inlineHtml += '</thead>'; inlineHtml += '<tbody id="resultOperatorTable" class="">'; resultSetOperators.each(function (searchResultOperators) { operatorID = searchResultOperators.getValue('internalid'); operatorName = searchResultOperators.getValue('name'); operatorPhone = searchResultOperators.getValue( 'custrecord_operator_phone'); operatorEmail = searchResultOperators.getValue( 'custrecord_operator_email'); operatorEmploymentType = searchResultOperators.getText( 'custrecord_operator_employment'); var operatorEmploymentTypeID = searchResultOperators.getValue( 'custrecord_operator_employment'); operatorRole = searchResultOperators.getText( 'custrecord_operator_role'); var operatorRoleID = searchResultOperators.getValue( 'custrecord_operator_role'); operatorMobileDev = searchResultOperators.getText( 'custrecord_operator_mobdev_platform'); var operatorMobileDevID = searchResultOperators.getValue( 'custrecord_operator_mobdev_platform'); operatorDDS = searchResultOperators.getText( 'custrecord_dds_operator'); var operatorDDSID = searchResultOperators.getValue( 'custrecord_dds_operator'); operatorPrimaryOperator = searchResultOperators.getText( 'custrecord_primary_operator'); var operatorPrimaryOperatorID = searchResultOperators.getValue( 'custrecord_primary_operator'); log.debug({ title: 'operatorEmploymentType', details: operatorEmploymentType }) log.debug({ title: 'operatorEmploymentTypeID', details: operatorEmploymentTypeID }) log.debug({ title: 'operatorRole', details: operatorRole }) log.debug({ title: 'operatorRoleID', details: operatorRoleID }) log.debug({ title: 'operatorMobileDevID', details: operatorMobileDevID }) log.debug({ title: 'operatorDDS', details: operatorDDS }) log.debug({ title: 'operatorDDSID', details: operatorDDSID }) log.debug({ title: 'operatorPrimaryOperator', details: operatorPrimaryOperator }) log.debug({ title: 'operatorPrimaryOperatorID', details: operatorPrimaryOperatorID }) inlineHtml += '<tr>' inlineHtml += '<td><a data-id="' + operatorID + '" class="btn btn-md btn-primary editOperatorTable" data-changed="notchanged">EDIT</a> <a data-id="' + operatorID + '" class="btn btn-md btn-danger deleteOperatorTable" >DELETE</a></td>' inlineHtml += '<td><input value="' + operatorName + '" readonly class="form-control operatorNameTable" /></td>' inlineHtml += '<td><input value="' + operatorEmail + '" readonly class="form-control operatorEmailTable" /></td>' inlineHtml += '<td><input value="' + operatorPhone + '" readonly class="form-control operatorPhoneTable" /></td>' inlineHtml += '<td><input value="' + operatorRole + '" readonly class="form-control operatorRoleTable" /><input id="" class="operatorRoleID" value="' + operatorRoleID + '" type="hidden"/></td>' inlineHtml += '<td><input value="' + operatorEmploymentType + '" readonly class="form-control operatorEmploymentTypeTable"/><input id="" class="operatorEmploymentTypeID" value="' + operatorEmploymentTypeID + '" type="hidden"/></td>' inlineHtml += '<td><input value="' + operatorDDS + '" readonly class="form-control operatorDDSTable" /><input id="" class="operatorDDSID" value="' + operatorDDSID + '" type="hidden"/></td>' inlineHtml += '<td><input value="' + operatorPrimaryOperator + '" readonly class="form-control operatorPrimaryOperatorTable" /><input id="" class="operatorPrimaryOperatorID" value="' + operatorPrimaryOperatorID + '" type="hidden"/></td>' inlineHtml += '<td><input value="' + operatorMobileDev + '" readonly class="form-control operatorMobileDevTable" /><input id="" class="operatorMobileDevID" value="' + operatorMobileDevID + '" type="hidden"/></td>' inlineHtml += '</tr>'; return true; }); inlineHtml += '</tbody></table>'; inlineHtml += '</div>'; inlineHtml += '</div>'; inlineHtml += franchiseeAddOperator() return inlineHtml; } function franchiseeFleetDetails(zee, resultSetOperators) { //NetSuite Search: Franchisee - Operator Vehicle Details var searchZeeVehicles = search.load({ id: 'customsearch1912', type: 'customrecord_vehicle' }); if (!isNullorEmpty(zee)) { searchZeeVehicles.filters.push(search.createFilter({ name: 'internalid', join: 'CUSTRECORD_VEHICLE_FRANCHISEE', operator: search.Operator.IS, values: zee })); } var resultSetZeeVehicles = searchZeeVehicles.run(); var inlineHtml = '<div class="form-group container">'; inlineHtml += '<div class="row">'; inlineHtml += '<div class="col-xs-12 heading1"><h4><span class="label label-default col-xs-12" style="background-color: #103D39;">FLEET DETAILS</span></h4></div>'; inlineHtml += '</div>'; inlineHtml += '</div>'; inlineHtml += '<div class="form-group container row_fleet_details hide">' inlineHtml += '<div class="row">'; inlineHtml += '<input id="vehicleInternalId" value="" type="hidden"/>' inlineHtml += '<div class="col-xs-6 vehicleRego_section"><div class="input-group"><span class="input-group-addon">REGISTRATION <span class="mandatory">*</span></span><input id="vehicleRegistration" class="form-control vehicleRegistration" /></div></div>'; inlineHtml += '</div>'; inlineHtml += '</div>'; inlineHtml += '<div class="form-group container row_fleet_details2 hide">' inlineHtml += '<div class="row">'; inlineHtml += '<div class="col-xs-3 operatorEmail_section"><div class="input-group"><span class="input-group-addon">MODEL <span class="mandatory">*</span></span><input id="vehicleModel" class="form-control vehicleModel" /></div></div>'; inlineHtml += '<div class="col-xs-3 operatorMobile_section"><div class="input-group"><span class="input-group-addon">MAKE<span class="mandatory">*</span></span><input id="vehicleMake" class="form-control vehicleMake" /></div></div>'; inlineHtml += '<div class="col-xs-3 operatorMobile_section"><div class="input-group"><span class="input-group-addon">COLOR <span class="mandatory">*</span></span><input id="vehicleColor" class="form-control vehicleColor" /></div></div>'; inlineHtml += '<div class="col-xs-3 operatorMobile_section"><div class="input-group"><span class="input-group-addon">YEAR <span class="mandatory">*</span></span><input id="vehicleYear" class="form-control vehicleYear" /></div></div>'; inlineHtml += '</div>'; inlineHtml += '</div>'; inlineHtml += '<div class="form-group container row_fleet_details3 hide">' inlineHtml += '<div class="row">'; inlineHtml += '<div class="col-xs-3"><div class="input-group"><span class="input-group-addon">SIGNAGE <span class="mandatory">*</span></span><select id="vehicleSignage" class="form-control vehicleSignage" >'; inlineHtml += '<option value=0></option><option value=1>Yes</option><option value=2>No</option>'; inlineHtml += '</select></div></div>'; inlineHtml += '<div class="col-xs-3"><div class="input-group"><span class="input-group-addon">CARGO CAGE <span class="mandatory">*</span></span><select id="vehicleCargoCage" class="form-control vehicleCargoCage" >'; inlineHtml += '<option value=0></option><option value=1>Yes</option><option value=2>No</option>'; inlineHtml += '</select></div></div>'; /* Employee 1 Contractor 2 Franchise Owner 4 */ inlineHtml += '<div class="col-xs-3"><div class="input-group"><span class="input-group-addon">ONWER <span class="mandatory">*</span></span><select id="vehicleOwner" class="form-control vehicleOwner" >'; inlineHtml += '<option value=0></option><option value=2>Driver</option><option value=3>Trolley/ Foot Courier</option><option value=5>Franchisee</option>'; inlineHtml += '</select></div></div>'; inlineHtml += '<div class="col-xs-3"><div class="input-group"><span class="input-group-addon">OPERATOR <span class="mandatory">*</span></span><select id="vehicleOperator" class="form-control vehicleOperator" ><option value=0></option>'; resultSetOperators.each(function (searchResultOperators) { operatorID = searchResultOperators.getValue('internalid'); operatorName = searchResultOperators.getValue('name'); inlineHtml += '<option value=' + operatorID + '>' + operatorName + '</option>'; return true; }); inlineHtml += '</select></div></div>'; inlineHtml += '</div>'; inlineHtml += '</div>'; inlineHtml += '<div class="form-group container savefleet_section hide">'; inlineHtml += '<div class="row">'; inlineHtml += '<div class="col-xs-2 "></div>'; inlineHtml += '<div class="col-xs-4 reviewaddress"><input type="button" value="SAVE FLEET" class="form-control btn btn-success" id="saveVehicle" /></div>'; inlineHtml += '<div class="col-xs-4 cancel"><input type="button" value="CANCEL" class="form-control btn btn-secondary" id="cancel" /></div>'; inlineHtml += '<div class="col-xs-2 "></div>'; inlineHtml += '</div>'; inlineHtml += '</div>'; inlineHtml += '<div class="form-group container" style="width: 100% !important;">'; inlineHtml += '<div class="row">'; inlineHtml += '<style>table#fleetTable {color: #103D39 !important; font-size: 12px;text-align: center;border: none;}.dataTables_wrapper {font-size: 14px;}table#fleetTable th{text-align: center;} .bolded{font-weight: bold;}</style>'; inlineHtml += '<table id="fleetTable" class="table table-responsive table-striped fleetTable tablesorter" style="width: 100%;border: 1px solid #103d39;">'; inlineHtml += '<thead style="color: white;background-color: #379E8F;font-weight: bold;">'; inlineHtml += '<tr class="text-center">'; inlineHtml += '<td>LINK</td>' inlineHtml += '<td>REGISTRATION</td>' inlineHtml += '<td>MODEL</td>' inlineHtml += '<td>MAKE</td>' inlineHtml += '<td>COLOR</td>' inlineHtml += '<td>YEAR</td>' inlineHtml += '<td>SIGNAGE</td>' inlineHtml += '<td>CARGO CAGE</td>' inlineHtml += '<td>OWNER</td>' inlineHtml += '<td>OPERATOR NAME</td>' inlineHtml += '</tr>'; inlineHtml += '</thead>'; inlineHtml += '<tbody id="resultOperatorTable" class="">'; resultSetZeeVehicles.each(function (searchResultZeeVehicles) { vehicleID = searchResultZeeVehicles.getValue('internalid'); vehicleRegistration = searchResultZeeVehicles.getValue('name'); vehicleModel = searchResultZeeVehicles.getValue( 'custrecord_vehicle_model_text'); vehicleMake = searchResultZeeVehicles.getValue( 'custrecord_vehicle_make'); vehicleYear = searchResultZeeVehicles.getValue( 'custrecord_vehicle_year'); vehicleColor = searchResultZeeVehicles.getValue( 'custrecord_vehicle_colour'); vehicleSignage = searchResultZeeVehicles.getValue( 'custrecord_vehicle_signage'); vehicleOwnerID = searchResultZeeVehicles.getValue( 'custrecord_vehicle_owner'); vehicleOwner = searchResultZeeVehicles.getText( 'custrecord_vehicle_owner'); vehicleCargoCageID = searchResultZeeVehicles.getValue( 'custrecord_cargo_cage'); vehicleCargoCage = searchResultZeeVehicles.getText( 'custrecord_cargo_cage'); vehicleOperatorInternalID = searchResultZeeVehicles.getValue({ name: "internalid", join: "CUSTRECORD_OPERATOR_VEHICLE" }); vehicleOperatorName = searchResultZeeVehicles.getValue({ name: "custrecord_operator_givennames", join: "CUSTRECORD_OPERATOR_VEHICLE" }); inlineHtml += '<tr>' inlineHtml += '<td><a data-id="' + vehicleID + '" class=" btn btn-md btn-primary editFleetTable" data-changed="notchanged">EDIT</a> <a data-id="' + vehicleID + '" class=" btn btn-md btn-danger deleteFleetTable" >DELETE</a></td>' inlineHtml += '<td><input value="' + vehicleRegistration + '" readonly class="form-control vehicleRegistrationTable"/></td>' inlineHtml += '<td><input value="' + vehicleModel + '" readonly class="form-control vehicleModelTable"/></td>' inlineHtml += '<td><input value="' + vehicleMake + '" readonly class="form-control vehicleMakeTable"/></td>' inlineHtml += '<td><input value="' + vehicleColor + '" readonly class="form-control vehicleColorTable"/></td>' inlineHtml += '<td><input value="' + vehicleYear + '" readonly class="form-control vehicleYearTable"/></td>' inlineHtml += '<td><input value="' + vehicleSignage + '" readonly class="form-control vehicleSignageTable"/><input id="vehicleSignageID" class="vehicleSignageID" value="' + vehicleSignage + '" type="hidden"/></td>' inlineHtml += '<td><input value="' + vehicleCargoCage + '" readonly class="form-control vehicleCargoCageTable"/><input id="vehicleCargoCageID" class="vehicleCargoCageID" value="' + vehicleCargoCageID + '" type="hidden"/></td>' inlineHtml += '<td><input value="' + vehicleOwner + '" readonly class="form-control vehicleOwnerTable"/><input id="vehicleOwnerID" class="vehicleOwnerID" value="' + vehicleOwnerID + '" type="hidden"/></td>' inlineHtml += '<td><input value="' + vehicleOperatorName + '" readonly class="form-control vehicleOperatorNameTable"/><input id="vehicleOperatorID" class="vehicleOperatorID" value="' + vehicleOperatorInternalID + '" type="hidden"/></td>' inlineHtml += '</tr>'; return true; }); inlineHtml += '</tbody></table>'; inlineHtml += '</div>'; inlineHtml += '</div>'; inlineHtml += franchiseeAddFleet() return inlineHtml; } function franchiseeBreachDetails() { var inlineHtml = '<div class="form-group container">'; inlineHtml += '<div class="row">'; inlineHtml += '<div class="col-xs-12 heading1"><h4><span class="label label-default col-xs-12" style="background-color: #103D39;">BREACH DETAILS</span></h4></div>'; inlineHtml += '</div>'; inlineHtml += '</div>'; return inlineHtml; } function franchiseeTerminationDetails() { var inlineHtml = '<div class="form-group container">'; inlineHtml += '<div class="row">'; inlineHtml += '<div class="col-xs-12 heading1"><h4><span class="label label-default col-xs-12" style="background-color: #103D39;">TERMINATION DETAILS</span></h4></div>'; inlineHtml += '</div>'; inlineHtml += '</div>'; return inlineHtml; } function addressContactsSection(resultSetAddresses) { var inlineQty = '<div class="form-group container contacts_section" style="font-size: xx-small;">'; inlineQty += '<div class="row">'; inlineQty += '<div class="col-xs-12 address_div">'; inlineQty += '<table border="0" cellpadding="15" id="address" class="table table-responsive table-striped address tablesorter" cellspacing="0" style="width: 100%;border: 1px solid #103d39;font-size: 12px;text-align: center;"><thead style="color: white;background-color: #379E8F;"><tr><th style="vertical-align: middle;text-align: center;">LINK</th><th style="vertical-align: middle;text-align: center;">ID</th><th style="vertical-align: middle;text-align: center;"><b>SUIT/LEVEL/UNIT </b></th><th style="vertical-align: middle;text-align: center;"><b>STREET NO. & NAME </b></th><th style="vertical-align: middle;text-align: center;"><b>SUBURB </b></th><th style="vertical-align: middle;text-align: center;"><b>STATE </b></th><th style="vertical-align: middle;text-align: center;"><b>POSTCODE </b></th></tr></thead><tbody>'; if (!isNullorEmpty(resultSetAddresses)) { //console.log("addresses work"); resultSetAddresses.each(function (searchResultAddresses) { var id = searchResultAddresses.getValue({ name: 'addressinternalid', join: 'Address' }); var addr1 = searchResultAddresses.getValue({ name: 'address1', join: 'Address' }); var addr2 = searchResultAddresses.getValue({ name: 'address2', join: 'Address' }); var city = searchResultAddresses.getValue({ name: 'city', join: 'Address' }); var state = searchResultAddresses.getValue({ name: 'state', join: 'Address' }); var zip = searchResultAddresses.getValue({ name: 'zipcode', join: 'Address' }); var lat = searchResultAddresses.getValue({ name: 'custrecord_address_lat', join: 'Address' }); var lon = searchResultAddresses.getValue({ name: 'custrecord_address_lon', join: 'Address' }); var default_shipping = searchResultAddresses.getValue({ name: 'isdefaultshipping', join: 'Address' }); var default_billing = searchResultAddresses.getValue({ name: 'isdefaultbilling', join: 'Address' }); var default_residential = searchResultAddresses.getValue({ name: 'isresidential', join: 'Address' }); if (isNullorEmpty(addr1) && isNullorEmpty(addr2)) { var full_address = city + ', ' + state + ' - ' + zip; } else if (isNullorEmpty(addr1) && !isNullorEmpty(addr2)) { var full_address = addr2 + ', ' + city + ', ' + state + ' - ' + zip; } else if (!isNullorEmpty(addr1) && isNullorEmpty(addr2)) { var full_address = addr1 + ', ' + city + ', ' + state + ' - ' + zip; } else { var full_address = addr1 + ', ' + addr2 + ', ' + city + ', ' + state + ' - ' + zip; } if (default_shipping == 'T') { shipping_state = state; } inlineQty += '<tr><td><a data-id="' + id + '" class="btn btn-md btn-primary editAddressTable" data-changed="notchanged">EDIT</a> <a data-id="' + id + '" class="btn btn-md btn-danger deleteAddressTable" >DELETE</a></td>'; inlineQty += '<td><input value="' + id + '" readonly class="form-control id"/></td>'; inlineQty += '<td><input value="' + addr1 + '" readonly class="form-control addr1Table"/></td>'; inlineQty += '<td><input value="' + addr2 + '" readonly class="form-control addr2Table"/></td>'; inlineQty += '<td><input value="' + city + '" readonly class="form-control cityTable"/></td>'; inlineQty += '<td><input value="' + state + '" readonly class="form-control stateTable"/></td>'; inlineQty += '<td><input value="' + zip + '" readonly class="form-control zipTable"/></td>'; return true; }); } inlineQty += '</tbody></table>'; inlineQty += '</div>'; inlineQty += '</div>'; inlineQty += '</div>'; inlineQty += '<div class="form-group container reviewaddress_section">'; inlineQty += '<div class="row">'; inlineQty += '<div class="col-xs-3 "></div>'; inlineQty += '<div class="col-xs-6 reviewaddress"><input type="button" value="ADD ADDRESSES" class="form-control btn btn-primary" style="background-color: #287587;" id="reviewaddress" /></div>'; inlineQty += '<div class="col-xs-3 "></div>'; inlineQty += '</div>'; inlineQty += '</div>'; return inlineQty; } function isNullorEmpty(strVal) { return (strVal == null || strVal == '' || strVal == 'null' || strVal == undefined || strVal == 'undefined' || strVal == '- None -' || strVal == '0'); } function isNullorEmptyExcZero(strVal) { return (strVal == null || strVal == '' || strVal == 'null' || strVal == undefined || strVal == 'undefined' || strVal == '- None -'); } /** * The header showing that the results are loading. * @returns {String} `inlineQty` */ function loadingSection() { var inlineHtml = '<div id="loading_section" class="form-group container loading_section " style="text-align:center">'; inlineHtml += '<div class="row">'; inlineHtml += '<div class="col-xs-12 loading_div">'; inlineHtml += '<h1>Loading...</h1>'; inlineHtml += '</div></div></div>'; return inlineHtml; } function getDateToday() { var date = new Date(); log.debug({ title: 'date', details: date }) format.format({ value: date, type: format.Type.DATE, timezone: format.Timezone.AUSTRALIA_SYDNEY }) return date; } function getDate(inputDate) { var date = new Date(inputDate); format.format({ value: date, type: format.Type.DATE, timezone: format.Timezone.AUSTRALIA_SYDNEY }) return date; } function getDay() { var date = new Date(); if (date.getHours() > 6) { date.setDate(date.getDate() + 1); } var day = date.getDay(); return day; } /** * Used to pass the values of `date_from` and `date_to` between the scripts and to Netsuite for the records and the search. * @param {String} date_iso "2020-06-01" * @returns {String} date_netsuite "1/6/2020" */ function dateISOToNetsuite(date_iso) { var date_netsuite = ''; if (!isNullorEmpty(date_iso)) { var date_utc = new Date(date_iso); // var date_netsuite = nlapiDateToString(date_utc); var date_netsuite = format.format({ value: date_utc, type: format.Type.DATE }); } return date_netsuite; } return { onRequest: onRequest }; });
/** *@NApiVersion 2.1 *@NScriptType Restlet *@author Shaun York <s@sry.dev> */ define(['N/log', 'N/search', 'N/record'], function (Log, Srh, Rec) { // TODO: Set this array via script parameter const NONE_BACKFLUSH_WORKCENTERS = ['16469', '16489'] const CREATE_WORKORDER_COMPLETION = 'mk' const DELETE_WORKORDER_COMPLETION = 'rm' function log_ss_debug(title, msg, context) { const debug_options = { title, details: `MSG: [${msg}]\n\n${JSON.stringify(context)}` } Log.debug(debug_options) } function isJson(jdoc) { try { return JSON.parse(jdoc) } catch (error) { log_ss_debug('isJson failed to parse', error.message, jdoc) } } class Completion { constructor(props) { this.workordercompletion_id = props.workordercompletion_id this.operation_sequence = props.operation_sequence this.mfgoptask_id = props.mfgoptask_id this.workorder_id = props.workorder_id this.completedQty = props.completedQty this.location_id = props.location_id this.operator_id = props.operator_id this.worktime_id = props.worktime_id this.machine_id = props.machine_id this.workcenter = props.workcenter this.scrapQty = props.scrapQty this.item_id = props.item_id this.action = props.action this.id = props.id this.errors = [] this.bin_lines = [] this.completion = null this.last_workcenter = null this.operation_is_complete = false this.last_nwo_workcenter = false this.component_invtdets_required = false this.transform_parameters = { fromType: Rec.Type.WORK_ORDER, fromId: props.workorder_id, toType: Rec.Type.WORK_ORDER_COMPLETION, isDynamic: true } this.machine_operator = { fieldId: 'custbody_operator', value: props.operator_id, ignoreFieldChange: false } this.start_operation_sequence = { fieldId: 'startoperation', text: props.operation_sequence, ignoreFieldChange: false } this.end_operation_sequence = { fieldId: 'endoperation', text: props.operation_sequence, ignoreFieldChange: false } this.quantity = { fieldId: 'completedquantity', value: props.completedQty, ignoreFieldChange: false } this.scrap = { fieldId: 'scrapquantity', value: props.scrapQty, ignoreFieldChange: false } this.is_back_flush = { fieldId: 'isbackflush', value: true, ignoreFieldChange: false } this.current_state = Srh.lookupFields({ type: 'manufacturingoperationtask', id: props.mfgoptask_id, columns: [ 'predecessor.internalid', 'predecessor.completedquantity', 'completedquantity', 'predecessor.inputquantity', 'inputquantity' ] }) this.nwo = Rec.load({ type: 'workorder', id: props.workorder_id }) this.op = Rec.load({ type: 'manufacturingoperationtask', id: props.mfgoptask_id }) } causedErrors() { return Boolean(this.errors.length) } props() { return { workordercompletion_id: this.workordercompletion_id, operation_sequence: this.operation_sequence, mfgoptask_id: this.mfgoptask_id, workorder_id: this.workorder_id, completedQty: this.completedQty, location_id: this.location_id, operator_id: this.operator_id, worktime_id: this.worktime_id, machine_id: this.machine_id, workcenter: this.workcenter, scrapQty: this.scrapQty, item_id: this.item_id, action: this.action, id: this.id } } init() { try { this.completion = Rec.transform(this.transform_parameters) this.completion.setValue(this.machine_operator) this.completion.setText(this.start_operation_sequence) this.completion.setText(this.end_operation_sequence) this.completion.setValue(this.quantity) if (parseFloat(this.scrapQty) > 0) { this.completion.setValue(this.scrap) const cqty = parseFloat(this.completedQty | 0) const sqty = parseFloat(this.scrapQty | 0) this.completedQty = (cqty + sqty).toString() } } catch (error) { this.errors.push(`Completion.init() ERROR: [> ${error.message} <]`) log_ss_debug('Completion failed on method', 'Completion.init()', { ...this.props(), ERROR: error.message }) } } isBackFlush() { if (this.completion !== null) { try { if (NONE_BACKFLUSH_WORKCENTERS.indexOf(this.workcenter) === -1) { this.completion.setValue({ fieldId: 'isbackflush', value: true, ignoreFieldChange: false }) } } catch (error) { this.errors.push(`Completion.isBackFlush() ERROR: [> ${error.message} <]`) log_ss_debug('isBackflush', 'Completion.isBackFlush()', { ...this.props(), ERROR: error.message }) } } else { this.errors.push('Missing completion...') log_ss_debug('isBackflush', 'Missing completion...', '') } } isValid() { try { //TODO assert predicate const wo = this.op.getValue({ fieldId: 'workorder' }) const id = this.op.getValue({ fieldId: 'id' }) if ( this.workorder_id === wo.toString() && this.mfgoptask_id === id.toString() ) { this.last_workcenter = this.op.getValue({ fieldId: 'manufacturingworkcenter' }) return true } else { return false } } catch (error) { this.errors.push(`Completion.isValid() ERROR: [> ${error.message} <]`) log_ss_debug('Completion failed on method', 'Completion.isValid()', { ...this.props(), ERROR: error.message }) return false } } canComplete() { const qty = parseFloat(this.completedQty | 0) const operation_required_qty = parseFloat(this.current_state['inputquantity'] | 0) const operation_completed_qty = parseFloat(this.current_state['completedquantity'] | 0) const total_completed = operation_completed_qty + qty this.operation_is_complete = total_completed >= operation_required_qty if (Array.isArray(this.current_state['predecessor.internalid'])) { if (this.current_state['predecessor.internalid'].length === 0) { log_ss_debug('canComplete', ' first mfg operation task', 'Yes') return true } } const previous_operation_completed_qty = parseFloat(this.current_state['predecessor.completedquantity'] | 0) const previous_operation_required_qty = parseFloat(this.current_state['predecessor.inputquantity'] | 0) const avaliable_qty = previous_operation_completed_qty - operation_completed_qty const remaining_qty = operation_required_qty - operation_completed_qty if (qty <= avaliable_qty) { return true } else { this.errors.push(`Completion.canComplete() ERROR: [> ${qty} less than or equal to ${avaliable_qty} <]`) log_ss_debug('Completion failed on method', 'Completion.canComplete()', { ...this.props(), qty, previous_operation_completed_qty, operation_completed_qty, previous_operation_required_qty, operation_required_qty, avaliable_qty, remaining_qty }) return false } } nwoIsComplete() { try { this.nwo.setValue({ fieldId: 'status', value: 'Built', ignoreFieldChange: false }) this.nwo.save() } catch (error) { this.errors.push(`Completion.nwoIsComplete() ERROR: [> ${error.message} <]`) log_ss_debug('Changing NWO status failed', error.message, { ...this.props(), ERROR: error.message }) } } componentInvtDets() { try { const componentLines = this.completion.getLineCount({ sublistId: 'component' }) for (var line = 0, l = componentLines; line !== l; line++) { const c_line = { sublistId: 'component', fieldId: 'componentinventorydetailreq', line } const line_requires_component_invt_dets = (this.completion.getSublistValue(c_line) === 'T') if (line_requires_component_invt_dets) { this.component_invtdets_required = true this.bin_lines.push({ line, componentinventorydetailreq: this.completion.getSublistValue({ ...c_line, fieldId: 'componentinventorydetailreq' }), operationsequencenumber: this.completion.getSublistValue({ ...c_line, fieldId: 'operationsequencenumber' }), itemlocationbinlist: this.completion.getSublistValue({ ...c_line, fieldId: 'itemlocationbinlist' }), units: this.completion.getSublistValue({ ...c_line, fieldId: 'units' }), item: this.completion.getSublistValue({ ...c_line, fieldId: 'item' }) }) } } } catch (error) { this.errors.push(`Completion.componentInvtDets() ERROR: [> ${error.message} <]`) log_ss_debug('Completion failed on method', 'Completion.componentInvtDets()', { ...this.props(), ERROR: error.message }) } } commitComponentInvtDets() { this.bin_lines.forEach(({ line, units, operationsequencenumber }) => { try { if (operationsequencenumber.toString() === this.operation_sequence) { const line_qty = this.completedQty * units this.completion.selectLine({ sublistId: 'component', line }) this.completion.setCurrentSublistValue({ sublistId: 'component', fieldId: 'quantity', value: line_qty }) const invtdets = this.completion.getCurrentSublistSubrecord({ sublistId: 'component', fieldId: 'componentinventorydetail' }) invtdets.selectLine({ sublistId: 'inventoryassignment', line }) invtdets.setCurrentSublistValue({ sublistId: 'inventoryassignment', fieldId: 'quantity', value: this.completedQty }) invtdets.commitLine({ sublistId: 'inventoryassignment' }) this.completion.commitLine({ sublistId: 'component' }) } else { log_ss_debug('commitComponentInvtDets', 'Operation sequence on component line doesn\'t match this.operation_sequence...', '') } } catch (error) { this.errors.push(`Completion.commitComponentInvtDets() ERROR: [> ${error.message} <]`) log_ss_debug(`Completion failed on method', 'Completion.commitComponentInvtDets(line:${line})`, { ...this.props(), error }) } }) } isLastWorkCenter() { try { var ops = [] const line_count = this.nwo.getLineCount({ sublistId: 'item' }) for (var n = 0, l = line_count; n !== l; n++) { //was getSublistField ops.push(this.nwo.getSublistValue({ sublistId: 'item', fieldId: 'operationsequencenumber', line: n })) } const highest_operation_sequence_value = ops.sort().pop().toString() if (this.operation_sequence === highest_operation_sequence_value) { this.last_nwo_workcenter = true log_ss_debug('requiredInventoryDetails', 'requires woc InvtDetails', 'Yes') this.completion.setValue(this.is_back_flush) const inventory_detail = this.completion.getSubrecord({ fieldId: 'inventorydetail' }) inventory_detail.selectNewLine({ sublistId: 'inventoryassignment' }) inventory_detail.setCurrentSublistValue({ sublistId: 'inventoryassignment', fieldId: 'quantity', value: this.completedQty - this.scrapQty }) inventory_detail.commitLine({ sublistId: 'inventoryassignment' }) return true } else { return false } } catch (error) { this.errors.push(`Completion.isLastWorkCenter() ERROR: [> ${error.message} <]`) log_ss_debug('Completion failed on method', 'Completion.requiredInventoryDetails()', { ...this.props(), ERROR: error.message }) } } save() { try { const completion_id = this.completion.save() this.workordercompletion_id = completion_id.toString() log_ss_debug('save', 'Saved completion', this.workordercompletion_id) if (this.operation_is_complete) { log_ss_debug('save', 'This Mfg Operation Task is complete...', this.mfgoptask_id) } } catch (error) { this.errors.push(`Completion.save() ERROR: [> ${error.message} <]`) log_ss_debug('Completion failed on method', 'Completion.save()', { ...this.props(), ERROR: error.message }) } } delete() { log_ss_debug('delete', 'Deleting completion', this.props()) try { Rec.delete({ type: Rec.Type.WORK_ORDER_COMPLETION, id: this.workordercompletion_id }) } catch (error) { this.errors.push(`Completion.delete() ERROR: [> ${error.message} <]`) log_ss_debug('Completion failed on method', 'Completion.delete()', { ...this.props(), ERROR: error.message }) } } } function get(args) { try { const completion = new Completion(args) switch (completion.action) { case CREATE_WORKORDER_COMPLETION: { // To be generated completion.init() completion.componentInvtDets() completion.isBackFlush() const is_valid_completion_operation = completion.isValid() const can_preform_completion = completion.canComplete() if (completion.component_invtdets_required) { completion.commitComponentInvtDets() } completion.isLastWorkCenter() if (completion.causedErrors()) { log_ss_debug('onGet', `Failed with ${completion.errors.length} errors...`, '') return JSON.stringify({ error: true, errors: completion.errors }) } else { log_ss_debug('onGet', 'Processing', completion.props()) } if (is_valid_completion_operation && can_preform_completion) { completion.save() if (completion.last_nwo_workcenter && completion.operation_is_complete) { completion.nwoIsComplete() } log_ss_debug('onGet', 'Created completion', completion.workordercompletion_id) return JSON.stringify(completion.props()) } break } case DELETE_WORKORDER_COMPLETION: { completion.delete() if (completion.causedErrors()) { log_ss_debug('onGet', `Failed with ${completion.errors.length} errors...`, '') return JSON.stringify({ error: true, errors: completion.errors }) } else { return JSON.stringify(completion.props()) } } default: throw Error('UNKNOWN_OR_MISSING_OPERATION_ACTION') } } catch (error) { log_ss_debug('onGet', error.name, error.message) return JSON.stringify({ error: true, message: error.message }) } } return { get } })
1,036
[{"tag": "EMAIL", "value": "s@sry.dev", "start": 68, "end": 77}]
true
1
/** *@NApiVersion 2.1 *@NScriptType Restlet *@author Shaun York <envkt@example.com> */ define(['N/log', 'N/search', 'N/record'], function (Log, Srh, Rec) { // TODO: Set this array via script parameter const NONE_BACKFLUSH_WORKCENTERS = ['16469', '16489'] const CREATE_WORKORDER_COMPLETION = 'mk' const DELETE_WORKORDER_COMPLETION = 'rm' function log_ss_debug(title, msg, context) { const debug_options = { title, details: `MSG: [${msg}]\n\n${JSON.stringify(context)}` } Log.debug(debug_options) } function isJson(jdoc) { try { return JSON.parse(jdoc) } catch (error) { log_ss_debug('isJson failed to parse', error.message, jdoc) } } class Completion { constructor(props) { this.workordercompletion_id = props.workordercompletion_id this.operation_sequence = props.operation_sequence this.mfgoptask_id = props.mfgoptask_id this.workorder_id = props.workorder_id this.completedQty = props.completedQty this.location_id = props.location_id this.operator_id = props.operator_id this.worktime_id = props.worktime_id this.machine_id = props.machine_id this.workcenter = props.workcenter this.scrapQty = props.scrapQty this.item_id = props.item_id this.action = props.action this.id = props.id this.errors = [] this.bin_lines = [] this.completion = null this.last_workcenter = null this.operation_is_complete = false this.last_nwo_workcenter = false this.component_invtdets_required = false this.transform_parameters = { fromType: Rec.Type.WORK_ORDER, fromId: props.workorder_id, toType: Rec.Type.WORK_ORDER_COMPLETION, isDynamic: true } this.machine_operator = { fieldId: 'custbody_operator', value: props.operator_id, ignoreFieldChange: false } this.start_operation_sequence = { fieldId: 'startoperation', text: props.operation_sequence, ignoreFieldChange: false } this.end_operation_sequence = { fieldId: 'endoperation', text: props.operation_sequence, ignoreFieldChange: false } this.quantity = { fieldId: 'completedquantity', value: props.completedQty, ignoreFieldChange: false } this.scrap = { fieldId: 'scrapquantity', value: props.scrapQty, ignoreFieldChange: false } this.is_back_flush = { fieldId: 'isbackflush', value: true, ignoreFieldChange: false } this.current_state = Srh.lookupFields({ type: 'manufacturingoperationtask', id: props.mfgoptask_id, columns: [ 'predecessor.internalid', 'predecessor.completedquantity', 'completedquantity', 'predecessor.inputquantity', 'inputquantity' ] }) this.nwo = Rec.load({ type: 'workorder', id: props.workorder_id }) this.op = Rec.load({ type: 'manufacturingoperationtask', id: props.mfgoptask_id }) } causedErrors() { return Boolean(this.errors.length) } props() { return { workordercompletion_id: this.workordercompletion_id, operation_sequence: this.operation_sequence, mfgoptask_id: this.mfgoptask_id, workorder_id: this.workorder_id, completedQty: this.completedQty, location_id: this.location_id, operator_id: this.operator_id, worktime_id: this.worktime_id, machine_id: this.machine_id, workcenter: this.workcenter, scrapQty: this.scrapQty, item_id: this.item_id, action: this.action, id: this.id } } init() { try { this.completion = Rec.transform(this.transform_parameters) this.completion.setValue(this.machine_operator) this.completion.setText(this.start_operation_sequence) this.completion.setText(this.end_operation_sequence) this.completion.setValue(this.quantity) if (parseFloat(this.scrapQty) > 0) { this.completion.setValue(this.scrap) const cqty = parseFloat(this.completedQty | 0) const sqty = parseFloat(this.scrapQty | 0) this.completedQty = (cqty + sqty).toString() } } catch (error) { this.errors.push(`Completion.init() ERROR: [> ${error.message} <]`) log_ss_debug('Completion failed on method', 'Completion.init()', { ...this.props(), ERROR: error.message }) } } isBackFlush() { if (this.completion !== null) { try { if (NONE_BACKFLUSH_WORKCENTERS.indexOf(this.workcenter) === -1) { this.completion.setValue({ fieldId: 'isbackflush', value: true, ignoreFieldChange: false }) } } catch (error) { this.errors.push(`Completion.isBackFlush() ERROR: [> ${error.message} <]`) log_ss_debug('isBackflush', 'Completion.isBackFlush()', { ...this.props(), ERROR: error.message }) } } else { this.errors.push('Missing completion...') log_ss_debug('isBackflush', 'Missing completion...', '') } } isValid() { try { //TODO assert predicate const wo = this.op.getValue({ fieldId: 'workorder' }) const id = this.op.getValue({ fieldId: 'id' }) if ( this.workorder_id === wo.toString() && this.mfgoptask_id === id.toString() ) { this.last_workcenter = this.op.getValue({ fieldId: 'manufacturingworkcenter' }) return true } else { return false } } catch (error) { this.errors.push(`Completion.isValid() ERROR: [> ${error.message} <]`) log_ss_debug('Completion failed on method', 'Completion.isValid()', { ...this.props(), ERROR: error.message }) return false } } canComplete() { const qty = parseFloat(this.completedQty | 0) const operation_required_qty = parseFloat(this.current_state['inputquantity'] | 0) const operation_completed_qty = parseFloat(this.current_state['completedquantity'] | 0) const total_completed = operation_completed_qty + qty this.operation_is_complete = total_completed >= operation_required_qty if (Array.isArray(this.current_state['predecessor.internalid'])) { if (this.current_state['predecessor.internalid'].length === 0) { log_ss_debug('canComplete', ' first mfg operation task', 'Yes') return true } } const previous_operation_completed_qty = parseFloat(this.current_state['predecessor.completedquantity'] | 0) const previous_operation_required_qty = parseFloat(this.current_state['predecessor.inputquantity'] | 0) const avaliable_qty = previous_operation_completed_qty - operation_completed_qty const remaining_qty = operation_required_qty - operation_completed_qty if (qty <= avaliable_qty) { return true } else { this.errors.push(`Completion.canComplete() ERROR: [> ${qty} less than or equal to ${avaliable_qty} <]`) log_ss_debug('Completion failed on method', 'Completion.canComplete()', { ...this.props(), qty, previous_operation_completed_qty, operation_completed_qty, previous_operation_required_qty, operation_required_qty, avaliable_qty, remaining_qty }) return false } } nwoIsComplete() { try { this.nwo.setValue({ fieldId: 'status', value: 'Built', ignoreFieldChange: false }) this.nwo.save() } catch (error) { this.errors.push(`Completion.nwoIsComplete() ERROR: [> ${error.message} <]`) log_ss_debug('Changing NWO status failed', error.message, { ...this.props(), ERROR: error.message }) } } componentInvtDets() { try { const componentLines = this.completion.getLineCount({ sublistId: 'component' }) for (var line = 0, l = componentLines; line !== l; line++) { const c_line = { sublistId: 'component', fieldId: 'componentinventorydetailreq', line } const line_requires_component_invt_dets = (this.completion.getSublistValue(c_line) === 'T') if (line_requires_component_invt_dets) { this.component_invtdets_required = true this.bin_lines.push({ line, componentinventorydetailreq: this.completion.getSublistValue({ ...c_line, fieldId: 'componentinventorydetailreq' }), operationsequencenumber: this.completion.getSublistValue({ ...c_line, fieldId: 'operationsequencenumber' }), itemlocationbinlist: this.completion.getSublistValue({ ...c_line, fieldId: 'itemlocationbinlist' }), units: this.completion.getSublistValue({ ...c_line, fieldId: 'units' }), item: this.completion.getSublistValue({ ...c_line, fieldId: 'item' }) }) } } } catch (error) { this.errors.push(`Completion.componentInvtDets() ERROR: [> ${error.message} <]`) log_ss_debug('Completion failed on method', 'Completion.componentInvtDets()', { ...this.props(), ERROR: error.message }) } } commitComponentInvtDets() { this.bin_lines.forEach(({ line, units, operationsequencenumber }) => { try { if (operationsequencenumber.toString() === this.operation_sequence) { const line_qty = this.completedQty * units this.completion.selectLine({ sublistId: 'component', line }) this.completion.setCurrentSublistValue({ sublistId: 'component', fieldId: 'quantity', value: line_qty }) const invtdets = this.completion.getCurrentSublistSubrecord({ sublistId: 'component', fieldId: 'componentinventorydetail' }) invtdets.selectLine({ sublistId: 'inventoryassignment', line }) invtdets.setCurrentSublistValue({ sublistId: 'inventoryassignment', fieldId: 'quantity', value: this.completedQty }) invtdets.commitLine({ sublistId: 'inventoryassignment' }) this.completion.commitLine({ sublistId: 'component' }) } else { log_ss_debug('commitComponentInvtDets', 'Operation sequence on component line doesn\'t match this.operation_sequence...', '') } } catch (error) { this.errors.push(`Completion.commitComponentInvtDets() ERROR: [> ${error.message} <]`) log_ss_debug(`Completion failed on method', 'Completion.commitComponentInvtDets(line:${line})`, { ...this.props(), error }) } }) } isLastWorkCenter() { try { var ops = [] const line_count = this.nwo.getLineCount({ sublistId: 'item' }) for (var n = 0, l = line_count; n !== l; n++) { //was getSublistField ops.push(this.nwo.getSublistValue({ sublistId: 'item', fieldId: 'operationsequencenumber', line: n })) } const highest_operation_sequence_value = ops.sort().pop().toString() if (this.operation_sequence === highest_operation_sequence_value) { this.last_nwo_workcenter = true log_ss_debug('requiredInventoryDetails', 'requires woc InvtDetails', 'Yes') this.completion.setValue(this.is_back_flush) const inventory_detail = this.completion.getSubrecord({ fieldId: 'inventorydetail' }) inventory_detail.selectNewLine({ sublistId: 'inventoryassignment' }) inventory_detail.setCurrentSublistValue({ sublistId: 'inventoryassignment', fieldId: 'quantity', value: this.completedQty - this.scrapQty }) inventory_detail.commitLine({ sublistId: 'inventoryassignment' }) return true } else { return false } } catch (error) { this.errors.push(`Completion.isLastWorkCenter() ERROR: [> ${error.message} <]`) log_ss_debug('Completion failed on method', 'Completion.requiredInventoryDetails()', { ...this.props(), ERROR: error.message }) } } save() { try { const completion_id = this.completion.save() this.workordercompletion_id = completion_id.toString() log_ss_debug('save', 'Saved completion', this.workordercompletion_id) if (this.operation_is_complete) { log_ss_debug('save', 'This Mfg Operation Task is complete...', this.mfgoptask_id) } } catch (error) { this.errors.push(`Completion.save() ERROR: [> ${error.message} <]`) log_ss_debug('Completion failed on method', 'Completion.save()', { ...this.props(), ERROR: error.message }) } } delete() { log_ss_debug('delete', 'Deleting completion', this.props()) try { Rec.delete({ type: Rec.Type.WORK_ORDER_COMPLETION, id: this.workordercompletion_id }) } catch (error) { this.errors.push(`Completion.delete() ERROR: [> ${error.message} <]`) log_ss_debug('Completion failed on method', 'Completion.delete()', { ...this.props(), ERROR: error.message }) } } } function get(args) { try { const completion = new Completion(args) switch (completion.action) { case CREATE_WORKORDER_COMPLETION: { // To be generated completion.init() completion.componentInvtDets() completion.isBackFlush() const is_valid_completion_operation = completion.isValid() const can_preform_completion = completion.canComplete() if (completion.component_invtdets_required) { completion.commitComponentInvtDets() } completion.isLastWorkCenter() if (completion.causedErrors()) { log_ss_debug('onGet', `Failed with ${completion.errors.length} errors...`, '') return JSON.stringify({ error: true, errors: completion.errors }) } else { log_ss_debug('onGet', 'Processing', completion.props()) } if (is_valid_completion_operation && can_preform_completion) { completion.save() if (completion.last_nwo_workcenter && completion.operation_is_complete) { completion.nwoIsComplete() } log_ss_debug('onGet', 'Created completion', completion.workordercompletion_id) return JSON.stringify(completion.props()) } break } case DELETE_WORKORDER_COMPLETION: { completion.delete() if (completion.causedErrors()) { log_ss_debug('onGet', `Failed with ${completion.errors.length} errors...`, '') return JSON.stringify({ error: true, errors: completion.errors }) } else { return JSON.stringify(completion.props()) } } default: throw Error('UNKNOWN_OR_MISSING_OPERATION_ACTION') } } catch (error) { log_ss_debug('onGet', error.name, error.message) return JSON.stringify({ error: true, message: error.message }) } } return { get } })
true
/** *@NApiVersion 2.1 *@NScriptType Restlet *@author Shaun York <PI:EMAIL:envkt@example.comEND_PI> */ define(['N/log', 'N/search', 'N/record'], function (Log, Srh, Rec) { // TODO: Set this array via script parameter const NONE_BACKFLUSH_WORKCENTERS = ['16469', '16489'] const CREATE_WORKORDER_COMPLETION = 'mk' const DELETE_WORKORDER_COMPLETION = 'rm' function log_ss_debug(title, msg, context) { const debug_options = { title, details: `MSG: [${msg}]\n\n${JSON.stringify(context)}` } Log.debug(debug_options) } function isJson(jdoc) { try { return JSON.parse(jdoc) } catch (error) { log_ss_debug('isJson failed to parse', error.message, jdoc) } } class Completion { constructor(props) { this.workordercompletion_id = props.workordercompletion_id this.operation_sequence = props.operation_sequence this.mfgoptask_id = props.mfgoptask_id this.workorder_id = props.workorder_id this.completedQty = props.completedQty this.location_id = props.location_id this.operator_id = props.operator_id this.worktime_id = props.worktime_id this.machine_id = props.machine_id this.workcenter = props.workcenter this.scrapQty = props.scrapQty this.item_id = props.item_id this.action = props.action this.id = props.id this.errors = [] this.bin_lines = [] this.completion = null this.last_workcenter = null this.operation_is_complete = false this.last_nwo_workcenter = false this.component_invtdets_required = false this.transform_parameters = { fromType: Rec.Type.WORK_ORDER, fromId: props.workorder_id, toType: Rec.Type.WORK_ORDER_COMPLETION, isDynamic: true } this.machine_operator = { fieldId: 'custbody_operator', value: props.operator_id, ignoreFieldChange: false } this.start_operation_sequence = { fieldId: 'startoperation', text: props.operation_sequence, ignoreFieldChange: false } this.end_operation_sequence = { fieldId: 'endoperation', text: props.operation_sequence, ignoreFieldChange: false } this.quantity = { fieldId: 'completedquantity', value: props.completedQty, ignoreFieldChange: false } this.scrap = { fieldId: 'scrapquantity', value: props.scrapQty, ignoreFieldChange: false } this.is_back_flush = { fieldId: 'isbackflush', value: true, ignoreFieldChange: false } this.current_state = Srh.lookupFields({ type: 'manufacturingoperationtask', id: props.mfgoptask_id, columns: [ 'predecessor.internalid', 'predecessor.completedquantity', 'completedquantity', 'predecessor.inputquantity', 'inputquantity' ] }) this.nwo = Rec.load({ type: 'workorder', id: props.workorder_id }) this.op = Rec.load({ type: 'manufacturingoperationtask', id: props.mfgoptask_id }) } causedErrors() { return Boolean(this.errors.length) } props() { return { workordercompletion_id: this.workordercompletion_id, operation_sequence: this.operation_sequence, mfgoptask_id: this.mfgoptask_id, workorder_id: this.workorder_id, completedQty: this.completedQty, location_id: this.location_id, operator_id: this.operator_id, worktime_id: this.worktime_id, machine_id: this.machine_id, workcenter: this.workcenter, scrapQty: this.scrapQty, item_id: this.item_id, action: this.action, id: this.id } } init() { try { this.completion = Rec.transform(this.transform_parameters) this.completion.setValue(this.machine_operator) this.completion.setText(this.start_operation_sequence) this.completion.setText(this.end_operation_sequence) this.completion.setValue(this.quantity) if (parseFloat(this.scrapQty) > 0) { this.completion.setValue(this.scrap) const cqty = parseFloat(this.completedQty | 0) const sqty = parseFloat(this.scrapQty | 0) this.completedQty = (cqty + sqty).toString() } } catch (error) { this.errors.push(`Completion.init() ERROR: [> ${error.message} <]`) log_ss_debug('Completion failed on method', 'Completion.init()', { ...this.props(), ERROR: error.message }) } } isBackFlush() { if (this.completion !== null) { try { if (NONE_BACKFLUSH_WORKCENTERS.indexOf(this.workcenter) === -1) { this.completion.setValue({ fieldId: 'isbackflush', value: true, ignoreFieldChange: false }) } } catch (error) { this.errors.push(`Completion.isBackFlush() ERROR: [> ${error.message} <]`) log_ss_debug('isBackflush', 'Completion.isBackFlush()', { ...this.props(), ERROR: error.message }) } } else { this.errors.push('Missing completion...') log_ss_debug('isBackflush', 'Missing completion...', '') } } isValid() { try { //TODO assert predicate const wo = this.op.getValue({ fieldId: 'workorder' }) const id = this.op.getValue({ fieldId: 'id' }) if ( this.workorder_id === wo.toString() && this.mfgoptask_id === id.toString() ) { this.last_workcenter = this.op.getValue({ fieldId: 'manufacturingworkcenter' }) return true } else { return false } } catch (error) { this.errors.push(`Completion.isValid() ERROR: [> ${error.message} <]`) log_ss_debug('Completion failed on method', 'Completion.isValid()', { ...this.props(), ERROR: error.message }) return false } } canComplete() { const qty = parseFloat(this.completedQty | 0) const operation_required_qty = parseFloat(this.current_state['inputquantity'] | 0) const operation_completed_qty = parseFloat(this.current_state['completedquantity'] | 0) const total_completed = operation_completed_qty + qty this.operation_is_complete = total_completed >= operation_required_qty if (Array.isArray(this.current_state['predecessor.internalid'])) { if (this.current_state['predecessor.internalid'].length === 0) { log_ss_debug('canComplete', ' first mfg operation task', 'Yes') return true } } const previous_operation_completed_qty = parseFloat(this.current_state['predecessor.completedquantity'] | 0) const previous_operation_required_qty = parseFloat(this.current_state['predecessor.inputquantity'] | 0) const avaliable_qty = previous_operation_completed_qty - operation_completed_qty const remaining_qty = operation_required_qty - operation_completed_qty if (qty <= avaliable_qty) { return true } else { this.errors.push(`Completion.canComplete() ERROR: [> ${qty} less than or equal to ${avaliable_qty} <]`) log_ss_debug('Completion failed on method', 'Completion.canComplete()', { ...this.props(), qty, previous_operation_completed_qty, operation_completed_qty, previous_operation_required_qty, operation_required_qty, avaliable_qty, remaining_qty }) return false } } nwoIsComplete() { try { this.nwo.setValue({ fieldId: 'status', value: 'Built', ignoreFieldChange: false }) this.nwo.save() } catch (error) { this.errors.push(`Completion.nwoIsComplete() ERROR: [> ${error.message} <]`) log_ss_debug('Changing NWO status failed', error.message, { ...this.props(), ERROR: error.message }) } } componentInvtDets() { try { const componentLines = this.completion.getLineCount({ sublistId: 'component' }) for (var line = 0, l = componentLines; line !== l; line++) { const c_line = { sublistId: 'component', fieldId: 'componentinventorydetailreq', line } const line_requires_component_invt_dets = (this.completion.getSublistValue(c_line) === 'T') if (line_requires_component_invt_dets) { this.component_invtdets_required = true this.bin_lines.push({ line, componentinventorydetailreq: this.completion.getSublistValue({ ...c_line, fieldId: 'componentinventorydetailreq' }), operationsequencenumber: this.completion.getSublistValue({ ...c_line, fieldId: 'operationsequencenumber' }), itemlocationbinlist: this.completion.getSublistValue({ ...c_line, fieldId: 'itemlocationbinlist' }), units: this.completion.getSublistValue({ ...c_line, fieldId: 'units' }), item: this.completion.getSublistValue({ ...c_line, fieldId: 'item' }) }) } } } catch (error) { this.errors.push(`Completion.componentInvtDets() ERROR: [> ${error.message} <]`) log_ss_debug('Completion failed on method', 'Completion.componentInvtDets()', { ...this.props(), ERROR: error.message }) } } commitComponentInvtDets() { this.bin_lines.forEach(({ line, units, operationsequencenumber }) => { try { if (operationsequencenumber.toString() === this.operation_sequence) { const line_qty = this.completedQty * units this.completion.selectLine({ sublistId: 'component', line }) this.completion.setCurrentSublistValue({ sublistId: 'component', fieldId: 'quantity', value: line_qty }) const invtdets = this.completion.getCurrentSublistSubrecord({ sublistId: 'component', fieldId: 'componentinventorydetail' }) invtdets.selectLine({ sublistId: 'inventoryassignment', line }) invtdets.setCurrentSublistValue({ sublistId: 'inventoryassignment', fieldId: 'quantity', value: this.completedQty }) invtdets.commitLine({ sublistId: 'inventoryassignment' }) this.completion.commitLine({ sublistId: 'component' }) } else { log_ss_debug('commitComponentInvtDets', 'Operation sequence on component line doesn\'t match this.operation_sequence...', '') } } catch (error) { this.errors.push(`Completion.commitComponentInvtDets() ERROR: [> ${error.message} <]`) log_ss_debug(`Completion failed on method', 'Completion.commitComponentInvtDets(line:${line})`, { ...this.props(), error }) } }) } isLastWorkCenter() { try { var ops = [] const line_count = this.nwo.getLineCount({ sublistId: 'item' }) for (var n = 0, l = line_count; n !== l; n++) { //was getSublistField ops.push(this.nwo.getSublistValue({ sublistId: 'item', fieldId: 'operationsequencenumber', line: n })) } const highest_operation_sequence_value = ops.sort().pop().toString() if (this.operation_sequence === highest_operation_sequence_value) { this.last_nwo_workcenter = true log_ss_debug('requiredInventoryDetails', 'requires woc InvtDetails', 'Yes') this.completion.setValue(this.is_back_flush) const inventory_detail = this.completion.getSubrecord({ fieldId: 'inventorydetail' }) inventory_detail.selectNewLine({ sublistId: 'inventoryassignment' }) inventory_detail.setCurrentSublistValue({ sublistId: 'inventoryassignment', fieldId: 'quantity', value: this.completedQty - this.scrapQty }) inventory_detail.commitLine({ sublistId: 'inventoryassignment' }) return true } else { return false } } catch (error) { this.errors.push(`Completion.isLastWorkCenter() ERROR: [> ${error.message} <]`) log_ss_debug('Completion failed on method', 'Completion.requiredInventoryDetails()', { ...this.props(), ERROR: error.message }) } } save() { try { const completion_id = this.completion.save() this.workordercompletion_id = completion_id.toString() log_ss_debug('save', 'Saved completion', this.workordercompletion_id) if (this.operation_is_complete) { log_ss_debug('save', 'This Mfg Operation Task is complete...', this.mfgoptask_id) } } catch (error) { this.errors.push(`Completion.save() ERROR: [> ${error.message} <]`) log_ss_debug('Completion failed on method', 'Completion.save()', { ...this.props(), ERROR: error.message }) } } delete() { log_ss_debug('delete', 'Deleting completion', this.props()) try { Rec.delete({ type: Rec.Type.WORK_ORDER_COMPLETION, id: this.workordercompletion_id }) } catch (error) { this.errors.push(`Completion.delete() ERROR: [> ${error.message} <]`) log_ss_debug('Completion failed on method', 'Completion.delete()', { ...this.props(), ERROR: error.message }) } } } function get(args) { try { const completion = new Completion(args) switch (completion.action) { case CREATE_WORKORDER_COMPLETION: { // To be generated completion.init() completion.componentInvtDets() completion.isBackFlush() const is_valid_completion_operation = completion.isValid() const can_preform_completion = completion.canComplete() if (completion.component_invtdets_required) { completion.commitComponentInvtDets() } completion.isLastWorkCenter() if (completion.causedErrors()) { log_ss_debug('onGet', `Failed with ${completion.errors.length} errors...`, '') return JSON.stringify({ error: true, errors: completion.errors }) } else { log_ss_debug('onGet', 'Processing', completion.props()) } if (is_valid_completion_operation && can_preform_completion) { completion.save() if (completion.last_nwo_workcenter && completion.operation_is_complete) { completion.nwoIsComplete() } log_ss_debug('onGet', 'Created completion', completion.workordercompletion_id) return JSON.stringify(completion.props()) } break } case DELETE_WORKORDER_COMPLETION: { completion.delete() if (completion.causedErrors()) { log_ss_debug('onGet', `Failed with ${completion.errors.length} errors...`, '') return JSON.stringify({ error: true, errors: completion.errors }) } else { return JSON.stringify(completion.props()) } } default: throw Error('UNKNOWN_OR_MISSING_OPERATION_ACTION') } } catch (error) { log_ss_debug('onGet', error.name, error.message) return JSON.stringify({ error: true, message: error.message }) } } return { get } })
/** *@NApiVersion 2.0 *@NScriptType Suitelet */ define(['N/ui/serverWidget', 'N/email', 'N/runtime', 'N/search', 'N/record', 'N/http', 'N/log', 'N/redirect'], function (ui, email, runtime, search, record, http, log, redirect) { function onRequest(context) { var baseURL = 'https://1048144.app.netsuite.com'; if (runtime.EnvType == "SANDBOX") { baseURL = 'https://system.sandbox.netsuite.com'; } var zee = 0; var role = runtime.getCurrentUser().role; if (role == 1000) { zee = runtime.getCurrentUser().id; } else if (role == 3) { //Administrator zee = 6; //test } else if (role == 1032) { // System Support zee = 425904; //test-AR } if (context.request.method === 'GET') { var customer_id = context.request.parameters.custid; var script_id = context.request.parameters.scriptid; if (isNullorEmpty(script_id)) { script_id = null; } var deploy_id = context.request.parameters.deployid; if (isNullorEmpty(deploy_id)) { deploy_id = null; }; // customer_id = 586137; var customer_record; var entityid; var companyName = ''; var abn = ''; var zeeText = ''; var accounts_email = ''; var accounts_phone = ''; var daytodayemail = ''; var daytodayphone = ''; var ap_mail_parcel = ''; var ap_outlet = ''; var lpo_customer = ''; var customer_status = ''; var customer_status_id = ''; var lead_source = ''; var lead_source_text = ''; var customer_industry = ''; var multisite = ''; var website = ''; var savedNoteSearch = null; log.debug({ title: 'Customer ID', details: customer_id }); var customer_record = record.load({ type: record.Type.CUSTOMER, id: customer_id, isDynamic: true }); entityid = customer_record.getValue({ fieldId: 'entityid' }); companyName = customer_record.getValue({ fieldId: 'companyname' }); abn = customer_record.getValue({ fieldId: 'vatregnumber' }); zee = customer_record.getValue({ fieldId: 'partner' }); zeeText = customer_record.getText({ fieldId: 'partner' }); accounts_email = customer_record.getValue({ fieldId: 'email' }); accounts_phone = customer_record.getValue({ fieldId: 'altphone' }); daytodayemail = customer_record.getValue({ fieldId: 'custentity_email_service' }); daytodayphone = customer_record.getValue({ fieldId: 'phone' }); ap_mail_parcel = customer_record.getValue({ fieldId: 'custentity_ap_mail_parcel' }); ap_outlet = customer_record.getValue({ fieldId: 'custentity_ap_outlet' }); lpo_customer = customer_record.getValue({ fieldId: 'custentity_ap_lpo_customer' }); customer_status = customer_record.getText({ fieldId: 'entitystatus' }); customer_status_id = customer_record.getValue({ fieldId: 'entitystatus' }); lead_source = customer_record.getValue({ fieldId: 'leadsource' }); lead_source_text = customer_record.getText({ fieldId: 'leadsource' }); customer_industry = customer_record.getValue({ fieldId: 'custentity_industry_category' }); multisite = customer_record.getValue({ fieldId: 'custentity_category_multisite' }); if (multisite == 'T') { multisite = 1; } else { multisite = 2; } website = customer_record.getValue({ fieldId: 'custentity_category_multisite_link' }); savedNoteSearch = search.load({ id: 'customsearch_user_note' }); savedNoteSearch.filters.push(search.createFilter({ name: 'internalid', join: 'Customer', operator: search.Operator.IS, values: customer_id })); var form = ui.createForm({ title: 'Customer Cancellation: ' + entityid + ' ' + companyName }); var customerID = form.addField({ id: 'custpage_customerid', type: ui.FieldType.TEXT, label: ' ' }).updateDisplayType({ displayType: ui.FieldDisplayType.HIDDEN }).defaultValue = customer_id; var zeeID = form.addField({ id: 'custpage_zeeid', type: ui.FieldType.TEXT, label: ' ' }).updateDisplayType({ displayType: ui.FieldDisplayType.HIDDEN }).defaultValue = zee; var inlineHtml = '<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script><script src="//code.jquery.com/jquery-1.11.0.min.js"></script><link rel="stylesheet" type="text/css" href="https://cdn.datatables.net/1.10.16/css/jquery.dataTables.css"><script type="text/javascript" charset="utf8" src="https://cdn.datatables.net/1.10.16/js/jquery.dataTables.js"></script><link href="//netdna.bootstrapcdn.com/bootstrap/3.3.2/css/bootstrap.min.css" rel="stylesheet"><script src="//netdna.bootstrapcdn.com/bootstrap/3.3.2/js/bootstrap.min.js"></script><link rel="stylesheet" href="https://1048144.app.netsuite.com/core/media/media.nl?id=2060796&c=1048144&h=9ee6accfd476c9cae718&_xt=.css"/><script src="https://1048144.app.netsuite.com/core/media/media.nl?id=2060797&c=1048144&h=ef2cda20731d146b5e98&_xt=.js"></script><link type="text/css" rel="stylesheet" href="https://1048144.app.netsuite.com/core/media/media.nl?id=2090583&c=1048144&h=a0ef6ac4e28f91203dfe&_xt=.css"><link href="https://cdnjs.cloudflare.com/ajax/libs/summernote/0.8.9/summernote.css" rel="stylesheet"><script src="https://cdnjs.cloudflare.com/ajax/libs/summernote/0.8.9/summernote.js"></script><script src="https://cdnjs.cloudflare.com/ajax/libs/jspdf/1.3.5/jspdf.debug.js" integrity="sha384-CchuzHs077vGtfhGYl9Qtc7Vx64rXBXdIAZIPbItbNyWIRTdG0oYAqki3Ry13Yzu" crossorigin="anonymous"></script><style>.mandatory{color:red;}</style>'; inlineHtml += '<div class="container" style="padding-top: 3%;"><div id="alert" class="alert alert-danger fade in"></div>'; var searchZees = search.load({ id: 'customsearch_salesp_franchisee' }); var resultSetZees = searchZees.run(); inlineHtml += '<input id="customer_id" class="form-control" required value="' + customer_id + '" type="hidden"/></div></div>'; inlineHtml += '<input id="zee_id" class="form-control" required value="' + zee + '" type="hidden"/></div></div>'; inlineHtml += '<input id="script_id" class="form-control" required value="' + script_id + '" type="hidden"/></div></div>'; inlineHtml += '<input id="deploy_id" class="form-control" required value="' + deploy_id + '" type="hidden"/></div></div>'; // inlineHtml += '<input id="type" class="form-control" required value="' + type + '" type="hidden"/></div></div>'; var resultSetContacts = null; var resultSetAddresses = null; var searched_addresses = search.load({ id: 'customsearch_salesp_address' }); searched_addresses.filters.push(search.createFilter({ name: 'internalid', operator: search.Operator.IS, values: customer_id })); resultSetAddresses = searched_addresses.run(); var searched_contacts = search.load({ id: 'customsearch_salesp_contacts' }); searched_contacts.filters.push(search.createFilter({ name: 'company', operator: search.Operator.IS, values: customer_id })); resultSetContacts = searched_contacts.run(); //Customer Details // inlineHtml += customerDetailsSection(entityid, companyName, abn, resultSetZees, zee, accounts_email, daytodayphone, daytodayemail, accounts_phone, customer_status, lead_source, customer_industry, lead_source_text); inlineHtml += cancellationNotes(); inlineHtml += '<div class="tabs" style="font-size: xx-small;"><ul class="nav nav-tabs nav-justified" style="padding-top: 3%;">'; var tab_content = ''; inlineHtml += '<li role="presentation" class="active"><a href="#notes">USER NOTES</a></li>'; inlineHtml += '</ul>'; tab_content += '<div role="tabpanel" class="tab-pane active" id="notes">'; //User Notes tab_content += userNote(savedNoteSearch); tab_content += '</div>'; inlineHtml += '<div class="tab-content" style="padding-top: 3%;">'; inlineHtml += tab_content; inlineHtml += '</div></div>'; var htmlInstruct = form.addField({ id: 'custpage_p1', type: ui.FieldType.INLINEHTML, label: ' ' }).updateLayoutType({ layoutType: ui.FieldLayoutType.OUTSIDEABOVE }).updateBreakType({ breakType: ui.FieldBreakType.STARTROW }).defaultValue = inlineHtml; // var htmlInstruct = form.addSubmitButton({ // label: 'Save' // }); form.clientScriptFileId = 2240633; context.response.writePage(form); } else { redirect.toSuitelet({ scriptId: 750, deploymentId: 1, parameters: { 'type': 'create' } }); } } function customerDetailsSection(entityid, companyName, abn, resultSetZees, zee, accounts_email, daytodayphone, daytodayemail, accounts_phone, customer_status, lead_source, customer_industry, lead_source_text) { var inlineQty = '<div class="form-group container company_name_section">'; inlineQty += '<div class="row">'; inlineQty += '<div class="col-xs-12 heading1"><h4><span class="label label-default col-xs-12">CUSTOMER DETAILS</span></h4></div>'; inlineQty += '</div>'; inlineQty += '</div>'; if (!isNullorEmpty(entityid)) { inlineQty += '<div class="form-group container entityid_section">'; inlineQty += '<div class="row">'; inlineQty += '<div class="col-xs-6 entityid"><div class="input-group"><span class="input-group-addon" id="entityid_text">ID </span><input id="entityid" class="form-control entityid" readonly value="' + entityid + '" data-oldvalue="' + entityid + '" /></div></div>'; inlineQty += '</div>'; inlineQty += '</div>'; } inlineQty += '<div class="form-group container company_name_section">'; inlineQty += '<div class="row">'; inlineQty += '<div class="col-xs-6 company_name"><div class="input-group"><span class="input-group-addon" id="company_name_text">NAME <span class="mandatory">*</span></span><input id="company_name" class="form-control company_name" required value="' + companyName + '" readonly data-oldvalue="' + companyName + '" /></div></div>'; inlineQty += '<div class="col-xs-6 industry"><div class="input-group"><span class="input-group-addon" id="industry_text">INDUSTRY </span><select id="industry" class="form-control industry" readonly><option></option>'; var industry_search = search.create({ type: 'customlist_industry_category', columns: [{ name: 'name' }, { name: 'internalId' }] }); industry_search.run().each(function (searchResult) { var listValue = searchResult.getValue('name'); var listID = searchResult.getValue('internalId'); if (!isNullorEmpty(customer_industry)) { if (customer_industry == listID) { inlineQty += '<option value="' + listID + '" selected>' + listValue + '</option>'; } } inlineQty += '<option value="' + listID + '">' + listValue + '</option>'; return true; }); inlineQty += '</select></div></div>'; inlineQty += '</div>'; inlineQty += '</div>'; inlineQty += '<div class="form-group container abn_section">'; inlineQty += '<div class="row">'; inlineQty += '<div class="col-xs-6 abn"><div class="input-group"><span class="input-group-addon" id="abn_text">ABN </span><input id="abn" class="form-control abn" value="' + abn + '" readonly data-oldvalue="' + abn + '"/></div></div>'; if (isNullorEmpty(customer_status)) { customer_status = 'SUSPECT - New' } inlineQty += '<div class="col-xs-6 status"><div class="input-group"><span class="input-group-addon" id="status_text">STATUS </span><input id="status" class="form-control status" readonly value="' + customer_status + '" data-oldvalue="' + customer_status + '" /></div></div>'; inlineQty += '</div>'; inlineQty += '</div>'; inlineQty += '<div class="form-group container zee_section">'; inlineQty += '<div class="row">'; inlineQty += '<div class="col-xs-6 zee"><div class="input-group"><span class="input-group-addon" id="zee_text">FRANCHISEE <span class="mandatory">*</span></span><select id="zee" class="form-control zee" readonly><option value=0></option>'; resultSetZees.each(function (searchResultZees) { zeeId = searchResultZees.getValue('internalid'); zeeName = searchResultZees.getValue('companyname'); if (zeeId == zee) { inlineQty += '<option value="' + zeeId + '" selected>' + zeeName + '</option>'; } else { inlineQty += '<option value="' + zeeId + '">' + zeeName + '</option>'; } return true; }); inlineQty += '</select></div></div>'; inlineQty += '<div class="col-xs-6 leadsource_div"><div class="input-group"><span class="input-group-addon" id="leadsource_text">LEAD SOURCE <span class="mandatory">*</span></span><select id="leadsource" class="form-control leadsource" readonly><option></option>'; // var campaignSearch = search.create({ // type: search.Type.CAMPAIGN, // title: 'LEAD SOURCE', // id: 'customsearch_lead_source', // columns: [{ // name: 'internalId' // }, { // name: 'title' // }] // }); // campaignSearch.save(); // var campaignSearch = search.load({ // id: 'customsearch_lead_source' // }); // campaignSearch.run().each(function(searchResult) { // var listValue = searchResult.getValue('title'); // // var listID = searchResult.getValue('internalId'); // inlineQty += '<option value="">' + listValue + '</option>'; // return true; // }); if (lead_source == 97943) { inlineQty += '<option value="97943" selected>HO Generated</option>'; } else { inlineQty += '<option value="97943">HO Generated</option>'; } if (lead_source == 17) { inlineQty += '<option value="17" selected>Inbound - Call</option>'; } else { inlineQty += '<option value="17">Inbound - Call</option>'; } if (lead_source == 99417) { inlineQty += '<option value="99417" selected>Inbound - Web</option>'; } else { inlineQty += '<option value="99417">Inbound - Web</option>'; } if (lead_source == -4) { inlineQty += '<option value="-4" selected>Franchisee Generated</option>'; } else { inlineQty += '<option value="-4" >Franchisee Generated</option>'; } if (lead_source == 226139) { inlineQty += '<option value="226139" selected>SRA Field Sales</option>'; } else { inlineQty += '<option value="226139">SRA Field Sales</option>'; } inlineQty += '</select></div></div>'; inlineQty += '</div>'; inlineQty += '</div>'; inlineQty += '<div class="form-group container email_section">'; inlineQty += '<div class="row">'; inlineQty += '<div class="col-xs-6 account_email_div"><div class="input-group"><span class="input-group-addon" id="account_email_text">ACCOUNTS (MAIN) EMAIL</span><input id="account_email" type="email" class="form-control account_email" data-oldvalue="' + accounts_email + '" value="' + accounts_email + '" /></div></div>'; inlineQty += '<div class="col-xs-6 daytodayemail_div"><div class="input-group"><span class="input-group-addon" id="daytodayemail_text">DAY-TO-DAY EMAIL</span><input id="daytodayemail" type="email" class="form-control daytodayemail" data-oldvalue="' + daytodayemail + '" value="' + daytodayemail + '" /></div></div>'; inlineQty += '</div>'; inlineQty += '</div>'; inlineQty += '<div class="form-group container phone_section">'; inlineQty += '<div class="row">'; inlineQty += '<div class="col-xs-6 account_phone_div"><div class="input-group"><span class="input-group-addon" id="account_phone_text">ACCOUNTS (MAIN) PHONE</span><input id="account_phone" class="form-control account_phone" data-oldvalue="' + accounts_phone + '" value="' + accounts_phone + '" /> <div class="input-group-btn"><button type="button" class="btn btn-success" id="call_accounts_phone"><span class="glyphicon glyphicon-earphone"></span></button></div></div></div>'; inlineQty += '<div class="col-xs-6 daytodayphone_div"><div class="input-group"><span class="input-group-addon" id="daytodayphone_text">DAY-TO-DAY PHONE <span class="mandatory">*</span></span><input id="daytodayphone" class="form-control daytodayphone" data-oldvalue="' + daytodayphone + '" value="' + daytodayphone + '" /><div class="input-group-btn"><button type="button" class="btn btn-success" id="call_daytoday_phone"><span class="glyphicon glyphicon-earphone"></span></button></div></div></div>'; inlineQty += '</div>'; inlineQty += '</div>'; return inlineQty; } function cancellationNotes() { var inlineQty = '<div class="form-group container company_name_section">'; inlineQty += '<div class="row">'; inlineQty += '<div class="col-xs-12 heading1"><h4><span class="label label-default col-xs-12">CANCELLATION DETAILS</span></h4></div>'; inlineQty += '</div>'; inlineQty += '</div>'; inlineQty += '<div class="form-group container cancel_date">'; inlineQty += '<div class="row">'; inlineQty += '<div class="col-xs-6 cancel_date"><div class="input-group"><span class="input-group-addon" id="cancel_date_text">SERVICE CANCELLATION DATE</span><input id="cancel_date" type="date" class="form-control cancel_date" value="" data-oldvalue="" /></div></div>'; inlineQty += '</div>'; inlineQty += '</div>'; inlineQty += '<div class="form-group container cancel_reason">'; inlineQty += '<div class="row">'; inlineQty += '<div class="col-xs-6 cancel_reason"><div class="input-group"><span class="input-group-addon" id="cancel_reason_text">SERVICE CANCELATION REASON</span><select id="cancel_reason" class="form-control cancel_reason" ><option></option>'; var industry_search = search.create({ type: 'customlist58', columns: [{ name: 'name' }, { name: 'internalId' }], filters: ['isinactive', 'is', 'false'] }); industry_search.run().each(function (searchResult) { var listValue = searchResult.getValue('name'); var listID = searchResult.getValue('internalId'); inlineQty += '<option value="' + listID + '">' + listValue + '</option>'; return true; }); inlineQty += '</select></div></div>'; inlineQty += '</div>'; inlineQty += '</div>'; inlineQty += '<div class="form-group container cancel_notice">'; inlineQty += '<div class="row">'; inlineQty += '<div class="col-xs-6 cancel_notice"><div class="input-group"><span class="input-group-addon" id="cancel_notice_text">SERVICE CANCELATION NOTICE</span><select id="cancel_notice" class="form-control cancel_notice" ><option></option>'; var industry_search = search.create({ type: 'customlist_cancellation_notice', columns: [{ name: 'name' }, { name: 'internalId' }], filters: ['isinactive', 'is', 'false'] }); industry_search.run().each(function (searchResult) { var listValue = searchResult.getValue('name'); var listID = searchResult.getValue('internalId'); inlineQty += '<option value="' + listID + '">' + listValue + '</option>'; return true; }); inlineQty += '</select></div></div>'; inlineQty += '</div>'; inlineQty += '</div>'; inlineQty += '<div class="form-group container cancel_comp">'; inlineQty += '<div class="row">'; inlineQty += '<div class="col-xs-6 cancel_comp"><div class="input-group"><span class="input-group-addon" id="cancel_comp_text">SERVICE CANCELLATION COMPETITOR</span><select id="cancel_comp" class="form-control cancel_comp" ><option></option>'; var industry_search = search.create({ type: 'customlist33', columns: [{ name: 'name' }, { name: 'internalId' }], filters: ['isinactive', 'is', 'false'] }); industry_search.run().each(function (searchResult) { var listValue = searchResult.getValue('name'); var listID = searchResult.getValue('internalId'); inlineQty += '<option value="' + listID + '">' + listValue + '</option>'; return true; }); inlineQty += '</select></div></div>'; inlineQty += '</div>'; inlineQty += '</div>'; // inlineQty += '<div class="form-group container row_body">'; // inlineQty += '<div class="row">' // inlineQty += '<div class="col-xs-12 body_section"><textarea id="email_body" name="editordata"></textarea></div></div>'; // inlineQty += '</div>'; // inlineQty += '</div>'; return inlineQty; } function userNote(savedNoteSearch) { var inlineQty = '<div class="form-group container reviewaddress_section">'; inlineQty += '<div class="row">'; inlineQty += '<div class="col-xs-3 create_note"><input type="button" value="CREATE USER NOTE" class="form-control btn btn-primary" id="create_note" /></div>'; inlineQty += '</div>'; inlineQty += '</div>'; if (!isNullorEmpty(savedNoteSearch)) { inlineQty += '<div class="form-group container contacts_section">'; inlineQty += '<div class="row">'; inlineQty += '<div class="col-xs-12 address_div">'; inlineQty += '<table border="0" cellpadding="15" id="address" class="table table-responsive table-striped address tablesorter" cellspacing="0" style="width: 100%;"><thead style="color: white;background-color: #607799;"><tr><th style="vertical-align: middle;text-align: center;"><b>CREATED DATE</b></th><th style="vertical-align: middle;text-align: center;"><b>ORGANISER</b></th><th style="vertical-align: middle;text-align: center;"><b>MESSAGE</b></th></tr></thead><tbody>'; savedNoteSearch.run().each(function (searchResult) { var note_date = searchResult.getValue({ name: 'notedate' }); var author = searchResult.getText({ name: "author" }); var message = searchResult.getValue({ name: 'note' }); inlineQty += '<tr><td>' + note_date + '</td><td>' + author + '</td><td>' + message + '</td></tr>'; return true; }); inlineQty += '</tbody></table>'; inlineQty += '</div>'; inlineQty += '</div>'; inlineQty += '</div>'; } return inlineQty; } /** * Is Null or Empty. * * @param {Object} strVal */ function isNullorEmpty(strVal) { return (strVal == null || strVal == '' || strVal == 'null' || strVal == undefined || strVal == 'undefined' || strVal == '- None -'); } return { onRequest: onRequest }; });
140
[{"tag": "KEY", "value": "sha384-CchuzHs077vGtfhGYl9Qtc7Vx64rXBXdIAZIPbItbNyWIRTdG0oYAqki3Ry13Yzu", "start": 5610, "end": 5681}]
true
1
/** *@NApiVersion 2.0 *@NScriptType Suitelet */ define(['N/ui/serverWidget', 'N/email', 'N/runtime', 'N/search', 'N/record', 'N/http', 'N/log', 'N/redirect'], function (ui, email, runtime, search, record, http, log, redirect) { function onRequest(context) { var baseURL = 'https://1048144.app.netsuite.com'; if (runtime.EnvType == "SANDBOX") { baseURL = 'https://system.sandbox.netsuite.com'; } var zee = 0; var role = runtime.getCurrentUser().role; if (role == 1000) { zee = runtime.getCurrentUser().id; } else if (role == 3) { //Administrator zee = 6; //test } else if (role == 1032) { // System Support zee = 425904; //test-AR } if (context.request.method === 'GET') { var customer_id = context.request.parameters.custid; var script_id = context.request.parameters.scriptid; if (isNullorEmpty(script_id)) { script_id = null; } var deploy_id = context.request.parameters.deployid; if (isNullorEmpty(deploy_id)) { deploy_id = null; }; // customer_id = 586137; var customer_record; var entityid; var companyName = ''; var abn = ''; var zeeText = ''; var accounts_email = ''; var accounts_phone = ''; var daytodayemail = ''; var daytodayphone = ''; var ap_mail_parcel = ''; var ap_outlet = ''; var lpo_customer = ''; var customer_status = ''; var customer_status_id = ''; var lead_source = ''; var lead_source_text = ''; var customer_industry = ''; var multisite = ''; var website = ''; var savedNoteSearch = null; log.debug({ title: 'Customer ID', details: customer_id }); var customer_record = record.load({ type: record.Type.CUSTOMER, id: customer_id, isDynamic: true }); entityid = customer_record.getValue({ fieldId: 'entityid' }); companyName = customer_record.getValue({ fieldId: 'companyname' }); abn = customer_record.getValue({ fieldId: 'vatregnumber' }); zee = customer_record.getValue({ fieldId: 'partner' }); zeeText = customer_record.getText({ fieldId: 'partner' }); accounts_email = customer_record.getValue({ fieldId: 'email' }); accounts_phone = customer_record.getValue({ fieldId: 'altphone' }); daytodayemail = customer_record.getValue({ fieldId: 'custentity_email_service' }); daytodayphone = customer_record.getValue({ fieldId: 'phone' }); ap_mail_parcel = customer_record.getValue({ fieldId: 'custentity_ap_mail_parcel' }); ap_outlet = customer_record.getValue({ fieldId: 'custentity_ap_outlet' }); lpo_customer = customer_record.getValue({ fieldId: 'custentity_ap_lpo_customer' }); customer_status = customer_record.getText({ fieldId: 'entitystatus' }); customer_status_id = customer_record.getValue({ fieldId: 'entitystatus' }); lead_source = customer_record.getValue({ fieldId: 'leadsource' }); lead_source_text = customer_record.getText({ fieldId: 'leadsource' }); customer_industry = customer_record.getValue({ fieldId: 'custentity_industry_category' }); multisite = customer_record.getValue({ fieldId: 'custentity_category_multisite' }); if (multisite == 'T') { multisite = 1; } else { multisite = 2; } website = customer_record.getValue({ fieldId: 'custentity_category_multisite_link' }); savedNoteSearch = search.load({ id: 'customsearch_user_note' }); savedNoteSearch.filters.push(search.createFilter({ name: 'internalid', join: 'Customer', operator: search.Operator.IS, values: customer_id })); var form = ui.createForm({ title: 'Customer Cancellation: ' + entityid + ' ' + companyName }); var customerID = form.addField({ id: 'custpage_customerid', type: ui.FieldType.TEXT, label: ' ' }).updateDisplayType({ displayType: ui.FieldDisplayType.HIDDEN }).defaultValue = customer_id; var zeeID = form.addField({ id: 'custpage_zeeid', type: ui.FieldType.TEXT, label: ' ' }).updateDisplayType({ displayType: ui.FieldDisplayType.HIDDEN }).defaultValue = zee; var inlineHtml = '<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script><script src="//code.jquery.com/jquery-1.11.0.min.js"></script><link rel="stylesheet" type="text/css" href="https://cdn.datatables.net/1.10.16/css/jquery.dataTables.css"><script type="text/javascript" charset="utf8" src="https://cdn.datatables.net/1.10.16/js/jquery.dataTables.js"></script><link href="//netdna.bootstrapcdn.com/bootstrap/3.3.2/css/bootstrap.min.css" rel="stylesheet"><script src="//netdna.bootstrapcdn.com/bootstrap/3.3.2/js/bootstrap.min.js"></script><link rel="stylesheet" href="https://1048144.app.netsuite.com/core/media/media.nl?id=2060796&c=1048144&h=9ee6accfd476c9cae718&_xt=.css"/><script src="https://1048144.app.netsuite.com/core/media/media.nl?id=2060797&c=1048144&h=ef2cda20731d146b5e98&_xt=.js"></script><link type="text/css" rel="stylesheet" href="https://1048144.app.netsuite.com/core/media/media.nl?id=2090583&c=1048144&h=a0ef6ac4e28f91203dfe&_xt=.css"><link href="https://cdnjs.cloudflare.com/ajax/libs/summernote/0.8.9/summernote.css" rel="stylesheet"><script src="https://cdnjs.cloudflare.com/ajax/libs/summernote/0.8.9/summernote.js"></script><script src="https://cdnjs.cloudflare.com/ajax/libs/jspdf/1.3.5/jspdf.debug.js" integrity="949d1u22cbffbrarjh182eig55721odj" crossorigin="anonymous"></script><style>.mandatory{color:red;}</style>'; inlineHtml += '<div class="container" style="padding-top: 3%;"><div id="alert" class="alert alert-danger fade in"></div>'; var searchZees = search.load({ id: 'customsearch_salesp_franchisee' }); var resultSetZees = searchZees.run(); inlineHtml += '<input id="customer_id" class="form-control" required value="' + customer_id + '" type="hidden"/></div></div>'; inlineHtml += '<input id="zee_id" class="form-control" required value="' + zee + '" type="hidden"/></div></div>'; inlineHtml += '<input id="script_id" class="form-control" required value="' + script_id + '" type="hidden"/></div></div>'; inlineHtml += '<input id="deploy_id" class="form-control" required value="' + deploy_id + '" type="hidden"/></div></div>'; // inlineHtml += '<input id="type" class="form-control" required value="' + type + '" type="hidden"/></div></div>'; var resultSetContacts = null; var resultSetAddresses = null; var searched_addresses = search.load({ id: 'customsearch_salesp_address' }); searched_addresses.filters.push(search.createFilter({ name: 'internalid', operator: search.Operator.IS, values: customer_id })); resultSetAddresses = searched_addresses.run(); var searched_contacts = search.load({ id: 'customsearch_salesp_contacts' }); searched_contacts.filters.push(search.createFilter({ name: 'company', operator: search.Operator.IS, values: customer_id })); resultSetContacts = searched_contacts.run(); //Customer Details // inlineHtml += customerDetailsSection(entityid, companyName, abn, resultSetZees, zee, accounts_email, daytodayphone, daytodayemail, accounts_phone, customer_status, lead_source, customer_industry, lead_source_text); inlineHtml += cancellationNotes(); inlineHtml += '<div class="tabs" style="font-size: xx-small;"><ul class="nav nav-tabs nav-justified" style="padding-top: 3%;">'; var tab_content = ''; inlineHtml += '<li role="presentation" class="active"><a href="#notes">USER NOTES</a></li>'; inlineHtml += '</ul>'; tab_content += '<div role="tabpanel" class="tab-pane active" id="notes">'; //User Notes tab_content += userNote(savedNoteSearch); tab_content += '</div>'; inlineHtml += '<div class="tab-content" style="padding-top: 3%;">'; inlineHtml += tab_content; inlineHtml += '</div></div>'; var htmlInstruct = form.addField({ id: 'custpage_p1', type: ui.FieldType.INLINEHTML, label: ' ' }).updateLayoutType({ layoutType: ui.FieldLayoutType.OUTSIDEABOVE }).updateBreakType({ breakType: ui.FieldBreakType.STARTROW }).defaultValue = inlineHtml; // var htmlInstruct = form.addSubmitButton({ // label: 'Save' // }); form.clientScriptFileId = 2240633; context.response.writePage(form); } else { redirect.toSuitelet({ scriptId: 750, deploymentId: 1, parameters: { 'type': 'create' } }); } } function customerDetailsSection(entityid, companyName, abn, resultSetZees, zee, accounts_email, daytodayphone, daytodayemail, accounts_phone, customer_status, lead_source, customer_industry, lead_source_text) { var inlineQty = '<div class="form-group container company_name_section">'; inlineQty += '<div class="row">'; inlineQty += '<div class="col-xs-12 heading1"><h4><span class="label label-default col-xs-12">CUSTOMER DETAILS</span></h4></div>'; inlineQty += '</div>'; inlineQty += '</div>'; if (!isNullorEmpty(entityid)) { inlineQty += '<div class="form-group container entityid_section">'; inlineQty += '<div class="row">'; inlineQty += '<div class="col-xs-6 entityid"><div class="input-group"><span class="input-group-addon" id="entityid_text">ID </span><input id="entityid" class="form-control entityid" readonly value="' + entityid + '" data-oldvalue="' + entityid + '" /></div></div>'; inlineQty += '</div>'; inlineQty += '</div>'; } inlineQty += '<div class="form-group container company_name_section">'; inlineQty += '<div class="row">'; inlineQty += '<div class="col-xs-6 company_name"><div class="input-group"><span class="input-group-addon" id="company_name_text">NAME <span class="mandatory">*</span></span><input id="company_name" class="form-control company_name" required value="' + companyName + '" readonly data-oldvalue="' + companyName + '" /></div></div>'; inlineQty += '<div class="col-xs-6 industry"><div class="input-group"><span class="input-group-addon" id="industry_text">INDUSTRY </span><select id="industry" class="form-control industry" readonly><option></option>'; var industry_search = search.create({ type: 'customlist_industry_category', columns: [{ name: 'name' }, { name: 'internalId' }] }); industry_search.run().each(function (searchResult) { var listValue = searchResult.getValue('name'); var listID = searchResult.getValue('internalId'); if (!isNullorEmpty(customer_industry)) { if (customer_industry == listID) { inlineQty += '<option value="' + listID + '" selected>' + listValue + '</option>'; } } inlineQty += '<option value="' + listID + '">' + listValue + '</option>'; return true; }); inlineQty += '</select></div></div>'; inlineQty += '</div>'; inlineQty += '</div>'; inlineQty += '<div class="form-group container abn_section">'; inlineQty += '<div class="row">'; inlineQty += '<div class="col-xs-6 abn"><div class="input-group"><span class="input-group-addon" id="abn_text">ABN </span><input id="abn" class="form-control abn" value="' + abn + '" readonly data-oldvalue="' + abn + '"/></div></div>'; if (isNullorEmpty(customer_status)) { customer_status = 'SUSPECT - New' } inlineQty += '<div class="col-xs-6 status"><div class="input-group"><span class="input-group-addon" id="status_text">STATUS </span><input id="status" class="form-control status" readonly value="' + customer_status + '" data-oldvalue="' + customer_status + '" /></div></div>'; inlineQty += '</div>'; inlineQty += '</div>'; inlineQty += '<div class="form-group container zee_section">'; inlineQty += '<div class="row">'; inlineQty += '<div class="col-xs-6 zee"><div class="input-group"><span class="input-group-addon" id="zee_text">FRANCHISEE <span class="mandatory">*</span></span><select id="zee" class="form-control zee" readonly><option value=0></option>'; resultSetZees.each(function (searchResultZees) { zeeId = searchResultZees.getValue('internalid'); zeeName = searchResultZees.getValue('companyname'); if (zeeId == zee) { inlineQty += '<option value="' + zeeId + '" selected>' + zeeName + '</option>'; } else { inlineQty += '<option value="' + zeeId + '">' + zeeName + '</option>'; } return true; }); inlineQty += '</select></div></div>'; inlineQty += '<div class="col-xs-6 leadsource_div"><div class="input-group"><span class="input-group-addon" id="leadsource_text">LEAD SOURCE <span class="mandatory">*</span></span><select id="leadsource" class="form-control leadsource" readonly><option></option>'; // var campaignSearch = search.create({ // type: search.Type.CAMPAIGN, // title: 'LEAD SOURCE', // id: 'customsearch_lead_source', // columns: [{ // name: 'internalId' // }, { // name: 'title' // }] // }); // campaignSearch.save(); // var campaignSearch = search.load({ // id: 'customsearch_lead_source' // }); // campaignSearch.run().each(function(searchResult) { // var listValue = searchResult.getValue('title'); // // var listID = searchResult.getValue('internalId'); // inlineQty += '<option value="">' + listValue + '</option>'; // return true; // }); if (lead_source == 97943) { inlineQty += '<option value="97943" selected>HO Generated</option>'; } else { inlineQty += '<option value="97943">HO Generated</option>'; } if (lead_source == 17) { inlineQty += '<option value="17" selected>Inbound - Call</option>'; } else { inlineQty += '<option value="17">Inbound - Call</option>'; } if (lead_source == 99417) { inlineQty += '<option value="99417" selected>Inbound - Web</option>'; } else { inlineQty += '<option value="99417">Inbound - Web</option>'; } if (lead_source == -4) { inlineQty += '<option value="-4" selected>Franchisee Generated</option>'; } else { inlineQty += '<option value="-4" >Franchisee Generated</option>'; } if (lead_source == 226139) { inlineQty += '<option value="226139" selected>SRA Field Sales</option>'; } else { inlineQty += '<option value="226139">SRA Field Sales</option>'; } inlineQty += '</select></div></div>'; inlineQty += '</div>'; inlineQty += '</div>'; inlineQty += '<div class="form-group container email_section">'; inlineQty += '<div class="row">'; inlineQty += '<div class="col-xs-6 account_email_div"><div class="input-group"><span class="input-group-addon" id="account_email_text">ACCOUNTS (MAIN) EMAIL</span><input id="account_email" type="email" class="form-control account_email" data-oldvalue="' + accounts_email + '" value="' + accounts_email + '" /></div></div>'; inlineQty += '<div class="col-xs-6 daytodayemail_div"><div class="input-group"><span class="input-group-addon" id="daytodayemail_text">DAY-TO-DAY EMAIL</span><input id="daytodayemail" type="email" class="form-control daytodayemail" data-oldvalue="' + daytodayemail + '" value="' + daytodayemail + '" /></div></div>'; inlineQty += '</div>'; inlineQty += '</div>'; inlineQty += '<div class="form-group container phone_section">'; inlineQty += '<div class="row">'; inlineQty += '<div class="col-xs-6 account_phone_div"><div class="input-group"><span class="input-group-addon" id="account_phone_text">ACCOUNTS (MAIN) PHONE</span><input id="account_phone" class="form-control account_phone" data-oldvalue="' + accounts_phone + '" value="' + accounts_phone + '" /> <div class="input-group-btn"><button type="button" class="btn btn-success" id="call_accounts_phone"><span class="glyphicon glyphicon-earphone"></span></button></div></div></div>'; inlineQty += '<div class="col-xs-6 daytodayphone_div"><div class="input-group"><span class="input-group-addon" id="daytodayphone_text">DAY-TO-DAY PHONE <span class="mandatory">*</span></span><input id="daytodayphone" class="form-control daytodayphone" data-oldvalue="' + daytodayphone + '" value="' + daytodayphone + '" /><div class="input-group-btn"><button type="button" class="btn btn-success" id="call_daytoday_phone"><span class="glyphicon glyphicon-earphone"></span></button></div></div></div>'; inlineQty += '</div>'; inlineQty += '</div>'; return inlineQty; } function cancellationNotes() { var inlineQty = '<div class="form-group container company_name_section">'; inlineQty += '<div class="row">'; inlineQty += '<div class="col-xs-12 heading1"><h4><span class="label label-default col-xs-12">CANCELLATION DETAILS</span></h4></div>'; inlineQty += '</div>'; inlineQty += '</div>'; inlineQty += '<div class="form-group container cancel_date">'; inlineQty += '<div class="row">'; inlineQty += '<div class="col-xs-6 cancel_date"><div class="input-group"><span class="input-group-addon" id="cancel_date_text">SERVICE CANCELLATION DATE</span><input id="cancel_date" type="date" class="form-control cancel_date" value="" data-oldvalue="" /></div></div>'; inlineQty += '</div>'; inlineQty += '</div>'; inlineQty += '<div class="form-group container cancel_reason">'; inlineQty += '<div class="row">'; inlineQty += '<div class="col-xs-6 cancel_reason"><div class="input-group"><span class="input-group-addon" id="cancel_reason_text">SERVICE CANCELATION REASON</span><select id="cancel_reason" class="form-control cancel_reason" ><option></option>'; var industry_search = search.create({ type: 'customlist58', columns: [{ name: 'name' }, { name: 'internalId' }], filters: ['isinactive', 'is', 'false'] }); industry_search.run().each(function (searchResult) { var listValue = searchResult.getValue('name'); var listID = searchResult.getValue('internalId'); inlineQty += '<option value="' + listID + '">' + listValue + '</option>'; return true; }); inlineQty += '</select></div></div>'; inlineQty += '</div>'; inlineQty += '</div>'; inlineQty += '<div class="form-group container cancel_notice">'; inlineQty += '<div class="row">'; inlineQty += '<div class="col-xs-6 cancel_notice"><div class="input-group"><span class="input-group-addon" id="cancel_notice_text">SERVICE CANCELATION NOTICE</span><select id="cancel_notice" class="form-control cancel_notice" ><option></option>'; var industry_search = search.create({ type: 'customlist_cancellation_notice', columns: [{ name: 'name' }, { name: 'internalId' }], filters: ['isinactive', 'is', 'false'] }); industry_search.run().each(function (searchResult) { var listValue = searchResult.getValue('name'); var listID = searchResult.getValue('internalId'); inlineQty += '<option value="' + listID + '">' + listValue + '</option>'; return true; }); inlineQty += '</select></div></div>'; inlineQty += '</div>'; inlineQty += '</div>'; inlineQty += '<div class="form-group container cancel_comp">'; inlineQty += '<div class="row">'; inlineQty += '<div class="col-xs-6 cancel_comp"><div class="input-group"><span class="input-group-addon" id="cancel_comp_text">SERVICE CANCELLATION COMPETITOR</span><select id="cancel_comp" class="form-control cancel_comp" ><option></option>'; var industry_search = search.create({ type: 'customlist33', columns: [{ name: 'name' }, { name: 'internalId' }], filters: ['isinactive', 'is', 'false'] }); industry_search.run().each(function (searchResult) { var listValue = searchResult.getValue('name'); var listID = searchResult.getValue('internalId'); inlineQty += '<option value="' + listID + '">' + listValue + '</option>'; return true; }); inlineQty += '</select></div></div>'; inlineQty += '</div>'; inlineQty += '</div>'; // inlineQty += '<div class="form-group container row_body">'; // inlineQty += '<div class="row">' // inlineQty += '<div class="col-xs-12 body_section"><textarea id="email_body" name="editordata"></textarea></div></div>'; // inlineQty += '</div>'; // inlineQty += '</div>'; return inlineQty; } function userNote(savedNoteSearch) { var inlineQty = '<div class="form-group container reviewaddress_section">'; inlineQty += '<div class="row">'; inlineQty += '<div class="col-xs-3 create_note"><input type="button" value="CREATE USER NOTE" class="form-control btn btn-primary" id="create_note" /></div>'; inlineQty += '</div>'; inlineQty += '</div>'; if (!isNullorEmpty(savedNoteSearch)) { inlineQty += '<div class="form-group container contacts_section">'; inlineQty += '<div class="row">'; inlineQty += '<div class="col-xs-12 address_div">'; inlineQty += '<table border="0" cellpadding="15" id="address" class="table table-responsive table-striped address tablesorter" cellspacing="0" style="width: 100%;"><thead style="color: white;background-color: #607799;"><tr><th style="vertical-align: middle;text-align: center;"><b>CREATED DATE</b></th><th style="vertical-align: middle;text-align: center;"><b>ORGANISER</b></th><th style="vertical-align: middle;text-align: center;"><b>MESSAGE</b></th></tr></thead><tbody>'; savedNoteSearch.run().each(function (searchResult) { var note_date = searchResult.getValue({ name: 'notedate' }); var author = searchResult.getText({ name: "author" }); var message = searchResult.getValue({ name: 'note' }); inlineQty += '<tr><td>' + note_date + '</td><td>' + author + '</td><td>' + message + '</td></tr>'; return true; }); inlineQty += '</tbody></table>'; inlineQty += '</div>'; inlineQty += '</div>'; inlineQty += '</div>'; } return inlineQty; } /** * Is Null or Empty. * * @param {Object} strVal */ function isNullorEmpty(strVal) { return (strVal == null || strVal == '' || strVal == 'null' || strVal == undefined || strVal == 'undefined' || strVal == '- None -'); } return { onRequest: onRequest }; });
true
/** *@NApiVersion 2.0 *@NScriptType Suitelet */ define(['N/ui/serverWidget', 'N/email', 'N/runtime', 'N/search', 'N/record', 'N/http', 'N/log', 'N/redirect'], function (ui, email, runtime, search, record, http, log, redirect) { function onRequest(context) { var baseURL = 'https://1048144.app.netsuite.com'; if (runtime.EnvType == "SANDBOX") { baseURL = 'https://system.sandbox.netsuite.com'; } var zee = 0; var role = runtime.getCurrentUser().role; if (role == 1000) { zee = runtime.getCurrentUser().id; } else if (role == 3) { //Administrator zee = 6; //test } else if (role == 1032) { // System Support zee = 425904; //test-AR } if (context.request.method === 'GET') { var customer_id = context.request.parameters.custid; var script_id = context.request.parameters.scriptid; if (isNullorEmpty(script_id)) { script_id = null; } var deploy_id = context.request.parameters.deployid; if (isNullorEmpty(deploy_id)) { deploy_id = null; }; // customer_id = 586137; var customer_record; var entityid; var companyName = ''; var abn = ''; var zeeText = ''; var accounts_email = ''; var accounts_phone = ''; var daytodayemail = ''; var daytodayphone = ''; var ap_mail_parcel = ''; var ap_outlet = ''; var lpo_customer = ''; var customer_status = ''; var customer_status_id = ''; var lead_source = ''; var lead_source_text = ''; var customer_industry = ''; var multisite = ''; var website = ''; var savedNoteSearch = null; log.debug({ title: 'Customer ID', details: customer_id }); var customer_record = record.load({ type: record.Type.CUSTOMER, id: customer_id, isDynamic: true }); entityid = customer_record.getValue({ fieldId: 'entityid' }); companyName = customer_record.getValue({ fieldId: 'companyname' }); abn = customer_record.getValue({ fieldId: 'vatregnumber' }); zee = customer_record.getValue({ fieldId: 'partner' }); zeeText = customer_record.getText({ fieldId: 'partner' }); accounts_email = customer_record.getValue({ fieldId: 'email' }); accounts_phone = customer_record.getValue({ fieldId: 'altphone' }); daytodayemail = customer_record.getValue({ fieldId: 'custentity_email_service' }); daytodayphone = customer_record.getValue({ fieldId: 'phone' }); ap_mail_parcel = customer_record.getValue({ fieldId: 'custentity_ap_mail_parcel' }); ap_outlet = customer_record.getValue({ fieldId: 'custentity_ap_outlet' }); lpo_customer = customer_record.getValue({ fieldId: 'custentity_ap_lpo_customer' }); customer_status = customer_record.getText({ fieldId: 'entitystatus' }); customer_status_id = customer_record.getValue({ fieldId: 'entitystatus' }); lead_source = customer_record.getValue({ fieldId: 'leadsource' }); lead_source_text = customer_record.getText({ fieldId: 'leadsource' }); customer_industry = customer_record.getValue({ fieldId: 'custentity_industry_category' }); multisite = customer_record.getValue({ fieldId: 'custentity_category_multisite' }); if (multisite == 'T') { multisite = 1; } else { multisite = 2; } website = customer_record.getValue({ fieldId: 'custentity_category_multisite_link' }); savedNoteSearch = search.load({ id: 'customsearch_user_note' }); savedNoteSearch.filters.push(search.createFilter({ name: 'internalid', join: 'Customer', operator: search.Operator.IS, values: customer_id })); var form = ui.createForm({ title: 'Customer Cancellation: ' + entityid + ' ' + companyName }); var customerID = form.addField({ id: 'custpage_customerid', type: ui.FieldType.TEXT, label: ' ' }).updateDisplayType({ displayType: ui.FieldDisplayType.HIDDEN }).defaultValue = customer_id; var zeeID = form.addField({ id: 'custpage_zeeid', type: ui.FieldType.TEXT, label: ' ' }).updateDisplayType({ displayType: ui.FieldDisplayType.HIDDEN }).defaultValue = zee; var inlineHtml = '<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script><script src="//code.jquery.com/jquery-1.11.0.min.js"></script><link rel="stylesheet" type="text/css" href="https://cdn.datatables.net/1.10.16/css/jquery.dataTables.css"><script type="text/javascript" charset="utf8" src="https://cdn.datatables.net/1.10.16/js/jquery.dataTables.js"></script><link href="//netdna.bootstrapcdn.com/bootstrap/3.3.2/css/bootstrap.min.css" rel="stylesheet"><script src="//netdna.bootstrapcdn.com/bootstrap/3.3.2/js/bootstrap.min.js"></script><link rel="stylesheet" href="https://1048144.app.netsuite.com/core/media/media.nl?id=2060796&c=1048144&h=9ee6accfd476c9cae718&_xt=.css"/><script src="https://1048144.app.netsuite.com/core/media/media.nl?id=2060797&c=1048144&h=ef2cda20731d146b5e98&_xt=.js"></script><link type="text/css" rel="stylesheet" href="https://1048144.app.netsuite.com/core/media/media.nl?id=2090583&c=1048144&h=a0ef6ac4e28f91203dfe&_xt=.css"><link href="https://cdnjs.cloudflare.com/ajax/libs/summernote/0.8.9/summernote.css" rel="stylesheet"><script src="https://cdnjs.cloudflare.com/ajax/libs/summernote/0.8.9/summernote.js"></script><script src="https://cdnjs.cloudflare.com/ajax/libs/jspdf/1.3.5/jspdf.debug.js" integrity="PI:KEY:949d1u22cbffbrarjh182eig55721odjEND_PI" crossorigin="anonymous"></script><style>.mandatory{color:red;}</style>'; inlineHtml += '<div class="container" style="padding-top: 3%;"><div id="alert" class="alert alert-danger fade in"></div>'; var searchZees = search.load({ id: 'customsearch_salesp_franchisee' }); var resultSetZees = searchZees.run(); inlineHtml += '<input id="customer_id" class="form-control" required value="' + customer_id + '" type="hidden"/></div></div>'; inlineHtml += '<input id="zee_id" class="form-control" required value="' + zee + '" type="hidden"/></div></div>'; inlineHtml += '<input id="script_id" class="form-control" required value="' + script_id + '" type="hidden"/></div></div>'; inlineHtml += '<input id="deploy_id" class="form-control" required value="' + deploy_id + '" type="hidden"/></div></div>'; // inlineHtml += '<input id="type" class="form-control" required value="' + type + '" type="hidden"/></div></div>'; var resultSetContacts = null; var resultSetAddresses = null; var searched_addresses = search.load({ id: 'customsearch_salesp_address' }); searched_addresses.filters.push(search.createFilter({ name: 'internalid', operator: search.Operator.IS, values: customer_id })); resultSetAddresses = searched_addresses.run(); var searched_contacts = search.load({ id: 'customsearch_salesp_contacts' }); searched_contacts.filters.push(search.createFilter({ name: 'company', operator: search.Operator.IS, values: customer_id })); resultSetContacts = searched_contacts.run(); //Customer Details // inlineHtml += customerDetailsSection(entityid, companyName, abn, resultSetZees, zee, accounts_email, daytodayphone, daytodayemail, accounts_phone, customer_status, lead_source, customer_industry, lead_source_text); inlineHtml += cancellationNotes(); inlineHtml += '<div class="tabs" style="font-size: xx-small;"><ul class="nav nav-tabs nav-justified" style="padding-top: 3%;">'; var tab_content = ''; inlineHtml += '<li role="presentation" class="active"><a href="#notes">USER NOTES</a></li>'; inlineHtml += '</ul>'; tab_content += '<div role="tabpanel" class="tab-pane active" id="notes">'; //User Notes tab_content += userNote(savedNoteSearch); tab_content += '</div>'; inlineHtml += '<div class="tab-content" style="padding-top: 3%;">'; inlineHtml += tab_content; inlineHtml += '</div></div>'; var htmlInstruct = form.addField({ id: 'custpage_p1', type: ui.FieldType.INLINEHTML, label: ' ' }).updateLayoutType({ layoutType: ui.FieldLayoutType.OUTSIDEABOVE }).updateBreakType({ breakType: ui.FieldBreakType.STARTROW }).defaultValue = inlineHtml; // var htmlInstruct = form.addSubmitButton({ // label: 'Save' // }); form.clientScriptFileId = 2240633; context.response.writePage(form); } else { redirect.toSuitelet({ scriptId: 750, deploymentId: 1, parameters: { 'type': 'create' } }); } } function customerDetailsSection(entityid, companyName, abn, resultSetZees, zee, accounts_email, daytodayphone, daytodayemail, accounts_phone, customer_status, lead_source, customer_industry, lead_source_text) { var inlineQty = '<div class="form-group container company_name_section">'; inlineQty += '<div class="row">'; inlineQty += '<div class="col-xs-12 heading1"><h4><span class="label label-default col-xs-12">CUSTOMER DETAILS</span></h4></div>'; inlineQty += '</div>'; inlineQty += '</div>'; if (!isNullorEmpty(entityid)) { inlineQty += '<div class="form-group container entityid_section">'; inlineQty += '<div class="row">'; inlineQty += '<div class="col-xs-6 entityid"><div class="input-group"><span class="input-group-addon" id="entityid_text">ID </span><input id="entityid" class="form-control entityid" readonly value="' + entityid + '" data-oldvalue="' + entityid + '" /></div></div>'; inlineQty += '</div>'; inlineQty += '</div>'; } inlineQty += '<div class="form-group container company_name_section">'; inlineQty += '<div class="row">'; inlineQty += '<div class="col-xs-6 company_name"><div class="input-group"><span class="input-group-addon" id="company_name_text">NAME <span class="mandatory">*</span></span><input id="company_name" class="form-control company_name" required value="' + companyName + '" readonly data-oldvalue="' + companyName + '" /></div></div>'; inlineQty += '<div class="col-xs-6 industry"><div class="input-group"><span class="input-group-addon" id="industry_text">INDUSTRY </span><select id="industry" class="form-control industry" readonly><option></option>'; var industry_search = search.create({ type: 'customlist_industry_category', columns: [{ name: 'name' }, { name: 'internalId' }] }); industry_search.run().each(function (searchResult) { var listValue = searchResult.getValue('name'); var listID = searchResult.getValue('internalId'); if (!isNullorEmpty(customer_industry)) { if (customer_industry == listID) { inlineQty += '<option value="' + listID + '" selected>' + listValue + '</option>'; } } inlineQty += '<option value="' + listID + '">' + listValue + '</option>'; return true; }); inlineQty += '</select></div></div>'; inlineQty += '</div>'; inlineQty += '</div>'; inlineQty += '<div class="form-group container abn_section">'; inlineQty += '<div class="row">'; inlineQty += '<div class="col-xs-6 abn"><div class="input-group"><span class="input-group-addon" id="abn_text">ABN </span><input id="abn" class="form-control abn" value="' + abn + '" readonly data-oldvalue="' + abn + '"/></div></div>'; if (isNullorEmpty(customer_status)) { customer_status = 'SUSPECT - New' } inlineQty += '<div class="col-xs-6 status"><div class="input-group"><span class="input-group-addon" id="status_text">STATUS </span><input id="status" class="form-control status" readonly value="' + customer_status + '" data-oldvalue="' + customer_status + '" /></div></div>'; inlineQty += '</div>'; inlineQty += '</div>'; inlineQty += '<div class="form-group container zee_section">'; inlineQty += '<div class="row">'; inlineQty += '<div class="col-xs-6 zee"><div class="input-group"><span class="input-group-addon" id="zee_text">FRANCHISEE <span class="mandatory">*</span></span><select id="zee" class="form-control zee" readonly><option value=0></option>'; resultSetZees.each(function (searchResultZees) { zeeId = searchResultZees.getValue('internalid'); zeeName = searchResultZees.getValue('companyname'); if (zeeId == zee) { inlineQty += '<option value="' + zeeId + '" selected>' + zeeName + '</option>'; } else { inlineQty += '<option value="' + zeeId + '">' + zeeName + '</option>'; } return true; }); inlineQty += '</select></div></div>'; inlineQty += '<div class="col-xs-6 leadsource_div"><div class="input-group"><span class="input-group-addon" id="leadsource_text">LEAD SOURCE <span class="mandatory">*</span></span><select id="leadsource" class="form-control leadsource" readonly><option></option>'; // var campaignSearch = search.create({ // type: search.Type.CAMPAIGN, // title: 'LEAD SOURCE', // id: 'customsearch_lead_source', // columns: [{ // name: 'internalId' // }, { // name: 'title' // }] // }); // campaignSearch.save(); // var campaignSearch = search.load({ // id: 'customsearch_lead_source' // }); // campaignSearch.run().each(function(searchResult) { // var listValue = searchResult.getValue('title'); // // var listID = searchResult.getValue('internalId'); // inlineQty += '<option value="">' + listValue + '</option>'; // return true; // }); if (lead_source == 97943) { inlineQty += '<option value="97943" selected>HO Generated</option>'; } else { inlineQty += '<option value="97943">HO Generated</option>'; } if (lead_source == 17) { inlineQty += '<option value="17" selected>Inbound - Call</option>'; } else { inlineQty += '<option value="17">Inbound - Call</option>'; } if (lead_source == 99417) { inlineQty += '<option value="99417" selected>Inbound - Web</option>'; } else { inlineQty += '<option value="99417">Inbound - Web</option>'; } if (lead_source == -4) { inlineQty += '<option value="-4" selected>Franchisee Generated</option>'; } else { inlineQty += '<option value="-4" >Franchisee Generated</option>'; } if (lead_source == 226139) { inlineQty += '<option value="226139" selected>SRA Field Sales</option>'; } else { inlineQty += '<option value="226139">SRA Field Sales</option>'; } inlineQty += '</select></div></div>'; inlineQty += '</div>'; inlineQty += '</div>'; inlineQty += '<div class="form-group container email_section">'; inlineQty += '<div class="row">'; inlineQty += '<div class="col-xs-6 account_email_div"><div class="input-group"><span class="input-group-addon" id="account_email_text">ACCOUNTS (MAIN) EMAIL</span><input id="account_email" type="email" class="form-control account_email" data-oldvalue="' + accounts_email + '" value="' + accounts_email + '" /></div></div>'; inlineQty += '<div class="col-xs-6 daytodayemail_div"><div class="input-group"><span class="input-group-addon" id="daytodayemail_text">DAY-TO-DAY EMAIL</span><input id="daytodayemail" type="email" class="form-control daytodayemail" data-oldvalue="' + daytodayemail + '" value="' + daytodayemail + '" /></div></div>'; inlineQty += '</div>'; inlineQty += '</div>'; inlineQty += '<div class="form-group container phone_section">'; inlineQty += '<div class="row">'; inlineQty += '<div class="col-xs-6 account_phone_div"><div class="input-group"><span class="input-group-addon" id="account_phone_text">ACCOUNTS (MAIN) PHONE</span><input id="account_phone" class="form-control account_phone" data-oldvalue="' + accounts_phone + '" value="' + accounts_phone + '" /> <div class="input-group-btn"><button type="button" class="btn btn-success" id="call_accounts_phone"><span class="glyphicon glyphicon-earphone"></span></button></div></div></div>'; inlineQty += '<div class="col-xs-6 daytodayphone_div"><div class="input-group"><span class="input-group-addon" id="daytodayphone_text">DAY-TO-DAY PHONE <span class="mandatory">*</span></span><input id="daytodayphone" class="form-control daytodayphone" data-oldvalue="' + daytodayphone + '" value="' + daytodayphone + '" /><div class="input-group-btn"><button type="button" class="btn btn-success" id="call_daytoday_phone"><span class="glyphicon glyphicon-earphone"></span></button></div></div></div>'; inlineQty += '</div>'; inlineQty += '</div>'; return inlineQty; } function cancellationNotes() { var inlineQty = '<div class="form-group container company_name_section">'; inlineQty += '<div class="row">'; inlineQty += '<div class="col-xs-12 heading1"><h4><span class="label label-default col-xs-12">CANCELLATION DETAILS</span></h4></div>'; inlineQty += '</div>'; inlineQty += '</div>'; inlineQty += '<div class="form-group container cancel_date">'; inlineQty += '<div class="row">'; inlineQty += '<div class="col-xs-6 cancel_date"><div class="input-group"><span class="input-group-addon" id="cancel_date_text">SERVICE CANCELLATION DATE</span><input id="cancel_date" type="date" class="form-control cancel_date" value="" data-oldvalue="" /></div></div>'; inlineQty += '</div>'; inlineQty += '</div>'; inlineQty += '<div class="form-group container cancel_reason">'; inlineQty += '<div class="row">'; inlineQty += '<div class="col-xs-6 cancel_reason"><div class="input-group"><span class="input-group-addon" id="cancel_reason_text">SERVICE CANCELATION REASON</span><select id="cancel_reason" class="form-control cancel_reason" ><option></option>'; var industry_search = search.create({ type: 'customlist58', columns: [{ name: 'name' }, { name: 'internalId' }], filters: ['isinactive', 'is', 'false'] }); industry_search.run().each(function (searchResult) { var listValue = searchResult.getValue('name'); var listID = searchResult.getValue('internalId'); inlineQty += '<option value="' + listID + '">' + listValue + '</option>'; return true; }); inlineQty += '</select></div></div>'; inlineQty += '</div>'; inlineQty += '</div>'; inlineQty += '<div class="form-group container cancel_notice">'; inlineQty += '<div class="row">'; inlineQty += '<div class="col-xs-6 cancel_notice"><div class="input-group"><span class="input-group-addon" id="cancel_notice_text">SERVICE CANCELATION NOTICE</span><select id="cancel_notice" class="form-control cancel_notice" ><option></option>'; var industry_search = search.create({ type: 'customlist_cancellation_notice', columns: [{ name: 'name' }, { name: 'internalId' }], filters: ['isinactive', 'is', 'false'] }); industry_search.run().each(function (searchResult) { var listValue = searchResult.getValue('name'); var listID = searchResult.getValue('internalId'); inlineQty += '<option value="' + listID + '">' + listValue + '</option>'; return true; }); inlineQty += '</select></div></div>'; inlineQty += '</div>'; inlineQty += '</div>'; inlineQty += '<div class="form-group container cancel_comp">'; inlineQty += '<div class="row">'; inlineQty += '<div class="col-xs-6 cancel_comp"><div class="input-group"><span class="input-group-addon" id="cancel_comp_text">SERVICE CANCELLATION COMPETITOR</span><select id="cancel_comp" class="form-control cancel_comp" ><option></option>'; var industry_search = search.create({ type: 'customlist33', columns: [{ name: 'name' }, { name: 'internalId' }], filters: ['isinactive', 'is', 'false'] }); industry_search.run().each(function (searchResult) { var listValue = searchResult.getValue('name'); var listID = searchResult.getValue('internalId'); inlineQty += '<option value="' + listID + '">' + listValue + '</option>'; return true; }); inlineQty += '</select></div></div>'; inlineQty += '</div>'; inlineQty += '</div>'; // inlineQty += '<div class="form-group container row_body">'; // inlineQty += '<div class="row">' // inlineQty += '<div class="col-xs-12 body_section"><textarea id="email_body" name="editordata"></textarea></div></div>'; // inlineQty += '</div>'; // inlineQty += '</div>'; return inlineQty; } function userNote(savedNoteSearch) { var inlineQty = '<div class="form-group container reviewaddress_section">'; inlineQty += '<div class="row">'; inlineQty += '<div class="col-xs-3 create_note"><input type="button" value="CREATE USER NOTE" class="form-control btn btn-primary" id="create_note" /></div>'; inlineQty += '</div>'; inlineQty += '</div>'; if (!isNullorEmpty(savedNoteSearch)) { inlineQty += '<div class="form-group container contacts_section">'; inlineQty += '<div class="row">'; inlineQty += '<div class="col-xs-12 address_div">'; inlineQty += '<table border="0" cellpadding="15" id="address" class="table table-responsive table-striped address tablesorter" cellspacing="0" style="width: 100%;"><thead style="color: white;background-color: #607799;"><tr><th style="vertical-align: middle;text-align: center;"><b>CREATED DATE</b></th><th style="vertical-align: middle;text-align: center;"><b>ORGANISER</b></th><th style="vertical-align: middle;text-align: center;"><b>MESSAGE</b></th></tr></thead><tbody>'; savedNoteSearch.run().each(function (searchResult) { var note_date = searchResult.getValue({ name: 'notedate' }); var author = searchResult.getText({ name: "author" }); var message = searchResult.getValue({ name: 'note' }); inlineQty += '<tr><td>' + note_date + '</td><td>' + author + '</td><td>' + message + '</td></tr>'; return true; }); inlineQty += '</tbody></table>'; inlineQty += '</div>'; inlineQty += '</div>'; inlineQty += '</div>'; } return inlineQty; } /** * Is Null or Empty. * * @param {Object} strVal */ function isNullorEmpty(strVal) { return (strVal == null || strVal == '' || strVal == 'null' || strVal == undefined || strVal == 'undefined' || strVal == '- None -'); } return { onRequest: onRequest }; });
/** *@NApiVersion 2.0 *@NScriptType Suitelet * * Module Description - * * NSVersion Date Author * 2.00 2020-12-19 13:12:36 Ravija Maheshwari * * @Last Modified by: Ravija * @Last Modified time: 2020-12-20 11:55 */ define(['N/ui/serverWidget', 'N/email', 'N/runtime', 'N/search', 'N/record', 'N/http', 'N/log', 'N/redirect', 'N/format', 'N/currentRecord', 'N/file'], function(ui, email, runtime, search, record, http, log, redirect, format, currentRecord, file) { function onRequest(context) { //Setup var baseURL = 'https://system.na2.netsuite.com'; if (runtime.EnvType == "SANDBOX") { baseURL = 'https://system.sandbox.netsuite.com'; } var zee = 0; var role = runtime.getCurrentUser().role; if (role == 1000) { zee = runtime.getCurrentUser().id; } else if (role == 3) { //Administrator zee = 6; //test } else if (role == 1032) { // System Support zee = 425904; //test-AR } if(context.request.method === 'GET'){ //Load Jquery var inlineQty = '<script src="https://code.jquery.com/jquery-1.12.4.min.js" integrity="sha384-nvAa0+6Qg9clwYCGGPpDQLVpLNn0fRaROjHqs13t4Ggj3Ez50XnGQqc/r8MhnRDZ" crossorigin="anonymous"></script>'; // Load Bootstrap inlineQty += '<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/3.4.1/css/bootstrap.min.css" integrity="sha384-HSMxcRTRxnN+Bdg0JdbxYKrThecOKuH5zCYotlSAcp1+c8xmyTe9GYg1l9a69psu" crossorigin="anonymous">'; inlineQty += '<script src="https://stackpath.bootstrapcdn.com/bootstrap/3.4.1/js/bootstrap.min.js" integrity="sha384-aJ21OjlMXNL5UyIl/XNwTMqvzeRMZH2w8c5cRVpzpU8Y5bApTppSuUkhZXN0VxHd" crossorigin="anonymous"></script>'; // Load Netsuite stylesheet and script inlineQty += '<link rel="stylesheet" href="https://1048144.app.netsuite.com/core/media/media.nl?id=2060796&c=1048144&h=9ee6accfd476c9cae718&_xt=.css"/>'; inlineQty += '<script src="https://1048144.app.netsuite.com/core/media/media.nl?id=2060797&c=1048144&h=ef2cda20731d146b5e98&_xt=.js"></script>'; inlineQty += '<link type="text/css" rel="stylesheet" href="https://1048144.app.netsuite.com/core/media/media.nl?id=2090583&c=1048144&h=a0ef6ac4e28f91203dfe&_xt=.css">'; inlineQty += '<style>.mandatory{color:red;}</style>'; inlineQty += '<link href="//netdna.bootstrapcdn.com/bootstrap/3.3.2/css/bootstrap.min.css" rel="stylesheet"><script src="//netdna.bootstrapcdn.com/bootstrap/3.3.2/js/bootstrap.min.js"></script><link rel="stylesheet" href="https://1048144.app.netsuite.com/core/media/media.nl?id=2060796&c=1048144&h=9ee6accfd476c9cae718&_xt=.css"/><script src="https://1048144.app.netsuite.com/core/media/media.nl?id=2060797&c=1048144&h=ef2cda20731d146b5e98&_xt=.js"></script><link type="text/css" rel="stylesheet" href="https://1048144.app.netsuite.com/core/media/media.nl?id=2090583&c=1048144&h=a0ef6ac4e28f91203dfe&_xt=.css">'; //Set the customer id if(!isNullorEmpty(context.request.parameters.custparam_params)){ var params = context.request.parameters.custparam_params; params = JSON.parse(params); var customer = parseInt(params.custid); }else{ var customer = parseInt(context.request.parameters.custid); } var recCustomer = record.load({ type: record.Type.CUSTOMER, id: customer, isDynamic: true }); var franchisee = recCustomer.getValue({fieldId: 'partner'}); var form = ui.createForm({ title: 'Service Management for : <a href="' + baseURL + '/app/common/entity/custjob.nl?id=' + customer + '">' + recCustomer.getValue({fieldId: 'entityid'}) +'</a> ' + recCustomer.getValue({fieldId: 'companyname'}) }); form.addField({ id: 'custpage_customer_id', label: 'Customer ID', type: ui.FieldType.TEXT }).updateDisplayType({ displayType: ui.FieldDisplayType.HIDDEN }).defaultValue = customer; var franchisee = search.lookupFields({ type: search.Type.CUSTOMER, id: customer, columns: "partner" }); form.addField({ id: 'custpage_customer_franchisee', type: ui.FieldType.TEXT, label: 'Franchisee ID' }).updateDisplayType({ displayType: ui.FieldDisplayType.HIDDEN }).defaultValue = franchisee.partner[0].value ; //franchisee ID inlineQty += currentAndScheduledServiceSection(customer); inlineQty += serviceActionsSection(); form.addField({ id: 'preview_table', type: ui.FieldType.INLINEHTML, label: 'preview table' }).defaultValue = inlineQty ; form.addSubmitButton({ label: 'Submit' }); form.addButton({ id: 'back', label: 'Back', }); form.addResetButton(); form.clientScriptFileId = 4569927; context.response.writePage(form); }else{ // redirect.redirect({ // url: 'https://1048144.app.netsuite.com/app/site/hosting/scriptlet.nl?script=1093&deploy=1&compid=1048144', // parameters: params // }); redirect.toSuitelet({ scriptId: 'customscript_sl_service_change_list_2', deploymentId: 'customdeploy_service_change_list_2', isExternal: false, parameters: params }); } } /** * Section displaying the current service details and existing scheduled chnages * @param {*} customerId */ function currentAndScheduledServiceSection(customerId){ // Get all the services associated with this customer var serviceFilter = search.createFilter({ name: 'custrecord_service_customer', join: null, operator: search.Operator.IS, values: customerId }); var serviceSearch = search.load({ type: 'customrecord_service', id: 'customsearch_smc_services' }); serviceSearch.filters.push(serviceFilter); var serviceResult = serviceSearch.run(); var firstService = serviceResult.getRange({ start: 0, end: 1000 }); var inlineQty = '<div class="container row ">'; inlineQty += '<div class="col-md-4 well well-sm" style="background-color: #607799;">'; inlineQty += '<h5 class="text-center">CURRENT SERVICE DETAILS</h5>'; inlineQty += '</div>'; inlineQty += '<div class="col-md-8 well well-sm" style="background-color: #607799;">'; inlineQty += '<h5 class="text-center">SCHEDULED CHANGES</h5>'; inlineQty += '</div>'; inlineQty += '</div>'; if (firstService.length != 0) { serviceResult.each(function(service) { inlineQty += '<div class="container row ">'; inlineQty += '<div class="col-md-4 well">'; //Current Service Details section inlineQty += '<div class="input-group form-group"><span class="input-group-addon" id="address1_text">SERVICE NAME</span><input id="service_name" class="form-control service_name" readonly value="' + service.getText('custrecord_service') + '" /></div>'; inlineQty += '<div class="input-group form-group"><span class="input-group-addon" id="address1_text">CURRENT PRICE | $</span><input id="current_price" class="form-control current_price" readonly value="' + service.getValue('custrecord_service_price') + '" /></div>'; inlineQty += '<div class="input-group form-group"><span class="input-group-addon" id="address1_text">ASSOCIATED PACKAGE</span><input id="associated_package" class="form-control associated_package" readonly value="' + service.getText('custrecord_service_package') + '" /></div>'; inlineQty += '<div class="input-group form-group"><span class="input-group-addon" id="address1_text">DESCRIPTION</span><input id="service_descp" class="form-control service_descp" data-serviceid="' + service.getValue('internalid') + '" value="' + service.getValue('custrecord_service_description') + '" /></div>'; inlineQty += '</div>'; //Scheduled changes searcch var searchedServiceChange = search.load({ id: 'customsearch_smc_service_chg', type: 'customrecord_servicechg' }); //Filter for all service changes services for this customer searchedServiceChange.filters.push(search.createFilter({ name: 'custrecord_servicechg_service', join: null, operator: search.Operator.IS, values: service.getValue({name:'internalid'}) })); searchedServiceChange.filters.push(search.createFilter({ name: 'custrecord_servicechg_status', join: null, operator: search.Operator.NONEOF, values: [2, 3] })); var resultSearchedServiceChg = searchedServiceChange.run(); //Scheduled changes section inlineQty += '<div class="col-md-8 well form-group">'; inlineQty += '<table class="table table-responsive table-striped customer tablesorter"><thead style="color: white;background-color: #607799;"><tr><th>ACTION</th><th>CHANGE TYPE</th><th>DATE EFFECTIVE</th><th>NEW PRICE</th><th>COMM REG</th><th>FREQUENCY</th><th>SCF</th></tr></thead><tbody>'; resultSearchedServiceChg.each(function(searchedServiceChg){ inlineQty += '<tr>'; inlineQty += '<td><button class="btn btn-warning btn-xs edit_class glyphicon glyphicon-pencil" data-dateeffective="' + searchedServiceChg.getValue({name: 'custrecord_servicechg_date_effective'}) + '" data-commreg="' + searchedServiceChg.getValue({name: 'custrecord_servicechg_comm_reg'}) + '" type="button" data-toggle="tooltip" data-placement="right" title="Edit"></button></td>'; inlineQty += '<td>' + searchedServiceChg.getValue({name: 'custrecord_servicechg_type'}) + '</td>'; inlineQty += '<td>' + searchedServiceChg.getValue({name:'custrecord_servicechg_date_effective'}) + '</td>'; inlineQty += '<td>' + searchedServiceChg.getValue({name:'custrecord_servicechg_new_price'}) + '</td>'; inlineQty += '<td>' + searchedServiceChg.getValue({name:'custrecord_servicechg_comm_reg'}) + '</td>'; inlineQty += '<td>' + searchedServiceChg.getText({name:'custrecord_servicechg_new_freq'}) + '</td>'; var fileID = searchedServiceChg.getValue({ name: 'custrecord_scand_form', name: 'CUSTRECORD_SERVICECHG_COMM_REG', summary: null }); if (!isNullorEmpty(fileID)) { var fileRecord = file.load({ id: fileID }); inlineQty += '<td><a href="' + fileRecord.url + '" target="_blank">' + searchedServiceChg.getText({name: "custrecord_scand_form", join: "CUSTRECORD_SERVICECHG_COMM_REG", summary: null}) + '</a></td>'; } else { inlineQty += '<td></td>'; } inlineQty += '</tr>'; return true; }); inlineQty += '</tbody></table>'; inlineQty += '</div>'; inlineQty += '</div>'; return true; }); } return inlineQty; } /** * Section for the New Scheduled Change and Cancel Service buttons */ function serviceActionsSection(){ var inlineQty = '<div class="form-group container row_button">'; inlineQty += '<div class="row">'; inlineQty += '<div class="col-xs-4 schedule_change_section"><input type="button" id="create_new" class="form-control btn btn-success btn-xs create_new" value="NEW SCHEDULED CHANGE" data-toggle="tooltip" data-placement="right" title="NEW SCHEDULED CHANGE" /></div>'; inlineQty += '<div class="col-xs-4 cancel_service_section"><input type="button" id="cancel_service" class="form-control btn btn-danger btn-xs cancel_service" value="CANCEL SERVICE" data-toggle="tooltip" data-placement="right" title="CANCEL SERVICE" /></div>'; inlineQty += '</div>'; inlineQty += '</div>'; return inlineQty; } /** * Is Null or Empty. * * @param {Object} strVal */ function isNullorEmpty(strVal) { return (strVal == null || strVal == '' || strVal == 'null' || strVal == undefined || strVal == 'undefined' || strVal == '- None -'); } return { onRequest: onRequest }; });
563
[{"tag": "KEY", "value": "sha384-aJ21OjlMXNL5UyIl/XNwTMqvzeRMZH2w8c5cRVpzpU8Y5bApTppSuUkhZXN0VxHd", "start": 1739, "end": 1810}, {"tag": "KEY", "value": "sha384-HSMxcRTRxnN+Bdg0JdbxYKrThecOKuH5zCYotlSAcp1+c8xmyTe9GYg1l9a69psu", "start": 1517, "end": 1588}, {"tag": "KEY", "value": "sha384-nvAa0+6Qg9clwYCGGPpDQLVpLNn0fRaROjHqs13t4Ggj3Ez50XnGQqc/r8MhnRDZ", "start": 1237, "end": 1308}]
true
3
/** *@NApiVersion 2.0 *@NScriptType Suitelet * * Module Description - * * NSVersion Date Author * 2.00 2020-12-19 13:12:36 Ravija Maheshwari * * @Last Modified by: Ravija * @Last Modified time: 2020-12-20 11:55 */ define(['N/ui/serverWidget', 'N/email', 'N/runtime', 'N/search', 'N/record', 'N/http', 'N/log', 'N/redirect', 'N/format', 'N/currentRecord', 'N/file'], function(ui, email, runtime, search, record, http, log, redirect, format, currentRecord, file) { function onRequest(context) { //Setup var baseURL = 'https://system.na2.netsuite.com'; if (runtime.EnvType == "SANDBOX") { baseURL = 'https://system.sandbox.netsuite.com'; } var zee = 0; var role = runtime.getCurrentUser().role; if (role == 1000) { zee = runtime.getCurrentUser().id; } else if (role == 3) { //Administrator zee = 6; //test } else if (role == 1032) { // System Support zee = 425904; //test-AR } if(context.request.method === 'GET'){ //Load Jquery var inlineQty = '<script src="https://code.jquery.com/jquery-1.12.4.min.js" integrity="kgfhvu9qnh3mr6eel97y6fq2hezzol8z" crossorigin="anonymous"></script>'; // Load Bootstrap inlineQty += '<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/3.4.1/css/bootstrap.min.css" integrity="9jnerlff23u8ed01np9g6ysbhsh0dvcs" crossorigin="anonymous">'; inlineQty += '<script src="https://stackpath.bootstrapcdn.com/bootstrap/3.4.1/js/bootstrap.min.js" integrity="949d1u22cbffbrarjh182eig55721odj" crossorigin="anonymous"></script>'; // Load Netsuite stylesheet and script inlineQty += '<link rel="stylesheet" href="https://1048144.app.netsuite.com/core/media/media.nl?id=2060796&c=1048144&h=9ee6accfd476c9cae718&_xt=.css"/>'; inlineQty += '<script src="https://1048144.app.netsuite.com/core/media/media.nl?id=2060797&c=1048144&h=ef2cda20731d146b5e98&_xt=.js"></script>'; inlineQty += '<link type="text/css" rel="stylesheet" href="https://1048144.app.netsuite.com/core/media/media.nl?id=2090583&c=1048144&h=a0ef6ac4e28f91203dfe&_xt=.css">'; inlineQty += '<style>.mandatory{color:red;}</style>'; inlineQty += '<link href="//netdna.bootstrapcdn.com/bootstrap/3.3.2/css/bootstrap.min.css" rel="stylesheet"><script src="//netdna.bootstrapcdn.com/bootstrap/3.3.2/js/bootstrap.min.js"></script><link rel="stylesheet" href="https://1048144.app.netsuite.com/core/media/media.nl?id=2060796&c=1048144&h=9ee6accfd476c9cae718&_xt=.css"/><script src="https://1048144.app.netsuite.com/core/media/media.nl?id=2060797&c=1048144&h=ef2cda20731d146b5e98&_xt=.js"></script><link type="text/css" rel="stylesheet" href="https://1048144.app.netsuite.com/core/media/media.nl?id=2090583&c=1048144&h=a0ef6ac4e28f91203dfe&_xt=.css">'; //Set the customer id if(!isNullorEmpty(context.request.parameters.custparam_params)){ var params = context.request.parameters.custparam_params; params = JSON.parse(params); var customer = parseInt(params.custid); }else{ var customer = parseInt(context.request.parameters.custid); } var recCustomer = record.load({ type: record.Type.CUSTOMER, id: customer, isDynamic: true }); var franchisee = recCustomer.getValue({fieldId: 'partner'}); var form = ui.createForm({ title: 'Service Management for : <a href="' + baseURL + '/app/common/entity/custjob.nl?id=' + customer + '">' + recCustomer.getValue({fieldId: 'entityid'}) +'</a> ' + recCustomer.getValue({fieldId: 'companyname'}) }); form.addField({ id: 'custpage_customer_id', label: 'Customer ID', type: ui.FieldType.TEXT }).updateDisplayType({ displayType: ui.FieldDisplayType.HIDDEN }).defaultValue = customer; var franchisee = search.lookupFields({ type: search.Type.CUSTOMER, id: customer, columns: "partner" }); form.addField({ id: 'custpage_customer_franchisee', type: ui.FieldType.TEXT, label: 'Franchisee ID' }).updateDisplayType({ displayType: ui.FieldDisplayType.HIDDEN }).defaultValue = franchisee.partner[0].value ; //franchisee ID inlineQty += currentAndScheduledServiceSection(customer); inlineQty += serviceActionsSection(); form.addField({ id: 'preview_table', type: ui.FieldType.INLINEHTML, label: 'preview table' }).defaultValue = inlineQty ; form.addSubmitButton({ label: 'Submit' }); form.addButton({ id: 'back', label: 'Back', }); form.addResetButton(); form.clientScriptFileId = 4569927; context.response.writePage(form); }else{ // redirect.redirect({ // url: 'https://1048144.app.netsuite.com/app/site/hosting/scriptlet.nl?script=1093&deploy=1&compid=1048144', // parameters: params // }); redirect.toSuitelet({ scriptId: 'customscript_sl_service_change_list_2', deploymentId: 'customdeploy_service_change_list_2', isExternal: false, parameters: params }); } } /** * Section displaying the current service details and existing scheduled chnages * @param {*} customerId */ function currentAndScheduledServiceSection(customerId){ // Get all the services associated with this customer var serviceFilter = search.createFilter({ name: 'custrecord_service_customer', join: null, operator: search.Operator.IS, values: customerId }); var serviceSearch = search.load({ type: 'customrecord_service', id: 'customsearch_smc_services' }); serviceSearch.filters.push(serviceFilter); var serviceResult = serviceSearch.run(); var firstService = serviceResult.getRange({ start: 0, end: 1000 }); var inlineQty = '<div class="container row ">'; inlineQty += '<div class="col-md-4 well well-sm" style="background-color: #607799;">'; inlineQty += '<h5 class="text-center">CURRENT SERVICE DETAILS</h5>'; inlineQty += '</div>'; inlineQty += '<div class="col-md-8 well well-sm" style="background-color: #607799;">'; inlineQty += '<h5 class="text-center">SCHEDULED CHANGES</h5>'; inlineQty += '</div>'; inlineQty += '</div>'; if (firstService.length != 0) { serviceResult.each(function(service) { inlineQty += '<div class="container row ">'; inlineQty += '<div class="col-md-4 well">'; //Current Service Details section inlineQty += '<div class="input-group form-group"><span class="input-group-addon" id="address1_text">SERVICE NAME</span><input id="service_name" class="form-control service_name" readonly value="' + service.getText('custrecord_service') + '" /></div>'; inlineQty += '<div class="input-group form-group"><span class="input-group-addon" id="address1_text">CURRENT PRICE | $</span><input id="current_price" class="form-control current_price" readonly value="' + service.getValue('custrecord_service_price') + '" /></div>'; inlineQty += '<div class="input-group form-group"><span class="input-group-addon" id="address1_text">ASSOCIATED PACKAGE</span><input id="associated_package" class="form-control associated_package" readonly value="' + service.getText('custrecord_service_package') + '" /></div>'; inlineQty += '<div class="input-group form-group"><span class="input-group-addon" id="address1_text">DESCRIPTION</span><input id="service_descp" class="form-control service_descp" data-serviceid="' + service.getValue('internalid') + '" value="' + service.getValue('custrecord_service_description') + '" /></div>'; inlineQty += '</div>'; //Scheduled changes searcch var searchedServiceChange = search.load({ id: 'customsearch_smc_service_chg', type: 'customrecord_servicechg' }); //Filter for all service changes services for this customer searchedServiceChange.filters.push(search.createFilter({ name: 'custrecord_servicechg_service', join: null, operator: search.Operator.IS, values: service.getValue({name:'internalid'}) })); searchedServiceChange.filters.push(search.createFilter({ name: 'custrecord_servicechg_status', join: null, operator: search.Operator.NONEOF, values: [2, 3] })); var resultSearchedServiceChg = searchedServiceChange.run(); //Scheduled changes section inlineQty += '<div class="col-md-8 well form-group">'; inlineQty += '<table class="table table-responsive table-striped customer tablesorter"><thead style="color: white;background-color: #607799;"><tr><th>ACTION</th><th>CHANGE TYPE</th><th>DATE EFFECTIVE</th><th>NEW PRICE</th><th>COMM REG</th><th>FREQUENCY</th><th>SCF</th></tr></thead><tbody>'; resultSearchedServiceChg.each(function(searchedServiceChg){ inlineQty += '<tr>'; inlineQty += '<td><button class="btn btn-warning btn-xs edit_class glyphicon glyphicon-pencil" data-dateeffective="' + searchedServiceChg.getValue({name: 'custrecord_servicechg_date_effective'}) + '" data-commreg="' + searchedServiceChg.getValue({name: 'custrecord_servicechg_comm_reg'}) + '" type="button" data-toggle="tooltip" data-placement="right" title="Edit"></button></td>'; inlineQty += '<td>' + searchedServiceChg.getValue({name: 'custrecord_servicechg_type'}) + '</td>'; inlineQty += '<td>' + searchedServiceChg.getValue({name:'custrecord_servicechg_date_effective'}) + '</td>'; inlineQty += '<td>' + searchedServiceChg.getValue({name:'custrecord_servicechg_new_price'}) + '</td>'; inlineQty += '<td>' + searchedServiceChg.getValue({name:'custrecord_servicechg_comm_reg'}) + '</td>'; inlineQty += '<td>' + searchedServiceChg.getText({name:'custrecord_servicechg_new_freq'}) + '</td>'; var fileID = searchedServiceChg.getValue({ name: 'custrecord_scand_form', name: 'CUSTRECORD_SERVICECHG_COMM_REG', summary: null }); if (!isNullorEmpty(fileID)) { var fileRecord = file.load({ id: fileID }); inlineQty += '<td><a href="' + fileRecord.url + '" target="_blank">' + searchedServiceChg.getText({name: "custrecord_scand_form", join: "CUSTRECORD_SERVICECHG_COMM_REG", summary: null}) + '</a></td>'; } else { inlineQty += '<td></td>'; } inlineQty += '</tr>'; return true; }); inlineQty += '</tbody></table>'; inlineQty += '</div>'; inlineQty += '</div>'; return true; }); } return inlineQty; } /** * Section for the New Scheduled Change and Cancel Service buttons */ function serviceActionsSection(){ var inlineQty = '<div class="form-group container row_button">'; inlineQty += '<div class="row">'; inlineQty += '<div class="col-xs-4 schedule_change_section"><input type="button" id="create_new" class="form-control btn btn-success btn-xs create_new" value="NEW SCHEDULED CHANGE" data-toggle="tooltip" data-placement="right" title="NEW SCHEDULED CHANGE" /></div>'; inlineQty += '<div class="col-xs-4 cancel_service_section"><input type="button" id="cancel_service" class="form-control btn btn-danger btn-xs cancel_service" value="CANCEL SERVICE" data-toggle="tooltip" data-placement="right" title="CANCEL SERVICE" /></div>'; inlineQty += '</div>'; inlineQty += '</div>'; return inlineQty; } /** * Is Null or Empty. * * @param {Object} strVal */ function isNullorEmpty(strVal) { return (strVal == null || strVal == '' || strVal == 'null' || strVal == undefined || strVal == 'undefined' || strVal == '- None -'); } return { onRequest: onRequest }; });
true
/** *@NApiVersion 2.0 *@NScriptType Suitelet * * Module Description - * * NSVersion Date Author * 2.00 2020-12-19 13:12:36 Ravija Maheshwari * * @Last Modified by: Ravija * @Last Modified time: 2020-12-20 11:55 */ define(['N/ui/serverWidget', 'N/email', 'N/runtime', 'N/search', 'N/record', 'N/http', 'N/log', 'N/redirect', 'N/format', 'N/currentRecord', 'N/file'], function(ui, email, runtime, search, record, http, log, redirect, format, currentRecord, file) { function onRequest(context) { //Setup var baseURL = 'https://system.na2.netsuite.com'; if (runtime.EnvType == "SANDBOX") { baseURL = 'https://system.sandbox.netsuite.com'; } var zee = 0; var role = runtime.getCurrentUser().role; if (role == 1000) { zee = runtime.getCurrentUser().id; } else if (role == 3) { //Administrator zee = 6; //test } else if (role == 1032) { // System Support zee = 425904; //test-AR } if(context.request.method === 'GET'){ //Load Jquery var inlineQty = '<script src="https://code.jquery.com/jquery-1.12.4.min.js" integrity="PI:KEY:kgfhvu9qnh3mr6eel97y6fq2hezzol8zEND_PI" crossorigin="anonymous"></script>'; // Load Bootstrap inlineQty += '<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/3.4.1/css/bootstrap.min.css" integrity="PI:KEY:9jnerlff23u8ed01np9g6ysbhsh0dvcsEND_PI" crossorigin="anonymous">'; inlineQty += '<script src="https://stackpath.bootstrapcdn.com/bootstrap/3.4.1/js/bootstrap.min.js" integrity="PI:KEY:949d1u22cbffbrarjh182eig55721odjEND_PI" crossorigin="anonymous"></script>'; // Load Netsuite stylesheet and script inlineQty += '<link rel="stylesheet" href="https://1048144.app.netsuite.com/core/media/media.nl?id=2060796&c=1048144&h=9ee6accfd476c9cae718&_xt=.css"/>'; inlineQty += '<script src="https://1048144.app.netsuite.com/core/media/media.nl?id=2060797&c=1048144&h=ef2cda20731d146b5e98&_xt=.js"></script>'; inlineQty += '<link type="text/css" rel="stylesheet" href="https://1048144.app.netsuite.com/core/media/media.nl?id=2090583&c=1048144&h=a0ef6ac4e28f91203dfe&_xt=.css">'; inlineQty += '<style>.mandatory{color:red;}</style>'; inlineQty += '<link href="//netdna.bootstrapcdn.com/bootstrap/3.3.2/css/bootstrap.min.css" rel="stylesheet"><script src="//netdna.bootstrapcdn.com/bootstrap/3.3.2/js/bootstrap.min.js"></script><link rel="stylesheet" href="https://1048144.app.netsuite.com/core/media/media.nl?id=2060796&c=1048144&h=9ee6accfd476c9cae718&_xt=.css"/><script src="https://1048144.app.netsuite.com/core/media/media.nl?id=2060797&c=1048144&h=ef2cda20731d146b5e98&_xt=.js"></script><link type="text/css" rel="stylesheet" href="https://1048144.app.netsuite.com/core/media/media.nl?id=2090583&c=1048144&h=a0ef6ac4e28f91203dfe&_xt=.css">'; //Set the customer id if(!isNullorEmpty(context.request.parameters.custparam_params)){ var params = context.request.parameters.custparam_params; params = JSON.parse(params); var customer = parseInt(params.custid); }else{ var customer = parseInt(context.request.parameters.custid); } var recCustomer = record.load({ type: record.Type.CUSTOMER, id: customer, isDynamic: true }); var franchisee = recCustomer.getValue({fieldId: 'partner'}); var form = ui.createForm({ title: 'Service Management for : <a href="' + baseURL + '/app/common/entity/custjob.nl?id=' + customer + '">' + recCustomer.getValue({fieldId: 'entityid'}) +'</a> ' + recCustomer.getValue({fieldId: 'companyname'}) }); form.addField({ id: 'custpage_customer_id', label: 'Customer ID', type: ui.FieldType.TEXT }).updateDisplayType({ displayType: ui.FieldDisplayType.HIDDEN }).defaultValue = customer; var franchisee = search.lookupFields({ type: search.Type.CUSTOMER, id: customer, columns: "partner" }); form.addField({ id: 'custpage_customer_franchisee', type: ui.FieldType.TEXT, label: 'Franchisee ID' }).updateDisplayType({ displayType: ui.FieldDisplayType.HIDDEN }).defaultValue = franchisee.partner[0].value ; //franchisee ID inlineQty += currentAndScheduledServiceSection(customer); inlineQty += serviceActionsSection(); form.addField({ id: 'preview_table', type: ui.FieldType.INLINEHTML, label: 'preview table' }).defaultValue = inlineQty ; form.addSubmitButton({ label: 'Submit' }); form.addButton({ id: 'back', label: 'Back', }); form.addResetButton(); form.clientScriptFileId = 4569927; context.response.writePage(form); }else{ // redirect.redirect({ // url: 'https://1048144.app.netsuite.com/app/site/hosting/scriptlet.nl?script=1093&deploy=1&compid=1048144', // parameters: params // }); redirect.toSuitelet({ scriptId: 'customscript_sl_service_change_list_2', deploymentId: 'customdeploy_service_change_list_2', isExternal: false, parameters: params }); } } /** * Section displaying the current service details and existing scheduled chnages * @param {*} customerId */ function currentAndScheduledServiceSection(customerId){ // Get all the services associated with this customer var serviceFilter = search.createFilter({ name: 'custrecord_service_customer', join: null, operator: search.Operator.IS, values: customerId }); var serviceSearch = search.load({ type: 'customrecord_service', id: 'customsearch_smc_services' }); serviceSearch.filters.push(serviceFilter); var serviceResult = serviceSearch.run(); var firstService = serviceResult.getRange({ start: 0, end: 1000 }); var inlineQty = '<div class="container row ">'; inlineQty += '<div class="col-md-4 well well-sm" style="background-color: #607799;">'; inlineQty += '<h5 class="text-center">CURRENT SERVICE DETAILS</h5>'; inlineQty += '</div>'; inlineQty += '<div class="col-md-8 well well-sm" style="background-color: #607799;">'; inlineQty += '<h5 class="text-center">SCHEDULED CHANGES</h5>'; inlineQty += '</div>'; inlineQty += '</div>'; if (firstService.length != 0) { serviceResult.each(function(service) { inlineQty += '<div class="container row ">'; inlineQty += '<div class="col-md-4 well">'; //Current Service Details section inlineQty += '<div class="input-group form-group"><span class="input-group-addon" id="address1_text">SERVICE NAME</span><input id="service_name" class="form-control service_name" readonly value="' + service.getText('custrecord_service') + '" /></div>'; inlineQty += '<div class="input-group form-group"><span class="input-group-addon" id="address1_text">CURRENT PRICE | $</span><input id="current_price" class="form-control current_price" readonly value="' + service.getValue('custrecord_service_price') + '" /></div>'; inlineQty += '<div class="input-group form-group"><span class="input-group-addon" id="address1_text">ASSOCIATED PACKAGE</span><input id="associated_package" class="form-control associated_package" readonly value="' + service.getText('custrecord_service_package') + '" /></div>'; inlineQty += '<div class="input-group form-group"><span class="input-group-addon" id="address1_text">DESCRIPTION</span><input id="service_descp" class="form-control service_descp" data-serviceid="' + service.getValue('internalid') + '" value="' + service.getValue('custrecord_service_description') + '" /></div>'; inlineQty += '</div>'; //Scheduled changes searcch var searchedServiceChange = search.load({ id: 'customsearch_smc_service_chg', type: 'customrecord_servicechg' }); //Filter for all service changes services for this customer searchedServiceChange.filters.push(search.createFilter({ name: 'custrecord_servicechg_service', join: null, operator: search.Operator.IS, values: service.getValue({name:'internalid'}) })); searchedServiceChange.filters.push(search.createFilter({ name: 'custrecord_servicechg_status', join: null, operator: search.Operator.NONEOF, values: [2, 3] })); var resultSearchedServiceChg = searchedServiceChange.run(); //Scheduled changes section inlineQty += '<div class="col-md-8 well form-group">'; inlineQty += '<table class="table table-responsive table-striped customer tablesorter"><thead style="color: white;background-color: #607799;"><tr><th>ACTION</th><th>CHANGE TYPE</th><th>DATE EFFECTIVE</th><th>NEW PRICE</th><th>COMM REG</th><th>FREQUENCY</th><th>SCF</th></tr></thead><tbody>'; resultSearchedServiceChg.each(function(searchedServiceChg){ inlineQty += '<tr>'; inlineQty += '<td><button class="btn btn-warning btn-xs edit_class glyphicon glyphicon-pencil" data-dateeffective="' + searchedServiceChg.getValue({name: 'custrecord_servicechg_date_effective'}) + '" data-commreg="' + searchedServiceChg.getValue({name: 'custrecord_servicechg_comm_reg'}) + '" type="button" data-toggle="tooltip" data-placement="right" title="Edit"></button></td>'; inlineQty += '<td>' + searchedServiceChg.getValue({name: 'custrecord_servicechg_type'}) + '</td>'; inlineQty += '<td>' + searchedServiceChg.getValue({name:'custrecord_servicechg_date_effective'}) + '</td>'; inlineQty += '<td>' + searchedServiceChg.getValue({name:'custrecord_servicechg_new_price'}) + '</td>'; inlineQty += '<td>' + searchedServiceChg.getValue({name:'custrecord_servicechg_comm_reg'}) + '</td>'; inlineQty += '<td>' + searchedServiceChg.getText({name:'custrecord_servicechg_new_freq'}) + '</td>'; var fileID = searchedServiceChg.getValue({ name: 'custrecord_scand_form', name: 'CUSTRECORD_SERVICECHG_COMM_REG', summary: null }); if (!isNullorEmpty(fileID)) { var fileRecord = file.load({ id: fileID }); inlineQty += '<td><a href="' + fileRecord.url + '" target="_blank">' + searchedServiceChg.getText({name: "custrecord_scand_form", join: "CUSTRECORD_SERVICECHG_COMM_REG", summary: null}) + '</a></td>'; } else { inlineQty += '<td></td>'; } inlineQty += '</tr>'; return true; }); inlineQty += '</tbody></table>'; inlineQty += '</div>'; inlineQty += '</div>'; return true; }); } return inlineQty; } /** * Section for the New Scheduled Change and Cancel Service buttons */ function serviceActionsSection(){ var inlineQty = '<div class="form-group container row_button">'; inlineQty += '<div class="row">'; inlineQty += '<div class="col-xs-4 schedule_change_section"><input type="button" id="create_new" class="form-control btn btn-success btn-xs create_new" value="NEW SCHEDULED CHANGE" data-toggle="tooltip" data-placement="right" title="NEW SCHEDULED CHANGE" /></div>'; inlineQty += '<div class="col-xs-4 cancel_service_section"><input type="button" id="cancel_service" class="form-control btn btn-danger btn-xs cancel_service" value="CANCEL SERVICE" data-toggle="tooltip" data-placement="right" title="CANCEL SERVICE" /></div>'; inlineQty += '</div>'; inlineQty += '</div>'; return inlineQty; } /** * Is Null or Empty. * * @param {Object} strVal */ function isNullorEmpty(strVal) { return (strVal == null || strVal == '' || strVal == 'null' || strVal == undefined || strVal == 'undefined' || strVal == '- None -'); } return { onRequest: onRequest }; });
define([], function() { /** * Custom Assembly Unbuild Form * @NApiVersion 2.x * @NModuleScope Public * @NScriptType ClientScript * @author trungpv <trung@lexor.com> */ /* === VARS === */ const MODULE_NAME = 'CUSTOM_ASSEMBLY_UNBUILD'; /* === EVENTS FUNCTIONS === */ /** * Line Init * @param {*} context */ function lineInit(context) { console.log(MODULE_NAME, "lineInit Triggered!", context); return; } /** * Page Init * @param {*} context */ function pageInit(context) { const currentRecord = context.currentRecord; console.log(MODULE_NAME, "pageInit Triggered!", context); const component = currentRecord.getSublist({ sublistId: 'component', }); console.log(MODULE_NAME, "pageInit Triggered!", component); return; } /** * Post Sourcing * @param {*} context */ function postSourcing(context) { console.log(MODULE_NAME, "postSourcing Triggered!", context); return; } /** * Save Record * @param {*} context */ function saveRecord(context) { console.log(MODULE_NAME, "saveRecord Triggered!", context); return true; //Return true if you want to continue saving the record. } /** * Sublist Changed * @param {*} context */ function sublistChanged(context) { console.log(MODULE_NAME, "sublistChanged Triggered!", context); } /** * Validate Delete * @param {*} context */ function validateDelete(context) { console.log(MODULE_NAME, "validateDelete Triggered!", context); return true; //Return true if the line deletion is valid. } /** * Validate Field * @param {*} context */ function validateField(context) { console.log(MODULE_NAME, "validateField Triggered!", context); return true; //Return true to continue with the change. } /** * Validate Insert * @param {*} context */ function validateInsert(context) { console.log(MODULE_NAME, "validateInsert Triggered!", context); return true; //Return true if the line insertion is valid. } /** * Validate Line * @param {*} context */ function validateLine(context) { console.log(MODULE_NAME, "validateLine Triggered!", context); return true; //Return true if the line is valid. } /** * Field Changed * @param {*} context */ function fieldChanged(context) { console.log(MODULE_NAME, "fieldChanged Triggered!", context); return; } /** * Export Events */ var exports = {}; exports.pageInit = pageInit; exports.lineInit = lineInit; exports.postSourcing = postSourcing; exports.saveRecord = saveRecord; exports.sublistChanged = sublistChanged; exports.validateDelete = validateDelete; exports.validateField = validateField; exports.validateInsert = validateInsert; exports.validateLine = validateLine; exports.fieldChanged = fieldChanged; return exports; });
779
[{"tag": "EMAIL", "value": "trung@lexor.com", "start": 165, "end": 180}]
true
1
define([], function() { /** * Custom Assembly Unbuild Form * @NApiVersion 2.x * @NModuleScope Public * @NScriptType ClientScript * @author trungpv <hzdkv@example.com> */ /* === VARS === */ const MODULE_NAME = 'CUSTOM_ASSEMBLY_UNBUILD'; /* === EVENTS FUNCTIONS === */ /** * Line Init * @param {*} context */ function lineInit(context) { console.log(MODULE_NAME, "lineInit Triggered!", context); return; } /** * Page Init * @param {*} context */ function pageInit(context) { const currentRecord = context.currentRecord; console.log(MODULE_NAME, "pageInit Triggered!", context); const component = currentRecord.getSublist({ sublistId: 'component', }); console.log(MODULE_NAME, "pageInit Triggered!", component); return; } /** * Post Sourcing * @param {*} context */ function postSourcing(context) { console.log(MODULE_NAME, "postSourcing Triggered!", context); return; } /** * Save Record * @param {*} context */ function saveRecord(context) { console.log(MODULE_NAME, "saveRecord Triggered!", context); return true; //Return true if you want to continue saving the record. } /** * Sublist Changed * @param {*} context */ function sublistChanged(context) { console.log(MODULE_NAME, "sublistChanged Triggered!", context); } /** * Validate Delete * @param {*} context */ function validateDelete(context) { console.log(MODULE_NAME, "validateDelete Triggered!", context); return true; //Return true if the line deletion is valid. } /** * Validate Field * @param {*} context */ function validateField(context) { console.log(MODULE_NAME, "validateField Triggered!", context); return true; //Return true to continue with the change. } /** * Validate Insert * @param {*} context */ function validateInsert(context) { console.log(MODULE_NAME, "validateInsert Triggered!", context); return true; //Return true if the line insertion is valid. } /** * Validate Line * @param {*} context */ function validateLine(context) { console.log(MODULE_NAME, "validateLine Triggered!", context); return true; //Return true if the line is valid. } /** * Field Changed * @param {*} context */ function fieldChanged(context) { console.log(MODULE_NAME, "fieldChanged Triggered!", context); return; } /** * Export Events */ var exports = {}; exports.pageInit = pageInit; exports.lineInit = lineInit; exports.postSourcing = postSourcing; exports.saveRecord = saveRecord; exports.sublistChanged = sublistChanged; exports.validateDelete = validateDelete; exports.validateField = validateField; exports.validateInsert = validateInsert; exports.validateLine = validateLine; exports.fieldChanged = fieldChanged; return exports; });
true
define([], function() { /** * Custom Assembly Unbuild Form * @NApiVersion 2.x * @NModuleScope Public * @NScriptType ClientScript * @author trungpv <PI:EMAIL:hzdkv@example.comEND_PI> */ /* === VARS === */ const MODULE_NAME = 'CUSTOM_ASSEMBLY_UNBUILD'; /* === EVENTS FUNCTIONS === */ /** * Line Init * @param {*} context */ function lineInit(context) { console.log(MODULE_NAME, "lineInit Triggered!", context); return; } /** * Page Init * @param {*} context */ function pageInit(context) { const currentRecord = context.currentRecord; console.log(MODULE_NAME, "pageInit Triggered!", context); const component = currentRecord.getSublist({ sublistId: 'component', }); console.log(MODULE_NAME, "pageInit Triggered!", component); return; } /** * Post Sourcing * @param {*} context */ function postSourcing(context) { console.log(MODULE_NAME, "postSourcing Triggered!", context); return; } /** * Save Record * @param {*} context */ function saveRecord(context) { console.log(MODULE_NAME, "saveRecord Triggered!", context); return true; //Return true if you want to continue saving the record. } /** * Sublist Changed * @param {*} context */ function sublistChanged(context) { console.log(MODULE_NAME, "sublistChanged Triggered!", context); } /** * Validate Delete * @param {*} context */ function validateDelete(context) { console.log(MODULE_NAME, "validateDelete Triggered!", context); return true; //Return true if the line deletion is valid. } /** * Validate Field * @param {*} context */ function validateField(context) { console.log(MODULE_NAME, "validateField Triggered!", context); return true; //Return true to continue with the change. } /** * Validate Insert * @param {*} context */ function validateInsert(context) { console.log(MODULE_NAME, "validateInsert Triggered!", context); return true; //Return true if the line insertion is valid. } /** * Validate Line * @param {*} context */ function validateLine(context) { console.log(MODULE_NAME, "validateLine Triggered!", context); return true; //Return true if the line is valid. } /** * Field Changed * @param {*} context */ function fieldChanged(context) { console.log(MODULE_NAME, "fieldChanged Triggered!", context); return; } /** * Export Events */ var exports = {}; exports.pageInit = pageInit; exports.lineInit = lineInit; exports.postSourcing = postSourcing; exports.saveRecord = saveRecord; exports.sublistChanged = sublistChanged; exports.validateDelete = validateDelete; exports.validateField = validateField; exports.validateInsert = validateInsert; exports.validateLine = validateLine; exports.fieldChanged = fieldChanged; return exports; });
/** * * @NApiVersion 2.0 * @NScriptType Suitelet * * Description: Separate page for escalating ticket * @Last Modified by: Sruti Desai * */ define(['N/ui/serverWidget', 'N/email', 'N/runtime', 'N/search', 'N/record', 'N/http', 'N/log', 'N/redirect', 'N/format'], function(ui, email, runtime, search, record, http, log, redirect, format) { var baseURL = 'https://1048144.app.netsuite.com'; if (runtime.envType == "SANDBOX") { baseURL = 'https://1048144-sb3.app.netsuite.com'; } var zee = 0; var role = runtime.getCurrentUser().role; var userRole = runtime.getCurrentUser().role; if (role == 1000) { //Franchisee zee = runtime.getCurrentUser(); } function onRequest(context) { if (context.request.method === 'GET') { var ticket_id = null; var customer_id = null; var customer_number = null; var selector_id = null; var selector_number = ''; var selector_type = 'barcode_number'; var date_created = ''; var creator_name = ''; var creator_id = null; var status_value = null; var status = ''; var customer_name = ''; var daytodayphone = ''; var daytodayemail = ''; var accountsphone = ''; var accountsemail = ''; var zee_id = null; var franchisee_name = ''; var zee_main_contact_name = ''; var zee_email = ''; var zee_main_contact_phone = ''; var zee_abn = ''; var date_stock_used = ''; var time_stock_used = ''; var final_delivery_text = ''; var selected_enquiry_status_id = null; var attachments_hyperlink = ''; var maap_bank_account_number = null; var maap_parent_bank_account_number = null; var selected_invoice_method_id = null; var accounts_cc_email = ''; var mpex_po_number = ''; var customer_po_number = ''; var terms = null; var customer_terms = ''; var account_manager = {}; var selected_invoice_cycle_id = null; var usage_report_id_1 = ''; var usage_report_id_2 = ''; var usage_report_id_3 = ''; var usage_report_id_4 = ''; var usage_report_array = []; var list_toll_issues = ''; var list_resolved_toll_issues = ''; var list_mp_ticket_issues = ''; var list_resolved_mp_ticket_issues = ''; var list_invoice_issues = ''; var list_resolved_invoice_issues = ''; var owner_list = ''; var comment = ''; var selected_label_id = null; var list_enquiry_mediums = ''; var total_enquiry_count = 0; var chat_enquiry_count = 0; var phone_enquiry_count = 0; var email_enquiry_count = 0; var list_toll_emails = ''; var params_email = { recipient: '', subject: '', body: '', cc: '', bcc: '', records: {}, attachments_credit_memo_ids: [], attachments_usage_report_ids: [], attachments_invoice_ids: [] }; var customer_issue = ''; var screenshot_file = ''; var browser = ''; var login_email_used = ''; var operating_system = ''; var phone_used = ''; var old_sender_name = ''; var old_sender_phone = ''; var customer_number_email_sent = 'F'; var customer_status_value = ''; var customer_ticket_status = ''; var customer_barcode_number = ''; var receiveremail = ''; var receiverphone = ''; var receivername = ''; var receiverstate = ''; var receiverzip = ''; var receiversuburb = ''; var receiveraddr1 = ''; var receiveraddr2 = ''; var prod_stock_invoice = ''; var barcodempdl = ''; var barcodesource = ''; // Load params var params = context.request.parameters.custparam_params; log.debug({ title: 'Params', details: params }) if (!isNullorEmpty(params)) { params = JSON.parse(params); log.debug({ title: 'Params not empty', details: params }); // Coming from the ticket_contact page or the edit_ticket page if (!isNullorEmpty(params.selector_number) && !isNullorEmpty(params.selector_type)) { selector_number = params.selector_number; selector_type = params.selector_type; //Coming from the ticket_contact page if (!isNullorEmpty(params.custid)) { customer_id = params.custid; } log.debug({ title: 'customer_id after ticket_contact_page : ', details: customer_id }); // Coming from the edit_ticket page if (!isNullorEmpty(params.ticket_id)) { ticket_id = parseInt(params.ticket_id); log.debug({ title: 'ticket id ISS', details: ticket_id }); // Load ticket data var ticketRecord = record.load({ type: 'customrecord_mp_ticket', id: ticket_id }); date_created = ticketRecord.getValue({ fieldId: 'created' }); creator_name = ticketRecord.getText({ fieldId: 'custrecord_creator' }); creator_id = ticketRecord.getValue({ fieldId: 'custrecord_creator' }); status_value = ticketRecord.getValue({ fieldId: 'custrecord_ticket_status' }); status = ticketRecord.getText({ fieldId: 'custrecord_ticket_status' }); customer_id = ticketRecord.getValue({ fieldId: 'custrecord_customer1' }); customer_name = ticketRecord.getText({ fieldId: 'custrecord_customer1' }); zee_id = ticketRecord.getValue({ fieldId: 'custrecord_zee' }); selected_enquiry_status_id = ticketRecord.getValue({ fieldId: 'custrecord_enquiry_status' }); attachments_hyperlink = ticketRecord.getValue({ fieldId: 'custrecord_mp_ticket_attachments' }); selected_label_id = ticketRecord.getValue({ fieldId: 'custrecord_ticket_label' }); list_enquiry_mediums = ticketRecord.getValue({ fieldId: 'custrecord_enquiry_medium' }); list_enquiry_mediums = java2jsArray(list_enquiry_mediums); total_enquiry_count = ticketRecord.getValue({ fieldId: 'custrecord_enquiry_count' }); chat_enquiry_count = ticketRecord.getValue({ fieldId: 'custrecord_chat_enquiry_count' }); phone_enquiry_count = ticketRecord.getValue({ fieldId: 'custrecord_phone_enquiry_count' }); email_enquiry_count = ticketRecord.getValue({ fieldId: 'custrecord_email_enquiry_count' }); customer_issue = ticketRecord.getValue({ fieldId: 'custrecord_customer_issue' }); screenshot_file = ticketRecord.getValue({ fieldId: 'custrecord_screenshot' }); browser = ticketRecord.getValue({ fieldId: 'custrecord_browser' }); login_email_used = ticketRecord.getValue({ fieldId: 'custrecord_login_email' }); operating_system = ticketRecord.getValue({ fieldId: 'custrecord_operating_system' }); phone_used = ticketRecord.getValue({ fieldId: 'custrecord_phone_used' }); customer_number = ticketRecord.getValue({ fieldId: 'custrecord_cust_number' }); old_sender_name = ticketRecord.getValue({ fieldId: 'custrecord_sender_name' }); old_sender_phone = ticketRecord.getValue({ fieldId: 'custrecord_sender_phone' }); customer_number_email_sent = ticketRecord.getValue({ fieldId: 'custrecord_customer_number_email_sent' }); customer_status_value = ticketRecord.getValue({fieldId: 'custrecord_mp_ticket_customer_status'}); customer_ticket_status = ticketRecord.getText({fieldId: 'custrecord_mp_ticket_customer_status'}); customer_barcode_number = ticketRecord.getValue({ fieldId : 'custrecord_barcode_number'}); if (!isNullorEmpty(customer_barcode_number)) { var rec = record.load({ type: 'customrecord_customer_product_stock', id: customer_barcode_number, }); receiveremail = rec.getValue({fieldId: 'custrecord_receiver_email'}); receiverphone = rec.getValue({fieldId: 'custrecord_receiver_phone'}); receivername = rec.getValue({fieldId: 'custrecord_receiver_name'}); receiverstate = rec.getValue({fieldId: 'custrecord_receiver_state'}); receiverzip = rec.getValue({fieldId: 'custrecord_receiver_postcode'}); receiversuburb = rec.getValue({fieldId: 'custrecord_receiver_suburb'}); receiveraddr1 = rec.getValue({fieldId: 'custrecord_receiver_addr1'}); receiveraddr2 = rec.getValue({fieldId: 'custrecord_receiver_addr2'}); prod_stock_invoice = rec.getText({fieldId: 'custrecord_prod_stock_invoice'}); barcodempdl = rec.getValue({fieldId: 'custrecord_mpdl_number'}); barcodesource = rec.getText({fieldId: 'custrecord_barcode_source'}); } if(isNullorEmpty(customer_id) && !isNullorEmpty(customer_number)){ var customer_search = search.load({ type: 'customer', id: 'customsearch_customer_name_2' }); customer_search.filters.push(search.createFilter({ name: 'entityid', operator: 'haskeywords', values: customer_number, })); customer_id = customer_search.run().getRange({ start: 0,end:1 })[0].getId(); } if (!isNullorEmpty(customer_id)) { //Load customer record and franchisee information var customerRecord = record.load({ type: 'customer', id: customer_id }); customer_number = customerRecord.getValue({ fieldId: 'entityid' }); daytodayphone = customerRecord.getValue({ fieldId: 'phone' }); daytodayemail = customerRecord.getValue({ fieldId: 'custentity_email_service' }); terms = customerRecord.getValue({ fieldId: 'terms' }); customer_terms = customerRecord.getValue({ fieldId: 'custentity_finance_terms' }); // Account manager var accountManagerSearch = search.load({ type: 'customer', id: 'customsearch3413' }); accountManagerSearch.filters.push(search.createFilter({ name: 'internalid', join: null, operator: search.Operator.ANYOF, values: customer_id, })) var accountManagerResultSet = accountManagerSearch.run(); var accountManagerResult = accountManagerResultSet.getRange({ start: 0, end: 1 }); accountManagerResult = accountManagerResult[0]; if (!isNullorEmpty(accountManagerResult)) { var account_manager_value = accountManagerResult.getValue({ name: "custrecord_sales_assigned", join: "CUSTRECORD_SALES_CUSTOMER", summary: null }); var account_manager_text = accountManagerResult.getText({ name: "custrecord_sales_assigned", join: "CUSTRECORD_SALES_CUSTOMER", summary: null }); if (!isNullorEmpty(account_manager_value)) { var account_manager_email = search.lookupFields({ type: 'employee', id: account_manager_value, columns: 'email' }); account_manager = { name: account_manager_text, email: account_manager_email }; } } // The Franchisee informations are imported from the customer record if possible. zee_id = customerRecord.getValue({ fieldId: 'partner' }); } if (!isNullorEmpty(zee_id)) { var zeeRecord = record.load({ type: 'partner', id: zee_id }); franchisee_name = zeeRecord.getValue({ fieldId: 'companyname' }); zee_main_contact_name = zeeRecord.getValue({ fieldId: 'custentity3' }); zee_email = zeeRecord.getValue({ fieldId: 'email' }); zee_main_contact_phone = zeeRecord.getValue({ fieldId: 'custentity2' }); zee_abn = zeeRecord.getValue({ fieldId: 'custentity_abn_franchiserecord' }); } else { franchisee_name = ticketRecord.getText({ fieldId: 'custrecord_zee' }); } switch (selector_type) { case 'barcode_number': selector_id = ticketRecord.getValue({ fieldId: 'custrecord_barcode_number' }); var stock_used = ''; if(!isNullorEmpty(selector_id)){ //Come in here only if selector_id is not null stock_used = search.lookupFields({ type: 'customrecord_customer_product_stock', id: selector_id, columns: ['custrecord_cust_date_stock_used', 'custrecord_cust_time_stock_used'] }); log.debug({ title: 'finalDel', details: search.lookupFields({ type: 'customrecord_customer_product_stock', id: selector_id, columns: 'custrecord_cust_prod_stock_final_del' }) }); var finalDelCheck = search.lookupFields({ type: 'customrecord_customer_product_stock', id: selector_id, columns: 'custrecord_cust_prod_stock_final_del' }).custrecord_cust_prod_stock_final_del; if (!isNullorEmpty(finalDelCheck)) { final_delivery_text = search.lookupFields({ type: 'customrecord_customer_product_stock', id: selector_id, columns: 'custrecord_cust_prod_stock_final_del' })["custrecord_cust_prod_stock_final_del"][0]["text"]; } date_stock_used = stock_used.custrecord_cust_date_stock_used; time_stock_used = stock_used.custrecord_cust_time_stock_used; } list_toll_issues = ticketRecord.getValue({ fieldId: 'custrecord_toll_issues' }); list_toll_issues = java2jsArray(list_toll_issues); list_resolved_toll_issues = ticketRecord.getValue({ fieldId: 'custrecord_resolved_toll_issues' }); list_resolved_toll_issues = java2jsArray(list_resolved_toll_issues); list_toll_emails = ticketRecord.getValue({ fieldId: 'custrecord_toll_emails' }); list_toll_emails = java2jsArray(list_toll_emails); break; case 'invoice_number': selector_id = ticketRecord.getValue({ fieldId: 'custrecord_invoice_number' }); var invoiceRecord = record.load({ type: 'invoice', id: selector_id }); accountsphone = customerRecord.getValue({ fieldId: 'altphone' }); accountsemail = customerRecord.getValue({ fieldId: 'email' }); maap_bank_account_number = customerRecord.getValue({ fieldId: 'custentity_maap_bankacctno' }); maap_parent_bank_account_number = customerRecord.getValue({ fieldId: 'custentity_maap_bankacctno_parent' }); selected_invoice_method_id = customerRecord.getValue({ fieldId: 'custentity_invoice_method' }); accounts_cc_email = customerRecord.getValue({ fieldId: 'custentity_accounts_cc_email' }); mpex_po_number = customerRecord.getValue({ fieldId: 'custentity_mpex_po' }); customer_po_number = customerRecord.getValue({ fieldId: 'custentity11' }); selected_invoice_cycle_id = customerRecord.getValue({ fieldId: 'custentity_mpex_invoicing_cycle' }); usage_report_id_1 = invoiceRecord.getValue({ fieldId: 'custbody_mpex_usage_report' }); usage_report_id_2 = invoiceRecord.getValue({ fieldId: 'custbody_mpex_usage_report_2' }); usage_report_id_3 = invoiceRecord.getValue({ fieldId: 'custbody_mpex_usage_report_3' }); usage_report_id_4 = invoiceRecord.getValue({ fieldId: 'custbody_mpex_usage_report_4' }); var usage_report_id_array = [usage_report_id_1, usage_report_id_2, usage_report_id_3, usage_report_id_4]; usage_report_id_array.forEach(function (usage_report_id) { if (!isNullorEmpty(usage_report_id)) { var usage_report_file = file.load({ id: usage_report_id }); usage_report_name = usage_report_file.name; usage_report_link = usage_report_file.url; usage_report_array.push({ id: usage_report_id, name: usage_report_name, url: usage_report_link }); } }); list_invoice_issues = ticketRecord.getValue({ fieldId: 'custrecord_invoice_issues' }); list_invoice_issues = java2jsArray(list_invoice_issues); list_resolved_invoice_issues = ticketRecord.getValue({ fieldId: 'custrecord_resolved_invoice_issues' }); list_resolved_invoice_issues = java2jsArray(list_resolved_invoice_issues); break; } list_mp_ticket_issues = ticketRecord.getValue({ fieldId: 'custrecord_mp_ticket_issue' }); list_mp_ticket_issues = java2jsArray(list_mp_ticket_issues); list_resolved_mp_ticket_issues = ticketRecord.getValue({ fieldId: 'custrecord_resolved_mp_ticket_issue' }); list_resolved_mp_ticket_issues = java2jsArray(list_resolved_mp_ticket_issues); owner_list = ticketRecord.getValue({ fieldId: 'custrecord_owner' }); owner_list = java2jsArray(owner_list); comment = ticketRecord.getValue({ fieldId: 'custrecord_comment' }); } } } var form = ui.createForm({ title: ' ', }); // Load jQuery var inlineHtml = '<script src="https://code.jquery.com/jquery-1.12.4.min.js" integrity="sha384-nvAa0+6Qg9clwYCGGPpDQLVpLNn0fRaROjHqs13t4Ggj3Ez50XnGQqc/r8MhnRDZ" crossorigin="anonymous"></script>'; // Load Tooltip inlineHtml += '<script src="https://unpkg.com/@popperjs/core@2"></script>'; // Load Bootstrap inlineHtml += '<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/3.4.1/css/bootstrap.min.css" integrity="sha384-HSMxcRTRxnN+Bdg0JdbxYKrThecOKuH5zCYotlSAcp1+c8xmyTe9GYg1l9a69psu" crossorigin="anonymous">'; inlineHtml += '<script src="https://stackpath.bootstrapcdn.com/bootstrap/3.4.1/js/bootstrap.min.js" integrity="sha384-aJ21OjlMXNL5UyIl/XNwTMqvzeRMZH2w8c5cRVpzpU8Y5bApTppSuUkhZXN0VxHd" crossorigin="anonymous"></script>'; // Load DataTables inlineHtml += '<link rel="stylesheet" type="text/css" href="//cdn.datatables.net/1.10.21/css/jquery.dataTables.min.css">'; inlineHtml += '<script type="text/javascript" charset="utf8" src="//cdn.datatables.net/1.10.21/js/jquery.dataTables.min.js"></script>'; // Load Summernote css/js inlineHtml += '<link href="https://cdnjs.cloudflare.com/ajax/libs/summernote/0.8.9/summernote.css" rel="stylesheet">'; inlineHtml += '<script src="https://cdnjs.cloudflare.com/ajax/libs/summernote/0.8.9/summernote.js"></script>'; // Load bootstrap-select inlineHtml += '<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap-select@1.13.14/dist/css/bootstrap-select.min.css">'; inlineHtml += '<script src="https://cdn.jsdelivr.net/npm/bootstrap-select@1.13.14/dist/js/bootstrap-select.min.js"></script>'; // Load Netsuite stylesheet and script inlineHtml += '<link rel="stylesheet" href="https://1048144.app.netsuite.com/core/media/media.nl?id=2060796&c=1048144&h=9ee6accfd476c9cae718&_xt=.css"/>'; inlineHtml += '<script src="https://1048144.app.netsuite.com/core/media/media.nl?id=2060797&c=1048144&h=ef2cda20731d146b5e98&_xt=.js"></script>'; inlineHtml += '<link type="text/css" rel="stylesheet" href="https://1048144.app.netsuite.com/core/media/media.nl?id=2090583&c=1048144&h=a0ef6ac4e28f91203dfe&_xt=.css">'; inlineHtml += '<style>.mandatory{color:red;}</style>'; // Define alert window. inlineHtml += '<div class="container" style="margin-top:14px;" hidden><div id="alert" class="alert alert-danger fade in"></div></div>'; // Define information window. inlineHtml += '<div class="container" hidden><p id="info" class="alert alert-info"></p></div>'; //inlineHtml += '<div style="background-color: #CFE0CE; min-height: 100vh; margin-top: -15px; padding-bottom: 50px"><br/>'; inlineHtml += '<div style="margin-top: -40px"><br/>'; inlineHtml += escalateButton(status_value); inlineHtml += '<h1 style="font-size: 25px; font-weight: 700; color: #103D39; text-align: center">Escalate Ticket - MPSD' + ticket_id + '</h1>'; //Tabs inlineHtml += tabsSection(customer_number, ticket_id, selector_number, selector_id, selector_type, status_value, date_created, creator_id, creator_name, status, customer_id, customer_name, daytodayphone, daytodayemail, accountsphone, accountsemail, maap_bank_account_number, maap_parent_bank_account_number, zee_id, franchisee_name, zee_main_contact_name, zee_email, zee_main_contact_phone, zee_abn, date_stock_used, time_stock_used, final_delivery_text, selected_enquiry_status_id,attachments_hyperlink, selected_enquiry_status_id, owner_list, list_toll_issues, list_resolved_toll_issues, comment, account_manager, list_toll_emails, customer_ticket_status, receiveremail, receiverphone, receivername, receiverstate, receiverzip, receiversuburb, receiveraddr1, receiveraddr2, barcodempdl, barcodesource, prod_stock_invoice) inlineHtml += '</div>'; form.addField({ id: 'preview_table', type: ui.FieldType.INLINEHTML, label: 'preview_table' }).updateBreakType({ breakType: ui.FieldBreakType.STARTROW }).defaultValue = inlineHtml; form.addField({ id: 'custpage_selector_number', type: ui.FieldType.TEXT, label: 'Selector Number' }).updateDisplayType({ displayType: ui.FieldDisplayType.HIDDEN }).defaultValue = selector_number; form.addField({ id: 'custpage_selector_type', type: ui.FieldType.TEXT, label: 'Selector Type' }).updateDisplayType({ displayType: ui.FieldDisplayType.HIDDEN }).defaultValue = selector_type; if (!isNullorEmpty(ticket_id)) { form.addField({ id: 'custpage_ticket_id', type: ui.FieldType.TEXT, label: 'Ticket ID' }).updateDisplayType({ displayType: ui.FieldDisplayType.HIDDEN }).defaultValue = ticket_id; } else { form.addField({ id: 'custpage_ticket_id', type: ui.FieldType.TEXT, label: 'Ticket ID' }).updateDisplayType({ displayType: ui.FieldDisplayType.HIDDEN }); } form.addField({ id: 'custpage_selector_id', type: ui.FieldType.TEXT, label: 'Selector ID' }).updateDisplayType({ displayType: ui.FieldDisplayType.HIDDEN }).defaultValue = selector_id; form.addField({ id: 'custpage_selector_issue', type: ui.FieldType.TEXT, label: 'Barcode issue' }).updateDisplayType({ displayType: ui.FieldDisplayType.HIDDEN }).defaultValue = 'F'; form.addField({ id: 'custpage_customer_id', type: ui.FieldType.TEXT, label: 'Customer ID' }).updateDisplayType({ displayType: ui.FieldDisplayType.HIDDEN }).defaultValue = customer_id; form.addField({ id: 'custpage_customer_number', type: ui.FieldType.TEXT, label: 'Customer Number' }).updateDisplayType({ displayType: ui.FieldDisplayType.HIDDEN }).defaultValue = customer_number; form.addField({ id: 'custpage_zee_id', type: ui.FieldType.TEXT, label: 'Franchisee ID' }).updateDisplayType({ displayType: ui.FieldDisplayType.HIDDEN }).defaultValue = zee_id; form.addField({ id: 'custpage_ticket_status_value', type: ui.FieldType.TEXT, label: 'Status Value' }).updateDisplayType({ displayType: ui.FieldDisplayType.HIDDEN }).defaultValue = status_value; form.addField({ id: 'custpage_created_ticket', type: ui.FieldType.TEXT, label: 'Created Ticket' }).updateDisplayType({ displayType: ui.FieldDisplayType.HIDDEN }).defaultValue = 'F'; form.addField({ id: 'custpage_usage_report_array', type: ui.FieldType.TEXT, label: 'Usage Reports' }).updateDisplayType({ displayType: ui.FieldDisplayType.HIDDEN }).defaultValue = JSON.stringify(usage_report_array); form.addField({ id: 'custpage_param_email', type: ui.FieldType.TEXT, label: 'Email parameters' }).updateDisplayType({ displayType: ui.FieldDisplayType.HIDDEN }).defaultValue = JSON.stringify(params_email); form.addField({ id: 'custpage_ss_image', type: ui.FieldType.TEXT, label: 'Screenshot Image' }).updateDisplayType({ displayType: ui.FieldDisplayType.HIDDEN }).defaultValue = screenshot_file; form.addField({ id: 'custpage_customer_number_email_sent', type: ui.FieldType.TEXT, label: 'Customer Email Sent' }).updateDisplayType({ displayType: ui.FieldDisplayType.HIDDEN }).defaultValue = customer_number_email_sent; form.clientScriptFileId = 4813457;//SB=4797047 PROD = 4813457 context.response.writePage(form); } else { } } /** * The output of .getFieldValues is a java String Array. * We want to convert it to a javaScript Array in order to read its values. * @param {Ljava.lang.String} javaArray * @return {Array} jsArray */ function java2jsArray(javaArray) { var jsArray = new Array; if (!isNullorEmpty(javaArray)) { javaArray.forEach(function(javaValue) { var jsValue = javaValue.toString(); jsArray.push(jsValue); }) } return jsArray; } /** * The "Customer number" input field. If there is a Ticket ID, then we are on the Edit Ticket page and * this field is pre-filled. * @param {*} customer_number */ function customerNumberSection(customer_number, ticket_id){ if(isNullorEmpty(customer_number)){ customer_number = ''; } // var disable = isNullorEmpty(ticket_id) ? '': 'disabled'; // Ticket details header var inlineQty = '<div class="form-group container tickets_details_header_section">'; inlineQty += '<div class="row">'; inlineQty += '<div class="col-xs-12 heading2" >'; inlineQty += '<h4><span style="background-color: #379E8F" class="label label-default col-xs-12">TICKET DETAILS</span></h4>'; inlineQty += '</div></div></div>'; // Customer number section inlineQty += '<div class="form-group container customer_number_section">'; inlineQty += '<div class="row">'; //Customer number field inlineQty += '<div class="col-xs-12 customer_number">'; inlineQty += '<div class="input-group">'; inlineQty += '<span class="input-group-addon" id="customer_number_text">CUSTOMER NUMBER</span>'; if(customer_number == '' && isNullorEmpty(ticket_id)){ inlineQty += '<input id="customer_number_value" value=" '+ customer_number +' " class="form-control customer_number">'; }else{ inlineQty += '<input id="customer_number_value" value=" '+ customer_number +' " class="form-control customer_number" disabled>'; } inlineQty += '</div></div></div></div>'; //Datatable for all tickets asscoiated to current customer number // inlineQty += '<div class="row">'; // inlineQty += '<div class="form-group container customer_number_tickets">'; // inlineQty += '<style> table {font-size: 12px;text-align: center;border: none;} {font-size: 14px;} table th{text-align: center;} .dataTables_wrapper{width:78%; margin-bottom:40px; margin-left: auto; margin-right: auto; margin-top: auto;} </style>'; // inlineQty += '<table cellpadding="15" id="customer_number_tickets_preview" class="table table-responsive table-striped customer tablesorter" cellspacing="0" style="width: 100%;">'; // inlineQty += '<thead style="color: white;background-color: #607799;">'; // inlineQty += '<tr class="text-center">'; // inlineQty += '</tr>'; // inlineQty += '</thead></table>'; // inlineQty += '</div></div>'; return inlineQty; } function escalateButton(status) { if (status < 11) { return '<button style="margin-left: 10px; margin-right: 5px; background-color: #FBEA51; color: #103D39; font-weight: 700; border-color: transparent; border-width: 2px; border-radius: 15px; height: 30px" type="button" id="escalationbtn" onclick="">Escalate to 1st Escalation</button>'; } else if (status == 11) { var html = '<button style="margin-left: 10px; margin-right: 5px; background-color: #FBEA51; color: #103D39; font-weight: 700; border-color: transparent; border-width: 2px; border-radius: 15px; height: 30px" type="button" id="escalationbtn" onclick="">Escalate to 2nd Escalation</button>'; html += '<button style="margin-left: 5px; margin-right: 5px; background-color: #FBEA51; color: #103D39; font-weight: 700; border-color: transparent; border-width: 2px; border-radius: 15px; height: 30px" type="button" id="removeescalationbtn" onclick="">Remove Escalation</button>'; return html; }else if (status == 12) { var html = '<button style="margin-left: 10px; margin-right: 5px; background-color: #FBEA51; color: #103D39; font-weight: 700; border-color: transparent; border-width: 2px; border-radius: 15px; height: 30px" type="button" id="escalationbtn" onclick="">Escalate to 3rd Escalation</button>'; html += '<button style="margin-left: 5px; margin-right: 5px; background-color: #FBEA51; color: #103D39; font-weight: 700; border-color: transparent; border-width: 2px; border-radius: 15px; height: 30px" type="button" id="removeescalationbtn" onclick="">Remove Escalation</button>'; return html; } else if (status == 13) { var html = '<button style="margin-left: 10px; margin-right: 5px; background-color: #FBEA51; color: #103D39; font-weight: 700; border-color: transparent; border-width: 2px; border-radius: 15px; height: 30px" type="button" id="escalationbtn" onclick="">Escalate to Final Escalation</button>'; html += '<button style="margin-left: 5px; margin-right: 5px; background-color: #FBEA51; color: #103D39; font-weight: 700; border-color: transparent; border-width: 2px; border-radius: 15px; height: 30px" type="button" id="removeescalationbtn" onclick="">Remove Escalation</button>'; return html; } else { return '<button style="margin-left: 10px; margin-right: 5px; background-color: #FBEA51; color: #103D39; font-weight: 700; border-color: transparent; border-width: 2px; border-radius: 15px; height: 30px" type="button" id="removeescalationbtn" onclick="">Remove Escalation</button>'; } } /** * The "Barcode number" OR "Invoice Number" input field. * If there is a TICKET ID, we are in the "Edit Ticket", so we display the Ticket ID field and the selector field is disabled. * @param {Number} ticket_id * @param {String} selector_number * @param {Number} selector_id * @param {String} selector_type * @param {Number} status_value * @return {String} inlineQty */ function selectorSection(ticket_id, selector_number, selector_id, selector_type, status_value) { if (isNullorEmpty(selector_number)) { selector_number = ''; } var inlineQty = '<div class="form-group container selector_section">'; inlineQty += '<div class="row">'; if (!isNullorEmpty(ticket_id)) { // Ticket ID field inlineQty += '<div class="col-xs-6 ticket_id">'; inlineQty += '<div class="input-group">'; inlineQty += '<span class="input-group-addon" id="ticket_id_text">TICKET ID</span>'; inlineQty += '<input id="ticket_id" value="MPSD' + ticket_id + '" class="form-control ticket_id" disabled />'; inlineQty += '</div></div>'; // Selector Number field inlineQty += '<div class="col-xs-6 selector_number">'; inlineQty += '<div class="input-group">'; switch (selector_type) { case 'barcode_number': inlineQty += '<span class="input-group-addon" id="selector_text">BARCODE NUMBER</span>'; break; case 'invoice_number': inlineQty += '<span class="input-group-addon" id="selector_text">INVOICE NUMBER</span>'; break; } inlineQty += '<input id="selector_value" value="' + selector_number + '" class="form-control selector_value" disabled>'; if (selector_type == 'invoice_number') { // Open Invoice record inlineQty += '<div class="input-group-btn">'; inlineQty += '<button id="open_inv" type="button" class="btn btn-default link_inv" data-inv-id="' + selector_id + '" data-toggle="tooltip" data-placement="top" title="Open Invoice">'; inlineQty += '<span class="glyphicon glyphicon-link"></span>'; inlineQty += '</button>'; inlineQty += '</div>'; // Attach Invoice to email if (isTicketNotClosed(status_value)) { inlineQty += '<div class="input-group-btn"><button style="background-color: #379E8F" id="add_inv" type="button" class="btn btn-success add_inv" data-inv-id="' + selector_id + '" data-toggle="tooltip" data-placement="right" title="Attach to email">'; inlineQty += '<span class="glyphicon glyphicon-plus"></span>'; inlineQty += '</button></div>'; } } inlineQty += '</div></div></div></div>'; } else { inlineQty += '<div class="col-xs-12 selector_number">'; inlineQty += '<div class="input-group">'; //Input group addon text switch (selector_type) { case 'barcode_number': inlineQty += '<span class="input-group-addon" id="selector_text">BARCODE NUMBER</span>'; break; case 'invoice_number': inlineQty += '<span class="input-group-addon" id="selector_text">INVOICE NUMBER</span>'; break; case 'customer_issue': inlineQty += '<span class="input-group-addon" id="selector_text">CUSTOMER ISSUE</span>'; break; } inlineQty += '<div class="input-group-btn">'; inlineQty += '<button tabindex="-1" data-toggle="dropdown" class="btn btn-default dropdown-toggle" type="button">'; inlineQty += '<span class="caret"></span>'; inlineQty += '<span class="sr-only">Toggle Dropdown</span>'; inlineQty += '</button>'; inlineQty += '<ul class="dropdown-menu hide" style="list-style:none;margin: 2px 0 0;">'; inlineQty += '<li><a href="#">BARCODE NUMBER</a></li>'; inlineQty += '<li><a href="#">INVOICE NUMBER</a></li>'; inlineQty += '<li><a href="#">CUSTOMER APP</a></li>'; inlineQty += '<li><a href="#">CUSTOMER PORTAL</a></li>'; inlineQty += '<li><a href="#">UPDATE LABEL</a></li>'; inlineQty += '</ul>'; inlineQty += '</div>'; //Input text switch (selector_type) { case 'barcode_number': inlineQty += '<input id="selector_value" class="form-control selector_value" placeholder="MPEN123456">'; break; case 'invoice_number': inlineQty += '<input id="selector_value" class="form-control selector_value" placeholder="INV123456">'; break; case 'customer_app': inlineQty += '<input id="selector_value" class="form-control selector_value" placeholder="Customer App" disabled value="Customer App">'; break; case 'customer_portal': inlineQty += '<input id="selector_value" class="form-control selector_value" placeholder="Customer Portal" disabled value="Customer Portal">'; break; case 'update_label': inlineQty += '<input id="selector_value" class="form-control selector_value" placeholder="Update Label" disabled value="Update Label">'; break; } inlineQty += '</div></div></div></div>'; } return inlineQty; } /** * Used to pass the values of `date_from` and `date_to` between the scripts and to Netsuite for the records and the search. * @param {String} date_iso "2020-06-01" * @returns {String} date_netsuite "1/6/2020" */ function dateISOToNetsuite(date_iso) { var date_netsuite = ''; if (!isNullorEmpty(date_iso)) { var date_netsuite = format.format({ value: date_iso, type: format.Type.DATETIME }); } return date_netsuite; } /** * The informations regarding the ticket being edited. * @param {String} date_created * @param {Number} creator_id * @param {String} creator_name * @param {String} status * @return {String} inlineQty */ function ticketSection(date_created, creator_id, creator_name, status, customer_ticket_status) { if (isNullorEmpty(date_created)) { date_created = ''; } if (isNullorEmpty(creator_name)) { creator_name = ''; } if (isNullorEmpty(status)) { status = ''; } var inlineQty = '<div class="form-group container created_status_section">'; inlineQty += '<div class="row">'; // Date created field inlineQty += '<div class="col-xs-6 date_created">'; inlineQty += '<div class="input-group">'; inlineQty += '<span class="input-group-addon" id="date_created_text">DATE CREATED</span>'; inlineQty += '<input id="date_created" value="' + date_created + '" class="form-control date_created" disabled />'; inlineQty += '</div></div>'; // Creator field inlineQty += '<div class="col-xs-6 creator">'; inlineQty += '<div class="input-group">'; inlineQty += '<span class="input-group-addon" id="creator_text">CREATOR</span>'; inlineQty += '<input id="creator" value="' + creator_name + '" data-creator-id="' + creator_id + '" class="form-control creator" disabled />'; inlineQty += '</div></div></div></div>'; // Status Section inlineQty += '<div class="form-group container status_section">'; inlineQty += '<div class="row">'; // Status field inlineQty += '<div class="col-xs-6 status">'; inlineQty += '<div class="input-group">'; inlineQty += '<span class="input-group-addon" id="status_text">STATUS</span>'; inlineQty += '<input id="status" value="' + status + '" class="form-control status" disabled />'; inlineQty += '</div></div>'; // Customer Status field inlineQty += '<div class="col-xs-6 status">'; inlineQty += '<div class="input-group">'; inlineQty += '<span class="input-group-addon" id="status_text">CUSTOMER STATUS</span>'; inlineQty += '<input id="status" value="' + customer_ticket_status + '" class="form-control status" disabled />'; inlineQty += '</div></div></div></div>'; return inlineQty; } /** * The Customer name field. * The customer name field should be automatically filled based on the Selector number value. * @param {String} customer_name * @return {String} inlineQty */ function customerSection(customer_name) { if (isNullorEmpty(customer_name)) { customer_name = ''; } // Customer Section var inlineQty = '<div class="form-group container customer_section">'; inlineQty += '<div class="row">'; // Customer name field inlineQty += '<div class="col-xs-12 customer_name">'; inlineQty += '<div class="input-group">'; inlineQty += '<span class="input-group-addon" id="customer_name_text">CUSTOMER NAME</span>'; inlineQty += '<input id="customer_name" value="' + customer_name + '" class="form-control customer_name" disabled>'; inlineQty += '</div></div></div></div>'; return inlineQty; } /** * The day to day phone and email fields of the customer. * These fields should be automatically filled based on the Selector number value. * @param {String} daytodayphone * @param {String} daytodayemail * @param {Number} status_value * @param {String} selector_type * @return {String} inlineQty */ function daytodayContactSection(daytodayphone, daytodayemail, status_value, selector_type) { if (isNullorEmpty(daytodayphone)) { daytodayphone = ''; } if (isNullorEmpty(daytodayemail)) { daytodayemail = ''; } var disabled = 'disabled'; if ((isFinanceRole(userRole)) && isTicketNotClosed(status_value) && selector_type == 'invoice_number') { disabled = ''; } var inlineQty = '<div class="form-group container daytodaycontact_section">'; inlineQty += '<div class="row">'; // Day to day email field inlineQty += '<div class="col-xs-6 daytodayemail_div">'; inlineQty += '<div class="input-group">'; inlineQty += '<span class="input-group-addon" id="daytodayemail_text">DAY-TO-DAY EMAIL</span>'; inlineQty += '<input id="daytodayemail" type="email" value="' + daytodayemail + '" class="form-control daytodayemail" ' + disabled + ' />'; inlineQty += '<div class="input-group-btn">'; inlineQty += '<button type="button" style="background-color: #379E8F" class="btn btn-success add_as_recipient" data-email="' + daytodayemail + '" data-contact-id="" data-firstname="" data-toggle="tooltip" data-placement="right" title="Add as recipient">'; inlineQty += '<span class="glyphicon glyphicon-envelope"></span>'; inlineQty += '</button>'; inlineQty += '</div>'; inlineQty += '</div></div>'; // Day to day phone field inlineQty += '<div class="col-xs-6 daytodayphone_div">'; inlineQty += '<div class="input-group">'; inlineQty += '<span class="input-group-addon" id="daytodayphone_text">DAY-TO-DAY PHONE</span>'; inlineQty += '<input id="daytodayphone" type="tel" value="' + daytodayphone + '" class="form-control daytodayphone" ' + disabled + ' />'; inlineQty += '<div class="input-group-btn"><button type="button" style="background-color: #379E8F" class="btn btn-success" id="call_daytoday_phone"><span class="glyphicon glyphicon-earphone"></span></button></div>'; inlineQty += '</div></div></div></div>'; return inlineQty; } /** * The accounts phone and email fields of the customer. * These fields should be automatically filled based on the Invoice number value. * @param {String} accountsphone * @param {String} accountsemail * @param {Number} status_value * @param {String} selector_type * @return {String} inlineQty */ function accountsContactSection(accountsphone, accountsemail, status_value, selector_type) { if (isNullorEmpty(accountsphone)) { accountsphone = ''; } if (isNullorEmpty(accountsemail)) { accountsemail = ''; } if (selector_type == 'invoice_number') { var inlineQty = '<div class="form-group container accountscontact_section">'; if (isFinanceRole(userRole) && isTicketNotClosed(status_value)) { var disabled = ''; } else { var disabled = 'disabled'; } } else { var inlineQty = '<div class="form-group container accountscontact_section hide">'; var disabled = 'disabled'; } inlineQty += '<div class="row">'; // Accounts email field inlineQty += '<div class="col-xs-6 accountsemail_div">'; inlineQty += '<div class="input-group">'; inlineQty += '<span class="input-group-addon" id="accountsemail_text">ACCOUNTS EMAIL</span>'; inlineQty += '<input id="accountsemail" type="email" value="' + accountsemail + '" class="form-control accountsemail" ' + disabled + ' />'; inlineQty += '<div class="input-group-btn">'; inlineQty += '<button type="button" class="btn btn-success add_as_recipient" data-email="' + accountsemail + '" data-contact-id="" data-firstname="" data-toggle="tooltip" data-placement="right" title="Add as recipient">'; inlineQty += '<span class="glyphicon glyphicon-envelope"></span>'; inlineQty += '</button>'; inlineQty += '</div>'; inlineQty += '</div></div>'; // Accounts phone field inlineQty += '<div class="col-xs-6 accountsphone_div">'; inlineQty += '<div class="input-group">'; inlineQty += '<span class="input-group-addon" id="accountsphone_text">ACCOUNTS PHONE</span>'; inlineQty += '<input id="accountsphone" type="tel" value="' + accountsphone + '" class="form-control accountsphone" ' + disabled + ' />'; inlineQty += '<div class="input-group-btn"><button type="button" style="background-color: #379E8F" class="btn btn-success" id="call_accounts_phone"><span class="glyphicon glyphicon-earphone"></span></button></div>'; inlineQty += '</div></div></div></div>'; return inlineQty; } /** * * @param {Number} maap_bank_account_number * @param {Number} maap_parent_bank_account_number * @param {String} selector_type * @returns {String} inlineQty */ function maapBankAccountSection(maap_bank_account_number, maap_parent_bank_account_number, selector_type) { switch (selector_type) { case 'barcode_number': var inlineQty = '<div class="form-group container accounts_number_section hide">'; break; case 'invoice_number': var inlineQty = '<div class="form-group container accounts_number_section">'; break; } inlineQty += '<div class="row">'; // MAAP Bank Account # field inlineQty += '<div class="col-xs-6 account_number_div">'; inlineQty += '<div class="input-group">'; inlineQty += '<span class="input-group-addon" id="account_number_text">MAAP BANK ACCOUNT #</span>'; inlineQty += '<input id="account_number" type="number" value="' + maap_bank_account_number + '" class="form-control account_number" disabled />'; inlineQty += '</div></div>'; // MAAP Parent Bank Account # field inlineQty += '<div class="col-xs-6 parent_account_number_div">'; inlineQty += '<div class="input-group">'; inlineQty += '<span class="input-group-addon" id="parent_account_number_text">MAAP PARENT BANK ACCOUNT #</span>'; inlineQty += '<input id="parent_account_number" type="number" value="' + maap_parent_bank_account_number + '" class="form-control parent_account_number" disabled />'; inlineQty += '</div></div></div></div>'; return inlineQty; } /** * The Franchisee name, and its main contact name and phone number fields. * These fields should be automatically filled based on the Selector number value. * @param {String} franchisee_name * @param {String} zee_main_contact_name * @param {String} zee_email * @param {String} zee_main_contact_phone * @param {String} zee_abn * @return {String} inlineQty */ function franchiseeMainContactSection(franchisee_name, zee_main_contact_name, zee_email, zee_main_contact_phone, zee_abn) { if (isNullorEmpty(franchisee_name)) { franchisee_name = ''; } if (isNullorEmpty(zee_main_contact_name)) { zee_main_contact_name = ''; } if (isNullorEmpty(zee_email)) { zee_email = ''; } if (isNullorEmpty(zee_main_contact_phone)) { zee_main_contact_phone = ''; } if (isNullorEmpty(zee_abn)) { zee_abn = ''; } var inlineQty = '<div class="form-group container zee_main_contact_section">'; inlineQty += '<div class="row">'; // Franchisee name field inlineQty += '<div class="col-xs-6 franchisee_name">'; inlineQty += '<div class="input-group">'; inlineQty += '<span class="input-group-addon" id="franchisee_name_text">FRANCHISEE NAME</span>'; inlineQty += '<input id="franchisee_name" value="' + franchisee_name + '" class="form-control franchisee_name" disabled>'; inlineQty += '</div></div>'; // Franchisee main contact name field inlineQty += '<div class="col-xs-6 zee_main_contact_name">'; inlineQty += '<div class="input-group">'; inlineQty += '<span class="input-group-addon" id="zee_main_contact_name_text">MAIN CONTACT</span>'; inlineQty += '<input id="zee_main_contact_name" value="' + zee_main_contact_name + '" class="form-control zee_main_contact_name" disabled>'; inlineQty += '</div></div></div></div>'; // Franchisee contact details inlineQty += '<div class="form-group container zee_main_contact_section">'; inlineQty += '<div class="row">'; // Franchisee email field inlineQty += '<div class="col-xs-12 zee_email">'; inlineQty += '<div class="input-group">'; inlineQty += '<span class="input-group-addon" id="zee_email_text">FRANCHISEE EMAIL</span>'; inlineQty += '<input id="zee_email" type="email" value="' + zee_email + '" class="form-control accountsemail" disabled />'; inlineQty += '<div class="input-group-btn">'; var zee_contact_id = '0'; inlineQty += '<button type="button" style="background-color: #379E8F" class="btn btn-success add_as_recipient" data-email="' + zee_email + '" data-contact-id="' + zee_contact_id + '" data-firstname="' + franchisee_name + '" data-toggle="tooltip" data-placement="right" title="Add as recipient">'; inlineQty += '<span class="glyphicon glyphicon-envelope"></span>'; inlineQty += '</button>'; inlineQty += '</div>'; inlineQty += '</div></div></div></div>'; // Franchisee phone and ABN details inlineQty += '<div class="form-group container zee_main_contact_section">'; inlineQty += '<div class="row">'; // Franchisee main contact phone field inlineQty += '<div class="col-xs-6 zee_main_contact_phone">' inlineQty += '<div class="input-group">' inlineQty += '<span class="input-group-addon" id="zee_main_contact_phone_text">FRANCHISEE PHONE</span>'; inlineQty += '<input id="zee_main_contact_phone" type="tel" value="' + zee_main_contact_phone + '" class="form-control zee_main_contact_phone" disabled />'; inlineQty += '<div class="input-group-btn"><button style="background-color: #379E8F" type="button" class="btn btn-success" id="call_zee_main_contact_phone"><span class="glyphicon glyphicon-earphone"></span></button>'; inlineQty += '</div>'; inlineQty += '</div></div>'; // Franchisee ABN number inlineQty += '<div class="col-xs-6 zee_abn">' inlineQty += '<div class="input-group">' inlineQty += '<span class="input-group-addon" id="zee_abn_text">FRANCHISEE ABN</span>' inlineQty += '<input id="zee_abn" class="form-control zee_abn" value="' + zee_abn + '" disabled>' inlineQty += '</div></div></div></div>'; return inlineQty; } /** * The MPEX Date and Time Stock used fields. * Visible only for the barcode records. * @param {String} selector_type * @param {String} date_stock_used * @param {String} time_stock_used * @return {String} inlineQty */ function mpexStockUsedSection(selector_type, date_stock_used, time_stock_used) { if (isNullorEmpty(date_stock_used)) { date_stock_used = '' } if (isNullorEmpty(time_stock_used)) { time_stock_used = '' } var hide_class = (selector_type == 'barcode_number') ? '' : 'hide'; // MPEX Stock Used Section var inlineQty = '<div class="form-group container mpex_stock_used_section ' + hide_class + '">'; inlineQty += '<div class="row">'; // Date Stock Used inlineQty += ' <div class="col-xs-6 date_stock_used">'; inlineQty += '<div class="input-group">'; inlineQty += '<span class="input-group-addon" id="date_stock_used_text">DATE STOCK USED</span>'; inlineQty += '<input id="date_stock_used" class="form-control date_stock_used" value="' + date_stock_used + '" disabled>'; inlineQty += '</div></div>'; // Time Stock Used inlineQty += '<div class="col-xs-6 time_stock_used">'; inlineQty += '<div class="input-group">'; inlineQty += '<span class="input-group-addon" id="time_stock_used_text">TIME STOCK USED</span>'; inlineQty += '<input id="time_stock_used" class="form-control time_stock_used" value="' + time_stock_used + '" disabled>'; inlineQty += '</div></div></div></div>'; return inlineQty; } /** * The MPEX Final Delivery field is visible only for the barcode records. * The Enquiry Status field is not disabled only for the ticket that have not yet been opened. * @param {Number} status_value * @param {String} selector_type * @param {String} final_delivery_text * @param {Number} selected_enquiry_status_id * @return {String} inlineQty */ function finalDeliveryEnquirySection(status_value, selector_type, final_delivery_text, selected_enquiry_status_id, prod_stock_invoice) { if (isNullorEmpty(final_delivery_text)) { final_delivery_text = '' } if (isNullorEmpty(selected_enquiry_status_id)) { selected_enquiry_status_id = '' } var barcode_hide_class = (selector_type == 'barcode_number') ? '' : 'hide'; var nb_col_enquiry_section = (selector_type == 'barcode_number') ? '6' : '12'; var enquiry_disabled = (isTicketNotClosed(status_value)) ? '' : 'disabled'; // Final Delivery + Enquiry Status Section var inlineQty = '<div class="form-group container final_delivery_enquiry_status_section">'; inlineQty += '<div class="row">'; // Final Delivery inlineQty += '<div class="col-xs-6 final_delivery ' + barcode_hide_class + '">'; inlineQty += '<div class="input-group">'; inlineQty += '<span class="input-group-addon" id="final_delivery_text">FINAL DELIVERY</span>'; inlineQty += '<input id="final_delivery" class="form-control final_delivery" value="' + final_delivery_text + '" disabled>'; inlineQty += '</div></div>'; // Final Delivery inlineQty += '<div class="col-xs-6 invoice ' + barcode_hide_class + '">'; inlineQty += '<div class="input-group">'; inlineQty += '<span class="input-group-addon" id="invoice_text">INVOICE</span>'; inlineQty += '<input id="invoice" class="form-control invoice" value="' + prod_stock_invoice + '" disabled>'; inlineQty += '</div></div>'; inlineQty += '</div></div>'; return inlineQty; } /** * The Attachments field (an editable hyperlink) * @param {String} attachments_hyperlink * @param {Number} status_value * @returns {String} inlineQty */ function attachmentsSection(attachments_hyperlink, status_value) { var inlineQty = ''; if (!isNullorEmpty(attachments_hyperlink)) { var disabled = (isTicketNotClosed(status_value)) ? '' : 'disabled'; inlineQty += '<div class="form-group container attachments_section">'; inlineQty += '<div class="row">'; inlineQty += '<div class="col-xs-12 attachments_div">'; inlineQty += '<div class="input-group">'; inlineQty += '<span class="input-group-addon" id="attachments_text">ATTACHMENTS</span>' inlineQty += '<input id="attachments" class="form-control attachments" type="url" value="' + attachments_hyperlink + '" ' + 'disabled' + '/>'; inlineQty += '</div></div></div></div>'; } return inlineQty; } /** * Section containing enquiry medium type and the enquiry status of the ticket enquiry * @param list_enquiry_mediums {String}atus and * @param total_enquiry_count {Number} * @param selector_type {String} * @param status_value {Number} * @returns {string} */ function enquiryMediumSection(list_enquiry_mediums, selected_enquiry_status_id, selector_type){ //Search for enquiry mediums var hasEnquiryMediums = (!isNullorEmpty(list_enquiry_mediums)); var enquiryMediumColumns = new Array(); enquiryMediumColumns[0] = search.createColumn({ name: 'name' }); enquiryMediumColumns[1] = search.createColumn({ name: 'internalId' }); var enquiryMediumResultSet = search.create({ type: 'customlist_ticket_enquiry_mediums', columns: enquiryMediumColumns, }); //Ticket Enquiry Header // var inlineQty = '<div class="form-group container ticket_enquiry_header_section">'; // inlineQty += '<div class="row">'; // inlineQty += '<div class="col-xs-12 heading2">'; // inlineQty += '<h4><span style="background-color: #379E8F" class="label label-default col-xs-12">TICKET ENQUIRY DETAILS</span></h4>'; // inlineQty += '</div></div></div>'; //Enquiry Medium HTML var inlineQty = '<div class="form-group container enquiry_medium_section">'; inlineQty += '<div class="row">'; inlineQty += '<div class="col-xs-6 enquiry_medium_div">'; inlineQty += '<div class="input-group">'; inlineQty += '<span class="input-group-addon" id="enquiry_medium_text">ENQUIRY MEDIUM</span>'; inlineQty += '<select multiple id="enquiry_medium_status" class="form-control enquiry_medium_status" size="'+ enquiryMediumResultSet.length + '" disabled>'; enquiryMediumResultSet.run().each(function (enquiryMediumResult) { var enquiryMediumName = enquiryMediumResult.getValue('name'); var enquiryMediumId = enquiryMediumResult.getValue('internalId'); var selected = false; if(hasEnquiryMediums){ selected = (list_enquiry_mediums.indexOf(enquiryMediumId) !== -1); } if(selected) { inlineQty += '<option value="' + enquiryMediumId + '"selected>' + enquiryMediumName + '</option>'; }else{ inlineQty += '<option value="' + enquiryMediumId + '">' + enquiryMediumName + '</option>'; } return true; }); inlineQty += '</select>'; inlineQty += '</div></div>'; // Enquiry Status var enquiry_status_columns = new Array(); enquiry_status_columns[0] = search.createColumn({ name: 'name' }); enquiry_status_columns[1] = search.createColumn({ name: 'internalId' }); var enquiryStatusResultSet = search.create({ type: 'customlist_mp_ticket_enquiry', columns: enquiry_status_columns, }); inlineQty += '<div class="col-xs-6 enquiry_status_div">'; inlineQty += '<div class="input-group">'; inlineQty += '<span class="input-group-addon" id="enquiry_status_text">ENQUIRY STATUS</span>'; inlineQty += '<select id="enquiry_status" class="form-control enquiry_status">'; inlineQty += '<option></option>'; enquiryStatusResultSet.run().each(function (enquiryStatusResult) { var enquiry_status_name = enquiryStatusResult.getValue('name'); var enquiry_status_id = enquiryStatusResult.getValue('internalId'); if (enquiry_status_id == selected_enquiry_status_id) { inlineQty += '<option value="' + enquiry_status_id + '" selected>' + enquiry_status_name + '</option>'; } else { inlineQty += '<option value="' + enquiry_status_id + '">' + enquiry_status_name + '</option>'; } return true; }); inlineQty += '</select>'; inlineQty += '</div></div></div></div>'; return inlineQty; } /** * Section containing the total enquiry count and its breakdwn counts of chat, phone and email * @param total_enquiry_count * @param chat_enquiry_count * @param phone_enquiry_count * @param email_enquiry_count * @param selector_type * @returns {string} */ function enquiryCountSection( total_enquiry_count, chat_enquiry_count, phone_enquiry_count, email_enquiry_count, selector_type){ if (isNullorEmpty(total_enquiry_count)) { total_enquiry_count = 0;} if (isNullorEmpty(chat_enquiry_count)) { chat_enquiry_count = 0;} if (isNullorEmpty(phone_enquiry_count)) { phone_enquiry_count = 0;} if (isNullorEmpty(email_enquiry_count)) { email_enquiry_count = 0;} //Total Enquiry Count HTML var inlineQty = '<div class="form-group container enquiry_count_section">'; inlineQty += '<div class="row">'; inlineQty += '<div class="col-xs-12 total_enquiry_count_div">'; inlineQty += '<div class="input-group">'; inlineQty += '<span class="input-group-addon" id="total_enquiry_count_text">ENQUIRY COUNT</span>'; inlineQty += '<input id="total_enquiry_count" class="form-control enquiry_count" value="' + total_enquiry_count + '" disabled />'; inlineQty += '</div></div></div></div>'; //Enquiries by chat count inlineQty += '<div class="form-group container enquiry_count_breakdown_section">'; inlineQty += '<div class="row">'; inlineQty += '<div class="col-xs-4 enquiry_count_by_chat">'; inlineQty += '<div class="input-group">'; inlineQty += '<span class="input-group-addon" id="enquiry_count_by_chat_text"> CHAT ENQUIRY </span>'; inlineQty += '<input id="enquiry_count_by_chat" value="' + chat_enquiry_count + '" class="form-control enquiry_count_by_chat" disabled>'; inlineQty += '<div class="input-group-btn">'; inlineQty += '<button type="button" style="background-color: #379E8F" class="btn btn-success increment_enquiry_count_by_chat" data-firstname="" data-toggle="tooltip" data-placement="right" title="Increment Chat Enquiry Count">'; inlineQty += '<span class="glyphicon glyphicon-plus"></span>'; inlineQty += '</button>'; inlineQty += '<button type="button" class="btn btn-danger decrement_enquiry_count_by_chat" data-firstname="" data-toggle="tooltip" data-placement="right" title="Decrement Chat Enquiry Count">'; inlineQty += '<span class="glyphicon glyphicon-minus"></span>'; inlineQty += '</button>'; inlineQty += '</div></div></div>'; inlineQty += '<div class="col-xs-4 enquiry_count_by_phone">'; inlineQty += '<div class="input-group">'; inlineQty += '<span class="input-group-addon" id="enquiry_count_by_phone_text"> PHONE ENQUIRY </span>'; inlineQty += '<input id="enquiry_count_by_phone" value="' + phone_enquiry_count + '" class="form-control enquiry_count_by_phone" disabled>'; inlineQty += '<div class="input-group-btn">'; inlineQty += '<button type="button" style="background-color: #379E8F" class="btn btn-success increment_enquiry_count_by_phone" data-firstname="" data-toggle="tooltip" data-placement="right" title="Increment Phone Enquiry Count">'; inlineQty += '<span class="glyphicon glyphicon-plus"></span>'; inlineQty += '</button>'; inlineQty += '<button type="button" class="btn btn-danger decrement_enquiry_count_by_phone" data-firstname="" data-toggle="tooltip" data-placement="right" title="Decrement Phone Enquiry Count">'; inlineQty += '<span class="glyphicon glyphicon-minus"></span>'; inlineQty += '</button>'; inlineQty += '</div></div></div>'; inlineQty += '<div class="col-xs-4 enquiry_count_by_email">'; inlineQty += '<div class="input-group">'; inlineQty += '<span class="input-group-addon" id="enquiry_count_by_email_text"> EMAIL ENQUIRY </span>'; inlineQty += '<input id="enquiry_count_by_email" value="' + email_enquiry_count + '" class="form-control enquiry_count_by_email" disabled>'; inlineQty += '<div class="input-group-btn">'; inlineQty += '<button type="button" style="background-color: #379E8F" class="btn btn-success increment_enquiry_count_by_email" data-firstname="" data-toggle="tooltip" data-placement="right" title="Increment Email Enquiry Count">'; inlineQty += '<span class="glyphicon glyphicon-plus"></span>'; inlineQty += '</button>'; inlineQty += '<button type="button" class="btn btn-danger decrement_enquiry_count_by_email" data-firstname="" data-toggle="tooltip" data-placement="right" title="Decrement Email Enquiry Count">'; inlineQty += '<span class="glyphicon glyphicon-minus"></span>'; inlineQty += '</button>'; inlineQty += '</div></div></div></div></div>'; return inlineQty; } /** * @return {String} inlineQty */ function issuesHeader() { var inlineQty = '<div class="form-group container toll_issues_header_section">'; inlineQty += '<div class="row">'; inlineQty += '<div class="col-xs-12 heading1">'; inlineQty += '<h4><span style="background-color: #379E8F" class="form-group label label-default col-xs-12">ISSUES</span></h4>'; inlineQty += '</div></div></div>'; return inlineQty; } /** * @param {Number} status_value * @return {String} inlineQty */ function reminderSection(status_value) { var hide_class = (!isTicketNotClosed(status_value)) ? 'hide' : ''; var inlineQty = '<div class="form-group container reminder_section ' + hide_class + '">'; inlineQty += '<div class="row">'; // Reminder field inlineQty += '<div class="col-xs-12 reminder">'; inlineQty += '<div class="input-group">'; inlineQty += '<span class="input-group-addon" id="reminder_text">REMINDER</span>'; inlineQty += '<input id="reminder" class="form-control reminder" type="date" disabled />'; inlineQty += '</div></div></div></div>'; return inlineQty; } /** * Based on the selected MP Issue, an Owner is allocated to the ticket. * IT issues have priority over the other issues. * Populated with selectOwner() in the pageInit function on the client script. * @param {Number} ticket_id * @param {Array} owner_list * @param {Number} status_value * @return {String} inlineQty */ function ownerSection(ticket_id, owner_list, status_value) { if (isNullorEmpty(ticket_id)) { // If ticket_id is null, owner_list as well. // In that case, only the creator of the ticket is pre-selected as the owner. var userId = runtime.getCurrentUser().toString(); owner_list = [userId]; } var disabled = (!isTicketNotClosed(status_value)) ? 'disabled' : ''; var inlineQty = '<div class="form-group container owner_section">'; inlineQty += '<div class="row">'; inlineQty += '<div class="col-xs-12 owner">'; inlineQty += '<div class="input-group">'; inlineQty += '<span class="input-group-addon" id="owner_text">OWNER<span class="mandatory">*</span></span>'; inlineQty += '<select multiple id="owner" class="form-control owner" ' + 'disabled' + '>'; var employeeSearch = search.load({ type: 'employee', id: 'customsearch_active_employees' }); var employeeResultSet = employeeSearch.run(); employeeResultSet.each(function(employeeResult) { var employee_id = employeeResult.searchId; var employee_firstname = employeeResult.getValue('firstname'); var employee_lastname = employeeResult.getValue('lastname'); var employee_email = employeeResult.getValue('email'); if (owner_list.indexOf(employee_id) != -1) { inlineQty += '<option value="' + employee_id + '" data-email="' + employee_email + '" selected>' + employee_firstname + ' ' + employee_lastname + '</option>'; } else { inlineQty += '<option value="' + employee_id + '" data-email="' + employee_email + '">' + employee_firstname + ' ' + employee_lastname + '</option>'; } return true; }); inlineQty += '</select>'; inlineQty += '</div></div></div></div>'; return inlineQty; } /** * The multiselect TOLL issues dropdown * @param {Array} list_toll_issues * @param {Array} list_resolved_toll_issues * @param {Number} status_value * @param {String} selector_type * @return {String} inlineQty */ function tollIssuesSection(list_toll_issues, list_resolved_toll_issues, status_value, selector_type) { // TOLL Issues var has_toll_issues = (!isNullorEmpty(list_toll_issues)); var toll_issues_columns = new Array(); toll_issues_columns[0] = search.createColumn({ name: 'name' }); toll_issues_columns[1] = search.createColumn({ name: 'internalId' }); var tollIssuesResultSet = search.create({ type: 'customlist_cust_prod_stock_toll_issues', columns: toll_issues_columns }); if (!isTicketNotClosed(status_value) || selector_type != 'barcode_number') { var inlineQty = '<div class="form-group container toll_issues_section hide">'; } else { var inlineQty = '<div class="form-group container toll_issues_section">'; } inlineQty += '<div class="row">'; inlineQty += '<div class="col-xs-12 toll_issues">'; inlineQty += '<div class="input-group"><span class="input-group-addon" id="toll_issues_text">TOLL ISSUES<span class="mandatory">*</span></span>'; inlineQty += '<select multiple id="toll_issues" class="form-control toll_issues" disabled size="' + tollIssuesResultSet.length + '">'; tollIssuesResultSet.run().each(function(tollIssueResult) { var issue_name = tollIssueResult.getValue('name'); var issue_id = tollIssueResult.getValue('internalId'); var selected = false; if (has_toll_issues) { selected = (list_toll_issues.indexOf(issue_id) !== -1); } if (selected) { inlineQty += '<option value="' + issue_id + '" selected>' + issue_name + '</option>'; } else { inlineQty += '<option value="' + issue_id + '">' + issue_name + '</option>'; } return true; }); inlineQty += '</select>'; inlineQty += '</div></div></div></div>'; // Resolved TOLL Issues log.debug({ title: 'list_resolved_toll_issues : ', details: list_resolved_toll_issues }); var has_resolved_toll_issues = (!isNullorEmpty(list_resolved_toll_issues)); if (has_resolved_toll_issues) { var text_resolved_toll_issues = ''; tollIssuesResultSet.run().each(function(tollIssueResult) { var issue_name = tollIssueResult.getValue('name'); var issue_id = tollIssueResult.getValue('internalId'); if (list_resolved_toll_issues.indexOf(issue_id) !== -1) { text_resolved_toll_issues += issue_name + '\n'; } }); log.debug({ title: 'text_resolved_toll_issues : ', details: text_resolved_toll_issues }); inlineQty += '<div class="form-group container resolved_toll_issues_section">'; inlineQty += '<div class="row">'; inlineQty += '<div class="col-xs-12 resolved_toll_issues">'; inlineQty += '<div class="input-group">'; inlineQty += '<span class="input-group-addon" id="resolved_toll_issues_text">RESOLVED TOLL ISSUES</span>'; inlineQty += '<textarea id="resolved_toll_issues" class="form-control resolved_toll_issues" rows="' + list_resolved_toll_issues.length + '" disabled>' + text_resolved_toll_issues.trim() + '</textarea>'; inlineQty += '</div></div></div></div>'; } return inlineQty; }; /** * The free-from text area for comments. * @param {String} comment * @param {String} selector_type * @param {Number} status_value * @return {String} inlineQty */ function commentSection(comment, selector_type, status_value) { if (isNullorEmpty(comment)) { comment = ''; } else { comment += '\n'; } switch (selector_type) { case 'barcode_number': var inlineQty = '<div class="form-group container comment_section">'; break; case 'invoice_number': var inlineQty = '<div class="form-group container comment_section hide">'; break; case 'customer_issue': var inlineQty = '<div class="form-group container comment_section">'; break; } inlineQty += '<div class="row">'; inlineQty += '<div class="col-xs-12 comment">'; inlineQty += '<div class="input-group">'; inlineQty += '<span class="input-group-addon" id="comment_text">COMMENT<span class="mandatory hide">*</span></span>'; if (isTicketNotClosed(status_value)) { inlineQty += '<textarea id="comment" class="form-control comment" rows="3" disabled>' + comment + '</textarea>'; } else { inlineQty += '<textarea id="comment" class="form-control comment" rows="3" disabled readonly>' + comment + '</textarea>'; } inlineQty += '</div></div></div></div>'; return inlineQty; } /** * The customer contact details section. * Possibility for the user to add / edit the contacts. * @return {String} inlineQty */ function mpexContactSection() { // Contact details header var inlineQty = '<div class="form-group container mpex_contact_section">'; inlineQty += '<div class="row">'; inlineQty += '<div class="col-xs-12 heading2">'; inlineQty += '<h4><span style="background-color: #379E8F" class="label label-default col-xs-12">CONTACT DETAILS</span></h4>'; inlineQty += '</div>'; inlineQty += '</div></div>'; // Contact table inlineQty += '<div class="form-group container contacts_section" style="font-size: small;">'; inlineQty += '<div class="row">'; inlineQty += '<div class="col-xs-12 contacts_div">'; // Since the table is not displayed correctly when added through suitelet, // It is added with jQuery in the pageInit() function in the client script 'mp_cl_open_ticket.js'. inlineQty += '</div>'; inlineQty += '</div>'; inlineQty += '</div>'; // Add/edit contacts button inlineQty += '<div class="form-group container reviewcontacts_section">'; inlineQty += '<div class="row">'; inlineQty += '<div class="col-xs-4 col-xs-offset-4 reviewcontacts">'; inlineQty += '<input type="button" style="background-color: #379E8F; border-color: #379E8F; font-weight: 700" value="ADD/EDIT CONTACTS" class="form-control btn btn-primary" id="reviewcontacts" />'; inlineQty += '</div></div></div>'; return inlineQty; }; /** * The receiver phone and email fields. * These fields should be automatically filled based on the Selector number value. * @param {String} daytodayphone * @param {String} daytodayemail * @param {Number} status_value * @param {String} selector_type * @return {String} inlineQty */ function receiverEmailPhone(selector_type, receiveremail, receiverphone, receivername, receiverstate, receiverzip, receiversuburb, receiveraddr1, receiveraddr2) { var disabled = 'disabled'; var inlineQty = ''; if (selector_type == 'barcode_number') { // Receiver details header var inlineQty = '<div class="form-group container tickets_details_header_section">'; inlineQty += '<div class="row">'; inlineQty += '<div class="col-xs-12 heading2" >'; inlineQty += '<h4><span style="background-color: #379E8F" class="label label-default col-xs-12">RECEIVER DETAILS</span></h4>'; inlineQty += '</div></div></div>'; inlineQty += '<div class="form-group container receivercontact_section">'; inlineQty += '<div class="row">'; // name field inlineQty += '<div class="col-xs-6 receivername_div">'; inlineQty += '<div class="input-group">'; inlineQty += '<span class="input-group-addon" id="receivername_text">NAME</span>'; inlineQty += '<input id="receivername" value="' + receivername + '" class="form-control receivername" ' + disabled + ' />'; inlineQty += '</div></div>'; // state field inlineQty += '<div class="col-xs-6 receiverstate_div">'; inlineQty += '<div class="input-group">'; inlineQty += '<span class="input-group-addon" id="receiverstate_text">STATE</span>'; inlineQty += '<input id="receiverstate" value="' + receiverstate + '" class="form-control receiverstate" ' + disabled + ' />'; inlineQty += '</div></div></div></div>'; inlineQty += '<div class="form-group container receivercontact2_section">'; inlineQty += '<div class="row">'; // Day to day email field inlineQty += '<div class="col-xs-6 receiveremail_div">'; inlineQty += '<div class="input-group">'; inlineQty += '<span class="input-group-addon" id="receiveremail_text">EMAIL</span>'; inlineQty += '<input id="receiveremail" type="email" value="' + receiveremail + '" class="form-control receiveremail" ' + disabled + ' />'; inlineQty += '<div class="input-group-btn">'; inlineQty += '<button type="button" style="background-color: #379E8F" class="btn btn-success add_as_recipient" data-email="' + receiveremail + '" data-contact-id="" data-firstname="" data-toggle="tooltip" data-placement="right" title="Add as recipient">'; inlineQty += '<span class="glyphicon glyphicon-envelope"></span>'; inlineQty += '</button>'; inlineQty += '</div>'; inlineQty += '</div></div>'; // Day to day phone field inlineQty += '<div class="col-xs-6 receiverphone_div">'; inlineQty += '<div class="input-group">'; inlineQty += '<span class="input-group-addon" id="receiverphone_text">PHONE</span>'; inlineQty += '<input id="receiverphone" type="tel" value="' + receiverphone + '" class="form-control receiverphone" ' + disabled + ' />'; inlineQty += '<div class="input-group-btn"><button type="button" style="background-color: #379E8F" class="btn btn-success" id="call_receiver_phone"><span class="glyphicon glyphicon-earphone"></span></button></div>'; inlineQty += '</div></div></div></div>'; inlineQty += '<div class="form-group container receivercontact3_section">'; inlineQty += '<div class="row">'; // suburb field inlineQty += '<div class="col-xs-6 receiversuburb_div">'; inlineQty += '<div class="input-group">'; inlineQty += '<span class="input-group-addon" id="receiversuburb_text">SUBURB</span>'; inlineQty += '<input id="receiversuburb" value="' + receiversuburb + '" class="form-control receiversuburb" ' + disabled + ' />'; inlineQty += '</div></div>'; // postcode field inlineQty += '<div class="col-xs-6 receiverzip_div">'; inlineQty += '<div class="input-group">'; inlineQty += '<span class="input-group-addon" id="receiverzip_text">POSTCODE</span>'; inlineQty += '<input id="receiverzip" value="' + receiverzip + '" class="form-control receiverzip" ' + disabled + ' />'; inlineQty += '</div></div></div></div>'; inlineQty += '<div class="form-group container receivercontact4_section">'; inlineQty += '<div class="row">'; // address1 field inlineQty += '<div class="col-xs-6 receiveraddr1_div">'; inlineQty += '<div class="input-group">'; inlineQty += '<span class="input-group-addon" id="receiveraddr1_text">ADDRESS1</span>'; inlineQty += '<input id="receiveraddr1" value="' + receiveraddr1 + '" class="form-control receiveraddr1" ' + disabled + ' />'; inlineQty += '</div></div>'; // address2 field inlineQty += '<div class="col-xs-6 receiveraddr2_div">'; inlineQty += '<div class="input-group">'; inlineQty += '<span class="input-group-addon" id="receiveraddr2_text">ADDRESS2</span>'; inlineQty += '<input id="receiveraddr2" value="' + receiveraddr2 + '" class="form-control receiveraddr2" ' + disabled + ' />'; inlineQty += '</div></div></div></div>'; } return inlineQty; } /** * The "Send Email" section. * Possibility for the user to send an email to the customer, based on selected templates. * @param {Number} ticket_id * @param {Number} status_value * @param {Object} account_manager * @returns {String} inlineQty */ function sendEmailSection(ticket_id, status_value, account_manager, list_toll_emails) { var has_toll_emails = (!isNullorEmpty(list_toll_emails)); if (isNullorEmpty(ticket_id) || !isTicketNotClosed(status_value)) { // The section is hidden here rather than in the openTicket function, // because we use the section to send an acknoledgement email when a ticket is opened. var inlineQty = '<div id="send_email_container" class="send_email hide">'; } else { var inlineQty = '<div id="send_email_container" class="send_email">'; } inlineQty += '<div class="form-group container send_email header_section">'; // Send email header inlineQty += '<div class="row">'; inlineQty += '<div class="col-xs-12 heading2">'; inlineQty += '<h4><span style="background-color: #379E8F" class="label label-default col-xs-12">SEND EMAILS</span></h4>'; inlineQty += '</div></div></div>'; inlineQty += '<br></br>' // Row addressees inlineQty += '<div class="form-group container send_email adressees_section">'; inlineQty += '<div class="row">'; inlineQty += '<div class="col-xs-12 to_section">'; inlineQty += '<div class="input-group">'; inlineQty += '<span class="input-group-addon">TO<span class="mandatory">*</span></span>'; inlineQty += '<input id="send_to" class="form-control" data-contact-id="" data-firstname=""/>'; inlineQty += '</div></div></div></div>'; // Toll addresses var toll_emails_columns = new Array(); toll_emails_columns[0] = search.createColumn({ name: 'name' }); toll_emails_columns[1] = search.createColumn({ name: 'internalId' }); var tollEmailsResultSet = search.create({ type: 'customlist_toll_emails', columns: toll_emails_columns, }) inlineQty += '<div class="form-group container send_email toll_adressees_section">'; inlineQty += '<div class="row">'; inlineQty += '<div class="col-xs-12 toll_section">'; inlineQty += '<div class="input-group">'; inlineQty += '<span class="input-group-addon">TOLL EMAILS</span>'; inlineQty += '<select multiple id="send_toll" class="form-control" size="' + tollEmailsResultSet.length + '"/>'; tollEmailsResultSet.run().each(function (tollEmailsResultSet){ var tollEmailName = tollEmailsResultSet.getValue('name'); var tollEmailId = tollEmailsResultSet.getValue('internalId'); var selected = false; if(has_toll_emails) { selected = (list_toll_emails.indexOf(tollEmailId) !== -1); } if (selected) { inlineQty += '<option value="' + tollEmailId + '" selected>' + tollEmailName + '</option>'; } else { inlineQty += '<option value="' + tollEmailId + '">' + tollEmailName + '</option>'; } return true; }); inlineQty += '</select>'; inlineQty += '</div></div></div></div>'; // Row ccs addresses inlineQty += '<div class="form-group container send_email cc_adressees_section">'; inlineQty += '<div class="row">'; inlineQty += '<div class="col-xs-6 cc_section">'; inlineQty += '<div class="input-group">'; inlineQty += '<span class="input-group-addon">CC</span>'; inlineQty += '<input id="send_cc" class="form-control"/>'; inlineQty += '</div></div>'; inlineQty += '<div class="col-xs-6 bcc_section">'; inlineQty += '<div class="input-group">'; inlineQty += '<span class="input-group-addon">BCC</span>'; inlineQty += '<input id="send_bcc" class="form-control"/>'; inlineQty += '</div></div></div></div>'; // Row account manager if (isNullorEmpty(account_manager.name)) { account_manager.name = '' } if (isNullorEmpty(account_manager.email)) { account_manager.email = '' } if (!isNullorEmpty(account_manager.email.email)) { inlineQty += '<div class="form-group container send_email acc_manager_section">'; inlineQty += '<div class="row">'; inlineQty += '<div class="col-xs-10 acc_manager_name_section">'; inlineQty += '<div class="input-group">'; inlineQty += '<span class="input-group-addon">ACCOUNT MANAGER</span>'; inlineQty += '<input id="acc_manager" class="form-control" data-email="' + account_manager.email.email + '" value="' + account_manager.name + ' - ' + account_manager.email.email + '" disabled/>'; inlineQty += '</div></div>'; inlineQty += '<div class="col-xs-2 acc_manager_button_section">'; inlineQty += '<button id="acc_manager_button" style="background-color: #379E8F; border-color: #379E8F" type="button" class="btn btn-success btn-block">ADD TO CC</button>'; inlineQty += '</div></div></div>'; } // Row Template inlineQty += '<div class="form-group container send_email template_section">'; inlineQty += '<div class="row">'; inlineQty += '<div class="col-xs-12 template_section">'; inlineQty += '<div class="input-group">'; inlineQty += '<span class="input-group-addon">TEMPLATE<span class="mandatory">*</span></span>'; inlineQty += '<select id="template" class="form-control">'; inlineQty += '<option></option>'; // Load the template options var templatesSearch = search.load({ id: 'customsearch_cctemplate_mp_ticket', type: 'customrecord_camp_comm_template' }); var templatesSearchResults = templatesSearch.run(); templatesSearchResults.each(function(templatesSearchResult) { // var tempId = templatesSearchResult.getValue('internalid'); var tempId = templatesSearchResult["id"]; var tempName = templatesSearchResult.getValue('name'); inlineQty += '<option value="' + tempId + '">' + tempName + '</option>'; return true; }); inlineQty += '</select>'; inlineQty += '</div></div></div></div>'; // Row Subject inlineQty += '<div class="form-group container send_email subject_section">'; inlineQty += '<div class="row">'; inlineQty += '<div class="col-xs-12 subject_section">'; inlineQty += '<div class="input-group">'; inlineQty += '<span class="input-group-addon">SUBJECT<span class="mandatory">*</span></span>'; inlineQty += '<input id="subject" class="form-control" />'; inlineQty += '</div></div></div></div>'; // Row Body inlineQty += '<div class="form-group container send_email body_section">'; inlineQty += '<div class="row">'; inlineQty += '<div class="col-xs-12 body_section">'; inlineQty += '<div id="email_body"></div>'; inlineQty += '</div></div></div>'; // SEND EMAIL button inlineQty += '<div class="form-group container send_email button_section">'; inlineQty += '<div class="row">'; inlineQty += '<div class="col-xs-4 col-xs-offset-4 send_email_btn">'; inlineQty += '<input type="button" style="background-color: #379E8F; border-color: #379E8F; font-weight: 700" value="SEND EMAIL" class="form-control btn btn-primary" id="send_email" />'; inlineQty += '</div></div></div></div>'; return inlineQty; }; function externalBarcodeSource(selector_type, barcodempdl, barcodesource) { var disabled = 'disabled'; var inlineQty = ''; if (selector_type == 'barcode_number') { inlineQty += '<div class="form-group container barcode_section">'; inlineQty += '<div class="row">'; // MPLD field inlineQty += '<div class="col-xs-6 barcodempdl_div">'; inlineQty += '<div class="input-group">'; inlineQty += '<span class="input-group-addon" id="barcodempdl_text">EXTERNAL BARCODE</span>'; inlineQty += '<input id="barcodempdl" value="' + barcodempdl + '" class="form-control barcodempdl" ' + disabled + ' />'; inlineQty += '</div></div>'; // barcode source field inlineQty += '<div class="col-xs-6 barcodesource_div">'; inlineQty += '<div class="input-group">'; inlineQty += '<span class="input-group-addon" id="barcodesource_text">BARCODE SOURCE</span>'; inlineQty += '<input id="barcodesource" value="' + barcodesource + '" class="form-control barcodesource" ' + disabled + ' />'; inlineQty += '</div></div></div></div>'; } return inlineQty; } function tabsSection(customer_number, ticket_id, selector_number, selector_id, selector_type, status_value, date_created, creator_id, creator_name, status, customer_id, customer_name, daytodayphone, daytodayemail, accountsphone, accountsemail, maap_bank_account_number, maap_parent_bank_account_number, zee_id, franchisee_name, zee_main_contact_name, zee_email, zee_main_contact_phone, zee_abn, date_stock_used, time_stock_used, final_delivery_text, selected_enquiry_status_id,attachments_hyperlink, selected_enquiry_status_id, owner_list, list_toll_issues, list_resolved_toll_issues, comment, account_manager, list_toll_emails, customer_ticket_status, receiveremail, receiverphone, receivername, receiverstate, receiverzip, receiversuburb, receiveraddr1, receiveraddr2, barcodempdl, barcodesource, prod_stock_invoice) { var inlineQty = '<br/><div >'; // Tabs headers inlineQty += '<style>.nav > li.active > a, .nav > li.active > a:focus, .nav > li.active > a:hover { background-color: #379E8F; color: #fff }'; inlineQty += '.nav > li > a, .nav > li > a:focus, .nav > li > a:hover { margin-left: 5px; margin-right: 5px; border: 2px solid #379E8F; color: #379E8F; }'; inlineQty += '</style>'; // Ticket details header inlineQty += '<div class="form-group container tickets_details_header_section" style="margin-top: 10px">'; inlineQty += '<div class="row">'; inlineQty += '<div class="col-xs-12" >'; inlineQty += '<span">'; inlineQty += '<ul class="nav nav-pills nav-justified" style="margin:0%; ">'; inlineQty += '<li role="presentation" class="active"><a data-toggle="tab" href="#ticketdetails"><b>TICKET DETAILS</b></a></li>'; inlineQty += '<li role="presentation" class=""><a data-toggle="tab" href="#sendemails"><b>SEND EMAILS</b></a></li>'; inlineQty += '</ul>'; inlineQty += '</span>'; inlineQty += '</div></div></div>'; // Tabs content inlineQty += '<div class="tab-content">'; // TICKET DETAILS TAB inlineQty += '<div role="tabpanel" class="tab-pane active" id="ticketdetails">'; inlineQty += customerNumberSection(customer_number, ticket_id); inlineQty += selectorSection(ticket_id, selector_number, selector_id, selector_type, status_value); if (!isNullorEmpty(ticket_id)) { inlineQty += externalBarcodeSource(selector_type, barcodempdl, barcodesource) inlineQty += ticketSection(dateISOToNetsuite(date_created), creator_id, creator_name, status, customer_ticket_status); } if (isNullorEmpty(ticket_id) || (!isNullorEmpty(ticket_id) && !isNullorEmpty(customer_id)) || !isNullorEmpty(customer_number)) { inlineQty += customerSection(customer_name); inlineQty += daytodayContactSection(daytodayphone, daytodayemail, status_value, selector_type); inlineQty += accountsContactSection(accountsphone, accountsemail, status_value, selector_type); } if(isNullorEmpty(ticket_id) || (!isNullorEmpty(ticket_id) && (selector_type == 'invoice_section'))) { inlineQty += maapBankAccountSection(maap_bank_account_number, maap_parent_bank_account_number, selector_type); } if (isNullorEmpty(ticket_id) || (!isNullorEmpty(ticket_id) && !isNullorEmpty(zee_id)) || !isNullorEmpty(customer_number)) { inlineQty += franchiseeMainContactSection(franchisee_name, zee_main_contact_name, zee_email, zee_main_contact_phone, zee_abn); } inlineQty += mpexStockUsedSection(selector_type, date_stock_used, time_stock_used); inlineQty += finalDeliveryEnquirySection(status_value, selector_type, final_delivery_text, selected_enquiry_status_id, prod_stock_invoice); inlineQty += attachmentsSection(attachments_hyperlink, status_value); if(!isNullorEmpty(ticket_id)) { inlineQty += receiverEmailPhone(selector_type, receiveremail, receiverphone, receivername, receiverstate, receiverzip, receiversuburb, receiveraddr1, receiveraddr2); } // ENQUIRY SECTION //inlineQty += enquiryMediumSection(list_enquiry_mediums, selected_enquiry_status_id, selector_type) //inlineQty += enquiryCountSection( total_enquiry_count, chat_enquiry_count, phone_enquiry_count, email_enquiry_count, selector_type); //TICKET LABEL DROPDOWN //inlineQty += labelSection(selected_label_id, selector_type, status_value); //inlineQty += closeReopenSubmitTicketButton(ticket_id, status_value); inlineQty += issuesHeader(); inlineQty += reminderSection(status_value); inlineQty += ownerSection(ticket_id, owner_list, status_value); inlineQty += tollIssuesSection(list_toll_issues, list_resolved_toll_issues, status_value, selector_type); inlineQty += commentSection(comment, selector_type, status_value); inlineQty += '</div>'; // CONTACT / EMAILS if (!isNullorEmpty(ticket_id)) { inlineQty += '<div role="tabpanel" class="tab-pane" id="sendemails">'; inlineQty += mpexContactSection(); inlineQty += sendEmailSection(ticket_id, status_value, account_manager, list_toll_emails); //inlineQty += closeReopenSubmitTicketButton(ticket_id, status_value); inlineQty += '</div>'; } inlineQty += '</div></div>'; return inlineQty; } /** * Returns whether a ticket is closed or not based on its status value. * @param {Number} status_value * @returns {Boolean} is_ticket_closed */ function isTicketNotClosed(status_value) { var is_ticket_not_closed = ((status_value != 3) && (status_value != 8)) ? true : false; return is_ticket_not_closed; } /** * Whether the user is from the finance team, * or a Data Systems Co-ordinator, MailPlus Administration or Administrator user. * @param {Number} userRole * @returns {Boolean} */ function isFinanceRole(userRole) { // 1001, 1031 and 1023 are finance roles // 1032 is the Data Systems Co-ordinator role (to be deleted in prod) // 1006 is the Mail Plus Administration role. // 3 is the Administrator role. return ((userRole == 1001 || userRole == 1031 || userRole == 1023) || ((userRole == 1032) || (userRole == 1006) || (userRole == 3))); } function isNullorEmpty(strVal) { return (strVal == null || strVal == '' || strVal == 'null' || strVal == undefined || strVal == 'undefined' || strVal == '- None -'); } return { onRequest: onRequest }; });
885
[{"tag": "KEY", "value": "sha384-HSMxcRTRxnN+Bdg0JdbxYKrThecOKuH5zCYotlSAcp1+c8xmyTe9GYg1l9a69psu", "start": 22082, "end": 22153}, {"tag": "KEY", "value": "sha384-nvAa0+6Qg9clwYCGGPpDQLVpLNn0fRaROjHqs13t4Ggj3Ez50XnGQqc/r8MhnRDZ", "start": 21676, "end": 21747}, {"tag": "KEY", "value": "sha384-aJ21OjlMXNL5UyIl/XNwTMqvzeRMZH2w8c5cRVpzpU8Y5bApTppSuUkhZXN0VxHd", "start": 22305, "end": 22376}]
true
3
/** * * @NApiVersion 2.0 * @NScriptType Suitelet * * Description: Separate page for escalating ticket * @Last Modified by: Sruti Desai * */ define(['N/ui/serverWidget', 'N/email', 'N/runtime', 'N/search', 'N/record', 'N/http', 'N/log', 'N/redirect', 'N/format'], function(ui, email, runtime, search, record, http, log, redirect, format) { var baseURL = 'https://1048144.app.netsuite.com'; if (runtime.envType == "SANDBOX") { baseURL = 'https://1048144-sb3.app.netsuite.com'; } var zee = 0; var role = runtime.getCurrentUser().role; var userRole = runtime.getCurrentUser().role; if (role == 1000) { //Franchisee zee = runtime.getCurrentUser(); } function onRequest(context) { if (context.request.method === 'GET') { var ticket_id = null; var customer_id = null; var customer_number = null; var selector_id = null; var selector_number = ''; var selector_type = 'barcode_number'; var date_created = ''; var creator_name = ''; var creator_id = null; var status_value = null; var status = ''; var customer_name = ''; var daytodayphone = ''; var daytodayemail = ''; var accountsphone = ''; var accountsemail = ''; var zee_id = null; var franchisee_name = ''; var zee_main_contact_name = ''; var zee_email = ''; var zee_main_contact_phone = ''; var zee_abn = ''; var date_stock_used = ''; var time_stock_used = ''; var final_delivery_text = ''; var selected_enquiry_status_id = null; var attachments_hyperlink = ''; var maap_bank_account_number = null; var maap_parent_bank_account_number = null; var selected_invoice_method_id = null; var accounts_cc_email = ''; var mpex_po_number = ''; var customer_po_number = ''; var terms = null; var customer_terms = ''; var account_manager = {}; var selected_invoice_cycle_id = null; var usage_report_id_1 = ''; var usage_report_id_2 = ''; var usage_report_id_3 = ''; var usage_report_id_4 = ''; var usage_report_array = []; var list_toll_issues = ''; var list_resolved_toll_issues = ''; var list_mp_ticket_issues = ''; var list_resolved_mp_ticket_issues = ''; var list_invoice_issues = ''; var list_resolved_invoice_issues = ''; var owner_list = ''; var comment = ''; var selected_label_id = null; var list_enquiry_mediums = ''; var total_enquiry_count = 0; var chat_enquiry_count = 0; var phone_enquiry_count = 0; var email_enquiry_count = 0; var list_toll_emails = ''; var params_email = { recipient: '', subject: '', body: '', cc: '', bcc: '', records: {}, attachments_credit_memo_ids: [], attachments_usage_report_ids: [], attachments_invoice_ids: [] }; var customer_issue = ''; var screenshot_file = ''; var browser = ''; var login_email_used = ''; var operating_system = ''; var phone_used = ''; var old_sender_name = ''; var old_sender_phone = ''; var customer_number_email_sent = 'F'; var customer_status_value = ''; var customer_ticket_status = ''; var customer_barcode_number = ''; var receiveremail = ''; var receiverphone = ''; var receivername = ''; var receiverstate = ''; var receiverzip = ''; var receiversuburb = ''; var receiveraddr1 = ''; var receiveraddr2 = ''; var prod_stock_invoice = ''; var barcodempdl = ''; var barcodesource = ''; // Load params var params = context.request.parameters.custparam_params; log.debug({ title: 'Params', details: params }) if (!isNullorEmpty(params)) { params = JSON.parse(params); log.debug({ title: 'Params not empty', details: params }); // Coming from the ticket_contact page or the edit_ticket page if (!isNullorEmpty(params.selector_number) && !isNullorEmpty(params.selector_type)) { selector_number = params.selector_number; selector_type = params.selector_type; //Coming from the ticket_contact page if (!isNullorEmpty(params.custid)) { customer_id = params.custid; } log.debug({ title: 'customer_id after ticket_contact_page : ', details: customer_id }); // Coming from the edit_ticket page if (!isNullorEmpty(params.ticket_id)) { ticket_id = parseInt(params.ticket_id); log.debug({ title: 'ticket id ISS', details: ticket_id }); // Load ticket data var ticketRecord = record.load({ type: 'customrecord_mp_ticket', id: ticket_id }); date_created = ticketRecord.getValue({ fieldId: 'created' }); creator_name = ticketRecord.getText({ fieldId: 'custrecord_creator' }); creator_id = ticketRecord.getValue({ fieldId: 'custrecord_creator' }); status_value = ticketRecord.getValue({ fieldId: 'custrecord_ticket_status' }); status = ticketRecord.getText({ fieldId: 'custrecord_ticket_status' }); customer_id = ticketRecord.getValue({ fieldId: 'custrecord_customer1' }); customer_name = ticketRecord.getText({ fieldId: 'custrecord_customer1' }); zee_id = ticketRecord.getValue({ fieldId: 'custrecord_zee' }); selected_enquiry_status_id = ticketRecord.getValue({ fieldId: 'custrecord_enquiry_status' }); attachments_hyperlink = ticketRecord.getValue({ fieldId: 'custrecord_mp_ticket_attachments' }); selected_label_id = ticketRecord.getValue({ fieldId: 'custrecord_ticket_label' }); list_enquiry_mediums = ticketRecord.getValue({ fieldId: 'custrecord_enquiry_medium' }); list_enquiry_mediums = java2jsArray(list_enquiry_mediums); total_enquiry_count = ticketRecord.getValue({ fieldId: 'custrecord_enquiry_count' }); chat_enquiry_count = ticketRecord.getValue({ fieldId: 'custrecord_chat_enquiry_count' }); phone_enquiry_count = ticketRecord.getValue({ fieldId: 'custrecord_phone_enquiry_count' }); email_enquiry_count = ticketRecord.getValue({ fieldId: 'custrecord_email_enquiry_count' }); customer_issue = ticketRecord.getValue({ fieldId: 'custrecord_customer_issue' }); screenshot_file = ticketRecord.getValue({ fieldId: 'custrecord_screenshot' }); browser = ticketRecord.getValue({ fieldId: 'custrecord_browser' }); login_email_used = ticketRecord.getValue({ fieldId: 'custrecord_login_email' }); operating_system = ticketRecord.getValue({ fieldId: 'custrecord_operating_system' }); phone_used = ticketRecord.getValue({ fieldId: 'custrecord_phone_used' }); customer_number = ticketRecord.getValue({ fieldId: 'custrecord_cust_number' }); old_sender_name = ticketRecord.getValue({ fieldId: 'custrecord_sender_name' }); old_sender_phone = ticketRecord.getValue({ fieldId: 'custrecord_sender_phone' }); customer_number_email_sent = ticketRecord.getValue({ fieldId: 'custrecord_customer_number_email_sent' }); customer_status_value = ticketRecord.getValue({fieldId: 'custrecord_mp_ticket_customer_status'}); customer_ticket_status = ticketRecord.getText({fieldId: 'custrecord_mp_ticket_customer_status'}); customer_barcode_number = ticketRecord.getValue({ fieldId : 'custrecord_barcode_number'}); if (!isNullorEmpty(customer_barcode_number)) { var rec = record.load({ type: 'customrecord_customer_product_stock', id: customer_barcode_number, }); receiveremail = rec.getValue({fieldId: 'custrecord_receiver_email'}); receiverphone = rec.getValue({fieldId: 'custrecord_receiver_phone'}); receivername = rec.getValue({fieldId: 'custrecord_receiver_name'}); receiverstate = rec.getValue({fieldId: 'custrecord_receiver_state'}); receiverzip = rec.getValue({fieldId: 'custrecord_receiver_postcode'}); receiversuburb = rec.getValue({fieldId: 'custrecord_receiver_suburb'}); receiveraddr1 = rec.getValue({fieldId: 'custrecord_receiver_addr1'}); receiveraddr2 = rec.getValue({fieldId: 'custrecord_receiver_addr2'}); prod_stock_invoice = rec.getText({fieldId: 'custrecord_prod_stock_invoice'}); barcodempdl = rec.getValue({fieldId: 'custrecord_mpdl_number'}); barcodesource = rec.getText({fieldId: 'custrecord_barcode_source'}); } if(isNullorEmpty(customer_id) && !isNullorEmpty(customer_number)){ var customer_search = search.load({ type: 'customer', id: 'customsearch_customer_name_2' }); customer_search.filters.push(search.createFilter({ name: 'entityid', operator: 'haskeywords', values: customer_number, })); customer_id = customer_search.run().getRange({ start: 0,end:1 })[0].getId(); } if (!isNullorEmpty(customer_id)) { //Load customer record and franchisee information var customerRecord = record.load({ type: 'customer', id: customer_id }); customer_number = customerRecord.getValue({ fieldId: 'entityid' }); daytodayphone = customerRecord.getValue({ fieldId: 'phone' }); daytodayemail = customerRecord.getValue({ fieldId: 'custentity_email_service' }); terms = customerRecord.getValue({ fieldId: 'terms' }); customer_terms = customerRecord.getValue({ fieldId: 'custentity_finance_terms' }); // Account manager var accountManagerSearch = search.load({ type: 'customer', id: 'customsearch3413' }); accountManagerSearch.filters.push(search.createFilter({ name: 'internalid', join: null, operator: search.Operator.ANYOF, values: customer_id, })) var accountManagerResultSet = accountManagerSearch.run(); var accountManagerResult = accountManagerResultSet.getRange({ start: 0, end: 1 }); accountManagerResult = accountManagerResult[0]; if (!isNullorEmpty(accountManagerResult)) { var account_manager_value = accountManagerResult.getValue({ name: "custrecord_sales_assigned", join: "CUSTRECORD_SALES_CUSTOMER", summary: null }); var account_manager_text = accountManagerResult.getText({ name: "custrecord_sales_assigned", join: "CUSTRECORD_SALES_CUSTOMER", summary: null }); if (!isNullorEmpty(account_manager_value)) { var account_manager_email = search.lookupFields({ type: 'employee', id: account_manager_value, columns: 'email' }); account_manager = { name: account_manager_text, email: account_manager_email }; } } // The Franchisee informations are imported from the customer record if possible. zee_id = customerRecord.getValue({ fieldId: 'partner' }); } if (!isNullorEmpty(zee_id)) { var zeeRecord = record.load({ type: 'partner', id: zee_id }); franchisee_name = zeeRecord.getValue({ fieldId: 'companyname' }); zee_main_contact_name = zeeRecord.getValue({ fieldId: 'custentity3' }); zee_email = zeeRecord.getValue({ fieldId: 'email' }); zee_main_contact_phone = zeeRecord.getValue({ fieldId: 'custentity2' }); zee_abn = zeeRecord.getValue({ fieldId: 'custentity_abn_franchiserecord' }); } else { franchisee_name = ticketRecord.getText({ fieldId: 'custrecord_zee' }); } switch (selector_type) { case 'barcode_number': selector_id = ticketRecord.getValue({ fieldId: 'custrecord_barcode_number' }); var stock_used = ''; if(!isNullorEmpty(selector_id)){ //Come in here only if selector_id is not null stock_used = search.lookupFields({ type: 'customrecord_customer_product_stock', id: selector_id, columns: ['custrecord_cust_date_stock_used', 'custrecord_cust_time_stock_used'] }); log.debug({ title: 'finalDel', details: search.lookupFields({ type: 'customrecord_customer_product_stock', id: selector_id, columns: 'custrecord_cust_prod_stock_final_del' }) }); var finalDelCheck = search.lookupFields({ type: 'customrecord_customer_product_stock', id: selector_id, columns: 'custrecord_cust_prod_stock_final_del' }).custrecord_cust_prod_stock_final_del; if (!isNullorEmpty(finalDelCheck)) { final_delivery_text = search.lookupFields({ type: 'customrecord_customer_product_stock', id: selector_id, columns: 'custrecord_cust_prod_stock_final_del' })["custrecord_cust_prod_stock_final_del"][0]["text"]; } date_stock_used = stock_used.custrecord_cust_date_stock_used; time_stock_used = stock_used.custrecord_cust_time_stock_used; } list_toll_issues = ticketRecord.getValue({ fieldId: 'custrecord_toll_issues' }); list_toll_issues = java2jsArray(list_toll_issues); list_resolved_toll_issues = ticketRecord.getValue({ fieldId: 'custrecord_resolved_toll_issues' }); list_resolved_toll_issues = java2jsArray(list_resolved_toll_issues); list_toll_emails = ticketRecord.getValue({ fieldId: 'custrecord_toll_emails' }); list_toll_emails = java2jsArray(list_toll_emails); break; case 'invoice_number': selector_id = ticketRecord.getValue({ fieldId: 'custrecord_invoice_number' }); var invoiceRecord = record.load({ type: 'invoice', id: selector_id }); accountsphone = customerRecord.getValue({ fieldId: 'altphone' }); accountsemail = customerRecord.getValue({ fieldId: 'email' }); maap_bank_account_number = customerRecord.getValue({ fieldId: 'custentity_maap_bankacctno' }); maap_parent_bank_account_number = customerRecord.getValue({ fieldId: 'custentity_maap_bankacctno_parent' }); selected_invoice_method_id = customerRecord.getValue({ fieldId: 'custentity_invoice_method' }); accounts_cc_email = customerRecord.getValue({ fieldId: 'custentity_accounts_cc_email' }); mpex_po_number = customerRecord.getValue({ fieldId: 'custentity_mpex_po' }); customer_po_number = customerRecord.getValue({ fieldId: 'custentity11' }); selected_invoice_cycle_id = customerRecord.getValue({ fieldId: 'custentity_mpex_invoicing_cycle' }); usage_report_id_1 = invoiceRecord.getValue({ fieldId: 'custbody_mpex_usage_report' }); usage_report_id_2 = invoiceRecord.getValue({ fieldId: 'custbody_mpex_usage_report_2' }); usage_report_id_3 = invoiceRecord.getValue({ fieldId: 'custbody_mpex_usage_report_3' }); usage_report_id_4 = invoiceRecord.getValue({ fieldId: 'custbody_mpex_usage_report_4' }); var usage_report_id_array = [usage_report_id_1, usage_report_id_2, usage_report_id_3, usage_report_id_4]; usage_report_id_array.forEach(function (usage_report_id) { if (!isNullorEmpty(usage_report_id)) { var usage_report_file = file.load({ id: usage_report_id }); usage_report_name = usage_report_file.name; usage_report_link = usage_report_file.url; usage_report_array.push({ id: usage_report_id, name: usage_report_name, url: usage_report_link }); } }); list_invoice_issues = ticketRecord.getValue({ fieldId: 'custrecord_invoice_issues' }); list_invoice_issues = java2jsArray(list_invoice_issues); list_resolved_invoice_issues = ticketRecord.getValue({ fieldId: 'custrecord_resolved_invoice_issues' }); list_resolved_invoice_issues = java2jsArray(list_resolved_invoice_issues); break; } list_mp_ticket_issues = ticketRecord.getValue({ fieldId: 'custrecord_mp_ticket_issue' }); list_mp_ticket_issues = java2jsArray(list_mp_ticket_issues); list_resolved_mp_ticket_issues = ticketRecord.getValue({ fieldId: 'custrecord_resolved_mp_ticket_issue' }); list_resolved_mp_ticket_issues = java2jsArray(list_resolved_mp_ticket_issues); owner_list = ticketRecord.getValue({ fieldId: 'custrecord_owner' }); owner_list = java2jsArray(owner_list); comment = ticketRecord.getValue({ fieldId: 'custrecord_comment' }); } } } var form = ui.createForm({ title: ' ', }); // Load jQuery var inlineHtml = '<script src="https://code.jquery.com/jquery-1.12.4.min.js" integrity="9q3vfhm7l33rus21toc8fndupq76itje" crossorigin="anonymous"></script>'; // Load Tooltip inlineHtml += '<script src="https://unpkg.com/@popperjs/core@2"></script>'; // Load Bootstrap inlineHtml += '<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/3.4.1/css/bootstrap.min.css" integrity="949d1u22cbffbrarjh182eig55721odj" crossorigin="anonymous">'; inlineHtml += '<script src="https://stackpath.bootstrapcdn.com/bootstrap/3.4.1/js/bootstrap.min.js" integrity="ax5kh6jaqkcd2tiexxs8v6xjo8yv8a6b" crossorigin="anonymous"></script>'; // Load DataTables inlineHtml += '<link rel="stylesheet" type="text/css" href="//cdn.datatables.net/1.10.21/css/jquery.dataTables.min.css">'; inlineHtml += '<script type="text/javascript" charset="utf8" src="//cdn.datatables.net/1.10.21/js/jquery.dataTables.min.js"></script>'; // Load Summernote css/js inlineHtml += '<link href="https://cdnjs.cloudflare.com/ajax/libs/summernote/0.8.9/summernote.css" rel="stylesheet">'; inlineHtml += '<script src="https://cdnjs.cloudflare.com/ajax/libs/summernote/0.8.9/summernote.js"></script>'; // Load bootstrap-select inlineHtml += '<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap-select@1.13.14/dist/css/bootstrap-select.min.css">'; inlineHtml += '<script src="https://cdn.jsdelivr.net/npm/bootstrap-select@1.13.14/dist/js/bootstrap-select.min.js"></script>'; // Load Netsuite stylesheet and script inlineHtml += '<link rel="stylesheet" href="https://1048144.app.netsuite.com/core/media/media.nl?id=2060796&c=1048144&h=9ee6accfd476c9cae718&_xt=.css"/>'; inlineHtml += '<script src="https://1048144.app.netsuite.com/core/media/media.nl?id=2060797&c=1048144&h=ef2cda20731d146b5e98&_xt=.js"></script>'; inlineHtml += '<link type="text/css" rel="stylesheet" href="https://1048144.app.netsuite.com/core/media/media.nl?id=2090583&c=1048144&h=a0ef6ac4e28f91203dfe&_xt=.css">'; inlineHtml += '<style>.mandatory{color:red;}</style>'; // Define alert window. inlineHtml += '<div class="container" style="margin-top:14px;" hidden><div id="alert" class="alert alert-danger fade in"></div></div>'; // Define information window. inlineHtml += '<div class="container" hidden><p id="info" class="alert alert-info"></p></div>'; //inlineHtml += '<div style="background-color: #CFE0CE; min-height: 100vh; margin-top: -15px; padding-bottom: 50px"><br/>'; inlineHtml += '<div style="margin-top: -40px"><br/>'; inlineHtml += escalateButton(status_value); inlineHtml += '<h1 style="font-size: 25px; font-weight: 700; color: #103D39; text-align: center">Escalate Ticket - MPSD' + ticket_id + '</h1>'; //Tabs inlineHtml += tabsSection(customer_number, ticket_id, selector_number, selector_id, selector_type, status_value, date_created, creator_id, creator_name, status, customer_id, customer_name, daytodayphone, daytodayemail, accountsphone, accountsemail, maap_bank_account_number, maap_parent_bank_account_number, zee_id, franchisee_name, zee_main_contact_name, zee_email, zee_main_contact_phone, zee_abn, date_stock_used, time_stock_used, final_delivery_text, selected_enquiry_status_id,attachments_hyperlink, selected_enquiry_status_id, owner_list, list_toll_issues, list_resolved_toll_issues, comment, account_manager, list_toll_emails, customer_ticket_status, receiveremail, receiverphone, receivername, receiverstate, receiverzip, receiversuburb, receiveraddr1, receiveraddr2, barcodempdl, barcodesource, prod_stock_invoice) inlineHtml += '</div>'; form.addField({ id: 'preview_table', type: ui.FieldType.INLINEHTML, label: 'preview_table' }).updateBreakType({ breakType: ui.FieldBreakType.STARTROW }).defaultValue = inlineHtml; form.addField({ id: 'custpage_selector_number', type: ui.FieldType.TEXT, label: 'Selector Number' }).updateDisplayType({ displayType: ui.FieldDisplayType.HIDDEN }).defaultValue = selector_number; form.addField({ id: 'custpage_selector_type', type: ui.FieldType.TEXT, label: 'Selector Type' }).updateDisplayType({ displayType: ui.FieldDisplayType.HIDDEN }).defaultValue = selector_type; if (!isNullorEmpty(ticket_id)) { form.addField({ id: 'custpage_ticket_id', type: ui.FieldType.TEXT, label: 'Ticket ID' }).updateDisplayType({ displayType: ui.FieldDisplayType.HIDDEN }).defaultValue = ticket_id; } else { form.addField({ id: 'custpage_ticket_id', type: ui.FieldType.TEXT, label: 'Ticket ID' }).updateDisplayType({ displayType: ui.FieldDisplayType.HIDDEN }); } form.addField({ id: 'custpage_selector_id', type: ui.FieldType.TEXT, label: 'Selector ID' }).updateDisplayType({ displayType: ui.FieldDisplayType.HIDDEN }).defaultValue = selector_id; form.addField({ id: 'custpage_selector_issue', type: ui.FieldType.TEXT, label: 'Barcode issue' }).updateDisplayType({ displayType: ui.FieldDisplayType.HIDDEN }).defaultValue = 'F'; form.addField({ id: 'custpage_customer_id', type: ui.FieldType.TEXT, label: 'Customer ID' }).updateDisplayType({ displayType: ui.FieldDisplayType.HIDDEN }).defaultValue = customer_id; form.addField({ id: 'custpage_customer_number', type: ui.FieldType.TEXT, label: 'Customer Number' }).updateDisplayType({ displayType: ui.FieldDisplayType.HIDDEN }).defaultValue = customer_number; form.addField({ id: 'custpage_zee_id', type: ui.FieldType.TEXT, label: 'Franchisee ID' }).updateDisplayType({ displayType: ui.FieldDisplayType.HIDDEN }).defaultValue = zee_id; form.addField({ id: 'custpage_ticket_status_value', type: ui.FieldType.TEXT, label: 'Status Value' }).updateDisplayType({ displayType: ui.FieldDisplayType.HIDDEN }).defaultValue = status_value; form.addField({ id: 'custpage_created_ticket', type: ui.FieldType.TEXT, label: 'Created Ticket' }).updateDisplayType({ displayType: ui.FieldDisplayType.HIDDEN }).defaultValue = 'F'; form.addField({ id: 'custpage_usage_report_array', type: ui.FieldType.TEXT, label: 'Usage Reports' }).updateDisplayType({ displayType: ui.FieldDisplayType.HIDDEN }).defaultValue = JSON.stringify(usage_report_array); form.addField({ id: 'custpage_param_email', type: ui.FieldType.TEXT, label: 'Email parameters' }).updateDisplayType({ displayType: ui.FieldDisplayType.HIDDEN }).defaultValue = JSON.stringify(params_email); form.addField({ id: 'custpage_ss_image', type: ui.FieldType.TEXT, label: 'Screenshot Image' }).updateDisplayType({ displayType: ui.FieldDisplayType.HIDDEN }).defaultValue = screenshot_file; form.addField({ id: 'custpage_customer_number_email_sent', type: ui.FieldType.TEXT, label: 'Customer Email Sent' }).updateDisplayType({ displayType: ui.FieldDisplayType.HIDDEN }).defaultValue = customer_number_email_sent; form.clientScriptFileId = 4813457;//SB=4797047 PROD = 4813457 context.response.writePage(form); } else { } } /** * The output of .getFieldValues is a java String Array. * We want to convert it to a javaScript Array in order to read its values. * @param {Ljava.lang.String} javaArray * @return {Array} jsArray */ function java2jsArray(javaArray) { var jsArray = new Array; if (!isNullorEmpty(javaArray)) { javaArray.forEach(function(javaValue) { var jsValue = javaValue.toString(); jsArray.push(jsValue); }) } return jsArray; } /** * The "Customer number" input field. If there is a Ticket ID, then we are on the Edit Ticket page and * this field is pre-filled. * @param {*} customer_number */ function customerNumberSection(customer_number, ticket_id){ if(isNullorEmpty(customer_number)){ customer_number = ''; } // var disable = isNullorEmpty(ticket_id) ? '': 'disabled'; // Ticket details header var inlineQty = '<div class="form-group container tickets_details_header_section">'; inlineQty += '<div class="row">'; inlineQty += '<div class="col-xs-12 heading2" >'; inlineQty += '<h4><span style="background-color: #379E8F" class="label label-default col-xs-12">TICKET DETAILS</span></h4>'; inlineQty += '</div></div></div>'; // Customer number section inlineQty += '<div class="form-group container customer_number_section">'; inlineQty += '<div class="row">'; //Customer number field inlineQty += '<div class="col-xs-12 customer_number">'; inlineQty += '<div class="input-group">'; inlineQty += '<span class="input-group-addon" id="customer_number_text">CUSTOMER NUMBER</span>'; if(customer_number == '' && isNullorEmpty(ticket_id)){ inlineQty += '<input id="customer_number_value" value=" '+ customer_number +' " class="form-control customer_number">'; }else{ inlineQty += '<input id="customer_number_value" value=" '+ customer_number +' " class="form-control customer_number" disabled>'; } inlineQty += '</div></div></div></div>'; //Datatable for all tickets asscoiated to current customer number // inlineQty += '<div class="row">'; // inlineQty += '<div class="form-group container customer_number_tickets">'; // inlineQty += '<style> table {font-size: 12px;text-align: center;border: none;} {font-size: 14px;} table th{text-align: center;} .dataTables_wrapper{width:78%; margin-bottom:40px; margin-left: auto; margin-right: auto; margin-top: auto;} </style>'; // inlineQty += '<table cellpadding="15" id="customer_number_tickets_preview" class="table table-responsive table-striped customer tablesorter" cellspacing="0" style="width: 100%;">'; // inlineQty += '<thead style="color: white;background-color: #607799;">'; // inlineQty += '<tr class="text-center">'; // inlineQty += '</tr>'; // inlineQty += '</thead></table>'; // inlineQty += '</div></div>'; return inlineQty; } function escalateButton(status) { if (status < 11) { return '<button style="margin-left: 10px; margin-right: 5px; background-color: #FBEA51; color: #103D39; font-weight: 700; border-color: transparent; border-width: 2px; border-radius: 15px; height: 30px" type="button" id="escalationbtn" onclick="">Escalate to 1st Escalation</button>'; } else if (status == 11) { var html = '<button style="margin-left: 10px; margin-right: 5px; background-color: #FBEA51; color: #103D39; font-weight: 700; border-color: transparent; border-width: 2px; border-radius: 15px; height: 30px" type="button" id="escalationbtn" onclick="">Escalate to 2nd Escalation</button>'; html += '<button style="margin-left: 5px; margin-right: 5px; background-color: #FBEA51; color: #103D39; font-weight: 700; border-color: transparent; border-width: 2px; border-radius: 15px; height: 30px" type="button" id="removeescalationbtn" onclick="">Remove Escalation</button>'; return html; }else if (status == 12) { var html = '<button style="margin-left: 10px; margin-right: 5px; background-color: #FBEA51; color: #103D39; font-weight: 700; border-color: transparent; border-width: 2px; border-radius: 15px; height: 30px" type="button" id="escalationbtn" onclick="">Escalate to 3rd Escalation</button>'; html += '<button style="margin-left: 5px; margin-right: 5px; background-color: #FBEA51; color: #103D39; font-weight: 700; border-color: transparent; border-width: 2px; border-radius: 15px; height: 30px" type="button" id="removeescalationbtn" onclick="">Remove Escalation</button>'; return html; } else if (status == 13) { var html = '<button style="margin-left: 10px; margin-right: 5px; background-color: #FBEA51; color: #103D39; font-weight: 700; border-color: transparent; border-width: 2px; border-radius: 15px; height: 30px" type="button" id="escalationbtn" onclick="">Escalate to Final Escalation</button>'; html += '<button style="margin-left: 5px; margin-right: 5px; background-color: #FBEA51; color: #103D39; font-weight: 700; border-color: transparent; border-width: 2px; border-radius: 15px; height: 30px" type="button" id="removeescalationbtn" onclick="">Remove Escalation</button>'; return html; } else { return '<button style="margin-left: 10px; margin-right: 5px; background-color: #FBEA51; color: #103D39; font-weight: 700; border-color: transparent; border-width: 2px; border-radius: 15px; height: 30px" type="button" id="removeescalationbtn" onclick="">Remove Escalation</button>'; } } /** * The "Barcode number" OR "Invoice Number" input field. * If there is a TICKET ID, we are in the "Edit Ticket", so we display the Ticket ID field and the selector field is disabled. * @param {Number} ticket_id * @param {String} selector_number * @param {Number} selector_id * @param {String} selector_type * @param {Number} status_value * @return {String} inlineQty */ function selectorSection(ticket_id, selector_number, selector_id, selector_type, status_value) { if (isNullorEmpty(selector_number)) { selector_number = ''; } var inlineQty = '<div class="form-group container selector_section">'; inlineQty += '<div class="row">'; if (!isNullorEmpty(ticket_id)) { // Ticket ID field inlineQty += '<div class="col-xs-6 ticket_id">'; inlineQty += '<div class="input-group">'; inlineQty += '<span class="input-group-addon" id="ticket_id_text">TICKET ID</span>'; inlineQty += '<input id="ticket_id" value="MPSD' + ticket_id + '" class="form-control ticket_id" disabled />'; inlineQty += '</div></div>'; // Selector Number field inlineQty += '<div class="col-xs-6 selector_number">'; inlineQty += '<div class="input-group">'; switch (selector_type) { case 'barcode_number': inlineQty += '<span class="input-group-addon" id="selector_text">BARCODE NUMBER</span>'; break; case 'invoice_number': inlineQty += '<span class="input-group-addon" id="selector_text">INVOICE NUMBER</span>'; break; } inlineQty += '<input id="selector_value" value="' + selector_number + '" class="form-control selector_value" disabled>'; if (selector_type == 'invoice_number') { // Open Invoice record inlineQty += '<div class="input-group-btn">'; inlineQty += '<button id="open_inv" type="button" class="btn btn-default link_inv" data-inv-id="' + selector_id + '" data-toggle="tooltip" data-placement="top" title="Open Invoice">'; inlineQty += '<span class="glyphicon glyphicon-link"></span>'; inlineQty += '</button>'; inlineQty += '</div>'; // Attach Invoice to email if (isTicketNotClosed(status_value)) { inlineQty += '<div class="input-group-btn"><button style="background-color: #379E8F" id="add_inv" type="button" class="btn btn-success add_inv" data-inv-id="' + selector_id + '" data-toggle="tooltip" data-placement="right" title="Attach to email">'; inlineQty += '<span class="glyphicon glyphicon-plus"></span>'; inlineQty += '</button></div>'; } } inlineQty += '</div></div></div></div>'; } else { inlineQty += '<div class="col-xs-12 selector_number">'; inlineQty += '<div class="input-group">'; //Input group addon text switch (selector_type) { case 'barcode_number': inlineQty += '<span class="input-group-addon" id="selector_text">BARCODE NUMBER</span>'; break; case 'invoice_number': inlineQty += '<span class="input-group-addon" id="selector_text">INVOICE NUMBER</span>'; break; case 'customer_issue': inlineQty += '<span class="input-group-addon" id="selector_text">CUSTOMER ISSUE</span>'; break; } inlineQty += '<div class="input-group-btn">'; inlineQty += '<button tabindex="-1" data-toggle="dropdown" class="btn btn-default dropdown-toggle" type="button">'; inlineQty += '<span class="caret"></span>'; inlineQty += '<span class="sr-only">Toggle Dropdown</span>'; inlineQty += '</button>'; inlineQty += '<ul class="dropdown-menu hide" style="list-style:none;margin: 2px 0 0;">'; inlineQty += '<li><a href="#">BARCODE NUMBER</a></li>'; inlineQty += '<li><a href="#">INVOICE NUMBER</a></li>'; inlineQty += '<li><a href="#">CUSTOMER APP</a></li>'; inlineQty += '<li><a href="#">CUSTOMER PORTAL</a></li>'; inlineQty += '<li><a href="#">UPDATE LABEL</a></li>'; inlineQty += '</ul>'; inlineQty += '</div>'; //Input text switch (selector_type) { case 'barcode_number': inlineQty += '<input id="selector_value" class="form-control selector_value" placeholder="MPEN123456">'; break; case 'invoice_number': inlineQty += '<input id="selector_value" class="form-control selector_value" placeholder="INV123456">'; break; case 'customer_app': inlineQty += '<input id="selector_value" class="form-control selector_value" placeholder="Customer App" disabled value="Customer App">'; break; case 'customer_portal': inlineQty += '<input id="selector_value" class="form-control selector_value" placeholder="Customer Portal" disabled value="Customer Portal">'; break; case 'update_label': inlineQty += '<input id="selector_value" class="form-control selector_value" placeholder="Update Label" disabled value="Update Label">'; break; } inlineQty += '</div></div></div></div>'; } return inlineQty; } /** * Used to pass the values of `date_from` and `date_to` between the scripts and to Netsuite for the records and the search. * @param {String} date_iso "2020-06-01" * @returns {String} date_netsuite "1/6/2020" */ function dateISOToNetsuite(date_iso) { var date_netsuite = ''; if (!isNullorEmpty(date_iso)) { var date_netsuite = format.format({ value: date_iso, type: format.Type.DATETIME }); } return date_netsuite; } /** * The informations regarding the ticket being edited. * @param {String} date_created * @param {Number} creator_id * @param {String} creator_name * @param {String} status * @return {String} inlineQty */ function ticketSection(date_created, creator_id, creator_name, status, customer_ticket_status) { if (isNullorEmpty(date_created)) { date_created = ''; } if (isNullorEmpty(creator_name)) { creator_name = ''; } if (isNullorEmpty(status)) { status = ''; } var inlineQty = '<div class="form-group container created_status_section">'; inlineQty += '<div class="row">'; // Date created field inlineQty += '<div class="col-xs-6 date_created">'; inlineQty += '<div class="input-group">'; inlineQty += '<span class="input-group-addon" id="date_created_text">DATE CREATED</span>'; inlineQty += '<input id="date_created" value="' + date_created + '" class="form-control date_created" disabled />'; inlineQty += '</div></div>'; // Creator field inlineQty += '<div class="col-xs-6 creator">'; inlineQty += '<div class="input-group">'; inlineQty += '<span class="input-group-addon" id="creator_text">CREATOR</span>'; inlineQty += '<input id="creator" value="' + creator_name + '" data-creator-id="' + creator_id + '" class="form-control creator" disabled />'; inlineQty += '</div></div></div></div>'; // Status Section inlineQty += '<div class="form-group container status_section">'; inlineQty += '<div class="row">'; // Status field inlineQty += '<div class="col-xs-6 status">'; inlineQty += '<div class="input-group">'; inlineQty += '<span class="input-group-addon" id="status_text">STATUS</span>'; inlineQty += '<input id="status" value="' + status + '" class="form-control status" disabled />'; inlineQty += '</div></div>'; // Customer Status field inlineQty += '<div class="col-xs-6 status">'; inlineQty += '<div class="input-group">'; inlineQty += '<span class="input-group-addon" id="status_text">CUSTOMER STATUS</span>'; inlineQty += '<input id="status" value="' + customer_ticket_status + '" class="form-control status" disabled />'; inlineQty += '</div></div></div></div>'; return inlineQty; } /** * The Customer name field. * The customer name field should be automatically filled based on the Selector number value. * @param {String} customer_name * @return {String} inlineQty */ function customerSection(customer_name) { if (isNullorEmpty(customer_name)) { customer_name = ''; } // Customer Section var inlineQty = '<div class="form-group container customer_section">'; inlineQty += '<div class="row">'; // Customer name field inlineQty += '<div class="col-xs-12 customer_name">'; inlineQty += '<div class="input-group">'; inlineQty += '<span class="input-group-addon" id="customer_name_text">CUSTOMER NAME</span>'; inlineQty += '<input id="customer_name" value="' + customer_name + '" class="form-control customer_name" disabled>'; inlineQty += '</div></div></div></div>'; return inlineQty; } /** * The day to day phone and email fields of the customer. * These fields should be automatically filled based on the Selector number value. * @param {String} daytodayphone * @param {String} daytodayemail * @param {Number} status_value * @param {String} selector_type * @return {String} inlineQty */ function daytodayContactSection(daytodayphone, daytodayemail, status_value, selector_type) { if (isNullorEmpty(daytodayphone)) { daytodayphone = ''; } if (isNullorEmpty(daytodayemail)) { daytodayemail = ''; } var disabled = 'disabled'; if ((isFinanceRole(userRole)) && isTicketNotClosed(status_value) && selector_type == 'invoice_number') { disabled = ''; } var inlineQty = '<div class="form-group container daytodaycontact_section">'; inlineQty += '<div class="row">'; // Day to day email field inlineQty += '<div class="col-xs-6 daytodayemail_div">'; inlineQty += '<div class="input-group">'; inlineQty += '<span class="input-group-addon" id="daytodayemail_text">DAY-TO-DAY EMAIL</span>'; inlineQty += '<input id="daytodayemail" type="email" value="' + daytodayemail + '" class="form-control daytodayemail" ' + disabled + ' />'; inlineQty += '<div class="input-group-btn">'; inlineQty += '<button type="button" style="background-color: #379E8F" class="btn btn-success add_as_recipient" data-email="' + daytodayemail + '" data-contact-id="" data-firstname="" data-toggle="tooltip" data-placement="right" title="Add as recipient">'; inlineQty += '<span class="glyphicon glyphicon-envelope"></span>'; inlineQty += '</button>'; inlineQty += '</div>'; inlineQty += '</div></div>'; // Day to day phone field inlineQty += '<div class="col-xs-6 daytodayphone_div">'; inlineQty += '<div class="input-group">'; inlineQty += '<span class="input-group-addon" id="daytodayphone_text">DAY-TO-DAY PHONE</span>'; inlineQty += '<input id="daytodayphone" type="tel" value="' + daytodayphone + '" class="form-control daytodayphone" ' + disabled + ' />'; inlineQty += '<div class="input-group-btn"><button type="button" style="background-color: #379E8F" class="btn btn-success" id="call_daytoday_phone"><span class="glyphicon glyphicon-earphone"></span></button></div>'; inlineQty += '</div></div></div></div>'; return inlineQty; } /** * The accounts phone and email fields of the customer. * These fields should be automatically filled based on the Invoice number value. * @param {String} accountsphone * @param {String} accountsemail * @param {Number} status_value * @param {String} selector_type * @return {String} inlineQty */ function accountsContactSection(accountsphone, accountsemail, status_value, selector_type) { if (isNullorEmpty(accountsphone)) { accountsphone = ''; } if (isNullorEmpty(accountsemail)) { accountsemail = ''; } if (selector_type == 'invoice_number') { var inlineQty = '<div class="form-group container accountscontact_section">'; if (isFinanceRole(userRole) && isTicketNotClosed(status_value)) { var disabled = ''; } else { var disabled = 'disabled'; } } else { var inlineQty = '<div class="form-group container accountscontact_section hide">'; var disabled = 'disabled'; } inlineQty += '<div class="row">'; // Accounts email field inlineQty += '<div class="col-xs-6 accountsemail_div">'; inlineQty += '<div class="input-group">'; inlineQty += '<span class="input-group-addon" id="accountsemail_text">ACCOUNTS EMAIL</span>'; inlineQty += '<input id="accountsemail" type="email" value="' + accountsemail + '" class="form-control accountsemail" ' + disabled + ' />'; inlineQty += '<div class="input-group-btn">'; inlineQty += '<button type="button" class="btn btn-success add_as_recipient" data-email="' + accountsemail + '" data-contact-id="" data-firstname="" data-toggle="tooltip" data-placement="right" title="Add as recipient">'; inlineQty += '<span class="glyphicon glyphicon-envelope"></span>'; inlineQty += '</button>'; inlineQty += '</div>'; inlineQty += '</div></div>'; // Accounts phone field inlineQty += '<div class="col-xs-6 accountsphone_div">'; inlineQty += '<div class="input-group">'; inlineQty += '<span class="input-group-addon" id="accountsphone_text">ACCOUNTS PHONE</span>'; inlineQty += '<input id="accountsphone" type="tel" value="' + accountsphone + '" class="form-control accountsphone" ' + disabled + ' />'; inlineQty += '<div class="input-group-btn"><button type="button" style="background-color: #379E8F" class="btn btn-success" id="call_accounts_phone"><span class="glyphicon glyphicon-earphone"></span></button></div>'; inlineQty += '</div></div></div></div>'; return inlineQty; } /** * * @param {Number} maap_bank_account_number * @param {Number} maap_parent_bank_account_number * @param {String} selector_type * @returns {String} inlineQty */ function maapBankAccountSection(maap_bank_account_number, maap_parent_bank_account_number, selector_type) { switch (selector_type) { case 'barcode_number': var inlineQty = '<div class="form-group container accounts_number_section hide">'; break; case 'invoice_number': var inlineQty = '<div class="form-group container accounts_number_section">'; break; } inlineQty += '<div class="row">'; // MAAP Bank Account # field inlineQty += '<div class="col-xs-6 account_number_div">'; inlineQty += '<div class="input-group">'; inlineQty += '<span class="input-group-addon" id="account_number_text">MAAP BANK ACCOUNT #</span>'; inlineQty += '<input id="account_number" type="number" value="' + maap_bank_account_number + '" class="form-control account_number" disabled />'; inlineQty += '</div></div>'; // MAAP Parent Bank Account # field inlineQty += '<div class="col-xs-6 parent_account_number_div">'; inlineQty += '<div class="input-group">'; inlineQty += '<span class="input-group-addon" id="parent_account_number_text">MAAP PARENT BANK ACCOUNT #</span>'; inlineQty += '<input id="parent_account_number" type="number" value="' + maap_parent_bank_account_number + '" class="form-control parent_account_number" disabled />'; inlineQty += '</div></div></div></div>'; return inlineQty; } /** * The Franchisee name, and its main contact name and phone number fields. * These fields should be automatically filled based on the Selector number value. * @param {String} franchisee_name * @param {String} zee_main_contact_name * @param {String} zee_email * @param {String} zee_main_contact_phone * @param {String} zee_abn * @return {String} inlineQty */ function franchiseeMainContactSection(franchisee_name, zee_main_contact_name, zee_email, zee_main_contact_phone, zee_abn) { if (isNullorEmpty(franchisee_name)) { franchisee_name = ''; } if (isNullorEmpty(zee_main_contact_name)) { zee_main_contact_name = ''; } if (isNullorEmpty(zee_email)) { zee_email = ''; } if (isNullorEmpty(zee_main_contact_phone)) { zee_main_contact_phone = ''; } if (isNullorEmpty(zee_abn)) { zee_abn = ''; } var inlineQty = '<div class="form-group container zee_main_contact_section">'; inlineQty += '<div class="row">'; // Franchisee name field inlineQty += '<div class="col-xs-6 franchisee_name">'; inlineQty += '<div class="input-group">'; inlineQty += '<span class="input-group-addon" id="franchisee_name_text">FRANCHISEE NAME</span>'; inlineQty += '<input id="franchisee_name" value="' + franchisee_name + '" class="form-control franchisee_name" disabled>'; inlineQty += '</div></div>'; // Franchisee main contact name field inlineQty += '<div class="col-xs-6 zee_main_contact_name">'; inlineQty += '<div class="input-group">'; inlineQty += '<span class="input-group-addon" id="zee_main_contact_name_text">MAIN CONTACT</span>'; inlineQty += '<input id="zee_main_contact_name" value="' + zee_main_contact_name + '" class="form-control zee_main_contact_name" disabled>'; inlineQty += '</div></div></div></div>'; // Franchisee contact details inlineQty += '<div class="form-group container zee_main_contact_section">'; inlineQty += '<div class="row">'; // Franchisee email field inlineQty += '<div class="col-xs-12 zee_email">'; inlineQty += '<div class="input-group">'; inlineQty += '<span class="input-group-addon" id="zee_email_text">FRANCHISEE EMAIL</span>'; inlineQty += '<input id="zee_email" type="email" value="' + zee_email + '" class="form-control accountsemail" disabled />'; inlineQty += '<div class="input-group-btn">'; var zee_contact_id = '0'; inlineQty += '<button type="button" style="background-color: #379E8F" class="btn btn-success add_as_recipient" data-email="' + zee_email + '" data-contact-id="' + zee_contact_id + '" data-firstname="' + franchisee_name + '" data-toggle="tooltip" data-placement="right" title="Add as recipient">'; inlineQty += '<span class="glyphicon glyphicon-envelope"></span>'; inlineQty += '</button>'; inlineQty += '</div>'; inlineQty += '</div></div></div></div>'; // Franchisee phone and ABN details inlineQty += '<div class="form-group container zee_main_contact_section">'; inlineQty += '<div class="row">'; // Franchisee main contact phone field inlineQty += '<div class="col-xs-6 zee_main_contact_phone">' inlineQty += '<div class="input-group">' inlineQty += '<span class="input-group-addon" id="zee_main_contact_phone_text">FRANCHISEE PHONE</span>'; inlineQty += '<input id="zee_main_contact_phone" type="tel" value="' + zee_main_contact_phone + '" class="form-control zee_main_contact_phone" disabled />'; inlineQty += '<div class="input-group-btn"><button style="background-color: #379E8F" type="button" class="btn btn-success" id="call_zee_main_contact_phone"><span class="glyphicon glyphicon-earphone"></span></button>'; inlineQty += '</div>'; inlineQty += '</div></div>'; // Franchisee ABN number inlineQty += '<div class="col-xs-6 zee_abn">' inlineQty += '<div class="input-group">' inlineQty += '<span class="input-group-addon" id="zee_abn_text">FRANCHISEE ABN</span>' inlineQty += '<input id="zee_abn" class="form-control zee_abn" value="' + zee_abn + '" disabled>' inlineQty += '</div></div></div></div>'; return inlineQty; } /** * The MPEX Date and Time Stock used fields. * Visible only for the barcode records. * @param {String} selector_type * @param {String} date_stock_used * @param {String} time_stock_used * @return {String} inlineQty */ function mpexStockUsedSection(selector_type, date_stock_used, time_stock_used) { if (isNullorEmpty(date_stock_used)) { date_stock_used = '' } if (isNullorEmpty(time_stock_used)) { time_stock_used = '' } var hide_class = (selector_type == 'barcode_number') ? '' : 'hide'; // MPEX Stock Used Section var inlineQty = '<div class="form-group container mpex_stock_used_section ' + hide_class + '">'; inlineQty += '<div class="row">'; // Date Stock Used inlineQty += ' <div class="col-xs-6 date_stock_used">'; inlineQty += '<div class="input-group">'; inlineQty += '<span class="input-group-addon" id="date_stock_used_text">DATE STOCK USED</span>'; inlineQty += '<input id="date_stock_used" class="form-control date_stock_used" value="' + date_stock_used + '" disabled>'; inlineQty += '</div></div>'; // Time Stock Used inlineQty += '<div class="col-xs-6 time_stock_used">'; inlineQty += '<div class="input-group">'; inlineQty += '<span class="input-group-addon" id="time_stock_used_text">TIME STOCK USED</span>'; inlineQty += '<input id="time_stock_used" class="form-control time_stock_used" value="' + time_stock_used + '" disabled>'; inlineQty += '</div></div></div></div>'; return inlineQty; } /** * The MPEX Final Delivery field is visible only for the barcode records. * The Enquiry Status field is not disabled only for the ticket that have not yet been opened. * @param {Number} status_value * @param {String} selector_type * @param {String} final_delivery_text * @param {Number} selected_enquiry_status_id * @return {String} inlineQty */ function finalDeliveryEnquirySection(status_value, selector_type, final_delivery_text, selected_enquiry_status_id, prod_stock_invoice) { if (isNullorEmpty(final_delivery_text)) { final_delivery_text = '' } if (isNullorEmpty(selected_enquiry_status_id)) { selected_enquiry_status_id = '' } var barcode_hide_class = (selector_type == 'barcode_number') ? '' : 'hide'; var nb_col_enquiry_section = (selector_type == 'barcode_number') ? '6' : '12'; var enquiry_disabled = (isTicketNotClosed(status_value)) ? '' : 'disabled'; // Final Delivery + Enquiry Status Section var inlineQty = '<div class="form-group container final_delivery_enquiry_status_section">'; inlineQty += '<div class="row">'; // Final Delivery inlineQty += '<div class="col-xs-6 final_delivery ' + barcode_hide_class + '">'; inlineQty += '<div class="input-group">'; inlineQty += '<span class="input-group-addon" id="final_delivery_text">FINAL DELIVERY</span>'; inlineQty += '<input id="final_delivery" class="form-control final_delivery" value="' + final_delivery_text + '" disabled>'; inlineQty += '</div></div>'; // Final Delivery inlineQty += '<div class="col-xs-6 invoice ' + barcode_hide_class + '">'; inlineQty += '<div class="input-group">'; inlineQty += '<span class="input-group-addon" id="invoice_text">INVOICE</span>'; inlineQty += '<input id="invoice" class="form-control invoice" value="' + prod_stock_invoice + '" disabled>'; inlineQty += '</div></div>'; inlineQty += '</div></div>'; return inlineQty; } /** * The Attachments field (an editable hyperlink) * @param {String} attachments_hyperlink * @param {Number} status_value * @returns {String} inlineQty */ function attachmentsSection(attachments_hyperlink, status_value) { var inlineQty = ''; if (!isNullorEmpty(attachments_hyperlink)) { var disabled = (isTicketNotClosed(status_value)) ? '' : 'disabled'; inlineQty += '<div class="form-group container attachments_section">'; inlineQty += '<div class="row">'; inlineQty += '<div class="col-xs-12 attachments_div">'; inlineQty += '<div class="input-group">'; inlineQty += '<span class="input-group-addon" id="attachments_text">ATTACHMENTS</span>' inlineQty += '<input id="attachments" class="form-control attachments" type="url" value="' + attachments_hyperlink + '" ' + 'disabled' + '/>'; inlineQty += '</div></div></div></div>'; } return inlineQty; } /** * Section containing enquiry medium type and the enquiry status of the ticket enquiry * @param list_enquiry_mediums {String}atus and * @param total_enquiry_count {Number} * @param selector_type {String} * @param status_value {Number} * @returns {string} */ function enquiryMediumSection(list_enquiry_mediums, selected_enquiry_status_id, selector_type){ //Search for enquiry mediums var hasEnquiryMediums = (!isNullorEmpty(list_enquiry_mediums)); var enquiryMediumColumns = new Array(); enquiryMediumColumns[0] = search.createColumn({ name: 'name' }); enquiryMediumColumns[1] = search.createColumn({ name: 'internalId' }); var enquiryMediumResultSet = search.create({ type: 'customlist_ticket_enquiry_mediums', columns: enquiryMediumColumns, }); //Ticket Enquiry Header // var inlineQty = '<div class="form-group container ticket_enquiry_header_section">'; // inlineQty += '<div class="row">'; // inlineQty += '<div class="col-xs-12 heading2">'; // inlineQty += '<h4><span style="background-color: #379E8F" class="label label-default col-xs-12">TICKET ENQUIRY DETAILS</span></h4>'; // inlineQty += '</div></div></div>'; //Enquiry Medium HTML var inlineQty = '<div class="form-group container enquiry_medium_section">'; inlineQty += '<div class="row">'; inlineQty += '<div class="col-xs-6 enquiry_medium_div">'; inlineQty += '<div class="input-group">'; inlineQty += '<span class="input-group-addon" id="enquiry_medium_text">ENQUIRY MEDIUM</span>'; inlineQty += '<select multiple id="enquiry_medium_status" class="form-control enquiry_medium_status" size="'+ enquiryMediumResultSet.length + '" disabled>'; enquiryMediumResultSet.run().each(function (enquiryMediumResult) { var enquiryMediumName = enquiryMediumResult.getValue('name'); var enquiryMediumId = enquiryMediumResult.getValue('internalId'); var selected = false; if(hasEnquiryMediums){ selected = (list_enquiry_mediums.indexOf(enquiryMediumId) !== -1); } if(selected) { inlineQty += '<option value="' + enquiryMediumId + '"selected>' + enquiryMediumName + '</option>'; }else{ inlineQty += '<option value="' + enquiryMediumId + '">' + enquiryMediumName + '</option>'; } return true; }); inlineQty += '</select>'; inlineQty += '</div></div>'; // Enquiry Status var enquiry_status_columns = new Array(); enquiry_status_columns[0] = search.createColumn({ name: 'name' }); enquiry_status_columns[1] = search.createColumn({ name: 'internalId' }); var enquiryStatusResultSet = search.create({ type: 'customlist_mp_ticket_enquiry', columns: enquiry_status_columns, }); inlineQty += '<div class="col-xs-6 enquiry_status_div">'; inlineQty += '<div class="input-group">'; inlineQty += '<span class="input-group-addon" id="enquiry_status_text">ENQUIRY STATUS</span>'; inlineQty += '<select id="enquiry_status" class="form-control enquiry_status">'; inlineQty += '<option></option>'; enquiryStatusResultSet.run().each(function (enquiryStatusResult) { var enquiry_status_name = enquiryStatusResult.getValue('name'); var enquiry_status_id = enquiryStatusResult.getValue('internalId'); if (enquiry_status_id == selected_enquiry_status_id) { inlineQty += '<option value="' + enquiry_status_id + '" selected>' + enquiry_status_name + '</option>'; } else { inlineQty += '<option value="' + enquiry_status_id + '">' + enquiry_status_name + '</option>'; } return true; }); inlineQty += '</select>'; inlineQty += '</div></div></div></div>'; return inlineQty; } /** * Section containing the total enquiry count and its breakdwn counts of chat, phone and email * @param total_enquiry_count * @param chat_enquiry_count * @param phone_enquiry_count * @param email_enquiry_count * @param selector_type * @returns {string} */ function enquiryCountSection( total_enquiry_count, chat_enquiry_count, phone_enquiry_count, email_enquiry_count, selector_type){ if (isNullorEmpty(total_enquiry_count)) { total_enquiry_count = 0;} if (isNullorEmpty(chat_enquiry_count)) { chat_enquiry_count = 0;} if (isNullorEmpty(phone_enquiry_count)) { phone_enquiry_count = 0;} if (isNullorEmpty(email_enquiry_count)) { email_enquiry_count = 0;} //Total Enquiry Count HTML var inlineQty = '<div class="form-group container enquiry_count_section">'; inlineQty += '<div class="row">'; inlineQty += '<div class="col-xs-12 total_enquiry_count_div">'; inlineQty += '<div class="input-group">'; inlineQty += '<span class="input-group-addon" id="total_enquiry_count_text">ENQUIRY COUNT</span>'; inlineQty += '<input id="total_enquiry_count" class="form-control enquiry_count" value="' + total_enquiry_count + '" disabled />'; inlineQty += '</div></div></div></div>'; //Enquiries by chat count inlineQty += '<div class="form-group container enquiry_count_breakdown_section">'; inlineQty += '<div class="row">'; inlineQty += '<div class="col-xs-4 enquiry_count_by_chat">'; inlineQty += '<div class="input-group">'; inlineQty += '<span class="input-group-addon" id="enquiry_count_by_chat_text"> CHAT ENQUIRY </span>'; inlineQty += '<input id="enquiry_count_by_chat" value="' + chat_enquiry_count + '" class="form-control enquiry_count_by_chat" disabled>'; inlineQty += '<div class="input-group-btn">'; inlineQty += '<button type="button" style="background-color: #379E8F" class="btn btn-success increment_enquiry_count_by_chat" data-firstname="" data-toggle="tooltip" data-placement="right" title="Increment Chat Enquiry Count">'; inlineQty += '<span class="glyphicon glyphicon-plus"></span>'; inlineQty += '</button>'; inlineQty += '<button type="button" class="btn btn-danger decrement_enquiry_count_by_chat" data-firstname="" data-toggle="tooltip" data-placement="right" title="Decrement Chat Enquiry Count">'; inlineQty += '<span class="glyphicon glyphicon-minus"></span>'; inlineQty += '</button>'; inlineQty += '</div></div></div>'; inlineQty += '<div class="col-xs-4 enquiry_count_by_phone">'; inlineQty += '<div class="input-group">'; inlineQty += '<span class="input-group-addon" id="enquiry_count_by_phone_text"> PHONE ENQUIRY </span>'; inlineQty += '<input id="enquiry_count_by_phone" value="' + phone_enquiry_count + '" class="form-control enquiry_count_by_phone" disabled>'; inlineQty += '<div class="input-group-btn">'; inlineQty += '<button type="button" style="background-color: #379E8F" class="btn btn-success increment_enquiry_count_by_phone" data-firstname="" data-toggle="tooltip" data-placement="right" title="Increment Phone Enquiry Count">'; inlineQty += '<span class="glyphicon glyphicon-plus"></span>'; inlineQty += '</button>'; inlineQty += '<button type="button" class="btn btn-danger decrement_enquiry_count_by_phone" data-firstname="" data-toggle="tooltip" data-placement="right" title="Decrement Phone Enquiry Count">'; inlineQty += '<span class="glyphicon glyphicon-minus"></span>'; inlineQty += '</button>'; inlineQty += '</div></div></div>'; inlineQty += '<div class="col-xs-4 enquiry_count_by_email">'; inlineQty += '<div class="input-group">'; inlineQty += '<span class="input-group-addon" id="enquiry_count_by_email_text"> EMAIL ENQUIRY </span>'; inlineQty += '<input id="enquiry_count_by_email" value="' + email_enquiry_count + '" class="form-control enquiry_count_by_email" disabled>'; inlineQty += '<div class="input-group-btn">'; inlineQty += '<button type="button" style="background-color: #379E8F" class="btn btn-success increment_enquiry_count_by_email" data-firstname="" data-toggle="tooltip" data-placement="right" title="Increment Email Enquiry Count">'; inlineQty += '<span class="glyphicon glyphicon-plus"></span>'; inlineQty += '</button>'; inlineQty += '<button type="button" class="btn btn-danger decrement_enquiry_count_by_email" data-firstname="" data-toggle="tooltip" data-placement="right" title="Decrement Email Enquiry Count">'; inlineQty += '<span class="glyphicon glyphicon-minus"></span>'; inlineQty += '</button>'; inlineQty += '</div></div></div></div></div>'; return inlineQty; } /** * @return {String} inlineQty */ function issuesHeader() { var inlineQty = '<div class="form-group container toll_issues_header_section">'; inlineQty += '<div class="row">'; inlineQty += '<div class="col-xs-12 heading1">'; inlineQty += '<h4><span style="background-color: #379E8F" class="form-group label label-default col-xs-12">ISSUES</span></h4>'; inlineQty += '</div></div></div>'; return inlineQty; } /** * @param {Number} status_value * @return {String} inlineQty */ function reminderSection(status_value) { var hide_class = (!isTicketNotClosed(status_value)) ? 'hide' : ''; var inlineQty = '<div class="form-group container reminder_section ' + hide_class + '">'; inlineQty += '<div class="row">'; // Reminder field inlineQty += '<div class="col-xs-12 reminder">'; inlineQty += '<div class="input-group">'; inlineQty += '<span class="input-group-addon" id="reminder_text">REMINDER</span>'; inlineQty += '<input id="reminder" class="form-control reminder" type="date" disabled />'; inlineQty += '</div></div></div></div>'; return inlineQty; } /** * Based on the selected MP Issue, an Owner is allocated to the ticket. * IT issues have priority over the other issues. * Populated with selectOwner() in the pageInit function on the client script. * @param {Number} ticket_id * @param {Array} owner_list * @param {Number} status_value * @return {String} inlineQty */ function ownerSection(ticket_id, owner_list, status_value) { if (isNullorEmpty(ticket_id)) { // If ticket_id is null, owner_list as well. // In that case, only the creator of the ticket is pre-selected as the owner. var userId = runtime.getCurrentUser().toString(); owner_list = [userId]; } var disabled = (!isTicketNotClosed(status_value)) ? 'disabled' : ''; var inlineQty = '<div class="form-group container owner_section">'; inlineQty += '<div class="row">'; inlineQty += '<div class="col-xs-12 owner">'; inlineQty += '<div class="input-group">'; inlineQty += '<span class="input-group-addon" id="owner_text">OWNER<span class="mandatory">*</span></span>'; inlineQty += '<select multiple id="owner" class="form-control owner" ' + 'disabled' + '>'; var employeeSearch = search.load({ type: 'employee', id: 'customsearch_active_employees' }); var employeeResultSet = employeeSearch.run(); employeeResultSet.each(function(employeeResult) { var employee_id = employeeResult.searchId; var employee_firstname = employeeResult.getValue('firstname'); var employee_lastname = employeeResult.getValue('lastname'); var employee_email = employeeResult.getValue('email'); if (owner_list.indexOf(employee_id) != -1) { inlineQty += '<option value="' + employee_id + '" data-email="' + employee_email + '" selected>' + employee_firstname + ' ' + employee_lastname + '</option>'; } else { inlineQty += '<option value="' + employee_id + '" data-email="' + employee_email + '">' + employee_firstname + ' ' + employee_lastname + '</option>'; } return true; }); inlineQty += '</select>'; inlineQty += '</div></div></div></div>'; return inlineQty; } /** * The multiselect TOLL issues dropdown * @param {Array} list_toll_issues * @param {Array} list_resolved_toll_issues * @param {Number} status_value * @param {String} selector_type * @return {String} inlineQty */ function tollIssuesSection(list_toll_issues, list_resolved_toll_issues, status_value, selector_type) { // TOLL Issues var has_toll_issues = (!isNullorEmpty(list_toll_issues)); var toll_issues_columns = new Array(); toll_issues_columns[0] = search.createColumn({ name: 'name' }); toll_issues_columns[1] = search.createColumn({ name: 'internalId' }); var tollIssuesResultSet = search.create({ type: 'customlist_cust_prod_stock_toll_issues', columns: toll_issues_columns }); if (!isTicketNotClosed(status_value) || selector_type != 'barcode_number') { var inlineQty = '<div class="form-group container toll_issues_section hide">'; } else { var inlineQty = '<div class="form-group container toll_issues_section">'; } inlineQty += '<div class="row">'; inlineQty += '<div class="col-xs-12 toll_issues">'; inlineQty += '<div class="input-group"><span class="input-group-addon" id="toll_issues_text">TOLL ISSUES<span class="mandatory">*</span></span>'; inlineQty += '<select multiple id="toll_issues" class="form-control toll_issues" disabled size="' + tollIssuesResultSet.length + '">'; tollIssuesResultSet.run().each(function(tollIssueResult) { var issue_name = tollIssueResult.getValue('name'); var issue_id = tollIssueResult.getValue('internalId'); var selected = false; if (has_toll_issues) { selected = (list_toll_issues.indexOf(issue_id) !== -1); } if (selected) { inlineQty += '<option value="' + issue_id + '" selected>' + issue_name + '</option>'; } else { inlineQty += '<option value="' + issue_id + '">' + issue_name + '</option>'; } return true; }); inlineQty += '</select>'; inlineQty += '</div></div></div></div>'; // Resolved TOLL Issues log.debug({ title: 'list_resolved_toll_issues : ', details: list_resolved_toll_issues }); var has_resolved_toll_issues = (!isNullorEmpty(list_resolved_toll_issues)); if (has_resolved_toll_issues) { var text_resolved_toll_issues = ''; tollIssuesResultSet.run().each(function(tollIssueResult) { var issue_name = tollIssueResult.getValue('name'); var issue_id = tollIssueResult.getValue('internalId'); if (list_resolved_toll_issues.indexOf(issue_id) !== -1) { text_resolved_toll_issues += issue_name + '\n'; } }); log.debug({ title: 'text_resolved_toll_issues : ', details: text_resolved_toll_issues }); inlineQty += '<div class="form-group container resolved_toll_issues_section">'; inlineQty += '<div class="row">'; inlineQty += '<div class="col-xs-12 resolved_toll_issues">'; inlineQty += '<div class="input-group">'; inlineQty += '<span class="input-group-addon" id="resolved_toll_issues_text">RESOLVED TOLL ISSUES</span>'; inlineQty += '<textarea id="resolved_toll_issues" class="form-control resolved_toll_issues" rows="' + list_resolved_toll_issues.length + '" disabled>' + text_resolved_toll_issues.trim() + '</textarea>'; inlineQty += '</div></div></div></div>'; } return inlineQty; }; /** * The free-from text area for comments. * @param {String} comment * @param {String} selector_type * @param {Number} status_value * @return {String} inlineQty */ function commentSection(comment, selector_type, status_value) { if (isNullorEmpty(comment)) { comment = ''; } else { comment += '\n'; } switch (selector_type) { case 'barcode_number': var inlineQty = '<div class="form-group container comment_section">'; break; case 'invoice_number': var inlineQty = '<div class="form-group container comment_section hide">'; break; case 'customer_issue': var inlineQty = '<div class="form-group container comment_section">'; break; } inlineQty += '<div class="row">'; inlineQty += '<div class="col-xs-12 comment">'; inlineQty += '<div class="input-group">'; inlineQty += '<span class="input-group-addon" id="comment_text">COMMENT<span class="mandatory hide">*</span></span>'; if (isTicketNotClosed(status_value)) { inlineQty += '<textarea id="comment" class="form-control comment" rows="3" disabled>' + comment + '</textarea>'; } else { inlineQty += '<textarea id="comment" class="form-control comment" rows="3" disabled readonly>' + comment + '</textarea>'; } inlineQty += '</div></div></div></div>'; return inlineQty; } /** * The customer contact details section. * Possibility for the user to add / edit the contacts. * @return {String} inlineQty */ function mpexContactSection() { // Contact details header var inlineQty = '<div class="form-group container mpex_contact_section">'; inlineQty += '<div class="row">'; inlineQty += '<div class="col-xs-12 heading2">'; inlineQty += '<h4><span style="background-color: #379E8F" class="label label-default col-xs-12">CONTACT DETAILS</span></h4>'; inlineQty += '</div>'; inlineQty += '</div></div>'; // Contact table inlineQty += '<div class="form-group container contacts_section" style="font-size: small;">'; inlineQty += '<div class="row">'; inlineQty += '<div class="col-xs-12 contacts_div">'; // Since the table is not displayed correctly when added through suitelet, // It is added with jQuery in the pageInit() function in the client script 'mp_cl_open_ticket.js'. inlineQty += '</div>'; inlineQty += '</div>'; inlineQty += '</div>'; // Add/edit contacts button inlineQty += '<div class="form-group container reviewcontacts_section">'; inlineQty += '<div class="row">'; inlineQty += '<div class="col-xs-4 col-xs-offset-4 reviewcontacts">'; inlineQty += '<input type="button" style="background-color: #379E8F; border-color: #379E8F; font-weight: 700" value="ADD/EDIT CONTACTS" class="form-control btn btn-primary" id="reviewcontacts" />'; inlineQty += '</div></div></div>'; return inlineQty; }; /** * The receiver phone and email fields. * These fields should be automatically filled based on the Selector number value. * @param {String} daytodayphone * @param {String} daytodayemail * @param {Number} status_value * @param {String} selector_type * @return {String} inlineQty */ function receiverEmailPhone(selector_type, receiveremail, receiverphone, receivername, receiverstate, receiverzip, receiversuburb, receiveraddr1, receiveraddr2) { var disabled = 'disabled'; var inlineQty = ''; if (selector_type == 'barcode_number') { // Receiver details header var inlineQty = '<div class="form-group container tickets_details_header_section">'; inlineQty += '<div class="row">'; inlineQty += '<div class="col-xs-12 heading2" >'; inlineQty += '<h4><span style="background-color: #379E8F" class="label label-default col-xs-12">RECEIVER DETAILS</span></h4>'; inlineQty += '</div></div></div>'; inlineQty += '<div class="form-group container receivercontact_section">'; inlineQty += '<div class="row">'; // name field inlineQty += '<div class="col-xs-6 receivername_div">'; inlineQty += '<div class="input-group">'; inlineQty += '<span class="input-group-addon" id="receivername_text">NAME</span>'; inlineQty += '<input id="receivername" value="' + receivername + '" class="form-control receivername" ' + disabled + ' />'; inlineQty += '</div></div>'; // state field inlineQty += '<div class="col-xs-6 receiverstate_div">'; inlineQty += '<div class="input-group">'; inlineQty += '<span class="input-group-addon" id="receiverstate_text">STATE</span>'; inlineQty += '<input id="receiverstate" value="' + receiverstate + '" class="form-control receiverstate" ' + disabled + ' />'; inlineQty += '</div></div></div></div>'; inlineQty += '<div class="form-group container receivercontact2_section">'; inlineQty += '<div class="row">'; // Day to day email field inlineQty += '<div class="col-xs-6 receiveremail_div">'; inlineQty += '<div class="input-group">'; inlineQty += '<span class="input-group-addon" id="receiveremail_text">EMAIL</span>'; inlineQty += '<input id="receiveremail" type="email" value="' + receiveremail + '" class="form-control receiveremail" ' + disabled + ' />'; inlineQty += '<div class="input-group-btn">'; inlineQty += '<button type="button" style="background-color: #379E8F" class="btn btn-success add_as_recipient" data-email="' + receiveremail + '" data-contact-id="" data-firstname="" data-toggle="tooltip" data-placement="right" title="Add as recipient">'; inlineQty += '<span class="glyphicon glyphicon-envelope"></span>'; inlineQty += '</button>'; inlineQty += '</div>'; inlineQty += '</div></div>'; // Day to day phone field inlineQty += '<div class="col-xs-6 receiverphone_div">'; inlineQty += '<div class="input-group">'; inlineQty += '<span class="input-group-addon" id="receiverphone_text">PHONE</span>'; inlineQty += '<input id="receiverphone" type="tel" value="' + receiverphone + '" class="form-control receiverphone" ' + disabled + ' />'; inlineQty += '<div class="input-group-btn"><button type="button" style="background-color: #379E8F" class="btn btn-success" id="call_receiver_phone"><span class="glyphicon glyphicon-earphone"></span></button></div>'; inlineQty += '</div></div></div></div>'; inlineQty += '<div class="form-group container receivercontact3_section">'; inlineQty += '<div class="row">'; // suburb field inlineQty += '<div class="col-xs-6 receiversuburb_div">'; inlineQty += '<div class="input-group">'; inlineQty += '<span class="input-group-addon" id="receiversuburb_text">SUBURB</span>'; inlineQty += '<input id="receiversuburb" value="' + receiversuburb + '" class="form-control receiversuburb" ' + disabled + ' />'; inlineQty += '</div></div>'; // postcode field inlineQty += '<div class="col-xs-6 receiverzip_div">'; inlineQty += '<div class="input-group">'; inlineQty += '<span class="input-group-addon" id="receiverzip_text">POSTCODE</span>'; inlineQty += '<input id="receiverzip" value="' + receiverzip + '" class="form-control receiverzip" ' + disabled + ' />'; inlineQty += '</div></div></div></div>'; inlineQty += '<div class="form-group container receivercontact4_section">'; inlineQty += '<div class="row">'; // address1 field inlineQty += '<div class="col-xs-6 receiveraddr1_div">'; inlineQty += '<div class="input-group">'; inlineQty += '<span class="input-group-addon" id="receiveraddr1_text">ADDRESS1</span>'; inlineQty += '<input id="receiveraddr1" value="' + receiveraddr1 + '" class="form-control receiveraddr1" ' + disabled + ' />'; inlineQty += '</div></div>'; // address2 field inlineQty += '<div class="col-xs-6 receiveraddr2_div">'; inlineQty += '<div class="input-group">'; inlineQty += '<span class="input-group-addon" id="receiveraddr2_text">ADDRESS2</span>'; inlineQty += '<input id="receiveraddr2" value="' + receiveraddr2 + '" class="form-control receiveraddr2" ' + disabled + ' />'; inlineQty += '</div></div></div></div>'; } return inlineQty; } /** * The "Send Email" section. * Possibility for the user to send an email to the customer, based on selected templates. * @param {Number} ticket_id * @param {Number} status_value * @param {Object} account_manager * @returns {String} inlineQty */ function sendEmailSection(ticket_id, status_value, account_manager, list_toll_emails) { var has_toll_emails = (!isNullorEmpty(list_toll_emails)); if (isNullorEmpty(ticket_id) || !isTicketNotClosed(status_value)) { // The section is hidden here rather than in the openTicket function, // because we use the section to send an acknoledgement email when a ticket is opened. var inlineQty = '<div id="send_email_container" class="send_email hide">'; } else { var inlineQty = '<div id="send_email_container" class="send_email">'; } inlineQty += '<div class="form-group container send_email header_section">'; // Send email header inlineQty += '<div class="row">'; inlineQty += '<div class="col-xs-12 heading2">'; inlineQty += '<h4><span style="background-color: #379E8F" class="label label-default col-xs-12">SEND EMAILS</span></h4>'; inlineQty += '</div></div></div>'; inlineQty += '<br></br>' // Row addressees inlineQty += '<div class="form-group container send_email adressees_section">'; inlineQty += '<div class="row">'; inlineQty += '<div class="col-xs-12 to_section">'; inlineQty += '<div class="input-group">'; inlineQty += '<span class="input-group-addon">TO<span class="mandatory">*</span></span>'; inlineQty += '<input id="send_to" class="form-control" data-contact-id="" data-firstname=""/>'; inlineQty += '</div></div></div></div>'; // Toll addresses var toll_emails_columns = new Array(); toll_emails_columns[0] = search.createColumn({ name: 'name' }); toll_emails_columns[1] = search.createColumn({ name: 'internalId' }); var tollEmailsResultSet = search.create({ type: 'customlist_toll_emails', columns: toll_emails_columns, }) inlineQty += '<div class="form-group container send_email toll_adressees_section">'; inlineQty += '<div class="row">'; inlineQty += '<div class="col-xs-12 toll_section">'; inlineQty += '<div class="input-group">'; inlineQty += '<span class="input-group-addon">TOLL EMAILS</span>'; inlineQty += '<select multiple id="send_toll" class="form-control" size="' + tollEmailsResultSet.length + '"/>'; tollEmailsResultSet.run().each(function (tollEmailsResultSet){ var tollEmailName = tollEmailsResultSet.getValue('name'); var tollEmailId = tollEmailsResultSet.getValue('internalId'); var selected = false; if(has_toll_emails) { selected = (list_toll_emails.indexOf(tollEmailId) !== -1); } if (selected) { inlineQty += '<option value="' + tollEmailId + '" selected>' + tollEmailName + '</option>'; } else { inlineQty += '<option value="' + tollEmailId + '">' + tollEmailName + '</option>'; } return true; }); inlineQty += '</select>'; inlineQty += '</div></div></div></div>'; // Row ccs addresses inlineQty += '<div class="form-group container send_email cc_adressees_section">'; inlineQty += '<div class="row">'; inlineQty += '<div class="col-xs-6 cc_section">'; inlineQty += '<div class="input-group">'; inlineQty += '<span class="input-group-addon">CC</span>'; inlineQty += '<input id="send_cc" class="form-control"/>'; inlineQty += '</div></div>'; inlineQty += '<div class="col-xs-6 bcc_section">'; inlineQty += '<div class="input-group">'; inlineQty += '<span class="input-group-addon">BCC</span>'; inlineQty += '<input id="send_bcc" class="form-control"/>'; inlineQty += '</div></div></div></div>'; // Row account manager if (isNullorEmpty(account_manager.name)) { account_manager.name = '' } if (isNullorEmpty(account_manager.email)) { account_manager.email = '' } if (!isNullorEmpty(account_manager.email.email)) { inlineQty += '<div class="form-group container send_email acc_manager_section">'; inlineQty += '<div class="row">'; inlineQty += '<div class="col-xs-10 acc_manager_name_section">'; inlineQty += '<div class="input-group">'; inlineQty += '<span class="input-group-addon">ACCOUNT MANAGER</span>'; inlineQty += '<input id="acc_manager" class="form-control" data-email="' + account_manager.email.email + '" value="' + account_manager.name + ' - ' + account_manager.email.email + '" disabled/>'; inlineQty += '</div></div>'; inlineQty += '<div class="col-xs-2 acc_manager_button_section">'; inlineQty += '<button id="acc_manager_button" style="background-color: #379E8F; border-color: #379E8F" type="button" class="btn btn-success btn-block">ADD TO CC</button>'; inlineQty += '</div></div></div>'; } // Row Template inlineQty += '<div class="form-group container send_email template_section">'; inlineQty += '<div class="row">'; inlineQty += '<div class="col-xs-12 template_section">'; inlineQty += '<div class="input-group">'; inlineQty += '<span class="input-group-addon">TEMPLATE<span class="mandatory">*</span></span>'; inlineQty += '<select id="template" class="form-control">'; inlineQty += '<option></option>'; // Load the template options var templatesSearch = search.load({ id: 'customsearch_cctemplate_mp_ticket', type: 'customrecord_camp_comm_template' }); var templatesSearchResults = templatesSearch.run(); templatesSearchResults.each(function(templatesSearchResult) { // var tempId = templatesSearchResult.getValue('internalid'); var tempId = templatesSearchResult["id"]; var tempName = templatesSearchResult.getValue('name'); inlineQty += '<option value="' + tempId + '">' + tempName + '</option>'; return true; }); inlineQty += '</select>'; inlineQty += '</div></div></div></div>'; // Row Subject inlineQty += '<div class="form-group container send_email subject_section">'; inlineQty += '<div class="row">'; inlineQty += '<div class="col-xs-12 subject_section">'; inlineQty += '<div class="input-group">'; inlineQty += '<span class="input-group-addon">SUBJECT<span class="mandatory">*</span></span>'; inlineQty += '<input id="subject" class="form-control" />'; inlineQty += '</div></div></div></div>'; // Row Body inlineQty += '<div class="form-group container send_email body_section">'; inlineQty += '<div class="row">'; inlineQty += '<div class="col-xs-12 body_section">'; inlineQty += '<div id="email_body"></div>'; inlineQty += '</div></div></div>'; // SEND EMAIL button inlineQty += '<div class="form-group container send_email button_section">'; inlineQty += '<div class="row">'; inlineQty += '<div class="col-xs-4 col-xs-offset-4 send_email_btn">'; inlineQty += '<input type="button" style="background-color: #379E8F; border-color: #379E8F; font-weight: 700" value="SEND EMAIL" class="form-control btn btn-primary" id="send_email" />'; inlineQty += '</div></div></div></div>'; return inlineQty; }; function externalBarcodeSource(selector_type, barcodempdl, barcodesource) { var disabled = 'disabled'; var inlineQty = ''; if (selector_type == 'barcode_number') { inlineQty += '<div class="form-group container barcode_section">'; inlineQty += '<div class="row">'; // MPLD field inlineQty += '<div class="col-xs-6 barcodempdl_div">'; inlineQty += '<div class="input-group">'; inlineQty += '<span class="input-group-addon" id="barcodempdl_text">EXTERNAL BARCODE</span>'; inlineQty += '<input id="barcodempdl" value="' + barcodempdl + '" class="form-control barcodempdl" ' + disabled + ' />'; inlineQty += '</div></div>'; // barcode source field inlineQty += '<div class="col-xs-6 barcodesource_div">'; inlineQty += '<div class="input-group">'; inlineQty += '<span class="input-group-addon" id="barcodesource_text">BARCODE SOURCE</span>'; inlineQty += '<input id="barcodesource" value="' + barcodesource + '" class="form-control barcodesource" ' + disabled + ' />'; inlineQty += '</div></div></div></div>'; } return inlineQty; } function tabsSection(customer_number, ticket_id, selector_number, selector_id, selector_type, status_value, date_created, creator_id, creator_name, status, customer_id, customer_name, daytodayphone, daytodayemail, accountsphone, accountsemail, maap_bank_account_number, maap_parent_bank_account_number, zee_id, franchisee_name, zee_main_contact_name, zee_email, zee_main_contact_phone, zee_abn, date_stock_used, time_stock_used, final_delivery_text, selected_enquiry_status_id,attachments_hyperlink, selected_enquiry_status_id, owner_list, list_toll_issues, list_resolved_toll_issues, comment, account_manager, list_toll_emails, customer_ticket_status, receiveremail, receiverphone, receivername, receiverstate, receiverzip, receiversuburb, receiveraddr1, receiveraddr2, barcodempdl, barcodesource, prod_stock_invoice) { var inlineQty = '<br/><div >'; // Tabs headers inlineQty += '<style>.nav > li.active > a, .nav > li.active > a:focus, .nav > li.active > a:hover { background-color: #379E8F; color: #fff }'; inlineQty += '.nav > li > a, .nav > li > a:focus, .nav > li > a:hover { margin-left: 5px; margin-right: 5px; border: 2px solid #379E8F; color: #379E8F; }'; inlineQty += '</style>'; // Ticket details header inlineQty += '<div class="form-group container tickets_details_header_section" style="margin-top: 10px">'; inlineQty += '<div class="row">'; inlineQty += '<div class="col-xs-12" >'; inlineQty += '<span">'; inlineQty += '<ul class="nav nav-pills nav-justified" style="margin:0%; ">'; inlineQty += '<li role="presentation" class="active"><a data-toggle="tab" href="#ticketdetails"><b>TICKET DETAILS</b></a></li>'; inlineQty += '<li role="presentation" class=""><a data-toggle="tab" href="#sendemails"><b>SEND EMAILS</b></a></li>'; inlineQty += '</ul>'; inlineQty += '</span>'; inlineQty += '</div></div></div>'; // Tabs content inlineQty += '<div class="tab-content">'; // TICKET DETAILS TAB inlineQty += '<div role="tabpanel" class="tab-pane active" id="ticketdetails">'; inlineQty += customerNumberSection(customer_number, ticket_id); inlineQty += selectorSection(ticket_id, selector_number, selector_id, selector_type, status_value); if (!isNullorEmpty(ticket_id)) { inlineQty += externalBarcodeSource(selector_type, barcodempdl, barcodesource) inlineQty += ticketSection(dateISOToNetsuite(date_created), creator_id, creator_name, status, customer_ticket_status); } if (isNullorEmpty(ticket_id) || (!isNullorEmpty(ticket_id) && !isNullorEmpty(customer_id)) || !isNullorEmpty(customer_number)) { inlineQty += customerSection(customer_name); inlineQty += daytodayContactSection(daytodayphone, daytodayemail, status_value, selector_type); inlineQty += accountsContactSection(accountsphone, accountsemail, status_value, selector_type); } if(isNullorEmpty(ticket_id) || (!isNullorEmpty(ticket_id) && (selector_type == 'invoice_section'))) { inlineQty += maapBankAccountSection(maap_bank_account_number, maap_parent_bank_account_number, selector_type); } if (isNullorEmpty(ticket_id) || (!isNullorEmpty(ticket_id) && !isNullorEmpty(zee_id)) || !isNullorEmpty(customer_number)) { inlineQty += franchiseeMainContactSection(franchisee_name, zee_main_contact_name, zee_email, zee_main_contact_phone, zee_abn); } inlineQty += mpexStockUsedSection(selector_type, date_stock_used, time_stock_used); inlineQty += finalDeliveryEnquirySection(status_value, selector_type, final_delivery_text, selected_enquiry_status_id, prod_stock_invoice); inlineQty += attachmentsSection(attachments_hyperlink, status_value); if(!isNullorEmpty(ticket_id)) { inlineQty += receiverEmailPhone(selector_type, receiveremail, receiverphone, receivername, receiverstate, receiverzip, receiversuburb, receiveraddr1, receiveraddr2); } // ENQUIRY SECTION //inlineQty += enquiryMediumSection(list_enquiry_mediums, selected_enquiry_status_id, selector_type) //inlineQty += enquiryCountSection( total_enquiry_count, chat_enquiry_count, phone_enquiry_count, email_enquiry_count, selector_type); //TICKET LABEL DROPDOWN //inlineQty += labelSection(selected_label_id, selector_type, status_value); //inlineQty += closeReopenSubmitTicketButton(ticket_id, status_value); inlineQty += issuesHeader(); inlineQty += reminderSection(status_value); inlineQty += ownerSection(ticket_id, owner_list, status_value); inlineQty += tollIssuesSection(list_toll_issues, list_resolved_toll_issues, status_value, selector_type); inlineQty += commentSection(comment, selector_type, status_value); inlineQty += '</div>'; // CONTACT / EMAILS if (!isNullorEmpty(ticket_id)) { inlineQty += '<div role="tabpanel" class="tab-pane" id="sendemails">'; inlineQty += mpexContactSection(); inlineQty += sendEmailSection(ticket_id, status_value, account_manager, list_toll_emails); //inlineQty += closeReopenSubmitTicketButton(ticket_id, status_value); inlineQty += '</div>'; } inlineQty += '</div></div>'; return inlineQty; } /** * Returns whether a ticket is closed or not based on its status value. * @param {Number} status_value * @returns {Boolean} is_ticket_closed */ function isTicketNotClosed(status_value) { var is_ticket_not_closed = ((status_value != 3) && (status_value != 8)) ? true : false; return is_ticket_not_closed; } /** * Whether the user is from the finance team, * or a Data Systems Co-ordinator, MailPlus Administration or Administrator user. * @param {Number} userRole * @returns {Boolean} */ function isFinanceRole(userRole) { // 1001, 1031 and 1023 are finance roles // 1032 is the Data Systems Co-ordinator role (to be deleted in prod) // 1006 is the Mail Plus Administration role. // 3 is the Administrator role. return ((userRole == 1001 || userRole == 1031 || userRole == 1023) || ((userRole == 1032) || (userRole == 1006) || (userRole == 3))); } function isNullorEmpty(strVal) { return (strVal == null || strVal == '' || strVal == 'null' || strVal == undefined || strVal == 'undefined' || strVal == '- None -'); } return { onRequest: onRequest }; });
true
/** * * @NApiVersion 2.0 * @NScriptType Suitelet * * Description: Separate page for escalating ticket * @Last Modified by: Sruti Desai * */ define(['N/ui/serverWidget', 'N/email', 'N/runtime', 'N/search', 'N/record', 'N/http', 'N/log', 'N/redirect', 'N/format'], function(ui, email, runtime, search, record, http, log, redirect, format) { var baseURL = 'https://1048144.app.netsuite.com'; if (runtime.envType == "SANDBOX") { baseURL = 'https://1048144-sb3.app.netsuite.com'; } var zee = 0; var role = runtime.getCurrentUser().role; var userRole = runtime.getCurrentUser().role; if (role == 1000) { //Franchisee zee = runtime.getCurrentUser(); } function onRequest(context) { if (context.request.method === 'GET') { var ticket_id = null; var customer_id = null; var customer_number = null; var selector_id = null; var selector_number = ''; var selector_type = 'barcode_number'; var date_created = ''; var creator_name = ''; var creator_id = null; var status_value = null; var status = ''; var customer_name = ''; var daytodayphone = ''; var daytodayemail = ''; var accountsphone = ''; var accountsemail = ''; var zee_id = null; var franchisee_name = ''; var zee_main_contact_name = ''; var zee_email = ''; var zee_main_contact_phone = ''; var zee_abn = ''; var date_stock_used = ''; var time_stock_used = ''; var final_delivery_text = ''; var selected_enquiry_status_id = null; var attachments_hyperlink = ''; var maap_bank_account_number = null; var maap_parent_bank_account_number = null; var selected_invoice_method_id = null; var accounts_cc_email = ''; var mpex_po_number = ''; var customer_po_number = ''; var terms = null; var customer_terms = ''; var account_manager = {}; var selected_invoice_cycle_id = null; var usage_report_id_1 = ''; var usage_report_id_2 = ''; var usage_report_id_3 = ''; var usage_report_id_4 = ''; var usage_report_array = []; var list_toll_issues = ''; var list_resolved_toll_issues = ''; var list_mp_ticket_issues = ''; var list_resolved_mp_ticket_issues = ''; var list_invoice_issues = ''; var list_resolved_invoice_issues = ''; var owner_list = ''; var comment = ''; var selected_label_id = null; var list_enquiry_mediums = ''; var total_enquiry_count = 0; var chat_enquiry_count = 0; var phone_enquiry_count = 0; var email_enquiry_count = 0; var list_toll_emails = ''; var params_email = { recipient: '', subject: '', body: '', cc: '', bcc: '', records: {}, attachments_credit_memo_ids: [], attachments_usage_report_ids: [], attachments_invoice_ids: [] }; var customer_issue = ''; var screenshot_file = ''; var browser = ''; var login_email_used = ''; var operating_system = ''; var phone_used = ''; var old_sender_name = ''; var old_sender_phone = ''; var customer_number_email_sent = 'F'; var customer_status_value = ''; var customer_ticket_status = ''; var customer_barcode_number = ''; var receiveremail = ''; var receiverphone = ''; var receivername = ''; var receiverstate = ''; var receiverzip = ''; var receiversuburb = ''; var receiveraddr1 = ''; var receiveraddr2 = ''; var prod_stock_invoice = ''; var barcodempdl = ''; var barcodesource = ''; // Load params var params = context.request.parameters.custparam_params; log.debug({ title: 'Params', details: params }) if (!isNullorEmpty(params)) { params = JSON.parse(params); log.debug({ title: 'Params not empty', details: params }); // Coming from the ticket_contact page or the edit_ticket page if (!isNullorEmpty(params.selector_number) && !isNullorEmpty(params.selector_type)) { selector_number = params.selector_number; selector_type = params.selector_type; //Coming from the ticket_contact page if (!isNullorEmpty(params.custid)) { customer_id = params.custid; } log.debug({ title: 'customer_id after ticket_contact_page : ', details: customer_id }); // Coming from the edit_ticket page if (!isNullorEmpty(params.ticket_id)) { ticket_id = parseInt(params.ticket_id); log.debug({ title: 'ticket id ISS', details: ticket_id }); // Load ticket data var ticketRecord = record.load({ type: 'customrecord_mp_ticket', id: ticket_id }); date_created = ticketRecord.getValue({ fieldId: 'created' }); creator_name = ticketRecord.getText({ fieldId: 'custrecord_creator' }); creator_id = ticketRecord.getValue({ fieldId: 'custrecord_creator' }); status_value = ticketRecord.getValue({ fieldId: 'custrecord_ticket_status' }); status = ticketRecord.getText({ fieldId: 'custrecord_ticket_status' }); customer_id = ticketRecord.getValue({ fieldId: 'custrecord_customer1' }); customer_name = ticketRecord.getText({ fieldId: 'custrecord_customer1' }); zee_id = ticketRecord.getValue({ fieldId: 'custrecord_zee' }); selected_enquiry_status_id = ticketRecord.getValue({ fieldId: 'custrecord_enquiry_status' }); attachments_hyperlink = ticketRecord.getValue({ fieldId: 'custrecord_mp_ticket_attachments' }); selected_label_id = ticketRecord.getValue({ fieldId: 'custrecord_ticket_label' }); list_enquiry_mediums = ticketRecord.getValue({ fieldId: 'custrecord_enquiry_medium' }); list_enquiry_mediums = java2jsArray(list_enquiry_mediums); total_enquiry_count = ticketRecord.getValue({ fieldId: 'custrecord_enquiry_count' }); chat_enquiry_count = ticketRecord.getValue({ fieldId: 'custrecord_chat_enquiry_count' }); phone_enquiry_count = ticketRecord.getValue({ fieldId: 'custrecord_phone_enquiry_count' }); email_enquiry_count = ticketRecord.getValue({ fieldId: 'custrecord_email_enquiry_count' }); customer_issue = ticketRecord.getValue({ fieldId: 'custrecord_customer_issue' }); screenshot_file = ticketRecord.getValue({ fieldId: 'custrecord_screenshot' }); browser = ticketRecord.getValue({ fieldId: 'custrecord_browser' }); login_email_used = ticketRecord.getValue({ fieldId: 'custrecord_login_email' }); operating_system = ticketRecord.getValue({ fieldId: 'custrecord_operating_system' }); phone_used = ticketRecord.getValue({ fieldId: 'custrecord_phone_used' }); customer_number = ticketRecord.getValue({ fieldId: 'custrecord_cust_number' }); old_sender_name = ticketRecord.getValue({ fieldId: 'custrecord_sender_name' }); old_sender_phone = ticketRecord.getValue({ fieldId: 'custrecord_sender_phone' }); customer_number_email_sent = ticketRecord.getValue({ fieldId: 'custrecord_customer_number_email_sent' }); customer_status_value = ticketRecord.getValue({fieldId: 'custrecord_mp_ticket_customer_status'}); customer_ticket_status = ticketRecord.getText({fieldId: 'custrecord_mp_ticket_customer_status'}); customer_barcode_number = ticketRecord.getValue({ fieldId : 'custrecord_barcode_number'}); if (!isNullorEmpty(customer_barcode_number)) { var rec = record.load({ type: 'customrecord_customer_product_stock', id: customer_barcode_number, }); receiveremail = rec.getValue({fieldId: 'custrecord_receiver_email'}); receiverphone = rec.getValue({fieldId: 'custrecord_receiver_phone'}); receivername = rec.getValue({fieldId: 'custrecord_receiver_name'}); receiverstate = rec.getValue({fieldId: 'custrecord_receiver_state'}); receiverzip = rec.getValue({fieldId: 'custrecord_receiver_postcode'}); receiversuburb = rec.getValue({fieldId: 'custrecord_receiver_suburb'}); receiveraddr1 = rec.getValue({fieldId: 'custrecord_receiver_addr1'}); receiveraddr2 = rec.getValue({fieldId: 'custrecord_receiver_addr2'}); prod_stock_invoice = rec.getText({fieldId: 'custrecord_prod_stock_invoice'}); barcodempdl = rec.getValue({fieldId: 'custrecord_mpdl_number'}); barcodesource = rec.getText({fieldId: 'custrecord_barcode_source'}); } if(isNullorEmpty(customer_id) && !isNullorEmpty(customer_number)){ var customer_search = search.load({ type: 'customer', id: 'customsearch_customer_name_2' }); customer_search.filters.push(search.createFilter({ name: 'entityid', operator: 'haskeywords', values: customer_number, })); customer_id = customer_search.run().getRange({ start: 0,end:1 })[0].getId(); } if (!isNullorEmpty(customer_id)) { //Load customer record and franchisee information var customerRecord = record.load({ type: 'customer', id: customer_id }); customer_number = customerRecord.getValue({ fieldId: 'entityid' }); daytodayphone = customerRecord.getValue({ fieldId: 'phone' }); daytodayemail = customerRecord.getValue({ fieldId: 'custentity_email_service' }); terms = customerRecord.getValue({ fieldId: 'terms' }); customer_terms = customerRecord.getValue({ fieldId: 'custentity_finance_terms' }); // Account manager var accountManagerSearch = search.load({ type: 'customer', id: 'customsearch3413' }); accountManagerSearch.filters.push(search.createFilter({ name: 'internalid', join: null, operator: search.Operator.ANYOF, values: customer_id, })) var accountManagerResultSet = accountManagerSearch.run(); var accountManagerResult = accountManagerResultSet.getRange({ start: 0, end: 1 }); accountManagerResult = accountManagerResult[0]; if (!isNullorEmpty(accountManagerResult)) { var account_manager_value = accountManagerResult.getValue({ name: "custrecord_sales_assigned", join: "CUSTRECORD_SALES_CUSTOMER", summary: null }); var account_manager_text = accountManagerResult.getText({ name: "custrecord_sales_assigned", join: "CUSTRECORD_SALES_CUSTOMER", summary: null }); if (!isNullorEmpty(account_manager_value)) { var account_manager_email = search.lookupFields({ type: 'employee', id: account_manager_value, columns: 'email' }); account_manager = { name: account_manager_text, email: account_manager_email }; } } // The Franchisee informations are imported from the customer record if possible. zee_id = customerRecord.getValue({ fieldId: 'partner' }); } if (!isNullorEmpty(zee_id)) { var zeeRecord = record.load({ type: 'partner', id: zee_id }); franchisee_name = zeeRecord.getValue({ fieldId: 'companyname' }); zee_main_contact_name = zeeRecord.getValue({ fieldId: 'custentity3' }); zee_email = zeeRecord.getValue({ fieldId: 'email' }); zee_main_contact_phone = zeeRecord.getValue({ fieldId: 'custentity2' }); zee_abn = zeeRecord.getValue({ fieldId: 'custentity_abn_franchiserecord' }); } else { franchisee_name = ticketRecord.getText({ fieldId: 'custrecord_zee' }); } switch (selector_type) { case 'barcode_number': selector_id = ticketRecord.getValue({ fieldId: 'custrecord_barcode_number' }); var stock_used = ''; if(!isNullorEmpty(selector_id)){ //Come in here only if selector_id is not null stock_used = search.lookupFields({ type: 'customrecord_customer_product_stock', id: selector_id, columns: ['custrecord_cust_date_stock_used', 'custrecord_cust_time_stock_used'] }); log.debug({ title: 'finalDel', details: search.lookupFields({ type: 'customrecord_customer_product_stock', id: selector_id, columns: 'custrecord_cust_prod_stock_final_del' }) }); var finalDelCheck = search.lookupFields({ type: 'customrecord_customer_product_stock', id: selector_id, columns: 'custrecord_cust_prod_stock_final_del' }).custrecord_cust_prod_stock_final_del; if (!isNullorEmpty(finalDelCheck)) { final_delivery_text = search.lookupFields({ type: 'customrecord_customer_product_stock', id: selector_id, columns: 'custrecord_cust_prod_stock_final_del' })["custrecord_cust_prod_stock_final_del"][0]["text"]; } date_stock_used = stock_used.custrecord_cust_date_stock_used; time_stock_used = stock_used.custrecord_cust_time_stock_used; } list_toll_issues = ticketRecord.getValue({ fieldId: 'custrecord_toll_issues' }); list_toll_issues = java2jsArray(list_toll_issues); list_resolved_toll_issues = ticketRecord.getValue({ fieldId: 'custrecord_resolved_toll_issues' }); list_resolved_toll_issues = java2jsArray(list_resolved_toll_issues); list_toll_emails = ticketRecord.getValue({ fieldId: 'custrecord_toll_emails' }); list_toll_emails = java2jsArray(list_toll_emails); break; case 'invoice_number': selector_id = ticketRecord.getValue({ fieldId: 'custrecord_invoice_number' }); var invoiceRecord = record.load({ type: 'invoice', id: selector_id }); accountsphone = customerRecord.getValue({ fieldId: 'altphone' }); accountsemail = customerRecord.getValue({ fieldId: 'email' }); maap_bank_account_number = customerRecord.getValue({ fieldId: 'custentity_maap_bankacctno' }); maap_parent_bank_account_number = customerRecord.getValue({ fieldId: 'custentity_maap_bankacctno_parent' }); selected_invoice_method_id = customerRecord.getValue({ fieldId: 'custentity_invoice_method' }); accounts_cc_email = customerRecord.getValue({ fieldId: 'custentity_accounts_cc_email' }); mpex_po_number = customerRecord.getValue({ fieldId: 'custentity_mpex_po' }); customer_po_number = customerRecord.getValue({ fieldId: 'custentity11' }); selected_invoice_cycle_id = customerRecord.getValue({ fieldId: 'custentity_mpex_invoicing_cycle' }); usage_report_id_1 = invoiceRecord.getValue({ fieldId: 'custbody_mpex_usage_report' }); usage_report_id_2 = invoiceRecord.getValue({ fieldId: 'custbody_mpex_usage_report_2' }); usage_report_id_3 = invoiceRecord.getValue({ fieldId: 'custbody_mpex_usage_report_3' }); usage_report_id_4 = invoiceRecord.getValue({ fieldId: 'custbody_mpex_usage_report_4' }); var usage_report_id_array = [usage_report_id_1, usage_report_id_2, usage_report_id_3, usage_report_id_4]; usage_report_id_array.forEach(function (usage_report_id) { if (!isNullorEmpty(usage_report_id)) { var usage_report_file = file.load({ id: usage_report_id }); usage_report_name = usage_report_file.name; usage_report_link = usage_report_file.url; usage_report_array.push({ id: usage_report_id, name: usage_report_name, url: usage_report_link }); } }); list_invoice_issues = ticketRecord.getValue({ fieldId: 'custrecord_invoice_issues' }); list_invoice_issues = java2jsArray(list_invoice_issues); list_resolved_invoice_issues = ticketRecord.getValue({ fieldId: 'custrecord_resolved_invoice_issues' }); list_resolved_invoice_issues = java2jsArray(list_resolved_invoice_issues); break; } list_mp_ticket_issues = ticketRecord.getValue({ fieldId: 'custrecord_mp_ticket_issue' }); list_mp_ticket_issues = java2jsArray(list_mp_ticket_issues); list_resolved_mp_ticket_issues = ticketRecord.getValue({ fieldId: 'custrecord_resolved_mp_ticket_issue' }); list_resolved_mp_ticket_issues = java2jsArray(list_resolved_mp_ticket_issues); owner_list = ticketRecord.getValue({ fieldId: 'custrecord_owner' }); owner_list = java2jsArray(owner_list); comment = ticketRecord.getValue({ fieldId: 'custrecord_comment' }); } } } var form = ui.createForm({ title: ' ', }); // Load jQuery var inlineHtml = '<script src="https://code.jquery.com/jquery-1.12.4.min.js" integrity="PI:KEY:9q3vfhm7l33rus21toc8fndupq76itjeEND_PI" crossorigin="anonymous"></script>'; // Load Tooltip inlineHtml += '<script src="https://unpkg.com/@popperjs/core@2"></script>'; // Load Bootstrap inlineHtml += '<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/3.4.1/css/bootstrap.min.css" integrity="PI:KEY:949d1u22cbffbrarjh182eig55721odjEND_PI" crossorigin="anonymous">'; inlineHtml += '<script src="https://stackpath.bootstrapcdn.com/bootstrap/3.4.1/js/bootstrap.min.js" integrity="PI:KEY:ax5kh6jaqkcd2tiexxs8v6xjo8yv8a6bEND_PI" crossorigin="anonymous"></script>'; // Load DataTables inlineHtml += '<link rel="stylesheet" type="text/css" href="//cdn.datatables.net/1.10.21/css/jquery.dataTables.min.css">'; inlineHtml += '<script type="text/javascript" charset="utf8" src="//cdn.datatables.net/1.10.21/js/jquery.dataTables.min.js"></script>'; // Load Summernote css/js inlineHtml += '<link href="https://cdnjs.cloudflare.com/ajax/libs/summernote/0.8.9/summernote.css" rel="stylesheet">'; inlineHtml += '<script src="https://cdnjs.cloudflare.com/ajax/libs/summernote/0.8.9/summernote.js"></script>'; // Load bootstrap-select inlineHtml += '<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap-select@1.13.14/dist/css/bootstrap-select.min.css">'; inlineHtml += '<script src="https://cdn.jsdelivr.net/npm/bootstrap-select@1.13.14/dist/js/bootstrap-select.min.js"></script>'; // Load Netsuite stylesheet and script inlineHtml += '<link rel="stylesheet" href="https://1048144.app.netsuite.com/core/media/media.nl?id=2060796&c=1048144&h=9ee6accfd476c9cae718&_xt=.css"/>'; inlineHtml += '<script src="https://1048144.app.netsuite.com/core/media/media.nl?id=2060797&c=1048144&h=ef2cda20731d146b5e98&_xt=.js"></script>'; inlineHtml += '<link type="text/css" rel="stylesheet" href="https://1048144.app.netsuite.com/core/media/media.nl?id=2090583&c=1048144&h=a0ef6ac4e28f91203dfe&_xt=.css">'; inlineHtml += '<style>.mandatory{color:red;}</style>'; // Define alert window. inlineHtml += '<div class="container" style="margin-top:14px;" hidden><div id="alert" class="alert alert-danger fade in"></div></div>'; // Define information window. inlineHtml += '<div class="container" hidden><p id="info" class="alert alert-info"></p></div>'; //inlineHtml += '<div style="background-color: #CFE0CE; min-height: 100vh; margin-top: -15px; padding-bottom: 50px"><br/>'; inlineHtml += '<div style="margin-top: -40px"><br/>'; inlineHtml += escalateButton(status_value); inlineHtml += '<h1 style="font-size: 25px; font-weight: 700; color: #103D39; text-align: center">Escalate Ticket - MPSD' + ticket_id + '</h1>'; //Tabs inlineHtml += tabsSection(customer_number, ticket_id, selector_number, selector_id, selector_type, status_value, date_created, creator_id, creator_name, status, customer_id, customer_name, daytodayphone, daytodayemail, accountsphone, accountsemail, maap_bank_account_number, maap_parent_bank_account_number, zee_id, franchisee_name, zee_main_contact_name, zee_email, zee_main_contact_phone, zee_abn, date_stock_used, time_stock_used, final_delivery_text, selected_enquiry_status_id,attachments_hyperlink, selected_enquiry_status_id, owner_list, list_toll_issues, list_resolved_toll_issues, comment, account_manager, list_toll_emails, customer_ticket_status, receiveremail, receiverphone, receivername, receiverstate, receiverzip, receiversuburb, receiveraddr1, receiveraddr2, barcodempdl, barcodesource, prod_stock_invoice) inlineHtml += '</div>'; form.addField({ id: 'preview_table', type: ui.FieldType.INLINEHTML, label: 'preview_table' }).updateBreakType({ breakType: ui.FieldBreakType.STARTROW }).defaultValue = inlineHtml; form.addField({ id: 'custpage_selector_number', type: ui.FieldType.TEXT, label: 'Selector Number' }).updateDisplayType({ displayType: ui.FieldDisplayType.HIDDEN }).defaultValue = selector_number; form.addField({ id: 'custpage_selector_type', type: ui.FieldType.TEXT, label: 'Selector Type' }).updateDisplayType({ displayType: ui.FieldDisplayType.HIDDEN }).defaultValue = selector_type; if (!isNullorEmpty(ticket_id)) { form.addField({ id: 'custpage_ticket_id', type: ui.FieldType.TEXT, label: 'Ticket ID' }).updateDisplayType({ displayType: ui.FieldDisplayType.HIDDEN }).defaultValue = ticket_id; } else { form.addField({ id: 'custpage_ticket_id', type: ui.FieldType.TEXT, label: 'Ticket ID' }).updateDisplayType({ displayType: ui.FieldDisplayType.HIDDEN }); } form.addField({ id: 'custpage_selector_id', type: ui.FieldType.TEXT, label: 'Selector ID' }).updateDisplayType({ displayType: ui.FieldDisplayType.HIDDEN }).defaultValue = selector_id; form.addField({ id: 'custpage_selector_issue', type: ui.FieldType.TEXT, label: 'Barcode issue' }).updateDisplayType({ displayType: ui.FieldDisplayType.HIDDEN }).defaultValue = 'F'; form.addField({ id: 'custpage_customer_id', type: ui.FieldType.TEXT, label: 'Customer ID' }).updateDisplayType({ displayType: ui.FieldDisplayType.HIDDEN }).defaultValue = customer_id; form.addField({ id: 'custpage_customer_number', type: ui.FieldType.TEXT, label: 'Customer Number' }).updateDisplayType({ displayType: ui.FieldDisplayType.HIDDEN }).defaultValue = customer_number; form.addField({ id: 'custpage_zee_id', type: ui.FieldType.TEXT, label: 'Franchisee ID' }).updateDisplayType({ displayType: ui.FieldDisplayType.HIDDEN }).defaultValue = zee_id; form.addField({ id: 'custpage_ticket_status_value', type: ui.FieldType.TEXT, label: 'Status Value' }).updateDisplayType({ displayType: ui.FieldDisplayType.HIDDEN }).defaultValue = status_value; form.addField({ id: 'custpage_created_ticket', type: ui.FieldType.TEXT, label: 'Created Ticket' }).updateDisplayType({ displayType: ui.FieldDisplayType.HIDDEN }).defaultValue = 'F'; form.addField({ id: 'custpage_usage_report_array', type: ui.FieldType.TEXT, label: 'Usage Reports' }).updateDisplayType({ displayType: ui.FieldDisplayType.HIDDEN }).defaultValue = JSON.stringify(usage_report_array); form.addField({ id: 'custpage_param_email', type: ui.FieldType.TEXT, label: 'Email parameters' }).updateDisplayType({ displayType: ui.FieldDisplayType.HIDDEN }).defaultValue = JSON.stringify(params_email); form.addField({ id: 'custpage_ss_image', type: ui.FieldType.TEXT, label: 'Screenshot Image' }).updateDisplayType({ displayType: ui.FieldDisplayType.HIDDEN }).defaultValue = screenshot_file; form.addField({ id: 'custpage_customer_number_email_sent', type: ui.FieldType.TEXT, label: 'Customer Email Sent' }).updateDisplayType({ displayType: ui.FieldDisplayType.HIDDEN }).defaultValue = customer_number_email_sent; form.clientScriptFileId = 4813457;//SB=4797047 PROD = 4813457 context.response.writePage(form); } else { } } /** * The output of .getFieldValues is a java String Array. * We want to convert it to a javaScript Array in order to read its values. * @param {Ljava.lang.String} javaArray * @return {Array} jsArray */ function java2jsArray(javaArray) { var jsArray = new Array; if (!isNullorEmpty(javaArray)) { javaArray.forEach(function(javaValue) { var jsValue = javaValue.toString(); jsArray.push(jsValue); }) } return jsArray; } /** * The "Customer number" input field. If there is a Ticket ID, then we are on the Edit Ticket page and * this field is pre-filled. * @param {*} customer_number */ function customerNumberSection(customer_number, ticket_id){ if(isNullorEmpty(customer_number)){ customer_number = ''; } // var disable = isNullorEmpty(ticket_id) ? '': 'disabled'; // Ticket details header var inlineQty = '<div class="form-group container tickets_details_header_section">'; inlineQty += '<div class="row">'; inlineQty += '<div class="col-xs-12 heading2" >'; inlineQty += '<h4><span style="background-color: #379E8F" class="label label-default col-xs-12">TICKET DETAILS</span></h4>'; inlineQty += '</div></div></div>'; // Customer number section inlineQty += '<div class="form-group container customer_number_section">'; inlineQty += '<div class="row">'; //Customer number field inlineQty += '<div class="col-xs-12 customer_number">'; inlineQty += '<div class="input-group">'; inlineQty += '<span class="input-group-addon" id="customer_number_text">CUSTOMER NUMBER</span>'; if(customer_number == '' && isNullorEmpty(ticket_id)){ inlineQty += '<input id="customer_number_value" value=" '+ customer_number +' " class="form-control customer_number">'; }else{ inlineQty += '<input id="customer_number_value" value=" '+ customer_number +' " class="form-control customer_number" disabled>'; } inlineQty += '</div></div></div></div>'; //Datatable for all tickets asscoiated to current customer number // inlineQty += '<div class="row">'; // inlineQty += '<div class="form-group container customer_number_tickets">'; // inlineQty += '<style> table {font-size: 12px;text-align: center;border: none;} {font-size: 14px;} table th{text-align: center;} .dataTables_wrapper{width:78%; margin-bottom:40px; margin-left: auto; margin-right: auto; margin-top: auto;} </style>'; // inlineQty += '<table cellpadding="15" id="customer_number_tickets_preview" class="table table-responsive table-striped customer tablesorter" cellspacing="0" style="width: 100%;">'; // inlineQty += '<thead style="color: white;background-color: #607799;">'; // inlineQty += '<tr class="text-center">'; // inlineQty += '</tr>'; // inlineQty += '</thead></table>'; // inlineQty += '</div></div>'; return inlineQty; } function escalateButton(status) { if (status < 11) { return '<button style="margin-left: 10px; margin-right: 5px; background-color: #FBEA51; color: #103D39; font-weight: 700; border-color: transparent; border-width: 2px; border-radius: 15px; height: 30px" type="button" id="escalationbtn" onclick="">Escalate to 1st Escalation</button>'; } else if (status == 11) { var html = '<button style="margin-left: 10px; margin-right: 5px; background-color: #FBEA51; color: #103D39; font-weight: 700; border-color: transparent; border-width: 2px; border-radius: 15px; height: 30px" type="button" id="escalationbtn" onclick="">Escalate to 2nd Escalation</button>'; html += '<button style="margin-left: 5px; margin-right: 5px; background-color: #FBEA51; color: #103D39; font-weight: 700; border-color: transparent; border-width: 2px; border-radius: 15px; height: 30px" type="button" id="removeescalationbtn" onclick="">Remove Escalation</button>'; return html; }else if (status == 12) { var html = '<button style="margin-left: 10px; margin-right: 5px; background-color: #FBEA51; color: #103D39; font-weight: 700; border-color: transparent; border-width: 2px; border-radius: 15px; height: 30px" type="button" id="escalationbtn" onclick="">Escalate to 3rd Escalation</button>'; html += '<button style="margin-left: 5px; margin-right: 5px; background-color: #FBEA51; color: #103D39; font-weight: 700; border-color: transparent; border-width: 2px; border-radius: 15px; height: 30px" type="button" id="removeescalationbtn" onclick="">Remove Escalation</button>'; return html; } else if (status == 13) { var html = '<button style="margin-left: 10px; margin-right: 5px; background-color: #FBEA51; color: #103D39; font-weight: 700; border-color: transparent; border-width: 2px; border-radius: 15px; height: 30px" type="button" id="escalationbtn" onclick="">Escalate to Final Escalation</button>'; html += '<button style="margin-left: 5px; margin-right: 5px; background-color: #FBEA51; color: #103D39; font-weight: 700; border-color: transparent; border-width: 2px; border-radius: 15px; height: 30px" type="button" id="removeescalationbtn" onclick="">Remove Escalation</button>'; return html; } else { return '<button style="margin-left: 10px; margin-right: 5px; background-color: #FBEA51; color: #103D39; font-weight: 700; border-color: transparent; border-width: 2px; border-radius: 15px; height: 30px" type="button" id="removeescalationbtn" onclick="">Remove Escalation</button>'; } } /** * The "Barcode number" OR "Invoice Number" input field. * If there is a TICKET ID, we are in the "Edit Ticket", so we display the Ticket ID field and the selector field is disabled. * @param {Number} ticket_id * @param {String} selector_number * @param {Number} selector_id * @param {String} selector_type * @param {Number} status_value * @return {String} inlineQty */ function selectorSection(ticket_id, selector_number, selector_id, selector_type, status_value) { if (isNullorEmpty(selector_number)) { selector_number = ''; } var inlineQty = '<div class="form-group container selector_section">'; inlineQty += '<div class="row">'; if (!isNullorEmpty(ticket_id)) { // Ticket ID field inlineQty += '<div class="col-xs-6 ticket_id">'; inlineQty += '<div class="input-group">'; inlineQty += '<span class="input-group-addon" id="ticket_id_text">TICKET ID</span>'; inlineQty += '<input id="ticket_id" value="MPSD' + ticket_id + '" class="form-control ticket_id" disabled />'; inlineQty += '</div></div>'; // Selector Number field inlineQty += '<div class="col-xs-6 selector_number">'; inlineQty += '<div class="input-group">'; switch (selector_type) { case 'barcode_number': inlineQty += '<span class="input-group-addon" id="selector_text">BARCODE NUMBER</span>'; break; case 'invoice_number': inlineQty += '<span class="input-group-addon" id="selector_text">INVOICE NUMBER</span>'; break; } inlineQty += '<input id="selector_value" value="' + selector_number + '" class="form-control selector_value" disabled>'; if (selector_type == 'invoice_number') { // Open Invoice record inlineQty += '<div class="input-group-btn">'; inlineQty += '<button id="open_inv" type="button" class="btn btn-default link_inv" data-inv-id="' + selector_id + '" data-toggle="tooltip" data-placement="top" title="Open Invoice">'; inlineQty += '<span class="glyphicon glyphicon-link"></span>'; inlineQty += '</button>'; inlineQty += '</div>'; // Attach Invoice to email if (isTicketNotClosed(status_value)) { inlineQty += '<div class="input-group-btn"><button style="background-color: #379E8F" id="add_inv" type="button" class="btn btn-success add_inv" data-inv-id="' + selector_id + '" data-toggle="tooltip" data-placement="right" title="Attach to email">'; inlineQty += '<span class="glyphicon glyphicon-plus"></span>'; inlineQty += '</button></div>'; } } inlineQty += '</div></div></div></div>'; } else { inlineQty += '<div class="col-xs-12 selector_number">'; inlineQty += '<div class="input-group">'; //Input group addon text switch (selector_type) { case 'barcode_number': inlineQty += '<span class="input-group-addon" id="selector_text">BARCODE NUMBER</span>'; break; case 'invoice_number': inlineQty += '<span class="input-group-addon" id="selector_text">INVOICE NUMBER</span>'; break; case 'customer_issue': inlineQty += '<span class="input-group-addon" id="selector_text">CUSTOMER ISSUE</span>'; break; } inlineQty += '<div class="input-group-btn">'; inlineQty += '<button tabindex="-1" data-toggle="dropdown" class="btn btn-default dropdown-toggle" type="button">'; inlineQty += '<span class="caret"></span>'; inlineQty += '<span class="sr-only">Toggle Dropdown</span>'; inlineQty += '</button>'; inlineQty += '<ul class="dropdown-menu hide" style="list-style:none;margin: 2px 0 0;">'; inlineQty += '<li><a href="#">BARCODE NUMBER</a></li>'; inlineQty += '<li><a href="#">INVOICE NUMBER</a></li>'; inlineQty += '<li><a href="#">CUSTOMER APP</a></li>'; inlineQty += '<li><a href="#">CUSTOMER PORTAL</a></li>'; inlineQty += '<li><a href="#">UPDATE LABEL</a></li>'; inlineQty += '</ul>'; inlineQty += '</div>'; //Input text switch (selector_type) { case 'barcode_number': inlineQty += '<input id="selector_value" class="form-control selector_value" placeholder="MPEN123456">'; break; case 'invoice_number': inlineQty += '<input id="selector_value" class="form-control selector_value" placeholder="INV123456">'; break; case 'customer_app': inlineQty += '<input id="selector_value" class="form-control selector_value" placeholder="Customer App" disabled value="Customer App">'; break; case 'customer_portal': inlineQty += '<input id="selector_value" class="form-control selector_value" placeholder="Customer Portal" disabled value="Customer Portal">'; break; case 'update_label': inlineQty += '<input id="selector_value" class="form-control selector_value" placeholder="Update Label" disabled value="Update Label">'; break; } inlineQty += '</div></div></div></div>'; } return inlineQty; } /** * Used to pass the values of `date_from` and `date_to` between the scripts and to Netsuite for the records and the search. * @param {String} date_iso "2020-06-01" * @returns {String} date_netsuite "1/6/2020" */ function dateISOToNetsuite(date_iso) { var date_netsuite = ''; if (!isNullorEmpty(date_iso)) { var date_netsuite = format.format({ value: date_iso, type: format.Type.DATETIME }); } return date_netsuite; } /** * The informations regarding the ticket being edited. * @param {String} date_created * @param {Number} creator_id * @param {String} creator_name * @param {String} status * @return {String} inlineQty */ function ticketSection(date_created, creator_id, creator_name, status, customer_ticket_status) { if (isNullorEmpty(date_created)) { date_created = ''; } if (isNullorEmpty(creator_name)) { creator_name = ''; } if (isNullorEmpty(status)) { status = ''; } var inlineQty = '<div class="form-group container created_status_section">'; inlineQty += '<div class="row">'; // Date created field inlineQty += '<div class="col-xs-6 date_created">'; inlineQty += '<div class="input-group">'; inlineQty += '<span class="input-group-addon" id="date_created_text">DATE CREATED</span>'; inlineQty += '<input id="date_created" value="' + date_created + '" class="form-control date_created" disabled />'; inlineQty += '</div></div>'; // Creator field inlineQty += '<div class="col-xs-6 creator">'; inlineQty += '<div class="input-group">'; inlineQty += '<span class="input-group-addon" id="creator_text">CREATOR</span>'; inlineQty += '<input id="creator" value="' + creator_name + '" data-creator-id="' + creator_id + '" class="form-control creator" disabled />'; inlineQty += '</div></div></div></div>'; // Status Section inlineQty += '<div class="form-group container status_section">'; inlineQty += '<div class="row">'; // Status field inlineQty += '<div class="col-xs-6 status">'; inlineQty += '<div class="input-group">'; inlineQty += '<span class="input-group-addon" id="status_text">STATUS</span>'; inlineQty += '<input id="status" value="' + status + '" class="form-control status" disabled />'; inlineQty += '</div></div>'; // Customer Status field inlineQty += '<div class="col-xs-6 status">'; inlineQty += '<div class="input-group">'; inlineQty += '<span class="input-group-addon" id="status_text">CUSTOMER STATUS</span>'; inlineQty += '<input id="status" value="' + customer_ticket_status + '" class="form-control status" disabled />'; inlineQty += '</div></div></div></div>'; return inlineQty; } /** * The Customer name field. * The customer name field should be automatically filled based on the Selector number value. * @param {String} customer_name * @return {String} inlineQty */ function customerSection(customer_name) { if (isNullorEmpty(customer_name)) { customer_name = ''; } // Customer Section var inlineQty = '<div class="form-group container customer_section">'; inlineQty += '<div class="row">'; // Customer name field inlineQty += '<div class="col-xs-12 customer_name">'; inlineQty += '<div class="input-group">'; inlineQty += '<span class="input-group-addon" id="customer_name_text">CUSTOMER NAME</span>'; inlineQty += '<input id="customer_name" value="' + customer_name + '" class="form-control customer_name" disabled>'; inlineQty += '</div></div></div></div>'; return inlineQty; } /** * The day to day phone and email fields of the customer. * These fields should be automatically filled based on the Selector number value. * @param {String} daytodayphone * @param {String} daytodayemail * @param {Number} status_value * @param {String} selector_type * @return {String} inlineQty */ function daytodayContactSection(daytodayphone, daytodayemail, status_value, selector_type) { if (isNullorEmpty(daytodayphone)) { daytodayphone = ''; } if (isNullorEmpty(daytodayemail)) { daytodayemail = ''; } var disabled = 'disabled'; if ((isFinanceRole(userRole)) && isTicketNotClosed(status_value) && selector_type == 'invoice_number') { disabled = ''; } var inlineQty = '<div class="form-group container daytodaycontact_section">'; inlineQty += '<div class="row">'; // Day to day email field inlineQty += '<div class="col-xs-6 daytodayemail_div">'; inlineQty += '<div class="input-group">'; inlineQty += '<span class="input-group-addon" id="daytodayemail_text">DAY-TO-DAY EMAIL</span>'; inlineQty += '<input id="daytodayemail" type="email" value="' + daytodayemail + '" class="form-control daytodayemail" ' + disabled + ' />'; inlineQty += '<div class="input-group-btn">'; inlineQty += '<button type="button" style="background-color: #379E8F" class="btn btn-success add_as_recipient" data-email="' + daytodayemail + '" data-contact-id="" data-firstname="" data-toggle="tooltip" data-placement="right" title="Add as recipient">'; inlineQty += '<span class="glyphicon glyphicon-envelope"></span>'; inlineQty += '</button>'; inlineQty += '</div>'; inlineQty += '</div></div>'; // Day to day phone field inlineQty += '<div class="col-xs-6 daytodayphone_div">'; inlineQty += '<div class="input-group">'; inlineQty += '<span class="input-group-addon" id="daytodayphone_text">DAY-TO-DAY PHONE</span>'; inlineQty += '<input id="daytodayphone" type="tel" value="' + daytodayphone + '" class="form-control daytodayphone" ' + disabled + ' />'; inlineQty += '<div class="input-group-btn"><button type="button" style="background-color: #379E8F" class="btn btn-success" id="call_daytoday_phone"><span class="glyphicon glyphicon-earphone"></span></button></div>'; inlineQty += '</div></div></div></div>'; return inlineQty; } /** * The accounts phone and email fields of the customer. * These fields should be automatically filled based on the Invoice number value. * @param {String} accountsphone * @param {String} accountsemail * @param {Number} status_value * @param {String} selector_type * @return {String} inlineQty */ function accountsContactSection(accountsphone, accountsemail, status_value, selector_type) { if (isNullorEmpty(accountsphone)) { accountsphone = ''; } if (isNullorEmpty(accountsemail)) { accountsemail = ''; } if (selector_type == 'invoice_number') { var inlineQty = '<div class="form-group container accountscontact_section">'; if (isFinanceRole(userRole) && isTicketNotClosed(status_value)) { var disabled = ''; } else { var disabled = 'disabled'; } } else { var inlineQty = '<div class="form-group container accountscontact_section hide">'; var disabled = 'disabled'; } inlineQty += '<div class="row">'; // Accounts email field inlineQty += '<div class="col-xs-6 accountsemail_div">'; inlineQty += '<div class="input-group">'; inlineQty += '<span class="input-group-addon" id="accountsemail_text">ACCOUNTS EMAIL</span>'; inlineQty += '<input id="accountsemail" type="email" value="' + accountsemail + '" class="form-control accountsemail" ' + disabled + ' />'; inlineQty += '<div class="input-group-btn">'; inlineQty += '<button type="button" class="btn btn-success add_as_recipient" data-email="' + accountsemail + '" data-contact-id="" data-firstname="" data-toggle="tooltip" data-placement="right" title="Add as recipient">'; inlineQty += '<span class="glyphicon glyphicon-envelope"></span>'; inlineQty += '</button>'; inlineQty += '</div>'; inlineQty += '</div></div>'; // Accounts phone field inlineQty += '<div class="col-xs-6 accountsphone_div">'; inlineQty += '<div class="input-group">'; inlineQty += '<span class="input-group-addon" id="accountsphone_text">ACCOUNTS PHONE</span>'; inlineQty += '<input id="accountsphone" type="tel" value="' + accountsphone + '" class="form-control accountsphone" ' + disabled + ' />'; inlineQty += '<div class="input-group-btn"><button type="button" style="background-color: #379E8F" class="btn btn-success" id="call_accounts_phone"><span class="glyphicon glyphicon-earphone"></span></button></div>'; inlineQty += '</div></div></div></div>'; return inlineQty; } /** * * @param {Number} maap_bank_account_number * @param {Number} maap_parent_bank_account_number * @param {String} selector_type * @returns {String} inlineQty */ function maapBankAccountSection(maap_bank_account_number, maap_parent_bank_account_number, selector_type) { switch (selector_type) { case 'barcode_number': var inlineQty = '<div class="form-group container accounts_number_section hide">'; break; case 'invoice_number': var inlineQty = '<div class="form-group container accounts_number_section">'; break; } inlineQty += '<div class="row">'; // MAAP Bank Account # field inlineQty += '<div class="col-xs-6 account_number_div">'; inlineQty += '<div class="input-group">'; inlineQty += '<span class="input-group-addon" id="account_number_text">MAAP BANK ACCOUNT #</span>'; inlineQty += '<input id="account_number" type="number" value="' + maap_bank_account_number + '" class="form-control account_number" disabled />'; inlineQty += '</div></div>'; // MAAP Parent Bank Account # field inlineQty += '<div class="col-xs-6 parent_account_number_div">'; inlineQty += '<div class="input-group">'; inlineQty += '<span class="input-group-addon" id="parent_account_number_text">MAAP PARENT BANK ACCOUNT #</span>'; inlineQty += '<input id="parent_account_number" type="number" value="' + maap_parent_bank_account_number + '" class="form-control parent_account_number" disabled />'; inlineQty += '</div></div></div></div>'; return inlineQty; } /** * The Franchisee name, and its main contact name and phone number fields. * These fields should be automatically filled based on the Selector number value. * @param {String} franchisee_name * @param {String} zee_main_contact_name * @param {String} zee_email * @param {String} zee_main_contact_phone * @param {String} zee_abn * @return {String} inlineQty */ function franchiseeMainContactSection(franchisee_name, zee_main_contact_name, zee_email, zee_main_contact_phone, zee_abn) { if (isNullorEmpty(franchisee_name)) { franchisee_name = ''; } if (isNullorEmpty(zee_main_contact_name)) { zee_main_contact_name = ''; } if (isNullorEmpty(zee_email)) { zee_email = ''; } if (isNullorEmpty(zee_main_contact_phone)) { zee_main_contact_phone = ''; } if (isNullorEmpty(zee_abn)) { zee_abn = ''; } var inlineQty = '<div class="form-group container zee_main_contact_section">'; inlineQty += '<div class="row">'; // Franchisee name field inlineQty += '<div class="col-xs-6 franchisee_name">'; inlineQty += '<div class="input-group">'; inlineQty += '<span class="input-group-addon" id="franchisee_name_text">FRANCHISEE NAME</span>'; inlineQty += '<input id="franchisee_name" value="' + franchisee_name + '" class="form-control franchisee_name" disabled>'; inlineQty += '</div></div>'; // Franchisee main contact name field inlineQty += '<div class="col-xs-6 zee_main_contact_name">'; inlineQty += '<div class="input-group">'; inlineQty += '<span class="input-group-addon" id="zee_main_contact_name_text">MAIN CONTACT</span>'; inlineQty += '<input id="zee_main_contact_name" value="' + zee_main_contact_name + '" class="form-control zee_main_contact_name" disabled>'; inlineQty += '</div></div></div></div>'; // Franchisee contact details inlineQty += '<div class="form-group container zee_main_contact_section">'; inlineQty += '<div class="row">'; // Franchisee email field inlineQty += '<div class="col-xs-12 zee_email">'; inlineQty += '<div class="input-group">'; inlineQty += '<span class="input-group-addon" id="zee_email_text">FRANCHISEE EMAIL</span>'; inlineQty += '<input id="zee_email" type="email" value="' + zee_email + '" class="form-control accountsemail" disabled />'; inlineQty += '<div class="input-group-btn">'; var zee_contact_id = '0'; inlineQty += '<button type="button" style="background-color: #379E8F" class="btn btn-success add_as_recipient" data-email="' + zee_email + '" data-contact-id="' + zee_contact_id + '" data-firstname="' + franchisee_name + '" data-toggle="tooltip" data-placement="right" title="Add as recipient">'; inlineQty += '<span class="glyphicon glyphicon-envelope"></span>'; inlineQty += '</button>'; inlineQty += '</div>'; inlineQty += '</div></div></div></div>'; // Franchisee phone and ABN details inlineQty += '<div class="form-group container zee_main_contact_section">'; inlineQty += '<div class="row">'; // Franchisee main contact phone field inlineQty += '<div class="col-xs-6 zee_main_contact_phone">' inlineQty += '<div class="input-group">' inlineQty += '<span class="input-group-addon" id="zee_main_contact_phone_text">FRANCHISEE PHONE</span>'; inlineQty += '<input id="zee_main_contact_phone" type="tel" value="' + zee_main_contact_phone + '" class="form-control zee_main_contact_phone" disabled />'; inlineQty += '<div class="input-group-btn"><button style="background-color: #379E8F" type="button" class="btn btn-success" id="call_zee_main_contact_phone"><span class="glyphicon glyphicon-earphone"></span></button>'; inlineQty += '</div>'; inlineQty += '</div></div>'; // Franchisee ABN number inlineQty += '<div class="col-xs-6 zee_abn">' inlineQty += '<div class="input-group">' inlineQty += '<span class="input-group-addon" id="zee_abn_text">FRANCHISEE ABN</span>' inlineQty += '<input id="zee_abn" class="form-control zee_abn" value="' + zee_abn + '" disabled>' inlineQty += '</div></div></div></div>'; return inlineQty; } /** * The MPEX Date and Time Stock used fields. * Visible only for the barcode records. * @param {String} selector_type * @param {String} date_stock_used * @param {String} time_stock_used * @return {String} inlineQty */ function mpexStockUsedSection(selector_type, date_stock_used, time_stock_used) { if (isNullorEmpty(date_stock_used)) { date_stock_used = '' } if (isNullorEmpty(time_stock_used)) { time_stock_used = '' } var hide_class = (selector_type == 'barcode_number') ? '' : 'hide'; // MPEX Stock Used Section var inlineQty = '<div class="form-group container mpex_stock_used_section ' + hide_class + '">'; inlineQty += '<div class="row">'; // Date Stock Used inlineQty += ' <div class="col-xs-6 date_stock_used">'; inlineQty += '<div class="input-group">'; inlineQty += '<span class="input-group-addon" id="date_stock_used_text">DATE STOCK USED</span>'; inlineQty += '<input id="date_stock_used" class="form-control date_stock_used" value="' + date_stock_used + '" disabled>'; inlineQty += '</div></div>'; // Time Stock Used inlineQty += '<div class="col-xs-6 time_stock_used">'; inlineQty += '<div class="input-group">'; inlineQty += '<span class="input-group-addon" id="time_stock_used_text">TIME STOCK USED</span>'; inlineQty += '<input id="time_stock_used" class="form-control time_stock_used" value="' + time_stock_used + '" disabled>'; inlineQty += '</div></div></div></div>'; return inlineQty; } /** * The MPEX Final Delivery field is visible only for the barcode records. * The Enquiry Status field is not disabled only for the ticket that have not yet been opened. * @param {Number} status_value * @param {String} selector_type * @param {String} final_delivery_text * @param {Number} selected_enquiry_status_id * @return {String} inlineQty */ function finalDeliveryEnquirySection(status_value, selector_type, final_delivery_text, selected_enquiry_status_id, prod_stock_invoice) { if (isNullorEmpty(final_delivery_text)) { final_delivery_text = '' } if (isNullorEmpty(selected_enquiry_status_id)) { selected_enquiry_status_id = '' } var barcode_hide_class = (selector_type == 'barcode_number') ? '' : 'hide'; var nb_col_enquiry_section = (selector_type == 'barcode_number') ? '6' : '12'; var enquiry_disabled = (isTicketNotClosed(status_value)) ? '' : 'disabled'; // Final Delivery + Enquiry Status Section var inlineQty = '<div class="form-group container final_delivery_enquiry_status_section">'; inlineQty += '<div class="row">'; // Final Delivery inlineQty += '<div class="col-xs-6 final_delivery ' + barcode_hide_class + '">'; inlineQty += '<div class="input-group">'; inlineQty += '<span class="input-group-addon" id="final_delivery_text">FINAL DELIVERY</span>'; inlineQty += '<input id="final_delivery" class="form-control final_delivery" value="' + final_delivery_text + '" disabled>'; inlineQty += '</div></div>'; // Final Delivery inlineQty += '<div class="col-xs-6 invoice ' + barcode_hide_class + '">'; inlineQty += '<div class="input-group">'; inlineQty += '<span class="input-group-addon" id="invoice_text">INVOICE</span>'; inlineQty += '<input id="invoice" class="form-control invoice" value="' + prod_stock_invoice + '" disabled>'; inlineQty += '</div></div>'; inlineQty += '</div></div>'; return inlineQty; } /** * The Attachments field (an editable hyperlink) * @param {String} attachments_hyperlink * @param {Number} status_value * @returns {String} inlineQty */ function attachmentsSection(attachments_hyperlink, status_value) { var inlineQty = ''; if (!isNullorEmpty(attachments_hyperlink)) { var disabled = (isTicketNotClosed(status_value)) ? '' : 'disabled'; inlineQty += '<div class="form-group container attachments_section">'; inlineQty += '<div class="row">'; inlineQty += '<div class="col-xs-12 attachments_div">'; inlineQty += '<div class="input-group">'; inlineQty += '<span class="input-group-addon" id="attachments_text">ATTACHMENTS</span>' inlineQty += '<input id="attachments" class="form-control attachments" type="url" value="' + attachments_hyperlink + '" ' + 'disabled' + '/>'; inlineQty += '</div></div></div></div>'; } return inlineQty; } /** * Section containing enquiry medium type and the enquiry status of the ticket enquiry * @param list_enquiry_mediums {String}atus and * @param total_enquiry_count {Number} * @param selector_type {String} * @param status_value {Number} * @returns {string} */ function enquiryMediumSection(list_enquiry_mediums, selected_enquiry_status_id, selector_type){ //Search for enquiry mediums var hasEnquiryMediums = (!isNullorEmpty(list_enquiry_mediums)); var enquiryMediumColumns = new Array(); enquiryMediumColumns[0] = search.createColumn({ name: 'name' }); enquiryMediumColumns[1] = search.createColumn({ name: 'internalId' }); var enquiryMediumResultSet = search.create({ type: 'customlist_ticket_enquiry_mediums', columns: enquiryMediumColumns, }); //Ticket Enquiry Header // var inlineQty = '<div class="form-group container ticket_enquiry_header_section">'; // inlineQty += '<div class="row">'; // inlineQty += '<div class="col-xs-12 heading2">'; // inlineQty += '<h4><span style="background-color: #379E8F" class="label label-default col-xs-12">TICKET ENQUIRY DETAILS</span></h4>'; // inlineQty += '</div></div></div>'; //Enquiry Medium HTML var inlineQty = '<div class="form-group container enquiry_medium_section">'; inlineQty += '<div class="row">'; inlineQty += '<div class="col-xs-6 enquiry_medium_div">'; inlineQty += '<div class="input-group">'; inlineQty += '<span class="input-group-addon" id="enquiry_medium_text">ENQUIRY MEDIUM</span>'; inlineQty += '<select multiple id="enquiry_medium_status" class="form-control enquiry_medium_status" size="'+ enquiryMediumResultSet.length + '" disabled>'; enquiryMediumResultSet.run().each(function (enquiryMediumResult) { var enquiryMediumName = enquiryMediumResult.getValue('name'); var enquiryMediumId = enquiryMediumResult.getValue('internalId'); var selected = false; if(hasEnquiryMediums){ selected = (list_enquiry_mediums.indexOf(enquiryMediumId) !== -1); } if(selected) { inlineQty += '<option value="' + enquiryMediumId + '"selected>' + enquiryMediumName + '</option>'; }else{ inlineQty += '<option value="' + enquiryMediumId + '">' + enquiryMediumName + '</option>'; } return true; }); inlineQty += '</select>'; inlineQty += '</div></div>'; // Enquiry Status var enquiry_status_columns = new Array(); enquiry_status_columns[0] = search.createColumn({ name: 'name' }); enquiry_status_columns[1] = search.createColumn({ name: 'internalId' }); var enquiryStatusResultSet = search.create({ type: 'customlist_mp_ticket_enquiry', columns: enquiry_status_columns, }); inlineQty += '<div class="col-xs-6 enquiry_status_div">'; inlineQty += '<div class="input-group">'; inlineQty += '<span class="input-group-addon" id="enquiry_status_text">ENQUIRY STATUS</span>'; inlineQty += '<select id="enquiry_status" class="form-control enquiry_status">'; inlineQty += '<option></option>'; enquiryStatusResultSet.run().each(function (enquiryStatusResult) { var enquiry_status_name = enquiryStatusResult.getValue('name'); var enquiry_status_id = enquiryStatusResult.getValue('internalId'); if (enquiry_status_id == selected_enquiry_status_id) { inlineQty += '<option value="' + enquiry_status_id + '" selected>' + enquiry_status_name + '</option>'; } else { inlineQty += '<option value="' + enquiry_status_id + '">' + enquiry_status_name + '</option>'; } return true; }); inlineQty += '</select>'; inlineQty += '</div></div></div></div>'; return inlineQty; } /** * Section containing the total enquiry count and its breakdwn counts of chat, phone and email * @param total_enquiry_count * @param chat_enquiry_count * @param phone_enquiry_count * @param email_enquiry_count * @param selector_type * @returns {string} */ function enquiryCountSection( total_enquiry_count, chat_enquiry_count, phone_enquiry_count, email_enquiry_count, selector_type){ if (isNullorEmpty(total_enquiry_count)) { total_enquiry_count = 0;} if (isNullorEmpty(chat_enquiry_count)) { chat_enquiry_count = 0;} if (isNullorEmpty(phone_enquiry_count)) { phone_enquiry_count = 0;} if (isNullorEmpty(email_enquiry_count)) { email_enquiry_count = 0;} //Total Enquiry Count HTML var inlineQty = '<div class="form-group container enquiry_count_section">'; inlineQty += '<div class="row">'; inlineQty += '<div class="col-xs-12 total_enquiry_count_div">'; inlineQty += '<div class="input-group">'; inlineQty += '<span class="input-group-addon" id="total_enquiry_count_text">ENQUIRY COUNT</span>'; inlineQty += '<input id="total_enquiry_count" class="form-control enquiry_count" value="' + total_enquiry_count + '" disabled />'; inlineQty += '</div></div></div></div>'; //Enquiries by chat count inlineQty += '<div class="form-group container enquiry_count_breakdown_section">'; inlineQty += '<div class="row">'; inlineQty += '<div class="col-xs-4 enquiry_count_by_chat">'; inlineQty += '<div class="input-group">'; inlineQty += '<span class="input-group-addon" id="enquiry_count_by_chat_text"> CHAT ENQUIRY </span>'; inlineQty += '<input id="enquiry_count_by_chat" value="' + chat_enquiry_count + '" class="form-control enquiry_count_by_chat" disabled>'; inlineQty += '<div class="input-group-btn">'; inlineQty += '<button type="button" style="background-color: #379E8F" class="btn btn-success increment_enquiry_count_by_chat" data-firstname="" data-toggle="tooltip" data-placement="right" title="Increment Chat Enquiry Count">'; inlineQty += '<span class="glyphicon glyphicon-plus"></span>'; inlineQty += '</button>'; inlineQty += '<button type="button" class="btn btn-danger decrement_enquiry_count_by_chat" data-firstname="" data-toggle="tooltip" data-placement="right" title="Decrement Chat Enquiry Count">'; inlineQty += '<span class="glyphicon glyphicon-minus"></span>'; inlineQty += '</button>'; inlineQty += '</div></div></div>'; inlineQty += '<div class="col-xs-4 enquiry_count_by_phone">'; inlineQty += '<div class="input-group">'; inlineQty += '<span class="input-group-addon" id="enquiry_count_by_phone_text"> PHONE ENQUIRY </span>'; inlineQty += '<input id="enquiry_count_by_phone" value="' + phone_enquiry_count + '" class="form-control enquiry_count_by_phone" disabled>'; inlineQty += '<div class="input-group-btn">'; inlineQty += '<button type="button" style="background-color: #379E8F" class="btn btn-success increment_enquiry_count_by_phone" data-firstname="" data-toggle="tooltip" data-placement="right" title="Increment Phone Enquiry Count">'; inlineQty += '<span class="glyphicon glyphicon-plus"></span>'; inlineQty += '</button>'; inlineQty += '<button type="button" class="btn btn-danger decrement_enquiry_count_by_phone" data-firstname="" data-toggle="tooltip" data-placement="right" title="Decrement Phone Enquiry Count">'; inlineQty += '<span class="glyphicon glyphicon-minus"></span>'; inlineQty += '</button>'; inlineQty += '</div></div></div>'; inlineQty += '<div class="col-xs-4 enquiry_count_by_email">'; inlineQty += '<div class="input-group">'; inlineQty += '<span class="input-group-addon" id="enquiry_count_by_email_text"> EMAIL ENQUIRY </span>'; inlineQty += '<input id="enquiry_count_by_email" value="' + email_enquiry_count + '" class="form-control enquiry_count_by_email" disabled>'; inlineQty += '<div class="input-group-btn">'; inlineQty += '<button type="button" style="background-color: #379E8F" class="btn btn-success increment_enquiry_count_by_email" data-firstname="" data-toggle="tooltip" data-placement="right" title="Increment Email Enquiry Count">'; inlineQty += '<span class="glyphicon glyphicon-plus"></span>'; inlineQty += '</button>'; inlineQty += '<button type="button" class="btn btn-danger decrement_enquiry_count_by_email" data-firstname="" data-toggle="tooltip" data-placement="right" title="Decrement Email Enquiry Count">'; inlineQty += '<span class="glyphicon glyphicon-minus"></span>'; inlineQty += '</button>'; inlineQty += '</div></div></div></div></div>'; return inlineQty; } /** * @return {String} inlineQty */ function issuesHeader() { var inlineQty = '<div class="form-group container toll_issues_header_section">'; inlineQty += '<div class="row">'; inlineQty += '<div class="col-xs-12 heading1">'; inlineQty += '<h4><span style="background-color: #379E8F" class="form-group label label-default col-xs-12">ISSUES</span></h4>'; inlineQty += '</div></div></div>'; return inlineQty; } /** * @param {Number} status_value * @return {String} inlineQty */ function reminderSection(status_value) { var hide_class = (!isTicketNotClosed(status_value)) ? 'hide' : ''; var inlineQty = '<div class="form-group container reminder_section ' + hide_class + '">'; inlineQty += '<div class="row">'; // Reminder field inlineQty += '<div class="col-xs-12 reminder">'; inlineQty += '<div class="input-group">'; inlineQty += '<span class="input-group-addon" id="reminder_text">REMINDER</span>'; inlineQty += '<input id="reminder" class="form-control reminder" type="date" disabled />'; inlineQty += '</div></div></div></div>'; return inlineQty; } /** * Based on the selected MP Issue, an Owner is allocated to the ticket. * IT issues have priority over the other issues. * Populated with selectOwner() in the pageInit function on the client script. * @param {Number} ticket_id * @param {Array} owner_list * @param {Number} status_value * @return {String} inlineQty */ function ownerSection(ticket_id, owner_list, status_value) { if (isNullorEmpty(ticket_id)) { // If ticket_id is null, owner_list as well. // In that case, only the creator of the ticket is pre-selected as the owner. var userId = runtime.getCurrentUser().toString(); owner_list = [userId]; } var disabled = (!isTicketNotClosed(status_value)) ? 'disabled' : ''; var inlineQty = '<div class="form-group container owner_section">'; inlineQty += '<div class="row">'; inlineQty += '<div class="col-xs-12 owner">'; inlineQty += '<div class="input-group">'; inlineQty += '<span class="input-group-addon" id="owner_text">OWNER<span class="mandatory">*</span></span>'; inlineQty += '<select multiple id="owner" class="form-control owner" ' + 'disabled' + '>'; var employeeSearch = search.load({ type: 'employee', id: 'customsearch_active_employees' }); var employeeResultSet = employeeSearch.run(); employeeResultSet.each(function(employeeResult) { var employee_id = employeeResult.searchId; var employee_firstname = employeeResult.getValue('firstname'); var employee_lastname = employeeResult.getValue('lastname'); var employee_email = employeeResult.getValue('email'); if (owner_list.indexOf(employee_id) != -1) { inlineQty += '<option value="' + employee_id + '" data-email="' + employee_email + '" selected>' + employee_firstname + ' ' + employee_lastname + '</option>'; } else { inlineQty += '<option value="' + employee_id + '" data-email="' + employee_email + '">' + employee_firstname + ' ' + employee_lastname + '</option>'; } return true; }); inlineQty += '</select>'; inlineQty += '</div></div></div></div>'; return inlineQty; } /** * The multiselect TOLL issues dropdown * @param {Array} list_toll_issues * @param {Array} list_resolved_toll_issues * @param {Number} status_value * @param {String} selector_type * @return {String} inlineQty */ function tollIssuesSection(list_toll_issues, list_resolved_toll_issues, status_value, selector_type) { // TOLL Issues var has_toll_issues = (!isNullorEmpty(list_toll_issues)); var toll_issues_columns = new Array(); toll_issues_columns[0] = search.createColumn({ name: 'name' }); toll_issues_columns[1] = search.createColumn({ name: 'internalId' }); var tollIssuesResultSet = search.create({ type: 'customlist_cust_prod_stock_toll_issues', columns: toll_issues_columns }); if (!isTicketNotClosed(status_value) || selector_type != 'barcode_number') { var inlineQty = '<div class="form-group container toll_issues_section hide">'; } else { var inlineQty = '<div class="form-group container toll_issues_section">'; } inlineQty += '<div class="row">'; inlineQty += '<div class="col-xs-12 toll_issues">'; inlineQty += '<div class="input-group"><span class="input-group-addon" id="toll_issues_text">TOLL ISSUES<span class="mandatory">*</span></span>'; inlineQty += '<select multiple id="toll_issues" class="form-control toll_issues" disabled size="' + tollIssuesResultSet.length + '">'; tollIssuesResultSet.run().each(function(tollIssueResult) { var issue_name = tollIssueResult.getValue('name'); var issue_id = tollIssueResult.getValue('internalId'); var selected = false; if (has_toll_issues) { selected = (list_toll_issues.indexOf(issue_id) !== -1); } if (selected) { inlineQty += '<option value="' + issue_id + '" selected>' + issue_name + '</option>'; } else { inlineQty += '<option value="' + issue_id + '">' + issue_name + '</option>'; } return true; }); inlineQty += '</select>'; inlineQty += '</div></div></div></div>'; // Resolved TOLL Issues log.debug({ title: 'list_resolved_toll_issues : ', details: list_resolved_toll_issues }); var has_resolved_toll_issues = (!isNullorEmpty(list_resolved_toll_issues)); if (has_resolved_toll_issues) { var text_resolved_toll_issues = ''; tollIssuesResultSet.run().each(function(tollIssueResult) { var issue_name = tollIssueResult.getValue('name'); var issue_id = tollIssueResult.getValue('internalId'); if (list_resolved_toll_issues.indexOf(issue_id) !== -1) { text_resolved_toll_issues += issue_name + '\n'; } }); log.debug({ title: 'text_resolved_toll_issues : ', details: text_resolved_toll_issues }); inlineQty += '<div class="form-group container resolved_toll_issues_section">'; inlineQty += '<div class="row">'; inlineQty += '<div class="col-xs-12 resolved_toll_issues">'; inlineQty += '<div class="input-group">'; inlineQty += '<span class="input-group-addon" id="resolved_toll_issues_text">RESOLVED TOLL ISSUES</span>'; inlineQty += '<textarea id="resolved_toll_issues" class="form-control resolved_toll_issues" rows="' + list_resolved_toll_issues.length + '" disabled>' + text_resolved_toll_issues.trim() + '</textarea>'; inlineQty += '</div></div></div></div>'; } return inlineQty; }; /** * The free-from text area for comments. * @param {String} comment * @param {String} selector_type * @param {Number} status_value * @return {String} inlineQty */ function commentSection(comment, selector_type, status_value) { if (isNullorEmpty(comment)) { comment = ''; } else { comment += '\n'; } switch (selector_type) { case 'barcode_number': var inlineQty = '<div class="form-group container comment_section">'; break; case 'invoice_number': var inlineQty = '<div class="form-group container comment_section hide">'; break; case 'customer_issue': var inlineQty = '<div class="form-group container comment_section">'; break; } inlineQty += '<div class="row">'; inlineQty += '<div class="col-xs-12 comment">'; inlineQty += '<div class="input-group">'; inlineQty += '<span class="input-group-addon" id="comment_text">COMMENT<span class="mandatory hide">*</span></span>'; if (isTicketNotClosed(status_value)) { inlineQty += '<textarea id="comment" class="form-control comment" rows="3" disabled>' + comment + '</textarea>'; } else { inlineQty += '<textarea id="comment" class="form-control comment" rows="3" disabled readonly>' + comment + '</textarea>'; } inlineQty += '</div></div></div></div>'; return inlineQty; } /** * The customer contact details section. * Possibility for the user to add / edit the contacts. * @return {String} inlineQty */ function mpexContactSection() { // Contact details header var inlineQty = '<div class="form-group container mpex_contact_section">'; inlineQty += '<div class="row">'; inlineQty += '<div class="col-xs-12 heading2">'; inlineQty += '<h4><span style="background-color: #379E8F" class="label label-default col-xs-12">CONTACT DETAILS</span></h4>'; inlineQty += '</div>'; inlineQty += '</div></div>'; // Contact table inlineQty += '<div class="form-group container contacts_section" style="font-size: small;">'; inlineQty += '<div class="row">'; inlineQty += '<div class="col-xs-12 contacts_div">'; // Since the table is not displayed correctly when added through suitelet, // It is added with jQuery in the pageInit() function in the client script 'mp_cl_open_ticket.js'. inlineQty += '</div>'; inlineQty += '</div>'; inlineQty += '</div>'; // Add/edit contacts button inlineQty += '<div class="form-group container reviewcontacts_section">'; inlineQty += '<div class="row">'; inlineQty += '<div class="col-xs-4 col-xs-offset-4 reviewcontacts">'; inlineQty += '<input type="button" style="background-color: #379E8F; border-color: #379E8F; font-weight: 700" value="ADD/EDIT CONTACTS" class="form-control btn btn-primary" id="reviewcontacts" />'; inlineQty += '</div></div></div>'; return inlineQty; }; /** * The receiver phone and email fields. * These fields should be automatically filled based on the Selector number value. * @param {String} daytodayphone * @param {String} daytodayemail * @param {Number} status_value * @param {String} selector_type * @return {String} inlineQty */ function receiverEmailPhone(selector_type, receiveremail, receiverphone, receivername, receiverstate, receiverzip, receiversuburb, receiveraddr1, receiveraddr2) { var disabled = 'disabled'; var inlineQty = ''; if (selector_type == 'barcode_number') { // Receiver details header var inlineQty = '<div class="form-group container tickets_details_header_section">'; inlineQty += '<div class="row">'; inlineQty += '<div class="col-xs-12 heading2" >'; inlineQty += '<h4><span style="background-color: #379E8F" class="label label-default col-xs-12">RECEIVER DETAILS</span></h4>'; inlineQty += '</div></div></div>'; inlineQty += '<div class="form-group container receivercontact_section">'; inlineQty += '<div class="row">'; // name field inlineQty += '<div class="col-xs-6 receivername_div">'; inlineQty += '<div class="input-group">'; inlineQty += '<span class="input-group-addon" id="receivername_text">NAME</span>'; inlineQty += '<input id="receivername" value="' + receivername + '" class="form-control receivername" ' + disabled + ' />'; inlineQty += '</div></div>'; // state field inlineQty += '<div class="col-xs-6 receiverstate_div">'; inlineQty += '<div class="input-group">'; inlineQty += '<span class="input-group-addon" id="receiverstate_text">STATE</span>'; inlineQty += '<input id="receiverstate" value="' + receiverstate + '" class="form-control receiverstate" ' + disabled + ' />'; inlineQty += '</div></div></div></div>'; inlineQty += '<div class="form-group container receivercontact2_section">'; inlineQty += '<div class="row">'; // Day to day email field inlineQty += '<div class="col-xs-6 receiveremail_div">'; inlineQty += '<div class="input-group">'; inlineQty += '<span class="input-group-addon" id="receiveremail_text">EMAIL</span>'; inlineQty += '<input id="receiveremail" type="email" value="' + receiveremail + '" class="form-control receiveremail" ' + disabled + ' />'; inlineQty += '<div class="input-group-btn">'; inlineQty += '<button type="button" style="background-color: #379E8F" class="btn btn-success add_as_recipient" data-email="' + receiveremail + '" data-contact-id="" data-firstname="" data-toggle="tooltip" data-placement="right" title="Add as recipient">'; inlineQty += '<span class="glyphicon glyphicon-envelope"></span>'; inlineQty += '</button>'; inlineQty += '</div>'; inlineQty += '</div></div>'; // Day to day phone field inlineQty += '<div class="col-xs-6 receiverphone_div">'; inlineQty += '<div class="input-group">'; inlineQty += '<span class="input-group-addon" id="receiverphone_text">PHONE</span>'; inlineQty += '<input id="receiverphone" type="tel" value="' + receiverphone + '" class="form-control receiverphone" ' + disabled + ' />'; inlineQty += '<div class="input-group-btn"><button type="button" style="background-color: #379E8F" class="btn btn-success" id="call_receiver_phone"><span class="glyphicon glyphicon-earphone"></span></button></div>'; inlineQty += '</div></div></div></div>'; inlineQty += '<div class="form-group container receivercontact3_section">'; inlineQty += '<div class="row">'; // suburb field inlineQty += '<div class="col-xs-6 receiversuburb_div">'; inlineQty += '<div class="input-group">'; inlineQty += '<span class="input-group-addon" id="receiversuburb_text">SUBURB</span>'; inlineQty += '<input id="receiversuburb" value="' + receiversuburb + '" class="form-control receiversuburb" ' + disabled + ' />'; inlineQty += '</div></div>'; // postcode field inlineQty += '<div class="col-xs-6 receiverzip_div">'; inlineQty += '<div class="input-group">'; inlineQty += '<span class="input-group-addon" id="receiverzip_text">POSTCODE</span>'; inlineQty += '<input id="receiverzip" value="' + receiverzip + '" class="form-control receiverzip" ' + disabled + ' />'; inlineQty += '</div></div></div></div>'; inlineQty += '<div class="form-group container receivercontact4_section">'; inlineQty += '<div class="row">'; // address1 field inlineQty += '<div class="col-xs-6 receiveraddr1_div">'; inlineQty += '<div class="input-group">'; inlineQty += '<span class="input-group-addon" id="receiveraddr1_text">ADDRESS1</span>'; inlineQty += '<input id="receiveraddr1" value="' + receiveraddr1 + '" class="form-control receiveraddr1" ' + disabled + ' />'; inlineQty += '</div></div>'; // address2 field inlineQty += '<div class="col-xs-6 receiveraddr2_div">'; inlineQty += '<div class="input-group">'; inlineQty += '<span class="input-group-addon" id="receiveraddr2_text">ADDRESS2</span>'; inlineQty += '<input id="receiveraddr2" value="' + receiveraddr2 + '" class="form-control receiveraddr2" ' + disabled + ' />'; inlineQty += '</div></div></div></div>'; } return inlineQty; } /** * The "Send Email" section. * Possibility for the user to send an email to the customer, based on selected templates. * @param {Number} ticket_id * @param {Number} status_value * @param {Object} account_manager * @returns {String} inlineQty */ function sendEmailSection(ticket_id, status_value, account_manager, list_toll_emails) { var has_toll_emails = (!isNullorEmpty(list_toll_emails)); if (isNullorEmpty(ticket_id) || !isTicketNotClosed(status_value)) { // The section is hidden here rather than in the openTicket function, // because we use the section to send an acknoledgement email when a ticket is opened. var inlineQty = '<div id="send_email_container" class="send_email hide">'; } else { var inlineQty = '<div id="send_email_container" class="send_email">'; } inlineQty += '<div class="form-group container send_email header_section">'; // Send email header inlineQty += '<div class="row">'; inlineQty += '<div class="col-xs-12 heading2">'; inlineQty += '<h4><span style="background-color: #379E8F" class="label label-default col-xs-12">SEND EMAILS</span></h4>'; inlineQty += '</div></div></div>'; inlineQty += '<br></br>' // Row addressees inlineQty += '<div class="form-group container send_email adressees_section">'; inlineQty += '<div class="row">'; inlineQty += '<div class="col-xs-12 to_section">'; inlineQty += '<div class="input-group">'; inlineQty += '<span class="input-group-addon">TO<span class="mandatory">*</span></span>'; inlineQty += '<input id="send_to" class="form-control" data-contact-id="" data-firstname=""/>'; inlineQty += '</div></div></div></div>'; // Toll addresses var toll_emails_columns = new Array(); toll_emails_columns[0] = search.createColumn({ name: 'name' }); toll_emails_columns[1] = search.createColumn({ name: 'internalId' }); var tollEmailsResultSet = search.create({ type: 'customlist_toll_emails', columns: toll_emails_columns, }) inlineQty += '<div class="form-group container send_email toll_adressees_section">'; inlineQty += '<div class="row">'; inlineQty += '<div class="col-xs-12 toll_section">'; inlineQty += '<div class="input-group">'; inlineQty += '<span class="input-group-addon">TOLL EMAILS</span>'; inlineQty += '<select multiple id="send_toll" class="form-control" size="' + tollEmailsResultSet.length + '"/>'; tollEmailsResultSet.run().each(function (tollEmailsResultSet){ var tollEmailName = tollEmailsResultSet.getValue('name'); var tollEmailId = tollEmailsResultSet.getValue('internalId'); var selected = false; if(has_toll_emails) { selected = (list_toll_emails.indexOf(tollEmailId) !== -1); } if (selected) { inlineQty += '<option value="' + tollEmailId + '" selected>' + tollEmailName + '</option>'; } else { inlineQty += '<option value="' + tollEmailId + '">' + tollEmailName + '</option>'; } return true; }); inlineQty += '</select>'; inlineQty += '</div></div></div></div>'; // Row ccs addresses inlineQty += '<div class="form-group container send_email cc_adressees_section">'; inlineQty += '<div class="row">'; inlineQty += '<div class="col-xs-6 cc_section">'; inlineQty += '<div class="input-group">'; inlineQty += '<span class="input-group-addon">CC</span>'; inlineQty += '<input id="send_cc" class="form-control"/>'; inlineQty += '</div></div>'; inlineQty += '<div class="col-xs-6 bcc_section">'; inlineQty += '<div class="input-group">'; inlineQty += '<span class="input-group-addon">BCC</span>'; inlineQty += '<input id="send_bcc" class="form-control"/>'; inlineQty += '</div></div></div></div>'; // Row account manager if (isNullorEmpty(account_manager.name)) { account_manager.name = '' } if (isNullorEmpty(account_manager.email)) { account_manager.email = '' } if (!isNullorEmpty(account_manager.email.email)) { inlineQty += '<div class="form-group container send_email acc_manager_section">'; inlineQty += '<div class="row">'; inlineQty += '<div class="col-xs-10 acc_manager_name_section">'; inlineQty += '<div class="input-group">'; inlineQty += '<span class="input-group-addon">ACCOUNT MANAGER</span>'; inlineQty += '<input id="acc_manager" class="form-control" data-email="' + account_manager.email.email + '" value="' + account_manager.name + ' - ' + account_manager.email.email + '" disabled/>'; inlineQty += '</div></div>'; inlineQty += '<div class="col-xs-2 acc_manager_button_section">'; inlineQty += '<button id="acc_manager_button" style="background-color: #379E8F; border-color: #379E8F" type="button" class="btn btn-success btn-block">ADD TO CC</button>'; inlineQty += '</div></div></div>'; } // Row Template inlineQty += '<div class="form-group container send_email template_section">'; inlineQty += '<div class="row">'; inlineQty += '<div class="col-xs-12 template_section">'; inlineQty += '<div class="input-group">'; inlineQty += '<span class="input-group-addon">TEMPLATE<span class="mandatory">*</span></span>'; inlineQty += '<select id="template" class="form-control">'; inlineQty += '<option></option>'; // Load the template options var templatesSearch = search.load({ id: 'customsearch_cctemplate_mp_ticket', type: 'customrecord_camp_comm_template' }); var templatesSearchResults = templatesSearch.run(); templatesSearchResults.each(function(templatesSearchResult) { // var tempId = templatesSearchResult.getValue('internalid'); var tempId = templatesSearchResult["id"]; var tempName = templatesSearchResult.getValue('name'); inlineQty += '<option value="' + tempId + '">' + tempName + '</option>'; return true; }); inlineQty += '</select>'; inlineQty += '</div></div></div></div>'; // Row Subject inlineQty += '<div class="form-group container send_email subject_section">'; inlineQty += '<div class="row">'; inlineQty += '<div class="col-xs-12 subject_section">'; inlineQty += '<div class="input-group">'; inlineQty += '<span class="input-group-addon">SUBJECT<span class="mandatory">*</span></span>'; inlineQty += '<input id="subject" class="form-control" />'; inlineQty += '</div></div></div></div>'; // Row Body inlineQty += '<div class="form-group container send_email body_section">'; inlineQty += '<div class="row">'; inlineQty += '<div class="col-xs-12 body_section">'; inlineQty += '<div id="email_body"></div>'; inlineQty += '</div></div></div>'; // SEND EMAIL button inlineQty += '<div class="form-group container send_email button_section">'; inlineQty += '<div class="row">'; inlineQty += '<div class="col-xs-4 col-xs-offset-4 send_email_btn">'; inlineQty += '<input type="button" style="background-color: #379E8F; border-color: #379E8F; font-weight: 700" value="SEND EMAIL" class="form-control btn btn-primary" id="send_email" />'; inlineQty += '</div></div></div></div>'; return inlineQty; }; function externalBarcodeSource(selector_type, barcodempdl, barcodesource) { var disabled = 'disabled'; var inlineQty = ''; if (selector_type == 'barcode_number') { inlineQty += '<div class="form-group container barcode_section">'; inlineQty += '<div class="row">'; // MPLD field inlineQty += '<div class="col-xs-6 barcodempdl_div">'; inlineQty += '<div class="input-group">'; inlineQty += '<span class="input-group-addon" id="barcodempdl_text">EXTERNAL BARCODE</span>'; inlineQty += '<input id="barcodempdl" value="' + barcodempdl + '" class="form-control barcodempdl" ' + disabled + ' />'; inlineQty += '</div></div>'; // barcode source field inlineQty += '<div class="col-xs-6 barcodesource_div">'; inlineQty += '<div class="input-group">'; inlineQty += '<span class="input-group-addon" id="barcodesource_text">BARCODE SOURCE</span>'; inlineQty += '<input id="barcodesource" value="' + barcodesource + '" class="form-control barcodesource" ' + disabled + ' />'; inlineQty += '</div></div></div></div>'; } return inlineQty; } function tabsSection(customer_number, ticket_id, selector_number, selector_id, selector_type, status_value, date_created, creator_id, creator_name, status, customer_id, customer_name, daytodayphone, daytodayemail, accountsphone, accountsemail, maap_bank_account_number, maap_parent_bank_account_number, zee_id, franchisee_name, zee_main_contact_name, zee_email, zee_main_contact_phone, zee_abn, date_stock_used, time_stock_used, final_delivery_text, selected_enquiry_status_id,attachments_hyperlink, selected_enquiry_status_id, owner_list, list_toll_issues, list_resolved_toll_issues, comment, account_manager, list_toll_emails, customer_ticket_status, receiveremail, receiverphone, receivername, receiverstate, receiverzip, receiversuburb, receiveraddr1, receiveraddr2, barcodempdl, barcodesource, prod_stock_invoice) { var inlineQty = '<br/><div >'; // Tabs headers inlineQty += '<style>.nav > li.active > a, .nav > li.active > a:focus, .nav > li.active > a:hover { background-color: #379E8F; color: #fff }'; inlineQty += '.nav > li > a, .nav > li > a:focus, .nav > li > a:hover { margin-left: 5px; margin-right: 5px; border: 2px solid #379E8F; color: #379E8F; }'; inlineQty += '</style>'; // Ticket details header inlineQty += '<div class="form-group container tickets_details_header_section" style="margin-top: 10px">'; inlineQty += '<div class="row">'; inlineQty += '<div class="col-xs-12" >'; inlineQty += '<span">'; inlineQty += '<ul class="nav nav-pills nav-justified" style="margin:0%; ">'; inlineQty += '<li role="presentation" class="active"><a data-toggle="tab" href="#ticketdetails"><b>TICKET DETAILS</b></a></li>'; inlineQty += '<li role="presentation" class=""><a data-toggle="tab" href="#sendemails"><b>SEND EMAILS</b></a></li>'; inlineQty += '</ul>'; inlineQty += '</span>'; inlineQty += '</div></div></div>'; // Tabs content inlineQty += '<div class="tab-content">'; // TICKET DETAILS TAB inlineQty += '<div role="tabpanel" class="tab-pane active" id="ticketdetails">'; inlineQty += customerNumberSection(customer_number, ticket_id); inlineQty += selectorSection(ticket_id, selector_number, selector_id, selector_type, status_value); if (!isNullorEmpty(ticket_id)) { inlineQty += externalBarcodeSource(selector_type, barcodempdl, barcodesource) inlineQty += ticketSection(dateISOToNetsuite(date_created), creator_id, creator_name, status, customer_ticket_status); } if (isNullorEmpty(ticket_id) || (!isNullorEmpty(ticket_id) && !isNullorEmpty(customer_id)) || !isNullorEmpty(customer_number)) { inlineQty += customerSection(customer_name); inlineQty += daytodayContactSection(daytodayphone, daytodayemail, status_value, selector_type); inlineQty += accountsContactSection(accountsphone, accountsemail, status_value, selector_type); } if(isNullorEmpty(ticket_id) || (!isNullorEmpty(ticket_id) && (selector_type == 'invoice_section'))) { inlineQty += maapBankAccountSection(maap_bank_account_number, maap_parent_bank_account_number, selector_type); } if (isNullorEmpty(ticket_id) || (!isNullorEmpty(ticket_id) && !isNullorEmpty(zee_id)) || !isNullorEmpty(customer_number)) { inlineQty += franchiseeMainContactSection(franchisee_name, zee_main_contact_name, zee_email, zee_main_contact_phone, zee_abn); } inlineQty += mpexStockUsedSection(selector_type, date_stock_used, time_stock_used); inlineQty += finalDeliveryEnquirySection(status_value, selector_type, final_delivery_text, selected_enquiry_status_id, prod_stock_invoice); inlineQty += attachmentsSection(attachments_hyperlink, status_value); if(!isNullorEmpty(ticket_id)) { inlineQty += receiverEmailPhone(selector_type, receiveremail, receiverphone, receivername, receiverstate, receiverzip, receiversuburb, receiveraddr1, receiveraddr2); } // ENQUIRY SECTION //inlineQty += enquiryMediumSection(list_enquiry_mediums, selected_enquiry_status_id, selector_type) //inlineQty += enquiryCountSection( total_enquiry_count, chat_enquiry_count, phone_enquiry_count, email_enquiry_count, selector_type); //TICKET LABEL DROPDOWN //inlineQty += labelSection(selected_label_id, selector_type, status_value); //inlineQty += closeReopenSubmitTicketButton(ticket_id, status_value); inlineQty += issuesHeader(); inlineQty += reminderSection(status_value); inlineQty += ownerSection(ticket_id, owner_list, status_value); inlineQty += tollIssuesSection(list_toll_issues, list_resolved_toll_issues, status_value, selector_type); inlineQty += commentSection(comment, selector_type, status_value); inlineQty += '</div>'; // CONTACT / EMAILS if (!isNullorEmpty(ticket_id)) { inlineQty += '<div role="tabpanel" class="tab-pane" id="sendemails">'; inlineQty += mpexContactSection(); inlineQty += sendEmailSection(ticket_id, status_value, account_manager, list_toll_emails); //inlineQty += closeReopenSubmitTicketButton(ticket_id, status_value); inlineQty += '</div>'; } inlineQty += '</div></div>'; return inlineQty; } /** * Returns whether a ticket is closed or not based on its status value. * @param {Number} status_value * @returns {Boolean} is_ticket_closed */ function isTicketNotClosed(status_value) { var is_ticket_not_closed = ((status_value != 3) && (status_value != 8)) ? true : false; return is_ticket_not_closed; } /** * Whether the user is from the finance team, * or a Data Systems Co-ordinator, MailPlus Administration or Administrator user. * @param {Number} userRole * @returns {Boolean} */ function isFinanceRole(userRole) { // 1001, 1031 and 1023 are finance roles // 1032 is the Data Systems Co-ordinator role (to be deleted in prod) // 1006 is the Mail Plus Administration role. // 3 is the Administrator role. return ((userRole == 1001 || userRole == 1031 || userRole == 1023) || ((userRole == 1032) || (userRole == 1006) || (userRole == 3))); } function isNullorEmpty(strVal) { return (strVal == null || strVal == '' || strVal == 'null' || strVal == undefined || strVal == 'undefined' || strVal == '- None -'); } return { onRequest: onRequest }; });
/** * @NApiVersion 2.x * @NScriptType ScheduledScript * * Module Description: Mass Invoice Email * * @Last Modified by: Anesu Chakaingesu * */ define(['N/ui/serverWidget', 'N/email', 'N/runtime', 'N/search', 'N/record', 'N/http', 'N/log', 'N/redirect', 'N/task', 'N/format', 'N/currentRecord', 'N/render'], function(ui, email, runtime, search, record, http, log, redirect, task, format, currentRecord, render) { var baseURL = 'https://1048144.app.netsuite.com'; if (runtime.envType == "SANDBOX") { baseURL = 'https://1048144-sb3.app.netsuite.com'; } var role = runtime.getCurrentUser().role; var zee = 0; var currRec = currentRecord.get(); var ctx = runtime.getCurrentScript(); // Date Today n Date Tomorrow var today_date = new Date(); // Test Time 6:00pm - '2022-06-29T18:20:00.000+10:00' today_date.toLocaleString('en-AU', { timeZone: 'Australia/Sydney' }); today_date = dateISOToNetsuite(today_date); today_date = format.parse({ value: today_date, type: format.Type.DATE }); // Reformat Date var sent_invoices = []; // var sent_invoices = ["4131738"] function main() { /** * Work Flow: * // Send Email // Add New Line in Record // Once Completed List, Delete All Records. */ // Get Results var taskIdSet = JSON.parse(JSON.stringify(ctx.getParameter({ name: 'custscript_ss_mass_inv_email_task_set'}))); var totalInvCount = parseInt(ctx.getParameter({ name: 'custscript_ss_mass_inv_email_tot_num_inv'})); var selectedZeeSet = new Array(); selectedZeeSet = JSON.parse(JSON.stringify(ctx.getParameter({ name: 'custscript_ss_mass_inv_email_zee_set'}))); var user_email = ctx.getParameter({ name: 'custscript_ss_mass_inv_email_user_email'}); var main_index = parseInt(ctx.getParameter({ name: 'custscript_ss_mass_inv_email_main_index'})) if (isNullorEmpty(main_index) || isNaN(main_index)){ main_index = 0; } var invoiceSet = JSON.parse(JSON.stringify({ name: 'custscript_ss_mass_inv_email_inv_set'})); if (invoiceSet.length > 1){ invoiceSet = invoiceSet.split("\u0005") // Remove NetSuite Random Space Thingo. } else { invoiceSet = []; } // Testing // var selectedZeeSet = [779884] // TEST // var taskIdSet = 272834; // TEST - NSW // var totalInvCount = 2; // 2 Invoices // Log Values: TESTs log.debug({ title: 'Executed Order 66: ZEE Ready', details: selectedZeeSet }); log.debug({ title: 'Executed Order 66: TASK Ready', details: taskIdSet }); log.debug({ title: 'Main Index: Ready', details: main_index }); log.debug({ title: 'Invoice Set: Ready', details: invoiceSet }); if (!isNullorEmpty(selectedZeeSet)){ // Verify Zee Set Exists. // Delete List Record All. deleteSentList(main_index); // Only Delete List on First Run. log.debug({ title: 'INVOICES ALREADY SENT', details: sent_invoices }); log.debug({ title: 'Type Of', details: typeof selectedZeeSet }); if (main_index == 0){ if (selectedZeeSet.length > 1){ log.debug({ title: 'Selected Zee: Split Array', details: selectedZeeSet }); selectedZeeSet = selectedZeeSet.split("\u0005") // Remove NetSuite Random Space Thingo. } } else { log.debug({ title: 'Selected Zee: Rescheduled Index, Array?', details: selectedZeeSet }); selectedZeeSet = JSON.parse(selectedZeeSet) } if (selectedZeeSet.length > 0){ // Ensures that Only when the Selected Zee List is populated, it will filter. // Load Search var invSearch = search.load({ type: 'invoice', id: 'customsearch_mass_inv_email_list' }); invSearch.filters.push(search.createFilter({ name: 'partner', operator: search.Operator.ANYOF, values: selectedZeeSet })); invSearch.filters.push(search.createFilter({ name: 'email', operator: search.Operator.ISNOTEMPTY, values: null })); if (sent_invoices != null && sent_invoices.length > 0){ invSearch.filters.push(search.createFilter({ name: 'internalid', operator: search.Operator.NONEOF, values: sent_invoices })); } var invSearchRes = invSearch.run(); // Search Result // if (main_index == 0) { // Update Total Invoice Count on First Run. // totalInvCount = invSearch.runPaged().count; var invResLength = invSearch.runPaged().count; // } // log.debug({ // title: 'Search Length', // details: totalInvCount // }); var invResultSet = []; // Sudo Array Containing Complete Search Data for (var data_index = 0; data_index < invResLength; data_index += 1000) { invResultSet.push(invSearchRes.getRange({ start: data_index, end: data_index + 999 })); } log.debug({ title: 'Search Result Set', details: invResultSet }); // Loop Through Search Results and Log var result_count = 0; for (var i = 0; i < invResultSet.length; i++) { var invResult = invResultSet[i]; log.debug({ title: 'Search Result Set: ' + i, details: invResult.length }); result_count = result_count + invResult.length; } log.debug({ title: 'Total Search Result', details: result_count }); // TEST DATA /** * For Loop * Index = 0; * var data_index = 650; * data_index < 1500; * data_index += 1000; * * zendeskSearchRes.getRange({ start: 650, end: 650 + 999 == 1649}) }); * THIS WILL NOT RUN AS ITS OVER 1500 zendeskSearchRes.getRange({ start: 1650, end: 1350 + 999 = 2349 }) }); * THIS DOES NO RUN AS ITS ENDING AT 1500. zendeskSearchRes.getRange({ start: 2000, end: 2000 + 999 = 2999 }); * */ var index = 0; for (var inv_data_index = 0; inv_data_index < invResultSet.length; inv_data_index++){ invResultSet[inv_data_index].every(function(invData){ //, index, arr var usageLimit = ctx.getRemainingUsage(); log.debug({ title: 'usageLimit', details: usageLimit }); // If SS Breaker has been scheduled, stop the script. // try { // var ss_breaker = task.create({ // taskType: task.TaskType.SCHEDULED_SCRIPT, // scriptId: 'customscript_ss_breaker', // deploymentId: 'customdeploy_ss_breaker_pending', // }); // var ss_breaker_task_id = ss_breaker.submit(); // var scriptStatus = task.checkStatus({ // taskId: ss_breaker_task_id // }); // log.debug({ // title: 'Script Status', // details: scriptStatus.status // }); // } catch (error) { // log.debug({ // title: 'Error: SS Break Status', // details: error // }); // } // if (scriptStatus.status == 'PENDING') { return false } else if (usageLimit < 200) { // TESTING PURPOSES: || index == 150 params = { custscript_ss_mass_inv_email_task_set: taskIdSet, custscript_ss_mass_inv_email_zee_set: selectedZeeSet, custscript_ss_mass_inv_email_main_index: main_index + index, custscript_ss_mass_inv_email_tot_num_inv: totalInvCount, custscript_ss_mass_inv_email_user_email: user_email, custscript_ss_mass_inv_email_inv_set: invoiceSet, }; var reschedule = task.create({ taskType: task.TaskType.SCHEDULED_SCRIPT, scriptId: 'customscript_ss_mass_inv_email', deploymentId: 'customdeploy_ss_mass_inv_email', params: params }); var reschedule_id = reschedule.submit(); log.error({ title: 'Attempting: Rescheduling Script', details: JSON.stringify(reschedule_id) }); return false; } else { log.debug({ title: 'Indexes: Main + Index', details: main_index + " | " + index }); // Customer Details var internalid = invData.getValue({ name: "internalid", join: 'customer' }); var entityid = invData.getValue({ name: "entityid", join: 'customer' }); var companyname = invData.getValue({ name: 'companyname', join: 'customer' }); var email_address = invData.getValue({ name: 'email', join: 'customer' }); var cc_email = invData.getValue({ name: 'custentity_accounts_cc_email', join: 'customer' }); cc_email = formatCCEmail(cc_email) var cc_address = []; if (cc_email.length > 1){ // More than one Email in Array. cc_email.forEach(function(el){ if (el.length > 4){ // Make Sure Elements (Email) length is not Blank and includes minimum 4 Characters (.com) cc_address.push(el); } }); } else { cc_address.push(cc_email); // If Only One, Push Email into Saved CC Array. } // Invoice Details var inv_id = invData.getValue({ name: 'internalid' }); var inv_type = invData.getText({ name: 'custbody_inv_type' }); var tot_am = '$' + invData.getValue({ name: 'amount' }); if (isNullorEmpty(inv_type)) { inv_type = 'Service'; } var doc_num = invData.getValue({ name: 'tranid' }); var days_open = invData.getValue({ name: 'daysopen' }); var zee_name = invData.getText({ name: 'partner' }); try { // Create Object createSentList(inv_id, doc_num, entityid, companyname, inv_type, tot_am, days_open, zee_name); // Save Invoices - Secondly var attachments = []; var invFile = getInvoiceFiles(inv_id); attachments.push(invFile); //Send Email sendEmail(internalid, companyname, email_address, attachments, doc_num, user_email, cc_address); // Set Invoice to Emailed and Date | After Emailed. setInvoiceData(inv_id); } catch (e) { log.error({ title: 'Send Email Error', details: e }); email.send({ author: 35031, // Accounts: 35031 | Customer Service: 112209 body: 'Error for Customer ID '+ internalid +' | Company Name ' + companyname + ' | with Invoice ID '+ inv_id + '\n\n' + e, // Get Email Template subject: 'Mass Invoice Email: Error', recipients: ['anesu.chakaingesu@mailplus.com.au'], // , 'popie.popie@mailplus.com.au' attachments: new Array(getInvoiceFiles(inv_id)), }); } index++; return true; } }) } } } setTaskCompleted(taskIdSet); // Set Task As Completed log.debug({ title: 'END SCRIPT' }) } function sendEmail(custSet, companyname, email_address, attachments, invoice_number, user_email, cc_address){ // log.debug({ // title: 'Email Address', // details: email_address // }) var email_template = emailTemplate(); if (!isNullorEmpty(cc_address)){ // CC Field Does email.send({ author: 35031, // Accounts: 35031 | Customer Service: 112209 body: email_template, // Get Email Template subject: 'MailPlus Invoice: ' + invoice_number, recipients: [email_address], // 'anesu.chakaingesu@mailplus.com.au' | email_address cc: [cc_address], // 'anesu.chakaingesu@mailplus.com.au' | cc_address attachments: attachments, relatedRecords:{ entityId: custSet // Add Email Reminder Notification as Message Under Customer } }); } else { // CC Field Does Not Exist email.send({ author: 35031, // Accounts: 35031 | Customer Service: 112209 body: email_template, // Get Email Template subject: 'MailPlus Invoice: ' + invoice_number, recipients: [email_address], // 'anesu.chakaingesu@mailplus.com.au' | email_address attachments: attachments, relatedRecords:{ entityId: custSet // Add Email Reminder Notification as Message Under Customer } }); } log.debug({ title: 'Send Out Emails: Attachments and Data', details: custSet + ' ' + companyname + ' ' + email_address + ' ' + attachments }) } function getInvoiceFiles(entityId){ var transactionFile = render.transaction({ entityId: parseInt(entityId), printMode: render.PrintMode.PDF }); log.debug({ title: 'Invoice File', details: transactionFile }) return transactionFile; } function setInvoiceData(invoice_id){ var rec = record.load({ type: 'invoice', id: invoice_id }) rec.setValue({ fieldId: 'custbody_invoice_emailed_date', value: today_date }); rec.setValue({ fieldId: 'custbody_invoice_emailed', value: true }); // true | TEST = false rec.save(); return true; } function setTaskCompleted(taskIdSet){ // Set Task as Completed; if (taskIdSet.length > 1){ taskIdSet = taskIdSet.split("\u0005") // Remove NetSuite Random Space Thingo. } taskIdSet.forEach(function(taskId){ var taskRec = record.load({ type: 'task', id: taskId}); taskRec.setValue({ fieldId: 'status', value: "COMPLETE" }) // Set to Completed; taskRec.save(); }); return true; } function createSentList(inv_id, doc_num, entityid, companyname, inv_type, tot_am, days_open, zee_name) { var sentListRec = record.create({ type: 'customrecord_mass_inv_email_list', isDynamic: true, }); sentListRec.setValue({ fieldId: 'name' , value: inv_id }); sentListRec.setValue({ fieldId: 'custrecord_mass_inv_email_zee_name' , value: zee_name}); // sentListRec.setValue({ fieldId: 'custrecord_mass_inv_email_doc_num' , value: doc_num}); sentListRec.setValue({ fieldId: 'custrecord_mass_inv_email_entityid' , value: entityid}); sentListRec.setValue({ fieldId: 'custrecord_mass_inv_email_companyname' , value: companyname}); sentListRec.setValue({ fieldId: 'custrecord_mass_inv_email_inv_type' , value: inv_type}); sentListRec.setValue({ fieldId: 'custrecord_mass_inv_email_tot_am' , value: tot_am}); sentListRec.setValue({ fieldId: 'custrecord_mass_inv_email_days_open' , value: days_open}); sentListRec.save(); return true; } function deleteSentList(main_index){ // Populate List of Invoices Already Sent log.debug({ title: 'Deleting Records', details: main_index }); var invRecEmailList = search.load({ id: 'customsearch_mass_inv_email_list_2', type: 'customrecord_mass_inv_email_list' }); invRecEmailList.run().each(function(res){ sent_invoices.push(res.getValue({ name: 'name' })); // populate list of invoices if (main_index == 0){ record.delete({ type: 'customrecord_mass_inv_email_list', id: res.getValue({ name: 'internalid' }) }); } return true; }); } function emailTemplate(){ //companyname, email_address var emailMerger = render.mergeEmail({ templateId: 177, //. Mass Invoice Email Template - 363 | Invoice Email - 177 entity: null, recipient: null, supportCaseId: null, transactionId: null, customRecord: null }); var html_body = emailMerger.body; return html_body; } function formatCCEmail(email_address) { // var email_address = email_address.replace(/ /g, ''); var cc_address = email_address.replace(/\s/g, ''); // Remove Spaces. cc_address = cc_address.toLowerCase(); // Lowercases everything cc_address = cc_address.split(','); // Split Comma to Array. return cc_address; } /** * Used to pass the values of `date_from` and `date_to` between the scripts and to Netsuite for the records and the search. * @param {String} date_iso "2020-06-01" * @returns {String} date_netsuite "1/6/2020" */ function dateISOToNetsuite(date_iso) { var date_netsuite = ''; if (!isNullorEmpty(date_iso)) { var date_utc = new Date(date_iso); // var date_netsuite = nlapiDateToString(date_utc); var date_netsuite = format.format({ value: date_utc, type: format.Type.DATE }); } return date_netsuite; } function isNullorEmpty(strVal) { return (strVal == null || strVal == '' || strVal == 'null' || strVal == undefined || strVal == 'undefined' || strVal == '- None -'); } return { execute: main } });
982
[{"tag": "EMAIL", "value": "anesu.chakaingesu@mailplus.com.au", "start": 14010, "end": 14043}, {"tag": "EMAIL", "value": "popie.popie@mailplus.com.au", "start": 14053, "end": 14080}, {"tag": "EMAIL", "value": "anesu.chakaingesu@mailplus.com.au", "start": 15172, "end": 15205}, {"tag": "EMAIL", "value": "anesu.chakaingesu@mailplus.com.au", "start": 15261, "end": 15294}, {"tag": "EMAIL", "value": "anesu.chakaingesu@mailplus.com.au", "start": 15836, "end": 15869}]
true
5
/** * @NApiVersion 2.x * @NScriptType ScheduledScript * * Module Description: Mass Invoice Email * * @Last Modified by: Anesu Chakaingesu * */ define(['N/ui/serverWidget', 'N/email', 'N/runtime', 'N/search', 'N/record', 'N/http', 'N/log', 'N/redirect', 'N/task', 'N/format', 'N/currentRecord', 'N/render'], function(ui, email, runtime, search, record, http, log, redirect, task, format, currentRecord, render) { var baseURL = 'https://1048144.app.netsuite.com'; if (runtime.envType == "SANDBOX") { baseURL = 'https://1048144-sb3.app.netsuite.com'; } var role = runtime.getCurrentUser().role; var zee = 0; var currRec = currentRecord.get(); var ctx = runtime.getCurrentScript(); // Date Today n Date Tomorrow var today_date = new Date(); // Test Time 6:00pm - '2022-06-29T18:20:00.000+10:00' today_date.toLocaleString('en-AU', { timeZone: 'Australia/Sydney' }); today_date = dateISOToNetsuite(today_date); today_date = format.parse({ value: today_date, type: format.Type.DATE }); // Reformat Date var sent_invoices = []; // var sent_invoices = ["4131738"] function main() { /** * Work Flow: * // Send Email // Add New Line in Record // Once Completed List, Delete All Records. */ // Get Results var taskIdSet = JSON.parse(JSON.stringify(ctx.getParameter({ name: 'custscript_ss_mass_inv_email_task_set'}))); var totalInvCount = parseInt(ctx.getParameter({ name: 'custscript_ss_mass_inv_email_tot_num_inv'})); var selectedZeeSet = new Array(); selectedZeeSet = JSON.parse(JSON.stringify(ctx.getParameter({ name: 'custscript_ss_mass_inv_email_zee_set'}))); var user_email = ctx.getParameter({ name: 'custscript_ss_mass_inv_email_user_email'}); var main_index = parseInt(ctx.getParameter({ name: 'custscript_ss_mass_inv_email_main_index'})) if (isNullorEmpty(main_index) || isNaN(main_index)){ main_index = 0; } var invoiceSet = JSON.parse(JSON.stringify({ name: 'custscript_ss_mass_inv_email_inv_set'})); if (invoiceSet.length > 1){ invoiceSet = invoiceSet.split("\u0005") // Remove NetSuite Random Space Thingo. } else { invoiceSet = []; } // Testing // var selectedZeeSet = [779884] // TEST // var taskIdSet = 272834; // TEST - NSW // var totalInvCount = 2; // 2 Invoices // Log Values: TESTs log.debug({ title: 'Executed Order 66: ZEE Ready', details: selectedZeeSet }); log.debug({ title: 'Executed Order 66: TASK Ready', details: taskIdSet }); log.debug({ title: 'Main Index: Ready', details: main_index }); log.debug({ title: 'Invoice Set: Ready', details: invoiceSet }); if (!isNullorEmpty(selectedZeeSet)){ // Verify Zee Set Exists. // Delete List Record All. deleteSentList(main_index); // Only Delete List on First Run. log.debug({ title: 'INVOICES ALREADY SENT', details: sent_invoices }); log.debug({ title: 'Type Of', details: typeof selectedZeeSet }); if (main_index == 0){ if (selectedZeeSet.length > 1){ log.debug({ title: 'Selected Zee: Split Array', details: selectedZeeSet }); selectedZeeSet = selectedZeeSet.split("\u0005") // Remove NetSuite Random Space Thingo. } } else { log.debug({ title: 'Selected Zee: Rescheduled Index, Array?', details: selectedZeeSet }); selectedZeeSet = JSON.parse(selectedZeeSet) } if (selectedZeeSet.length > 0){ // Ensures that Only when the Selected Zee List is populated, it will filter. // Load Search var invSearch = search.load({ type: 'invoice', id: 'customsearch_mass_inv_email_list' }); invSearch.filters.push(search.createFilter({ name: 'partner', operator: search.Operator.ANYOF, values: selectedZeeSet })); invSearch.filters.push(search.createFilter({ name: 'email', operator: search.Operator.ISNOTEMPTY, values: null })); if (sent_invoices != null && sent_invoices.length > 0){ invSearch.filters.push(search.createFilter({ name: 'internalid', operator: search.Operator.NONEOF, values: sent_invoices })); } var invSearchRes = invSearch.run(); // Search Result // if (main_index == 0) { // Update Total Invoice Count on First Run. // totalInvCount = invSearch.runPaged().count; var invResLength = invSearch.runPaged().count; // } // log.debug({ // title: 'Search Length', // details: totalInvCount // }); var invResultSet = []; // Sudo Array Containing Complete Search Data for (var data_index = 0; data_index < invResLength; data_index += 1000) { invResultSet.push(invSearchRes.getRange({ start: data_index, end: data_index + 999 })); } log.debug({ title: 'Search Result Set', details: invResultSet }); // Loop Through Search Results and Log var result_count = 0; for (var i = 0; i < invResultSet.length; i++) { var invResult = invResultSet[i]; log.debug({ title: 'Search Result Set: ' + i, details: invResult.length }); result_count = result_count + invResult.length; } log.debug({ title: 'Total Search Result', details: result_count }); // TEST DATA /** * For Loop * Index = 0; * var data_index = 650; * data_index < 1500; * data_index += 1000; * * zendeskSearchRes.getRange({ start: 650, end: 650 + 999 == 1649}) }); * THIS WILL NOT RUN AS ITS OVER 1500 zendeskSearchRes.getRange({ start: 1650, end: 1350 + 999 = 2349 }) }); * THIS DOES NO RUN AS ITS ENDING AT 1500. zendeskSearchRes.getRange({ start: 2000, end: 2000 + 999 = 2999 }); * */ var index = 0; for (var inv_data_index = 0; inv_data_index < invResultSet.length; inv_data_index++){ invResultSet[inv_data_index].every(function(invData){ //, index, arr var usageLimit = ctx.getRemainingUsage(); log.debug({ title: 'usageLimit', details: usageLimit }); // If SS Breaker has been scheduled, stop the script. // try { // var ss_breaker = task.create({ // taskType: task.TaskType.SCHEDULED_SCRIPT, // scriptId: 'customscript_ss_breaker', // deploymentId: 'customdeploy_ss_breaker_pending', // }); // var ss_breaker_task_id = ss_breaker.submit(); // var scriptStatus = task.checkStatus({ // taskId: ss_breaker_task_id // }); // log.debug({ // title: 'Script Status', // details: scriptStatus.status // }); // } catch (error) { // log.debug({ // title: 'Error: SS Break Status', // details: error // }); // } // if (scriptStatus.status == 'PENDING') { return false } else if (usageLimit < 200) { // TESTING PURPOSES: || index == 150 params = { custscript_ss_mass_inv_email_task_set: taskIdSet, custscript_ss_mass_inv_email_zee_set: selectedZeeSet, custscript_ss_mass_inv_email_main_index: main_index + index, custscript_ss_mass_inv_email_tot_num_inv: totalInvCount, custscript_ss_mass_inv_email_user_email: user_email, custscript_ss_mass_inv_email_inv_set: invoiceSet, }; var reschedule = task.create({ taskType: task.TaskType.SCHEDULED_SCRIPT, scriptId: 'customscript_ss_mass_inv_email', deploymentId: 'customdeploy_ss_mass_inv_email', params: params }); var reschedule_id = reschedule.submit(); log.error({ title: 'Attempting: Rescheduling Script', details: JSON.stringify(reschedule_id) }); return false; } else { log.debug({ title: 'Indexes: Main + Index', details: main_index + " | " + index }); // Customer Details var internalid = invData.getValue({ name: "internalid", join: 'customer' }); var entityid = invData.getValue({ name: "entityid", join: 'customer' }); var companyname = invData.getValue({ name: 'companyname', join: 'customer' }); var email_address = invData.getValue({ name: 'email', join: 'customer' }); var cc_email = invData.getValue({ name: 'custentity_accounts_cc_email', join: 'customer' }); cc_email = formatCCEmail(cc_email) var cc_address = []; if (cc_email.length > 1){ // More than one Email in Array. cc_email.forEach(function(el){ if (el.length > 4){ // Make Sure Elements (Email) length is not Blank and includes minimum 4 Characters (.com) cc_address.push(el); } }); } else { cc_address.push(cc_email); // If Only One, Push Email into Saved CC Array. } // Invoice Details var inv_id = invData.getValue({ name: 'internalid' }); var inv_type = invData.getText({ name: 'custbody_inv_type' }); var tot_am = '$' + invData.getValue({ name: 'amount' }); if (isNullorEmpty(inv_type)) { inv_type = 'Service'; } var doc_num = invData.getValue({ name: 'tranid' }); var days_open = invData.getValue({ name: 'daysopen' }); var zee_name = invData.getText({ name: 'partner' }); try { // Create Object createSentList(inv_id, doc_num, entityid, companyname, inv_type, tot_am, days_open, zee_name); // Save Invoices - Secondly var attachments = []; var invFile = getInvoiceFiles(inv_id); attachments.push(invFile); //Send Email sendEmail(internalid, companyname, email_address, attachments, doc_num, user_email, cc_address); // Set Invoice to Emailed and Date | After Emailed. setInvoiceData(inv_id); } catch (e) { log.error({ title: 'Send Email Error', details: e }); email.send({ author: 35031, // Accounts: 35031 | Customer Service: 112209 body: 'Error for Customer ID '+ internalid +' | Company Name ' + companyname + ' | with Invoice ID '+ inv_id + '\n\n' + e, // Get Email Template subject: 'Mass Invoice Email: Error', recipients: ['anpch@example.com'], // , 'nnheo@example.com' attachments: new Array(getInvoiceFiles(inv_id)), }); } index++; return true; } }) } } } setTaskCompleted(taskIdSet); // Set Task As Completed log.debug({ title: 'END SCRIPT' }) } function sendEmail(custSet, companyname, email_address, attachments, invoice_number, user_email, cc_address){ // log.debug({ // title: 'Email Address', // details: email_address // }) var email_template = emailTemplate(); if (!isNullorEmpty(cc_address)){ // CC Field Does email.send({ author: 35031, // Accounts: 35031 | Customer Service: 112209 body: email_template, // Get Email Template subject: 'MailPlus Invoice: ' + invoice_number, recipients: [email_address], // 'anpch@example.com' | email_address cc: [cc_address], // 'anpch@example.com' | cc_address attachments: attachments, relatedRecords:{ entityId: custSet // Add Email Reminder Notification as Message Under Customer } }); } else { // CC Field Does Not Exist email.send({ author: 35031, // Accounts: 35031 | Customer Service: 112209 body: email_template, // Get Email Template subject: 'MailPlus Invoice: ' + invoice_number, recipients: [email_address], // 'anpch@example.com' | email_address attachments: attachments, relatedRecords:{ entityId: custSet // Add Email Reminder Notification as Message Under Customer } }); } log.debug({ title: 'Send Out Emails: Attachments and Data', details: custSet + ' ' + companyname + ' ' + email_address + ' ' + attachments }) } function getInvoiceFiles(entityId){ var transactionFile = render.transaction({ entityId: parseInt(entityId), printMode: render.PrintMode.PDF }); log.debug({ title: 'Invoice File', details: transactionFile }) return transactionFile; } function setInvoiceData(invoice_id){ var rec = record.load({ type: 'invoice', id: invoice_id }) rec.setValue({ fieldId: 'custbody_invoice_emailed_date', value: today_date }); rec.setValue({ fieldId: 'custbody_invoice_emailed', value: true }); // true | TEST = false rec.save(); return true; } function setTaskCompleted(taskIdSet){ // Set Task as Completed; if (taskIdSet.length > 1){ taskIdSet = taskIdSet.split("\u0005") // Remove NetSuite Random Space Thingo. } taskIdSet.forEach(function(taskId){ var taskRec = record.load({ type: 'task', id: taskId}); taskRec.setValue({ fieldId: 'status', value: "COMPLETE" }) // Set to Completed; taskRec.save(); }); return true; } function createSentList(inv_id, doc_num, entityid, companyname, inv_type, tot_am, days_open, zee_name) { var sentListRec = record.create({ type: 'customrecord_mass_inv_email_list', isDynamic: true, }); sentListRec.setValue({ fieldId: 'name' , value: inv_id }); sentListRec.setValue({ fieldId: 'custrecord_mass_inv_email_zee_name' , value: zee_name}); // sentListRec.setValue({ fieldId: 'custrecord_mass_inv_email_doc_num' , value: doc_num}); sentListRec.setValue({ fieldId: 'custrecord_mass_inv_email_entityid' , value: entityid}); sentListRec.setValue({ fieldId: 'custrecord_mass_inv_email_companyname' , value: companyname}); sentListRec.setValue({ fieldId: 'custrecord_mass_inv_email_inv_type' , value: inv_type}); sentListRec.setValue({ fieldId: 'custrecord_mass_inv_email_tot_am' , value: tot_am}); sentListRec.setValue({ fieldId: 'custrecord_mass_inv_email_days_open' , value: days_open}); sentListRec.save(); return true; } function deleteSentList(main_index){ // Populate List of Invoices Already Sent log.debug({ title: 'Deleting Records', details: main_index }); var invRecEmailList = search.load({ id: 'customsearch_mass_inv_email_list_2', type: 'customrecord_mass_inv_email_list' }); invRecEmailList.run().each(function(res){ sent_invoices.push(res.getValue({ name: 'name' })); // populate list of invoices if (main_index == 0){ record.delete({ type: 'customrecord_mass_inv_email_list', id: res.getValue({ name: 'internalid' }) }); } return true; }); } function emailTemplate(){ //companyname, email_address var emailMerger = render.mergeEmail({ templateId: 177, //. Mass Invoice Email Template - 363 | Invoice Email - 177 entity: null, recipient: null, supportCaseId: null, transactionId: null, customRecord: null }); var html_body = emailMerger.body; return html_body; } function formatCCEmail(email_address) { // var email_address = email_address.replace(/ /g, ''); var cc_address = email_address.replace(/\s/g, ''); // Remove Spaces. cc_address = cc_address.toLowerCase(); // Lowercases everything cc_address = cc_address.split(','); // Split Comma to Array. return cc_address; } /** * Used to pass the values of `date_from` and `date_to` between the scripts and to Netsuite for the records and the search. * @param {String} date_iso "2020-06-01" * @returns {String} date_netsuite "1/6/2020" */ function dateISOToNetsuite(date_iso) { var date_netsuite = ''; if (!isNullorEmpty(date_iso)) { var date_utc = new Date(date_iso); // var date_netsuite = nlapiDateToString(date_utc); var date_netsuite = format.format({ value: date_utc, type: format.Type.DATE }); } return date_netsuite; } function isNullorEmpty(strVal) { return (strVal == null || strVal == '' || strVal == 'null' || strVal == undefined || strVal == 'undefined' || strVal == '- None -'); } return { execute: main } });
true
/** * @NApiVersion 2.x * @NScriptType ScheduledScript * * Module Description: Mass Invoice Email * * @Last Modified by: Anesu Chakaingesu * */ define(['N/ui/serverWidget', 'N/email', 'N/runtime', 'N/search', 'N/record', 'N/http', 'N/log', 'N/redirect', 'N/task', 'N/format', 'N/currentRecord', 'N/render'], function(ui, email, runtime, search, record, http, log, redirect, task, format, currentRecord, render) { var baseURL = 'https://1048144.app.netsuite.com'; if (runtime.envType == "SANDBOX") { baseURL = 'https://1048144-sb3.app.netsuite.com'; } var role = runtime.getCurrentUser().role; var zee = 0; var currRec = currentRecord.get(); var ctx = runtime.getCurrentScript(); // Date Today n Date Tomorrow var today_date = new Date(); // Test Time 6:00pm - '2022-06-29T18:20:00.000+10:00' today_date.toLocaleString('en-AU', { timeZone: 'Australia/Sydney' }); today_date = dateISOToNetsuite(today_date); today_date = format.parse({ value: today_date, type: format.Type.DATE }); // Reformat Date var sent_invoices = []; // var sent_invoices = ["4131738"] function main() { /** * Work Flow: * // Send Email // Add New Line in Record // Once Completed List, Delete All Records. */ // Get Results var taskIdSet = JSON.parse(JSON.stringify(ctx.getParameter({ name: 'custscript_ss_mass_inv_email_task_set'}))); var totalInvCount = parseInt(ctx.getParameter({ name: 'custscript_ss_mass_inv_email_tot_num_inv'})); var selectedZeeSet = new Array(); selectedZeeSet = JSON.parse(JSON.stringify(ctx.getParameter({ name: 'custscript_ss_mass_inv_email_zee_set'}))); var user_email = ctx.getParameter({ name: 'custscript_ss_mass_inv_email_user_email'}); var main_index = parseInt(ctx.getParameter({ name: 'custscript_ss_mass_inv_email_main_index'})) if (isNullorEmpty(main_index) || isNaN(main_index)){ main_index = 0; } var invoiceSet = JSON.parse(JSON.stringify({ name: 'custscript_ss_mass_inv_email_inv_set'})); if (invoiceSet.length > 1){ invoiceSet = invoiceSet.split("\u0005") // Remove NetSuite Random Space Thingo. } else { invoiceSet = []; } // Testing // var selectedZeeSet = [779884] // TEST // var taskIdSet = 272834; // TEST - NSW // var totalInvCount = 2; // 2 Invoices // Log Values: TESTs log.debug({ title: 'Executed Order 66: ZEE Ready', details: selectedZeeSet }); log.debug({ title: 'Executed Order 66: TASK Ready', details: taskIdSet }); log.debug({ title: 'Main Index: Ready', details: main_index }); log.debug({ title: 'Invoice Set: Ready', details: invoiceSet }); if (!isNullorEmpty(selectedZeeSet)){ // Verify Zee Set Exists. // Delete List Record All. deleteSentList(main_index); // Only Delete List on First Run. log.debug({ title: 'INVOICES ALREADY SENT', details: sent_invoices }); log.debug({ title: 'Type Of', details: typeof selectedZeeSet }); if (main_index == 0){ if (selectedZeeSet.length > 1){ log.debug({ title: 'Selected Zee: Split Array', details: selectedZeeSet }); selectedZeeSet = selectedZeeSet.split("\u0005") // Remove NetSuite Random Space Thingo. } } else { log.debug({ title: 'Selected Zee: Rescheduled Index, Array?', details: selectedZeeSet }); selectedZeeSet = JSON.parse(selectedZeeSet) } if (selectedZeeSet.length > 0){ // Ensures that Only when the Selected Zee List is populated, it will filter. // Load Search var invSearch = search.load({ type: 'invoice', id: 'customsearch_mass_inv_email_list' }); invSearch.filters.push(search.createFilter({ name: 'partner', operator: search.Operator.ANYOF, values: selectedZeeSet })); invSearch.filters.push(search.createFilter({ name: 'email', operator: search.Operator.ISNOTEMPTY, values: null })); if (sent_invoices != null && sent_invoices.length > 0){ invSearch.filters.push(search.createFilter({ name: 'internalid', operator: search.Operator.NONEOF, values: sent_invoices })); } var invSearchRes = invSearch.run(); // Search Result // if (main_index == 0) { // Update Total Invoice Count on First Run. // totalInvCount = invSearch.runPaged().count; var invResLength = invSearch.runPaged().count; // } // log.debug({ // title: 'Search Length', // details: totalInvCount // }); var invResultSet = []; // Sudo Array Containing Complete Search Data for (var data_index = 0; data_index < invResLength; data_index += 1000) { invResultSet.push(invSearchRes.getRange({ start: data_index, end: data_index + 999 })); } log.debug({ title: 'Search Result Set', details: invResultSet }); // Loop Through Search Results and Log var result_count = 0; for (var i = 0; i < invResultSet.length; i++) { var invResult = invResultSet[i]; log.debug({ title: 'Search Result Set: ' + i, details: invResult.length }); result_count = result_count + invResult.length; } log.debug({ title: 'Total Search Result', details: result_count }); // TEST DATA /** * For Loop * Index = 0; * var data_index = 650; * data_index < 1500; * data_index += 1000; * * zendeskSearchRes.getRange({ start: 650, end: 650 + 999 == 1649}) }); * THIS WILL NOT RUN AS ITS OVER 1500 zendeskSearchRes.getRange({ start: 1650, end: 1350 + 999 = 2349 }) }); * THIS DOES NO RUN AS ITS ENDING AT 1500. zendeskSearchRes.getRange({ start: 2000, end: 2000 + 999 = 2999 }); * */ var index = 0; for (var inv_data_index = 0; inv_data_index < invResultSet.length; inv_data_index++){ invResultSet[inv_data_index].every(function(invData){ //, index, arr var usageLimit = ctx.getRemainingUsage(); log.debug({ title: 'usageLimit', details: usageLimit }); // If SS Breaker has been scheduled, stop the script. // try { // var ss_breaker = task.create({ // taskType: task.TaskType.SCHEDULED_SCRIPT, // scriptId: 'customscript_ss_breaker', // deploymentId: 'customdeploy_ss_breaker_pending', // }); // var ss_breaker_task_id = ss_breaker.submit(); // var scriptStatus = task.checkStatus({ // taskId: ss_breaker_task_id // }); // log.debug({ // title: 'Script Status', // details: scriptStatus.status // }); // } catch (error) { // log.debug({ // title: 'Error: SS Break Status', // details: error // }); // } // if (scriptStatus.status == 'PENDING') { return false } else if (usageLimit < 200) { // TESTING PURPOSES: || index == 150 params = { custscript_ss_mass_inv_email_task_set: taskIdSet, custscript_ss_mass_inv_email_zee_set: selectedZeeSet, custscript_ss_mass_inv_email_main_index: main_index + index, custscript_ss_mass_inv_email_tot_num_inv: totalInvCount, custscript_ss_mass_inv_email_user_email: user_email, custscript_ss_mass_inv_email_inv_set: invoiceSet, }; var reschedule = task.create({ taskType: task.TaskType.SCHEDULED_SCRIPT, scriptId: 'customscript_ss_mass_inv_email', deploymentId: 'customdeploy_ss_mass_inv_email', params: params }); var reschedule_id = reschedule.submit(); log.error({ title: 'Attempting: Rescheduling Script', details: JSON.stringify(reschedule_id) }); return false; } else { log.debug({ title: 'Indexes: Main + Index', details: main_index + " | " + index }); // Customer Details var internalid = invData.getValue({ name: "internalid", join: 'customer' }); var entityid = invData.getValue({ name: "entityid", join: 'customer' }); var companyname = invData.getValue({ name: 'companyname', join: 'customer' }); var email_address = invData.getValue({ name: 'email', join: 'customer' }); var cc_email = invData.getValue({ name: 'custentity_accounts_cc_email', join: 'customer' }); cc_email = formatCCEmail(cc_email) var cc_address = []; if (cc_email.length > 1){ // More than one Email in Array. cc_email.forEach(function(el){ if (el.length > 4){ // Make Sure Elements (Email) length is not Blank and includes minimum 4 Characters (.com) cc_address.push(el); } }); } else { cc_address.push(cc_email); // If Only One, Push Email into Saved CC Array. } // Invoice Details var inv_id = invData.getValue({ name: 'internalid' }); var inv_type = invData.getText({ name: 'custbody_inv_type' }); var tot_am = '$' + invData.getValue({ name: 'amount' }); if (isNullorEmpty(inv_type)) { inv_type = 'Service'; } var doc_num = invData.getValue({ name: 'tranid' }); var days_open = invData.getValue({ name: 'daysopen' }); var zee_name = invData.getText({ name: 'partner' }); try { // Create Object createSentList(inv_id, doc_num, entityid, companyname, inv_type, tot_am, days_open, zee_name); // Save Invoices - Secondly var attachments = []; var invFile = getInvoiceFiles(inv_id); attachments.push(invFile); //Send Email sendEmail(internalid, companyname, email_address, attachments, doc_num, user_email, cc_address); // Set Invoice to Emailed and Date | After Emailed. setInvoiceData(inv_id); } catch (e) { log.error({ title: 'Send Email Error', details: e }); email.send({ author: 35031, // Accounts: 35031 | Customer Service: 112209 body: 'Error for Customer ID '+ internalid +' | Company Name ' + companyname + ' | with Invoice ID '+ inv_id + '\n\n' + e, // Get Email Template subject: 'Mass Invoice Email: Error', recipients: ['PI:EMAIL:anpch@example.comEND_PI'], // , 'PI:EMAIL:nnheo@example.comEND_PI' attachments: new Array(getInvoiceFiles(inv_id)), }); } index++; return true; } }) } } } setTaskCompleted(taskIdSet); // Set Task As Completed log.debug({ title: 'END SCRIPT' }) } function sendEmail(custSet, companyname, email_address, attachments, invoice_number, user_email, cc_address){ // log.debug({ // title: 'Email Address', // details: email_address // }) var email_template = emailTemplate(); if (!isNullorEmpty(cc_address)){ // CC Field Does email.send({ author: 35031, // Accounts: 35031 | Customer Service: 112209 body: email_template, // Get Email Template subject: 'MailPlus Invoice: ' + invoice_number, recipients: [email_address], // 'PI:EMAIL:anpch@example.comEND_PI' | email_address cc: [cc_address], // 'PI:EMAIL:anpch@example.comEND_PI' | cc_address attachments: attachments, relatedRecords:{ entityId: custSet // Add Email Reminder Notification as Message Under Customer } }); } else { // CC Field Does Not Exist email.send({ author: 35031, // Accounts: 35031 | Customer Service: 112209 body: email_template, // Get Email Template subject: 'MailPlus Invoice: ' + invoice_number, recipients: [email_address], // 'PI:EMAIL:anpch@example.comEND_PI' | email_address attachments: attachments, relatedRecords:{ entityId: custSet // Add Email Reminder Notification as Message Under Customer } }); } log.debug({ title: 'Send Out Emails: Attachments and Data', details: custSet + ' ' + companyname + ' ' + email_address + ' ' + attachments }) } function getInvoiceFiles(entityId){ var transactionFile = render.transaction({ entityId: parseInt(entityId), printMode: render.PrintMode.PDF }); log.debug({ title: 'Invoice File', details: transactionFile }) return transactionFile; } function setInvoiceData(invoice_id){ var rec = record.load({ type: 'invoice', id: invoice_id }) rec.setValue({ fieldId: 'custbody_invoice_emailed_date', value: today_date }); rec.setValue({ fieldId: 'custbody_invoice_emailed', value: true }); // true | TEST = false rec.save(); return true; } function setTaskCompleted(taskIdSet){ // Set Task as Completed; if (taskIdSet.length > 1){ taskIdSet = taskIdSet.split("\u0005") // Remove NetSuite Random Space Thingo. } taskIdSet.forEach(function(taskId){ var taskRec = record.load({ type: 'task', id: taskId}); taskRec.setValue({ fieldId: 'status', value: "COMPLETE" }) // Set to Completed; taskRec.save(); }); return true; } function createSentList(inv_id, doc_num, entityid, companyname, inv_type, tot_am, days_open, zee_name) { var sentListRec = record.create({ type: 'customrecord_mass_inv_email_list', isDynamic: true, }); sentListRec.setValue({ fieldId: 'name' , value: inv_id }); sentListRec.setValue({ fieldId: 'custrecord_mass_inv_email_zee_name' , value: zee_name}); // sentListRec.setValue({ fieldId: 'custrecord_mass_inv_email_doc_num' , value: doc_num}); sentListRec.setValue({ fieldId: 'custrecord_mass_inv_email_entityid' , value: entityid}); sentListRec.setValue({ fieldId: 'custrecord_mass_inv_email_companyname' , value: companyname}); sentListRec.setValue({ fieldId: 'custrecord_mass_inv_email_inv_type' , value: inv_type}); sentListRec.setValue({ fieldId: 'custrecord_mass_inv_email_tot_am' , value: tot_am}); sentListRec.setValue({ fieldId: 'custrecord_mass_inv_email_days_open' , value: days_open}); sentListRec.save(); return true; } function deleteSentList(main_index){ // Populate List of Invoices Already Sent log.debug({ title: 'Deleting Records', details: main_index }); var invRecEmailList = search.load({ id: 'customsearch_mass_inv_email_list_2', type: 'customrecord_mass_inv_email_list' }); invRecEmailList.run().each(function(res){ sent_invoices.push(res.getValue({ name: 'name' })); // populate list of invoices if (main_index == 0){ record.delete({ type: 'customrecord_mass_inv_email_list', id: res.getValue({ name: 'internalid' }) }); } return true; }); } function emailTemplate(){ //companyname, email_address var emailMerger = render.mergeEmail({ templateId: 177, //. Mass Invoice Email Template - 363 | Invoice Email - 177 entity: null, recipient: null, supportCaseId: null, transactionId: null, customRecord: null }); var html_body = emailMerger.body; return html_body; } function formatCCEmail(email_address) { // var email_address = email_address.replace(/ /g, ''); var cc_address = email_address.replace(/\s/g, ''); // Remove Spaces. cc_address = cc_address.toLowerCase(); // Lowercases everything cc_address = cc_address.split(','); // Split Comma to Array. return cc_address; } /** * Used to pass the values of `date_from` and `date_to` between the scripts and to Netsuite for the records and the search. * @param {String} date_iso "2020-06-01" * @returns {String} date_netsuite "1/6/2020" */ function dateISOToNetsuite(date_iso) { var date_netsuite = ''; if (!isNullorEmpty(date_iso)) { var date_utc = new Date(date_iso); // var date_netsuite = nlapiDateToString(date_utc); var date_netsuite = format.format({ value: date_utc, type: format.Type.DATE }); } return date_netsuite; } function isNullorEmpty(strVal) { return (strVal == null || strVal == '' || strVal == 'null' || strVal == undefined || strVal == 'undefined' || strVal == '- None -'); } return { execute: main } });
/** *@NApiVersion 2.x *@NScriptType UserEventScript */ define(["N/search", "N/record", "N/email", "N/runtime", "N/https", "N/format"], function(search, record, email, runtime, https, format) { function credit_limit_request(context) { try { //Get Field Values var newRecord = context.newRecord; var EH_Final_Response = newRecord.getValue({ fieldId: 'custrecord_euler_hermes_response' }); // If request hasnt been submitted yet if (EH_Final_Response == '' || EH_Final_Response == null) { var company_id = newRecord.getValue({ fieldId: 'custrecord_company_id' }); var netsuite_customer_id = newRecord.getValue({ fieldId: 'custrecord_netsuite_customer', }); var request_id = newRecord.getValue({ fieldId: 'custrecord_credit_limit_request_link' }) var amount = newRecord.getValue({ fieldId: 'custrecord_amount_requested' }); var ApiKey = 'bGJlcWlyaUB0ZWxxdWVzdGludGwuY29tOjFfSDctPjB1Um5pQlZZRSc1NTVqZSZyZVxwb350Zw==' // Production //var ApiKey = 'bGJlcWlyaUB0ZWxxdWVzdGludGwuY29tOi5XIXE/UD9rZ1EnLmpbNio0WHo+VFF1blVYNVxSeA==' //Sandbox var Auth_Headers = {}; Auth_Headers['Content-Type'] = 'application/json'; var RequestJs = { "apiKey": ApiKey } // Authorize Connection var EH_Auth_Response = https.request({ method: https.Method.POST, url: 'https://api.eulerhermes.com/v1/idp/oauth2/authorize', //Production //url: "https://api-services.uat.1placedessaisons.com/uatm/v1/idp/oauth2/authorize", // Sandbox body: JSON.stringify(RequestJs), headers: Auth_Headers }); if (EH_Auth_Response.code == 200) { var AuthResult = JSON.parse(EH_Auth_Response.body); var AccessToken = AuthResult.access_token; } //Request Credit limit //Headers var search_Auth_Headers = {}; search_Auth_Headers['Content-Type'] = 'application/json'; search_Auth_Headers['Authorization'] = 'Bearer ' + AccessToken; search_Auth_Headers['Content-Length'] = '0'; search_Auth_Headers['Host'] = '<calculated when request is sent>'; search_Auth_Headers['User-Agent'] = 'PostmanRuntime/7.28.4'; search_Auth_Headers['Accept'] = '*/*'; search_Auth_Headers['Accept-Encoding'] = 'gzip, deflate, br'; search_Auth_Headers['Connection'] = 'keep-alive'; var newRequestBody = { "coverTypeCode": "CreditLimit", "requestOrigin": "ExternalPlatform", "requestData": { "amount": amount, "currencyCode": "USD", "companyId": company_id, "comment": "Auto Requested", "isRequestUrgent": "true" }, "policy": { "policyId": "5121840", "businessUnitCode": "ACI" } } var credit_limit_request = https.request({ method: https.Method.POST, url: 'https://api.eulerhermes.com/riskinfo/v2/covers', //Production //url: "https://api-services.uat.1placedessaisons.com/uatm/riskinfo/v2/covers", // Sandbox body: JSON.stringify(newRequestBody), headers: search_Auth_Headers }); var response_url = "https://api.eulerhermes.com/riskinfo/v2/covers?policyId=5121840&businessUnitCode=ACI&companyId=" + company_id; //Production // var response_url = "https://api-services.uat.1placedessaisons.com/uatm/riskinfo/v2/covers?policyId=5121840&businessUnitCode=ACI&companyId="+company_id; //Sandbox var euler_hermes_response = https.request({ method: https.Method.GET, url: response_url, //body: JSON.stringify(newRequestBody), headers: search_Auth_Headers }); var response_body = JSON.parse(euler_hermes_response.body) if (response_body != 'undefined') var code = response_body[0].coverStatusCode log.debug({ title: 'coverStatus Code', details: code }) newRecord.setValue({ fieldId: 'custrecord_euler_hermes_response', value: response_body[0].coverStatusCode }); //Add Euler Hermes id to customer record var cust_rec = record.load({ type: record.Type.CUSTOMER, id: netsuite_customer_id, isDynamic: true, }); cust_rec.setValue({ fieldId: 'custentity_eh_id', value: company_id }); cust_rec.setValue({ fieldId: 'custentity_eh_request_amount', value: amount }); if (response_body[0].coverStatusCode == "Agreement") { cust_rec.setValue({ fieldId: 'custentity_eh_request_status', value: 2 }); } else { cust_rec.setValue({ fieldId: 'custentity_eh_request_status', value: 1 }); } cust_rec.save({ enableSourcing: true, ignoreMandatoryFields: true }); } } catch (e) { log.debug({ title: 'Error', details: e }) } } return { beforeSubmit: credit_limit_request, }; });
1,188
[{"tag": "KEY", "value": "bGJlcWlyaUB0ZWxxdWVzdGludGwuY29tOi5XIXE/UD9rZ1EnLmpbNio0WHo+VFF1blVYNVxSeA==", "start": 1426, "end": 1502}, {"tag": "KEY", "value": "bGJlcWlyaUB0ZWxxdWVzdGludGwuY29tOjFfSDctPjB1Um5pQlZZRSc1NTVqZSZyZVxwb350Zw==", "start": 1297, "end": 1373}]
true
2
/** *@NApiVersion 2.x *@NScriptType UserEventScript */ define(["N/search", "N/record", "N/email", "N/runtime", "N/https", "N/format"], function(search, record, email, runtime, https, format) { function credit_limit_request(context) { try { //Get Field Values var newRecord = context.newRecord; var EH_Final_Response = newRecord.getValue({ fieldId: 'custrecord_euler_hermes_response' }); // If request hasnt been submitted yet if (EH_Final_Response == '' || EH_Final_Response == null) { var company_id = newRecord.getValue({ fieldId: 'custrecord_company_id' }); var netsuite_customer_id = newRecord.getValue({ fieldId: 'custrecord_netsuite_customer', }); var request_id = newRecord.getValue({ fieldId: 'custrecord_credit_limit_request_link' }) var amount = newRecord.getValue({ fieldId: 'custrecord_amount_requested' }); var ApiKey = 'vqbpgud2ghvjgm1n5hdgjnn5818fzsf2' // Production //var ApiKey = 'vqbpgud2ghvjgm1n5hdgjnn5818fzsf2' //Sandbox var Auth_Headers = {}; Auth_Headers['Content-Type'] = 'application/json'; var RequestJs = { "apiKey": ApiKey } // Authorize Connection var EH_Auth_Response = https.request({ method: https.Method.POST, url: 'https://api.eulerhermes.com/v1/idp/oauth2/authorize', //Production //url: "https://api-services.uat.1placedessaisons.com/uatm/v1/idp/oauth2/authorize", // Sandbox body: JSON.stringify(RequestJs), headers: Auth_Headers }); if (EH_Auth_Response.code == 200) { var AuthResult = JSON.parse(EH_Auth_Response.body); var AccessToken = AuthResult.access_token; } //Request Credit limit //Headers var search_Auth_Headers = {}; search_Auth_Headers['Content-Type'] = 'application/json'; search_Auth_Headers['Authorization'] = 'Bearer ' + AccessToken; search_Auth_Headers['Content-Length'] = '0'; search_Auth_Headers['Host'] = '<calculated when request is sent>'; search_Auth_Headers['User-Agent'] = 'PostmanRuntime/7.28.4'; search_Auth_Headers['Accept'] = '*/*'; search_Auth_Headers['Accept-Encoding'] = 'gzip, deflate, br'; search_Auth_Headers['Connection'] = 'keep-alive'; var newRequestBody = { "coverTypeCode": "CreditLimit", "requestOrigin": "ExternalPlatform", "requestData": { "amount": amount, "currencyCode": "USD", "companyId": company_id, "comment": "Auto Requested", "isRequestUrgent": "true" }, "policy": { "policyId": "5121840", "businessUnitCode": "ACI" } } var credit_limit_request = https.request({ method: https.Method.POST, url: 'https://api.eulerhermes.com/riskinfo/v2/covers', //Production //url: "https://api-services.uat.1placedessaisons.com/uatm/riskinfo/v2/covers", // Sandbox body: JSON.stringify(newRequestBody), headers: search_Auth_Headers }); var response_url = "https://api.eulerhermes.com/riskinfo/v2/covers?policyId=5121840&businessUnitCode=ACI&companyId=" + company_id; //Production // var response_url = "https://api-services.uat.1placedessaisons.com/uatm/riskinfo/v2/covers?policyId=5121840&businessUnitCode=ACI&companyId="+company_id; //Sandbox var euler_hermes_response = https.request({ method: https.Method.GET, url: response_url, //body: JSON.stringify(newRequestBody), headers: search_Auth_Headers }); var response_body = JSON.parse(euler_hermes_response.body) if (response_body != 'undefined') var code = response_body[0].coverStatusCode log.debug({ title: 'coverStatus Code', details: code }) newRecord.setValue({ fieldId: 'custrecord_euler_hermes_response', value: response_body[0].coverStatusCode }); //Add Euler Hermes id to customer record var cust_rec = record.load({ type: record.Type.CUSTOMER, id: netsuite_customer_id, isDynamic: true, }); cust_rec.setValue({ fieldId: 'custentity_eh_id', value: company_id }); cust_rec.setValue({ fieldId: 'custentity_eh_request_amount', value: amount }); if (response_body[0].coverStatusCode == "Agreement") { cust_rec.setValue({ fieldId: 'custentity_eh_request_status', value: 2 }); } else { cust_rec.setValue({ fieldId: 'custentity_eh_request_status', value: 1 }); } cust_rec.save({ enableSourcing: true, ignoreMandatoryFields: true }); } } catch (e) { log.debug({ title: 'Error', details: e }) } } return { beforeSubmit: credit_limit_request, }; });
true
/** *@NApiVersion 2.x *@NScriptType UserEventScript */ define(["N/search", "N/record", "N/email", "N/runtime", "N/https", "N/format"], function(search, record, email, runtime, https, format) { function credit_limit_request(context) { try { //Get Field Values var newRecord = context.newRecord; var EH_Final_Response = newRecord.getValue({ fieldId: 'custrecord_euler_hermes_response' }); // If request hasnt been submitted yet if (EH_Final_Response == '' || EH_Final_Response == null) { var company_id = newRecord.getValue({ fieldId: 'custrecord_company_id' }); var netsuite_customer_id = newRecord.getValue({ fieldId: 'custrecord_netsuite_customer', }); var request_id = newRecord.getValue({ fieldId: 'custrecord_credit_limit_request_link' }) var amount = newRecord.getValue({ fieldId: 'custrecord_amount_requested' }); var ApiKey = 'PI:KEY:vqbpgud2ghvjgm1n5hdgjnn5818fzsf2END_PI' // Production //var ApiKey = 'PI:KEY:vqbpgud2ghvjgm1n5hdgjnn5818fzsf2END_PI' //Sandbox var Auth_Headers = {}; Auth_Headers['Content-Type'] = 'application/json'; var RequestJs = { "apiKey": ApiKey } // Authorize Connection var EH_Auth_Response = https.request({ method: https.Method.POST, url: 'https://api.eulerhermes.com/v1/idp/oauth2/authorize', //Production //url: "https://api-services.uat.1placedessaisons.com/uatm/v1/idp/oauth2/authorize", // Sandbox body: JSON.stringify(RequestJs), headers: Auth_Headers }); if (EH_Auth_Response.code == 200) { var AuthResult = JSON.parse(EH_Auth_Response.body); var AccessToken = AuthResult.access_token; } //Request Credit limit //Headers var search_Auth_Headers = {}; search_Auth_Headers['Content-Type'] = 'application/json'; search_Auth_Headers['Authorization'] = 'Bearer ' + AccessToken; search_Auth_Headers['Content-Length'] = '0'; search_Auth_Headers['Host'] = '<calculated when request is sent>'; search_Auth_Headers['User-Agent'] = 'PostmanRuntime/7.28.4'; search_Auth_Headers['Accept'] = '*/*'; search_Auth_Headers['Accept-Encoding'] = 'gzip, deflate, br'; search_Auth_Headers['Connection'] = 'keep-alive'; var newRequestBody = { "coverTypeCode": "CreditLimit", "requestOrigin": "ExternalPlatform", "requestData": { "amount": amount, "currencyCode": "USD", "companyId": company_id, "comment": "Auto Requested", "isRequestUrgent": "true" }, "policy": { "policyId": "5121840", "businessUnitCode": "ACI" } } var credit_limit_request = https.request({ method: https.Method.POST, url: 'https://api.eulerhermes.com/riskinfo/v2/covers', //Production //url: "https://api-services.uat.1placedessaisons.com/uatm/riskinfo/v2/covers", // Sandbox body: JSON.stringify(newRequestBody), headers: search_Auth_Headers }); var response_url = "https://api.eulerhermes.com/riskinfo/v2/covers?policyId=5121840&businessUnitCode=ACI&companyId=" + company_id; //Production // var response_url = "https://api-services.uat.1placedessaisons.com/uatm/riskinfo/v2/covers?policyId=5121840&businessUnitCode=ACI&companyId="+company_id; //Sandbox var euler_hermes_response = https.request({ method: https.Method.GET, url: response_url, //body: JSON.stringify(newRequestBody), headers: search_Auth_Headers }); var response_body = JSON.parse(euler_hermes_response.body) if (response_body != 'undefined') var code = response_body[0].coverStatusCode log.debug({ title: 'coverStatus Code', details: code }) newRecord.setValue({ fieldId: 'custrecord_euler_hermes_response', value: response_body[0].coverStatusCode }); //Add Euler Hermes id to customer record var cust_rec = record.load({ type: record.Type.CUSTOMER, id: netsuite_customer_id, isDynamic: true, }); cust_rec.setValue({ fieldId: 'custentity_eh_id', value: company_id }); cust_rec.setValue({ fieldId: 'custentity_eh_request_amount', value: amount }); if (response_body[0].coverStatusCode == "Agreement") { cust_rec.setValue({ fieldId: 'custentity_eh_request_status', value: 2 }); } else { cust_rec.setValue({ fieldId: 'custentity_eh_request_status', value: 1 }); } cust_rec.save({ enableSourcing: true, ignoreMandatoryFields: true }); } } catch (e) { log.debug({ title: 'Error', details: e }) } } return { beforeSubmit: credit_limit_request, }; });
/** * @NApiVersion 2.x * @NScriptType ScheduledScript * * Module Description: Schedule Script to Set the Date Invoiced Finalised Field * * @Last Modified by: Sruti Desai * */ define(['N/runtime', 'N/search', 'N/record', 'N/log', 'N/task', 'N/currentRecord', 'N/format'], function(runtime, search, record, log, task, currentRecord, format) { var zee = 0; var role = runtime.getCurrentUser().role; var ctx = runtime.getCurrentScript(); var usageThreshold = 500; var adhocInvDeploy = 'customdeploy2'; var prevInvDeploy = ctx.deploymentId; var baseURL = 'https://1048144.app.netsuite.com'; if (runtime.EnvType == "SANDBOX") { baseURL = 'https://system.sandbox.netsuite.com'; } /** * [updateDateInvFin description] - Function to the set the Date Invoiced Finalised field in the job record. * @param {string} custscript_partner Partner ID * @param {string} custscript_startdate Start Date * @param {string} custscript_enddate End Date */ function main() { log.debug({ title: 'START -->', details: ctx.getRemainingUsage() }); var partner = parseInt(ctx.getParameter({ name: 'custscript_partner'})); var startDate = ctx.getParameter({ name: 'custscript_startdate' }); var endDate = ctx.getParameter({ name: 'custscript_enddate' }); log.debug({ title: 'partner', details: partner }); log.debug({ title: 'startDate', details: startDate }); log.debug({ title: 'endDate', details: endDate }); if (!isNullorEmpty(ctx.getParameter({ name: 'custscript_prev_deploy' }) )) { log.emergency({ title: 'Received Parameters | ', details: 'Zee ID: ' + partner }); log.emergency({ title: 'Received Parameters | ', details: 'Start Date: ' + startDate }); log.emergency({ title: 'Received Parameters | ', details: 'End Date: ' + endDate }); prevInvDeploy = ctx.getParameter({ name: 'custscript_prev_deploy' }); } else { prevInvDeploy = ctx.getDeploymentId; log.emergency({ title: 'Initial Parameters | ', details: 'Zee ID: ' + partner }); log.emergency({ title: 'Initial Parameters | ', details: 'Start Date: ' + startDate }); log.emergency({ title: 'Initial Parameters | ', details: 'End Date: ' + endDate }); } var searchedAlljobs = search.load({ id: 'customsearch_inv_review_jobs_uninv', type: 'customrecord_job' }) var zee_record = record.load({ type: record.Type.PARTNER, id: partner, }); var zee_text = zee_record.getValue({ fieldId: 'entitytitle' }); var strFormula = "COALESCE({custrecord_job_service.custrecord_service_franchisee},{custrecord_job_group.custrecord_jobgroup_franchisee},{custrecord_job_franchisee},'')"; searchedAlljobs.filters.push(search.createFilter({ name: 'custrecord_job_date_inv_finalised', operator: search.Operator.ISEMPTY })); searchedAlljobs.filters.push(search.createFilter({ name: 'custrecord_job_date_reviewed', operator: search.Operator.ISNOTEMPTY })); if (!isNullorEmpty(startDate) && !isNullorEmpty(endDate)) { searchedAlljobs.filters.push(search.createFilter({ name: 'custrecord_job_date_scheduled', operator: search.Operator.ONORAFTER, values: format.parse({ value: startDate, type: format.Type.DATE })})); searchedAlljobs.filters.push(search.createFilter({ name: 'custrecord_job_date_scheduled', operator: search.Operator.ONORBEFORE, values: format.parse({ value: endDate, type: format.Type.DATE })})); } var resultSetAlljobs = searchedAlljobs.run(); var count = 0; resultSetAlljobs.each(function(searchResultAlljobs) { count++; usageStart = ctx.getRemainingUsage(); if (usageStart <= usageThreshold) { log.debug({ title: 'SWITCHing -->', details: ctx }.getRemainingUsage()); var params = { custscript_partner: partner, custscript_prev_deploy: ctx.deploymentId, custscript_startdate: startDate, custscript_enddate: endDate } log.emergency({ title: 'Parameters Passed | ', details: 'Zee ID: ' + partner }); log.emergency({ title: 'Parameters Passed | ', details: 'Start Date: ' + startDate }); log.emergency({ title: 'Parameters Passed | ', details: 'End Date: ' + endDate }); var reschedule = task.create({ taskType: task.TaskType.SCHEDULED_SCRIPT, deploymentId: adhocInvDeploy, params: params, scriptId: prevInvDeploy, }) reschedule.submit(); if (reschedule == false) { return false; } } var jobID = searchResultAlljobs.getValue('internalid'); var jobService = searchResultAlljobs.getText("custrecord_job_service"); var jobCustomer = searchResultAlljobs.getText("custrecord_job_customer"); var specialCustomerType = searchResultAlljobs.getValue({ name: "custentity_special_customer_type", join: "CUSTRECORD_JOB_CUSTOMER", summary: null }); var linkedMPCustomer = searchResultAlljobs.getValue({ name: "custentity_np_mp_customer", join: "CUSTRECORD_JOB_CUSTOMER", summary: null }); var linkedSpecialCustomer = searchResultAlljobs.getValue({ name: "custentity_np_np_customer", join: "CUSTRECORD_JOB_CUSTOMER", summary: null }); var jobPackageType = searchResultAlljobs.getValue({ name: "custrecord_service_package_type", join: "CUSTRECORD_JOB_SERVICE_PACKAGE", summary: null }); try { var jobRecord = record.load({ type: 'customrecord_job', id: jobID }); //Below section is for Special Customers, so the job is transferred to that Special Customer and the Field SPECIAL CUSTOMER in the Job record is filled to the Special Customer. //Below condition is to check if the customer to which the job is assigned to has both the LINKED MP CUSTOMER & SPECIAL CUSTOMER TYPE not null, then an error email is sent out. if (!isNullorEmpty(linkedMPCustomer) || !isNullorEmpty(specialCustomerType)) { var body = 'Customer: ' + jobCustomer + ', has Linked MP Customer Field and Special Customer Type field set to ' + linkedMPCustomer + ' & ' + specialCustomerType + ' respectively.'; email.send({ author: 409635, body: body, recipients: ['ankith.ravindran@mailplus.com.au', 'Willian.Suryadharma@mailplus.com.au'], subject: 'AIC: Date Invoice Finalised SC - Linked MP Customer & Customer Type both not null', }); } else if (!isNullorEmpty(linkedSpecialCustomer) && isNullorEmpty(specialCustomerType)) { //To check if the customer to which the job is assigned has the LINKED SPECIAL CUSTOMER filled & SPECIAL CUSTOMER TYPE not equal to null, then we go to the Linked Special customer record and get the Special Customer type. var specialCustomerRecord = record.load({ type: 'customer', id: linkedSpecialCustomer }); var specialCustomerSpecialCustomerType = specialCustomerRecord.getValue({ fieldId: 'custentity_special_customer_type' }); var specialCustomerTypeRecord = record.load({ type: 'customrecord_special_customer_type', id: specialCustomerSpecialCustomerType }); //Get the allowed services from the Special Customer Type record. var allowedServicesIDs = specialCustomerTypeRecord.getValue({ fieldId: 'custrecord_special_allowed_service' }); var allowedServicesTexts = specialCustomerTypeRecord.getText({ fieldId: 'custrecord_special_allowed_service' }); var result = null; //If the Special Customer Type is of type AusPost or Secure Cash if (specialCustomerSpecialCustomerType == 2 || specialCustomerSpecialCustomerType == 3) { //If the Allowed Services field is not null if (!isNullorEmpty(allowedServicesTexts) && !isNullorEmpty(allowedServicesIDs)) { // Check if the service performed by the job exists in the Allowed Services result = allowedServicesTexts.indexOf(jobService); // If exists if (result >= 0) { //Fill the Special Customer with the Linked Special Customer jobRecord.setValue({ fieldId: 'custrecord_job_special_customer', value: linkedSpecialCustomer }); } } else { } } else { //If Special Customer Type is of Type NeoPost. //Get the Allowed Package from the Special Type record var allowedPackage = specialCustomerTypeRecord.getValue({ fieldId: 'custrecord_special_allowed_package' }); //If allowed Package is equal to NeopPost if (allowedPackage == jobPackageType) { //Fill the Special Customer with the Linked Special Customer jobRecord.setValue({ fieldId: 'custrecord_job_special_customer', value: linkedSpecialCustomer }); } } } var jobGroupStatus = jobRecord.getValue({ fieldId: 'custrecord_job_group_status' }); var jobInvoiceable = jobRecord.getValue({ fieldId: 'custrecord_job_invoiceable' }); var jobCat = jobRecord.getValue({ fieldId: 'custrecord_job_service_category' }); var packageStatus = jobRecord.getValue({ fieldId: 'custrecord_package_status' }); var jobGroupSource = jobRecord.getValue({ fieldId: 'custrecord_job_source' }); if (isNullorEmpty(jobInvoiceable)) { if (!isNullorEmpty(packageStatus)) { if (packageStatus == 1 || isNullorEmpty(packageStatus)) { // Job Group Status is Null for Extras and Jobs Created in NS jobRecord.setValue({ fieldId: 'custrecord_job_invoiceable', value: 1 }); } else { jobRecord.setValue({ fieldId: 'custrecord_job_invoiceable', value: 2 }); } } else { if (jobGroupStatus == 'Completed' || (isNullorEmpty(jobGroupStatus) && jobGroupSource == 5) || jobCat != '1') { // Job Group Status is Null for Extras and Jobs Created in NS jobRecord.setValue({ fieldId: 'custrecord_job_invoiceable', value: 1 }); } else { jobRecord.setValue({ fieldId: 'custrecord_job_invoiceable', value: 2 }); } } } jobRecord.setValue({ fieldId: 'custrecord_job_date_inv_finalised', value: getDate() }); jobRecord.save({ enableSourcing: true, ignoreMandatoryFields: true }); usagePerLoop = ctx.getRemainingUsage() - usageStart log.debug({ title: 'Loop #:' + count + ' | job id: ' + jobID + ' | Usg: ' + usagePerLoop }); return true; } catch (e) { var message = ''; message += "Job: <a href ='https://1048144.app.netsuite.com/app/common/custom/custrecordentry.nl?rectype=941&id=" + jobID + "'> View Job</a></br>"; message += "----------------------------------------------------------------------------------</br>"; message += e; email.send({ author: 409635, body: message, recipients: ['ankith.ravindran@mailplus.com.au', 'willian.suryadharma@mailplus.com.au'], subject: 'AIC - Review - Date Inv Finalised (SC) - Unable to update Job', }); } return true; }); log.debug({ title: 'END -->', details: ctx.getRemainingUsage() }); } function isNullorEmpty(strVal) { return (strVal == null || strVal == '' || strVal == 'null' || strVal == undefined || strVal == 'undefined' || strVal == '- None -'); } return { execute: main } } );
727
[{"tag": "EMAIL", "value": "ankith.ravindran@mailplus.com.au", "start": 7450, "end": 7482}, {"tag": "EMAIL", "value": "Willian.Suryadharma@mailplus.com.au", "start": 7486, "end": 7521}, {"tag": "EMAIL", "value": "ankith.ravindran@mailplus.com.au", "start": 13580, "end": 13612}, {"tag": "EMAIL", "value": "willian.suryadharma@mailplus.com.au", "start": 13616, "end": 13651}]
true
4
/** * @NApiVersion 2.x * @NScriptType ScheduledScript * * Module Description: Schedule Script to Set the Date Invoiced Finalised Field * * @Last Modified by: Sruti Desai * */ define(['N/runtime', 'N/search', 'N/record', 'N/log', 'N/task', 'N/currentRecord', 'N/format'], function(runtime, search, record, log, task, currentRecord, format) { var zee = 0; var role = runtime.getCurrentUser().role; var ctx = runtime.getCurrentScript(); var usageThreshold = 500; var adhocInvDeploy = 'customdeploy2'; var prevInvDeploy = ctx.deploymentId; var baseURL = 'https://1048144.app.netsuite.com'; if (runtime.EnvType == "SANDBOX") { baseURL = 'https://system.sandbox.netsuite.com'; } /** * [updateDateInvFin description] - Function to the set the Date Invoiced Finalised field in the job record. * @param {string} custscript_partner Partner ID * @param {string} custscript_startdate Start Date * @param {string} custscript_enddate End Date */ function main() { log.debug({ title: 'START -->', details: ctx.getRemainingUsage() }); var partner = parseInt(ctx.getParameter({ name: 'custscript_partner'})); var startDate = ctx.getParameter({ name: 'custscript_startdate' }); var endDate = ctx.getParameter({ name: 'custscript_enddate' }); log.debug({ title: 'partner', details: partner }); log.debug({ title: 'startDate', details: startDate }); log.debug({ title: 'endDate', details: endDate }); if (!isNullorEmpty(ctx.getParameter({ name: 'custscript_prev_deploy' }) )) { log.emergency({ title: 'Received Parameters | ', details: 'Zee ID: ' + partner }); log.emergency({ title: 'Received Parameters | ', details: 'Start Date: ' + startDate }); log.emergency({ title: 'Received Parameters | ', details: 'End Date: ' + endDate }); prevInvDeploy = ctx.getParameter({ name: 'custscript_prev_deploy' }); } else { prevInvDeploy = ctx.getDeploymentId; log.emergency({ title: 'Initial Parameters | ', details: 'Zee ID: ' + partner }); log.emergency({ title: 'Initial Parameters | ', details: 'Start Date: ' + startDate }); log.emergency({ title: 'Initial Parameters | ', details: 'End Date: ' + endDate }); } var searchedAlljobs = search.load({ id: 'customsearch_inv_review_jobs_uninv', type: 'customrecord_job' }) var zee_record = record.load({ type: record.Type.PARTNER, id: partner, }); var zee_text = zee_record.getValue({ fieldId: 'entitytitle' }); var strFormula = "COALESCE({custrecord_job_service.custrecord_service_franchisee},{custrecord_job_group.custrecord_jobgroup_franchisee},{custrecord_job_franchisee},'')"; searchedAlljobs.filters.push(search.createFilter({ name: 'custrecord_job_date_inv_finalised', operator: search.Operator.ISEMPTY })); searchedAlljobs.filters.push(search.createFilter({ name: 'custrecord_job_date_reviewed', operator: search.Operator.ISNOTEMPTY })); if (!isNullorEmpty(startDate) && !isNullorEmpty(endDate)) { searchedAlljobs.filters.push(search.createFilter({ name: 'custrecord_job_date_scheduled', operator: search.Operator.ONORAFTER, values: format.parse({ value: startDate, type: format.Type.DATE })})); searchedAlljobs.filters.push(search.createFilter({ name: 'custrecord_job_date_scheduled', operator: search.Operator.ONORBEFORE, values: format.parse({ value: endDate, type: format.Type.DATE })})); } var resultSetAlljobs = searchedAlljobs.run(); var count = 0; resultSetAlljobs.each(function(searchResultAlljobs) { count++; usageStart = ctx.getRemainingUsage(); if (usageStart <= usageThreshold) { log.debug({ title: 'SWITCHing -->', details: ctx }.getRemainingUsage()); var params = { custscript_partner: partner, custscript_prev_deploy: ctx.deploymentId, custscript_startdate: startDate, custscript_enddate: endDate } log.emergency({ title: 'Parameters Passed | ', details: 'Zee ID: ' + partner }); log.emergency({ title: 'Parameters Passed | ', details: 'Start Date: ' + startDate }); log.emergency({ title: 'Parameters Passed | ', details: 'End Date: ' + endDate }); var reschedule = task.create({ taskType: task.TaskType.SCHEDULED_SCRIPT, deploymentId: adhocInvDeploy, params: params, scriptId: prevInvDeploy, }) reschedule.submit(); if (reschedule == false) { return false; } } var jobID = searchResultAlljobs.getValue('internalid'); var jobService = searchResultAlljobs.getText("custrecord_job_service"); var jobCustomer = searchResultAlljobs.getText("custrecord_job_customer"); var specialCustomerType = searchResultAlljobs.getValue({ name: "custentity_special_customer_type", join: "CUSTRECORD_JOB_CUSTOMER", summary: null }); var linkedMPCustomer = searchResultAlljobs.getValue({ name: "custentity_np_mp_customer", join: "CUSTRECORD_JOB_CUSTOMER", summary: null }); var linkedSpecialCustomer = searchResultAlljobs.getValue({ name: "custentity_np_np_customer", join: "CUSTRECORD_JOB_CUSTOMER", summary: null }); var jobPackageType = searchResultAlljobs.getValue({ name: "custrecord_service_package_type", join: "CUSTRECORD_JOB_SERVICE_PACKAGE", summary: null }); try { var jobRecord = record.load({ type: 'customrecord_job', id: jobID }); //Below section is for Special Customers, so the job is transferred to that Special Customer and the Field SPECIAL CUSTOMER in the Job record is filled to the Special Customer. //Below condition is to check if the customer to which the job is assigned to has both the LINKED MP CUSTOMER & SPECIAL CUSTOMER TYPE not null, then an error email is sent out. if (!isNullorEmpty(linkedMPCustomer) || !isNullorEmpty(specialCustomerType)) { var body = 'Customer: ' + jobCustomer + ', has Linked MP Customer Field and Special Customer Type field set to ' + linkedMPCustomer + ' & ' + specialCustomerType + ' respectively.'; email.send({ author: 409635, body: body, recipients: ['efpyi@example.com', 'ychag@example.com'], subject: 'AIC: Date Invoice Finalised SC - Linked MP Customer & Customer Type both not null', }); } else if (!isNullorEmpty(linkedSpecialCustomer) && isNullorEmpty(specialCustomerType)) { //To check if the customer to which the job is assigned has the LINKED SPECIAL CUSTOMER filled & SPECIAL CUSTOMER TYPE not equal to null, then we go to the Linked Special customer record and get the Special Customer type. var specialCustomerRecord = record.load({ type: 'customer', id: linkedSpecialCustomer }); var specialCustomerSpecialCustomerType = specialCustomerRecord.getValue({ fieldId: 'custentity_special_customer_type' }); var specialCustomerTypeRecord = record.load({ type: 'customrecord_special_customer_type', id: specialCustomerSpecialCustomerType }); //Get the allowed services from the Special Customer Type record. var allowedServicesIDs = specialCustomerTypeRecord.getValue({ fieldId: 'custrecord_special_allowed_service' }); var allowedServicesTexts = specialCustomerTypeRecord.getText({ fieldId: 'custrecord_special_allowed_service' }); var result = null; //If the Special Customer Type is of type AusPost or Secure Cash if (specialCustomerSpecialCustomerType == 2 || specialCustomerSpecialCustomerType == 3) { //If the Allowed Services field is not null if (!isNullorEmpty(allowedServicesTexts) && !isNullorEmpty(allowedServicesIDs)) { // Check if the service performed by the job exists in the Allowed Services result = allowedServicesTexts.indexOf(jobService); // If exists if (result >= 0) { //Fill the Special Customer with the Linked Special Customer jobRecord.setValue({ fieldId: 'custrecord_job_special_customer', value: linkedSpecialCustomer }); } } else { } } else { //If Special Customer Type is of Type NeoPost. //Get the Allowed Package from the Special Type record var allowedPackage = specialCustomerTypeRecord.getValue({ fieldId: 'custrecord_special_allowed_package' }); //If allowed Package is equal to NeopPost if (allowedPackage == jobPackageType) { //Fill the Special Customer with the Linked Special Customer jobRecord.setValue({ fieldId: 'custrecord_job_special_customer', value: linkedSpecialCustomer }); } } } var jobGroupStatus = jobRecord.getValue({ fieldId: 'custrecord_job_group_status' }); var jobInvoiceable = jobRecord.getValue({ fieldId: 'custrecord_job_invoiceable' }); var jobCat = jobRecord.getValue({ fieldId: 'custrecord_job_service_category' }); var packageStatus = jobRecord.getValue({ fieldId: 'custrecord_package_status' }); var jobGroupSource = jobRecord.getValue({ fieldId: 'custrecord_job_source' }); if (isNullorEmpty(jobInvoiceable)) { if (!isNullorEmpty(packageStatus)) { if (packageStatus == 1 || isNullorEmpty(packageStatus)) { // Job Group Status is Null for Extras and Jobs Created in NS jobRecord.setValue({ fieldId: 'custrecord_job_invoiceable', value: 1 }); } else { jobRecord.setValue({ fieldId: 'custrecord_job_invoiceable', value: 2 }); } } else { if (jobGroupStatus == 'Completed' || (isNullorEmpty(jobGroupStatus) && jobGroupSource == 5) || jobCat != '1') { // Job Group Status is Null for Extras and Jobs Created in NS jobRecord.setValue({ fieldId: 'custrecord_job_invoiceable', value: 1 }); } else { jobRecord.setValue({ fieldId: 'custrecord_job_invoiceable', value: 2 }); } } } jobRecord.setValue({ fieldId: 'custrecord_job_date_inv_finalised', value: getDate() }); jobRecord.save({ enableSourcing: true, ignoreMandatoryFields: true }); usagePerLoop = ctx.getRemainingUsage() - usageStart log.debug({ title: 'Loop #:' + count + ' | job id: ' + jobID + ' | Usg: ' + usagePerLoop }); return true; } catch (e) { var message = ''; message += "Job: <a href ='https://1048144.app.netsuite.com/app/common/custom/custrecordentry.nl?rectype=941&id=" + jobID + "'> View Job</a></br>"; message += "----------------------------------------------------------------------------------</br>"; message += e; email.send({ author: 409635, body: message, recipients: ['efpyi@example.com', 'ychag@example.com'], subject: 'AIC - Review - Date Inv Finalised (SC) - Unable to update Job', }); } return true; }); log.debug({ title: 'END -->', details: ctx.getRemainingUsage() }); } function isNullorEmpty(strVal) { return (strVal == null || strVal == '' || strVal == 'null' || strVal == undefined || strVal == 'undefined' || strVal == '- None -'); } return { execute: main } } );
true
/** * @NApiVersion 2.x * @NScriptType ScheduledScript * * Module Description: Schedule Script to Set the Date Invoiced Finalised Field * * @Last Modified by: Sruti Desai * */ define(['N/runtime', 'N/search', 'N/record', 'N/log', 'N/task', 'N/currentRecord', 'N/format'], function(runtime, search, record, log, task, currentRecord, format) { var zee = 0; var role = runtime.getCurrentUser().role; var ctx = runtime.getCurrentScript(); var usageThreshold = 500; var adhocInvDeploy = 'customdeploy2'; var prevInvDeploy = ctx.deploymentId; var baseURL = 'https://1048144.app.netsuite.com'; if (runtime.EnvType == "SANDBOX") { baseURL = 'https://system.sandbox.netsuite.com'; } /** * [updateDateInvFin description] - Function to the set the Date Invoiced Finalised field in the job record. * @param {string} custscript_partner Partner ID * @param {string} custscript_startdate Start Date * @param {string} custscript_enddate End Date */ function main() { log.debug({ title: 'START -->', details: ctx.getRemainingUsage() }); var partner = parseInt(ctx.getParameter({ name: 'custscript_partner'})); var startDate = ctx.getParameter({ name: 'custscript_startdate' }); var endDate = ctx.getParameter({ name: 'custscript_enddate' }); log.debug({ title: 'partner', details: partner }); log.debug({ title: 'startDate', details: startDate }); log.debug({ title: 'endDate', details: endDate }); if (!isNullorEmpty(ctx.getParameter({ name: 'custscript_prev_deploy' }) )) { log.emergency({ title: 'Received Parameters | ', details: 'Zee ID: ' + partner }); log.emergency({ title: 'Received Parameters | ', details: 'Start Date: ' + startDate }); log.emergency({ title: 'Received Parameters | ', details: 'End Date: ' + endDate }); prevInvDeploy = ctx.getParameter({ name: 'custscript_prev_deploy' }); } else { prevInvDeploy = ctx.getDeploymentId; log.emergency({ title: 'Initial Parameters | ', details: 'Zee ID: ' + partner }); log.emergency({ title: 'Initial Parameters | ', details: 'Start Date: ' + startDate }); log.emergency({ title: 'Initial Parameters | ', details: 'End Date: ' + endDate }); } var searchedAlljobs = search.load({ id: 'customsearch_inv_review_jobs_uninv', type: 'customrecord_job' }) var zee_record = record.load({ type: record.Type.PARTNER, id: partner, }); var zee_text = zee_record.getValue({ fieldId: 'entitytitle' }); var strFormula = "COALESCE({custrecord_job_service.custrecord_service_franchisee},{custrecord_job_group.custrecord_jobgroup_franchisee},{custrecord_job_franchisee},'')"; searchedAlljobs.filters.push(search.createFilter({ name: 'custrecord_job_date_inv_finalised', operator: search.Operator.ISEMPTY })); searchedAlljobs.filters.push(search.createFilter({ name: 'custrecord_job_date_reviewed', operator: search.Operator.ISNOTEMPTY })); if (!isNullorEmpty(startDate) && !isNullorEmpty(endDate)) { searchedAlljobs.filters.push(search.createFilter({ name: 'custrecord_job_date_scheduled', operator: search.Operator.ONORAFTER, values: format.parse({ value: startDate, type: format.Type.DATE })})); searchedAlljobs.filters.push(search.createFilter({ name: 'custrecord_job_date_scheduled', operator: search.Operator.ONORBEFORE, values: format.parse({ value: endDate, type: format.Type.DATE })})); } var resultSetAlljobs = searchedAlljobs.run(); var count = 0; resultSetAlljobs.each(function(searchResultAlljobs) { count++; usageStart = ctx.getRemainingUsage(); if (usageStart <= usageThreshold) { log.debug({ title: 'SWITCHing -->', details: ctx }.getRemainingUsage()); var params = { custscript_partner: partner, custscript_prev_deploy: ctx.deploymentId, custscript_startdate: startDate, custscript_enddate: endDate } log.emergency({ title: 'Parameters Passed | ', details: 'Zee ID: ' + partner }); log.emergency({ title: 'Parameters Passed | ', details: 'Start Date: ' + startDate }); log.emergency({ title: 'Parameters Passed | ', details: 'End Date: ' + endDate }); var reschedule = task.create({ taskType: task.TaskType.SCHEDULED_SCRIPT, deploymentId: adhocInvDeploy, params: params, scriptId: prevInvDeploy, }) reschedule.submit(); if (reschedule == false) { return false; } } var jobID = searchResultAlljobs.getValue('internalid'); var jobService = searchResultAlljobs.getText("custrecord_job_service"); var jobCustomer = searchResultAlljobs.getText("custrecord_job_customer"); var specialCustomerType = searchResultAlljobs.getValue({ name: "custentity_special_customer_type", join: "CUSTRECORD_JOB_CUSTOMER", summary: null }); var linkedMPCustomer = searchResultAlljobs.getValue({ name: "custentity_np_mp_customer", join: "CUSTRECORD_JOB_CUSTOMER", summary: null }); var linkedSpecialCustomer = searchResultAlljobs.getValue({ name: "custentity_np_np_customer", join: "CUSTRECORD_JOB_CUSTOMER", summary: null }); var jobPackageType = searchResultAlljobs.getValue({ name: "custrecord_service_package_type", join: "CUSTRECORD_JOB_SERVICE_PACKAGE", summary: null }); try { var jobRecord = record.load({ type: 'customrecord_job', id: jobID }); //Below section is for Special Customers, so the job is transferred to that Special Customer and the Field SPECIAL CUSTOMER in the Job record is filled to the Special Customer. //Below condition is to check if the customer to which the job is assigned to has both the LINKED MP CUSTOMER & SPECIAL CUSTOMER TYPE not null, then an error email is sent out. if (!isNullorEmpty(linkedMPCustomer) || !isNullorEmpty(specialCustomerType)) { var body = 'Customer: ' + jobCustomer + ', has Linked MP Customer Field and Special Customer Type field set to ' + linkedMPCustomer + ' & ' + specialCustomerType + ' respectively.'; email.send({ author: 409635, body: body, recipients: ['PI:EMAIL:efpyi@example.comEND_PI', 'PI:EMAIL:ychag@example.comEND_PI'], subject: 'AIC: Date Invoice Finalised SC - Linked MP Customer & Customer Type both not null', }); } else if (!isNullorEmpty(linkedSpecialCustomer) && isNullorEmpty(specialCustomerType)) { //To check if the customer to which the job is assigned has the LINKED SPECIAL CUSTOMER filled & SPECIAL CUSTOMER TYPE not equal to null, then we go to the Linked Special customer record and get the Special Customer type. var specialCustomerRecord = record.load({ type: 'customer', id: linkedSpecialCustomer }); var specialCustomerSpecialCustomerType = specialCustomerRecord.getValue({ fieldId: 'custentity_special_customer_type' }); var specialCustomerTypeRecord = record.load({ type: 'customrecord_special_customer_type', id: specialCustomerSpecialCustomerType }); //Get the allowed services from the Special Customer Type record. var allowedServicesIDs = specialCustomerTypeRecord.getValue({ fieldId: 'custrecord_special_allowed_service' }); var allowedServicesTexts = specialCustomerTypeRecord.getText({ fieldId: 'custrecord_special_allowed_service' }); var result = null; //If the Special Customer Type is of type AusPost or Secure Cash if (specialCustomerSpecialCustomerType == 2 || specialCustomerSpecialCustomerType == 3) { //If the Allowed Services field is not null if (!isNullorEmpty(allowedServicesTexts) && !isNullorEmpty(allowedServicesIDs)) { // Check if the service performed by the job exists in the Allowed Services result = allowedServicesTexts.indexOf(jobService); // If exists if (result >= 0) { //Fill the Special Customer with the Linked Special Customer jobRecord.setValue({ fieldId: 'custrecord_job_special_customer', value: linkedSpecialCustomer }); } } else { } } else { //If Special Customer Type is of Type NeoPost. //Get the Allowed Package from the Special Type record var allowedPackage = specialCustomerTypeRecord.getValue({ fieldId: 'custrecord_special_allowed_package' }); //If allowed Package is equal to NeopPost if (allowedPackage == jobPackageType) { //Fill the Special Customer with the Linked Special Customer jobRecord.setValue({ fieldId: 'custrecord_job_special_customer', value: linkedSpecialCustomer }); } } } var jobGroupStatus = jobRecord.getValue({ fieldId: 'custrecord_job_group_status' }); var jobInvoiceable = jobRecord.getValue({ fieldId: 'custrecord_job_invoiceable' }); var jobCat = jobRecord.getValue({ fieldId: 'custrecord_job_service_category' }); var packageStatus = jobRecord.getValue({ fieldId: 'custrecord_package_status' }); var jobGroupSource = jobRecord.getValue({ fieldId: 'custrecord_job_source' }); if (isNullorEmpty(jobInvoiceable)) { if (!isNullorEmpty(packageStatus)) { if (packageStatus == 1 || isNullorEmpty(packageStatus)) { // Job Group Status is Null for Extras and Jobs Created in NS jobRecord.setValue({ fieldId: 'custrecord_job_invoiceable', value: 1 }); } else { jobRecord.setValue({ fieldId: 'custrecord_job_invoiceable', value: 2 }); } } else { if (jobGroupStatus == 'Completed' || (isNullorEmpty(jobGroupStatus) && jobGroupSource == 5) || jobCat != '1') { // Job Group Status is Null for Extras and Jobs Created in NS jobRecord.setValue({ fieldId: 'custrecord_job_invoiceable', value: 1 }); } else { jobRecord.setValue({ fieldId: 'custrecord_job_invoiceable', value: 2 }); } } } jobRecord.setValue({ fieldId: 'custrecord_job_date_inv_finalised', value: getDate() }); jobRecord.save({ enableSourcing: true, ignoreMandatoryFields: true }); usagePerLoop = ctx.getRemainingUsage() - usageStart log.debug({ title: 'Loop #:' + count + ' | job id: ' + jobID + ' | Usg: ' + usagePerLoop }); return true; } catch (e) { var message = ''; message += "Job: <a href ='https://1048144.app.netsuite.com/app/common/custom/custrecordentry.nl?rectype=941&id=" + jobID + "'> View Job</a></br>"; message += "----------------------------------------------------------------------------------</br>"; message += e; email.send({ author: 409635, body: message, recipients: ['PI:EMAIL:efpyi@example.comEND_PI', 'PI:EMAIL:ychag@example.comEND_PI'], subject: 'AIC - Review - Date Inv Finalised (SC) - Unable to update Job', }); } return true; }); log.debug({ title: 'END -->', details: ctx.getRemainingUsage() }); } function isNullorEmpty(strVal) { return (strVal == null || strVal == '' || strVal == 'null' || strVal == undefined || strVal == 'undefined' || strVal == '- None -'); } return { execute: main } } );
define(["N/search", "/SuiteScripts/lib/autocomplete"], function( search, autocomplete ) { /** * Lexor Case Form * @NApiVersion 2.x * @NScriptType ClientScript * @author trungpv <trung@lexor.com> */ /* === VARS === */ /* === EVENTS FUNCTIONS === */ /** * Page Init * @param {*} context */ function pageInit(context) { const currentRecord = context.currentRecord; loadCSSText( ".autocomplete{background:#fff;z-index:1000;overflow:auto;box-sizing:border-box;border:1px solid #ccc;font-size:13px}.autocomplete>div{padding:5px 5px;border-bottom:1px solid #ccc}.autocomplete .group{background:#eee}.autocomplete>div.selected,.autocomplete>div:hover:not(.group){background:#607799;cursor:pointer;color:#fff}" ); var phone = document.getElementById("phone"); autocomplete({ input: phone, fetch: function(text, update) { // Start Search search.global .promise({ keywords: text }) .then(function(globalSearchResults) { processSupportCases(globalSearchResults, function(supportCases) { loadSupportCase(supportCases, function(dataSupportCase) { getSupportCase(dataSupportCase, function(arrItems) { var items = []; for (var index = 0; index < arrItems.length; index++) { var arrItem = arrItems[index].data; items = items.concat(arrItem); } update(items); }); }); }); }) .catch(function onRejected(reason) {}); }, render: function(el, currentValue) { console.log(el); var div = document.createElement("div"); var formatStr = '<p><strong style="font-weight: bold;">' + el.recordType + "</strong></p>"; // formatStr += // '<p>Name: <strong style="font-weight: bold;">' + // title + // "</strong></p>"; // formatStr += // '<p>Status: <strong style="font-weight: bold;">' + // status + // "</strong></p>"; // formatStr += // '<p>Assigned To: <strong style="font-weight: bold;">' + // assigned + // "</strong></p>"; // formatStr += // '<p>Phone: <strong style="font-weight: bold;">' + // phone + // "</strong></p>"; div.innerHTML = formatStr; return div; }, onSelect: function(item) { NS.jQuery("#phone").val(""); window.open("/app/crm/support/supportcase.nl?id=" + item.id, "_blank"); } }); return; } /** HELPER FUNCTIONS **/ /** * Load CSS from Text * @param {*} str */ function loadCSSText(str) { if (window.document) { var fileref = window.document.createElement("style"); fileref.innerHTML = str; window.document.head.appendChild(fileref); } } /** * A specialized version of `_.filter` for arrays without support for * iteratee shorthands. * * @private * @param {Array} [array] The array to iterate over. * @param {Function} predicate The function invoked per iteration. * @returns {Array} Returns the new filtered array. */ function arrayFilter(array, predicate) { var index = -1, length = array == null ? 0 : array.length, resIndex = 0, result = []; while (++index < length) { var value = array[index]; if (predicate(value, index, array)) { result[resIndex++] = value; } } return result; } /** * Convert Name * @param {*} firstname * @param {*} middlename * @param {*} lastname */ function getName(firstname, middlename, lastname) { var name = ""; name += firstname !== "" ? firstname : ""; name += middlename !== "" ? " " + middlename : ""; name += lastname !== "" ? " " + lastname : ""; return name; } /** * Process Support Cases * @param {*} globalSearchResults * @param {*} done */ function processSupportCases(globalSearchResults, done) { const types = ["Customer", "Lead", "Prospect"]; var promises = []; for (var index = 0; index < globalSearchResults.length; index++) { var o = globalSearchResults[index]; if ( (o.getValue({ name: "info1" }) !== "" || o.getValue({ name: "info2" }) !== "") && types.includes( o.getValue({ name: "type" }) ) ) { promises.push( search.create.promise({ type: search.Type.SUPPORT_CASE, filters: [["company.internalid", search.Operator.IS, [o.id]]], columns: [ search.createColumn({ name: "casenumber", sort: search.Sort.DESC }), // "title", // "stage", // "status", // "employee.firstname" ] }) ); } } Promise.all(promises) .then(done) .catch(function onRejected(reason) { console.log("processSupportCases", reason); }); } /** * Load Support Case * @param {*} supportCase * @param {*} done */ function loadSupportCase(supportCases, done) { var promises = []; for (var index = 0; index < supportCases.length; index++) { promises.push(supportCases[index].runPaged.promise()); } Promise.all(promises) .then(done) .catch(function onRejected(reason) { console.log("loadSupportCase", reason); }); } /** * Get Support Case Detail * @param {*} dataSupportCases * @param {*} done */ function getSupportCase(dataSupportCase, done) { var promises = []; for (var index = 0; index < dataSupportCase.length; index++) { var _dSC = dataSupportCase[index]; if (_dSC.pageRanges.length > 0) { for (var i = 0; i < _dSC.pageRanges.length; i++) { promises.push( _dSC.fetch.promise({ index: i }) ); } } } Promise.all(promises) .then(done) .catch(function onRejected(reason) { console.log("getSupportCase", reason); }); } /** * Export Events */ var exports = {}; exports.pageInit = pageInit; return exports; });
531
[{"tag": "EMAIL", "value": "trung@lexor.com", "start": 196, "end": 211}]
true
1
define(["N/search", "/SuiteScripts/lib/autocomplete"], function( search, autocomplete ) { /** * Lexor Case Form * @NApiVersion 2.x * @NScriptType ClientScript * @author trungpv <hzdkv@example.com> */ /* === VARS === */ /* === EVENTS FUNCTIONS === */ /** * Page Init * @param {*} context */ function pageInit(context) { const currentRecord = context.currentRecord; loadCSSText( ".autocomplete{background:#fff;z-index:1000;overflow:auto;box-sizing:border-box;border:1px solid #ccc;font-size:13px}.autocomplete>div{padding:5px 5px;border-bottom:1px solid #ccc}.autocomplete .group{background:#eee}.autocomplete>div.selected,.autocomplete>div:hover:not(.group){background:#607799;cursor:pointer;color:#fff}" ); var phone = document.getElementById("phone"); autocomplete({ input: phone, fetch: function(text, update) { // Start Search search.global .promise({ keywords: text }) .then(function(globalSearchResults) { processSupportCases(globalSearchResults, function(supportCases) { loadSupportCase(supportCases, function(dataSupportCase) { getSupportCase(dataSupportCase, function(arrItems) { var items = []; for (var index = 0; index < arrItems.length; index++) { var arrItem = arrItems[index].data; items = items.concat(arrItem); } update(items); }); }); }); }) .catch(function onRejected(reason) {}); }, render: function(el, currentValue) { console.log(el); var div = document.createElement("div"); var formatStr = '<p><strong style="font-weight: bold;">' + el.recordType + "</strong></p>"; // formatStr += // '<p>Name: <strong style="font-weight: bold;">' + // title + // "</strong></p>"; // formatStr += // '<p>Status: <strong style="font-weight: bold;">' + // status + // "</strong></p>"; // formatStr += // '<p>Assigned To: <strong style="font-weight: bold;">' + // assigned + // "</strong></p>"; // formatStr += // '<p>Phone: <strong style="font-weight: bold;">' + // phone + // "</strong></p>"; div.innerHTML = formatStr; return div; }, onSelect: function(item) { NS.jQuery("#phone").val(""); window.open("/app/crm/support/supportcase.nl?id=" + item.id, "_blank"); } }); return; } /** HELPER FUNCTIONS **/ /** * Load CSS from Text * @param {*} str */ function loadCSSText(str) { if (window.document) { var fileref = window.document.createElement("style"); fileref.innerHTML = str; window.document.head.appendChild(fileref); } } /** * A specialized version of `_.filter` for arrays without support for * iteratee shorthands. * * @private * @param {Array} [array] The array to iterate over. * @param {Function} predicate The function invoked per iteration. * @returns {Array} Returns the new filtered array. */ function arrayFilter(array, predicate) { var index = -1, length = array == null ? 0 : array.length, resIndex = 0, result = []; while (++index < length) { var value = array[index]; if (predicate(value, index, array)) { result[resIndex++] = value; } } return result; } /** * Convert Name * @param {*} firstname * @param {*} middlename * @param {*} lastname */ function getName(firstname, middlename, lastname) { var name = ""; name += firstname !== "" ? firstname : ""; name += middlename !== "" ? " " + middlename : ""; name += lastname !== "" ? " " + lastname : ""; return name; } /** * Process Support Cases * @param {*} globalSearchResults * @param {*} done */ function processSupportCases(globalSearchResults, done) { const types = ["Customer", "Lead", "Prospect"]; var promises = []; for (var index = 0; index < globalSearchResults.length; index++) { var o = globalSearchResults[index]; if ( (o.getValue({ name: "info1" }) !== "" || o.getValue({ name: "info2" }) !== "") && types.includes( o.getValue({ name: "type" }) ) ) { promises.push( search.create.promise({ type: search.Type.SUPPORT_CASE, filters: [["company.internalid", search.Operator.IS, [o.id]]], columns: [ search.createColumn({ name: "casenumber", sort: search.Sort.DESC }), // "title", // "stage", // "status", // "employee.firstname" ] }) ); } } Promise.all(promises) .then(done) .catch(function onRejected(reason) { console.log("processSupportCases", reason); }); } /** * Load Support Case * @param {*} supportCase * @param {*} done */ function loadSupportCase(supportCases, done) { var promises = []; for (var index = 0; index < supportCases.length; index++) { promises.push(supportCases[index].runPaged.promise()); } Promise.all(promises) .then(done) .catch(function onRejected(reason) { console.log("loadSupportCase", reason); }); } /** * Get Support Case Detail * @param {*} dataSupportCases * @param {*} done */ function getSupportCase(dataSupportCase, done) { var promises = []; for (var index = 0; index < dataSupportCase.length; index++) { var _dSC = dataSupportCase[index]; if (_dSC.pageRanges.length > 0) { for (var i = 0; i < _dSC.pageRanges.length; i++) { promises.push( _dSC.fetch.promise({ index: i }) ); } } } Promise.all(promises) .then(done) .catch(function onRejected(reason) { console.log("getSupportCase", reason); }); } /** * Export Events */ var exports = {}; exports.pageInit = pageInit; return exports; });
true
define(["N/search", "/SuiteScripts/lib/autocomplete"], function( search, autocomplete ) { /** * Lexor Case Form * @NApiVersion 2.x * @NScriptType ClientScript * @author trungpv <PI:EMAIL:hzdkv@example.comEND_PI> */ /* === VARS === */ /* === EVENTS FUNCTIONS === */ /** * Page Init * @param {*} context */ function pageInit(context) { const currentRecord = context.currentRecord; loadCSSText( ".autocomplete{background:#fff;z-index:1000;overflow:auto;box-sizing:border-box;border:1px solid #ccc;font-size:13px}.autocomplete>div{padding:5px 5px;border-bottom:1px solid #ccc}.autocomplete .group{background:#eee}.autocomplete>div.selected,.autocomplete>div:hover:not(.group){background:#607799;cursor:pointer;color:#fff}" ); var phone = document.getElementById("phone"); autocomplete({ input: phone, fetch: function(text, update) { // Start Search search.global .promise({ keywords: text }) .then(function(globalSearchResults) { processSupportCases(globalSearchResults, function(supportCases) { loadSupportCase(supportCases, function(dataSupportCase) { getSupportCase(dataSupportCase, function(arrItems) { var items = []; for (var index = 0; index < arrItems.length; index++) { var arrItem = arrItems[index].data; items = items.concat(arrItem); } update(items); }); }); }); }) .catch(function onRejected(reason) {}); }, render: function(el, currentValue) { console.log(el); var div = document.createElement("div"); var formatStr = '<p><strong style="font-weight: bold;">' + el.recordType + "</strong></p>"; // formatStr += // '<p>Name: <strong style="font-weight: bold;">' + // title + // "</strong></p>"; // formatStr += // '<p>Status: <strong style="font-weight: bold;">' + // status + // "</strong></p>"; // formatStr += // '<p>Assigned To: <strong style="font-weight: bold;">' + // assigned + // "</strong></p>"; // formatStr += // '<p>Phone: <strong style="font-weight: bold;">' + // phone + // "</strong></p>"; div.innerHTML = formatStr; return div; }, onSelect: function(item) { NS.jQuery("#phone").val(""); window.open("/app/crm/support/supportcase.nl?id=" + item.id, "_blank"); } }); return; } /** HELPER FUNCTIONS **/ /** * Load CSS from Text * @param {*} str */ function loadCSSText(str) { if (window.document) { var fileref = window.document.createElement("style"); fileref.innerHTML = str; window.document.head.appendChild(fileref); } } /** * A specialized version of `_.filter` for arrays without support for * iteratee shorthands. * * @private * @param {Array} [array] The array to iterate over. * @param {Function} predicate The function invoked per iteration. * @returns {Array} Returns the new filtered array. */ function arrayFilter(array, predicate) { var index = -1, length = array == null ? 0 : array.length, resIndex = 0, result = []; while (++index < length) { var value = array[index]; if (predicate(value, index, array)) { result[resIndex++] = value; } } return result; } /** * Convert Name * @param {*} firstname * @param {*} middlename * @param {*} lastname */ function getName(firstname, middlename, lastname) { var name = ""; name += firstname !== "" ? firstname : ""; name += middlename !== "" ? " " + middlename : ""; name += lastname !== "" ? " " + lastname : ""; return name; } /** * Process Support Cases * @param {*} globalSearchResults * @param {*} done */ function processSupportCases(globalSearchResults, done) { const types = ["Customer", "Lead", "Prospect"]; var promises = []; for (var index = 0; index < globalSearchResults.length; index++) { var o = globalSearchResults[index]; if ( (o.getValue({ name: "info1" }) !== "" || o.getValue({ name: "info2" }) !== "") && types.includes( o.getValue({ name: "type" }) ) ) { promises.push( search.create.promise({ type: search.Type.SUPPORT_CASE, filters: [["company.internalid", search.Operator.IS, [o.id]]], columns: [ search.createColumn({ name: "casenumber", sort: search.Sort.DESC }), // "title", // "stage", // "status", // "employee.firstname" ] }) ); } } Promise.all(promises) .then(done) .catch(function onRejected(reason) { console.log("processSupportCases", reason); }); } /** * Load Support Case * @param {*} supportCase * @param {*} done */ function loadSupportCase(supportCases, done) { var promises = []; for (var index = 0; index < supportCases.length; index++) { promises.push(supportCases[index].runPaged.promise()); } Promise.all(promises) .then(done) .catch(function onRejected(reason) { console.log("loadSupportCase", reason); }); } /** * Get Support Case Detail * @param {*} dataSupportCases * @param {*} done */ function getSupportCase(dataSupportCase, done) { var promises = []; for (var index = 0; index < dataSupportCase.length; index++) { var _dSC = dataSupportCase[index]; if (_dSC.pageRanges.length > 0) { for (var i = 0; i < _dSC.pageRanges.length; i++) { promises.push( _dSC.fetch.promise({ index: i }) ); } } } Promise.all(promises) .then(done) .catch(function onRejected(reason) { console.log("getSupportCase", reason); }); } /** * Export Events */ var exports = {}; exports.pageInit = pageInit; return exports; });
/** * * @NApiVersion 2.0 * @NScriptType Suitelet * * Description: A ticketing system for the Customer Service. * @Last Modified by: Sruti Desai * */ define(['N/ui/serverWidget', 'N/email', 'N/runtime', 'N/search', 'N/record', 'N/http', 'N/log', 'N/redirect', 'N/format', 'N/file'], function(ui, email, runtime, search, record, http, log, redirect, format, file) { var baseURL = 'https://1048144.app.netsuite.com'; if (runtime.EnvType == "SANDBOX") { baseURL = 'https://1048144-sb3.app.netsuite.com'; } var zee = 0; var role = runtime.getCurrentUser().role; var userRole = runtime.getCurrentUser().role; var ctx = runtime.getCurrentScript(); var userId = runtime.getCurrentUser().id; if (role == 1000) { //Franchisee zee = runtime.getCurrentUser(); } function onRequest(context) { if (context.request.method === 'GET') { var ticket_id = null; var customer_id = null; var customer_number = null; var selector_id = null; var selector_number = ''; var selector_type = 'barcode_number'; var connote_number = ''; var date_created = ''; var creator_name = ''; var creator_id = null; var status_value = null; var escalated_to_it = ''; var status = ''; var customer_name = ''; var daytodayphone = ''; var daytodayemail = ''; var accountsphone = ''; var accountsemail = ''; var zee_id = null; var franchisee_name = ''; var zee_main_contact_name = ''; var zee_email = ''; var zee_main_contact_phone = ''; var zee_abn = ''; var date_stock_used = ''; var time_stock_used = ''; var final_delivery_text = ''; var selected_enquiry_status_id = null; var attachments_hyperlink = ''; var maap_bank_account_number = null; var maap_parent_bank_account_number = null; var selected_invoice_method_id = null; var accounts_cc_email = ''; var mpex_po_number = ''; var customer_po_number = ''; var terms = null; var customer_terms = ''; var account_manager = {}; var selected_invoice_cycle_id = null; var usage_report_id_1 = ''; var usage_report_id_2 = ''; var usage_report_id_3 = ''; var usage_report_id_4 = ''; var usage_report_array = []; var list_toll_issues = ''; var list_resolved_toll_issues = ''; var list_mp_ticket_issues = ''; var list_resolved_mp_ticket_issues = ''; var list_invoice_issues = ''; var list_resolved_invoice_issues = ''; var owner_list = ''; var comment = ''; var selected_label_id = null; var list_enquiry_mediums = ''; var total_enquiry_count = 0; var chat_enquiry_count = 0; var phone_enquiry_count = 0; var email_enquiry_count = 0; var phone_interaction_count = 0; var email_interaction_count = 0; var list_toll_emails = ''; var params_email = { recipient: '', subject: '', body: '', cc: '', bcc: '', records: {}, attachments_credit_memo_ids: [], attachments_usage_report_ids: [], attachments_invoice_ids: [] }; var customer_barcode_number = ''; var customer_issue = ''; var screenshot_file = ''; var browser = ''; var login_email_used = ''; var operating_system = ''; var phone_used = ''; var old_sender_name = ''; var old_sender_phone = ''; var customer_number_email_sent = 'F'; var customer_ticket_status = ''; var receiveremail = ''; var receiverphone = ''; var receivername = ''; var receiverstate = ''; var receiverzip = ''; var receiversuburb = ''; var receiveraddr1 = ''; var receiveraddr2 = ''; var prod_stock_invoice = ''; var barcodempdl = ''; var barcodesource = ''; // Load params var params = context.request.parameters.custparam_params; log.debug({ title: 'Params', details: params }) if (!isNullorEmpty(params)) { params = JSON.parse(params); log.debug({ title: 'Params not empty', details: params }); // Coming from the ticket_contact page or the edit_ticket page if (!isNullorEmpty(params.selector_number) && !isNullorEmpty(params.selector_type)) { selector_number = params.selector_number; selector_type = params.selector_type; //Coming from the ticket_contact page if (!isNullorEmpty(params.custid)) { customer_id = params.custid; } log.debug({ title: 'customer_id after ticket_contact_page : ', details: customer_id }); // Coming from the edit_ticket page if (!isNullorEmpty(params.ticket_id)) { ticket_id = parseInt(params.ticket_id); log.debug({ title: 'ticket id ISS', details: ticket_id }); // Load ticket data var ticketRecord = record.load({ type: 'customrecord_mp_ticket', id: ticket_id }); date_created = ticketRecord.getValue({ fieldId: 'created' }); creator_name = ticketRecord.getText({ fieldId: 'custrecord_creator' }); creator_id = ticketRecord.getValue({ fieldId: 'custrecord_creator' }); status_value = ticketRecord.getValue({ fieldId: 'custrecord_ticket_status' }); escalated_to_it = ticketRecord.getValue({ fieldId: 'custrecord_date_escalated_it' }); status = ticketRecord.getText({ fieldId: 'custrecord_ticket_status' }); customer_id = ticketRecord.getValue({ fieldId: 'custrecord_customer1' }); customer_name = ticketRecord.getText({ fieldId: 'custrecord_customer1' }); zee_id = ticketRecord.getValue({ fieldId: 'custrecord_zee' }); selected_enquiry_status_id = ticketRecord.getValue({ fieldId: 'custrecord_enquiry_status' }); attachments_hyperlink = ticketRecord.getValue({ fieldId: 'custrecord_mp_ticket_attachments' }); selected_label_id = ticketRecord.getValue({ fieldId: 'custrecord_ticket_label' }); list_enquiry_mediums = ticketRecord.getValue({ fieldId: 'custrecord_enquiry_medium' }); list_enquiry_mediums = java2jsArray(list_enquiry_mediums); total_enquiry_count = ticketRecord.getValue({ fieldId: 'custrecord_enquiry_count' }); chat_enquiry_count = ticketRecord.getValue({ fieldId: 'custrecord_chat_enquiry_count' }); phone_enquiry_count = ticketRecord.getValue({ fieldId: 'custrecord_phone_enquiry_count' }); phone_interaction_count = ticketRecord.getValue({ fieldId: 'custrecord_phone_interaction_count' }); email_interaction_count= ticketRecord.getValue({ fieldId: 'custrecord_email_interaction_count' }); email_enquiry_count = ticketRecord.getValue({ fieldId: 'custrecord_email_enquiry_count' }); customer_issue = ticketRecord.getValue({ fieldId: 'custrecord_customer_issue' }); screenshot_file = ticketRecord.getValue({ fieldId: 'custrecord_screenshot' }); browser = ticketRecord.getValue({ fieldId: 'custrecord_browser' }); login_email_used = ticketRecord.getValue({ fieldId: 'custrecord_login_email' }); operating_system = ticketRecord.getValue({ fieldId: 'custrecord_operating_system' }); phone_used = ticketRecord.getValue({ fieldId: 'custrecord_phone_used' }); customer_number = ticketRecord.getValue({ fieldId: 'custrecord_cust_number' }); old_sender_name = ticketRecord.getValue({ fieldId: 'custrecord_sender_name' }); old_sender_phone = ticketRecord.getValue({ fieldId: 'custrecord_sender_phone' }); customer_number_email_sent = ticketRecord.getValue({ fieldId: 'custrecord_customer_number_email_sent' }); customer_barcode_number = ticketRecord.getValue({ fieldId : 'custrecord_barcode_number'}); customer_ticket_status = ticketRecord.getText({ fieldId : 'custrecord_mp_ticket_customer_status'}); if (!isNullorEmpty(customer_barcode_number)) { var rec = record.load({ type: 'customrecord_customer_product_stock', id: customer_barcode_number, }); receiveremail = rec.getValue({fieldId: 'custrecord_receiver_email'}); receiverphone = rec.getValue({fieldId: 'custrecord_receiver_phone'}); receivername = rec.getValue({fieldId: 'custrecord_receiver_name'}); receiverstate = rec.getValue({fieldId: 'custrecord_receiver_state'}); receiverzip = rec.getValue({fieldId: 'custrecord_receiver_postcode'}); receiversuburb = rec.getValue({fieldId: 'custrecord_receiver_suburb'}); receiveraddr1 = rec.getValue({fieldId: 'custrecord_receiver_addr1'}); receiveraddr2 = rec.getValue({fieldId: 'custrecord_receiver_addr2'}); prod_stock_invoice = rec.getText({fieldId: 'custrecord_prod_stock_invoice'}); barcodempdl = rec.getValue({fieldId: 'custrecord_mpdl_number'}); barcodesource = rec.getText({fieldId: 'custrecord_barcode_source'}); connote_number = rec.getValue({fieldId: 'custrecord_connote_number'}); } if(isNullorEmpty(customer_id) && !isNullorEmpty(customer_number)){ var customer_search = search.load({ type: 'customer', id: 'customsearch_customer_name_2' }); customer_search.filters.push(search.createFilter({ name: 'entityid', operator: 'haskeywords', values: customer_number, })); log.debug({ title: 'customer_search.run().getRange({ start: 0,end:1 })[0].id', details: customer_search.run().getRange({ start: 0,end:1 })[0].id }); customer_id = customer_search.run().getRange({ start: 0,end:1 })[0].id; } if (!isNullorEmpty(customer_id)) { //Load customer record and franchisee information var customerRecord = record.load({ type: 'customer', id: customer_id }); customer_number = customerRecord.getValue({ fieldId: 'entityid' }); daytodayphone = customerRecord.getValue({ fieldId: 'phone' }); daytodayemail = customerRecord.getValue({ fieldId: 'custentity_email_service' }); terms = customerRecord.getValue({ fieldId: 'terms' }); customer_terms = customerRecord.getValue({ fieldId: 'custentity_finance_terms' }); // Account manager var accountManagerSearch = search.load({ type: 'customer', id: 'customsearch3413' }); accountManagerSearch.filters.push(search.createFilter({ name: 'internalid', join: null, operator: search.Operator.ANYOF, values: customer_id, })) var accountManagerResultSet = accountManagerSearch.run(); var accountManagerResult = accountManagerResultSet.getRange({ start: 0, end: 1 }); accountManagerResult = accountManagerResult[0]; if (!isNullorEmpty(accountManagerResult)) { var account_manager_value = accountManagerResult.getValue({ name: "custrecord_sales_assigned", join: "CUSTRECORD_SALES_CUSTOMER", summary: null }); var account_manager_text = accountManagerResult.getText({ name: "custrecord_sales_assigned", join: "CUSTRECORD_SALES_CUSTOMER", summary: null }); if (!isNullorEmpty(account_manager_value)) { var account_manager_email = search.lookupFields({ type: 'employee', id: account_manager_value, columns: 'email' }); account_manager = { name: account_manager_text, email: account_manager_email }; } } // The Franchisee informations are imported from the customer record if possible. zee_id = customerRecord.getValue({ fieldId: 'partner' }); } if (!isNullorEmpty(zee_id)) { var zeeRecord = record.load({ type: 'partner', id: zee_id }); franchisee_name = zeeRecord.getValue({ fieldId: 'companyname' }); zee_main_contact_name = zeeRecord.getValue({ fieldId: 'custentity3' }); zee_email = zeeRecord.getValue({ fieldId: 'email' }); zee_main_contact_phone = zeeRecord.getValue({ fieldId: 'custentity2' }); zee_abn = zeeRecord.getValue({ fieldId: 'custentity_abn_franchiserecord' }); } else { franchisee_name = ticketRecord.getText({ fieldId: 'custrecord_zee' }); } switch (selector_type) { case 'barcode_number': selector_id = ticketRecord.getValue({ fieldId: 'custrecord_barcode_number' }); var stock_used = ''; if(!isNullorEmpty(selector_id)){ //Come in here only if selector_id is not null stock_used = search.lookupFields({ type: 'customrecord_customer_product_stock', id: selector_id, columns: ['custrecord_cust_date_stock_used', 'custrecord_cust_time_stock_used'] }); log.debug({ title: 'stock_used', details: stock_used }) log.debug({ title: 'finalDel', details: search.lookupFields({ type: 'customrecord_customer_product_stock', id: selector_id, columns: 'custrecord_cust_prod_stock_final_del' }) }); var finalDelCheck = search.lookupFields({ type: 'customrecord_customer_product_stock', id: selector_id, columns: 'custrecord_cust_prod_stock_final_del' }).custrecord_cust_prod_stock_final_del; if (!isNullorEmpty(finalDelCheck)) { final_delivery_text = search.lookupFields({ type: 'customrecord_customer_product_stock', id: selector_id, columns: 'custrecord_cust_prod_stock_final_del' })["custrecord_cust_prod_stock_final_del"][0]["text"]; } date_stock_used = stock_used.custrecord_cust_date_stock_used; time_stock_used = stock_used.custrecord_cust_time_stock_used; } list_toll_issues = ticketRecord.getValue({ fieldId: 'custrecord_toll_issues' }); list_toll_issues = java2jsArray(list_toll_issues); list_resolved_toll_issues = ticketRecord.getValue({ fieldId: 'custrecord_resolved_toll_issues' }); list_resolved_toll_issues = java2jsArray(list_resolved_toll_issues); list_toll_emails = ticketRecord.getValue({ fieldId: 'custrecord_toll_emails' }); list_toll_emails = java2jsArray(list_toll_emails); break; case 'invoice_number': selector_id = ticketRecord.getValue({ fieldId: 'custrecord_invoice_number' }); var invoiceRecord = record.load({ type: 'invoice', id: selector_id }); accountsphone = customerRecord.getValue({ fieldId: 'altphone' }); accountsemail = customerRecord.getValue({ fieldId: 'email' }); maap_bank_account_number = customerRecord.getValue({ fieldId: 'custentity_maap_bankacctno' }); maap_parent_bank_account_number = customerRecord.getValue({ fieldId: 'custentity_maap_bankacctno_parent' }); selected_invoice_method_id = customerRecord.getValue({ fieldId: 'custentity_invoice_method' }); accounts_cc_email = customerRecord.getValue({ fieldId: 'custentity_accounts_cc_email' }); mpex_po_number = customerRecord.getValue({ fieldId: 'custentity_mpex_po' }); customer_po_number = customerRecord.getValue({ fieldId: 'custentity11' }); selected_invoice_cycle_id = customerRecord.getValue({ fieldId: 'custentity_mpex_invoicing_cycle' }); usage_report_id_1 = invoiceRecord.getValue({ fieldId: 'custbody_mpex_usage_report' }); usage_report_id_2 = invoiceRecord.getValue({ fieldId: 'custbody_mpex_usage_report_2' }); usage_report_id_3 = invoiceRecord.getValue({ fieldId: 'custbody_mpex_usage_report_3' }); usage_report_id_4 = invoiceRecord.getValue({ fieldId: 'custbody_mpex_usage_report_4' }); var usage_report_id_array = [usage_report_id_1, usage_report_id_2, usage_report_id_3, usage_report_id_4]; usage_report_id_array.forEach(function (usage_report_id) { if (!isNullorEmpty(usage_report_id)) { var usage_report_file = file.load({ id: usage_report_id }); usage_report_name = usage_report_file.name; usage_report_link = usage_report_file.url; usage_report_array.push({ id: usage_report_id, name: usage_report_name, url: usage_report_link }); } }); list_invoice_issues = ticketRecord.getValue({ fieldId: 'custrecord_invoice_issues' }); list_invoice_issues = java2jsArray(list_invoice_issues); list_resolved_invoice_issues = ticketRecord.getValue({ fieldId: 'custrecord_resolved_invoice_issues' }); list_resolved_invoice_issues = java2jsArray(list_resolved_invoice_issues); break; } list_mp_ticket_issues = ticketRecord.getValue({ fieldId: 'custrecord_mp_ticket_issue' }); list_mp_ticket_issues = java2jsArray(list_mp_ticket_issues); list_resolved_mp_ticket_issues = ticketRecord.getValue({ fieldId: 'custrecord_resolved_mp_ticket_issue' }); list_resolved_mp_ticket_issues = java2jsArray(list_resolved_mp_ticket_issues); owner_list = ticketRecord.getValue({ fieldId: 'custrecord_owner' }); owner_list = Ownerjava2jsArray(owner_list); comment = ticketRecord.getValue({ fieldId: 'custrecord_comment' }); } } } var form = ui.createForm({ title: ' ', }); // Load jQuery var inlineHtml = '<script src="https://code.jquery.com/jquery-1.12.4.min.js" integrity="sha384-nvAa0+6Qg9clwYCGGPpDQLVpLNn0fRaROjHqs13t4Ggj3Ez50XnGQqc/r8MhnRDZ" crossorigin="anonymous"></script>'; // Load Tooltip inlineHtml += '<script src="https://unpkg.com/@popperjs/core@2"></script>'; // Load Bootstrap inlineHtml += '<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/3.4.1/css/bootstrap.min.css" integrity="sha384-HSMxcRTRxnN+Bdg0JdbxYKrThecOKuH5zCYotlSAcp1+c8xmyTe9GYg1l9a69psu" crossorigin="anonymous">'; inlineHtml += '<script src="https://stackpath.bootstrapcdn.com/bootstrap/3.4.1/js/bootstrap.min.js" integrity="sha384-aJ21OjlMXNL5UyIl/XNwTMqvzeRMZH2w8c5cRVpzpU8Y5bApTppSuUkhZXN0VxHd" crossorigin="anonymous"></script>'; // Load DataTables inlineHtml += '<link rel="stylesheet" type="text/css" href="//cdn.datatables.net/1.10.21/css/jquery.dataTables.min.css">'; inlineHtml += '<script type="text/javascript" charset="utf8" src="//cdn.datatables.net/1.10.21/js/jquery.dataTables.min.js"></script>'; // Load Summernote css/js inlineHtml += '<link href="https://cdnjs.cloudflare.com/ajax/libs/summernote/0.8.9/summernote.css" rel="stylesheet">'; inlineHtml += '<script src="https://cdnjs.cloudflare.com/ajax/libs/summernote/0.8.9/summernote.js"></script>'; // Load bootstrap-select inlineHtml += '<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap-select@1.13.14/dist/css/bootstrap-select.min.css">'; inlineHtml += '<script src="https://cdn.jsdelivr.net/npm/bootstrap-select@1.13.14/dist/js/bootstrap-select.min.js"></script>'; // Load Netsuite stylesheet and script inlineHtml += '<link rel="stylesheet" href="https://1048144.app.netsuite.com/core/media/media.nl?id=2060796&c=1048144&h=9ee6accfd476c9cae718&_xt=.css"/>'; inlineHtml += '<script src="https://1048144.app.netsuite.com/core/media/media.nl?id=2060797&c=1048144&h=ef2cda20731d146b5e98&_xt=.js"></script>'; inlineHtml += '<link type="text/css" rel="stylesheet" href="https://1048144.app.netsuite.com/core/media/media.nl?id=2090583&c=1048144&h=a0ef6ac4e28f91203dfe&_xt=.css">'; inlineHtml += '<style>.mandatory{color:red;}</style>'; // Define alert window. inlineHtml += '<div class="container" style="margin-top:14px;" hidden><div id="danger-alert" class="alert alert-danger fade in"></div></div>'; // Define information window. inlineHtml += '<div class="container" hidden><p id="info" class="alert alert-info"></p></div>'; inlineHtml += tabsSection(customer_number, ticket_id, selector_number, selector_id, selector_type, status_value, customer_name, daytodayphone, daytodayemail, franchisee_name, zee_main_contact_name, zee_email, zee_main_contact_phone, zee_abn, date_stock_used, time_stock_used, final_delivery_text, selected_enquiry_status_id, attachments_hyperlink, owner_list, list_toll_issues, list_resolved_toll_issues, comment, date_created, creator_id, creator_name, status, customer_id, accountsphone, accountsemail, zee_id, list_enquiry_mediums, total_enquiry_count, chat_enquiry_count, phone_enquiry_count, email_enquiry_count, selected_label_id, maap_bank_account_number, maap_parent_bank_account_number, account_manager, list_toll_emails, customer_barcode_number, connote_number, receiveremail, receiverphone, receivername, receiverstate, receiverzip, receiversuburb, receiveraddr1, receiveraddr2, prod_stock_invoice, barcodempdl, barcodesource, list_mp_ticket_issues, list_resolved_mp_ticket_issues, list_invoice_issues, list_resolved_invoice_issues, selected_invoice_method_id, accounts_cc_email, mpex_po_number, customer_po_number, selected_invoice_cycle_id, terms, customer_terms, screenshot_file, browser, login_email_used, operating_system, phone_used, old_sender_name, old_sender_phone, phone_interaction_count, email_interaction_count, escalated_to_it); // inlineHtml += customerNumberSection(customer_number, ticket_id); // inlineHtml += selectorSection(ticket_id, selector_number, selector_id, selector_type, status_value); // if (!isNullorEmpty(ticket_id)) { // inlineHtml += ticketSection(dateISOToNetsuite(date_created), creator_id, creator_name, status); // } // if (isNullorEmpty(ticket_id) || (!isNullorEmpty(ticket_id) && !isNullorEmpty(customer_id)) || !isNullorEmpty(customer_number)) { // inlineHtml += customerSection(customer_name); // inlineHtml += daytodayContactSection(daytodayphone, daytodayemail, status_value, selector_type); // inlineHtml += accountsContactSection(accountsphone, accountsemail, status_value, selector_type); // } // if(isNullorEmpty(ticket_id) || (!isNullorEmpty(ticket_id) && (selector_type == 'invoice_section'))) { // inlineHtml += maapBankAccountSection(maap_bank_account_number, maap_parent_bank_account_number, selector_type); // } // if (isNullorEmpty(ticket_id) || (!isNullorEmpty(ticket_id) && !isNullorEmpty(zee_id)) || !isNullorEmpty(customer_number)) { // inlineHtml += franchiseeMainContactSection(franchisee_name, zee_main_contact_name, zee_email, zee_main_contact_phone, zee_abn); // } // inlineHtml += mpexStockUsedSection(selector_type, date_stock_used, time_stock_used); // inlineHtml += finalDeliveryEnquirySection(status_value, selector_type, final_delivery_text, selected_enquiry_status_id); // inlineHtml += attachmentsSection(attachments_hyperlink, status_value); // if (isNullorEmpty(ticket_id) || (!isNullorEmpty(ticket_id) && (selector_type == 'invoice_number'))) { // inlineHtml += otherInvoiceFieldsSection(selected_invoice_method_id, accounts_cc_email, mpex_po_number, customer_po_number, selected_invoice_cycle_id, terms, customer_terms, status_value, selector_type); // inlineHtml += openInvoicesSection(ticket_id, selector_type); // if (!isNullorEmpty(ticket_id)) { // inlineHtml += creditMemoSection(selector_type); // inlineHtml += usageReportSection(selector_type); // } // } // inlineHtml += mpexContactSection(); // inlineHtml += enquiryMediumSection(list_enquiry_mediums, selected_enquiry_status_id ,selector_type); // inlineHtml += enquiryCountSection(total_enquiry_count, chat_enquiry_count, phone_enquiry_count, email_enquiry_count); // inlineHtml += labelSection(selected_label_id, selector_type, status_value); // inlineHtml += sendEmailSection(ticket_id, status_value, account_manager,list_toll_emails); // log.debug({ title: 'before prev email - cust id', details: customer_id }); // if(!isNullorEmpty(customer_id)){ // inlineHtml += previousEmailsSection(customer_id); // } // inlineHtml += issuesHeader(); // inlineHtml += customerIssuesSection(ticket_id, selector_type, selector_number, screenshot_file, browser, login_email_used, operating_system, phone_used, old_sender_name, old_sender_phone, status_value); // if(selector_type == "barcode_number" || selector_type == "invoice_number"){ // inlineHtml += reminderSection(status_value); // } // inlineHtml += ownerSection(ticket_id, owner_list, status_value); // inlineHtml += tollIssuesSection(list_toll_issues, list_resolved_toll_issues, status_value, selector_type); // inlineHtml += mpTicketIssuesSection(list_mp_ticket_issues, list_resolved_mp_ticket_issues, status_value, selector_type); // inlineHtml += invoiceIssuesSection(list_invoice_issues, list_resolved_invoice_issues, status_value, selector_type); // inlineHtml += usernoteSection(selector_type, status_value); // inlineHtml += commentSection(comment, selector_type, status_value); // inlineHtml += dataTablePreview(); //inlineHtml += closeReopenSubmitTicketButton(ticket_id, status_value); form.addField({ id: 'preview_table', type: ui.FieldType.INLINEHTML, label: 'preview_table' }).defaultValue = inlineHtml; form.addField({ id: 'custpage_open_new_ticket', type: ui.FieldType.TEXT, label: 'Open New Ticket' }).updateDisplayType({ displayType: ui.FieldDisplayType.HIDDEN }).defaultValue = 'F'; log.debug({ title: 'Selector_number', details: selector_number }); form.addField({ id: 'custpage_selector_number', type: ui.FieldType.TEXT, label: 'Selector Number' }).updateDisplayType({ displayType: ui.FieldDisplayType.HIDDEN }).defaultValue = selector_number; form.addField({ id: 'custpage_selector_type', type: ui.FieldType.TEXT, label: 'Selector Type' }).updateDisplayType({ displayType: ui.FieldDisplayType.HIDDEN }).defaultValue = selector_type; if (!isNullorEmpty(ticket_id)) { form.addField({ id: 'custpage_ticket_id', type: ui.FieldType.TEXT, label: 'Ticket ID' }).updateDisplayType({ displayType: ui.FieldDisplayType.HIDDEN }).defaultValue = ticket_id; } else { form.addField({ id: 'custpage_ticket_id', type: ui.FieldType.TEXT, label: 'Ticket ID' }).updateDisplayType({ displayType: ui.FieldDisplayType.HIDDEN }); } form.addField({ id: 'custpage_selector_id', type: ui.FieldType.TEXT, label: 'Selector ID' }).updateDisplayType({ displayType: ui.FieldDisplayType.HIDDEN }).defaultValue = selector_id; form.addField({ id: 'custpage_selector_issue', type: ui.FieldType.TEXT, label: 'Barcode issue' }).updateDisplayType({ displayType: ui.FieldDisplayType.HIDDEN }).defaultValue = 'F'; form.addField({ id: 'custpage_customer_id', type: ui.FieldType.TEXT, label: 'Customer ID' }).updateDisplayType({ displayType: ui.FieldDisplayType.HIDDEN }).defaultValue = customer_id; form.addField({ id: 'custpage_customer_number', type: ui.FieldType.TEXT, label: 'Customer Number' }).updateDisplayType({ displayType: ui.FieldDisplayType.HIDDEN }).defaultValue = customer_number; form.addField({ id: 'custpage_zee_id', type: ui.FieldType.TEXT, label: 'Franchisee ID' }).updateDisplayType({ displayType: ui.FieldDisplayType.HIDDEN }).defaultValue = zee_id; form.addField({ id: 'custpage_ticket_status_value', type: ui.FieldType.TEXT, label: 'Status Value' }).updateDisplayType({ displayType: ui.FieldDisplayType.HIDDEN }).defaultValue = status_value; form.addField({ id: 'custpage_created_ticket', type: ui.FieldType.TEXT, label: 'Created Ticket' }).updateDisplayType({ displayType: ui.FieldDisplayType.HIDDEN }).defaultValue = 'F'; form.addField({ id: 'custpage_usage_report_array', type: ui.FieldType.TEXT, label: 'Usage Reports' }).updateDisplayType({ displayType: ui.FieldDisplayType.HIDDEN }).defaultValue = JSON.stringify(usage_report_array); form.addField({ id: 'custpage_param_email', type: ui.FieldType.TEXT, label: 'Email parameters' }).updateDisplayType({ displayType: ui.FieldDisplayType.HIDDEN }).defaultValue = JSON.stringify(params_email); form.addField({ id: 'custpage_ss_image', type: ui.FieldType.TEXT, label: 'Screenshot Image' }).updateDisplayType({ displayType: ui.FieldDisplayType.HIDDEN }).defaultValue = screenshot_file; form.addField({ id: 'custpage_customer_number_email_sent', type: ui.FieldType.TEXT, label: 'Customer Email Sent' }).updateDisplayType({ displayType: ui.FieldDisplayType.HIDDEN }).defaultValue = customer_number_email_sent; if (!isNullorEmpty(ticket_id)) { if (isTicketNotClosed(status_value)) { form.addSubmitButton({ label: 'Update Ticket' }); } // else { // form.addSubmitButton({ label: 'Reopen Ticket' }); // } } else { form.addSubmitButton({ label: 'Save Ticket' }); // form.addButton({ id: 'custpage_openandnew', label: 'Open & New Ticket', functionName: 'openAndNew()' }); // } // if (isTicketNotClosed(status_value)) { // form.addButton({ id: 'custpage_escalate', label: 'Escalate', functionName: 'onEscalate()' }); } // form.addButton({ id: 'custpage_cancel', label: 'Cancel', functionName: 'onCancel()' }); form.clientScriptFileId = 4813453;//SB=4796340 PROD=4813453 context.response.writePage(form); } else { log.debug({ title: "In else POST part", details: '' }); var created_ticket = context.request.parameters.custpage_created_ticket; log.debug({ title: "created_ticket", details: created_ticket }); var is_ss_changed = context.request.parameters.custpage_is_ss_changed; log.debug({ title: "is_ss_changed", details: is_ss_changed }); if (created_ticket == 'T') { var ticket_id = context.request.parameters.custpage_ticket_id; var selector_number = context.request.parameters.custpage_selector_number; var selector_type = context.request.parameters.custpage_selector_type; var open_new_ticket = context.request.parameters.custpage_open_new_ticket; if (open_new_ticket == 'T') { // If the ticket was just created, and the user clicked on 'Open & New Ticket', // The user is redirected to a new "Open Ticket" page. redirect.toSuitelet({ scriptId: 'customscript_sl_open_ticket_2', deploymentId: 'customdeploy_sl_open_ticket_2', parameters: params2 }); } else { custparam_params = { ticket_id: parseInt(ticket_id), selector_number: selector_number, selector_type: selector_type, } custparam_params = JSON.stringify(custparam_params); log.debug({ title: "custparams", details: custparam_params }); var params2 = { custparam_params: custparam_params }; // If the ticket was just created, the user is redirected to the "Edit Ticket" page redirect.toSuitelet({ scriptId: 'customscript_sl_open_ticket_2', deploymentId: 'customdeploy_sl_open_ticket_2', parameters: params2 }); } } else { var params_email = context.request.parameters.custpage_param_email; params_email = JSON.parse(params_email); var to = params_email.recipient; var email_subject = params_email.subject; var email_body = decodeURIComponent(params_email.body); var cc = null; var bcc = null var emailAttach = null; var attachments_credit_memo_ids = null; var attachments_usage_report_ids = null; var attachments_invoice_ids = null; var customer_id = context.request.parameters.custpage_customer_id; var open_new_ticket = context.request.parameters.custpage_open_new_ticket; if (!isNullorEmpty(params_email.cc)) { cc = params_email.cc; } if (!isNullorEmpty(params_email.bcc)) { bcc = params_email.bcc; } if (!isNullorEmpty(params_email.records)) { emailAttach = params_email.records; } var attachement_files = []; if (!isNullorEmpty(params_email.attachments_credit_memo_ids)) { attachments_credit_memo_ids = params_email.attachments_credit_memo_ids; attachments_credit_memo_ids.forEach(function(record_id) { render.transaction({ entityId: record_id, printMode: render.PrintMode.PDF, formId: number, inCustLocale: boolean }); }); } if (!isNullorEmpty(params_email.attachments_usage_report_ids)) { attachments_usage_report_ids = params_email.attachments_usage_report_ids; attachments_usage_report_ids.forEach(function(record_id) { attachement_files.push(file.load({ id: record_id })); }); } if (!isNullorEmpty(params_email.attachments_invoice_ids)) { attachments_invoice_ids = params_email.attachments_invoice_ids; attachments_invoice_ids.forEach(function(invoice_id) { render.transaction({ entityId: invoice_id, printMode: render.PrintMode.PDF, }) }); } // If the parameter is non null, it means that the "SEND EMAIL" button was clicked. if (!isNullorEmpty(attachement_files)) { try { email.send({ author: 112209, body: email_body, recipients: to, subject: email_subject, attachments: attachement_files, bcc: bcc, cc: cc, relatedRecords: { entityId: customer_id}, }); // 112209 is from MailPlus Team } catch (error) { if (error instanceof error.SuiteScriptError) { return error.name; } } } log.debug({ title: 'open_new_ticket', details: open_new_ticket }); if (open_new_ticket == 'T') { log.debug({ title: 'open ticket page', details: 'open ticket page' }) // If the ticket was just updated, and the user clicked on 'Updated & New Ticket', // The user is redirected to a new "Open Ticket" page. redirect.toSuitelet({ scriptId: 'customscript_sl_open_ticket_2', deploymentId: 'customdeploy_sl_open_ticket_2', }); } else { // If the ticket was updated, the user is redirected to the "View MP Tickets" page redirect.toSuitelet({ scriptId: 'customscript_sl_edit_ticket_2', deploymentId: 'customdeploy_sl_edit_ticket_2', }); } } } } function instructionsBox(ticket_id) { //Important Instructions box var inlineHtml = '<br></br>' inlineHtml += '<div></div>'; inlineHtml += '<div class="form-group container test_section">'; //inlineHtml += '<button type="button" class="btn btn-sm btn-info instruction_button" data-toggle="collapse" data-target="#demo">Click for Instructions</button>'; //inlineHtml += '<div id="demo" style="background-color: #cfeefc !important;border: 1px solid #417ed9;padding: 20px 30px 30px 30px;width:96%;position:absolute" class="collapse"><b><u>IMPORTANT INSTRUCTIONS:</u></b>'; inlineHtml += '<div style=\"background-color: #e3e8e5 !important;border: 2px solid #379E8F;padding: 20px 30px 30px 30px; text-align: left\"><b><u>Mandatory Fields:</u></b>'; inlineHtml += '<ul>'; inlineHtml += '<li><b><u>Ticket Details</u></b>: Total Enquiry Count must be at least 1 i.e. Chat/Email/Phone must have at least 1 incremented and Receiver Details should be filled in if blank</li>'; inlineHtml += '<li><b><u>Issues</u></b>: Owner and Toll Emails must have at least one selected</li>'; inlineHtml += '<li>If you have any issues, please contact Ankith</li>'; inlineHtml += '</ul></div></div><br/>'; return inlineHtml; } function externalBarcodeSource(selector_type, barcodempdl, barcodesource) { var disabled = 'disabled'; var inlineQty = ''; if (selector_type == 'barcode_number') { inlineQty += '<div class="form-group container barcode_section">'; inlineQty += '<div class="row">'; // MPLD field inlineQty += '<div class="col-xs-6 barcodempdl_div">'; inlineQty += '<div class="input-group">'; inlineQty += '<span class="input-group-addon" id="barcodempdl_text">EXTERNAL BARCODE</span>'; inlineQty += '<input id="barcodempdl" value="' + barcodempdl + '" class="form-control barcodempdl" ' + disabled + ' />'; inlineQty += '</div></div>'; // barcode source field inlineQty += '<div class="col-xs-6 barcodesource_div">'; inlineQty += '<div class="input-group">'; inlineQty += '<span class="input-group-addon" id="barcodesource_text">BARCODE SOURCE</span>'; inlineQty += '<input id="barcodesource" value="' + barcodesource + '" class="form-control barcodesource" ' + disabled + ' />'; inlineQty += '</div></div></div></div>'; } return inlineQty; } function tabsSection(customer_number, ticket_id, selector_number, selector_id, selector_type, status_value, customer_name, daytodayphone, daytodayemail, franchisee_name, zee_main_contact_name, zee_email, zee_main_contact_phone, zee_abn, date_stock_used, time_stock_used, final_delivery_text, selected_enquiry_status_id, attachments_hyperlink, owner_list, list_toll_issues, list_resolved_toll_issues, comment, date_created, creator_id, creator_name, status, customer_id, accountsphone, accountsemail, zee_id, list_enquiry_mediums, total_enquiry_count, chat_enquiry_count, phone_enquiry_count, email_enquiry_count, selected_label_id, maap_bank_account_number, maap_parent_bank_account_number, account_manager, list_toll_emails, customer_barcode_number, connote_number, receiveremail, receiverphone, receivername, receiverstate, receiverzip, receiversuburb, receiveraddr1, receiveraddr2, prod_stock_invoice, barcodempdl, barcodesource, list_mp_ticket_issues, list_resolved_mp_ticket_issues, list_invoice_issues, list_resolved_invoice_issues, selected_invoice_method_id, accounts_cc_email, mpex_po_number, customer_po_number, selected_invoice_cycle_id, terms, customer_terms, screenshot_file, browser, login_email_used, operating_system, phone_used, old_sender_name, old_sender_phone, phone_interaction_count, email_interaction_count, escalated_to_it) { var inlineQty = '<div style="margin-top: -10px"><br/>'; // BUTTONS if (!isNullorEmpty(ticket_id)) { if (isTicketNotClosed(status_value) && selector_type != "customer_issue") { inlineQty += '<button style="float: left; margin-left: 10px; margin-right: 5px; background-color: #FBEA51; color: #103D39; font-weight: 700; border-color: transparent; border-width: 2px; border-radius: 15px; height: 30px" type="button" id="updateticketbutton" onclick="">Update & New Ticket</button>'; inlineQty += '<button style="float: left; margin-left: 5x; margin-right: 5px; background-color: #FBEA51; color: #103D39; font-weight: 700; border-color: transparent; border-width: 2px; border-radius: 15px; height: 30px" type="button" id="updatecloseticketbutton" onclick="">Update & Close Ticket</button>'; } else if (!isTicketNotClosed(status_value)) { inlineQty += '<button style="float: left; margin-left: 10px; margin-right: 5px; background-color: #FBEA51; color: #103D39; font-weight: 700; border-color: transparent; border-width: 2px; border-radius: 15px; height: 30px" type="button" id="reopenticketbutton" onclick="">Reopen Ticket</button>'; } } else { //inlineQty += '<button style="float: left; margin-left: 10px; margin-right: 5px; background-color: #FBEA51; color: #103D39; font-weight: 700; border-color: transparent; border-width: 2px; border-radius: 15px; height: 30px" type="button" id="openticketbutton" onclick="">Save Ticket</button>'; inlineQty += '<button style="float: left; margin-left: 10px; margin-right: 5px; background-color: #FBEA51; color: #103D39; font-weight: 700; border-color: transparent; border-width: 2px; border-radius: 15px; height: 30px" type="button" id="opennewticketbutton" onclick="">Save & New Ticket</button>'; } if (isTicketNotClosed(status_value)) { if (!isNullorEmpty(ticket_id) && selector_type != "customer_issue") { inlineQty += '<button style="float: left; margin-left: 5px; margin-right: 5px; background-color: #f4524d; color: #fff; font-weight: 700; border-color: transparent; border-width: 2px; border-radius: 15px; height: 30px" type="button" id="closeticketbutton" onclick="">Close Ticket</button>'; inlineQty += '<button style="float: left; margin-left: 5px; margin-right: 5px; background-color: #f4524d; color: #fff; font-weight: 700; border-color: transparent; border-width: 2px; border-radius: 15px; height: 30px" type="button" id="closenewticketbutton" onclick="">Close & New Ticket</button>'; inlineQty += '<button style="float: left; margin-left: 5px; margin-right: 5px; background-color: #f4524d; color: #fff; font-weight: 700; border-color: transparent; border-width: 2px; border-radius: 15px; height: 30px" type="button" id="closelostbutton" onclick="">Close Ticket - Lost Item</button>'; if (userId == 409635 || userId == 696992 || userId == 766498) { inlineQty += '<button style="float: left; margin-left: 5px; margin-right: 5px; background-color: #FBEA51; color: #103D39; font-weight: 700; border-color: transparent; border-width: 2px; border-radius: 15px; height: 30px" type="button" id="closeunallocatedbutton" onclick="">Close Unallocated Ticket</button>'; } } else if (!isNullorEmpty(ticket_id) && !isNullorEmpty(escalated_to_it)) { inlineQty += '<button style="float: left; margin-left: 5px; margin-right: 5px; background-color: #f4524d; color: #fff; font-weight: 700; border-color: transparent; border-width: 2px; border-radius: 15px; height: 30px" type="button" id="closeresolvedbutton" onclick="">Close - Resolved Ticket</button>'; inlineQty += '<button style="float: left; margin-left: 5px; margin-right: 5px; background-color: #f4524d; color: #fff; font-weight: 700; border-color: transparent; border-width: 2px; border-radius: 15px; height: 30px" type="button" id="closeunresolvedbutton" onclick="">Close - Unresolved Ticket</button>'; } else { inlineQty += '<button style="float: left; margin-left: 5px; margin-right: 5px; background-color: #f4524d; color: #fff; font-weight: 700; border-color: transparent; border-width: 2px; border-radius: 15px; height: 30px" type="button" id="closeticketbutton" onclick="">Close Ticket</button>'; } } // ESCALATE AND CANCEL BUTTONS log.debug({ title: 'debugging', }); log.debug({ title: "selector_type", details: selector_type }); log.debug({ title: "isTicketNotClosed(status_value)", details: isTicketNotClosed(status_value) }); log.debug({ title: "!isNullorEmpty(ticket_id)", details: !isNullorEmpty(ticket_id) }); log.debug({ title: "userId", details: userId }); if (selector_type == "customer_issue" && isTicketNotClosed(status_value) && !isNullorEmpty(ticket_id) && isNullorEmpty(escalated_to_it)) { inlineQty += '<button style="float: left; margin-left: 5px; margin-right: 5px; background-color: #fc9003; color: #fff; font-weight: 700; border-color: transparent; border-width: 2px; border-radius: 15px; height: 30px" type="button" id="escalaterianne" onclick="">Escalate To IT</button>'; } else if (selector_type == "customer_issue" && isTicketNotClosed(status_value) && !isNullorEmpty(ticket_id) && !isNullorEmpty(escalated_to_it) && status_value != 10 && status_value != 17) { inlineQty += '<button style="float: left; margin-left: 5px; margin-right: 5px; background-color: #fc9003; color: #fff; font-weight: 700; border-color: transparent; border-width: 2px; border-radius: 15px; height: 30px" type="button" id="escalateankith" onclick="">Escalate To Ankith</button>'; } else if (selector_type == "customer_issue" && isTicketNotClosed(status_value) && !isNullorEmpty(ticket_id) && status_value == 10) { inlineQty += '<button style="float: left; margin-left: 5px; margin-right: 5px; background-color: #fc9003; color: #fff; font-weight: 700; border-color: transparent; border-width: 2px; border-radius: 15px; height: 30px" type="button" id="escalateunderdev" onclick="">Set Status to Under Development</button>'; } else if (selector_type == "customer_issue" && isTicketNotClosed(status_value) && !isNullorEmpty(ticket_id) && status_value == 17) { inlineQty += '<button style="float: left; margin-left: 5px; margin-right: 5px; background-color: #fc9003; color: #fff; font-weight: 700; border-color: transparent; border-width: 2px; border-radius: 15px; height: 30px" type="button" id="escalateremoveunderdev" onclick="">Remove Under Development Status</button>'; } else if (isTicketNotClosed(status_value) && !isNullorEmpty(ticket_id) && selector_type != "customer_issue") { inlineQty += '<button style="float: left; margin-left: 5px; margin-right: 5px; background-color: #379E8F; color: #fff; font-weight: 700; border-color: transparent; border-width: 2px; border-radius: 15px; height: 30px" type="button" id="escalatebutton" onclick="">' + escalateButton(status_value) + '</button>'; } if (!isNullorEmpty(ticket_id) && !isTicketNotClosed(status_value)) { inlineQty += '<button style="float: left; margin-left: 10px; margin-right: 5px; background-color: #FBEA51; color: #103D39; font-weight: 700; border-color: transparent; border-width: 2px; border-radius: 15px; height: 30px" type="button" id="cancelbutton" onclick="">Cancel</button>'; } else { inlineQty += '<button style="float: left; margin-left: 5px; margin-right: 5px; background-color: #FBEA51; color: #103D39; font-weight: 700; border-color: transparent; border-width: 2px; border-radius: 15px; height: 30px" type="button" id="cancelbutton" onclick="">Cancel</button>'; } // Title if (!isNullorEmpty(ticket_id)) { inlineQty += '<h1 style="display: inline-block; font-size: 25px; margin-top: 20px; font-weight: 700; color: #103D39; text-align: center; width: 100%">Edit Ticket - MPSD' + ticket_id + '</h1>' } else { inlineQty += '<h1 style="display: inline-block; font-size: 25px; font-weight: 700; color: #103D39; text-align: center; width: 100%">Open New Ticket</h1>' } inlineQty += instructionsBox(); // Tabs headers inlineQty += '<style>.nav > li.active > a, .nav > li.active > a:focus, .nav > li.active > a:hover { background-color: #379E8F; color: #fff }'; inlineQty += '.nav > li > a, .nav > li > a:focus, .nav > li > a:hover { margin-left: 5px; margin-right: 5px; border: 2px solid #379E8F; color: #379E8F; }'; inlineQty += '</style>'; // Ticket details header inlineQty += '<div class="form-group container tickets_details_header_section" style="margin-top: 10px">'; inlineQty += '<div class="row">'; inlineQty += '<div class="col-xs-12" >'; inlineQty += '<span">'; inlineQty += '<ul class="nav nav-pills nav-justified" style="margin:0%; ">'; inlineQty += '<li role="presentation" class="active"><a data-toggle="tab" href="#ticketdetails"><b>TICKET DETAILS</b></a></li>'; inlineQty += '<li role="presentation" class=""><a data-toggle="tab" href="#issues"><b>ISSUES</b></a></li>'; if (!isNullorEmpty(ticket_id)) { inlineQty += '<li role="presentation" class=""><a data-toggle="tab" href="#sendemail"><b>SEND EMAIL</b></a></li>'; } else { inlineQty += '<li role="presentation" class=""><a data-toggle="tab" href="#contactdetails"><b>CONTACT DETAILS</b></a></li>'; } if (!isNullorEmpty(ticket_id)) { inlineQty += '<li role="presentation" class=""><a data-toggle="tab" href="#prevtickets"><b>PREVIOUS TICKETS</b></a></li>'; inlineQty += '<li role="presentation" class=""><a data-toggle="tab" href="#prevemails"><b>PREVIOUS EMAILS</b></a></li>'; } //style="background-color: #379E8F" inlineQty += '</ul>'; inlineQty += '</span>'; inlineQty += '</div></div></div>'; // Tabs content inlineQty += '<div class="tab-content">'; // TICKET DETAILS TAB inlineQty += '<div role="tabpanel" class="tab-pane active" id="ticketdetails">'; inlineQty += customerNumberSection(customer_number, ticket_id, selector_type, escalated_to_it, creator_id); inlineQty += selectorSection(ticket_id, selector_number, selector_id, selector_type, status_value); if (!isNullorEmpty(ticket_id)) { inlineQty += ticketSection(dateISOToNetsuite(date_created), creator_id, creator_name, status, connote_number); inlineQty += externalBarcodeSource(selector_type, barcodempdl, barcodesource) } if (isNullorEmpty(ticket_id) || (!isNullorEmpty(ticket_id) && !isNullorEmpty(customer_id)) || !isNullorEmpty(customer_number)) { inlineQty += customerSection(customer_name); inlineQty += daytodayContactSection(daytodayphone, daytodayemail, status_value, selector_type); inlineQty += accountsContactSection(accountsphone, accountsemail, status_value, selector_type); } else if (isNullorEmpty(customer_number) && creator_id == 112209 && !isNullorEmpty(escalated_to_it) && selector_type == "customer_issue" && !isNullorEmpty(ticket_id)) { inlineQty += customerSection(customer_name); inlineQty += daytodayContactSection(daytodayphone, daytodayemail, status_value, selector_type); inlineQty += accountsContactSection(accountsphone, accountsemail, status_value, selector_type); } if(isNullorEmpty(ticket_id) || (!isNullorEmpty(ticket_id) && (selector_type == 'invoice_section'))) { inlineQty += maapBankAccountSection(maap_bank_account_number, maap_parent_bank_account_number, selector_type); } if (isNullorEmpty(ticket_id) || (!isNullorEmpty(ticket_id) && !isNullorEmpty(zee_id)) || !isNullorEmpty(customer_number)) { inlineQty += franchiseeMainContactSection(franchisee_name, zee_main_contact_name, zee_email, zee_main_contact_phone, zee_abn); } inlineQty += mpexStockUsedSection(selector_type, date_stock_used, time_stock_used); inlineQty += finalDeliveryEnquirySection(status_value, selector_type, final_delivery_text, selected_enquiry_status_id, prod_stock_invoice); inlineQty += attachmentsSection(attachments_hyperlink, status_value); if (isNullorEmpty(ticket_id) || (!isNullorEmpty(ticket_id) && (selector_type == 'invoice_number'))) { inlineQty += otherInvoiceFieldsSection(selected_invoice_method_id, accounts_cc_email, mpex_po_number, customer_po_number, selected_invoice_cycle_id, terms, customer_terms, status_value, selector_type); // inlineQty += enquiryMediumSection(list_enquiry_mediums, selected_enquiry_status_id, selector_type); // inlineQty += enquiryCountSection( total_enquiry_count, chat_enquiry_count, phone_enquiry_count, email_enquiry_count, selector_type); inlineQty += openInvoicesSection(ticket_id, selector_type); if (!isNullorEmpty(ticket_id)) { inlineQty += creditMemoSection(selector_type); inlineQty += usageReportSection(selector_type); } } inlineQty += enquiryMediumSection(list_enquiry_mediums, selected_enquiry_status_id, selector_type); inlineQty += enquiryCountSection( total_enquiry_count, chat_enquiry_count, phone_enquiry_count, email_enquiry_count, selector_type, phone_interaction_count, email_interaction_count); if(!isNullorEmpty(ticket_id)) { inlineQty += receiverEmailPhone(selector_type, receiveremail, receiverphone, receivername, receiverstate, receiverzip, receiversuburb, receiveraddr1, receiveraddr2); } //TICKET LABEL DROPDOWN //inlineQty += labelSection(selected_label_id, selector_type, status_value); inlineQty += '</div>'; // ISSUES TAB inlineQty += '<div role="tabpanel" class="tab-pane" id="issues">'; inlineQty += issuesHeader(); inlineQty += customerIssuesSection(ticket_id, selector_type, selector_number, screenshot_file, browser, login_email_used, operating_system, phone_used, old_sender_name, old_sender_phone, status_value); if(selector_type == "barcode_number" || selector_type == "invoice_number"){ inlineQty += reminderSection(status_value); } inlineQty += ownerSection(ticket_id, owner_list, status_value); inlineQty += tollIssuesSection(list_toll_issues, list_resolved_toll_issues, status_value, selector_type); inlineQty += mpTicketIssuesSection(list_mp_ticket_issues, list_resolved_mp_ticket_issues, status_value, selector_type); inlineQty += invoiceIssuesSection(list_invoice_issues, list_resolved_invoice_issues, status_value, selector_type); inlineQty += usernoteSection(selector_type, status_value); inlineQty += commentSection(comment, selector_type, status_value); inlineQty += '</div>'; // CONTACT / EMAILS if (!isNullorEmpty(ticket_id)) { inlineQty += '<div role="tabpanel" class="tab-pane" id="sendemail">'; inlineQty += mpexContactSection(); inlineQty += sendEmailSection(ticket_id, status_value, account_manager, list_toll_emails); //inlineQty += closeReopenSubmitTicketButton(ticket_id, status_value); inlineQty += '</div>'; } else { inlineQty += '<div role="tabpanel" class="tab-pane" id="contactdetails">'; inlineQty += mpexContactSection(); //inlineQty += closeReopenSubmitTicketButton(ticket_id, status_value); inlineQty += '</div>'; } // PREV TICKETS + EMAILS TAB if (!isNullorEmpty(ticket_id)) { // PREV TICKETS TAB inlineQty += '<div role="tabpanel" class="tab-pane" id="prevtickets">'; inlineQty += dataTablePreview(); //inlineQty += closeReopenSubmitTicketButton(ticket_id, status_value); inlineQty += '</div>'; inlineQty += '<div role="tabpanel" class="tab-pane" id="prevemails">'; log.debug({ title: 'before prev email - cust id', details: customer_id }); if(!isNullorEmpty(customer_id)){ inlineQty += previousEmailsSection(customer_id); } //inlineQty += closeReopenSubmitTicketButton(ticket_id, status_value); inlineQty += '</div>'; } inlineQty += '</div></div>'; return inlineQty; } /** * The "Customer number" input field. If there is a Ticket ID, then we are on the Edit Ticket page and * this field is pre-filled. * @param {*} customer_number */ function customerNumberSection(customer_number, ticket_id, selector_type, escalated_to_it, creator_id){ if(isNullorEmpty(customer_number)){ customer_number = ''; } // var disable = isNullorEmpty(ticket_id) ? '': 'disabled'; // Ticket details header var inlineQty = '<div class="form-group container tickets_details_header_section">'; inlineQty += '<div class="row">'; inlineQty += '<div class="col-xs-12 heading2" >'; inlineQty += '<h4><span style="background-color: #379E8F" class="label label-default col-xs-12">TICKET DETAILS</span></h4>'; inlineQty += '</div></div></div>'; // Customer number section inlineQty += '<div class="form-group container customer_number_section">'; inlineQty += '<div class="row">'; //Customer number field inlineQty += '<div class="col-xs-12 customer_number">'; inlineQty += '<div class="input-group">'; inlineQty += '<span class="input-group-addon" id="customer_number_text">CUSTOMER NUMBER</span>'; if(customer_number == '' && isNullorEmpty(ticket_id)){ inlineQty += '<input id="customer_number_value" value=" '+ customer_number +' " class="form-control customer_number">'; } else if (customer_number == '' && creator_id == 112209 && !isNullorEmpty(escalated_to_it) && selector_type == "customer_issue" && !isNullorEmpty(ticket_id)) { inlineQty += '<input id="customer_number_value" value=" '+ customer_number +' " class="form-control customer_number">'; } else{ inlineQty += '<input id="customer_number_value" value=" '+ customer_number +' " class="form-control customer_number" disabled>'; } inlineQty += '</div></div></div></div>'; //Datatable for all tickets asscoiated to current customer number inlineQty += '<div class="row">'; inlineQty += '<div class="form-group container customer_number_tickets">'; inlineQty += '<style> table {font-size: 12px;text-align: center;border: none;} {font-size: 14px;} table th{text-align: center;} .dataTables_wrapper{width:78%; margin-bottom:40px; margin-left: auto; margin-right: auto; margin-top: auto;} </style>'; inlineQty += '<table cellpadding="15" id="customer_number_tickets_preview" class="table table-responsive table-striped customer tablesorter" cellspacing="0" style="width: 100%;">'; inlineQty += '<thead style="color: white;background-color: #379E8F;">'; inlineQty += '<tr class="text-center">'; inlineQty += '</tr>'; inlineQty += '</thead></table>'; inlineQty += '</div></div>'; return inlineQty; } /** * The "Barcode number" OR "Invoice Number" input field. * If there is a TICKET ID, we are in the "Edit Ticket", so we display the Ticket ID field and the selector field is disabled. * @param {Number} ticket_id * @param {String} selector_number * @param {Number} selector_id * @param {String} selector_type * @param {Number} status_value * @return {String} inlineQty */ function selectorSection(ticket_id, selector_number, selector_id, selector_type, status_value) { if (isNullorEmpty(selector_number)) { selector_number = ''; } var inlineQty = '<div class="form-group container selector_section">'; inlineQty += '<div class="row">'; if (!isNullorEmpty(ticket_id)) { // Ticket ID field inlineQty += '<div class="col-xs-6 ticket_id">'; inlineQty += '<div class="input-group">'; inlineQty += '<span class="input-group-addon" id="ticket_id_text">TICKET ID</span>'; inlineQty += '<input id="ticket_id" value="MPSD' + ticket_id + '" class="form-control ticket_id" disabled />'; inlineQty += '</div></div>'; // Selector Number field inlineQty += '<div class="col-xs-6 selector_number">'; inlineQty += '<div class="input-group">'; switch (selector_type) { case 'barcode_number': inlineQty += '<span class="input-group-addon" id="selector_text">BARCODE NUMBER</span>'; break; case 'invoice_number': inlineQty += '<span class="input-group-addon" id="selector_text">INVOICE NUMBER</span>'; break; } inlineQty += '<input id="selector_value" value="' + selector_number + '" class="form-control selector_value" disabled>'; if (selector_type == 'invoice_number') { // Open Invoice record inlineQty += '<div class="input-group-btn">'; inlineQty += '<button id="open_inv" type="button" class="btn btn-default link_inv" data-inv-id="' + selector_id + '" data-toggle="tooltip" data-placement="top" title="Open Invoice">'; inlineQty += '<span class="glyphicon glyphicon-link"></span>'; inlineQty += '</button>'; inlineQty += '</div>'; // Attach Invoice to email if (isTicketNotClosed(status_value)) { inlineQty += '<div class="input-group-btn"><button style="background-color: #379E8F" id="add_inv" type="button" class="btn btn-success add_inv" data-inv-id="' + selector_id + '" data-toggle="tooltip" data-placement="right" title="Attach to email">'; inlineQty += '<span class="glyphicon glyphicon-plus"></span>'; inlineQty += '</button></div>'; } } inlineQty += '</div></div></div></div>'; } else { inlineQty += '<div class="col-xs-12 selector_number">'; inlineQty += '<div class="input-group">'; //Input group addon text switch (selector_type) { case 'barcode_number': inlineQty += '<span class="input-group-addon" id="selector_text">BARCODE NUMBER</span>'; break; case 'invoice_number': inlineQty += '<span class="input-group-addon" id="selector_text">INVOICE NUMBER</span>'; break; case 'customer_issue': inlineQty += '<span class="input-group-addon" id="selector_text">CUSTOMER ISSUE</span>'; break; } inlineQty += '<div class="input-group-btn">'; inlineQty += '<button tabindex="-1" data-toggle="dropdown" class="btn btn-default dropdown-toggle" type="button">'; inlineQty += '<span class="caret"></span>'; inlineQty += '<span class="sr-only">Toggle Dropdown</span>'; inlineQty += '</button>'; inlineQty += '<ul class="dropdown-menu hide" style="list-style:none;margin: 2px 0 0;">'; inlineQty += '<li><a href="#">BARCODE NUMBER</a></li>'; inlineQty += '<li><a href="#">INVOICE NUMBER</a></li>'; //inlineQty += '<li><a href="#">CUSTOMER APP</a></li>'; inlineQty += '<li><a href="#">CUSTOMER PORTAL</a></li>'; inlineQty += '<li><a href="#">UPDATE LABEL</a></li>'; inlineQty += '</ul>'; inlineQty += '</div>'; //Input text switch (selector_type) { case 'barcode_number': inlineQty += '<input id="selector_value" class="form-control selector_value" placeholder="MPEN123456">'; break; case 'invoice_number': inlineQty += '<input id="selector_value" class="form-control selector_value" placeholder="INV123456">'; break; case 'customer_app': inlineQty += '<input id="selector_value" class="form-control selector_value" placeholder="Customer App" disabled value="Customer App">'; break; case 'customer_portal': inlineQty += '<input id="selector_value" class="form-control selector_value" placeholder="Customer Portal" disabled value="Customer Portal">'; break; case 'update_label': inlineQty += '<input id="selector_value" class="form-control selector_value" placeholder="Update Label" disabled value="Update Label">'; break; } inlineQty += '</div></div></div></div>'; } return inlineQty; } /** * The informations regarding the ticket being edited. * @param {String} date_created * @param {Number} creator_id * @param {String} creator_name * @param {String} status * @return {String} inlineQty */ function ticketSection(date_created, creator_id, creator_name, status, connote_number) { if (isNullorEmpty(date_created)) { date_created = ''; } if (isNullorEmpty(creator_name)) { creator_name = ''; } if (isNullorEmpty(status)) { status = ''; } var inlineQty = '<div class="form-group container created_status_section">'; inlineQty += '<div class="row">'; // Date created field inlineQty += '<div class="col-xs-6 date_created">'; inlineQty += '<div class="input-group">'; inlineQty += '<span class="input-group-addon" id="date_created_text">DATE CREATED</span>'; inlineQty += '<input id="date_created" value="' + date_created + '" class="form-control date_created" disabled />'; inlineQty += '</div></div>'; // Creator field inlineQty += '<div class="col-xs-6 creator">'; inlineQty += '<div class="input-group">'; inlineQty += '<span class="input-group-addon" id="creator_text">CREATOR</span>'; inlineQty += '<input id="creator" value="' + creator_name + '" data-creator-id="' + creator_id + '" class="form-control creator" disabled />'; inlineQty += '</div></div></div></div>'; // Status Section inlineQty += '<div class="form-group container status_section">'; inlineQty += '<div class="row">'; // Status field inlineQty += '<div class="col-xs-6 status">'; inlineQty += '<div class="input-group">'; inlineQty += '<span class="input-group-addon" id="status_text">STATUS</span>'; inlineQty += '<input id="status" value="' + status + '" class="form-control status" disabled />'; inlineQty += '</div></div>'; // Customer Status field inlineQty += '<div class="col-xs-6 status">'; inlineQty += '<div class="input-group">'; inlineQty += '<span class="input-group-addon" id="status_text">CONNOTE NUMBER</span>'; inlineQty += '<input id="status" value="' + connote_number + '" class="form-control status" disabled />'; inlineQty += '</div></div></div></div>'; return inlineQty; } /** * The Customer name field. * The customer name field should be automatically filled based on the Selector number value. * @param {String} customer_name * @return {String} inlineQty */ function customerSection(customer_name) { if (isNullorEmpty(customer_name)) { customer_name = ''; } // Customer Section var inlineQty = '<div class="form-group container customer_section">'; inlineQty += '<div class="row">'; // Customer name field inlineQty += '<div class="col-xs-12 customer_name">'; inlineQty += '<div class="input-group">'; inlineQty += '<span class="input-group-addon" id="customer_name_text">CUSTOMER NAME</span>'; inlineQty += '<input id="customer_name" value="' + customer_name + '" class="form-control customer_name" disabled>'; inlineQty += '</div></div></div></div>'; return inlineQty; } /** * The day to day phone and email fields of the customer. * These fields should be automatically filled based on the Selector number value. * @param {String} daytodayphone * @param {String} daytodayemail * @param {Number} status_value * @param {String} selector_type * @return {String} inlineQty */ function daytodayContactSection(daytodayphone, daytodayemail, status_value, selector_type) { if (isNullorEmpty(daytodayphone)) { daytodayphone = ''; } if (isNullorEmpty(daytodayemail)) { daytodayemail = ''; } var disabled = 'disabled'; if ((isFinanceRole(userRole)) && isTicketNotClosed(status_value) && selector_type == 'invoice_number') { disabled = ''; } var inlineQty = '<div class="form-group container daytodaycontact_section">'; inlineQty += '<div class="row">'; // Day to day email field inlineQty += '<div class="col-xs-6 daytodayemail_div">'; inlineQty += '<div class="input-group">'; inlineQty += '<span class="input-group-addon" id="daytodayemail_text">DAY-TO-DAY EMAIL</span>'; inlineQty += '<input id="daytodayemail" type="email" value="' + daytodayemail + '" class="form-control daytodayemail" ' + disabled + ' />'; inlineQty += '<div class="input-group-btn">'; inlineQty += '<button type="button" style="background-color: #379E8F" class="btn btn-success add_as_recipient" data-email="' + daytodayemail + '" data-contact-id="" data-firstname="" data-toggle="tooltip" data-placement="right" title="Add as recipient">'; inlineQty += '<span class="glyphicon glyphicon-envelope"></span>'; inlineQty += '</button>'; inlineQty += '</div>'; inlineQty += '</div></div>'; // Day to day phone field inlineQty += '<div class="col-xs-6 daytodayphone_div">'; inlineQty += '<div class="input-group">'; inlineQty += '<span class="input-group-addon" id="daytodayphone_text">DAY-TO-DAY PHONE</span>'; inlineQty += '<input id="daytodayphone" type="tel" value="' + daytodayphone + '" class="form-control daytodayphone" ' + disabled + ' />'; inlineQty += '<div class="input-group-btn"><button type="button" style="background-color: #379E8F" class="btn btn-success" id="call_daytoday_phone"><span class="glyphicon glyphicon-earphone"></span></button></div>'; inlineQty += '</div></div></div></div>'; return inlineQty; } /** * The receiver phone and email fields. * These fields should be automatically filled based on the Selector number value. * @param {String} daytodayphone * @param {String} daytodayemail * @param {Number} status_value * @param {String} selector_type * @return {String} inlineQty */ function receiverEmailPhone(selector_type, receiveremail, receiverphone, receivername, receiverstate, receiverzip, receiversuburb, receiveraddr1, receiveraddr2) { var disabled = 'disabled'; if (isNullorEmpty(receiveremail) && isNullorEmpty(receiveraddr1) && isNullorEmpty(receiveraddr2) && isNullorEmpty(receivername) && isNullorEmpty(receiverphone) && isNullorEmpty(receiverstate) && isNullorEmpty(receiverzip) && isNullorEmpty(receiversuburb)) { disabled = ''; } var inlineQty = ''; if (selector_type == 'barcode_number') { // Receiver details header var inlineQty = '<div class="form-group container tickets_details_header_section">'; inlineQty += '<div class="row">'; inlineQty += '<div class="col-xs-12 heading2" >'; inlineQty += '<h4><span style="background-color: #379E8F" class="label label-default col-xs-12">RECEIVER DETAILS</span></h4>'; inlineQty += '</div></div></div>'; //First Row inlineQty += '<div class="form-group container receivercontact_section">'; inlineQty += '<div class="row">'; // name field inlineQty += '<div class="col-xs-4 receivername_div">'; inlineQty += '<div class="input-group">'; inlineQty += '<span class="input-group-addon" id="receivername_text">NAME</span>'; inlineQty += '<input id="receivername" value="' + receivername + '" class="form-control receivername" ' + disabled + ' />'; inlineQty += '</div></div>'; // Day to day phone field inlineQty += '<div class="col-xs-4 receiverphone_div">'; inlineQty += '<div class="input-group">'; inlineQty += '<span class="input-group-addon" id="receiverphone_text">PHONE</span>'; inlineQty += '<input id="receiverphone" type="tel" value="' + receiverphone + '" class="form-control receiverphone" ' + disabled + ' />'; inlineQty += '<div class="input-group-btn"><button type="button" style="background-color: #379E8F" class="btn btn-success" id="call_receiver_phone"><span class="glyphicon glyphicon-earphone"></span></button></div>'; inlineQty += '</div></div>'; // Day to day email field inlineQty += '<div class="col-xs-4 receiveremail_div">'; inlineQty += '<div class="input-group">'; inlineQty += '<span class="input-group-addon" id="receiveremail_text">EMAIL</span>'; inlineQty += '<input id="receiveremail" type="email" value="' + receiveremail + '" class="form-control receiveremail" ' + disabled + ' />'; inlineQty += '<div class="input-group-btn">'; inlineQty += '<button type="button" style="background-color: #379E8F" class="btn btn-success add_as_recipient" data-email="' + receiveremail + '" data-contact-id="" data-firstname="" data-toggle="tooltip" data-placement="right" title="Add as recipient">'; inlineQty += '<span class="glyphicon glyphicon-envelope"></span>'; inlineQty += '</button>'; inlineQty += '</div>'; inlineQty += '</div></div>'; inlineQty += '</div></div>'; //2nd Row inlineQty += '<div class="form-group container receivercontact2_section">'; inlineQty += '<div class="row">'; // address1 field inlineQty += '<div class="col-xs-6 receiveraddr1_div">'; inlineQty += '<div class="input-group">'; inlineQty += '<span class="input-group-addon" id="receiveraddr1_text">ADDRESS1</span>'; inlineQty += '<input id="receiveraddr1" value="' + receiveraddr1 + '" class="form-control receiveraddr1" ' + disabled + ' />'; inlineQty += '</div></div>'; // address2 field inlineQty += '<div class="col-xs-6 receiveraddr2_div">'; inlineQty += '<div class="input-group">'; inlineQty += '<span class="input-group-addon" id="receiveraddr2_text">ADDRESS2</span>'; inlineQty += '<input id="receiveraddr2" value="' + receiveraddr2 + '" class="form-control receiveraddr2" ' + disabled + ' />'; inlineQty += '</div></div>'; inlineQty += '</div></div>'; //3rd Row inlineQty += '<div class="form-group container receivercontact3_section">'; inlineQty += '<div class="row">'; // suburb field inlineQty += '<div class="col-xs-4 receiversuburb_div">'; inlineQty += '<div class="input-group">'; inlineQty += '<span class="input-group-addon" id="receiversuburb_text">SUBURB</span>'; inlineQty += '<input id="receiversuburb" value="' + receiversuburb + '" class="form-control receiversuburb" ' + disabled + ' />'; inlineQty += '</div></div>'; // postcode field inlineQty += '<div class="col-xs-4 receiverzip_div">'; inlineQty += '<div class="input-group">'; inlineQty += '<span class="input-group-addon" id="receiverzip_text">POSTCODE</span>'; inlineQty += '<input id="receiverzip" value="' + receiverzip + '" class="form-control receiverzip" ' + disabled + ' />'; inlineQty += '</div></div>'; // state field inlineQty += '<div class="col-xs-4 receiverstate_div">'; inlineQty += '<div class="input-group">'; inlineQty += '<span class="input-group-addon" id="receiverstate_text">STATE</span>'; inlineQty += '<input id="receiverstate" value="' + receiverstate + '" class="form-control receiverstate" ' + disabled + ' />'; inlineQty += '</div></div>'; inlineQty += '</div></div>'; } return inlineQty; } /** * The accounts phone and email fields of the customer. * These fields should be automatically filled based on the Invoice number value. * @param {String} accountsphone * @param {String} accountsemail * @param {Number} status_value * @param {String} selector_type * @return {String} inlineQty */ function accountsContactSection(accountsphone, accountsemail, status_value, selector_type) { if (isNullorEmpty(accountsphone)) { accountsphone = ''; } if (isNullorEmpty(accountsemail)) { accountsemail = ''; } if (selector_type == 'invoice_number') { var inlineQty = '<div class="form-group container accountscontact_section">'; if (isFinanceRole(userRole) && isTicketNotClosed(status_value)) { var disabled = ''; } else { var disabled = 'disabled'; } } else { var inlineQty = '<div class="form-group container accountscontact_section hide">'; var disabled = 'disabled'; } inlineQty += '<div class="row">'; // Accounts email field inlineQty += '<div class="col-xs-6 accountsemail_div">'; inlineQty += '<div class="input-group">'; inlineQty += '<span class="input-group-addon" id="accountsemail_text">ACCOUNTS EMAIL</span>'; inlineQty += '<input id="accountsemail" type="email" value="' + accountsemail + '" class="form-control accountsemail" ' + disabled + ' />'; inlineQty += '<div class="input-group-btn">'; inlineQty += '<button type="button" style="background-color: #379E8F" class="btn btn-success add_as_recipient" data-email="' + accountsemail + '" data-contact-id="" data-firstname="" data-toggle="tooltip" data-placement="right" title="Add as recipient">'; inlineQty += '<span class="glyphicon glyphicon-envelope"></span>'; inlineQty += '</button>'; inlineQty += '</div>'; inlineQty += '</div></div>'; // Accounts phone field inlineQty += '<div class="col-xs-6 accountsphone_div">'; inlineQty += '<div class="input-group">'; inlineQty += '<span class="input-group-addon" id="accountsphone_text">ACCOUNTS PHONE</span>'; inlineQty += '<input id="accountsphone" type="tel" value="' + accountsphone + '" class="form-control accountsphone" ' + disabled + ' />'; inlineQty += '<div class="input-group-btn"><button type="button" style="background-color: #379E8F" class="btn btn-success" id="call_accounts_phone"><span class="glyphicon glyphicon-earphone"></span></button></div>'; inlineQty += '</div></div></div></div>'; return inlineQty; } /** * * @param {Number} maap_bank_account_number * @param {Number} maap_parent_bank_account_number * @param {String} selector_type * @returns {String} inlineQty */ function maapBankAccountSection(maap_bank_account_number, maap_parent_bank_account_number, selector_type) { switch (selector_type) { case 'barcode_number': var inlineQty = '<div class="form-group container accounts_number_section hide">'; break; case 'invoice_number': var inlineQty = '<div class="form-group container accounts_number_section">'; break; } inlineQty += '<div class="row">'; // MAAP Bank Account # field inlineQty += '<div class="col-xs-6 account_number_div">'; inlineQty += '<div class="input-group">'; inlineQty += '<span class="input-group-addon" id="account_number_text">MAAP BANK ACCOUNT #</span>'; inlineQty += '<input id="account_number" type="number" value="' + maap_bank_account_number + '" class="form-control account_number" disabled />'; inlineQty += '</div></div>'; // MAAP Parent Bank Account # field inlineQty += '<div class="col-xs-6 parent_account_number_div">'; inlineQty += '<div class="input-group">'; inlineQty += '<span class="input-group-addon" id="parent_account_number_text">MAAP PARENT BANK ACCOUNT #</span>'; inlineQty += '<input id="parent_account_number" type="number" value="' + maap_parent_bank_account_number + '" class="form-control parent_account_number" disabled />'; inlineQty += '</div></div></div></div>'; return inlineQty; } /** * The Franchisee name, and its main contact name and phone number fields. * These fields should be automatically filled based on the Selector number value. * @param {String} franchisee_name * @param {String} zee_main_contact_name * @param {String} zee_email * @param {String} zee_main_contact_phone * @param {String} zee_abn * @return {String} inlineQty */ function franchiseeMainContactSection(franchisee_name, zee_main_contact_name, zee_email, zee_main_contact_phone, zee_abn) { if (isNullorEmpty(franchisee_name)) { franchisee_name = ''; } if (isNullorEmpty(zee_main_contact_name)) { zee_main_contact_name = ''; } if (isNullorEmpty(zee_email)) { zee_email = ''; } if (isNullorEmpty(zee_main_contact_phone)) { zee_main_contact_phone = ''; } if (isNullorEmpty(zee_abn)) { zee_abn = ''; } var inlineQty = '<div class="form-group container zee_main_contact_section">'; inlineQty += '<div class="row">'; // Franchisee name field inlineQty += '<div class="col-xs-6 franchisee_name">'; inlineQty += '<div class="input-group">'; inlineQty += '<span class="input-group-addon" id="franchisee_name_text">FRANCHISEE NAME</span>'; inlineQty += '<input id="franchisee_name" value="' + franchisee_name + '" class="form-control franchisee_name" disabled>'; inlineQty += '</div></div>'; // Franchisee main contact name field inlineQty += '<div class="col-xs-6 zee_main_contact_name">'; inlineQty += '<div class="input-group">'; inlineQty += '<span class="input-group-addon" id="zee_main_contact_name_text">MAIN CONTACT</span>'; inlineQty += '<input id="zee_main_contact_name" value="' + zee_main_contact_name + '" class="form-control zee_main_contact_name" disabled>'; inlineQty += '</div></div></div></div>'; // Franchisee contact details inlineQty += '<div class="form-group container zee_main_contact_section">'; inlineQty += '<div class="row">'; // Franchisee email field inlineQty += '<div class="col-xs-12 zee_email">'; inlineQty += '<div class="input-group">'; inlineQty += '<span class="input-group-addon" id="zee_email_text">FRANCHISEE EMAIL</span>'; inlineQty += '<input id="zee_email" type="email" value="' + zee_email + '" class="form-control accountsemail" disabled />'; inlineQty += '<div class="input-group-btn">'; var zee_contact_id = '0'; inlineQty += '<button type="button" style="background-color: #379E8F" class="btn btn-success add_as_recipient" data-email="' + zee_email + '" data-contact-id="' + zee_contact_id + '" data-firstname="' + franchisee_name + '" data-toggle="tooltip" data-placement="right" title="Add as recipient">'; inlineQty += '<span class="glyphicon glyphicon-envelope"></span>'; inlineQty += '</button>'; inlineQty += '</div>'; inlineQty += '</div></div></div></div>'; // Franchisee phone and ABN details inlineQty += '<div class="form-group container zee_main_contact_section">'; inlineQty += '<div class="row">'; // Franchisee main contact phone field inlineQty += '<div class="col-xs-6 zee_main_contact_phone">' inlineQty += '<div class="input-group">' inlineQty += '<span class="input-group-addon" id="zee_main_contact_phone_text">FRANCHISEE PHONE</span>'; inlineQty += '<input id="zee_main_contact_phone" type="tel" value="' + zee_main_contact_phone + '" class="form-control zee_main_contact_phone" disabled />'; inlineQty += '<div class="input-group-btn"><button style="background-color: #379E8F" type="button" class="btn btn-success" id="call_zee_main_contact_phone"><span class="glyphicon glyphicon-earphone"></span></button>'; inlineQty += '</div>'; inlineQty += '</div></div>'; // Franchisee ABN number inlineQty += '<div class="col-xs-6 zee_abn">' inlineQty += '<div class="input-group">' inlineQty += '<span class="input-group-addon" id="zee_abn_text">FRANCHISEE ABN</span>' inlineQty += '<input id="zee_abn" class="form-control zee_abn" value="' + zee_abn + '" disabled>' inlineQty += '</div></div></div></div>'; return inlineQty; } /** * The MPEX Date and Time Stock used fields. * Visible only for the barcode records. * @param {String} selector_type * @param {String} date_stock_used * @param {String} time_stock_used * @return {String} inlineQty */ function mpexStockUsedSection(selector_type, date_stock_used, time_stock_used) { if (isNullorEmpty(date_stock_used)) { date_stock_used = '' } if (isNullorEmpty(time_stock_used)) { time_stock_used = '' } var hide_class = (selector_type == 'barcode_number') ? '' : 'hide'; // MPEX Stock Used Section var inlineQty = '<div class="form-group container mpex_stock_used_section ' + hide_class + '">'; inlineQty += '<div class="row">'; // Date Stock Used inlineQty += ' <div class="col-xs-6 date_stock_used">'; inlineQty += '<div class="input-group">'; inlineQty += '<span class="input-group-addon" id="date_stock_used_text">DATE STOCK USED</span>'; inlineQty += '<input id="date_stock_used" class="form-control date_stock_used" value="' + date_stock_used + '" disabled>'; inlineQty += '</div></div>'; // Time Stock Used inlineQty += '<div class="col-xs-6 time_stock_used">'; inlineQty += '<div class="input-group">'; inlineQty += '<span class="input-group-addon" id="time_stock_used_text">TIME STOCK USED</span>'; inlineQty += '<input id="time_stock_used" class="form-control time_stock_used" value="' + time_stock_used + '" disabled>'; inlineQty += '</div></div></div></div>'; return inlineQty; } /** * The MPEX Final Delivery field is visible only for the barcode records. * The Enquiry Status field is not disabled only for the ticket that have not yet been opened. * @param {Number} status_value * @param {String} selector_type * @param {String} final_delivery_text * @param {Number} selected_enquiry_status_id * @return {String} inlineQty */ function finalDeliveryEnquirySection(status_value, selector_type, final_delivery_text, selected_enquiry_status_id, prod_stock_invoice) { if (isNullorEmpty(final_delivery_text)) { final_delivery_text = '' } if (isNullorEmpty(selected_enquiry_status_id)) { selected_enquiry_status_id = '' } var barcode_hide_class = (selector_type == 'barcode_number') ? '' : 'hide'; var nb_col_enquiry_section = (selector_type == 'barcode_number') ? '6' : '12'; var enquiry_disabled = (isTicketNotClosed(status_value)) ? '' : 'disabled'; // Final Delivery + Enquiry Status Section var inlineQty = '<div class="form-group container final_delivery_enquiry_status_section">'; inlineQty += '<div class="row">'; // Final Delivery inlineQty += '<div class="col-xs-6 final_delivery ' + barcode_hide_class + '">'; inlineQty += '<div class="input-group">'; inlineQty += '<span class="input-group-addon" id="final_delivery_text">FINAL DELIVERY</span>'; inlineQty += '<input id="final_delivery" class="form-control final_delivery" value="' + final_delivery_text + '" disabled>'; inlineQty += '</div></div>'; // Final Delivery inlineQty += '<div class="col-xs-6 invoice ' + barcode_hide_class + '">'; inlineQty += '<div class="input-group">'; inlineQty += '<span class="input-group-addon" id="invoice_text">INVOICE</span>'; inlineQty += '<input id="invoice" class="form-control invoice" value="' + prod_stock_invoice + '" disabled>'; inlineQty += '</div></div>'; inlineQty += '</div></div>'; return inlineQty; } /** * Ticket Label Section for if label on mpex was Printed or Handwritten * @param {Number} selected_label_id * @return {String} inlineQty */ function labelSection(selected_label_id, selector_type, status_value){ if (isNullorEmpty(selected_label_id)){ selected_label_id = ''; } var barcodeHideClass = (selector_type == 'barcode_number') ? '' : 'hide'; var labeldisabled = (isTicketNotClosed(status_value)) ? '' : 'disabled'; var inlineQty = '<div class="form-group container label_section '+ barcodeHideClass + '">'; inlineQty += '<div class="row">'; inlineQty += '<div class="col-xs-6 label_div">'; inlineQty += '<div class="input-group">'; inlineQty += '<span class="input-group-addon" id="label_text">TICKET LABEL</span>'; inlineQty += '<select id="label_status" class="form-control label_status" '+ labeldisabled+ '>'; inlineQty += '<option></option>'; var labelColumns = new Array(); labelColumns[0] = search.createColumn({ name: 'name' }); labelColumns[1] = search.createColumn({ name: 'internalId' }); var labelResultSet = search.create({ type: 'customlist_mp_ticket_label', columns: labelColumns, }); labelResultSet.run().each(function (labelResult) { var labelName = labelResult.getValue('name'); var labelId = labelResult.getValue('internalId'); if(selected_label_id == labelId) { inlineQty += '<option value="' + labelId + '"selected>' + labelName + '</option>'; }else{ inlineQty += '<option value="' + labelId + '">' + labelName + '</option>'; } return inlineQty; }); inlineQty += '</select>'; inlineQty += '</div></div></div></div>'; return inlineQty; } /** * Section containing enquiry medium type and the enquiry status of the ticket enquiry * @param list_enquiry_mediums {String}atus and * @param total_enquiry_count {Number} * @param selector_type {String} * @param status_value {Number} * @returns {string} */ function enquiryMediumSection(list_enquiry_mediums, selected_enquiry_status_id, selector_type){ //Search for enquiry mediums var hasEnquiryMediums = (!isNullorEmpty(list_enquiry_mediums)); var enquiryMediumColumns = new Array(); enquiryMediumColumns[0] = search.createColumn({ name: 'name' }); enquiryMediumColumns[1] = search.createColumn({ name: 'internalId' }); var enquiryMediumResultSet = search.create({ type: 'customlist_ticket_enquiry_mediums', columns: enquiryMediumColumns, }); //Ticket Enquiry Header // var inlineQty = '<div class="form-group container ticket_enquiry_header_section">'; // inlineQty += '<div class="row">'; // inlineQty += '<div class="col-xs-12 heading2">'; // inlineQty += '<h4><span style="background-color: #379E8F" class="label label-default col-xs-12">TICKET ENQUIRY DETAILS</span></h4>'; // inlineQty += '</div></div></div>'; //Enquiry Medium HTML var inlineQty = '<div class="form-group container enquiry_medium_section">'; inlineQty += '<div class="row">'; // inlineQty += '<div class="col-xs-6 enquiry_medium_div">'; // inlineQty += '<div class="input-group">'; // inlineQty += '<span class="input-group-addon" id="enquiry_medium_text">ENQUIRY MEDIUM</span>'; // inlineQty += '<select multiple id="enquiry_medium_status" class="form-control enquiry_medium_status" size="'+ enquiryMediumResultSet.length + '" disabled>'; // enquiryMediumResultSet.run().each(function (enquiryMediumResult) { // var enquiryMediumName = enquiryMediumResult.getValue('name'); // var enquiryMediumId = enquiryMediumResult.getValue('internalId'); // var selected = false; // if(hasEnquiryMediums){ // selected = (list_enquiry_mediums.indexOf(enquiryMediumId) !== -1); // } // if(selected) { // inlineQty += '<option value="' + enquiryMediumId + '"selected>' + enquiryMediumName + '</option>'; // }else{ // inlineQty += '<option value="' + enquiryMediumId + '">' + enquiryMediumName + '</option>'; // } // return true; // }); // inlineQty += '</select>'; // inlineQty += '</div></div>'; // Enquiry Status var enquiry_status_columns = new Array(); enquiry_status_columns[0] = search.createColumn({ name: 'name' }); enquiry_status_columns[1] = search.createColumn({ name: 'internalId' }); var enquiryStatusResultSet = search.create({ type: 'customlist_mp_ticket_enquiry', columns: enquiry_status_columns, }); inlineQty += '<div class="col-xs-6 enquiry_status_div">'; inlineQty += '<div class="input-group">'; inlineQty += '<span class="input-group-addon" id="enquiry_status_text">ENQUIRY STATUS</span>'; inlineQty += '<select id="enquiry_status" class="form-control enquiry_status">'; inlineQty += '<option></option>'; enquiryStatusResultSet.run().each(function (enquiryStatusResult) { var enquiry_status_name = enquiryStatusResult.getValue('name'); var enquiry_status_id = enquiryStatusResult.getValue('internalId'); if (enquiry_status_id == selected_enquiry_status_id) { inlineQty += '<option value="' + enquiry_status_id + '" selected>' + enquiry_status_name + '</option>'; } else { inlineQty += '<option value="' + enquiry_status_id + '">' + enquiry_status_name + '</option>'; } return true; }); inlineQty += '</select>'; inlineQty += '</div></div></div></div>'; return inlineQty; } /** * Section containing the total enquiry count and its breakdwn counts of chat, phone and email * @param total_enquiry_count * @param chat_enquiry_count * @param phone_enquiry_count * @param email_enquiry_count * @param selector_type * @returns {string} */ function enquiryCountSection( total_enquiry_count, chat_enquiry_count, phone_enquiry_count, email_enquiry_count, selector_type, phone_interaction_count, email_interaction_count){ if (isNullorEmpty(total_enquiry_count)) { total_enquiry_count = 0;} if (isNullorEmpty(chat_enquiry_count)) { chat_enquiry_count = 0;} if (isNullorEmpty(phone_enquiry_count)) { phone_enquiry_count = 0;} if (isNullorEmpty(email_enquiry_count)) { email_enquiry_count = 0;} if (isNullorEmpty(phone_interaction_count)) { phone_interaction_count = 0;} if (isNullorEmpty(email_interaction_count)) { email_interaction_count = 0;} //Total Enquiry Count HTML // var inlineQty = '<div class="form-group container enquiry_count_section">'; // inlineQty += '<div class="row">'; // inlineQty += '<div class="col-xs-12 total_enquiry_count_div">'; // inlineQty += '<div class="input-group">'; // inlineQty += '<span class="input-group-addon" id="total_enquiry_count_text">ENQUIRY COUNT</span>'; // inlineQty += '<input id="total_enquiry_count" class="form-control enquiry_count" value="' + total_enquiry_count + '" disabled />'; // inlineQty += '</div></div></div></div>'; //Enquiries by chat count var inlineQty = '<div class="form-group container enquiry_count_breakdown_section">'; inlineQty += '<div class="row">'; inlineQty += '<div class="col-xs-4 enquiry_count_by_chat">'; inlineQty += '<div class="input-group">'; inlineQty += '<span class="input-group-addon" id="enquiry_count_by_chat_text"> WEBSITE ENQUIRY </span>'; inlineQty += '<input id="enquiry_count_by_chat" value="' + chat_enquiry_count + '" class="form-control enquiry_count_by_chat" disabled>'; inlineQty += '<div class="input-group-btn">'; inlineQty += '<button type="button" style="background-color: #379E8F" class="btn btn-success increment_enquiry_count_by_chat" data-firstname="" data-toggle="tooltip" data-placement="right" title="Increment Chat Enquiry Count">'; inlineQty += '<span class="glyphicon glyphicon-plus"></span>'; inlineQty += '</button>'; inlineQty += '<button type="button" class="btn btn-danger decrement_enquiry_count_by_chat" data-firstname="" data-toggle="tooltip" data-placement="right" title="Decrement Chat Enquiry Count">'; inlineQty += '<span class="glyphicon glyphicon-minus"></span>'; inlineQty += '</button>'; inlineQty += '</div></div></div>'; inlineQty += '<div class="col-xs-4 enquiry_count_by_phone">'; inlineQty += '<div class="input-group">'; inlineQty += '<span class="input-group-addon" id="enquiry_count_by_phone_text"> PHONE ENQUIRY </span>'; inlineQty += '<input id="enquiry_count_by_phone" value="' + phone_enquiry_count + '" class="form-control enquiry_count_by_phone" disabled>'; inlineQty += '<div class="input-group-btn">'; inlineQty += '<button type="button" style="background-color: #379E8F" class="btn btn-success increment_enquiry_count_by_phone" data-firstname="" data-toggle="tooltip" data-placement="right" title="Increment Phone Enquiry Count">'; inlineQty += '<span class="glyphicon glyphicon-plus"></span>'; inlineQty += '</button>'; inlineQty += '<button type="button" class="btn btn-danger decrement_enquiry_count_by_phone" data-firstname="" data-toggle="tooltip" data-placement="right" title="Decrement Phone Enquiry Count">'; inlineQty += '<span class="glyphicon glyphicon-minus"></span>'; inlineQty += '</button>'; inlineQty += '</div></div></div>'; inlineQty += '<div class="col-xs-4 enquiry_count_by_email">'; inlineQty += '<div class="input-group">'; inlineQty += '<span class="input-group-addon" id="enquiry_count_by_email_text"> EMAIL ENQUIRY </span>'; inlineQty += '<input id="enquiry_count_by_email" value="' + email_enquiry_count + '" class="form-control enquiry_count_by_email" disabled>'; inlineQty += '<div class="input-group-btn">'; inlineQty += '<button type="button" style="background-color: #379E8F" class="btn btn-success increment_enquiry_count_by_email" data-firstname="" data-toggle="tooltip" data-placement="right" title="Increment Email Enquiry Count">'; inlineQty += '<span class="glyphicon glyphicon-plus"></span>'; inlineQty += '</button>'; inlineQty += '<button type="button" class="btn btn-danger decrement_enquiry_count_by_email" data-firstname="" data-toggle="tooltip" data-placement="right" title="Decrement Email Enquiry Count">'; inlineQty += '<span class="glyphicon glyphicon-minus"></span>'; inlineQty += '</button>'; inlineQty += '</div></div></div></div></div>'; if (selector_type == "customer_issue") { inlineQty += '<div class="form-group container interaction_count_breakdown_section">'; inlineQty += '<div class="row">'; inlineQty += '<div class="col-xs-6 interaction_count_by_phone">'; inlineQty += '<div class="input-group">'; inlineQty += '<span class="input-group-addon" id="interaction_count_by_phone_text"> PHONE INTERACTION </span>'; inlineQty += '<input id="interaction_count_by_phone" value="' + phone_interaction_count + '" class="form-control interaction_count_by_phone" disabled>'; inlineQty += '<div class="input-group-btn">'; inlineQty += '<button type="button" style="background-color: #379E8F" class="btn btn-success increment_interaction_count_by_phone" data-firstname="" data-toggle="tooltip" data-placement="right" title="Increment Phone Interaction Count">'; inlineQty += '<span class="glyphicon glyphicon-plus"></span>'; inlineQty += '</button>'; inlineQty += '<button type="button" class="btn btn-danger decrement_interaction_count_by_phone" data-firstname="" data-toggle="tooltip" data-placement="right" title="Decrement Phone interaction Count">'; inlineQty += '<span class="glyphicon glyphicon-minus"></span>'; inlineQty += '</button>'; inlineQty += '</div></div></div>'; inlineQty += '<div class="col-xs-6 interaction_count_by_email">'; inlineQty += '<div class="input-group">'; inlineQty += '<span class="input-group-addon" id="interaction_count_by_email_text"> EMAIL INTERACTION </span>'; inlineQty += '<input id="interaction_count_by_email" value="' + email_interaction_count + '" class="form-control interaction_count_by_email" disabled>'; inlineQty += '<div class="input-group-btn">'; inlineQty += '<button type="button" style="background-color: #379E8F" class="btn btn-success increment_interaction_count_by_email" data-firstname="" data-toggle="tooltip" data-placement="right" title="Increment Email Interaction Count">'; inlineQty += '<span class="glyphicon glyphicon-plus"></span>'; inlineQty += '</button>'; inlineQty += '<button type="button" class="btn btn-danger decrement_interaction_count_by_email" data-firstname="" data-toggle="tooltip" data-placement="right" title="Decrement Email Interaction Count">'; inlineQty += '<span class="glyphicon glyphicon-minus"></span>'; inlineQty += '</button>'; inlineQty += '</div></div></div></div></div>'; } return inlineQty; } /** * These fields should be displayed only for an Invoice ticket, and be edited only by the finance team. * - Invoice Method field * - Accounts cc email field * - MPEX PO # field * - Customer PO # field * - MPEX Invoicing Cycle field * @param {Number} selected_invoice_method_id * @param {String} accounts_cc_email * @param {String} mpex_po_number * @param {String} customer_po_number * @param {Number} selected_invoice_cycle_id * @param {Number} terms * @param {String} customer_terms * @param {Number} status_value * @param {String} selector_type * @return {String} inlineQty */ function otherInvoiceFieldsSection(selected_invoice_method_id, accounts_cc_email, mpex_po_number, customer_po_number, selected_invoice_cycle_id, terms, customer_terms, status_value, selector_type) { if (isNullorEmpty(accounts_cc_email)) { accounts_cc_email = '' } if (isNullorEmpty(mpex_po_number)) { mpex_po_number = '' } if (isNullorEmpty(customer_po_number)) { customer_po_number = '' } if (isNullorEmpty(customer_terms)) { customer_terms = '' } var invoice_method_columns = new Array(); invoice_method_columns[0] = search.createColumn({ name: 'name' }); invoice_method_columns[1] = search.createColumn({ name: 'internalId' }); var invoiceMethodResultSet = search.create({ type: 'customlist_invoice_method', columns: invoice_method_columns, }); switch (selector_type) { case 'barcode_number': var inlineQty = '<div class="form-group container invoice_method_accounts_cc_email_section hide">'; var disabled = 'disabled'; break; case 'invoice_number': var inlineQty = '<div class="form-group container invoice_method_accounts_cc_email_section">'; if (isFinanceRole(userRole) && isTicketNotClosed(status_value)) { var disabled = ''; } else { var disabled = 'disabled'; } break; } inlineQty += '<div class="row">'; // Invoice Method field inlineQty += '<div class="col-xs-6 invoice_method_div">'; inlineQty += '<div class="input-group">'; inlineQty += '<span class="input-group-addon" id="invoice_method_text">INVOICE METHOD</span>'; inlineQty += '<select id="invoice_method" class="form-control" ' + disabled + '>'; inlineQty += '<option></option>'; invoiceMethodResultSet.run().each(function(invoiceMethodResult) { var invoice_method_name = invoiceMethodResult.getValue('name'); var invoice_method_id = invoiceMethodResult.getValue('internalId'); if (invoice_method_id == selected_invoice_method_id) { inlineQty += '<option value="' + invoice_method_id + '" selected>' + invoice_method_name + '</option>'; } else { inlineQty += '<option value="' + invoice_method_id + '">' + invoice_method_name + '</option>'; } return true; }); inlineQty += '</select>'; inlineQty += '</div></div>'; // Accounts cc email field --> inlineQty += '<div class="col-xs-6 accounts_cc_email_div">'; inlineQty += '<div class="input-group">'; inlineQty += '<span class="input-group-addon" id="accounts_cc_email_text">ACCOUNTS CC EMAIL</span>'; inlineQty += '<input id="accounts_cc_email" type="email" value="' + accounts_cc_email + '" class="form-control accounts_cc_email" ' + disabled + '/>'; inlineQty += '<div class="input-group-btn">'; inlineQty += '<button type="button" style="background-color: #379E8F" class="btn btn-success add_as_recipient" data-email="' + accounts_cc_email + '" data-contact-id="" data-firstname="" data-toggle="tooltip" data-placement="right" title="Add as recipient">'; inlineQty += '<span class="glyphicon glyphicon-envelope"></span>'; inlineQty += '</button>'; inlineQty += '</div>'; inlineQty += '</div></div></div></div>'; switch (selector_type) { case 'barcode_number': inlineQty += '<div class="form-group container mpex_customer_po_number_section hide">'; break; case 'invoice_number': inlineQty += '<div class="form-group container mpex_customer_po_number_section">'; break; } inlineQty += '<div class="row">'; // MPEX PO # inlineQty += '<div class="col-xs-6 mpex_po_number_div">'; inlineQty += '<div class="input-group">'; inlineQty += '<span class="input-group-addon" id="mpex_po_number_text">MPEX PO #</span>'; inlineQty += '<input id="mpex_po_number" value="' + mpex_po_number + '" class="form-control mpex_po_number" ' + disabled + '/>'; inlineQty += '</div></div>'; // Customer PO # inlineQty += '<div class="col-xs-6 customer_po_number_div">'; inlineQty += '<div class="input-group">'; inlineQty += '<span class="input-group-addon" id="customer_po_number_text">CUSTOMER PO #</span>'; inlineQty += '<input id="customer_po_number" value="' + customer_po_number + '" class="form-control customer_po_number" ' + disabled + '/>'; inlineQty += '</div></div></div></div>'; // Terms fields switch (selector_type) { case 'barcode_number': inlineQty += '<div class="form-group container terms_section hide">'; break; case 'invoice_number': inlineQty += '<div class="form-group container terms_section">'; break; } inlineQty += '<div class="row">'; // Terms inlineQty += '<div class="col-xs-6 terms_div">'; inlineQty += '<div class="input-group">'; inlineQty += '<span class="input-group-addon" id="terms_text">TERMS</span>'; // Find the text related to the terms value. var terms_options = [{ "value": "", "text": "" }, { "value": "5", "text": "1% 10 Net 30" }, { "value": "6", "text": "2% 10 Net 30" }, { "value": "4", "text": "Due on receipt" }, { "value": "1", "text": "Net 15 Days" }, { "value": "2", "text": "Net 30 Days" }, { "value": "8", "text": "Net 45 Days" }, { "value": "3", "text": "Net 60 Days" }, { "value": "7", "text": "Net 7 Days" }, { "value": "9", "text": "Net 90 Days" }]; var terms_option = findObjectByKey(terms_options, "value", terms); var terms_text = isNullorEmpty(terms_option) ? '' : terms_option.text; inlineQty += '<input id="terms" class="form-control terms" value="' + terms_text + '" disabled/>'; inlineQty += '</div></div>'; // Customer's terms inlineQty += '<div class="col-xs-6 customers_terms_div">'; inlineQty += '<div class="input-group">'; inlineQty += '<span class="input-group-addon" id="customers_terms_text">' + "CUSTOMER'S TERMS</span>"; inlineQty += '<input id="customers_terms" class="form-control customers_terms" value="' + customer_terms + '" ' + disabled + '/>'; inlineQty += '</div></div></div></div>'; // MPEX Invoicing Cycle var invoice_cycle_columns = new Array(); invoice_cycle_columns[0] = search.createColumn({ name: 'name' }); invoice_cycle_columns[1] = search.createColumn({ name: 'internalId' }); var invoiceCycleResultSet = search.create({ type: 'customlist_invoicing_cyle', columns: invoice_cycle_columns, }) switch (selector_type) { case 'barcode_number': inlineQty += '<div class="form-group container mpex_invoicing_cycle_section hide">'; break; case 'invoice_number': inlineQty += '<div class="form-group container mpex_invoicing_cycle_section">'; break; } inlineQty += '<div class="row">'; inlineQty += '<div class="col-xs-12 mpex_invoicing_cycle_div">'; inlineQty += '<div class="input-group">'; inlineQty += '<span class="input-group-addon" id="mpex_invoicing_cycle_text">MPEX INVOICING CYCLE</span>'; inlineQty += '<select id="mpex_invoicing_cycle" class="form-control mpex_invoicing_cycle" ' + disabled + '>'; inlineQty += '<option></option>'; invoiceCycleResultSet.run().each(function (invoiceCycleResult) { var invoice_cycle_name = invoiceCycleResult.getValue('name'); var invoice_cycle_id = invoiceCycleResult.getValue('internalId'); if (invoice_cycle_id == selected_invoice_cycle_id) { inlineQty += '<option value="' + invoice_cycle_id + '" selected>' + invoice_cycle_name + '</option>'; } else { inlineQty += '<option value="' + invoice_cycle_id + '">' + invoice_cycle_name + '</option>'; } return true; }); inlineQty += '</select>'; inlineQty += '</div></div></div></div>'; return inlineQty; } /** * The Attachments field (an editable hyperlink) * @param {String} attachments_hyperlink * @param {Number} status_value * @returns {String} inlineQty */ function attachmentsSection(attachments_hyperlink, status_value) { if (isNullorEmpty(attachments_hyperlink)) { attachments_hyperlink = '' } var disabled = (isTicketNotClosed(status_value)) ? '' : 'disabled'; var inlineQty = '<div class="form-group container attachments_section">'; inlineQty += '<div class="row">'; inlineQty += '<div class="col-xs-12 attachments_div">'; inlineQty += '<div class="input-group">'; inlineQty += '<span class="input-group-addon" id="attachments_text">ATTACHMENTS</span>' inlineQty += '<input id="attachments" class="form-control attachments" type="url" value="' + attachments_hyperlink + '" ' + disabled + '/>'; inlineQty += '</div></div></div></div>'; return inlineQty; } /** * The customer contact details section. * Possibility for the user to add / edit the contacts. * @return {String} inlineQty */ function mpexContactSection() { // Contact details header var inlineQty = '<div class="form-group container mpex_contact_section">'; inlineQty += '<div class="row">'; inlineQty += '<div class="col-xs-12 heading2">'; inlineQty += '<h4><span style="background-color: #379E8F" class="label label-default col-xs-12">CONTACT DETAILS</span></h4>'; inlineQty += '</div>'; inlineQty += '</div></div>'; // Contact table inlineQty += '<div class="form-group container contacts_section" style="font-size: small;">'; inlineQty += '<div class="row">'; inlineQty += '<div class="col-xs-12 contacts_div">'; // Since the table is not displayed correctly when added through suitelet, // It is added with jQuery in the pageInit() function in the client script 'mp_cl_open_ticket.js'. inlineQty += '</div>'; inlineQty += '</div>'; inlineQty += '</div>'; // Add/edit contacts button inlineQty += '<div class="form-group container reviewcontacts_section">'; inlineQty += '<div class="row">'; inlineQty += '<div class="col-xs-4 col-xs-offset-4 reviewcontacts">'; inlineQty += '<input type="button" style="background-color: #379E8F; border-color: #379E8F; font-weight: 700" value="ADD/EDIT CONTACTS" class="form-control btn btn-primary" id="reviewcontacts" />'; inlineQty += '</div></div></div>'; return inlineQty; }; /** * A Datatable displaying the open invoices of the customer * @param {Number} ticket_id * @param {String} selector_type * @return {String} inlineQty */ function openInvoicesSection(ticket_id, selector_type) { if (isNullorEmpty(ticket_id)) { ticket_id = '' } var hide_class_section = (isNullorEmpty(ticket_id) || selector_type != 'invoice_number') ? 'hide' : ''; // Open invoices header var inlineQty = '<div class="form-group container open_invoices open_invoices_header ' + hide_class_section + '">'; inlineQty += '<div class="row">'; inlineQty += '<div class="col-xs-12 heading2">'; inlineQty += '<h4><span style="background-color: #379E8F" class="label label-default col-xs-12">OPEN INVOICES</span></h4>'; inlineQty += '</div></div></div>'; // Open invoices dropdown field inlineQty += '<div class="form-group container open_invoices invoices_dropdown ' + hide_class_section + '">'; inlineQty += '<div class="row">'; inlineQty += '<div class="col-xs-12 invoices_dropdown_div">'; inlineQty += '<div class="input-group">'; inlineQty += '<span class="input-group-addon" id="invoices_dropdown_text">INVOICE STATUS</span>'; inlineQty += '<select id="invoices_dropdown" class="form-control">'; inlineQty += '<option value="open" selected>Open</option>'; inlineQty += '<option value="paidInFull">Paid In Full (last 3 months)</option>'; inlineQty += '</select>'; inlineQty += '</div></div></div></div>'; // Open Invoices Datatable //inlineQty += '<div class="form-group container open_invoices open_invoices_datatable>'; //inlineQty += '</div>'; inlineQty += '<div class="form-group open_invoices open_invoices_table ' + hide_class_section + '">'; inlineQty += dataTable(); // inlineQty += '<div class="row">'; // inlineQty += '<div class="col-xs-18" id="open_invoice_dt_div">'; // // It is inserted as inline html in the script mp_cl_open_ticket // inlineQty += '</div></div></div>'; inlineQty += '</div>' return inlineQty; } function dataTable() { var inlineQty = '<style>table#invoices-preview {font-size: 12px;text-align: center;border: none;}.dataTables_wrapper {font-size: 14px;}table#invoices-preview th{text-align: center;} .bolded{font-weight: bold;}</style>'; inlineQty += '<table id="invoices-preview" class="table table-responsive table-striped customer tablesorter" style="width: 100%; table-layout: fixed">'; inlineQty += '<thead style="color: white;background-color: #379E8F;">'; inlineQty += '<tr class="text-center">'; inlineQty += '</tr>'; inlineQty += '</thead>'; inlineQty += '<tbody id="result_invoices"></tbody>'; inlineQty += '</table>'; return inlineQty; } /** * The Credit Memo Section. * Displays a table of the credit memos linked to the invoice. * Possibility to attach the credit memo PDF to the email. * @param {String} selector_type * @return {String} inlineQty */ function creditMemoSection(selector_type) { var inlineQty = ''; if (selector_type == 'invoice_number') { // Credit Memo Header inlineQty += '<div class="form-group container credit_memo credit_memo_header">'; inlineQty += '<div class="row">'; inlineQty += '<div class="col-xs-12 heading2">'; inlineQty += '<h4><span style="background-color: #379E8F" class="label label-default col-xs-12">CREDIT MEMO</span></h4>'; inlineQty += '</div></div></div>'; // Credit Memo table inlineQty += '<div class="form-group container credit_memo credit_memo_section" style="font-size: small;">'; inlineQty += '<div class="row">'; inlineQty += '<div class="col-xs-12 credit_memo_div">'; // Since the table is not displayed correctly when added through suitelet, // It is added with jQuery in the pageInit() function in the client script 'mp_cl_open_ticket.js'. inlineQty += '</div></div></div>'; } return inlineQty; } function usageReportSection(selector_type) { var inlineQty = ''; if (selector_type == 'invoice_number') { // Usage Report Header inlineQty += '<div class="form-group container usage_report usage_report_header">'; inlineQty += '<div class="row">'; inlineQty += '<div class="col-xs-12 heading2">'; inlineQty += '<h4><span style="background-color: #379E8F" class="label label-default col-xs-12">USAGE REPORT</span></h4>'; inlineQty += '</div></div></div>'; // Usage Report table inlineQty += '<div class="form-group container usage_report usage_report_section" style="font-size: small;">'; inlineQty += '<div class="row">'; inlineQty += '<div class="col-xs-12 usage_report_div">'; // Since the table is not displayed correctly when added through suitelet, // It is added with jQuery in the pageInit() function in the client script 'mp_cl_open_ticket.js'. inlineQty += '</div></div></div>'; } return inlineQty; } /** * The "Send Email" section. * Possibility for the user to send an email to the customer, based on selected templates. * @param {Number} ticket_id * @param {Number} status_value * @param {Object} account_manager * @returns {String} inlineQty */ function sendEmailSection(ticket_id, status_value, account_manager, list_toll_emails) { var has_toll_emails = (!isNullorEmpty(list_toll_emails)); if (isNullorEmpty(ticket_id) || !isTicketNotClosed(status_value)) { // The section is hidden here rather than in the openTicket function, // because we use the section to send an acknoledgement email when a ticket is opened. var inlineQty = '<div id="send_email_container" class="send_email hide">'; } else { var inlineQty = '<div id="send_email_container" class="send_email">'; } // inlineQty += '<div class="form-group container send_email header_section">'; // // Send email header // inlineQty += '<div class="row">'; // inlineQty += '<div class="col-xs-12 heading2">'; // inlineQty += '<h4><span style="background-color: #379E8F" class="label label-default col-xs-12">SEND EMAILS</span></h4>'; // inlineQty += '</div></div></div>'; inlineQty += '<br></br>' // Row addressees inlineQty += '<div class="form-group container send_email adressees_section">'; inlineQty += '<div class="row">'; inlineQty += '<div class="col-xs-12 to_section">'; inlineQty += '<div class="input-group">'; inlineQty += '<span class="input-group-addon">TO<span class="mandatory">*</span></span>'; inlineQty += '<input id="send_to" class="form-control" data-contact-id="" data-firstname=""/>'; inlineQty += '</div></div></div></div>'; // Toll addresses var toll_emails_columns = new Array(); toll_emails_columns[0] = search.createColumn({ name: 'name' }); toll_emails_columns[1] = search.createColumn({ name: 'internalId' }); var tollEmailsResultSet = search.create({ type: 'customlist_toll_emails', columns: toll_emails_columns, }) inlineQty += '<div class="form-group container send_email toll_adressees_section">'; inlineQty += '<div class="row">'; inlineQty += '<div class="col-xs-12 toll_section">'; inlineQty += '<div class="input-group">'; inlineQty += '<span class="input-group-addon">TOLL EMAILS</span>'; inlineQty += '<select multiple id="send_toll" class="form-control" size="' + tollEmailsResultSet.length + '"/>'; tollEmailsResultSet.run().each(function (tollEmailsResultSet){ var tollEmailName = tollEmailsResultSet.getValue('name'); var tollEmailId = tollEmailsResultSet.getValue('internalId'); var selected = false; if(has_toll_emails) { selected = (list_toll_emails.indexOf(tollEmailId) !== -1); } if (selected) { inlineQty += '<option value="' + tollEmailId + '" selected>' + tollEmailName + '</option>'; } else { inlineQty += '<option value="' + tollEmailId + '">' + tollEmailName + '</option>'; } return true; }); inlineQty += '</select>'; inlineQty += '</div></div></div></div>'; // Row ccs addresses inlineQty += '<div class="form-group container send_email cc_adressees_section">'; inlineQty += '<div class="row">'; inlineQty += '<div class="col-xs-6 cc_section">'; inlineQty += '<div class="input-group">'; inlineQty += '<span class="input-group-addon">CC</span>'; inlineQty += '<input id="send_cc" class="form-control"/>'; inlineQty += '</div></div>'; inlineQty += '<div class="col-xs-6 bcc_section">'; inlineQty += '<div class="input-group">'; inlineQty += '<span class="input-group-addon">BCC</span>'; inlineQty += '<input id="send_bcc" class="form-control"/>'; inlineQty += '</div></div></div></div>'; // Row account manager if (isNullorEmpty(account_manager.name)) { account_manager.name = '' } if (isNullorEmpty(account_manager.email)) { account_manager.email = '' } if (!isNullorEmpty(account_manager.email.email)) { inlineQty += '<div class="form-group container send_email acc_manager_section">'; inlineQty += '<div class="row">'; inlineQty += '<div class="col-xs-10 acc_manager_name_section">'; inlineQty += '<div class="input-group">'; inlineQty += '<span class="input-group-addon">ACCOUNT MANAGER</span>'; inlineQty += '<input id="acc_manager" class="form-control" data-email="' + account_manager.email.email + '" value="' + account_manager.name + ' - ' + account_manager.email.email + '" disabled/>'; inlineQty += '</div></div>'; inlineQty += '<div class="col-xs-2 acc_manager_button_section">'; inlineQty += '<button id="acc_manager_button" style="background-color: #379E8F; border-color: #379E8F" type="button" class="btn btn-success btn-block">ADD TO CC</button>'; inlineQty += '</div></div></div>'; } // Row Template inlineQty += '<div class="form-group container send_email template_section">'; inlineQty += '<div class="row">'; inlineQty += '<div class="col-xs-12 template_section">'; inlineQty += '<div class="input-group">'; inlineQty += '<span class="input-group-addon">TEMPLATE<span class="mandatory">*</span></span>'; inlineQty += '<select id="template" class="form-control">'; inlineQty += '<option></option>'; // Load the template options var templatesSearch = search.load({ id: 'customsearch_cctemplate_mp_ticket', type: 'customrecord_camp_comm_template' }); var templatesSearchResults = templatesSearch.run(); templatesSearchResults.each(function(templatesSearchResult) { // var tempId = templatesSearchResult.getValue('internalid'); var tempId = templatesSearchResult["id"]; var tempName = templatesSearchResult.getValue('name'); inlineQty += '<option value="' + tempId + '">' + tempName + '</option>'; return true; }); inlineQty += '</select>'; inlineQty += '</div></div></div></div>'; // Row Subject inlineQty += '<div class="form-group container send_email subject_section">'; inlineQty += '<div class="row">'; inlineQty += '<div class="col-xs-12 subject_section">'; inlineQty += '<div class="input-group">'; inlineQty += '<span class="input-group-addon">SUBJECT<span class="mandatory">*</span></span>'; inlineQty += '<input id="subject" class="form-control" />'; inlineQty += '</div></div></div></div>'; // Row Body inlineQty += '<div class="form-group container send_email body_section">'; inlineQty += '<div class="row">'; inlineQty += '<div class="col-xs-12 body_section">'; inlineQty += '<div id="email_body"></div>'; inlineQty += '</div></div></div>'; // SEND EMAIL button inlineQty += '<div class="form-group container send_email button_section">'; inlineQty += '<div class="row">'; inlineQty += '<div class="col-xs-4 col-xs-offset-4 send_email_btn">'; inlineQty += '<input type="button" style="background-color: #379E8F; border-color: #379E8F; font-weight: 700" value="SEND EMAIL" class="form-control btn btn-primary" id="send_email" />'; inlineQty += '</div></div></div></div>'; return inlineQty; }; /** * Section for the previous emails datatable * @param customer_id * @returns {string} */ function previousEmailsSection(customer_id){ var customerRecord = record.load({ type: record.Type.CUSTOMER, id: customer_id, }); var customer_internal_id = customerRecord.getValue({ fieldId: 'id' }); // Previous Emails header var inlineQty = '<div class="form-group container previous_emails_header">'; inlineQty += '<div class="row">'; inlineQty += '<div class="col-xs-12 heading2">'; inlineQty += '<h4><span style="background-color: #379E8F" class="label label-default col-xs-12">PREVIOUS EMAILS</span></h4>'; inlineQty += '</div></div></div>'; //Searching emails filtered by - internal customer id and dated before the lastmonthonefiscalquarterago (i.e. the past three months) var emailSearch = search.load({ type: 'message', id: 'customsearch_all_messages' }); var emailSearchFilter = [["customer.internalid","anyof",customer_internal_id], "AND", ["messagedate", "after", "lastmonthonefiscalquarterago"]]; //670041, 313070 emailSearch.filterExpression = emailSearchFilter; var resultEmailSet = emailSearch.run(); var allEmails = resultEmailSet.getRange({ start: 0, end: 1000 }); //Previous Emails table setup // inlineQty += '<style> table {font-size: 12px;text-align: center;border: none;} {font-size: 14px;} table th{text-align: center;} .dataTables_wrapper{width:78%; margin:auto;} </style>'; // inlineQty += '<div class="form-group container previous_emails_section">'; // inlineQty += '<table cellpadding="15" id="emails-preview" class="table table-responsive table-striped customer tablesorter" cellspacing="0" style="width: 100%;">'; // inlineQty += '<thead style="color: white;background-color: #CFE0CE;">'; // inlineQty += '<tr class="text-center">'; // inlineQty += '<th scope="col">Message Date</th>'; // inlineQty += '<th scope="col">Author</th>'; // inlineQty += '<th scope="col">Receipients</th>'; // inlineQty += '<th scope="col">Subject</th>'; // inlineQty += '<th scope="col">More</th>'; // inlineQty += '</tr>'; // inlineQty += '</thead>'; // inlineQty += '<tbody>'; inlineQty += '<style>table#emails-preview {font-size: 12px;text-align: center;border: none; background-color: #379E8F}.dataTables_wrapper {font-size: 12px;}table#emails-preview th{background-color: #379E8F; text-align: center;}</style>'; inlineQty += '<table cellpadding="15" id="emails-preview" class="table table-responsive table-striped customer tablesorter" cellspacing="0" style="width: 100%;">'; inlineQty += '<thead style="color: white;background-color: #379E8F;">'; inlineQty += '<tr class="text-center">'; inlineQty += '<th scope="col">Message Date</th>'; inlineQty += '<th scope="col">Author</th>'; inlineQty += '<th scope="col">Receipients</th>'; inlineQty += '<th scope="col">Subject</th>'; inlineQty += '<th scope="col">More</th>'; inlineQty += '</tr>'; inlineQty += '</thead>'; inlineQty += '<tbody>'; allEmails.forEach(function (email) { var messageid = email.searchId; var date = email.getValue('messagedate'); var author = email.getValue('authoremail'); var recipients = email.getText('recipients'); var subject = email.getValue('subject'); var url = "https://1048144-sb3.app.netsuite.com/app/crm/common/crmmessage.nl?id=" + messageid; //Table row data inlineQty += '<tr>'; inlineQty += '<td> ' + date + ' </td>'; inlineQty += '<td> ' + author + ' </td>'; inlineQty += '<td> ' + recipients + ' </td>'; inlineQty += '<td> ' + subject + '</td>'; inlineQty += '<td> <a href='+ url + '> View More </a> </td>'; inlineQty += '</tr>'; }); inlineQty += '</tbody>'; inlineQty += '</table>'; //inlineQty += '</div>'; return inlineQty; } /** * @return {String} inlineQty */ function issuesHeader() { var inlineQty = '<div class="form-group container toll_issues_header_section">'; inlineQty += '<div class="row">'; inlineQty += '<div class="col-xs-12 heading1">'; inlineQty += '<h4><span style="background-color: #379E8F" class="form-group label label-default col-xs-12">ISSUES</span></h4>'; inlineQty += '</div></div></div>'; return inlineQty; } /** * @param {Number} status_value * @return {String} inlineQty */ function reminderSection(status_value) { var hide_class = (!isTicketNotClosed(status_value)) ? 'hide' : ''; var inlineQty = '<div class="form-group container reminder_section ' + hide_class + '">'; inlineQty += '<div class="row">'; // Reminder field inlineQty += '<div class="col-xs-12 reminder">'; inlineQty += '<div class="input-group">'; inlineQty += '<span class="input-group-addon" id="reminder_text">REMINDER</span>'; inlineQty += '<input id="reminder" class="form-control reminder" type="date" />'; inlineQty += '</div></div></div></div>'; return inlineQty; } /** * Based on the selected MP Issue, an Owner is allocated to the ticket. * IT issues have priority over the other issues. * Populated with selectOwner() in the pageInit function on the client script. * @param {Number} ticket_id * @param {Array} owner_list * @param {Number} status_value * @return {String} inlineQty */ function ownerSection(ticket_id, owner_list, status_value) { if (isNullorEmpty(ticket_id)) { // If ticket_id is null, owner_list as well. // In that case, only the creator of the ticket is pre-selected as the owner. var userId = runtime.getCurrentUser().id; log.debug({ title: 'userId', details: userId }) owner_list = [userId]; } var disabled = (!isTicketNotClosed(status_value)) ? 'disabled' : ''; log.debug({ title: 'owner_list', details: owner_list }) var inlineQty = '<div class="form-group container owner_section">'; inlineQty += '<div class="row">'; inlineQty += '<div class="col-xs-12 owner">'; inlineQty += '<div class="input-group">'; inlineQty += '<span class="input-group-addon" id="owner_text">OWNER<span class="mandatory">*</span></span>'; inlineQty += '<select multiple id="owner" class="form-control owner" ' + disabled + '>'; var employeeSearch = search.load({ type: 'employee', id: 'customsearch_active_employees' }); var employeeResultSet = employeeSearch.run(); employeeResultSet.each(function(employeeResult) { var employee_id = employeeResult.id; var employee_firstname = employeeResult.getValue('firstname'); var employee_lastname = employeeResult.getValue('lastname'); var employee_email = employeeResult.getValue('email'); if (owner_list.indexOf(parseInt(employee_id)) != -1) { inlineQty += '<option value="' + employee_id + '" data-email="' + employee_email + '" selected>' + employee_firstname + ' ' + employee_lastname + '</option>'; } else { inlineQty += '<option value="' + employee_id + '" data-email="' + employee_email + '">' + employee_firstname + ' ' + employee_lastname + '</option>'; } return true; }); inlineQty += '</select>'; inlineQty += '</div></div></div></div>'; return inlineQty; } function customerIssueDropdown(){ //Load the customer issue list var col = new Array(); col[0] = search.createColumn({ name: 'name' }); col[1] = search.createColumn({ name: 'internalId' }); var results = search.create({ type: 'customlist_customer_ticket_issues', columns: col, }) var inlineQty = '<div class="form-group container customer_issues_dropdown_section">'; inlineQty += '<div class="row">'; inlineQty += '<div class="col-xs-12">'; inlineQty += '<div class="input-group"><span class="input-group-addon">CUSTOMER ISSUE</span>'; inlineQty += '<select id="customer_issue_dropdown" class="form-control">'; inlineQty += '<option></option>'; for (var i = 0; results != null && i < results.length; i++) {​​​​​ var res = results[i]; var listValue = res.getValue('name'); var listID = res.getValue('internalId'); inlineQty += '<option value="' + listID + '">' + listValue + '</option>'; // if (selected) { // inlineQty += '<option value="' + listID + '" selected>' + listValue + '</option>'; // } else { // inlineQty += '<option value="' + listID + '">' + listValue + '</option>'; // } } inlineQty += '</select>'; inlineQty += '</div></div></div></div>'; return inlineQty; } function customerIssuesSection(ticket_id, selector_type, selector_number, screenshot_file, selected_browser, login_email_used, selected_operating_system, phone_used, old_sender_name, old_sender_phone, status_value){ if (isNullorEmpty(screenshot_file)) { screenshot_file = '';} if (isNullorEmpty(selected_browser)) { selected_browser = '';} if (isNullorEmpty(login_email_used)) { login_email_used = '';} if (isNullorEmpty(selected_operating_system)) { operating_system = '';} if (isNullorEmpty(phone_used)) { phone_used = '';} if (isNullorEmpty(old_sender_name)) { old_sender_name = '';} if (isNullorEmpty(old_sender_phone)) { old_sender_phone = '';} var hide_class_section_mp_app = ((selector_type == "customer_issue") && (selector_number == 'Customer App')) ? '' : 'hide'; var hide_class_section_mp_label = ((selector_type == "customer_issue") && (selector_number == 'Update Label')) ? '' : 'hide'; var is_customer_issue_hide = (selector_type != "customer_issue") ? 'hide': ''; var hide_class_section_mp_portal = ((selector_type == "customer_issue") && (selector_number == 'Customer Portal')) ? '' : 'hide'; var inlineQty = ''; //Screenshot section if(selector_type == "customer_issue" && (selector_number == "Customer App" || selector_number == "Customer Portal") && !isNullorEmpty(ticket_id)){ inlineQty += '<div class="form-group container ss_section">'; inlineQty += '<div class="row">'; inlineQty += '<div class="col-xs-12 screenshot_div">'; inlineQty += '<div class="input-group"><span class="input-group-addon" id="screenshot_text">SCREENSHOT</span>'; inlineQty += '<input type="file" class="form-control" id="screenshot_image" value="'+ screenshot_file + '">'; inlineQty += '</div></div></div></div>'; } // Browser and OS Section inlineQty += '<div class="form-group container browser_os_section ' + hide_class_section_mp_portal + ' ' + is_customer_issue_hide + '">'; inlineQty += '<div class="row">'; inlineQty += '<div class="col-xs-6 browser_div">'; inlineQty += '<div class="input-group"><span class="input-group-addon" id="browser_text">BROWSER</span>'; inlineQty += '<select id="browser_value" class="form-control label_status">'; inlineQty += '<option></option>' var browserColumns = new Array(); browserColumns[0] = search.createColumn({ name: 'name' }); browserColumns[1] = search.createColumn({ name: 'internalId' }); var browserResultSet = search.create({ type: 'customlist_common_browsers', columns: browserColumns }); browserResultSet.run().each(function (browserResult) { var browserName = browserResult.getValue('name'); var browserId = browserResult.getValue('internalId'); if(selected_browser == browserId) { inlineQty += '<option value="' + browserId + '"selected>' + browserName + '</option>'; }else{ inlineQty += '<option value="' + browserId + '">' + browserName + '</option>'; } return inlineQty; }); inlineQty += '</select></div></div>'; inlineQty += '<div class="col-xs-6 os_div">'; inlineQty += '<div class="input-group"><span class="input-group-addon" id="os_text">OPERATING SYSTEM</span>'; inlineQty += '<select id="os_value" class="form-control">'; inlineQty += '<option></option>' var osColumns = new Array(); osColumns[0] = search.createColumn({ name: 'name' }); osColumns[1] = search.createColumn({ name: 'internalId' }); var osResultSet = search.create({ type: 'customlist_common_os', columns: osColumns }); osResultSet.run().each(function (osResult) { var osName = osResult.getValue('name'); var osId = osResult.getValue('internalId'); if(selected_browser == osId) { inlineQty += '<option value="' + osId + '"selected>' + osName + '</option>'; }else{ inlineQty += '<option value="' + osId + '">' + osName + '</option>'; } return inlineQty; }); inlineQty += '</select>'; inlineQty += '</div></div></div></div>'; //Customer App issues - Phone section inlineQty += '<div class="form-group container '+is_customer_issue_hide+' phone_section ' + hide_class_section_mp_app + '">'; inlineQty += '<div class="row">'; inlineQty += '<div class="col-xs-12 phone_div">'; inlineQty += '<div class="input-group"><span class="input-group-addon" id="screenshot_text">PHONE</span>'; inlineQty += '<input type="text" class="form-control" id="phone_used" placeholder=" Google Pixel 3" value="'+ phone_used + '">'; inlineQty += '</div></div></div></div>'; //Login email used section inlineQty += '<div class="form-group container login_email_used_section '+ is_customer_issue_hide +'">'; inlineQty += '<div class="row">'; inlineQty += '<div class="col-xs-12 login_email_div">'; inlineQty += '<div class="input-group">'; inlineQty += '<span class="input-group-addon" id="login_email">LOGIN EMAIL</span>'; inlineQty += '<input id="login_email_text" class="form-control" value="'+ login_email_used + '"/>'; inlineQty += '</div></div></div></div>'; //Sender details name and phone number inlineQty += '<div class="form-group container '+ is_customer_issue_hide +' sender_details_section ' + hide_class_section_mp_label + '">'; inlineQty += '<div class="row">'; inlineQty += '<div class="col-xs-6 sender_name_div">'; inlineQty += '<div class="input-group">'; inlineQty += '<span class="input-group-addon" id="sender_name">SENDER NAME</span>'; inlineQty += '<input id="sender_name_text" class="form-control" value="'+ old_sender_name + '"/>'; inlineQty += '</div></div>'; inlineQty += '<div class="col-xs-6 sender_phone_div">'; inlineQty += '<div class="input-group">'; inlineQty += '<span class="input-group-addon" id="sender_phone">SENDER PHONE</span>'; inlineQty += '<input id="sender_phone_text" class="form-control" value="'+ old_sender_phone + '"/>'; inlineQty += '</div></div></div></div>'; return inlineQty; } /** * The multiselect TOLL issues dropdown * @param {Array} list_toll_issues * @param {Array} list_resolved_toll_issues * @param {Number} status_value * @param {String} selector_type * @return {String} inlineQty */ function tollIssuesSection(list_toll_issues, list_resolved_toll_issues, status_value, selector_type) { // TOLL Issues var has_toll_issues = (!isNullorEmpty(list_toll_issues)); var toll_issues_columns = new Array(); toll_issues_columns[0] = search.createColumn({ name: 'name' }); toll_issues_columns[1] = search.createColumn({ name: 'internalId' }); var tollIssuesResultSet = search.create({ type: 'customlist_cust_prod_stock_toll_issues', columns: toll_issues_columns }); if (!isTicketNotClosed(status_value) || selector_type != 'barcode_number') { var inlineQty = '<div class="form-group container toll_issues_section hide">'; } else { var inlineQty = '<div class="form-group container toll_issues_section">'; } inlineQty += '<div class="row">'; inlineQty += '<div class="col-xs-12 toll_issues">'; inlineQty += '<div class="input-group"><span class="input-group-addon" id="toll_issues_text">TOLL ISSUES<span class="mandatory">*</span></span>'; inlineQty += '<select multiple id="toll_issues" class="form-control toll_issues" size="' + tollIssuesResultSet.length + '">'; tollIssuesResultSet.run().each(function(tollIssueResult) { var issue_name = tollIssueResult.getValue('name'); var issue_id = tollIssueResult.getValue('internalId'); var selected = false; if (has_toll_issues) { selected = (list_toll_issues.indexOf(issue_id) !== -1); } if (selected) { inlineQty += '<option value="' + issue_id + '" selected>' + issue_name + '</option>'; } else { inlineQty += '<option value="' + issue_id + '">' + issue_name + '</option>'; } return true; }); inlineQty += '</select>'; inlineQty += '</div></div></div></div>'; // Resolved TOLL Issues log.debug({ title: 'list_resolved_toll_issues : ', details: list_resolved_toll_issues }); var has_resolved_toll_issues = (!isNullorEmpty(list_resolved_toll_issues)); if (has_resolved_toll_issues) { var text_resolved_toll_issues = ''; tollIssuesResultSet.run().each(function(tollIssueResult) { var issue_name = tollIssueResult.getValue('name'); var issue_id = tollIssueResult.getValue('internalId'); if (list_resolved_toll_issues.indexOf(issue_id) !== -1) { text_resolved_toll_issues += issue_name + '\n'; } return true; }); log.debug({ title: 'text_resolved_toll_issues : ', details: text_resolved_toll_issues }); inlineQty += '<div class="form-group container resolved_toll_issues_section">'; inlineQty += '<div class="row">'; inlineQty += '<div class="col-xs-12 resolved_toll_issues">'; inlineQty += '<div class="input-group">'; inlineQty += '<span class="input-group-addon" id="resolved_toll_issues_text">RESOLVED TOLL ISSUES</span>'; inlineQty += '<textarea id="resolved_toll_issues" class="form-control resolved_toll_issues" rows="' + list_resolved_toll_issues.length + '" disabled>' + text_resolved_toll_issues.trim() + '</textarea>'; inlineQty += '</div></div></div></div>'; } return inlineQty; }; /** * The multiselect MP Ticket issues dropdown * @param {Array} list_mp_ticket_issues * @param {Array} list_resolved_mp_ticket_issues * @param {Number} status_value * @param {String} selector_type * @return {String} inlineQty */ function mpTicketIssuesSection(list_mp_ticket_issues, list_resolved_mp_ticket_issues, status_value, selector_type) { // MP Ticket Issues var has_mp_ticket_issues = !isNullorEmpty(list_mp_ticket_issues); var disabled_mp_issue_field = (isTicketNotClosed(status_value)) ? '' : 'disabled'; log.debug({ title: 'has_mp_ticket_issues : ', details: has_mp_ticket_issues }); if (has_mp_ticket_issues && status_value != 3) { // The MP Ticket issue section is displayed if the status is 'Closed - Unallocated' (status_value == 8) var inlineQty = '<div class="form-group container mp_issues_section">'; } else { var inlineQty = '<div class="form-group container mp_issues_section hide">'; } inlineQty += '<div class="row">'; inlineQty += '<div class="col-xs-12 mp_issues">'; var mp_ticket_issues_columns = new Array(); mp_ticket_issues_columns[0] = search.createColumn({ name: 'name' }); mp_ticket_issues_columns[1] = search.createColumn({ name: 'internalId' }); var mpTicketIssuesResultSet = search.create({ type: 'customlist_mp_ticket_issues', columns: mp_ticket_issues_columns }); inlineQty += '<div class="input-group">' inlineQty += '<span class="input-group-addon" id="mp_issues_text">MP ISSUES<span class="mandatory hide">*</span></span>'; inlineQty += '<select multiple id="mp_issues" class="form-control mp_issues" size="' + mpTicketIssuesResultSet.length + '" ' + disabled_mp_issue_field + '>'; mpTicketIssuesResultSet.run().each(function(mpTicketIssueResult) { var mp_issue_name = mpTicketIssueResult.getValue('name'); var mp_issue_id = mpTicketIssueResult.getValue('internalId'); var selected = false; if (has_mp_ticket_issues) { selected = (list_mp_ticket_issues.indexOf(mp_issue_id) !== -1); } var show_option = (selector_type == 'barcode_number' || (selector_type == 'invoice_number' && mp_issue_id == 4) || (selector_type == "customer_issue")); var selected_option = (selected) ? 'selected' : ''; if (show_option) { inlineQty += '<option value="' + mp_issue_id + '" ' + selected_option + '> ' + mp_issue_name + '</option > '; } return true; }); inlineQty += '</select>'; inlineQty += '</div></div></div></div>'; // Resolved MP Ticket Issues var has_resolved_mp_ticket_issues = !isNullorEmpty(list_resolved_mp_ticket_issues); if (has_resolved_mp_ticket_issues && selector_type != "customer_issue") { var text_resolved_mp_ticket_issues = ''; mpTicketIssuesResultSet.run().each(function(mpTicketIssueResult) { var mp_issue_name = mpTicketIssueResult.getValue('name'); var mp_issue_id = mpTicketIssueResult.getValue('internalId'); if (list_resolved_mp_ticket_issues.indexOf(mp_issue_id) !== -1) { text_resolved_mp_ticket_issues += mp_issue_name + '\n'; } return true; }); inlineQty += '<div class="form-group container resolved_mp_issues_section">'; inlineQty += '<div class="row">'; inlineQty += '<div class="col-xs-12 resolved_mp_issues">'; inlineQty += '<div class="input-group">'; inlineQty += '<span class="input-group-addon" id="resolved_mp_issues_text">RESOLVED MP ISSUES</span>'; inlineQty += '<textarea id="resolved_mp_issues" class="form-control resolved_mp_issues" rows="' + list_resolved_mp_ticket_issues.length + '" disabled>' + text_resolved_mp_ticket_issues.trim() + '</textarea>'; inlineQty += '</div></div></div></div>'; } return inlineQty; } /** * The multiselect Invoice issues dropdown * @param {Array} list_invoice_issues * @param {Array} list_resolved_invoice_issues * @param {Number} status_value * @param {String} selector_type * @return {String} inlineQty */ function invoiceIssuesSection(list_invoice_issues, list_resolved_invoice_issues, status_value, selector_type) { var has_invoice_issues = (!isNullorEmpty(list_invoice_issues)); var invoice_issues_columns = new Array(); invoice_issues_columns[0] = search.createColumn({ name: 'name' }); // Might need to be changed invoice_issues_columns[1] = search.createColumn({ name: 'internalId' }); // Might need to be changed var invoiceIssuesResultSet = search.create({ type: 'customlist_invoice_issues', columns: invoice_issues_columns }); if (!isTicketNotClosed(status_value) || selector_type != 'invoice_number') { var inlineQty = '<div class="form-group container invoice_issues_section hide">'; } else { var inlineQty = '<div class="form-group container invoice_issues_section">'; } inlineQty += '<div class="row">'; inlineQty += '<div class="col-xs-12 invoice_issues">'; inlineQty += '<div class="input-group"><span class="input-group-addon" id="invoice_issues_text">INVOICE ISSUES<span class="mandatory">*</span></span>'; inlineQty += '<select multiple id="invoice_issues" class="form-control invoice_issues">'; invoiceIssuesResultSet.run().each(function(invoiceIssueResult) { var issue_name = invoiceIssueResult.getValue('name'); // Might need to be changed var issue_id = invoiceIssueResult.getValue('internalId'); // Might need to be changed var selected = false; if (has_invoice_issues) { selected = (list_invoice_issues.indexOf(issue_id) != -1); } if (selected) { inlineQty += '<option value="' + issue_id + '" selected>' + issue_name + '</option>'; } else { inlineQty += '<option value="' + issue_id + '">' + issue_name + '</option>'; } return true; }); inlineQty += '</select>'; inlineQty += '</div></div></div></div>'; // Resolved invoice Issues log.debug({ title: 'list_resolved_invoice_issues : ', details: list_resolved_invoice_issues }); var has_resolved_invoice_issues = (!isNullorEmpty(list_resolved_invoice_issues)); if (has_resolved_invoice_issues) { var text_resolved_invoice_issues = ''; invoiceIssuesResultSet.run().each(function(invoiceIssueResult) { var issue_name = invoiceIssueResult.getValue('name'); // Might need to be changed var issue_id = invoiceIssueResult.getValue('internalId'); // Might need to be changed if (list_resolved_invoice_issues.indexOf(issue_id) !== -1) { text_resolved_invoice_issues += issue_name + '\n'; } }); log.debug({ title: 'text_resolved_invoice_issues : ', details: text_resolved_invoice_issues }); inlineQty += '<div class="form-group container resolved_invoice_issues_section">'; inlineQty += '<div class="row">'; inlineQty += '<div class="col-xs-12 resolved_invoice_issues">'; inlineQty += '<div class="input-group">'; inlineQty += '<span class="input-group-addon" id="resolved_invoice_issues_text">RESOLVED INVOICE ISSUES</span>'; inlineQty += '<textarea id="resolved_invoice_issues" class="form-control resolved_invoice_issues" rows="' + list_resolved_invoice_issues.length + '" disabled>' + text_resolved_invoice_issues.trim() + '</textarea>'; inlineQty += '</div></div></div></div>'; } return inlineQty; } /** * @param {String} selector_type * @param {Number} status_value * @return {String} inlineQty */ function usernoteSection(selector_type, status_value) { var usernote_titles_columns = new Array(); usernote_titles_columns[0] = search.createColumn({ name: 'name' }); usernote_titles_columns[1] = search.createColumn({ name: 'internalId' }); var usernoteTitlesResultSet = search.create({ type: 'customlist_user_note_title', columns: usernote_titles_columns }); // Row Title if (selector_type == 'invoice_number' && isTicketNotClosed(status_value)) { var inlineQty = '<div class="form-group container user_note user_note_title_section">'; } else { var inlineQty = '<div class="form-group container user_note user_note_title_section hide">'; } inlineQty += '<div class="row">'; inlineQty += '<div class="col-xs-12 user_note_title_section">'; inlineQty += '<div class="input-group">'; inlineQty += '<span class="input-group-addon">TITLE<span class="mandatory">*</span></span>'; inlineQty += '<select id="user_note_title" class="form-control">'; usernoteTitlesResultSet.run().each(function(usernoteTitleResult) { var title_name = usernoteTitleResult.getValue('name'); var title_id = usernoteTitleResult.getValue('internalId'); if (title_id == 3) { inlineQty += '<option value="' + title_id + '" selected>' + title_name + '</option>'; } else { inlineQty += '<option value="' + title_id + '">' + title_name + '</option>'; } return true; }); inlineQty += '</select>'; inlineQty += '</div></div></div></div>'; // Row User Note Textarea if (selector_type == 'invoice_number' && isTicketNotClosed(status_value)) { inlineQty += '<div class="form-group container user_note user_note_textarea_section">'; } else { inlineQty += '<div class="form-group container user_note user_note_textarea_section hide">'; } inlineQty += '<div class="row">'; inlineQty += '<div class="col-xs-12 user_note_textarea">'; inlineQty += '<div class="input-group">'; inlineQty += '<span class="input-group-addon" id="user_note_textarea_text">USER NOTE<span class="mandatory hide">*</span></span>'; inlineQty += '<textarea id="user_note_textarea" class="form-control user_note_textarea" rows="3"></textarea>'; inlineQty += '</div></div></div></div>'; // User Note table if (selector_type == 'invoice_number') { inlineQty += '<div class="form-group container user_note user_note_section" style="font-size: small;">'; } else { inlineQty += '<div class="form-group container user_note user_note_section hide" style="font-size: small;">'; } inlineQty += '<div class="row">'; inlineQty += '<div class="col-xs-12 user_note_div">'; // Since the table is not displayed correctly when added through suitelet, // It is added with jQuery in the pageInit() function in the client script 'mp_cl_open_ticket.js'. inlineQty += '</div>'; inlineQty += '</div>'; inlineQty += '</div>'; return inlineQty; } /** * Used to pass the values of `date_from` and `date_to` between the scripts and to Netsuite for the records and the search. * @param {String} date_iso "2020-06-01" * @returns {String} date_netsuite "1/6/2020" */ function dateISOToNetsuite(date_iso) { var date_netsuite = ''; if (!isNullorEmpty(date_iso)) { var date_netsuite = format.format({ value: date_iso, type: format.Type.DATETIME }); } return date_netsuite; } /** * The free-from text area for comments. * @param {String} comment * @param {String} selector_type * @param {Number} status_value * @return {String} inlineQty */ function commentSection(comment, selector_type, status_value) { if (isNullorEmpty(comment)) { comment = ''; } else { comment += '\n'; } switch (selector_type) { case 'barcode_number': var inlineQty = '<div class="form-group container comment_section">'; break; case 'invoice_number': var inlineQty = '<div class="form-group container comment_section hide">'; break; case 'customer_issue': var inlineQty = '<div class="form-group container comment_section">'; break; } inlineQty += '<div class="row">'; inlineQty += '<div class="col-xs-12 comment">'; inlineQty += '<div class="input-group">'; inlineQty += '<span class="input-group-addon" id="comment_text">COMMENT<span class="mandatory hide">*</span></span>'; if (isTicketNotClosed(status_value)) { inlineQty += '<textarea id="comment" class="form-control comment" rows="3">' + comment + '</textarea>'; } else { inlineQty += '<textarea id="comment" class="form-control comment" rows="3" readonly>' + comment + '</textarea>'; } inlineQty += '</div></div></div></div>'; return inlineQty; } /** * The table that will display the differents tickets linked to the customer. * @return {String} inlineQty */ function dataTablePreview() { var inlineQty = '<div class="form-group container tickets_datatable_section">'; inlineQty += '<div class="row">'; inlineQty += '<div class="col-xs-12 heading2">'; inlineQty += '<h4><span style="background-color: #379E8F" class="label label-default col-xs-12">PREVIOUS TICKETS</span></h4>'; inlineQty += '</div></div></div>'; inlineQty += '<style>table#tickets-preview {font-size: 12px;text-align: center;border: none; background-color: #379E8F}.dataTables_wrapper {font-size: 12px;}table#tickets-preview th{background-color: #379E8F; text-align: center;}</style>'; inlineQty += '<table cellpadding="15" id="tickets-preview" class="table table-responsive table-striped customer tablesorter" cellspacing="0" style="width: 100%;">'; inlineQty += '<thead style="color: white;background-color: #379E8F;">'; inlineQty += '<tr class="text-center">'; inlineQty += '</tr>'; inlineQty += '</thead>'; inlineQty += '<tbody id="result_tickets"></tbody>'; inlineQty += '</table>'; return inlineQty; } /** * The inline HTML for the close ticket button or the reopen button, * and the submitter button at the bottom of the page. * @param {Number} ticket_id * @param {Number} status_value * @return {String} inlineQty */ function closeReopenSubmitTicketButton(ticket_id, status_value) { var inlineQty = '<div class="form-group container close_reopen_submit_ticket_section">'; inlineQty += '<div class="row">'; log.debug({ title: 'status_value', details: status_value }); log.debug({ title: 'ticket_id', details: ticket_id }); if (isTicketNotClosed(status_value)) { if (!isNullorEmpty(ticket_id)) { inlineQty += '<div class="col-xs-2 close_ticket">'; inlineQty += '<input type="button" value="CLOSE TICKET" style="background-color: #FBEA51; border: 3px solid #379E8F; color: #379E8F; font-weight: 700" class="form-control btn btn-default" id="close_ticket" onclick="closeTicket()"/>'; inlineQty += '</div>'; inlineQty += '<div class="col-xs-3 close_ticket_lost">'; inlineQty += '<input type="button" value="CLOSE TICKET - LOST ITEM" style="background-color: #FBEA51; border: 3px solid #379E8F; color: #379E8F; font-weight: 700" class="form-control btn btn-default" id="close_ticket_lost" onclick="closeTicketLost()"/>'; inlineQty += '</div>'; if (userId == 409635 || userId == 696992 || userId == 766498) { inlineQty += '<div class="col-xs-3 close_unallocated_ticket hide">'; inlineQty += '<input type="button" value="CLOSE UNALLOCATED TICKET" style="background-color: #FBEA51; border: 3px solid #379E8F; color: #379E8F; font-weight: 700" class="form-control btn btn-default" id="close_unallocated_ticket" onclick="closeUnallocatedTicket()" />'; inlineQty += '</div>'; } } inlineQty += '<div class="col-xs-2 submitter">'; inlineQty += '<input type="button" style="background-color: #FBEA51; border: 3px solid #379E8F; color: #379E8F; font-weight: 700" value="UPDATE TICKET" class="form-control btn btn-primary" id="submit_ticket" />'; inlineQty += '</div>'; if (isNullorEmpty(ticket_id)) { inlineQty += '<div class="col-xs-3 open_and_new_ticket_btn">'; inlineQty += '<input type="button" style="background-color: #FBEA51; border: 3px solid #379E8F; color: #379E8F; font-weight: 700" value="OPEN AND NEW TICKET" class="form-control btn btn-primary" id="open_and_new_ticket_btn" />'; inlineQty += '</div>'; } inlineQty += '<style>.escalate:hover {box-shadow: 0 12px 16px 0 rgba(0,0,0,0.24), 0 17px 50px 0 rgba(0,0,0,0.19)}</style>'; inlineQty += '<div class="col-xs-2 escalate">'; inlineQty += '<input type="button" style="background-color: #FBEA51; border: 3px solid #379E8F; color: #379E8F; font-weight: 700" value="ESCALATE" class="form-control btn btn-default" id="escalate" onclick="onEscalate()"/>'; inlineQty += '</div>'; } else { inlineQty += '<div class="col-xs-2 col-xs-offset-2 reopen_ticket">'; inlineQty += '<input type="button" style="background-color: #FBEA51; border: 3px solid #379E8F; color: #379E8F; font-weight: 700" value="REOPEN TICKET" class="form-control btn btn-primary" id="reopen_ticket" />'; inlineQty += '</div>'; } inlineQty += '<div class="col-xs-2 cancel">'; inlineQty += '<input type="button" style="background-color: #FBEA51; border: 3px solid #379E8F; color: #379E8F; font-weight: 700" value="CANCEL" class="form-control btn btn-default" id="cancel" onclick="onCancel()"/>'; inlineQty += '</div>'; inlineQty += '</div></div>'; return inlineQty; } function Ownerjava2jsArray(javaArray) { var jsArray = new Array; if (!isNullorEmpty(javaArray)) { javaArray.forEach(function(javaValue) { var jsValue = parseInt(javaValue); jsArray.push(jsValue); }) } return jsArray; } /** * The output of .getFieldValues is a java String Array. * We want to convert it to a javaScript Array in order to read its values. * @param {Ljava.lang.String} javaArray * @return {Array} jsArray */ function java2jsArray(javaArray) { var jsArray = new Array; if (!isNullorEmpty(javaArray)) { javaArray.forEach(function(javaValue) { var jsValue = javaValue.toString(); jsArray.push(jsValue); }) } return jsArray; } /** * Parse the objects in an array, and returns an object based on the value of one of its keys. * With ES6, this function would simply be `array.find(obj => obj[key] == value)` * @param {Array} array * @param {String} key * @param {*} value * @returns {Object} */ function findObjectByKey(array, key, value) { for (var i = 0; i < array.length; i++) { if (array[i][key] === value) { return array[i]; } } return null; } /** * Returns whether a ticket is closed or not based on its status value. * @param {Number} status_value * @returns {Boolean} is_ticket_closed */ function isTicketNotClosed(status_value) { var is_ticket_not_closed = ((status_value != 3) && (status_value != 8) && (status_value != 15)) ? true : false; return is_ticket_not_closed; } function escalateButton(status) { if (status < 11) { return 'Escalate to 1st Escalation'; } else if (status == 11) { return 'Escalate to 2nd Escalation'; }else if (status == 12) { return 'Escalate to 3rd Escalation'; } else if (status == 13) { return 'Escalate to Final Escalation'; } else { return 'Escalate'; } } /** * Whether the user is from the finance team, * or a Data Systems Co-ordinator, MailPlus Administration or Administrator user. * @param {Number} userRole * @returns {Boolean} */ function isFinanceRole(userRole) { // 1001, 1031 and 1023 are finance roles // 1032 is the Data Systems Co-ordinator role (to be deleted in prod) // 1006 is the Mail Plus Administration role. // 3 is the Administrator role. return ((userRole == 1001 || userRole == 1031 || userRole == 1023) || ((userRole == 1032) || (userRole == 1006) || (userRole == 3))); } function isNullorEmpty(strVal) { return (strVal == null || strVal == '' || strVal == 'null' || strVal == undefined || strVal == 'undefined' || strVal == '- None -'); } return { onRequest: onRequest }; });
332
[{"tag": "KEY", "value": "sha384-nvAa0+6Qg9clwYCGGPpDQLVpLNn0fRaROjHqs13t4Ggj3Ez50XnGQqc/r8MhnRDZ", "start": 22948, "end": 23019}, {"tag": "KEY", "value": "sha384-aJ21OjlMXNL5UyIl/XNwTMqvzeRMZH2w8c5cRVpzpU8Y5bApTppSuUkhZXN0VxHd", "start": 23577, "end": 23648}, {"tag": "KEY", "value": "sha384-HSMxcRTRxnN+Bdg0JdbxYKrThecOKuH5zCYotlSAcp1+c8xmyTe9GYg1l9a69psu", "start": 23354, "end": 23425}]
true
3
/** * * @NApiVersion 2.0 * @NScriptType Suitelet * * Description: A ticketing system for the Customer Service. * @Last Modified by: Sruti Desai * */ define(['N/ui/serverWidget', 'N/email', 'N/runtime', 'N/search', 'N/record', 'N/http', 'N/log', 'N/redirect', 'N/format', 'N/file'], function(ui, email, runtime, search, record, http, log, redirect, format, file) { var baseURL = 'https://1048144.app.netsuite.com'; if (runtime.EnvType == "SANDBOX") { baseURL = 'https://1048144-sb3.app.netsuite.com'; } var zee = 0; var role = runtime.getCurrentUser().role; var userRole = runtime.getCurrentUser().role; var ctx = runtime.getCurrentScript(); var userId = runtime.getCurrentUser().id; if (role == 1000) { //Franchisee zee = runtime.getCurrentUser(); } function onRequest(context) { if (context.request.method === 'GET') { var ticket_id = null; var customer_id = null; var customer_number = null; var selector_id = null; var selector_number = ''; var selector_type = 'barcode_number'; var connote_number = ''; var date_created = ''; var creator_name = ''; var creator_id = null; var status_value = null; var escalated_to_it = ''; var status = ''; var customer_name = ''; var daytodayphone = ''; var daytodayemail = ''; var accountsphone = ''; var accountsemail = ''; var zee_id = null; var franchisee_name = ''; var zee_main_contact_name = ''; var zee_email = ''; var zee_main_contact_phone = ''; var zee_abn = ''; var date_stock_used = ''; var time_stock_used = ''; var final_delivery_text = ''; var selected_enquiry_status_id = null; var attachments_hyperlink = ''; var maap_bank_account_number = null; var maap_parent_bank_account_number = null; var selected_invoice_method_id = null; var accounts_cc_email = ''; var mpex_po_number = ''; var customer_po_number = ''; var terms = null; var customer_terms = ''; var account_manager = {}; var selected_invoice_cycle_id = null; var usage_report_id_1 = ''; var usage_report_id_2 = ''; var usage_report_id_3 = ''; var usage_report_id_4 = ''; var usage_report_array = []; var list_toll_issues = ''; var list_resolved_toll_issues = ''; var list_mp_ticket_issues = ''; var list_resolved_mp_ticket_issues = ''; var list_invoice_issues = ''; var list_resolved_invoice_issues = ''; var owner_list = ''; var comment = ''; var selected_label_id = null; var list_enquiry_mediums = ''; var total_enquiry_count = 0; var chat_enquiry_count = 0; var phone_enquiry_count = 0; var email_enquiry_count = 0; var phone_interaction_count = 0; var email_interaction_count = 0; var list_toll_emails = ''; var params_email = { recipient: '', subject: '', body: '', cc: '', bcc: '', records: {}, attachments_credit_memo_ids: [], attachments_usage_report_ids: [], attachments_invoice_ids: [] }; var customer_barcode_number = ''; var customer_issue = ''; var screenshot_file = ''; var browser = ''; var login_email_used = ''; var operating_system = ''; var phone_used = ''; var old_sender_name = ''; var old_sender_phone = ''; var customer_number_email_sent = 'F'; var customer_ticket_status = ''; var receiveremail = ''; var receiverphone = ''; var receivername = ''; var receiverstate = ''; var receiverzip = ''; var receiversuburb = ''; var receiveraddr1 = ''; var receiveraddr2 = ''; var prod_stock_invoice = ''; var barcodempdl = ''; var barcodesource = ''; // Load params var params = context.request.parameters.custparam_params; log.debug({ title: 'Params', details: params }) if (!isNullorEmpty(params)) { params = JSON.parse(params); log.debug({ title: 'Params not empty', details: params }); // Coming from the ticket_contact page or the edit_ticket page if (!isNullorEmpty(params.selector_number) && !isNullorEmpty(params.selector_type)) { selector_number = params.selector_number; selector_type = params.selector_type; //Coming from the ticket_contact page if (!isNullorEmpty(params.custid)) { customer_id = params.custid; } log.debug({ title: 'customer_id after ticket_contact_page : ', details: customer_id }); // Coming from the edit_ticket page if (!isNullorEmpty(params.ticket_id)) { ticket_id = parseInt(params.ticket_id); log.debug({ title: 'ticket id ISS', details: ticket_id }); // Load ticket data var ticketRecord = record.load({ type: 'customrecord_mp_ticket', id: ticket_id }); date_created = ticketRecord.getValue({ fieldId: 'created' }); creator_name = ticketRecord.getText({ fieldId: 'custrecord_creator' }); creator_id = ticketRecord.getValue({ fieldId: 'custrecord_creator' }); status_value = ticketRecord.getValue({ fieldId: 'custrecord_ticket_status' }); escalated_to_it = ticketRecord.getValue({ fieldId: 'custrecord_date_escalated_it' }); status = ticketRecord.getText({ fieldId: 'custrecord_ticket_status' }); customer_id = ticketRecord.getValue({ fieldId: 'custrecord_customer1' }); customer_name = ticketRecord.getText({ fieldId: 'custrecord_customer1' }); zee_id = ticketRecord.getValue({ fieldId: 'custrecord_zee' }); selected_enquiry_status_id = ticketRecord.getValue({ fieldId: 'custrecord_enquiry_status' }); attachments_hyperlink = ticketRecord.getValue({ fieldId: 'custrecord_mp_ticket_attachments' }); selected_label_id = ticketRecord.getValue({ fieldId: 'custrecord_ticket_label' }); list_enquiry_mediums = ticketRecord.getValue({ fieldId: 'custrecord_enquiry_medium' }); list_enquiry_mediums = java2jsArray(list_enquiry_mediums); total_enquiry_count = ticketRecord.getValue({ fieldId: 'custrecord_enquiry_count' }); chat_enquiry_count = ticketRecord.getValue({ fieldId: 'custrecord_chat_enquiry_count' }); phone_enquiry_count = ticketRecord.getValue({ fieldId: 'custrecord_phone_enquiry_count' }); phone_interaction_count = ticketRecord.getValue({ fieldId: 'custrecord_phone_interaction_count' }); email_interaction_count= ticketRecord.getValue({ fieldId: 'custrecord_email_interaction_count' }); email_enquiry_count = ticketRecord.getValue({ fieldId: 'custrecord_email_enquiry_count' }); customer_issue = ticketRecord.getValue({ fieldId: 'custrecord_customer_issue' }); screenshot_file = ticketRecord.getValue({ fieldId: 'custrecord_screenshot' }); browser = ticketRecord.getValue({ fieldId: 'custrecord_browser' }); login_email_used = ticketRecord.getValue({ fieldId: 'custrecord_login_email' }); operating_system = ticketRecord.getValue({ fieldId: 'custrecord_operating_system' }); phone_used = ticketRecord.getValue({ fieldId: 'custrecord_phone_used' }); customer_number = ticketRecord.getValue({ fieldId: 'custrecord_cust_number' }); old_sender_name = ticketRecord.getValue({ fieldId: 'custrecord_sender_name' }); old_sender_phone = ticketRecord.getValue({ fieldId: 'custrecord_sender_phone' }); customer_number_email_sent = ticketRecord.getValue({ fieldId: 'custrecord_customer_number_email_sent' }); customer_barcode_number = ticketRecord.getValue({ fieldId : 'custrecord_barcode_number'}); customer_ticket_status = ticketRecord.getText({ fieldId : 'custrecord_mp_ticket_customer_status'}); if (!isNullorEmpty(customer_barcode_number)) { var rec = record.load({ type: 'customrecord_customer_product_stock', id: customer_barcode_number, }); receiveremail = rec.getValue({fieldId: 'custrecord_receiver_email'}); receiverphone = rec.getValue({fieldId: 'custrecord_receiver_phone'}); receivername = rec.getValue({fieldId: 'custrecord_receiver_name'}); receiverstate = rec.getValue({fieldId: 'custrecord_receiver_state'}); receiverzip = rec.getValue({fieldId: 'custrecord_receiver_postcode'}); receiversuburb = rec.getValue({fieldId: 'custrecord_receiver_suburb'}); receiveraddr1 = rec.getValue({fieldId: 'custrecord_receiver_addr1'}); receiveraddr2 = rec.getValue({fieldId: 'custrecord_receiver_addr2'}); prod_stock_invoice = rec.getText({fieldId: 'custrecord_prod_stock_invoice'}); barcodempdl = rec.getValue({fieldId: 'custrecord_mpdl_number'}); barcodesource = rec.getText({fieldId: 'custrecord_barcode_source'}); connote_number = rec.getValue({fieldId: 'custrecord_connote_number'}); } if(isNullorEmpty(customer_id) && !isNullorEmpty(customer_number)){ var customer_search = search.load({ type: 'customer', id: 'customsearch_customer_name_2' }); customer_search.filters.push(search.createFilter({ name: 'entityid', operator: 'haskeywords', values: customer_number, })); log.debug({ title: 'customer_search.run().getRange({ start: 0,end:1 })[0].id', details: customer_search.run().getRange({ start: 0,end:1 })[0].id }); customer_id = customer_search.run().getRange({ start: 0,end:1 })[0].id; } if (!isNullorEmpty(customer_id)) { //Load customer record and franchisee information var customerRecord = record.load({ type: 'customer', id: customer_id }); customer_number = customerRecord.getValue({ fieldId: 'entityid' }); daytodayphone = customerRecord.getValue({ fieldId: 'phone' }); daytodayemail = customerRecord.getValue({ fieldId: 'custentity_email_service' }); terms = customerRecord.getValue({ fieldId: 'terms' }); customer_terms = customerRecord.getValue({ fieldId: 'custentity_finance_terms' }); // Account manager var accountManagerSearch = search.load({ type: 'customer', id: 'customsearch3413' }); accountManagerSearch.filters.push(search.createFilter({ name: 'internalid', join: null, operator: search.Operator.ANYOF, values: customer_id, })) var accountManagerResultSet = accountManagerSearch.run(); var accountManagerResult = accountManagerResultSet.getRange({ start: 0, end: 1 }); accountManagerResult = accountManagerResult[0]; if (!isNullorEmpty(accountManagerResult)) { var account_manager_value = accountManagerResult.getValue({ name: "custrecord_sales_assigned", join: "CUSTRECORD_SALES_CUSTOMER", summary: null }); var account_manager_text = accountManagerResult.getText({ name: "custrecord_sales_assigned", join: "CUSTRECORD_SALES_CUSTOMER", summary: null }); if (!isNullorEmpty(account_manager_value)) { var account_manager_email = search.lookupFields({ type: 'employee', id: account_manager_value, columns: 'email' }); account_manager = { name: account_manager_text, email: account_manager_email }; } } // The Franchisee informations are imported from the customer record if possible. zee_id = customerRecord.getValue({ fieldId: 'partner' }); } if (!isNullorEmpty(zee_id)) { var zeeRecord = record.load({ type: 'partner', id: zee_id }); franchisee_name = zeeRecord.getValue({ fieldId: 'companyname' }); zee_main_contact_name = zeeRecord.getValue({ fieldId: 'custentity3' }); zee_email = zeeRecord.getValue({ fieldId: 'email' }); zee_main_contact_phone = zeeRecord.getValue({ fieldId: 'custentity2' }); zee_abn = zeeRecord.getValue({ fieldId: 'custentity_abn_franchiserecord' }); } else { franchisee_name = ticketRecord.getText({ fieldId: 'custrecord_zee' }); } switch (selector_type) { case 'barcode_number': selector_id = ticketRecord.getValue({ fieldId: 'custrecord_barcode_number' }); var stock_used = ''; if(!isNullorEmpty(selector_id)){ //Come in here only if selector_id is not null stock_used = search.lookupFields({ type: 'customrecord_customer_product_stock', id: selector_id, columns: ['custrecord_cust_date_stock_used', 'custrecord_cust_time_stock_used'] }); log.debug({ title: 'stock_used', details: stock_used }) log.debug({ title: 'finalDel', details: search.lookupFields({ type: 'customrecord_customer_product_stock', id: selector_id, columns: 'custrecord_cust_prod_stock_final_del' }) }); var finalDelCheck = search.lookupFields({ type: 'customrecord_customer_product_stock', id: selector_id, columns: 'custrecord_cust_prod_stock_final_del' }).custrecord_cust_prod_stock_final_del; if (!isNullorEmpty(finalDelCheck)) { final_delivery_text = search.lookupFields({ type: 'customrecord_customer_product_stock', id: selector_id, columns: 'custrecord_cust_prod_stock_final_del' })["custrecord_cust_prod_stock_final_del"][0]["text"]; } date_stock_used = stock_used.custrecord_cust_date_stock_used; time_stock_used = stock_used.custrecord_cust_time_stock_used; } list_toll_issues = ticketRecord.getValue({ fieldId: 'custrecord_toll_issues' }); list_toll_issues = java2jsArray(list_toll_issues); list_resolved_toll_issues = ticketRecord.getValue({ fieldId: 'custrecord_resolved_toll_issues' }); list_resolved_toll_issues = java2jsArray(list_resolved_toll_issues); list_toll_emails = ticketRecord.getValue({ fieldId: 'custrecord_toll_emails' }); list_toll_emails = java2jsArray(list_toll_emails); break; case 'invoice_number': selector_id = ticketRecord.getValue({ fieldId: 'custrecord_invoice_number' }); var invoiceRecord = record.load({ type: 'invoice', id: selector_id }); accountsphone = customerRecord.getValue({ fieldId: 'altphone' }); accountsemail = customerRecord.getValue({ fieldId: 'email' }); maap_bank_account_number = customerRecord.getValue({ fieldId: 'custentity_maap_bankacctno' }); maap_parent_bank_account_number = customerRecord.getValue({ fieldId: 'custentity_maap_bankacctno_parent' }); selected_invoice_method_id = customerRecord.getValue({ fieldId: 'custentity_invoice_method' }); accounts_cc_email = customerRecord.getValue({ fieldId: 'custentity_accounts_cc_email' }); mpex_po_number = customerRecord.getValue({ fieldId: 'custentity_mpex_po' }); customer_po_number = customerRecord.getValue({ fieldId: 'custentity11' }); selected_invoice_cycle_id = customerRecord.getValue({ fieldId: 'custentity_mpex_invoicing_cycle' }); usage_report_id_1 = invoiceRecord.getValue({ fieldId: 'custbody_mpex_usage_report' }); usage_report_id_2 = invoiceRecord.getValue({ fieldId: 'custbody_mpex_usage_report_2' }); usage_report_id_3 = invoiceRecord.getValue({ fieldId: 'custbody_mpex_usage_report_3' }); usage_report_id_4 = invoiceRecord.getValue({ fieldId: 'custbody_mpex_usage_report_4' }); var usage_report_id_array = [usage_report_id_1, usage_report_id_2, usage_report_id_3, usage_report_id_4]; usage_report_id_array.forEach(function (usage_report_id) { if (!isNullorEmpty(usage_report_id)) { var usage_report_file = file.load({ id: usage_report_id }); usage_report_name = usage_report_file.name; usage_report_link = usage_report_file.url; usage_report_array.push({ id: usage_report_id, name: usage_report_name, url: usage_report_link }); } }); list_invoice_issues = ticketRecord.getValue({ fieldId: 'custrecord_invoice_issues' }); list_invoice_issues = java2jsArray(list_invoice_issues); list_resolved_invoice_issues = ticketRecord.getValue({ fieldId: 'custrecord_resolved_invoice_issues' }); list_resolved_invoice_issues = java2jsArray(list_resolved_invoice_issues); break; } list_mp_ticket_issues = ticketRecord.getValue({ fieldId: 'custrecord_mp_ticket_issue' }); list_mp_ticket_issues = java2jsArray(list_mp_ticket_issues); list_resolved_mp_ticket_issues = ticketRecord.getValue({ fieldId: 'custrecord_resolved_mp_ticket_issue' }); list_resolved_mp_ticket_issues = java2jsArray(list_resolved_mp_ticket_issues); owner_list = ticketRecord.getValue({ fieldId: 'custrecord_owner' }); owner_list = Ownerjava2jsArray(owner_list); comment = ticketRecord.getValue({ fieldId: 'custrecord_comment' }); } } } var form = ui.createForm({ title: ' ', }); // Load jQuery var inlineHtml = '<script src="https://code.jquery.com/jquery-1.12.4.min.js" integrity="9jnerlff23u8ed01np9g6ysbhsh0dvcs" crossorigin="anonymous"></script>'; // Load Tooltip inlineHtml += '<script src="https://unpkg.com/@popperjs/core@2"></script>'; // Load Bootstrap inlineHtml += '<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/3.4.1/css/bootstrap.min.css" integrity="949d1u22cbffbrarjh182eig55721odj" crossorigin="anonymous">'; inlineHtml += '<script src="https://stackpath.bootstrapcdn.com/bootstrap/3.4.1/js/bootstrap.min.js" integrity="ax5kh6jaqkcd2tiexxs8v6xjo8yv8a6b" crossorigin="anonymous"></script>'; // Load DataTables inlineHtml += '<link rel="stylesheet" type="text/css" href="//cdn.datatables.net/1.10.21/css/jquery.dataTables.min.css">'; inlineHtml += '<script type="text/javascript" charset="utf8" src="//cdn.datatables.net/1.10.21/js/jquery.dataTables.min.js"></script>'; // Load Summernote css/js inlineHtml += '<link href="https://cdnjs.cloudflare.com/ajax/libs/summernote/0.8.9/summernote.css" rel="stylesheet">'; inlineHtml += '<script src="https://cdnjs.cloudflare.com/ajax/libs/summernote/0.8.9/summernote.js"></script>'; // Load bootstrap-select inlineHtml += '<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap-select@1.13.14/dist/css/bootstrap-select.min.css">'; inlineHtml += '<script src="https://cdn.jsdelivr.net/npm/bootstrap-select@1.13.14/dist/js/bootstrap-select.min.js"></script>'; // Load Netsuite stylesheet and script inlineHtml += '<link rel="stylesheet" href="https://1048144.app.netsuite.com/core/media/media.nl?id=2060796&c=1048144&h=9ee6accfd476c9cae718&_xt=.css"/>'; inlineHtml += '<script src="https://1048144.app.netsuite.com/core/media/media.nl?id=2060797&c=1048144&h=ef2cda20731d146b5e98&_xt=.js"></script>'; inlineHtml += '<link type="text/css" rel="stylesheet" href="https://1048144.app.netsuite.com/core/media/media.nl?id=2090583&c=1048144&h=a0ef6ac4e28f91203dfe&_xt=.css">'; inlineHtml += '<style>.mandatory{color:red;}</style>'; // Define alert window. inlineHtml += '<div class="container" style="margin-top:14px;" hidden><div id="danger-alert" class="alert alert-danger fade in"></div></div>'; // Define information window. inlineHtml += '<div class="container" hidden><p id="info" class="alert alert-info"></p></div>'; inlineHtml += tabsSection(customer_number, ticket_id, selector_number, selector_id, selector_type, status_value, customer_name, daytodayphone, daytodayemail, franchisee_name, zee_main_contact_name, zee_email, zee_main_contact_phone, zee_abn, date_stock_used, time_stock_used, final_delivery_text, selected_enquiry_status_id, attachments_hyperlink, owner_list, list_toll_issues, list_resolved_toll_issues, comment, date_created, creator_id, creator_name, status, customer_id, accountsphone, accountsemail, zee_id, list_enquiry_mediums, total_enquiry_count, chat_enquiry_count, phone_enquiry_count, email_enquiry_count, selected_label_id, maap_bank_account_number, maap_parent_bank_account_number, account_manager, list_toll_emails, customer_barcode_number, connote_number, receiveremail, receiverphone, receivername, receiverstate, receiverzip, receiversuburb, receiveraddr1, receiveraddr2, prod_stock_invoice, barcodempdl, barcodesource, list_mp_ticket_issues, list_resolved_mp_ticket_issues, list_invoice_issues, list_resolved_invoice_issues, selected_invoice_method_id, accounts_cc_email, mpex_po_number, customer_po_number, selected_invoice_cycle_id, terms, customer_terms, screenshot_file, browser, login_email_used, operating_system, phone_used, old_sender_name, old_sender_phone, phone_interaction_count, email_interaction_count, escalated_to_it); // inlineHtml += customerNumberSection(customer_number, ticket_id); // inlineHtml += selectorSection(ticket_id, selector_number, selector_id, selector_type, status_value); // if (!isNullorEmpty(ticket_id)) { // inlineHtml += ticketSection(dateISOToNetsuite(date_created), creator_id, creator_name, status); // } // if (isNullorEmpty(ticket_id) || (!isNullorEmpty(ticket_id) && !isNullorEmpty(customer_id)) || !isNullorEmpty(customer_number)) { // inlineHtml += customerSection(customer_name); // inlineHtml += daytodayContactSection(daytodayphone, daytodayemail, status_value, selector_type); // inlineHtml += accountsContactSection(accountsphone, accountsemail, status_value, selector_type); // } // if(isNullorEmpty(ticket_id) || (!isNullorEmpty(ticket_id) && (selector_type == 'invoice_section'))) { // inlineHtml += maapBankAccountSection(maap_bank_account_number, maap_parent_bank_account_number, selector_type); // } // if (isNullorEmpty(ticket_id) || (!isNullorEmpty(ticket_id) && !isNullorEmpty(zee_id)) || !isNullorEmpty(customer_number)) { // inlineHtml += franchiseeMainContactSection(franchisee_name, zee_main_contact_name, zee_email, zee_main_contact_phone, zee_abn); // } // inlineHtml += mpexStockUsedSection(selector_type, date_stock_used, time_stock_used); // inlineHtml += finalDeliveryEnquirySection(status_value, selector_type, final_delivery_text, selected_enquiry_status_id); // inlineHtml += attachmentsSection(attachments_hyperlink, status_value); // if (isNullorEmpty(ticket_id) || (!isNullorEmpty(ticket_id) && (selector_type == 'invoice_number'))) { // inlineHtml += otherInvoiceFieldsSection(selected_invoice_method_id, accounts_cc_email, mpex_po_number, customer_po_number, selected_invoice_cycle_id, terms, customer_terms, status_value, selector_type); // inlineHtml += openInvoicesSection(ticket_id, selector_type); // if (!isNullorEmpty(ticket_id)) { // inlineHtml += creditMemoSection(selector_type); // inlineHtml += usageReportSection(selector_type); // } // } // inlineHtml += mpexContactSection(); // inlineHtml += enquiryMediumSection(list_enquiry_mediums, selected_enquiry_status_id ,selector_type); // inlineHtml += enquiryCountSection(total_enquiry_count, chat_enquiry_count, phone_enquiry_count, email_enquiry_count); // inlineHtml += labelSection(selected_label_id, selector_type, status_value); // inlineHtml += sendEmailSection(ticket_id, status_value, account_manager,list_toll_emails); // log.debug({ title: 'before prev email - cust id', details: customer_id }); // if(!isNullorEmpty(customer_id)){ // inlineHtml += previousEmailsSection(customer_id); // } // inlineHtml += issuesHeader(); // inlineHtml += customerIssuesSection(ticket_id, selector_type, selector_number, screenshot_file, browser, login_email_used, operating_system, phone_used, old_sender_name, old_sender_phone, status_value); // if(selector_type == "barcode_number" || selector_type == "invoice_number"){ // inlineHtml += reminderSection(status_value); // } // inlineHtml += ownerSection(ticket_id, owner_list, status_value); // inlineHtml += tollIssuesSection(list_toll_issues, list_resolved_toll_issues, status_value, selector_type); // inlineHtml += mpTicketIssuesSection(list_mp_ticket_issues, list_resolved_mp_ticket_issues, status_value, selector_type); // inlineHtml += invoiceIssuesSection(list_invoice_issues, list_resolved_invoice_issues, status_value, selector_type); // inlineHtml += usernoteSection(selector_type, status_value); // inlineHtml += commentSection(comment, selector_type, status_value); // inlineHtml += dataTablePreview(); //inlineHtml += closeReopenSubmitTicketButton(ticket_id, status_value); form.addField({ id: 'preview_table', type: ui.FieldType.INLINEHTML, label: 'preview_table' }).defaultValue = inlineHtml; form.addField({ id: 'custpage_open_new_ticket', type: ui.FieldType.TEXT, label: 'Open New Ticket' }).updateDisplayType({ displayType: ui.FieldDisplayType.HIDDEN }).defaultValue = 'F'; log.debug({ title: 'Selector_number', details: selector_number }); form.addField({ id: 'custpage_selector_number', type: ui.FieldType.TEXT, label: 'Selector Number' }).updateDisplayType({ displayType: ui.FieldDisplayType.HIDDEN }).defaultValue = selector_number; form.addField({ id: 'custpage_selector_type', type: ui.FieldType.TEXT, label: 'Selector Type' }).updateDisplayType({ displayType: ui.FieldDisplayType.HIDDEN }).defaultValue = selector_type; if (!isNullorEmpty(ticket_id)) { form.addField({ id: 'custpage_ticket_id', type: ui.FieldType.TEXT, label: 'Ticket ID' }).updateDisplayType({ displayType: ui.FieldDisplayType.HIDDEN }).defaultValue = ticket_id; } else { form.addField({ id: 'custpage_ticket_id', type: ui.FieldType.TEXT, label: 'Ticket ID' }).updateDisplayType({ displayType: ui.FieldDisplayType.HIDDEN }); } form.addField({ id: 'custpage_selector_id', type: ui.FieldType.TEXT, label: 'Selector ID' }).updateDisplayType({ displayType: ui.FieldDisplayType.HIDDEN }).defaultValue = selector_id; form.addField({ id: 'custpage_selector_issue', type: ui.FieldType.TEXT, label: 'Barcode issue' }).updateDisplayType({ displayType: ui.FieldDisplayType.HIDDEN }).defaultValue = 'F'; form.addField({ id: 'custpage_customer_id', type: ui.FieldType.TEXT, label: 'Customer ID' }).updateDisplayType({ displayType: ui.FieldDisplayType.HIDDEN }).defaultValue = customer_id; form.addField({ id: 'custpage_customer_number', type: ui.FieldType.TEXT, label: 'Customer Number' }).updateDisplayType({ displayType: ui.FieldDisplayType.HIDDEN }).defaultValue = customer_number; form.addField({ id: 'custpage_zee_id', type: ui.FieldType.TEXT, label: 'Franchisee ID' }).updateDisplayType({ displayType: ui.FieldDisplayType.HIDDEN }).defaultValue = zee_id; form.addField({ id: 'custpage_ticket_status_value', type: ui.FieldType.TEXT, label: 'Status Value' }).updateDisplayType({ displayType: ui.FieldDisplayType.HIDDEN }).defaultValue = status_value; form.addField({ id: 'custpage_created_ticket', type: ui.FieldType.TEXT, label: 'Created Ticket' }).updateDisplayType({ displayType: ui.FieldDisplayType.HIDDEN }).defaultValue = 'F'; form.addField({ id: 'custpage_usage_report_array', type: ui.FieldType.TEXT, label: 'Usage Reports' }).updateDisplayType({ displayType: ui.FieldDisplayType.HIDDEN }).defaultValue = JSON.stringify(usage_report_array); form.addField({ id: 'custpage_param_email', type: ui.FieldType.TEXT, label: 'Email parameters' }).updateDisplayType({ displayType: ui.FieldDisplayType.HIDDEN }).defaultValue = JSON.stringify(params_email); form.addField({ id: 'custpage_ss_image', type: ui.FieldType.TEXT, label: 'Screenshot Image' }).updateDisplayType({ displayType: ui.FieldDisplayType.HIDDEN }).defaultValue = screenshot_file; form.addField({ id: 'custpage_customer_number_email_sent', type: ui.FieldType.TEXT, label: 'Customer Email Sent' }).updateDisplayType({ displayType: ui.FieldDisplayType.HIDDEN }).defaultValue = customer_number_email_sent; if (!isNullorEmpty(ticket_id)) { if (isTicketNotClosed(status_value)) { form.addSubmitButton({ label: 'Update Ticket' }); } // else { // form.addSubmitButton({ label: 'Reopen Ticket' }); // } } else { form.addSubmitButton({ label: 'Save Ticket' }); // form.addButton({ id: 'custpage_openandnew', label: 'Open & New Ticket', functionName: 'openAndNew()' }); // } // if (isTicketNotClosed(status_value)) { // form.addButton({ id: 'custpage_escalate', label: 'Escalate', functionName: 'onEscalate()' }); } // form.addButton({ id: 'custpage_cancel', label: 'Cancel', functionName: 'onCancel()' }); form.clientScriptFileId = 4813453;//SB=4796340 PROD=4813453 context.response.writePage(form); } else { log.debug({ title: "In else POST part", details: '' }); var created_ticket = context.request.parameters.custpage_created_ticket; log.debug({ title: "created_ticket", details: created_ticket }); var is_ss_changed = context.request.parameters.custpage_is_ss_changed; log.debug({ title: "is_ss_changed", details: is_ss_changed }); if (created_ticket == 'T') { var ticket_id = context.request.parameters.custpage_ticket_id; var selector_number = context.request.parameters.custpage_selector_number; var selector_type = context.request.parameters.custpage_selector_type; var open_new_ticket = context.request.parameters.custpage_open_new_ticket; if (open_new_ticket == 'T') { // If the ticket was just created, and the user clicked on 'Open & New Ticket', // The user is redirected to a new "Open Ticket" page. redirect.toSuitelet({ scriptId: 'customscript_sl_open_ticket_2', deploymentId: 'customdeploy_sl_open_ticket_2', parameters: params2 }); } else { custparam_params = { ticket_id: parseInt(ticket_id), selector_number: selector_number, selector_type: selector_type, } custparam_params = JSON.stringify(custparam_params); log.debug({ title: "custparams", details: custparam_params }); var params2 = { custparam_params: custparam_params }; // If the ticket was just created, the user is redirected to the "Edit Ticket" page redirect.toSuitelet({ scriptId: 'customscript_sl_open_ticket_2', deploymentId: 'customdeploy_sl_open_ticket_2', parameters: params2 }); } } else { var params_email = context.request.parameters.custpage_param_email; params_email = JSON.parse(params_email); var to = params_email.recipient; var email_subject = params_email.subject; var email_body = decodeURIComponent(params_email.body); var cc = null; var bcc = null var emailAttach = null; var attachments_credit_memo_ids = null; var attachments_usage_report_ids = null; var attachments_invoice_ids = null; var customer_id = context.request.parameters.custpage_customer_id; var open_new_ticket = context.request.parameters.custpage_open_new_ticket; if (!isNullorEmpty(params_email.cc)) { cc = params_email.cc; } if (!isNullorEmpty(params_email.bcc)) { bcc = params_email.bcc; } if (!isNullorEmpty(params_email.records)) { emailAttach = params_email.records; } var attachement_files = []; if (!isNullorEmpty(params_email.attachments_credit_memo_ids)) { attachments_credit_memo_ids = params_email.attachments_credit_memo_ids; attachments_credit_memo_ids.forEach(function(record_id) { render.transaction({ entityId: record_id, printMode: render.PrintMode.PDF, formId: number, inCustLocale: boolean }); }); } if (!isNullorEmpty(params_email.attachments_usage_report_ids)) { attachments_usage_report_ids = params_email.attachments_usage_report_ids; attachments_usage_report_ids.forEach(function(record_id) { attachement_files.push(file.load({ id: record_id })); }); } if (!isNullorEmpty(params_email.attachments_invoice_ids)) { attachments_invoice_ids = params_email.attachments_invoice_ids; attachments_invoice_ids.forEach(function(invoice_id) { render.transaction({ entityId: invoice_id, printMode: render.PrintMode.PDF, }) }); } // If the parameter is non null, it means that the "SEND EMAIL" button was clicked. if (!isNullorEmpty(attachement_files)) { try { email.send({ author: 112209, body: email_body, recipients: to, subject: email_subject, attachments: attachement_files, bcc: bcc, cc: cc, relatedRecords: { entityId: customer_id}, }); // 112209 is from MailPlus Team } catch (error) { if (error instanceof error.SuiteScriptError) { return error.name; } } } log.debug({ title: 'open_new_ticket', details: open_new_ticket }); if (open_new_ticket == 'T') { log.debug({ title: 'open ticket page', details: 'open ticket page' }) // If the ticket was just updated, and the user clicked on 'Updated & New Ticket', // The user is redirected to a new "Open Ticket" page. redirect.toSuitelet({ scriptId: 'customscript_sl_open_ticket_2', deploymentId: 'customdeploy_sl_open_ticket_2', }); } else { // If the ticket was updated, the user is redirected to the "View MP Tickets" page redirect.toSuitelet({ scriptId: 'customscript_sl_edit_ticket_2', deploymentId: 'customdeploy_sl_edit_ticket_2', }); } } } } function instructionsBox(ticket_id) { //Important Instructions box var inlineHtml = '<br></br>' inlineHtml += '<div></div>'; inlineHtml += '<div class="form-group container test_section">'; //inlineHtml += '<button type="button" class="btn btn-sm btn-info instruction_button" data-toggle="collapse" data-target="#demo">Click for Instructions</button>'; //inlineHtml += '<div id="demo" style="background-color: #cfeefc !important;border: 1px solid #417ed9;padding: 20px 30px 30px 30px;width:96%;position:absolute" class="collapse"><b><u>IMPORTANT INSTRUCTIONS:</u></b>'; inlineHtml += '<div style=\"background-color: #e3e8e5 !important;border: 2px solid #379E8F;padding: 20px 30px 30px 30px; text-align: left\"><b><u>Mandatory Fields:</u></b>'; inlineHtml += '<ul>'; inlineHtml += '<li><b><u>Ticket Details</u></b>: Total Enquiry Count must be at least 1 i.e. Chat/Email/Phone must have at least 1 incremented and Receiver Details should be filled in if blank</li>'; inlineHtml += '<li><b><u>Issues</u></b>: Owner and Toll Emails must have at least one selected</li>'; inlineHtml += '<li>If you have any issues, please contact Ankith</li>'; inlineHtml += '</ul></div></div><br/>'; return inlineHtml; } function externalBarcodeSource(selector_type, barcodempdl, barcodesource) { var disabled = 'disabled'; var inlineQty = ''; if (selector_type == 'barcode_number') { inlineQty += '<div class="form-group container barcode_section">'; inlineQty += '<div class="row">'; // MPLD field inlineQty += '<div class="col-xs-6 barcodempdl_div">'; inlineQty += '<div class="input-group">'; inlineQty += '<span class="input-group-addon" id="barcodempdl_text">EXTERNAL BARCODE</span>'; inlineQty += '<input id="barcodempdl" value="' + barcodempdl + '" class="form-control barcodempdl" ' + disabled + ' />'; inlineQty += '</div></div>'; // barcode source field inlineQty += '<div class="col-xs-6 barcodesource_div">'; inlineQty += '<div class="input-group">'; inlineQty += '<span class="input-group-addon" id="barcodesource_text">BARCODE SOURCE</span>'; inlineQty += '<input id="barcodesource" value="' + barcodesource + '" class="form-control barcodesource" ' + disabled + ' />'; inlineQty += '</div></div></div></div>'; } return inlineQty; } function tabsSection(customer_number, ticket_id, selector_number, selector_id, selector_type, status_value, customer_name, daytodayphone, daytodayemail, franchisee_name, zee_main_contact_name, zee_email, zee_main_contact_phone, zee_abn, date_stock_used, time_stock_used, final_delivery_text, selected_enquiry_status_id, attachments_hyperlink, owner_list, list_toll_issues, list_resolved_toll_issues, comment, date_created, creator_id, creator_name, status, customer_id, accountsphone, accountsemail, zee_id, list_enquiry_mediums, total_enquiry_count, chat_enquiry_count, phone_enquiry_count, email_enquiry_count, selected_label_id, maap_bank_account_number, maap_parent_bank_account_number, account_manager, list_toll_emails, customer_barcode_number, connote_number, receiveremail, receiverphone, receivername, receiverstate, receiverzip, receiversuburb, receiveraddr1, receiveraddr2, prod_stock_invoice, barcodempdl, barcodesource, list_mp_ticket_issues, list_resolved_mp_ticket_issues, list_invoice_issues, list_resolved_invoice_issues, selected_invoice_method_id, accounts_cc_email, mpex_po_number, customer_po_number, selected_invoice_cycle_id, terms, customer_terms, screenshot_file, browser, login_email_used, operating_system, phone_used, old_sender_name, old_sender_phone, phone_interaction_count, email_interaction_count, escalated_to_it) { var inlineQty = '<div style="margin-top: -10px"><br/>'; // BUTTONS if (!isNullorEmpty(ticket_id)) { if (isTicketNotClosed(status_value) && selector_type != "customer_issue") { inlineQty += '<button style="float: left; margin-left: 10px; margin-right: 5px; background-color: #FBEA51; color: #103D39; font-weight: 700; border-color: transparent; border-width: 2px; border-radius: 15px; height: 30px" type="button" id="updateticketbutton" onclick="">Update & New Ticket</button>'; inlineQty += '<button style="float: left; margin-left: 5x; margin-right: 5px; background-color: #FBEA51; color: #103D39; font-weight: 700; border-color: transparent; border-width: 2px; border-radius: 15px; height: 30px" type="button" id="updatecloseticketbutton" onclick="">Update & Close Ticket</button>'; } else if (!isTicketNotClosed(status_value)) { inlineQty += '<button style="float: left; margin-left: 10px; margin-right: 5px; background-color: #FBEA51; color: #103D39; font-weight: 700; border-color: transparent; border-width: 2px; border-radius: 15px; height: 30px" type="button" id="reopenticketbutton" onclick="">Reopen Ticket</button>'; } } else { //inlineQty += '<button style="float: left; margin-left: 10px; margin-right: 5px; background-color: #FBEA51; color: #103D39; font-weight: 700; border-color: transparent; border-width: 2px; border-radius: 15px; height: 30px" type="button" id="openticketbutton" onclick="">Save Ticket</button>'; inlineQty += '<button style="float: left; margin-left: 10px; margin-right: 5px; background-color: #FBEA51; color: #103D39; font-weight: 700; border-color: transparent; border-width: 2px; border-radius: 15px; height: 30px" type="button" id="opennewticketbutton" onclick="">Save & New Ticket</button>'; } if (isTicketNotClosed(status_value)) { if (!isNullorEmpty(ticket_id) && selector_type != "customer_issue") { inlineQty += '<button style="float: left; margin-left: 5px; margin-right: 5px; background-color: #f4524d; color: #fff; font-weight: 700; border-color: transparent; border-width: 2px; border-radius: 15px; height: 30px" type="button" id="closeticketbutton" onclick="">Close Ticket</button>'; inlineQty += '<button style="float: left; margin-left: 5px; margin-right: 5px; background-color: #f4524d; color: #fff; font-weight: 700; border-color: transparent; border-width: 2px; border-radius: 15px; height: 30px" type="button" id="closenewticketbutton" onclick="">Close & New Ticket</button>'; inlineQty += '<button style="float: left; margin-left: 5px; margin-right: 5px; background-color: #f4524d; color: #fff; font-weight: 700; border-color: transparent; border-width: 2px; border-radius: 15px; height: 30px" type="button" id="closelostbutton" onclick="">Close Ticket - Lost Item</button>'; if (userId == 409635 || userId == 696992 || userId == 766498) { inlineQty += '<button style="float: left; margin-left: 5px; margin-right: 5px; background-color: #FBEA51; color: #103D39; font-weight: 700; border-color: transparent; border-width: 2px; border-radius: 15px; height: 30px" type="button" id="closeunallocatedbutton" onclick="">Close Unallocated Ticket</button>'; } } else if (!isNullorEmpty(ticket_id) && !isNullorEmpty(escalated_to_it)) { inlineQty += '<button style="float: left; margin-left: 5px; margin-right: 5px; background-color: #f4524d; color: #fff; font-weight: 700; border-color: transparent; border-width: 2px; border-radius: 15px; height: 30px" type="button" id="closeresolvedbutton" onclick="">Close - Resolved Ticket</button>'; inlineQty += '<button style="float: left; margin-left: 5px; margin-right: 5px; background-color: #f4524d; color: #fff; font-weight: 700; border-color: transparent; border-width: 2px; border-radius: 15px; height: 30px" type="button" id="closeunresolvedbutton" onclick="">Close - Unresolved Ticket</button>'; } else { inlineQty += '<button style="float: left; margin-left: 5px; margin-right: 5px; background-color: #f4524d; color: #fff; font-weight: 700; border-color: transparent; border-width: 2px; border-radius: 15px; height: 30px" type="button" id="closeticketbutton" onclick="">Close Ticket</button>'; } } // ESCALATE AND CANCEL BUTTONS log.debug({ title: 'debugging', }); log.debug({ title: "selector_type", details: selector_type }); log.debug({ title: "isTicketNotClosed(status_value)", details: isTicketNotClosed(status_value) }); log.debug({ title: "!isNullorEmpty(ticket_id)", details: !isNullorEmpty(ticket_id) }); log.debug({ title: "userId", details: userId }); if (selector_type == "customer_issue" && isTicketNotClosed(status_value) && !isNullorEmpty(ticket_id) && isNullorEmpty(escalated_to_it)) { inlineQty += '<button style="float: left; margin-left: 5px; margin-right: 5px; background-color: #fc9003; color: #fff; font-weight: 700; border-color: transparent; border-width: 2px; border-radius: 15px; height: 30px" type="button" id="escalaterianne" onclick="">Escalate To IT</button>'; } else if (selector_type == "customer_issue" && isTicketNotClosed(status_value) && !isNullorEmpty(ticket_id) && !isNullorEmpty(escalated_to_it) && status_value != 10 && status_value != 17) { inlineQty += '<button style="float: left; margin-left: 5px; margin-right: 5px; background-color: #fc9003; color: #fff; font-weight: 700; border-color: transparent; border-width: 2px; border-radius: 15px; height: 30px" type="button" id="escalateankith" onclick="">Escalate To Ankith</button>'; } else if (selector_type == "customer_issue" && isTicketNotClosed(status_value) && !isNullorEmpty(ticket_id) && status_value == 10) { inlineQty += '<button style="float: left; margin-left: 5px; margin-right: 5px; background-color: #fc9003; color: #fff; font-weight: 700; border-color: transparent; border-width: 2px; border-radius: 15px; height: 30px" type="button" id="escalateunderdev" onclick="">Set Status to Under Development</button>'; } else if (selector_type == "customer_issue" && isTicketNotClosed(status_value) && !isNullorEmpty(ticket_id) && status_value == 17) { inlineQty += '<button style="float: left; margin-left: 5px; margin-right: 5px; background-color: #fc9003; color: #fff; font-weight: 700; border-color: transparent; border-width: 2px; border-radius: 15px; height: 30px" type="button" id="escalateremoveunderdev" onclick="">Remove Under Development Status</button>'; } else if (isTicketNotClosed(status_value) && !isNullorEmpty(ticket_id) && selector_type != "customer_issue") { inlineQty += '<button style="float: left; margin-left: 5px; margin-right: 5px; background-color: #379E8F; color: #fff; font-weight: 700; border-color: transparent; border-width: 2px; border-radius: 15px; height: 30px" type="button" id="escalatebutton" onclick="">' + escalateButton(status_value) + '</button>'; } if (!isNullorEmpty(ticket_id) && !isTicketNotClosed(status_value)) { inlineQty += '<button style="float: left; margin-left: 10px; margin-right: 5px; background-color: #FBEA51; color: #103D39; font-weight: 700; border-color: transparent; border-width: 2px; border-radius: 15px; height: 30px" type="button" id="cancelbutton" onclick="">Cancel</button>'; } else { inlineQty += '<button style="float: left; margin-left: 5px; margin-right: 5px; background-color: #FBEA51; color: #103D39; font-weight: 700; border-color: transparent; border-width: 2px; border-radius: 15px; height: 30px" type="button" id="cancelbutton" onclick="">Cancel</button>'; } // Title if (!isNullorEmpty(ticket_id)) { inlineQty += '<h1 style="display: inline-block; font-size: 25px; margin-top: 20px; font-weight: 700; color: #103D39; text-align: center; width: 100%">Edit Ticket - MPSD' + ticket_id + '</h1>' } else { inlineQty += '<h1 style="display: inline-block; font-size: 25px; font-weight: 700; color: #103D39; text-align: center; width: 100%">Open New Ticket</h1>' } inlineQty += instructionsBox(); // Tabs headers inlineQty += '<style>.nav > li.active > a, .nav > li.active > a:focus, .nav > li.active > a:hover { background-color: #379E8F; color: #fff }'; inlineQty += '.nav > li > a, .nav > li > a:focus, .nav > li > a:hover { margin-left: 5px; margin-right: 5px; border: 2px solid #379E8F; color: #379E8F; }'; inlineQty += '</style>'; // Ticket details header inlineQty += '<div class="form-group container tickets_details_header_section" style="margin-top: 10px">'; inlineQty += '<div class="row">'; inlineQty += '<div class="col-xs-12" >'; inlineQty += '<span">'; inlineQty += '<ul class="nav nav-pills nav-justified" style="margin:0%; ">'; inlineQty += '<li role="presentation" class="active"><a data-toggle="tab" href="#ticketdetails"><b>TICKET DETAILS</b></a></li>'; inlineQty += '<li role="presentation" class=""><a data-toggle="tab" href="#issues"><b>ISSUES</b></a></li>'; if (!isNullorEmpty(ticket_id)) { inlineQty += '<li role="presentation" class=""><a data-toggle="tab" href="#sendemail"><b>SEND EMAIL</b></a></li>'; } else { inlineQty += '<li role="presentation" class=""><a data-toggle="tab" href="#contactdetails"><b>CONTACT DETAILS</b></a></li>'; } if (!isNullorEmpty(ticket_id)) { inlineQty += '<li role="presentation" class=""><a data-toggle="tab" href="#prevtickets"><b>PREVIOUS TICKETS</b></a></li>'; inlineQty += '<li role="presentation" class=""><a data-toggle="tab" href="#prevemails"><b>PREVIOUS EMAILS</b></a></li>'; } //style="background-color: #379E8F" inlineQty += '</ul>'; inlineQty += '</span>'; inlineQty += '</div></div></div>'; // Tabs content inlineQty += '<div class="tab-content">'; // TICKET DETAILS TAB inlineQty += '<div role="tabpanel" class="tab-pane active" id="ticketdetails">'; inlineQty += customerNumberSection(customer_number, ticket_id, selector_type, escalated_to_it, creator_id); inlineQty += selectorSection(ticket_id, selector_number, selector_id, selector_type, status_value); if (!isNullorEmpty(ticket_id)) { inlineQty += ticketSection(dateISOToNetsuite(date_created), creator_id, creator_name, status, connote_number); inlineQty += externalBarcodeSource(selector_type, barcodempdl, barcodesource) } if (isNullorEmpty(ticket_id) || (!isNullorEmpty(ticket_id) && !isNullorEmpty(customer_id)) || !isNullorEmpty(customer_number)) { inlineQty += customerSection(customer_name); inlineQty += daytodayContactSection(daytodayphone, daytodayemail, status_value, selector_type); inlineQty += accountsContactSection(accountsphone, accountsemail, status_value, selector_type); } else if (isNullorEmpty(customer_number) && creator_id == 112209 && !isNullorEmpty(escalated_to_it) && selector_type == "customer_issue" && !isNullorEmpty(ticket_id)) { inlineQty += customerSection(customer_name); inlineQty += daytodayContactSection(daytodayphone, daytodayemail, status_value, selector_type); inlineQty += accountsContactSection(accountsphone, accountsemail, status_value, selector_type); } if(isNullorEmpty(ticket_id) || (!isNullorEmpty(ticket_id) && (selector_type == 'invoice_section'))) { inlineQty += maapBankAccountSection(maap_bank_account_number, maap_parent_bank_account_number, selector_type); } if (isNullorEmpty(ticket_id) || (!isNullorEmpty(ticket_id) && !isNullorEmpty(zee_id)) || !isNullorEmpty(customer_number)) { inlineQty += franchiseeMainContactSection(franchisee_name, zee_main_contact_name, zee_email, zee_main_contact_phone, zee_abn); } inlineQty += mpexStockUsedSection(selector_type, date_stock_used, time_stock_used); inlineQty += finalDeliveryEnquirySection(status_value, selector_type, final_delivery_text, selected_enquiry_status_id, prod_stock_invoice); inlineQty += attachmentsSection(attachments_hyperlink, status_value); if (isNullorEmpty(ticket_id) || (!isNullorEmpty(ticket_id) && (selector_type == 'invoice_number'))) { inlineQty += otherInvoiceFieldsSection(selected_invoice_method_id, accounts_cc_email, mpex_po_number, customer_po_number, selected_invoice_cycle_id, terms, customer_terms, status_value, selector_type); // inlineQty += enquiryMediumSection(list_enquiry_mediums, selected_enquiry_status_id, selector_type); // inlineQty += enquiryCountSection( total_enquiry_count, chat_enquiry_count, phone_enquiry_count, email_enquiry_count, selector_type); inlineQty += openInvoicesSection(ticket_id, selector_type); if (!isNullorEmpty(ticket_id)) { inlineQty += creditMemoSection(selector_type); inlineQty += usageReportSection(selector_type); } } inlineQty += enquiryMediumSection(list_enquiry_mediums, selected_enquiry_status_id, selector_type); inlineQty += enquiryCountSection( total_enquiry_count, chat_enquiry_count, phone_enquiry_count, email_enquiry_count, selector_type, phone_interaction_count, email_interaction_count); if(!isNullorEmpty(ticket_id)) { inlineQty += receiverEmailPhone(selector_type, receiveremail, receiverphone, receivername, receiverstate, receiverzip, receiversuburb, receiveraddr1, receiveraddr2); } //TICKET LABEL DROPDOWN //inlineQty += labelSection(selected_label_id, selector_type, status_value); inlineQty += '</div>'; // ISSUES TAB inlineQty += '<div role="tabpanel" class="tab-pane" id="issues">'; inlineQty += issuesHeader(); inlineQty += customerIssuesSection(ticket_id, selector_type, selector_number, screenshot_file, browser, login_email_used, operating_system, phone_used, old_sender_name, old_sender_phone, status_value); if(selector_type == "barcode_number" || selector_type == "invoice_number"){ inlineQty += reminderSection(status_value); } inlineQty += ownerSection(ticket_id, owner_list, status_value); inlineQty += tollIssuesSection(list_toll_issues, list_resolved_toll_issues, status_value, selector_type); inlineQty += mpTicketIssuesSection(list_mp_ticket_issues, list_resolved_mp_ticket_issues, status_value, selector_type); inlineQty += invoiceIssuesSection(list_invoice_issues, list_resolved_invoice_issues, status_value, selector_type); inlineQty += usernoteSection(selector_type, status_value); inlineQty += commentSection(comment, selector_type, status_value); inlineQty += '</div>'; // CONTACT / EMAILS if (!isNullorEmpty(ticket_id)) { inlineQty += '<div role="tabpanel" class="tab-pane" id="sendemail">'; inlineQty += mpexContactSection(); inlineQty += sendEmailSection(ticket_id, status_value, account_manager, list_toll_emails); //inlineQty += closeReopenSubmitTicketButton(ticket_id, status_value); inlineQty += '</div>'; } else { inlineQty += '<div role="tabpanel" class="tab-pane" id="contactdetails">'; inlineQty += mpexContactSection(); //inlineQty += closeReopenSubmitTicketButton(ticket_id, status_value); inlineQty += '</div>'; } // PREV TICKETS + EMAILS TAB if (!isNullorEmpty(ticket_id)) { // PREV TICKETS TAB inlineQty += '<div role="tabpanel" class="tab-pane" id="prevtickets">'; inlineQty += dataTablePreview(); //inlineQty += closeReopenSubmitTicketButton(ticket_id, status_value); inlineQty += '</div>'; inlineQty += '<div role="tabpanel" class="tab-pane" id="prevemails">'; log.debug({ title: 'before prev email - cust id', details: customer_id }); if(!isNullorEmpty(customer_id)){ inlineQty += previousEmailsSection(customer_id); } //inlineQty += closeReopenSubmitTicketButton(ticket_id, status_value); inlineQty += '</div>'; } inlineQty += '</div></div>'; return inlineQty; } /** * The "Customer number" input field. If there is a Ticket ID, then we are on the Edit Ticket page and * this field is pre-filled. * @param {*} customer_number */ function customerNumberSection(customer_number, ticket_id, selector_type, escalated_to_it, creator_id){ if(isNullorEmpty(customer_number)){ customer_number = ''; } // var disable = isNullorEmpty(ticket_id) ? '': 'disabled'; // Ticket details header var inlineQty = '<div class="form-group container tickets_details_header_section">'; inlineQty += '<div class="row">'; inlineQty += '<div class="col-xs-12 heading2" >'; inlineQty += '<h4><span style="background-color: #379E8F" class="label label-default col-xs-12">TICKET DETAILS</span></h4>'; inlineQty += '</div></div></div>'; // Customer number section inlineQty += '<div class="form-group container customer_number_section">'; inlineQty += '<div class="row">'; //Customer number field inlineQty += '<div class="col-xs-12 customer_number">'; inlineQty += '<div class="input-group">'; inlineQty += '<span class="input-group-addon" id="customer_number_text">CUSTOMER NUMBER</span>'; if(customer_number == '' && isNullorEmpty(ticket_id)){ inlineQty += '<input id="customer_number_value" value=" '+ customer_number +' " class="form-control customer_number">'; } else if (customer_number == '' && creator_id == 112209 && !isNullorEmpty(escalated_to_it) && selector_type == "customer_issue" && !isNullorEmpty(ticket_id)) { inlineQty += '<input id="customer_number_value" value=" '+ customer_number +' " class="form-control customer_number">'; } else{ inlineQty += '<input id="customer_number_value" value=" '+ customer_number +' " class="form-control customer_number" disabled>'; } inlineQty += '</div></div></div></div>'; //Datatable for all tickets asscoiated to current customer number inlineQty += '<div class="row">'; inlineQty += '<div class="form-group container customer_number_tickets">'; inlineQty += '<style> table {font-size: 12px;text-align: center;border: none;} {font-size: 14px;} table th{text-align: center;} .dataTables_wrapper{width:78%; margin-bottom:40px; margin-left: auto; margin-right: auto; margin-top: auto;} </style>'; inlineQty += '<table cellpadding="15" id="customer_number_tickets_preview" class="table table-responsive table-striped customer tablesorter" cellspacing="0" style="width: 100%;">'; inlineQty += '<thead style="color: white;background-color: #379E8F;">'; inlineQty += '<tr class="text-center">'; inlineQty += '</tr>'; inlineQty += '</thead></table>'; inlineQty += '</div></div>'; return inlineQty; } /** * The "Barcode number" OR "Invoice Number" input field. * If there is a TICKET ID, we are in the "Edit Ticket", so we display the Ticket ID field and the selector field is disabled. * @param {Number} ticket_id * @param {String} selector_number * @param {Number} selector_id * @param {String} selector_type * @param {Number} status_value * @return {String} inlineQty */ function selectorSection(ticket_id, selector_number, selector_id, selector_type, status_value) { if (isNullorEmpty(selector_number)) { selector_number = ''; } var inlineQty = '<div class="form-group container selector_section">'; inlineQty += '<div class="row">'; if (!isNullorEmpty(ticket_id)) { // Ticket ID field inlineQty += '<div class="col-xs-6 ticket_id">'; inlineQty += '<div class="input-group">'; inlineQty += '<span class="input-group-addon" id="ticket_id_text">TICKET ID</span>'; inlineQty += '<input id="ticket_id" value="MPSD' + ticket_id + '" class="form-control ticket_id" disabled />'; inlineQty += '</div></div>'; // Selector Number field inlineQty += '<div class="col-xs-6 selector_number">'; inlineQty += '<div class="input-group">'; switch (selector_type) { case 'barcode_number': inlineQty += '<span class="input-group-addon" id="selector_text">BARCODE NUMBER</span>'; break; case 'invoice_number': inlineQty += '<span class="input-group-addon" id="selector_text">INVOICE NUMBER</span>'; break; } inlineQty += '<input id="selector_value" value="' + selector_number + '" class="form-control selector_value" disabled>'; if (selector_type == 'invoice_number') { // Open Invoice record inlineQty += '<div class="input-group-btn">'; inlineQty += '<button id="open_inv" type="button" class="btn btn-default link_inv" data-inv-id="' + selector_id + '" data-toggle="tooltip" data-placement="top" title="Open Invoice">'; inlineQty += '<span class="glyphicon glyphicon-link"></span>'; inlineQty += '</button>'; inlineQty += '</div>'; // Attach Invoice to email if (isTicketNotClosed(status_value)) { inlineQty += '<div class="input-group-btn"><button style="background-color: #379E8F" id="add_inv" type="button" class="btn btn-success add_inv" data-inv-id="' + selector_id + '" data-toggle="tooltip" data-placement="right" title="Attach to email">'; inlineQty += '<span class="glyphicon glyphicon-plus"></span>'; inlineQty += '</button></div>'; } } inlineQty += '</div></div></div></div>'; } else { inlineQty += '<div class="col-xs-12 selector_number">'; inlineQty += '<div class="input-group">'; //Input group addon text switch (selector_type) { case 'barcode_number': inlineQty += '<span class="input-group-addon" id="selector_text">BARCODE NUMBER</span>'; break; case 'invoice_number': inlineQty += '<span class="input-group-addon" id="selector_text">INVOICE NUMBER</span>'; break; case 'customer_issue': inlineQty += '<span class="input-group-addon" id="selector_text">CUSTOMER ISSUE</span>'; break; } inlineQty += '<div class="input-group-btn">'; inlineQty += '<button tabindex="-1" data-toggle="dropdown" class="btn btn-default dropdown-toggle" type="button">'; inlineQty += '<span class="caret"></span>'; inlineQty += '<span class="sr-only">Toggle Dropdown</span>'; inlineQty += '</button>'; inlineQty += '<ul class="dropdown-menu hide" style="list-style:none;margin: 2px 0 0;">'; inlineQty += '<li><a href="#">BARCODE NUMBER</a></li>'; inlineQty += '<li><a href="#">INVOICE NUMBER</a></li>'; //inlineQty += '<li><a href="#">CUSTOMER APP</a></li>'; inlineQty += '<li><a href="#">CUSTOMER PORTAL</a></li>'; inlineQty += '<li><a href="#">UPDATE LABEL</a></li>'; inlineQty += '</ul>'; inlineQty += '</div>'; //Input text switch (selector_type) { case 'barcode_number': inlineQty += '<input id="selector_value" class="form-control selector_value" placeholder="MPEN123456">'; break; case 'invoice_number': inlineQty += '<input id="selector_value" class="form-control selector_value" placeholder="INV123456">'; break; case 'customer_app': inlineQty += '<input id="selector_value" class="form-control selector_value" placeholder="Customer App" disabled value="Customer App">'; break; case 'customer_portal': inlineQty += '<input id="selector_value" class="form-control selector_value" placeholder="Customer Portal" disabled value="Customer Portal">'; break; case 'update_label': inlineQty += '<input id="selector_value" class="form-control selector_value" placeholder="Update Label" disabled value="Update Label">'; break; } inlineQty += '</div></div></div></div>'; } return inlineQty; } /** * The informations regarding the ticket being edited. * @param {String} date_created * @param {Number} creator_id * @param {String} creator_name * @param {String} status * @return {String} inlineQty */ function ticketSection(date_created, creator_id, creator_name, status, connote_number) { if (isNullorEmpty(date_created)) { date_created = ''; } if (isNullorEmpty(creator_name)) { creator_name = ''; } if (isNullorEmpty(status)) { status = ''; } var inlineQty = '<div class="form-group container created_status_section">'; inlineQty += '<div class="row">'; // Date created field inlineQty += '<div class="col-xs-6 date_created">'; inlineQty += '<div class="input-group">'; inlineQty += '<span class="input-group-addon" id="date_created_text">DATE CREATED</span>'; inlineQty += '<input id="date_created" value="' + date_created + '" class="form-control date_created" disabled />'; inlineQty += '</div></div>'; // Creator field inlineQty += '<div class="col-xs-6 creator">'; inlineQty += '<div class="input-group">'; inlineQty += '<span class="input-group-addon" id="creator_text">CREATOR</span>'; inlineQty += '<input id="creator" value="' + creator_name + '" data-creator-id="' + creator_id + '" class="form-control creator" disabled />'; inlineQty += '</div></div></div></div>'; // Status Section inlineQty += '<div class="form-group container status_section">'; inlineQty += '<div class="row">'; // Status field inlineQty += '<div class="col-xs-6 status">'; inlineQty += '<div class="input-group">'; inlineQty += '<span class="input-group-addon" id="status_text">STATUS</span>'; inlineQty += '<input id="status" value="' + status + '" class="form-control status" disabled />'; inlineQty += '</div></div>'; // Customer Status field inlineQty += '<div class="col-xs-6 status">'; inlineQty += '<div class="input-group">'; inlineQty += '<span class="input-group-addon" id="status_text">CONNOTE NUMBER</span>'; inlineQty += '<input id="status" value="' + connote_number + '" class="form-control status" disabled />'; inlineQty += '</div></div></div></div>'; return inlineQty; } /** * The Customer name field. * The customer name field should be automatically filled based on the Selector number value. * @param {String} customer_name * @return {String} inlineQty */ function customerSection(customer_name) { if (isNullorEmpty(customer_name)) { customer_name = ''; } // Customer Section var inlineQty = '<div class="form-group container customer_section">'; inlineQty += '<div class="row">'; // Customer name field inlineQty += '<div class="col-xs-12 customer_name">'; inlineQty += '<div class="input-group">'; inlineQty += '<span class="input-group-addon" id="customer_name_text">CUSTOMER NAME</span>'; inlineQty += '<input id="customer_name" value="' + customer_name + '" class="form-control customer_name" disabled>'; inlineQty += '</div></div></div></div>'; return inlineQty; } /** * The day to day phone and email fields of the customer. * These fields should be automatically filled based on the Selector number value. * @param {String} daytodayphone * @param {String} daytodayemail * @param {Number} status_value * @param {String} selector_type * @return {String} inlineQty */ function daytodayContactSection(daytodayphone, daytodayemail, status_value, selector_type) { if (isNullorEmpty(daytodayphone)) { daytodayphone = ''; } if (isNullorEmpty(daytodayemail)) { daytodayemail = ''; } var disabled = 'disabled'; if ((isFinanceRole(userRole)) && isTicketNotClosed(status_value) && selector_type == 'invoice_number') { disabled = ''; } var inlineQty = '<div class="form-group container daytodaycontact_section">'; inlineQty += '<div class="row">'; // Day to day email field inlineQty += '<div class="col-xs-6 daytodayemail_div">'; inlineQty += '<div class="input-group">'; inlineQty += '<span class="input-group-addon" id="daytodayemail_text">DAY-TO-DAY EMAIL</span>'; inlineQty += '<input id="daytodayemail" type="email" value="' + daytodayemail + '" class="form-control daytodayemail" ' + disabled + ' />'; inlineQty += '<div class="input-group-btn">'; inlineQty += '<button type="button" style="background-color: #379E8F" class="btn btn-success add_as_recipient" data-email="' + daytodayemail + '" data-contact-id="" data-firstname="" data-toggle="tooltip" data-placement="right" title="Add as recipient">'; inlineQty += '<span class="glyphicon glyphicon-envelope"></span>'; inlineQty += '</button>'; inlineQty += '</div>'; inlineQty += '</div></div>'; // Day to day phone field inlineQty += '<div class="col-xs-6 daytodayphone_div">'; inlineQty += '<div class="input-group">'; inlineQty += '<span class="input-group-addon" id="daytodayphone_text">DAY-TO-DAY PHONE</span>'; inlineQty += '<input id="daytodayphone" type="tel" value="' + daytodayphone + '" class="form-control daytodayphone" ' + disabled + ' />'; inlineQty += '<div class="input-group-btn"><button type="button" style="background-color: #379E8F" class="btn btn-success" id="call_daytoday_phone"><span class="glyphicon glyphicon-earphone"></span></button></div>'; inlineQty += '</div></div></div></div>'; return inlineQty; } /** * The receiver phone and email fields. * These fields should be automatically filled based on the Selector number value. * @param {String} daytodayphone * @param {String} daytodayemail * @param {Number} status_value * @param {String} selector_type * @return {String} inlineQty */ function receiverEmailPhone(selector_type, receiveremail, receiverphone, receivername, receiverstate, receiverzip, receiversuburb, receiveraddr1, receiveraddr2) { var disabled = 'disabled'; if (isNullorEmpty(receiveremail) && isNullorEmpty(receiveraddr1) && isNullorEmpty(receiveraddr2) && isNullorEmpty(receivername) && isNullorEmpty(receiverphone) && isNullorEmpty(receiverstate) && isNullorEmpty(receiverzip) && isNullorEmpty(receiversuburb)) { disabled = ''; } var inlineQty = ''; if (selector_type == 'barcode_number') { // Receiver details header var inlineQty = '<div class="form-group container tickets_details_header_section">'; inlineQty += '<div class="row">'; inlineQty += '<div class="col-xs-12 heading2" >'; inlineQty += '<h4><span style="background-color: #379E8F" class="label label-default col-xs-12">RECEIVER DETAILS</span></h4>'; inlineQty += '</div></div></div>'; //First Row inlineQty += '<div class="form-group container receivercontact_section">'; inlineQty += '<div class="row">'; // name field inlineQty += '<div class="col-xs-4 receivername_div">'; inlineQty += '<div class="input-group">'; inlineQty += '<span class="input-group-addon" id="receivername_text">NAME</span>'; inlineQty += '<input id="receivername" value="' + receivername + '" class="form-control receivername" ' + disabled + ' />'; inlineQty += '</div></div>'; // Day to day phone field inlineQty += '<div class="col-xs-4 receiverphone_div">'; inlineQty += '<div class="input-group">'; inlineQty += '<span class="input-group-addon" id="receiverphone_text">PHONE</span>'; inlineQty += '<input id="receiverphone" type="tel" value="' + receiverphone + '" class="form-control receiverphone" ' + disabled + ' />'; inlineQty += '<div class="input-group-btn"><button type="button" style="background-color: #379E8F" class="btn btn-success" id="call_receiver_phone"><span class="glyphicon glyphicon-earphone"></span></button></div>'; inlineQty += '</div></div>'; // Day to day email field inlineQty += '<div class="col-xs-4 receiveremail_div">'; inlineQty += '<div class="input-group">'; inlineQty += '<span class="input-group-addon" id="receiveremail_text">EMAIL</span>'; inlineQty += '<input id="receiveremail" type="email" value="' + receiveremail + '" class="form-control receiveremail" ' + disabled + ' />'; inlineQty += '<div class="input-group-btn">'; inlineQty += '<button type="button" style="background-color: #379E8F" class="btn btn-success add_as_recipient" data-email="' + receiveremail + '" data-contact-id="" data-firstname="" data-toggle="tooltip" data-placement="right" title="Add as recipient">'; inlineQty += '<span class="glyphicon glyphicon-envelope"></span>'; inlineQty += '</button>'; inlineQty += '</div>'; inlineQty += '</div></div>'; inlineQty += '</div></div>'; //2nd Row inlineQty += '<div class="form-group container receivercontact2_section">'; inlineQty += '<div class="row">'; // address1 field inlineQty += '<div class="col-xs-6 receiveraddr1_div">'; inlineQty += '<div class="input-group">'; inlineQty += '<span class="input-group-addon" id="receiveraddr1_text">ADDRESS1</span>'; inlineQty += '<input id="receiveraddr1" value="' + receiveraddr1 + '" class="form-control receiveraddr1" ' + disabled + ' />'; inlineQty += '</div></div>'; // address2 field inlineQty += '<div class="col-xs-6 receiveraddr2_div">'; inlineQty += '<div class="input-group">'; inlineQty += '<span class="input-group-addon" id="receiveraddr2_text">ADDRESS2</span>'; inlineQty += '<input id="receiveraddr2" value="' + receiveraddr2 + '" class="form-control receiveraddr2" ' + disabled + ' />'; inlineQty += '</div></div>'; inlineQty += '</div></div>'; //3rd Row inlineQty += '<div class="form-group container receivercontact3_section">'; inlineQty += '<div class="row">'; // suburb field inlineQty += '<div class="col-xs-4 receiversuburb_div">'; inlineQty += '<div class="input-group">'; inlineQty += '<span class="input-group-addon" id="receiversuburb_text">SUBURB</span>'; inlineQty += '<input id="receiversuburb" value="' + receiversuburb + '" class="form-control receiversuburb" ' + disabled + ' />'; inlineQty += '</div></div>'; // postcode field inlineQty += '<div class="col-xs-4 receiverzip_div">'; inlineQty += '<div class="input-group">'; inlineQty += '<span class="input-group-addon" id="receiverzip_text">POSTCODE</span>'; inlineQty += '<input id="receiverzip" value="' + receiverzip + '" class="form-control receiverzip" ' + disabled + ' />'; inlineQty += '</div></div>'; // state field inlineQty += '<div class="col-xs-4 receiverstate_div">'; inlineQty += '<div class="input-group">'; inlineQty += '<span class="input-group-addon" id="receiverstate_text">STATE</span>'; inlineQty += '<input id="receiverstate" value="' + receiverstate + '" class="form-control receiverstate" ' + disabled + ' />'; inlineQty += '</div></div>'; inlineQty += '</div></div>'; } return inlineQty; } /** * The accounts phone and email fields of the customer. * These fields should be automatically filled based on the Invoice number value. * @param {String} accountsphone * @param {String} accountsemail * @param {Number} status_value * @param {String} selector_type * @return {String} inlineQty */ function accountsContactSection(accountsphone, accountsemail, status_value, selector_type) { if (isNullorEmpty(accountsphone)) { accountsphone = ''; } if (isNullorEmpty(accountsemail)) { accountsemail = ''; } if (selector_type == 'invoice_number') { var inlineQty = '<div class="form-group container accountscontact_section">'; if (isFinanceRole(userRole) && isTicketNotClosed(status_value)) { var disabled = ''; } else { var disabled = 'disabled'; } } else { var inlineQty = '<div class="form-group container accountscontact_section hide">'; var disabled = 'disabled'; } inlineQty += '<div class="row">'; // Accounts email field inlineQty += '<div class="col-xs-6 accountsemail_div">'; inlineQty += '<div class="input-group">'; inlineQty += '<span class="input-group-addon" id="accountsemail_text">ACCOUNTS EMAIL</span>'; inlineQty += '<input id="accountsemail" type="email" value="' + accountsemail + '" class="form-control accountsemail" ' + disabled + ' />'; inlineQty += '<div class="input-group-btn">'; inlineQty += '<button type="button" style="background-color: #379E8F" class="btn btn-success add_as_recipient" data-email="' + accountsemail + '" data-contact-id="" data-firstname="" data-toggle="tooltip" data-placement="right" title="Add as recipient">'; inlineQty += '<span class="glyphicon glyphicon-envelope"></span>'; inlineQty += '</button>'; inlineQty += '</div>'; inlineQty += '</div></div>'; // Accounts phone field inlineQty += '<div class="col-xs-6 accountsphone_div">'; inlineQty += '<div class="input-group">'; inlineQty += '<span class="input-group-addon" id="accountsphone_text">ACCOUNTS PHONE</span>'; inlineQty += '<input id="accountsphone" type="tel" value="' + accountsphone + '" class="form-control accountsphone" ' + disabled + ' />'; inlineQty += '<div class="input-group-btn"><button type="button" style="background-color: #379E8F" class="btn btn-success" id="call_accounts_phone"><span class="glyphicon glyphicon-earphone"></span></button></div>'; inlineQty += '</div></div></div></div>'; return inlineQty; } /** * * @param {Number} maap_bank_account_number * @param {Number} maap_parent_bank_account_number * @param {String} selector_type * @returns {String} inlineQty */ function maapBankAccountSection(maap_bank_account_number, maap_parent_bank_account_number, selector_type) { switch (selector_type) { case 'barcode_number': var inlineQty = '<div class="form-group container accounts_number_section hide">'; break; case 'invoice_number': var inlineQty = '<div class="form-group container accounts_number_section">'; break; } inlineQty += '<div class="row">'; // MAAP Bank Account # field inlineQty += '<div class="col-xs-6 account_number_div">'; inlineQty += '<div class="input-group">'; inlineQty += '<span class="input-group-addon" id="account_number_text">MAAP BANK ACCOUNT #</span>'; inlineQty += '<input id="account_number" type="number" value="' + maap_bank_account_number + '" class="form-control account_number" disabled />'; inlineQty += '</div></div>'; // MAAP Parent Bank Account # field inlineQty += '<div class="col-xs-6 parent_account_number_div">'; inlineQty += '<div class="input-group">'; inlineQty += '<span class="input-group-addon" id="parent_account_number_text">MAAP PARENT BANK ACCOUNT #</span>'; inlineQty += '<input id="parent_account_number" type="number" value="' + maap_parent_bank_account_number + '" class="form-control parent_account_number" disabled />'; inlineQty += '</div></div></div></div>'; return inlineQty; } /** * The Franchisee name, and its main contact name and phone number fields. * These fields should be automatically filled based on the Selector number value. * @param {String} franchisee_name * @param {String} zee_main_contact_name * @param {String} zee_email * @param {String} zee_main_contact_phone * @param {String} zee_abn * @return {String} inlineQty */ function franchiseeMainContactSection(franchisee_name, zee_main_contact_name, zee_email, zee_main_contact_phone, zee_abn) { if (isNullorEmpty(franchisee_name)) { franchisee_name = ''; } if (isNullorEmpty(zee_main_contact_name)) { zee_main_contact_name = ''; } if (isNullorEmpty(zee_email)) { zee_email = ''; } if (isNullorEmpty(zee_main_contact_phone)) { zee_main_contact_phone = ''; } if (isNullorEmpty(zee_abn)) { zee_abn = ''; } var inlineQty = '<div class="form-group container zee_main_contact_section">'; inlineQty += '<div class="row">'; // Franchisee name field inlineQty += '<div class="col-xs-6 franchisee_name">'; inlineQty += '<div class="input-group">'; inlineQty += '<span class="input-group-addon" id="franchisee_name_text">FRANCHISEE NAME</span>'; inlineQty += '<input id="franchisee_name" value="' + franchisee_name + '" class="form-control franchisee_name" disabled>'; inlineQty += '</div></div>'; // Franchisee main contact name field inlineQty += '<div class="col-xs-6 zee_main_contact_name">'; inlineQty += '<div class="input-group">'; inlineQty += '<span class="input-group-addon" id="zee_main_contact_name_text">MAIN CONTACT</span>'; inlineQty += '<input id="zee_main_contact_name" value="' + zee_main_contact_name + '" class="form-control zee_main_contact_name" disabled>'; inlineQty += '</div></div></div></div>'; // Franchisee contact details inlineQty += '<div class="form-group container zee_main_contact_section">'; inlineQty += '<div class="row">'; // Franchisee email field inlineQty += '<div class="col-xs-12 zee_email">'; inlineQty += '<div class="input-group">'; inlineQty += '<span class="input-group-addon" id="zee_email_text">FRANCHISEE EMAIL</span>'; inlineQty += '<input id="zee_email" type="email" value="' + zee_email + '" class="form-control accountsemail" disabled />'; inlineQty += '<div class="input-group-btn">'; var zee_contact_id = '0'; inlineQty += '<button type="button" style="background-color: #379E8F" class="btn btn-success add_as_recipient" data-email="' + zee_email + '" data-contact-id="' + zee_contact_id + '" data-firstname="' + franchisee_name + '" data-toggle="tooltip" data-placement="right" title="Add as recipient">'; inlineQty += '<span class="glyphicon glyphicon-envelope"></span>'; inlineQty += '</button>'; inlineQty += '</div>'; inlineQty += '</div></div></div></div>'; // Franchisee phone and ABN details inlineQty += '<div class="form-group container zee_main_contact_section">'; inlineQty += '<div class="row">'; // Franchisee main contact phone field inlineQty += '<div class="col-xs-6 zee_main_contact_phone">' inlineQty += '<div class="input-group">' inlineQty += '<span class="input-group-addon" id="zee_main_contact_phone_text">FRANCHISEE PHONE</span>'; inlineQty += '<input id="zee_main_contact_phone" type="tel" value="' + zee_main_contact_phone + '" class="form-control zee_main_contact_phone" disabled />'; inlineQty += '<div class="input-group-btn"><button style="background-color: #379E8F" type="button" class="btn btn-success" id="call_zee_main_contact_phone"><span class="glyphicon glyphicon-earphone"></span></button>'; inlineQty += '</div>'; inlineQty += '</div></div>'; // Franchisee ABN number inlineQty += '<div class="col-xs-6 zee_abn">' inlineQty += '<div class="input-group">' inlineQty += '<span class="input-group-addon" id="zee_abn_text">FRANCHISEE ABN</span>' inlineQty += '<input id="zee_abn" class="form-control zee_abn" value="' + zee_abn + '" disabled>' inlineQty += '</div></div></div></div>'; return inlineQty; } /** * The MPEX Date and Time Stock used fields. * Visible only for the barcode records. * @param {String} selector_type * @param {String} date_stock_used * @param {String} time_stock_used * @return {String} inlineQty */ function mpexStockUsedSection(selector_type, date_stock_used, time_stock_used) { if (isNullorEmpty(date_stock_used)) { date_stock_used = '' } if (isNullorEmpty(time_stock_used)) { time_stock_used = '' } var hide_class = (selector_type == 'barcode_number') ? '' : 'hide'; // MPEX Stock Used Section var inlineQty = '<div class="form-group container mpex_stock_used_section ' + hide_class + '">'; inlineQty += '<div class="row">'; // Date Stock Used inlineQty += ' <div class="col-xs-6 date_stock_used">'; inlineQty += '<div class="input-group">'; inlineQty += '<span class="input-group-addon" id="date_stock_used_text">DATE STOCK USED</span>'; inlineQty += '<input id="date_stock_used" class="form-control date_stock_used" value="' + date_stock_used + '" disabled>'; inlineQty += '</div></div>'; // Time Stock Used inlineQty += '<div class="col-xs-6 time_stock_used">'; inlineQty += '<div class="input-group">'; inlineQty += '<span class="input-group-addon" id="time_stock_used_text">TIME STOCK USED</span>'; inlineQty += '<input id="time_stock_used" class="form-control time_stock_used" value="' + time_stock_used + '" disabled>'; inlineQty += '</div></div></div></div>'; return inlineQty; } /** * The MPEX Final Delivery field is visible only for the barcode records. * The Enquiry Status field is not disabled only for the ticket that have not yet been opened. * @param {Number} status_value * @param {String} selector_type * @param {String} final_delivery_text * @param {Number} selected_enquiry_status_id * @return {String} inlineQty */ function finalDeliveryEnquirySection(status_value, selector_type, final_delivery_text, selected_enquiry_status_id, prod_stock_invoice) { if (isNullorEmpty(final_delivery_text)) { final_delivery_text = '' } if (isNullorEmpty(selected_enquiry_status_id)) { selected_enquiry_status_id = '' } var barcode_hide_class = (selector_type == 'barcode_number') ? '' : 'hide'; var nb_col_enquiry_section = (selector_type == 'barcode_number') ? '6' : '12'; var enquiry_disabled = (isTicketNotClosed(status_value)) ? '' : 'disabled'; // Final Delivery + Enquiry Status Section var inlineQty = '<div class="form-group container final_delivery_enquiry_status_section">'; inlineQty += '<div class="row">'; // Final Delivery inlineQty += '<div class="col-xs-6 final_delivery ' + barcode_hide_class + '">'; inlineQty += '<div class="input-group">'; inlineQty += '<span class="input-group-addon" id="final_delivery_text">FINAL DELIVERY</span>'; inlineQty += '<input id="final_delivery" class="form-control final_delivery" value="' + final_delivery_text + '" disabled>'; inlineQty += '</div></div>'; // Final Delivery inlineQty += '<div class="col-xs-6 invoice ' + barcode_hide_class + '">'; inlineQty += '<div class="input-group">'; inlineQty += '<span class="input-group-addon" id="invoice_text">INVOICE</span>'; inlineQty += '<input id="invoice" class="form-control invoice" value="' + prod_stock_invoice + '" disabled>'; inlineQty += '</div></div>'; inlineQty += '</div></div>'; return inlineQty; } /** * Ticket Label Section for if label on mpex was Printed or Handwritten * @param {Number} selected_label_id * @return {String} inlineQty */ function labelSection(selected_label_id, selector_type, status_value){ if (isNullorEmpty(selected_label_id)){ selected_label_id = ''; } var barcodeHideClass = (selector_type == 'barcode_number') ? '' : 'hide'; var labeldisabled = (isTicketNotClosed(status_value)) ? '' : 'disabled'; var inlineQty = '<div class="form-group container label_section '+ barcodeHideClass + '">'; inlineQty += '<div class="row">'; inlineQty += '<div class="col-xs-6 label_div">'; inlineQty += '<div class="input-group">'; inlineQty += '<span class="input-group-addon" id="label_text">TICKET LABEL</span>'; inlineQty += '<select id="label_status" class="form-control label_status" '+ labeldisabled+ '>'; inlineQty += '<option></option>'; var labelColumns = new Array(); labelColumns[0] = search.createColumn({ name: 'name' }); labelColumns[1] = search.createColumn({ name: 'internalId' }); var labelResultSet = search.create({ type: 'customlist_mp_ticket_label', columns: labelColumns, }); labelResultSet.run().each(function (labelResult) { var labelName = labelResult.getValue('name'); var labelId = labelResult.getValue('internalId'); if(selected_label_id == labelId) { inlineQty += '<option value="' + labelId + '"selected>' + labelName + '</option>'; }else{ inlineQty += '<option value="' + labelId + '">' + labelName + '</option>'; } return inlineQty; }); inlineQty += '</select>'; inlineQty += '</div></div></div></div>'; return inlineQty; } /** * Section containing enquiry medium type and the enquiry status of the ticket enquiry * @param list_enquiry_mediums {String}atus and * @param total_enquiry_count {Number} * @param selector_type {String} * @param status_value {Number} * @returns {string} */ function enquiryMediumSection(list_enquiry_mediums, selected_enquiry_status_id, selector_type){ //Search for enquiry mediums var hasEnquiryMediums = (!isNullorEmpty(list_enquiry_mediums)); var enquiryMediumColumns = new Array(); enquiryMediumColumns[0] = search.createColumn({ name: 'name' }); enquiryMediumColumns[1] = search.createColumn({ name: 'internalId' }); var enquiryMediumResultSet = search.create({ type: 'customlist_ticket_enquiry_mediums', columns: enquiryMediumColumns, }); //Ticket Enquiry Header // var inlineQty = '<div class="form-group container ticket_enquiry_header_section">'; // inlineQty += '<div class="row">'; // inlineQty += '<div class="col-xs-12 heading2">'; // inlineQty += '<h4><span style="background-color: #379E8F" class="label label-default col-xs-12">TICKET ENQUIRY DETAILS</span></h4>'; // inlineQty += '</div></div></div>'; //Enquiry Medium HTML var inlineQty = '<div class="form-group container enquiry_medium_section">'; inlineQty += '<div class="row">'; // inlineQty += '<div class="col-xs-6 enquiry_medium_div">'; // inlineQty += '<div class="input-group">'; // inlineQty += '<span class="input-group-addon" id="enquiry_medium_text">ENQUIRY MEDIUM</span>'; // inlineQty += '<select multiple id="enquiry_medium_status" class="form-control enquiry_medium_status" size="'+ enquiryMediumResultSet.length + '" disabled>'; // enquiryMediumResultSet.run().each(function (enquiryMediumResult) { // var enquiryMediumName = enquiryMediumResult.getValue('name'); // var enquiryMediumId = enquiryMediumResult.getValue('internalId'); // var selected = false; // if(hasEnquiryMediums){ // selected = (list_enquiry_mediums.indexOf(enquiryMediumId) !== -1); // } // if(selected) { // inlineQty += '<option value="' + enquiryMediumId + '"selected>' + enquiryMediumName + '</option>'; // }else{ // inlineQty += '<option value="' + enquiryMediumId + '">' + enquiryMediumName + '</option>'; // } // return true; // }); // inlineQty += '</select>'; // inlineQty += '</div></div>'; // Enquiry Status var enquiry_status_columns = new Array(); enquiry_status_columns[0] = search.createColumn({ name: 'name' }); enquiry_status_columns[1] = search.createColumn({ name: 'internalId' }); var enquiryStatusResultSet = search.create({ type: 'customlist_mp_ticket_enquiry', columns: enquiry_status_columns, }); inlineQty += '<div class="col-xs-6 enquiry_status_div">'; inlineQty += '<div class="input-group">'; inlineQty += '<span class="input-group-addon" id="enquiry_status_text">ENQUIRY STATUS</span>'; inlineQty += '<select id="enquiry_status" class="form-control enquiry_status">'; inlineQty += '<option></option>'; enquiryStatusResultSet.run().each(function (enquiryStatusResult) { var enquiry_status_name = enquiryStatusResult.getValue('name'); var enquiry_status_id = enquiryStatusResult.getValue('internalId'); if (enquiry_status_id == selected_enquiry_status_id) { inlineQty += '<option value="' + enquiry_status_id + '" selected>' + enquiry_status_name + '</option>'; } else { inlineQty += '<option value="' + enquiry_status_id + '">' + enquiry_status_name + '</option>'; } return true; }); inlineQty += '</select>'; inlineQty += '</div></div></div></div>'; return inlineQty; } /** * Section containing the total enquiry count and its breakdwn counts of chat, phone and email * @param total_enquiry_count * @param chat_enquiry_count * @param phone_enquiry_count * @param email_enquiry_count * @param selector_type * @returns {string} */ function enquiryCountSection( total_enquiry_count, chat_enquiry_count, phone_enquiry_count, email_enquiry_count, selector_type, phone_interaction_count, email_interaction_count){ if (isNullorEmpty(total_enquiry_count)) { total_enquiry_count = 0;} if (isNullorEmpty(chat_enquiry_count)) { chat_enquiry_count = 0;} if (isNullorEmpty(phone_enquiry_count)) { phone_enquiry_count = 0;} if (isNullorEmpty(email_enquiry_count)) { email_enquiry_count = 0;} if (isNullorEmpty(phone_interaction_count)) { phone_interaction_count = 0;} if (isNullorEmpty(email_interaction_count)) { email_interaction_count = 0;} //Total Enquiry Count HTML // var inlineQty = '<div class="form-group container enquiry_count_section">'; // inlineQty += '<div class="row">'; // inlineQty += '<div class="col-xs-12 total_enquiry_count_div">'; // inlineQty += '<div class="input-group">'; // inlineQty += '<span class="input-group-addon" id="total_enquiry_count_text">ENQUIRY COUNT</span>'; // inlineQty += '<input id="total_enquiry_count" class="form-control enquiry_count" value="' + total_enquiry_count + '" disabled />'; // inlineQty += '</div></div></div></div>'; //Enquiries by chat count var inlineQty = '<div class="form-group container enquiry_count_breakdown_section">'; inlineQty += '<div class="row">'; inlineQty += '<div class="col-xs-4 enquiry_count_by_chat">'; inlineQty += '<div class="input-group">'; inlineQty += '<span class="input-group-addon" id="enquiry_count_by_chat_text"> WEBSITE ENQUIRY </span>'; inlineQty += '<input id="enquiry_count_by_chat" value="' + chat_enquiry_count + '" class="form-control enquiry_count_by_chat" disabled>'; inlineQty += '<div class="input-group-btn">'; inlineQty += '<button type="button" style="background-color: #379E8F" class="btn btn-success increment_enquiry_count_by_chat" data-firstname="" data-toggle="tooltip" data-placement="right" title="Increment Chat Enquiry Count">'; inlineQty += '<span class="glyphicon glyphicon-plus"></span>'; inlineQty += '</button>'; inlineQty += '<button type="button" class="btn btn-danger decrement_enquiry_count_by_chat" data-firstname="" data-toggle="tooltip" data-placement="right" title="Decrement Chat Enquiry Count">'; inlineQty += '<span class="glyphicon glyphicon-minus"></span>'; inlineQty += '</button>'; inlineQty += '</div></div></div>'; inlineQty += '<div class="col-xs-4 enquiry_count_by_phone">'; inlineQty += '<div class="input-group">'; inlineQty += '<span class="input-group-addon" id="enquiry_count_by_phone_text"> PHONE ENQUIRY </span>'; inlineQty += '<input id="enquiry_count_by_phone" value="' + phone_enquiry_count + '" class="form-control enquiry_count_by_phone" disabled>'; inlineQty += '<div class="input-group-btn">'; inlineQty += '<button type="button" style="background-color: #379E8F" class="btn btn-success increment_enquiry_count_by_phone" data-firstname="" data-toggle="tooltip" data-placement="right" title="Increment Phone Enquiry Count">'; inlineQty += '<span class="glyphicon glyphicon-plus"></span>'; inlineQty += '</button>'; inlineQty += '<button type="button" class="btn btn-danger decrement_enquiry_count_by_phone" data-firstname="" data-toggle="tooltip" data-placement="right" title="Decrement Phone Enquiry Count">'; inlineQty += '<span class="glyphicon glyphicon-minus"></span>'; inlineQty += '</button>'; inlineQty += '</div></div></div>'; inlineQty += '<div class="col-xs-4 enquiry_count_by_email">'; inlineQty += '<div class="input-group">'; inlineQty += '<span class="input-group-addon" id="enquiry_count_by_email_text"> EMAIL ENQUIRY </span>'; inlineQty += '<input id="enquiry_count_by_email" value="' + email_enquiry_count + '" class="form-control enquiry_count_by_email" disabled>'; inlineQty += '<div class="input-group-btn">'; inlineQty += '<button type="button" style="background-color: #379E8F" class="btn btn-success increment_enquiry_count_by_email" data-firstname="" data-toggle="tooltip" data-placement="right" title="Increment Email Enquiry Count">'; inlineQty += '<span class="glyphicon glyphicon-plus"></span>'; inlineQty += '</button>'; inlineQty += '<button type="button" class="btn btn-danger decrement_enquiry_count_by_email" data-firstname="" data-toggle="tooltip" data-placement="right" title="Decrement Email Enquiry Count">'; inlineQty += '<span class="glyphicon glyphicon-minus"></span>'; inlineQty += '</button>'; inlineQty += '</div></div></div></div></div>'; if (selector_type == "customer_issue") { inlineQty += '<div class="form-group container interaction_count_breakdown_section">'; inlineQty += '<div class="row">'; inlineQty += '<div class="col-xs-6 interaction_count_by_phone">'; inlineQty += '<div class="input-group">'; inlineQty += '<span class="input-group-addon" id="interaction_count_by_phone_text"> PHONE INTERACTION </span>'; inlineQty += '<input id="interaction_count_by_phone" value="' + phone_interaction_count + '" class="form-control interaction_count_by_phone" disabled>'; inlineQty += '<div class="input-group-btn">'; inlineQty += '<button type="button" style="background-color: #379E8F" class="btn btn-success increment_interaction_count_by_phone" data-firstname="" data-toggle="tooltip" data-placement="right" title="Increment Phone Interaction Count">'; inlineQty += '<span class="glyphicon glyphicon-plus"></span>'; inlineQty += '</button>'; inlineQty += '<button type="button" class="btn btn-danger decrement_interaction_count_by_phone" data-firstname="" data-toggle="tooltip" data-placement="right" title="Decrement Phone interaction Count">'; inlineQty += '<span class="glyphicon glyphicon-minus"></span>'; inlineQty += '</button>'; inlineQty += '</div></div></div>'; inlineQty += '<div class="col-xs-6 interaction_count_by_email">'; inlineQty += '<div class="input-group">'; inlineQty += '<span class="input-group-addon" id="interaction_count_by_email_text"> EMAIL INTERACTION </span>'; inlineQty += '<input id="interaction_count_by_email" value="' + email_interaction_count + '" class="form-control interaction_count_by_email" disabled>'; inlineQty += '<div class="input-group-btn">'; inlineQty += '<button type="button" style="background-color: #379E8F" class="btn btn-success increment_interaction_count_by_email" data-firstname="" data-toggle="tooltip" data-placement="right" title="Increment Email Interaction Count">'; inlineQty += '<span class="glyphicon glyphicon-plus"></span>'; inlineQty += '</button>'; inlineQty += '<button type="button" class="btn btn-danger decrement_interaction_count_by_email" data-firstname="" data-toggle="tooltip" data-placement="right" title="Decrement Email Interaction Count">'; inlineQty += '<span class="glyphicon glyphicon-minus"></span>'; inlineQty += '</button>'; inlineQty += '</div></div></div></div></div>'; } return inlineQty; } /** * These fields should be displayed only for an Invoice ticket, and be edited only by the finance team. * - Invoice Method field * - Accounts cc email field * - MPEX PO # field * - Customer PO # field * - MPEX Invoicing Cycle field * @param {Number} selected_invoice_method_id * @param {String} accounts_cc_email * @param {String} mpex_po_number * @param {String} customer_po_number * @param {Number} selected_invoice_cycle_id * @param {Number} terms * @param {String} customer_terms * @param {Number} status_value * @param {String} selector_type * @return {String} inlineQty */ function otherInvoiceFieldsSection(selected_invoice_method_id, accounts_cc_email, mpex_po_number, customer_po_number, selected_invoice_cycle_id, terms, customer_terms, status_value, selector_type) { if (isNullorEmpty(accounts_cc_email)) { accounts_cc_email = '' } if (isNullorEmpty(mpex_po_number)) { mpex_po_number = '' } if (isNullorEmpty(customer_po_number)) { customer_po_number = '' } if (isNullorEmpty(customer_terms)) { customer_terms = '' } var invoice_method_columns = new Array(); invoice_method_columns[0] = search.createColumn({ name: 'name' }); invoice_method_columns[1] = search.createColumn({ name: 'internalId' }); var invoiceMethodResultSet = search.create({ type: 'customlist_invoice_method', columns: invoice_method_columns, }); switch (selector_type) { case 'barcode_number': var inlineQty = '<div class="form-group container invoice_method_accounts_cc_email_section hide">'; var disabled = 'disabled'; break; case 'invoice_number': var inlineQty = '<div class="form-group container invoice_method_accounts_cc_email_section">'; if (isFinanceRole(userRole) && isTicketNotClosed(status_value)) { var disabled = ''; } else { var disabled = 'disabled'; } break; } inlineQty += '<div class="row">'; // Invoice Method field inlineQty += '<div class="col-xs-6 invoice_method_div">'; inlineQty += '<div class="input-group">'; inlineQty += '<span class="input-group-addon" id="invoice_method_text">INVOICE METHOD</span>'; inlineQty += '<select id="invoice_method" class="form-control" ' + disabled + '>'; inlineQty += '<option></option>'; invoiceMethodResultSet.run().each(function(invoiceMethodResult) { var invoice_method_name = invoiceMethodResult.getValue('name'); var invoice_method_id = invoiceMethodResult.getValue('internalId'); if (invoice_method_id == selected_invoice_method_id) { inlineQty += '<option value="' + invoice_method_id + '" selected>' + invoice_method_name + '</option>'; } else { inlineQty += '<option value="' + invoice_method_id + '">' + invoice_method_name + '</option>'; } return true; }); inlineQty += '</select>'; inlineQty += '</div></div>'; // Accounts cc email field --> inlineQty += '<div class="col-xs-6 accounts_cc_email_div">'; inlineQty += '<div class="input-group">'; inlineQty += '<span class="input-group-addon" id="accounts_cc_email_text">ACCOUNTS CC EMAIL</span>'; inlineQty += '<input id="accounts_cc_email" type="email" value="' + accounts_cc_email + '" class="form-control accounts_cc_email" ' + disabled + '/>'; inlineQty += '<div class="input-group-btn">'; inlineQty += '<button type="button" style="background-color: #379E8F" class="btn btn-success add_as_recipient" data-email="' + accounts_cc_email + '" data-contact-id="" data-firstname="" data-toggle="tooltip" data-placement="right" title="Add as recipient">'; inlineQty += '<span class="glyphicon glyphicon-envelope"></span>'; inlineQty += '</button>'; inlineQty += '</div>'; inlineQty += '</div></div></div></div>'; switch (selector_type) { case 'barcode_number': inlineQty += '<div class="form-group container mpex_customer_po_number_section hide">'; break; case 'invoice_number': inlineQty += '<div class="form-group container mpex_customer_po_number_section">'; break; } inlineQty += '<div class="row">'; // MPEX PO # inlineQty += '<div class="col-xs-6 mpex_po_number_div">'; inlineQty += '<div class="input-group">'; inlineQty += '<span class="input-group-addon" id="mpex_po_number_text">MPEX PO #</span>'; inlineQty += '<input id="mpex_po_number" value="' + mpex_po_number + '" class="form-control mpex_po_number" ' + disabled + '/>'; inlineQty += '</div></div>'; // Customer PO # inlineQty += '<div class="col-xs-6 customer_po_number_div">'; inlineQty += '<div class="input-group">'; inlineQty += '<span class="input-group-addon" id="customer_po_number_text">CUSTOMER PO #</span>'; inlineQty += '<input id="customer_po_number" value="' + customer_po_number + '" class="form-control customer_po_number" ' + disabled + '/>'; inlineQty += '</div></div></div></div>'; // Terms fields switch (selector_type) { case 'barcode_number': inlineQty += '<div class="form-group container terms_section hide">'; break; case 'invoice_number': inlineQty += '<div class="form-group container terms_section">'; break; } inlineQty += '<div class="row">'; // Terms inlineQty += '<div class="col-xs-6 terms_div">'; inlineQty += '<div class="input-group">'; inlineQty += '<span class="input-group-addon" id="terms_text">TERMS</span>'; // Find the text related to the terms value. var terms_options = [{ "value": "", "text": "" }, { "value": "5", "text": "1% 10 Net 30" }, { "value": "6", "text": "2% 10 Net 30" }, { "value": "4", "text": "Due on receipt" }, { "value": "1", "text": "Net 15 Days" }, { "value": "2", "text": "Net 30 Days" }, { "value": "8", "text": "Net 45 Days" }, { "value": "3", "text": "Net 60 Days" }, { "value": "7", "text": "Net 7 Days" }, { "value": "9", "text": "Net 90 Days" }]; var terms_option = findObjectByKey(terms_options, "value", terms); var terms_text = isNullorEmpty(terms_option) ? '' : terms_option.text; inlineQty += '<input id="terms" class="form-control terms" value="' + terms_text + '" disabled/>'; inlineQty += '</div></div>'; // Customer's terms inlineQty += '<div class="col-xs-6 customers_terms_div">'; inlineQty += '<div class="input-group">'; inlineQty += '<span class="input-group-addon" id="customers_terms_text">' + "CUSTOMER'S TERMS</span>"; inlineQty += '<input id="customers_terms" class="form-control customers_terms" value="' + customer_terms + '" ' + disabled + '/>'; inlineQty += '</div></div></div></div>'; // MPEX Invoicing Cycle var invoice_cycle_columns = new Array(); invoice_cycle_columns[0] = search.createColumn({ name: 'name' }); invoice_cycle_columns[1] = search.createColumn({ name: 'internalId' }); var invoiceCycleResultSet = search.create({ type: 'customlist_invoicing_cyle', columns: invoice_cycle_columns, }) switch (selector_type) { case 'barcode_number': inlineQty += '<div class="form-group container mpex_invoicing_cycle_section hide">'; break; case 'invoice_number': inlineQty += '<div class="form-group container mpex_invoicing_cycle_section">'; break; } inlineQty += '<div class="row">'; inlineQty += '<div class="col-xs-12 mpex_invoicing_cycle_div">'; inlineQty += '<div class="input-group">'; inlineQty += '<span class="input-group-addon" id="mpex_invoicing_cycle_text">MPEX INVOICING CYCLE</span>'; inlineQty += '<select id="mpex_invoicing_cycle" class="form-control mpex_invoicing_cycle" ' + disabled + '>'; inlineQty += '<option></option>'; invoiceCycleResultSet.run().each(function (invoiceCycleResult) { var invoice_cycle_name = invoiceCycleResult.getValue('name'); var invoice_cycle_id = invoiceCycleResult.getValue('internalId'); if (invoice_cycle_id == selected_invoice_cycle_id) { inlineQty += '<option value="' + invoice_cycle_id + '" selected>' + invoice_cycle_name + '</option>'; } else { inlineQty += '<option value="' + invoice_cycle_id + '">' + invoice_cycle_name + '</option>'; } return true; }); inlineQty += '</select>'; inlineQty += '</div></div></div></div>'; return inlineQty; } /** * The Attachments field (an editable hyperlink) * @param {String} attachments_hyperlink * @param {Number} status_value * @returns {String} inlineQty */ function attachmentsSection(attachments_hyperlink, status_value) { if (isNullorEmpty(attachments_hyperlink)) { attachments_hyperlink = '' } var disabled = (isTicketNotClosed(status_value)) ? '' : 'disabled'; var inlineQty = '<div class="form-group container attachments_section">'; inlineQty += '<div class="row">'; inlineQty += '<div class="col-xs-12 attachments_div">'; inlineQty += '<div class="input-group">'; inlineQty += '<span class="input-group-addon" id="attachments_text">ATTACHMENTS</span>' inlineQty += '<input id="attachments" class="form-control attachments" type="url" value="' + attachments_hyperlink + '" ' + disabled + '/>'; inlineQty += '</div></div></div></div>'; return inlineQty; } /** * The customer contact details section. * Possibility for the user to add / edit the contacts. * @return {String} inlineQty */ function mpexContactSection() { // Contact details header var inlineQty = '<div class="form-group container mpex_contact_section">'; inlineQty += '<div class="row">'; inlineQty += '<div class="col-xs-12 heading2">'; inlineQty += '<h4><span style="background-color: #379E8F" class="label label-default col-xs-12">CONTACT DETAILS</span></h4>'; inlineQty += '</div>'; inlineQty += '</div></div>'; // Contact table inlineQty += '<div class="form-group container contacts_section" style="font-size: small;">'; inlineQty += '<div class="row">'; inlineQty += '<div class="col-xs-12 contacts_div">'; // Since the table is not displayed correctly when added through suitelet, // It is added with jQuery in the pageInit() function in the client script 'mp_cl_open_ticket.js'. inlineQty += '</div>'; inlineQty += '</div>'; inlineQty += '</div>'; // Add/edit contacts button inlineQty += '<div class="form-group container reviewcontacts_section">'; inlineQty += '<div class="row">'; inlineQty += '<div class="col-xs-4 col-xs-offset-4 reviewcontacts">'; inlineQty += '<input type="button" style="background-color: #379E8F; border-color: #379E8F; font-weight: 700" value="ADD/EDIT CONTACTS" class="form-control btn btn-primary" id="reviewcontacts" />'; inlineQty += '</div></div></div>'; return inlineQty; }; /** * A Datatable displaying the open invoices of the customer * @param {Number} ticket_id * @param {String} selector_type * @return {String} inlineQty */ function openInvoicesSection(ticket_id, selector_type) { if (isNullorEmpty(ticket_id)) { ticket_id = '' } var hide_class_section = (isNullorEmpty(ticket_id) || selector_type != 'invoice_number') ? 'hide' : ''; // Open invoices header var inlineQty = '<div class="form-group container open_invoices open_invoices_header ' + hide_class_section + '">'; inlineQty += '<div class="row">'; inlineQty += '<div class="col-xs-12 heading2">'; inlineQty += '<h4><span style="background-color: #379E8F" class="label label-default col-xs-12">OPEN INVOICES</span></h4>'; inlineQty += '</div></div></div>'; // Open invoices dropdown field inlineQty += '<div class="form-group container open_invoices invoices_dropdown ' + hide_class_section + '">'; inlineQty += '<div class="row">'; inlineQty += '<div class="col-xs-12 invoices_dropdown_div">'; inlineQty += '<div class="input-group">'; inlineQty += '<span class="input-group-addon" id="invoices_dropdown_text">INVOICE STATUS</span>'; inlineQty += '<select id="invoices_dropdown" class="form-control">'; inlineQty += '<option value="open" selected>Open</option>'; inlineQty += '<option value="paidInFull">Paid In Full (last 3 months)</option>'; inlineQty += '</select>'; inlineQty += '</div></div></div></div>'; // Open Invoices Datatable //inlineQty += '<div class="form-group container open_invoices open_invoices_datatable>'; //inlineQty += '</div>'; inlineQty += '<div class="form-group open_invoices open_invoices_table ' + hide_class_section + '">'; inlineQty += dataTable(); // inlineQty += '<div class="row">'; // inlineQty += '<div class="col-xs-18" id="open_invoice_dt_div">'; // // It is inserted as inline html in the script mp_cl_open_ticket // inlineQty += '</div></div></div>'; inlineQty += '</div>' return inlineQty; } function dataTable() { var inlineQty = '<style>table#invoices-preview {font-size: 12px;text-align: center;border: none;}.dataTables_wrapper {font-size: 14px;}table#invoices-preview th{text-align: center;} .bolded{font-weight: bold;}</style>'; inlineQty += '<table id="invoices-preview" class="table table-responsive table-striped customer tablesorter" style="width: 100%; table-layout: fixed">'; inlineQty += '<thead style="color: white;background-color: #379E8F;">'; inlineQty += '<tr class="text-center">'; inlineQty += '</tr>'; inlineQty += '</thead>'; inlineQty += '<tbody id="result_invoices"></tbody>'; inlineQty += '</table>'; return inlineQty; } /** * The Credit Memo Section. * Displays a table of the credit memos linked to the invoice. * Possibility to attach the credit memo PDF to the email. * @param {String} selector_type * @return {String} inlineQty */ function creditMemoSection(selector_type) { var inlineQty = ''; if (selector_type == 'invoice_number') { // Credit Memo Header inlineQty += '<div class="form-group container credit_memo credit_memo_header">'; inlineQty += '<div class="row">'; inlineQty += '<div class="col-xs-12 heading2">'; inlineQty += '<h4><span style="background-color: #379E8F" class="label label-default col-xs-12">CREDIT MEMO</span></h4>'; inlineQty += '</div></div></div>'; // Credit Memo table inlineQty += '<div class="form-group container credit_memo credit_memo_section" style="font-size: small;">'; inlineQty += '<div class="row">'; inlineQty += '<div class="col-xs-12 credit_memo_div">'; // Since the table is not displayed correctly when added through suitelet, // It is added with jQuery in the pageInit() function in the client script 'mp_cl_open_ticket.js'. inlineQty += '</div></div></div>'; } return inlineQty; } function usageReportSection(selector_type) { var inlineQty = ''; if (selector_type == 'invoice_number') { // Usage Report Header inlineQty += '<div class="form-group container usage_report usage_report_header">'; inlineQty += '<div class="row">'; inlineQty += '<div class="col-xs-12 heading2">'; inlineQty += '<h4><span style="background-color: #379E8F" class="label label-default col-xs-12">USAGE REPORT</span></h4>'; inlineQty += '</div></div></div>'; // Usage Report table inlineQty += '<div class="form-group container usage_report usage_report_section" style="font-size: small;">'; inlineQty += '<div class="row">'; inlineQty += '<div class="col-xs-12 usage_report_div">'; // Since the table is not displayed correctly when added through suitelet, // It is added with jQuery in the pageInit() function in the client script 'mp_cl_open_ticket.js'. inlineQty += '</div></div></div>'; } return inlineQty; } /** * The "Send Email" section. * Possibility for the user to send an email to the customer, based on selected templates. * @param {Number} ticket_id * @param {Number} status_value * @param {Object} account_manager * @returns {String} inlineQty */ function sendEmailSection(ticket_id, status_value, account_manager, list_toll_emails) { var has_toll_emails = (!isNullorEmpty(list_toll_emails)); if (isNullorEmpty(ticket_id) || !isTicketNotClosed(status_value)) { // The section is hidden here rather than in the openTicket function, // because we use the section to send an acknoledgement email when a ticket is opened. var inlineQty = '<div id="send_email_container" class="send_email hide">'; } else { var inlineQty = '<div id="send_email_container" class="send_email">'; } // inlineQty += '<div class="form-group container send_email header_section">'; // // Send email header // inlineQty += '<div class="row">'; // inlineQty += '<div class="col-xs-12 heading2">'; // inlineQty += '<h4><span style="background-color: #379E8F" class="label label-default col-xs-12">SEND EMAILS</span></h4>'; // inlineQty += '</div></div></div>'; inlineQty += '<br></br>' // Row addressees inlineQty += '<div class="form-group container send_email adressees_section">'; inlineQty += '<div class="row">'; inlineQty += '<div class="col-xs-12 to_section">'; inlineQty += '<div class="input-group">'; inlineQty += '<span class="input-group-addon">TO<span class="mandatory">*</span></span>'; inlineQty += '<input id="send_to" class="form-control" data-contact-id="" data-firstname=""/>'; inlineQty += '</div></div></div></div>'; // Toll addresses var toll_emails_columns = new Array(); toll_emails_columns[0] = search.createColumn({ name: 'name' }); toll_emails_columns[1] = search.createColumn({ name: 'internalId' }); var tollEmailsResultSet = search.create({ type: 'customlist_toll_emails', columns: toll_emails_columns, }) inlineQty += '<div class="form-group container send_email toll_adressees_section">'; inlineQty += '<div class="row">'; inlineQty += '<div class="col-xs-12 toll_section">'; inlineQty += '<div class="input-group">'; inlineQty += '<span class="input-group-addon">TOLL EMAILS</span>'; inlineQty += '<select multiple id="send_toll" class="form-control" size="' + tollEmailsResultSet.length + '"/>'; tollEmailsResultSet.run().each(function (tollEmailsResultSet){ var tollEmailName = tollEmailsResultSet.getValue('name'); var tollEmailId = tollEmailsResultSet.getValue('internalId'); var selected = false; if(has_toll_emails) { selected = (list_toll_emails.indexOf(tollEmailId) !== -1); } if (selected) { inlineQty += '<option value="' + tollEmailId + '" selected>' + tollEmailName + '</option>'; } else { inlineQty += '<option value="' + tollEmailId + '">' + tollEmailName + '</option>'; } return true; }); inlineQty += '</select>'; inlineQty += '</div></div></div></div>'; // Row ccs addresses inlineQty += '<div class="form-group container send_email cc_adressees_section">'; inlineQty += '<div class="row">'; inlineQty += '<div class="col-xs-6 cc_section">'; inlineQty += '<div class="input-group">'; inlineQty += '<span class="input-group-addon">CC</span>'; inlineQty += '<input id="send_cc" class="form-control"/>'; inlineQty += '</div></div>'; inlineQty += '<div class="col-xs-6 bcc_section">'; inlineQty += '<div class="input-group">'; inlineQty += '<span class="input-group-addon">BCC</span>'; inlineQty += '<input id="send_bcc" class="form-control"/>'; inlineQty += '</div></div></div></div>'; // Row account manager if (isNullorEmpty(account_manager.name)) { account_manager.name = '' } if (isNullorEmpty(account_manager.email)) { account_manager.email = '' } if (!isNullorEmpty(account_manager.email.email)) { inlineQty += '<div class="form-group container send_email acc_manager_section">'; inlineQty += '<div class="row">'; inlineQty += '<div class="col-xs-10 acc_manager_name_section">'; inlineQty += '<div class="input-group">'; inlineQty += '<span class="input-group-addon">ACCOUNT MANAGER</span>'; inlineQty += '<input id="acc_manager" class="form-control" data-email="' + account_manager.email.email + '" value="' + account_manager.name + ' - ' + account_manager.email.email + '" disabled/>'; inlineQty += '</div></div>'; inlineQty += '<div class="col-xs-2 acc_manager_button_section">'; inlineQty += '<button id="acc_manager_button" style="background-color: #379E8F; border-color: #379E8F" type="button" class="btn btn-success btn-block">ADD TO CC</button>'; inlineQty += '</div></div></div>'; } // Row Template inlineQty += '<div class="form-group container send_email template_section">'; inlineQty += '<div class="row">'; inlineQty += '<div class="col-xs-12 template_section">'; inlineQty += '<div class="input-group">'; inlineQty += '<span class="input-group-addon">TEMPLATE<span class="mandatory">*</span></span>'; inlineQty += '<select id="template" class="form-control">'; inlineQty += '<option></option>'; // Load the template options var templatesSearch = search.load({ id: 'customsearch_cctemplate_mp_ticket', type: 'customrecord_camp_comm_template' }); var templatesSearchResults = templatesSearch.run(); templatesSearchResults.each(function(templatesSearchResult) { // var tempId = templatesSearchResult.getValue('internalid'); var tempId = templatesSearchResult["id"]; var tempName = templatesSearchResult.getValue('name'); inlineQty += '<option value="' + tempId + '">' + tempName + '</option>'; return true; }); inlineQty += '</select>'; inlineQty += '</div></div></div></div>'; // Row Subject inlineQty += '<div class="form-group container send_email subject_section">'; inlineQty += '<div class="row">'; inlineQty += '<div class="col-xs-12 subject_section">'; inlineQty += '<div class="input-group">'; inlineQty += '<span class="input-group-addon">SUBJECT<span class="mandatory">*</span></span>'; inlineQty += '<input id="subject" class="form-control" />'; inlineQty += '</div></div></div></div>'; // Row Body inlineQty += '<div class="form-group container send_email body_section">'; inlineQty += '<div class="row">'; inlineQty += '<div class="col-xs-12 body_section">'; inlineQty += '<div id="email_body"></div>'; inlineQty += '</div></div></div>'; // SEND EMAIL button inlineQty += '<div class="form-group container send_email button_section">'; inlineQty += '<div class="row">'; inlineQty += '<div class="col-xs-4 col-xs-offset-4 send_email_btn">'; inlineQty += '<input type="button" style="background-color: #379E8F; border-color: #379E8F; font-weight: 700" value="SEND EMAIL" class="form-control btn btn-primary" id="send_email" />'; inlineQty += '</div></div></div></div>'; return inlineQty; }; /** * Section for the previous emails datatable * @param customer_id * @returns {string} */ function previousEmailsSection(customer_id){ var customerRecord = record.load({ type: record.Type.CUSTOMER, id: customer_id, }); var customer_internal_id = customerRecord.getValue({ fieldId: 'id' }); // Previous Emails header var inlineQty = '<div class="form-group container previous_emails_header">'; inlineQty += '<div class="row">'; inlineQty += '<div class="col-xs-12 heading2">'; inlineQty += '<h4><span style="background-color: #379E8F" class="label label-default col-xs-12">PREVIOUS EMAILS</span></h4>'; inlineQty += '</div></div></div>'; //Searching emails filtered by - internal customer id and dated before the lastmonthonefiscalquarterago (i.e. the past three months) var emailSearch = search.load({ type: 'message', id: 'customsearch_all_messages' }); var emailSearchFilter = [["customer.internalid","anyof",customer_internal_id], "AND", ["messagedate", "after", "lastmonthonefiscalquarterago"]]; //670041, 313070 emailSearch.filterExpression = emailSearchFilter; var resultEmailSet = emailSearch.run(); var allEmails = resultEmailSet.getRange({ start: 0, end: 1000 }); //Previous Emails table setup // inlineQty += '<style> table {font-size: 12px;text-align: center;border: none;} {font-size: 14px;} table th{text-align: center;} .dataTables_wrapper{width:78%; margin:auto;} </style>'; // inlineQty += '<div class="form-group container previous_emails_section">'; // inlineQty += '<table cellpadding="15" id="emails-preview" class="table table-responsive table-striped customer tablesorter" cellspacing="0" style="width: 100%;">'; // inlineQty += '<thead style="color: white;background-color: #CFE0CE;">'; // inlineQty += '<tr class="text-center">'; // inlineQty += '<th scope="col">Message Date</th>'; // inlineQty += '<th scope="col">Author</th>'; // inlineQty += '<th scope="col">Receipients</th>'; // inlineQty += '<th scope="col">Subject</th>'; // inlineQty += '<th scope="col">More</th>'; // inlineQty += '</tr>'; // inlineQty += '</thead>'; // inlineQty += '<tbody>'; inlineQty += '<style>table#emails-preview {font-size: 12px;text-align: center;border: none; background-color: #379E8F}.dataTables_wrapper {font-size: 12px;}table#emails-preview th{background-color: #379E8F; text-align: center;}</style>'; inlineQty += '<table cellpadding="15" id="emails-preview" class="table table-responsive table-striped customer tablesorter" cellspacing="0" style="width: 100%;">'; inlineQty += '<thead style="color: white;background-color: #379E8F;">'; inlineQty += '<tr class="text-center">'; inlineQty += '<th scope="col">Message Date</th>'; inlineQty += '<th scope="col">Author</th>'; inlineQty += '<th scope="col">Receipients</th>'; inlineQty += '<th scope="col">Subject</th>'; inlineQty += '<th scope="col">More</th>'; inlineQty += '</tr>'; inlineQty += '</thead>'; inlineQty += '<tbody>'; allEmails.forEach(function (email) { var messageid = email.searchId; var date = email.getValue('messagedate'); var author = email.getValue('authoremail'); var recipients = email.getText('recipients'); var subject = email.getValue('subject'); var url = "https://1048144-sb3.app.netsuite.com/app/crm/common/crmmessage.nl?id=" + messageid; //Table row data inlineQty += '<tr>'; inlineQty += '<td> ' + date + ' </td>'; inlineQty += '<td> ' + author + ' </td>'; inlineQty += '<td> ' + recipients + ' </td>'; inlineQty += '<td> ' + subject + '</td>'; inlineQty += '<td> <a href='+ url + '> View More </a> </td>'; inlineQty += '</tr>'; }); inlineQty += '</tbody>'; inlineQty += '</table>'; //inlineQty += '</div>'; return inlineQty; } /** * @return {String} inlineQty */ function issuesHeader() { var inlineQty = '<div class="form-group container toll_issues_header_section">'; inlineQty += '<div class="row">'; inlineQty += '<div class="col-xs-12 heading1">'; inlineQty += '<h4><span style="background-color: #379E8F" class="form-group label label-default col-xs-12">ISSUES</span></h4>'; inlineQty += '</div></div></div>'; return inlineQty; } /** * @param {Number} status_value * @return {String} inlineQty */ function reminderSection(status_value) { var hide_class = (!isTicketNotClosed(status_value)) ? 'hide' : ''; var inlineQty = '<div class="form-group container reminder_section ' + hide_class + '">'; inlineQty += '<div class="row">'; // Reminder field inlineQty += '<div class="col-xs-12 reminder">'; inlineQty += '<div class="input-group">'; inlineQty += '<span class="input-group-addon" id="reminder_text">REMINDER</span>'; inlineQty += '<input id="reminder" class="form-control reminder" type="date" />'; inlineQty += '</div></div></div></div>'; return inlineQty; } /** * Based on the selected MP Issue, an Owner is allocated to the ticket. * IT issues have priority over the other issues. * Populated with selectOwner() in the pageInit function on the client script. * @param {Number} ticket_id * @param {Array} owner_list * @param {Number} status_value * @return {String} inlineQty */ function ownerSection(ticket_id, owner_list, status_value) { if (isNullorEmpty(ticket_id)) { // If ticket_id is null, owner_list as well. // In that case, only the creator of the ticket is pre-selected as the owner. var userId = runtime.getCurrentUser().id; log.debug({ title: 'userId', details: userId }) owner_list = [userId]; } var disabled = (!isTicketNotClosed(status_value)) ? 'disabled' : ''; log.debug({ title: 'owner_list', details: owner_list }) var inlineQty = '<div class="form-group container owner_section">'; inlineQty += '<div class="row">'; inlineQty += '<div class="col-xs-12 owner">'; inlineQty += '<div class="input-group">'; inlineQty += '<span class="input-group-addon" id="owner_text">OWNER<span class="mandatory">*</span></span>'; inlineQty += '<select multiple id="owner" class="form-control owner" ' + disabled + '>'; var employeeSearch = search.load({ type: 'employee', id: 'customsearch_active_employees' }); var employeeResultSet = employeeSearch.run(); employeeResultSet.each(function(employeeResult) { var employee_id = employeeResult.id; var employee_firstname = employeeResult.getValue('firstname'); var employee_lastname = employeeResult.getValue('lastname'); var employee_email = employeeResult.getValue('email'); if (owner_list.indexOf(parseInt(employee_id)) != -1) { inlineQty += '<option value="' + employee_id + '" data-email="' + employee_email + '" selected>' + employee_firstname + ' ' + employee_lastname + '</option>'; } else { inlineQty += '<option value="' + employee_id + '" data-email="' + employee_email + '">' + employee_firstname + ' ' + employee_lastname + '</option>'; } return true; }); inlineQty += '</select>'; inlineQty += '</div></div></div></div>'; return inlineQty; } function customerIssueDropdown(){ //Load the customer issue list var col = new Array(); col[0] = search.createColumn({ name: 'name' }); col[1] = search.createColumn({ name: 'internalId' }); var results = search.create({ type: 'customlist_customer_ticket_issues', columns: col, }) var inlineQty = '<div class="form-group container customer_issues_dropdown_section">'; inlineQty += '<div class="row">'; inlineQty += '<div class="col-xs-12">'; inlineQty += '<div class="input-group"><span class="input-group-addon">CUSTOMER ISSUE</span>'; inlineQty += '<select id="customer_issue_dropdown" class="form-control">'; inlineQty += '<option></option>'; for (var i = 0; results != null && i < results.length; i++) {​​​​​ var res = results[i]; var listValue = res.getValue('name'); var listID = res.getValue('internalId'); inlineQty += '<option value="' + listID + '">' + listValue + '</option>'; // if (selected) { // inlineQty += '<option value="' + listID + '" selected>' + listValue + '</option>'; // } else { // inlineQty += '<option value="' + listID + '">' + listValue + '</option>'; // } } inlineQty += '</select>'; inlineQty += '</div></div></div></div>'; return inlineQty; } function customerIssuesSection(ticket_id, selector_type, selector_number, screenshot_file, selected_browser, login_email_used, selected_operating_system, phone_used, old_sender_name, old_sender_phone, status_value){ if (isNullorEmpty(screenshot_file)) { screenshot_file = '';} if (isNullorEmpty(selected_browser)) { selected_browser = '';} if (isNullorEmpty(login_email_used)) { login_email_used = '';} if (isNullorEmpty(selected_operating_system)) { operating_system = '';} if (isNullorEmpty(phone_used)) { phone_used = '';} if (isNullorEmpty(old_sender_name)) { old_sender_name = '';} if (isNullorEmpty(old_sender_phone)) { old_sender_phone = '';} var hide_class_section_mp_app = ((selector_type == "customer_issue") && (selector_number == 'Customer App')) ? '' : 'hide'; var hide_class_section_mp_label = ((selector_type == "customer_issue") && (selector_number == 'Update Label')) ? '' : 'hide'; var is_customer_issue_hide = (selector_type != "customer_issue") ? 'hide': ''; var hide_class_section_mp_portal = ((selector_type == "customer_issue") && (selector_number == 'Customer Portal')) ? '' : 'hide'; var inlineQty = ''; //Screenshot section if(selector_type == "customer_issue" && (selector_number == "Customer App" || selector_number == "Customer Portal") && !isNullorEmpty(ticket_id)){ inlineQty += '<div class="form-group container ss_section">'; inlineQty += '<div class="row">'; inlineQty += '<div class="col-xs-12 screenshot_div">'; inlineQty += '<div class="input-group"><span class="input-group-addon" id="screenshot_text">SCREENSHOT</span>'; inlineQty += '<input type="file" class="form-control" id="screenshot_image" value="'+ screenshot_file + '">'; inlineQty += '</div></div></div></div>'; } // Browser and OS Section inlineQty += '<div class="form-group container browser_os_section ' + hide_class_section_mp_portal + ' ' + is_customer_issue_hide + '">'; inlineQty += '<div class="row">'; inlineQty += '<div class="col-xs-6 browser_div">'; inlineQty += '<div class="input-group"><span class="input-group-addon" id="browser_text">BROWSER</span>'; inlineQty += '<select id="browser_value" class="form-control label_status">'; inlineQty += '<option></option>' var browserColumns = new Array(); browserColumns[0] = search.createColumn({ name: 'name' }); browserColumns[1] = search.createColumn({ name: 'internalId' }); var browserResultSet = search.create({ type: 'customlist_common_browsers', columns: browserColumns }); browserResultSet.run().each(function (browserResult) { var browserName = browserResult.getValue('name'); var browserId = browserResult.getValue('internalId'); if(selected_browser == browserId) { inlineQty += '<option value="' + browserId + '"selected>' + browserName + '</option>'; }else{ inlineQty += '<option value="' + browserId + '">' + browserName + '</option>'; } return inlineQty; }); inlineQty += '</select></div></div>'; inlineQty += '<div class="col-xs-6 os_div">'; inlineQty += '<div class="input-group"><span class="input-group-addon" id="os_text">OPERATING SYSTEM</span>'; inlineQty += '<select id="os_value" class="form-control">'; inlineQty += '<option></option>' var osColumns = new Array(); osColumns[0] = search.createColumn({ name: 'name' }); osColumns[1] = search.createColumn({ name: 'internalId' }); var osResultSet = search.create({ type: 'customlist_common_os', columns: osColumns }); osResultSet.run().each(function (osResult) { var osName = osResult.getValue('name'); var osId = osResult.getValue('internalId'); if(selected_browser == osId) { inlineQty += '<option value="' + osId + '"selected>' + osName + '</option>'; }else{ inlineQty += '<option value="' + osId + '">' + osName + '</option>'; } return inlineQty; }); inlineQty += '</select>'; inlineQty += '</div></div></div></div>'; //Customer App issues - Phone section inlineQty += '<div class="form-group container '+is_customer_issue_hide+' phone_section ' + hide_class_section_mp_app + '">'; inlineQty += '<div class="row">'; inlineQty += '<div class="col-xs-12 phone_div">'; inlineQty += '<div class="input-group"><span class="input-group-addon" id="screenshot_text">PHONE</span>'; inlineQty += '<input type="text" class="form-control" id="phone_used" placeholder=" Google Pixel 3" value="'+ phone_used + '">'; inlineQty += '</div></div></div></div>'; //Login email used section inlineQty += '<div class="form-group container login_email_used_section '+ is_customer_issue_hide +'">'; inlineQty += '<div class="row">'; inlineQty += '<div class="col-xs-12 login_email_div">'; inlineQty += '<div class="input-group">'; inlineQty += '<span class="input-group-addon" id="login_email">LOGIN EMAIL</span>'; inlineQty += '<input id="login_email_text" class="form-control" value="'+ login_email_used + '"/>'; inlineQty += '</div></div></div></div>'; //Sender details name and phone number inlineQty += '<div class="form-group container '+ is_customer_issue_hide +' sender_details_section ' + hide_class_section_mp_label + '">'; inlineQty += '<div class="row">'; inlineQty += '<div class="col-xs-6 sender_name_div">'; inlineQty += '<div class="input-group">'; inlineQty += '<span class="input-group-addon" id="sender_name">SENDER NAME</span>'; inlineQty += '<input id="sender_name_text" class="form-control" value="'+ old_sender_name + '"/>'; inlineQty += '</div></div>'; inlineQty += '<div class="col-xs-6 sender_phone_div">'; inlineQty += '<div class="input-group">'; inlineQty += '<span class="input-group-addon" id="sender_phone">SENDER PHONE</span>'; inlineQty += '<input id="sender_phone_text" class="form-control" value="'+ old_sender_phone + '"/>'; inlineQty += '</div></div></div></div>'; return inlineQty; } /** * The multiselect TOLL issues dropdown * @param {Array} list_toll_issues * @param {Array} list_resolved_toll_issues * @param {Number} status_value * @param {String} selector_type * @return {String} inlineQty */ function tollIssuesSection(list_toll_issues, list_resolved_toll_issues, status_value, selector_type) { // TOLL Issues var has_toll_issues = (!isNullorEmpty(list_toll_issues)); var toll_issues_columns = new Array(); toll_issues_columns[0] = search.createColumn({ name: 'name' }); toll_issues_columns[1] = search.createColumn({ name: 'internalId' }); var tollIssuesResultSet = search.create({ type: 'customlist_cust_prod_stock_toll_issues', columns: toll_issues_columns }); if (!isTicketNotClosed(status_value) || selector_type != 'barcode_number') { var inlineQty = '<div class="form-group container toll_issues_section hide">'; } else { var inlineQty = '<div class="form-group container toll_issues_section">'; } inlineQty += '<div class="row">'; inlineQty += '<div class="col-xs-12 toll_issues">'; inlineQty += '<div class="input-group"><span class="input-group-addon" id="toll_issues_text">TOLL ISSUES<span class="mandatory">*</span></span>'; inlineQty += '<select multiple id="toll_issues" class="form-control toll_issues" size="' + tollIssuesResultSet.length + '">'; tollIssuesResultSet.run().each(function(tollIssueResult) { var issue_name = tollIssueResult.getValue('name'); var issue_id = tollIssueResult.getValue('internalId'); var selected = false; if (has_toll_issues) { selected = (list_toll_issues.indexOf(issue_id) !== -1); } if (selected) { inlineQty += '<option value="' + issue_id + '" selected>' + issue_name + '</option>'; } else { inlineQty += '<option value="' + issue_id + '">' + issue_name + '</option>'; } return true; }); inlineQty += '</select>'; inlineQty += '</div></div></div></div>'; // Resolved TOLL Issues log.debug({ title: 'list_resolved_toll_issues : ', details: list_resolved_toll_issues }); var has_resolved_toll_issues = (!isNullorEmpty(list_resolved_toll_issues)); if (has_resolved_toll_issues) { var text_resolved_toll_issues = ''; tollIssuesResultSet.run().each(function(tollIssueResult) { var issue_name = tollIssueResult.getValue('name'); var issue_id = tollIssueResult.getValue('internalId'); if (list_resolved_toll_issues.indexOf(issue_id) !== -1) { text_resolved_toll_issues += issue_name + '\n'; } return true; }); log.debug({ title: 'text_resolved_toll_issues : ', details: text_resolved_toll_issues }); inlineQty += '<div class="form-group container resolved_toll_issues_section">'; inlineQty += '<div class="row">'; inlineQty += '<div class="col-xs-12 resolved_toll_issues">'; inlineQty += '<div class="input-group">'; inlineQty += '<span class="input-group-addon" id="resolved_toll_issues_text">RESOLVED TOLL ISSUES</span>'; inlineQty += '<textarea id="resolved_toll_issues" class="form-control resolved_toll_issues" rows="' + list_resolved_toll_issues.length + '" disabled>' + text_resolved_toll_issues.trim() + '</textarea>'; inlineQty += '</div></div></div></div>'; } return inlineQty; }; /** * The multiselect MP Ticket issues dropdown * @param {Array} list_mp_ticket_issues * @param {Array} list_resolved_mp_ticket_issues * @param {Number} status_value * @param {String} selector_type * @return {String} inlineQty */ function mpTicketIssuesSection(list_mp_ticket_issues, list_resolved_mp_ticket_issues, status_value, selector_type) { // MP Ticket Issues var has_mp_ticket_issues = !isNullorEmpty(list_mp_ticket_issues); var disabled_mp_issue_field = (isTicketNotClosed(status_value)) ? '' : 'disabled'; log.debug({ title: 'has_mp_ticket_issues : ', details: has_mp_ticket_issues }); if (has_mp_ticket_issues && status_value != 3) { // The MP Ticket issue section is displayed if the status is 'Closed - Unallocated' (status_value == 8) var inlineQty = '<div class="form-group container mp_issues_section">'; } else { var inlineQty = '<div class="form-group container mp_issues_section hide">'; } inlineQty += '<div class="row">'; inlineQty += '<div class="col-xs-12 mp_issues">'; var mp_ticket_issues_columns = new Array(); mp_ticket_issues_columns[0] = search.createColumn({ name: 'name' }); mp_ticket_issues_columns[1] = search.createColumn({ name: 'internalId' }); var mpTicketIssuesResultSet = search.create({ type: 'customlist_mp_ticket_issues', columns: mp_ticket_issues_columns }); inlineQty += '<div class="input-group">' inlineQty += '<span class="input-group-addon" id="mp_issues_text">MP ISSUES<span class="mandatory hide">*</span></span>'; inlineQty += '<select multiple id="mp_issues" class="form-control mp_issues" size="' + mpTicketIssuesResultSet.length + '" ' + disabled_mp_issue_field + '>'; mpTicketIssuesResultSet.run().each(function(mpTicketIssueResult) { var mp_issue_name = mpTicketIssueResult.getValue('name'); var mp_issue_id = mpTicketIssueResult.getValue('internalId'); var selected = false; if (has_mp_ticket_issues) { selected = (list_mp_ticket_issues.indexOf(mp_issue_id) !== -1); } var show_option = (selector_type == 'barcode_number' || (selector_type == 'invoice_number' && mp_issue_id == 4) || (selector_type == "customer_issue")); var selected_option = (selected) ? 'selected' : ''; if (show_option) { inlineQty += '<option value="' + mp_issue_id + '" ' + selected_option + '> ' + mp_issue_name + '</option > '; } return true; }); inlineQty += '</select>'; inlineQty += '</div></div></div></div>'; // Resolved MP Ticket Issues var has_resolved_mp_ticket_issues = !isNullorEmpty(list_resolved_mp_ticket_issues); if (has_resolved_mp_ticket_issues && selector_type != "customer_issue") { var text_resolved_mp_ticket_issues = ''; mpTicketIssuesResultSet.run().each(function(mpTicketIssueResult) { var mp_issue_name = mpTicketIssueResult.getValue('name'); var mp_issue_id = mpTicketIssueResult.getValue('internalId'); if (list_resolved_mp_ticket_issues.indexOf(mp_issue_id) !== -1) { text_resolved_mp_ticket_issues += mp_issue_name + '\n'; } return true; }); inlineQty += '<div class="form-group container resolved_mp_issues_section">'; inlineQty += '<div class="row">'; inlineQty += '<div class="col-xs-12 resolved_mp_issues">'; inlineQty += '<div class="input-group">'; inlineQty += '<span class="input-group-addon" id="resolved_mp_issues_text">RESOLVED MP ISSUES</span>'; inlineQty += '<textarea id="resolved_mp_issues" class="form-control resolved_mp_issues" rows="' + list_resolved_mp_ticket_issues.length + '" disabled>' + text_resolved_mp_ticket_issues.trim() + '</textarea>'; inlineQty += '</div></div></div></div>'; } return inlineQty; } /** * The multiselect Invoice issues dropdown * @param {Array} list_invoice_issues * @param {Array} list_resolved_invoice_issues * @param {Number} status_value * @param {String} selector_type * @return {String} inlineQty */ function invoiceIssuesSection(list_invoice_issues, list_resolved_invoice_issues, status_value, selector_type) { var has_invoice_issues = (!isNullorEmpty(list_invoice_issues)); var invoice_issues_columns = new Array(); invoice_issues_columns[0] = search.createColumn({ name: 'name' }); // Might need to be changed invoice_issues_columns[1] = search.createColumn({ name: 'internalId' }); // Might need to be changed var invoiceIssuesResultSet = search.create({ type: 'customlist_invoice_issues', columns: invoice_issues_columns }); if (!isTicketNotClosed(status_value) || selector_type != 'invoice_number') { var inlineQty = '<div class="form-group container invoice_issues_section hide">'; } else { var inlineQty = '<div class="form-group container invoice_issues_section">'; } inlineQty += '<div class="row">'; inlineQty += '<div class="col-xs-12 invoice_issues">'; inlineQty += '<div class="input-group"><span class="input-group-addon" id="invoice_issues_text">INVOICE ISSUES<span class="mandatory">*</span></span>'; inlineQty += '<select multiple id="invoice_issues" class="form-control invoice_issues">'; invoiceIssuesResultSet.run().each(function(invoiceIssueResult) { var issue_name = invoiceIssueResult.getValue('name'); // Might need to be changed var issue_id = invoiceIssueResult.getValue('internalId'); // Might need to be changed var selected = false; if (has_invoice_issues) { selected = (list_invoice_issues.indexOf(issue_id) != -1); } if (selected) { inlineQty += '<option value="' + issue_id + '" selected>' + issue_name + '</option>'; } else { inlineQty += '<option value="' + issue_id + '">' + issue_name + '</option>'; } return true; }); inlineQty += '</select>'; inlineQty += '</div></div></div></div>'; // Resolved invoice Issues log.debug({ title: 'list_resolved_invoice_issues : ', details: list_resolved_invoice_issues }); var has_resolved_invoice_issues = (!isNullorEmpty(list_resolved_invoice_issues)); if (has_resolved_invoice_issues) { var text_resolved_invoice_issues = ''; invoiceIssuesResultSet.run().each(function(invoiceIssueResult) { var issue_name = invoiceIssueResult.getValue('name'); // Might need to be changed var issue_id = invoiceIssueResult.getValue('internalId'); // Might need to be changed if (list_resolved_invoice_issues.indexOf(issue_id) !== -1) { text_resolved_invoice_issues += issue_name + '\n'; } }); log.debug({ title: 'text_resolved_invoice_issues : ', details: text_resolved_invoice_issues }); inlineQty += '<div class="form-group container resolved_invoice_issues_section">'; inlineQty += '<div class="row">'; inlineQty += '<div class="col-xs-12 resolved_invoice_issues">'; inlineQty += '<div class="input-group">'; inlineQty += '<span class="input-group-addon" id="resolved_invoice_issues_text">RESOLVED INVOICE ISSUES</span>'; inlineQty += '<textarea id="resolved_invoice_issues" class="form-control resolved_invoice_issues" rows="' + list_resolved_invoice_issues.length + '" disabled>' + text_resolved_invoice_issues.trim() + '</textarea>'; inlineQty += '</div></div></div></div>'; } return inlineQty; } /** * @param {String} selector_type * @param {Number} status_value * @return {String} inlineQty */ function usernoteSection(selector_type, status_value) { var usernote_titles_columns = new Array(); usernote_titles_columns[0] = search.createColumn({ name: 'name' }); usernote_titles_columns[1] = search.createColumn({ name: 'internalId' }); var usernoteTitlesResultSet = search.create({ type: 'customlist_user_note_title', columns: usernote_titles_columns }); // Row Title if (selector_type == 'invoice_number' && isTicketNotClosed(status_value)) { var inlineQty = '<div class="form-group container user_note user_note_title_section">'; } else { var inlineQty = '<div class="form-group container user_note user_note_title_section hide">'; } inlineQty += '<div class="row">'; inlineQty += '<div class="col-xs-12 user_note_title_section">'; inlineQty += '<div class="input-group">'; inlineQty += '<span class="input-group-addon">TITLE<span class="mandatory">*</span></span>'; inlineQty += '<select id="user_note_title" class="form-control">'; usernoteTitlesResultSet.run().each(function(usernoteTitleResult) { var title_name = usernoteTitleResult.getValue('name'); var title_id = usernoteTitleResult.getValue('internalId'); if (title_id == 3) { inlineQty += '<option value="' + title_id + '" selected>' + title_name + '</option>'; } else { inlineQty += '<option value="' + title_id + '">' + title_name + '</option>'; } return true; }); inlineQty += '</select>'; inlineQty += '</div></div></div></div>'; // Row User Note Textarea if (selector_type == 'invoice_number' && isTicketNotClosed(status_value)) { inlineQty += '<div class="form-group container user_note user_note_textarea_section">'; } else { inlineQty += '<div class="form-group container user_note user_note_textarea_section hide">'; } inlineQty += '<div class="row">'; inlineQty += '<div class="col-xs-12 user_note_textarea">'; inlineQty += '<div class="input-group">'; inlineQty += '<span class="input-group-addon" id="user_note_textarea_text">USER NOTE<span class="mandatory hide">*</span></span>'; inlineQty += '<textarea id="user_note_textarea" class="form-control user_note_textarea" rows="3"></textarea>'; inlineQty += '</div></div></div></div>'; // User Note table if (selector_type == 'invoice_number') { inlineQty += '<div class="form-group container user_note user_note_section" style="font-size: small;">'; } else { inlineQty += '<div class="form-group container user_note user_note_section hide" style="font-size: small;">'; } inlineQty += '<div class="row">'; inlineQty += '<div class="col-xs-12 user_note_div">'; // Since the table is not displayed correctly when added through suitelet, // It is added with jQuery in the pageInit() function in the client script 'mp_cl_open_ticket.js'. inlineQty += '</div>'; inlineQty += '</div>'; inlineQty += '</div>'; return inlineQty; } /** * Used to pass the values of `date_from` and `date_to` between the scripts and to Netsuite for the records and the search. * @param {String} date_iso "2020-06-01" * @returns {String} date_netsuite "1/6/2020" */ function dateISOToNetsuite(date_iso) { var date_netsuite = ''; if (!isNullorEmpty(date_iso)) { var date_netsuite = format.format({ value: date_iso, type: format.Type.DATETIME }); } return date_netsuite; } /** * The free-from text area for comments. * @param {String} comment * @param {String} selector_type * @param {Number} status_value * @return {String} inlineQty */ function commentSection(comment, selector_type, status_value) { if (isNullorEmpty(comment)) { comment = ''; } else { comment += '\n'; } switch (selector_type) { case 'barcode_number': var inlineQty = '<div class="form-group container comment_section">'; break; case 'invoice_number': var inlineQty = '<div class="form-group container comment_section hide">'; break; case 'customer_issue': var inlineQty = '<div class="form-group container comment_section">'; break; } inlineQty += '<div class="row">'; inlineQty += '<div class="col-xs-12 comment">'; inlineQty += '<div class="input-group">'; inlineQty += '<span class="input-group-addon" id="comment_text">COMMENT<span class="mandatory hide">*</span></span>'; if (isTicketNotClosed(status_value)) { inlineQty += '<textarea id="comment" class="form-control comment" rows="3">' + comment + '</textarea>'; } else { inlineQty += '<textarea id="comment" class="form-control comment" rows="3" readonly>' + comment + '</textarea>'; } inlineQty += '</div></div></div></div>'; return inlineQty; } /** * The table that will display the differents tickets linked to the customer. * @return {String} inlineQty */ function dataTablePreview() { var inlineQty = '<div class="form-group container tickets_datatable_section">'; inlineQty += '<div class="row">'; inlineQty += '<div class="col-xs-12 heading2">'; inlineQty += '<h4><span style="background-color: #379E8F" class="label label-default col-xs-12">PREVIOUS TICKETS</span></h4>'; inlineQty += '</div></div></div>'; inlineQty += '<style>table#tickets-preview {font-size: 12px;text-align: center;border: none; background-color: #379E8F}.dataTables_wrapper {font-size: 12px;}table#tickets-preview th{background-color: #379E8F; text-align: center;}</style>'; inlineQty += '<table cellpadding="15" id="tickets-preview" class="table table-responsive table-striped customer tablesorter" cellspacing="0" style="width: 100%;">'; inlineQty += '<thead style="color: white;background-color: #379E8F;">'; inlineQty += '<tr class="text-center">'; inlineQty += '</tr>'; inlineQty += '</thead>'; inlineQty += '<tbody id="result_tickets"></tbody>'; inlineQty += '</table>'; return inlineQty; } /** * The inline HTML for the close ticket button or the reopen button, * and the submitter button at the bottom of the page. * @param {Number} ticket_id * @param {Number} status_value * @return {String} inlineQty */ function closeReopenSubmitTicketButton(ticket_id, status_value) { var inlineQty = '<div class="form-group container close_reopen_submit_ticket_section">'; inlineQty += '<div class="row">'; log.debug({ title: 'status_value', details: status_value }); log.debug({ title: 'ticket_id', details: ticket_id }); if (isTicketNotClosed(status_value)) { if (!isNullorEmpty(ticket_id)) { inlineQty += '<div class="col-xs-2 close_ticket">'; inlineQty += '<input type="button" value="CLOSE TICKET" style="background-color: #FBEA51; border: 3px solid #379E8F; color: #379E8F; font-weight: 700" class="form-control btn btn-default" id="close_ticket" onclick="closeTicket()"/>'; inlineQty += '</div>'; inlineQty += '<div class="col-xs-3 close_ticket_lost">'; inlineQty += '<input type="button" value="CLOSE TICKET - LOST ITEM" style="background-color: #FBEA51; border: 3px solid #379E8F; color: #379E8F; font-weight: 700" class="form-control btn btn-default" id="close_ticket_lost" onclick="closeTicketLost()"/>'; inlineQty += '</div>'; if (userId == 409635 || userId == 696992 || userId == 766498) { inlineQty += '<div class="col-xs-3 close_unallocated_ticket hide">'; inlineQty += '<input type="button" value="CLOSE UNALLOCATED TICKET" style="background-color: #FBEA51; border: 3px solid #379E8F; color: #379E8F; font-weight: 700" class="form-control btn btn-default" id="close_unallocated_ticket" onclick="closeUnallocatedTicket()" />'; inlineQty += '</div>'; } } inlineQty += '<div class="col-xs-2 submitter">'; inlineQty += '<input type="button" style="background-color: #FBEA51; border: 3px solid #379E8F; color: #379E8F; font-weight: 700" value="UPDATE TICKET" class="form-control btn btn-primary" id="submit_ticket" />'; inlineQty += '</div>'; if (isNullorEmpty(ticket_id)) { inlineQty += '<div class="col-xs-3 open_and_new_ticket_btn">'; inlineQty += '<input type="button" style="background-color: #FBEA51; border: 3px solid #379E8F; color: #379E8F; font-weight: 700" value="OPEN AND NEW TICKET" class="form-control btn btn-primary" id="open_and_new_ticket_btn" />'; inlineQty += '</div>'; } inlineQty += '<style>.escalate:hover {box-shadow: 0 12px 16px 0 rgba(0,0,0,0.24), 0 17px 50px 0 rgba(0,0,0,0.19)}</style>'; inlineQty += '<div class="col-xs-2 escalate">'; inlineQty += '<input type="button" style="background-color: #FBEA51; border: 3px solid #379E8F; color: #379E8F; font-weight: 700" value="ESCALATE" class="form-control btn btn-default" id="escalate" onclick="onEscalate()"/>'; inlineQty += '</div>'; } else { inlineQty += '<div class="col-xs-2 col-xs-offset-2 reopen_ticket">'; inlineQty += '<input type="button" style="background-color: #FBEA51; border: 3px solid #379E8F; color: #379E8F; font-weight: 700" value="REOPEN TICKET" class="form-control btn btn-primary" id="reopen_ticket" />'; inlineQty += '</div>'; } inlineQty += '<div class="col-xs-2 cancel">'; inlineQty += '<input type="button" style="background-color: #FBEA51; border: 3px solid #379E8F; color: #379E8F; font-weight: 700" value="CANCEL" class="form-control btn btn-default" id="cancel" onclick="onCancel()"/>'; inlineQty += '</div>'; inlineQty += '</div></div>'; return inlineQty; } function Ownerjava2jsArray(javaArray) { var jsArray = new Array; if (!isNullorEmpty(javaArray)) { javaArray.forEach(function(javaValue) { var jsValue = parseInt(javaValue); jsArray.push(jsValue); }) } return jsArray; } /** * The output of .getFieldValues is a java String Array. * We want to convert it to a javaScript Array in order to read its values. * @param {Ljava.lang.String} javaArray * @return {Array} jsArray */ function java2jsArray(javaArray) { var jsArray = new Array; if (!isNullorEmpty(javaArray)) { javaArray.forEach(function(javaValue) { var jsValue = javaValue.toString(); jsArray.push(jsValue); }) } return jsArray; } /** * Parse the objects in an array, and returns an object based on the value of one of its keys. * With ES6, this function would simply be `array.find(obj => obj[key] == value)` * @param {Array} array * @param {String} key * @param {*} value * @returns {Object} */ function findObjectByKey(array, key, value) { for (var i = 0; i < array.length; i++) { if (array[i][key] === value) { return array[i]; } } return null; } /** * Returns whether a ticket is closed or not based on its status value. * @param {Number} status_value * @returns {Boolean} is_ticket_closed */ function isTicketNotClosed(status_value) { var is_ticket_not_closed = ((status_value != 3) && (status_value != 8) && (status_value != 15)) ? true : false; return is_ticket_not_closed; } function escalateButton(status) { if (status < 11) { return 'Escalate to 1st Escalation'; } else if (status == 11) { return 'Escalate to 2nd Escalation'; }else if (status == 12) { return 'Escalate to 3rd Escalation'; } else if (status == 13) { return 'Escalate to Final Escalation'; } else { return 'Escalate'; } } /** * Whether the user is from the finance team, * or a Data Systems Co-ordinator, MailPlus Administration or Administrator user. * @param {Number} userRole * @returns {Boolean} */ function isFinanceRole(userRole) { // 1001, 1031 and 1023 are finance roles // 1032 is the Data Systems Co-ordinator role (to be deleted in prod) // 1006 is the Mail Plus Administration role. // 3 is the Administrator role. return ((userRole == 1001 || userRole == 1031 || userRole == 1023) || ((userRole == 1032) || (userRole == 1006) || (userRole == 3))); } function isNullorEmpty(strVal) { return (strVal == null || strVal == '' || strVal == 'null' || strVal == undefined || strVal == 'undefined' || strVal == '- None -'); } return { onRequest: onRequest }; });
true
/** * * @NApiVersion 2.0 * @NScriptType Suitelet * * Description: A ticketing system for the Customer Service. * @Last Modified by: Sruti Desai * */ define(['N/ui/serverWidget', 'N/email', 'N/runtime', 'N/search', 'N/record', 'N/http', 'N/log', 'N/redirect', 'N/format', 'N/file'], function(ui, email, runtime, search, record, http, log, redirect, format, file) { var baseURL = 'https://1048144.app.netsuite.com'; if (runtime.EnvType == "SANDBOX") { baseURL = 'https://1048144-sb3.app.netsuite.com'; } var zee = 0; var role = runtime.getCurrentUser().role; var userRole = runtime.getCurrentUser().role; var ctx = runtime.getCurrentScript(); var userId = runtime.getCurrentUser().id; if (role == 1000) { //Franchisee zee = runtime.getCurrentUser(); } function onRequest(context) { if (context.request.method === 'GET') { var ticket_id = null; var customer_id = null; var customer_number = null; var selector_id = null; var selector_number = ''; var selector_type = 'barcode_number'; var connote_number = ''; var date_created = ''; var creator_name = ''; var creator_id = null; var status_value = null; var escalated_to_it = ''; var status = ''; var customer_name = ''; var daytodayphone = ''; var daytodayemail = ''; var accountsphone = ''; var accountsemail = ''; var zee_id = null; var franchisee_name = ''; var zee_main_contact_name = ''; var zee_email = ''; var zee_main_contact_phone = ''; var zee_abn = ''; var date_stock_used = ''; var time_stock_used = ''; var final_delivery_text = ''; var selected_enquiry_status_id = null; var attachments_hyperlink = ''; var maap_bank_account_number = null; var maap_parent_bank_account_number = null; var selected_invoice_method_id = null; var accounts_cc_email = ''; var mpex_po_number = ''; var customer_po_number = ''; var terms = null; var customer_terms = ''; var account_manager = {}; var selected_invoice_cycle_id = null; var usage_report_id_1 = ''; var usage_report_id_2 = ''; var usage_report_id_3 = ''; var usage_report_id_4 = ''; var usage_report_array = []; var list_toll_issues = ''; var list_resolved_toll_issues = ''; var list_mp_ticket_issues = ''; var list_resolved_mp_ticket_issues = ''; var list_invoice_issues = ''; var list_resolved_invoice_issues = ''; var owner_list = ''; var comment = ''; var selected_label_id = null; var list_enquiry_mediums = ''; var total_enquiry_count = 0; var chat_enquiry_count = 0; var phone_enquiry_count = 0; var email_enquiry_count = 0; var phone_interaction_count = 0; var email_interaction_count = 0; var list_toll_emails = ''; var params_email = { recipient: '', subject: '', body: '', cc: '', bcc: '', records: {}, attachments_credit_memo_ids: [], attachments_usage_report_ids: [], attachments_invoice_ids: [] }; var customer_barcode_number = ''; var customer_issue = ''; var screenshot_file = ''; var browser = ''; var login_email_used = ''; var operating_system = ''; var phone_used = ''; var old_sender_name = ''; var old_sender_phone = ''; var customer_number_email_sent = 'F'; var customer_ticket_status = ''; var receiveremail = ''; var receiverphone = ''; var receivername = ''; var receiverstate = ''; var receiverzip = ''; var receiversuburb = ''; var receiveraddr1 = ''; var receiveraddr2 = ''; var prod_stock_invoice = ''; var barcodempdl = ''; var barcodesource = ''; // Load params var params = context.request.parameters.custparam_params; log.debug({ title: 'Params', details: params }) if (!isNullorEmpty(params)) { params = JSON.parse(params); log.debug({ title: 'Params not empty', details: params }); // Coming from the ticket_contact page or the edit_ticket page if (!isNullorEmpty(params.selector_number) && !isNullorEmpty(params.selector_type)) { selector_number = params.selector_number; selector_type = params.selector_type; //Coming from the ticket_contact page if (!isNullorEmpty(params.custid)) { customer_id = params.custid; } log.debug({ title: 'customer_id after ticket_contact_page : ', details: customer_id }); // Coming from the edit_ticket page if (!isNullorEmpty(params.ticket_id)) { ticket_id = parseInt(params.ticket_id); log.debug({ title: 'ticket id ISS', details: ticket_id }); // Load ticket data var ticketRecord = record.load({ type: 'customrecord_mp_ticket', id: ticket_id }); date_created = ticketRecord.getValue({ fieldId: 'created' }); creator_name = ticketRecord.getText({ fieldId: 'custrecord_creator' }); creator_id = ticketRecord.getValue({ fieldId: 'custrecord_creator' }); status_value = ticketRecord.getValue({ fieldId: 'custrecord_ticket_status' }); escalated_to_it = ticketRecord.getValue({ fieldId: 'custrecord_date_escalated_it' }); status = ticketRecord.getText({ fieldId: 'custrecord_ticket_status' }); customer_id = ticketRecord.getValue({ fieldId: 'custrecord_customer1' }); customer_name = ticketRecord.getText({ fieldId: 'custrecord_customer1' }); zee_id = ticketRecord.getValue({ fieldId: 'custrecord_zee' }); selected_enquiry_status_id = ticketRecord.getValue({ fieldId: 'custrecord_enquiry_status' }); attachments_hyperlink = ticketRecord.getValue({ fieldId: 'custrecord_mp_ticket_attachments' }); selected_label_id = ticketRecord.getValue({ fieldId: 'custrecord_ticket_label' }); list_enquiry_mediums = ticketRecord.getValue({ fieldId: 'custrecord_enquiry_medium' }); list_enquiry_mediums = java2jsArray(list_enquiry_mediums); total_enquiry_count = ticketRecord.getValue({ fieldId: 'custrecord_enquiry_count' }); chat_enquiry_count = ticketRecord.getValue({ fieldId: 'custrecord_chat_enquiry_count' }); phone_enquiry_count = ticketRecord.getValue({ fieldId: 'custrecord_phone_enquiry_count' }); phone_interaction_count = ticketRecord.getValue({ fieldId: 'custrecord_phone_interaction_count' }); email_interaction_count= ticketRecord.getValue({ fieldId: 'custrecord_email_interaction_count' }); email_enquiry_count = ticketRecord.getValue({ fieldId: 'custrecord_email_enquiry_count' }); customer_issue = ticketRecord.getValue({ fieldId: 'custrecord_customer_issue' }); screenshot_file = ticketRecord.getValue({ fieldId: 'custrecord_screenshot' }); browser = ticketRecord.getValue({ fieldId: 'custrecord_browser' }); login_email_used = ticketRecord.getValue({ fieldId: 'custrecord_login_email' }); operating_system = ticketRecord.getValue({ fieldId: 'custrecord_operating_system' }); phone_used = ticketRecord.getValue({ fieldId: 'custrecord_phone_used' }); customer_number = ticketRecord.getValue({ fieldId: 'custrecord_cust_number' }); old_sender_name = ticketRecord.getValue({ fieldId: 'custrecord_sender_name' }); old_sender_phone = ticketRecord.getValue({ fieldId: 'custrecord_sender_phone' }); customer_number_email_sent = ticketRecord.getValue({ fieldId: 'custrecord_customer_number_email_sent' }); customer_barcode_number = ticketRecord.getValue({ fieldId : 'custrecord_barcode_number'}); customer_ticket_status = ticketRecord.getText({ fieldId : 'custrecord_mp_ticket_customer_status'}); if (!isNullorEmpty(customer_barcode_number)) { var rec = record.load({ type: 'customrecord_customer_product_stock', id: customer_barcode_number, }); receiveremail = rec.getValue({fieldId: 'custrecord_receiver_email'}); receiverphone = rec.getValue({fieldId: 'custrecord_receiver_phone'}); receivername = rec.getValue({fieldId: 'custrecord_receiver_name'}); receiverstate = rec.getValue({fieldId: 'custrecord_receiver_state'}); receiverzip = rec.getValue({fieldId: 'custrecord_receiver_postcode'}); receiversuburb = rec.getValue({fieldId: 'custrecord_receiver_suburb'}); receiveraddr1 = rec.getValue({fieldId: 'custrecord_receiver_addr1'}); receiveraddr2 = rec.getValue({fieldId: 'custrecord_receiver_addr2'}); prod_stock_invoice = rec.getText({fieldId: 'custrecord_prod_stock_invoice'}); barcodempdl = rec.getValue({fieldId: 'custrecord_mpdl_number'}); barcodesource = rec.getText({fieldId: 'custrecord_barcode_source'}); connote_number = rec.getValue({fieldId: 'custrecord_connote_number'}); } if(isNullorEmpty(customer_id) && !isNullorEmpty(customer_number)){ var customer_search = search.load({ type: 'customer', id: 'customsearch_customer_name_2' }); customer_search.filters.push(search.createFilter({ name: 'entityid', operator: 'haskeywords', values: customer_number, })); log.debug({ title: 'customer_search.run().getRange({ start: 0,end:1 })[0].id', details: customer_search.run().getRange({ start: 0,end:1 })[0].id }); customer_id = customer_search.run().getRange({ start: 0,end:1 })[0].id; } if (!isNullorEmpty(customer_id)) { //Load customer record and franchisee information var customerRecord = record.load({ type: 'customer', id: customer_id }); customer_number = customerRecord.getValue({ fieldId: 'entityid' }); daytodayphone = customerRecord.getValue({ fieldId: 'phone' }); daytodayemail = customerRecord.getValue({ fieldId: 'custentity_email_service' }); terms = customerRecord.getValue({ fieldId: 'terms' }); customer_terms = customerRecord.getValue({ fieldId: 'custentity_finance_terms' }); // Account manager var accountManagerSearch = search.load({ type: 'customer', id: 'customsearch3413' }); accountManagerSearch.filters.push(search.createFilter({ name: 'internalid', join: null, operator: search.Operator.ANYOF, values: customer_id, })) var accountManagerResultSet = accountManagerSearch.run(); var accountManagerResult = accountManagerResultSet.getRange({ start: 0, end: 1 }); accountManagerResult = accountManagerResult[0]; if (!isNullorEmpty(accountManagerResult)) { var account_manager_value = accountManagerResult.getValue({ name: "custrecord_sales_assigned", join: "CUSTRECORD_SALES_CUSTOMER", summary: null }); var account_manager_text = accountManagerResult.getText({ name: "custrecord_sales_assigned", join: "CUSTRECORD_SALES_CUSTOMER", summary: null }); if (!isNullorEmpty(account_manager_value)) { var account_manager_email = search.lookupFields({ type: 'employee', id: account_manager_value, columns: 'email' }); account_manager = { name: account_manager_text, email: account_manager_email }; } } // The Franchisee informations are imported from the customer record if possible. zee_id = customerRecord.getValue({ fieldId: 'partner' }); } if (!isNullorEmpty(zee_id)) { var zeeRecord = record.load({ type: 'partner', id: zee_id }); franchisee_name = zeeRecord.getValue({ fieldId: 'companyname' }); zee_main_contact_name = zeeRecord.getValue({ fieldId: 'custentity3' }); zee_email = zeeRecord.getValue({ fieldId: 'email' }); zee_main_contact_phone = zeeRecord.getValue({ fieldId: 'custentity2' }); zee_abn = zeeRecord.getValue({ fieldId: 'custentity_abn_franchiserecord' }); } else { franchisee_name = ticketRecord.getText({ fieldId: 'custrecord_zee' }); } switch (selector_type) { case 'barcode_number': selector_id = ticketRecord.getValue({ fieldId: 'custrecord_barcode_number' }); var stock_used = ''; if(!isNullorEmpty(selector_id)){ //Come in here only if selector_id is not null stock_used = search.lookupFields({ type: 'customrecord_customer_product_stock', id: selector_id, columns: ['custrecord_cust_date_stock_used', 'custrecord_cust_time_stock_used'] }); log.debug({ title: 'stock_used', details: stock_used }) log.debug({ title: 'finalDel', details: search.lookupFields({ type: 'customrecord_customer_product_stock', id: selector_id, columns: 'custrecord_cust_prod_stock_final_del' }) }); var finalDelCheck = search.lookupFields({ type: 'customrecord_customer_product_stock', id: selector_id, columns: 'custrecord_cust_prod_stock_final_del' }).custrecord_cust_prod_stock_final_del; if (!isNullorEmpty(finalDelCheck)) { final_delivery_text = search.lookupFields({ type: 'customrecord_customer_product_stock', id: selector_id, columns: 'custrecord_cust_prod_stock_final_del' })["custrecord_cust_prod_stock_final_del"][0]["text"]; } date_stock_used = stock_used.custrecord_cust_date_stock_used; time_stock_used = stock_used.custrecord_cust_time_stock_used; } list_toll_issues = ticketRecord.getValue({ fieldId: 'custrecord_toll_issues' }); list_toll_issues = java2jsArray(list_toll_issues); list_resolved_toll_issues = ticketRecord.getValue({ fieldId: 'custrecord_resolved_toll_issues' }); list_resolved_toll_issues = java2jsArray(list_resolved_toll_issues); list_toll_emails = ticketRecord.getValue({ fieldId: 'custrecord_toll_emails' }); list_toll_emails = java2jsArray(list_toll_emails); break; case 'invoice_number': selector_id = ticketRecord.getValue({ fieldId: 'custrecord_invoice_number' }); var invoiceRecord = record.load({ type: 'invoice', id: selector_id }); accountsphone = customerRecord.getValue({ fieldId: 'altphone' }); accountsemail = customerRecord.getValue({ fieldId: 'email' }); maap_bank_account_number = customerRecord.getValue({ fieldId: 'custentity_maap_bankacctno' }); maap_parent_bank_account_number = customerRecord.getValue({ fieldId: 'custentity_maap_bankacctno_parent' }); selected_invoice_method_id = customerRecord.getValue({ fieldId: 'custentity_invoice_method' }); accounts_cc_email = customerRecord.getValue({ fieldId: 'custentity_accounts_cc_email' }); mpex_po_number = customerRecord.getValue({ fieldId: 'custentity_mpex_po' }); customer_po_number = customerRecord.getValue({ fieldId: 'custentity11' }); selected_invoice_cycle_id = customerRecord.getValue({ fieldId: 'custentity_mpex_invoicing_cycle' }); usage_report_id_1 = invoiceRecord.getValue({ fieldId: 'custbody_mpex_usage_report' }); usage_report_id_2 = invoiceRecord.getValue({ fieldId: 'custbody_mpex_usage_report_2' }); usage_report_id_3 = invoiceRecord.getValue({ fieldId: 'custbody_mpex_usage_report_3' }); usage_report_id_4 = invoiceRecord.getValue({ fieldId: 'custbody_mpex_usage_report_4' }); var usage_report_id_array = [usage_report_id_1, usage_report_id_2, usage_report_id_3, usage_report_id_4]; usage_report_id_array.forEach(function (usage_report_id) { if (!isNullorEmpty(usage_report_id)) { var usage_report_file = file.load({ id: usage_report_id }); usage_report_name = usage_report_file.name; usage_report_link = usage_report_file.url; usage_report_array.push({ id: usage_report_id, name: usage_report_name, url: usage_report_link }); } }); list_invoice_issues = ticketRecord.getValue({ fieldId: 'custrecord_invoice_issues' }); list_invoice_issues = java2jsArray(list_invoice_issues); list_resolved_invoice_issues = ticketRecord.getValue({ fieldId: 'custrecord_resolved_invoice_issues' }); list_resolved_invoice_issues = java2jsArray(list_resolved_invoice_issues); break; } list_mp_ticket_issues = ticketRecord.getValue({ fieldId: 'custrecord_mp_ticket_issue' }); list_mp_ticket_issues = java2jsArray(list_mp_ticket_issues); list_resolved_mp_ticket_issues = ticketRecord.getValue({ fieldId: 'custrecord_resolved_mp_ticket_issue' }); list_resolved_mp_ticket_issues = java2jsArray(list_resolved_mp_ticket_issues); owner_list = ticketRecord.getValue({ fieldId: 'custrecord_owner' }); owner_list = Ownerjava2jsArray(owner_list); comment = ticketRecord.getValue({ fieldId: 'custrecord_comment' }); } } } var form = ui.createForm({ title: ' ', }); // Load jQuery var inlineHtml = '<script src="https://code.jquery.com/jquery-1.12.4.min.js" integrity="PI:KEY:9jnerlff23u8ed01np9g6ysbhsh0dvcsEND_PI" crossorigin="anonymous"></script>'; // Load Tooltip inlineHtml += '<script src="https://unpkg.com/@popperjs/core@2"></script>'; // Load Bootstrap inlineHtml += '<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/3.4.1/css/bootstrap.min.css" integrity="PI:KEY:949d1u22cbffbrarjh182eig55721odjEND_PI" crossorigin="anonymous">'; inlineHtml += '<script src="https://stackpath.bootstrapcdn.com/bootstrap/3.4.1/js/bootstrap.min.js" integrity="PI:KEY:ax5kh6jaqkcd2tiexxs8v6xjo8yv8a6bEND_PI" crossorigin="anonymous"></script>'; // Load DataTables inlineHtml += '<link rel="stylesheet" type="text/css" href="//cdn.datatables.net/1.10.21/css/jquery.dataTables.min.css">'; inlineHtml += '<script type="text/javascript" charset="utf8" src="//cdn.datatables.net/1.10.21/js/jquery.dataTables.min.js"></script>'; // Load Summernote css/js inlineHtml += '<link href="https://cdnjs.cloudflare.com/ajax/libs/summernote/0.8.9/summernote.css" rel="stylesheet">'; inlineHtml += '<script src="https://cdnjs.cloudflare.com/ajax/libs/summernote/0.8.9/summernote.js"></script>'; // Load bootstrap-select inlineHtml += '<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap-select@1.13.14/dist/css/bootstrap-select.min.css">'; inlineHtml += '<script src="https://cdn.jsdelivr.net/npm/bootstrap-select@1.13.14/dist/js/bootstrap-select.min.js"></script>'; // Load Netsuite stylesheet and script inlineHtml += '<link rel="stylesheet" href="https://1048144.app.netsuite.com/core/media/media.nl?id=2060796&c=1048144&h=9ee6accfd476c9cae718&_xt=.css"/>'; inlineHtml += '<script src="https://1048144.app.netsuite.com/core/media/media.nl?id=2060797&c=1048144&h=ef2cda20731d146b5e98&_xt=.js"></script>'; inlineHtml += '<link type="text/css" rel="stylesheet" href="https://1048144.app.netsuite.com/core/media/media.nl?id=2090583&c=1048144&h=a0ef6ac4e28f91203dfe&_xt=.css">'; inlineHtml += '<style>.mandatory{color:red;}</style>'; // Define alert window. inlineHtml += '<div class="container" style="margin-top:14px;" hidden><div id="danger-alert" class="alert alert-danger fade in"></div></div>'; // Define information window. inlineHtml += '<div class="container" hidden><p id="info" class="alert alert-info"></p></div>'; inlineHtml += tabsSection(customer_number, ticket_id, selector_number, selector_id, selector_type, status_value, customer_name, daytodayphone, daytodayemail, franchisee_name, zee_main_contact_name, zee_email, zee_main_contact_phone, zee_abn, date_stock_used, time_stock_used, final_delivery_text, selected_enquiry_status_id, attachments_hyperlink, owner_list, list_toll_issues, list_resolved_toll_issues, comment, date_created, creator_id, creator_name, status, customer_id, accountsphone, accountsemail, zee_id, list_enquiry_mediums, total_enquiry_count, chat_enquiry_count, phone_enquiry_count, email_enquiry_count, selected_label_id, maap_bank_account_number, maap_parent_bank_account_number, account_manager, list_toll_emails, customer_barcode_number, connote_number, receiveremail, receiverphone, receivername, receiverstate, receiverzip, receiversuburb, receiveraddr1, receiveraddr2, prod_stock_invoice, barcodempdl, barcodesource, list_mp_ticket_issues, list_resolved_mp_ticket_issues, list_invoice_issues, list_resolved_invoice_issues, selected_invoice_method_id, accounts_cc_email, mpex_po_number, customer_po_number, selected_invoice_cycle_id, terms, customer_terms, screenshot_file, browser, login_email_used, operating_system, phone_used, old_sender_name, old_sender_phone, phone_interaction_count, email_interaction_count, escalated_to_it); // inlineHtml += customerNumberSection(customer_number, ticket_id); // inlineHtml += selectorSection(ticket_id, selector_number, selector_id, selector_type, status_value); // if (!isNullorEmpty(ticket_id)) { // inlineHtml += ticketSection(dateISOToNetsuite(date_created), creator_id, creator_name, status); // } // if (isNullorEmpty(ticket_id) || (!isNullorEmpty(ticket_id) && !isNullorEmpty(customer_id)) || !isNullorEmpty(customer_number)) { // inlineHtml += customerSection(customer_name); // inlineHtml += daytodayContactSection(daytodayphone, daytodayemail, status_value, selector_type); // inlineHtml += accountsContactSection(accountsphone, accountsemail, status_value, selector_type); // } // if(isNullorEmpty(ticket_id) || (!isNullorEmpty(ticket_id) && (selector_type == 'invoice_section'))) { // inlineHtml += maapBankAccountSection(maap_bank_account_number, maap_parent_bank_account_number, selector_type); // } // if (isNullorEmpty(ticket_id) || (!isNullorEmpty(ticket_id) && !isNullorEmpty(zee_id)) || !isNullorEmpty(customer_number)) { // inlineHtml += franchiseeMainContactSection(franchisee_name, zee_main_contact_name, zee_email, zee_main_contact_phone, zee_abn); // } // inlineHtml += mpexStockUsedSection(selector_type, date_stock_used, time_stock_used); // inlineHtml += finalDeliveryEnquirySection(status_value, selector_type, final_delivery_text, selected_enquiry_status_id); // inlineHtml += attachmentsSection(attachments_hyperlink, status_value); // if (isNullorEmpty(ticket_id) || (!isNullorEmpty(ticket_id) && (selector_type == 'invoice_number'))) { // inlineHtml += otherInvoiceFieldsSection(selected_invoice_method_id, accounts_cc_email, mpex_po_number, customer_po_number, selected_invoice_cycle_id, terms, customer_terms, status_value, selector_type); // inlineHtml += openInvoicesSection(ticket_id, selector_type); // if (!isNullorEmpty(ticket_id)) { // inlineHtml += creditMemoSection(selector_type); // inlineHtml += usageReportSection(selector_type); // } // } // inlineHtml += mpexContactSection(); // inlineHtml += enquiryMediumSection(list_enquiry_mediums, selected_enquiry_status_id ,selector_type); // inlineHtml += enquiryCountSection(total_enquiry_count, chat_enquiry_count, phone_enquiry_count, email_enquiry_count); // inlineHtml += labelSection(selected_label_id, selector_type, status_value); // inlineHtml += sendEmailSection(ticket_id, status_value, account_manager,list_toll_emails); // log.debug({ title: 'before prev email - cust id', details: customer_id }); // if(!isNullorEmpty(customer_id)){ // inlineHtml += previousEmailsSection(customer_id); // } // inlineHtml += issuesHeader(); // inlineHtml += customerIssuesSection(ticket_id, selector_type, selector_number, screenshot_file, browser, login_email_used, operating_system, phone_used, old_sender_name, old_sender_phone, status_value); // if(selector_type == "barcode_number" || selector_type == "invoice_number"){ // inlineHtml += reminderSection(status_value); // } // inlineHtml += ownerSection(ticket_id, owner_list, status_value); // inlineHtml += tollIssuesSection(list_toll_issues, list_resolved_toll_issues, status_value, selector_type); // inlineHtml += mpTicketIssuesSection(list_mp_ticket_issues, list_resolved_mp_ticket_issues, status_value, selector_type); // inlineHtml += invoiceIssuesSection(list_invoice_issues, list_resolved_invoice_issues, status_value, selector_type); // inlineHtml += usernoteSection(selector_type, status_value); // inlineHtml += commentSection(comment, selector_type, status_value); // inlineHtml += dataTablePreview(); //inlineHtml += closeReopenSubmitTicketButton(ticket_id, status_value); form.addField({ id: 'preview_table', type: ui.FieldType.INLINEHTML, label: 'preview_table' }).defaultValue = inlineHtml; form.addField({ id: 'custpage_open_new_ticket', type: ui.FieldType.TEXT, label: 'Open New Ticket' }).updateDisplayType({ displayType: ui.FieldDisplayType.HIDDEN }).defaultValue = 'F'; log.debug({ title: 'Selector_number', details: selector_number }); form.addField({ id: 'custpage_selector_number', type: ui.FieldType.TEXT, label: 'Selector Number' }).updateDisplayType({ displayType: ui.FieldDisplayType.HIDDEN }).defaultValue = selector_number; form.addField({ id: 'custpage_selector_type', type: ui.FieldType.TEXT, label: 'Selector Type' }).updateDisplayType({ displayType: ui.FieldDisplayType.HIDDEN }).defaultValue = selector_type; if (!isNullorEmpty(ticket_id)) { form.addField({ id: 'custpage_ticket_id', type: ui.FieldType.TEXT, label: 'Ticket ID' }).updateDisplayType({ displayType: ui.FieldDisplayType.HIDDEN }).defaultValue = ticket_id; } else { form.addField({ id: 'custpage_ticket_id', type: ui.FieldType.TEXT, label: 'Ticket ID' }).updateDisplayType({ displayType: ui.FieldDisplayType.HIDDEN }); } form.addField({ id: 'custpage_selector_id', type: ui.FieldType.TEXT, label: 'Selector ID' }).updateDisplayType({ displayType: ui.FieldDisplayType.HIDDEN }).defaultValue = selector_id; form.addField({ id: 'custpage_selector_issue', type: ui.FieldType.TEXT, label: 'Barcode issue' }).updateDisplayType({ displayType: ui.FieldDisplayType.HIDDEN }).defaultValue = 'F'; form.addField({ id: 'custpage_customer_id', type: ui.FieldType.TEXT, label: 'Customer ID' }).updateDisplayType({ displayType: ui.FieldDisplayType.HIDDEN }).defaultValue = customer_id; form.addField({ id: 'custpage_customer_number', type: ui.FieldType.TEXT, label: 'Customer Number' }).updateDisplayType({ displayType: ui.FieldDisplayType.HIDDEN }).defaultValue = customer_number; form.addField({ id: 'custpage_zee_id', type: ui.FieldType.TEXT, label: 'Franchisee ID' }).updateDisplayType({ displayType: ui.FieldDisplayType.HIDDEN }).defaultValue = zee_id; form.addField({ id: 'custpage_ticket_status_value', type: ui.FieldType.TEXT, label: 'Status Value' }).updateDisplayType({ displayType: ui.FieldDisplayType.HIDDEN }).defaultValue = status_value; form.addField({ id: 'custpage_created_ticket', type: ui.FieldType.TEXT, label: 'Created Ticket' }).updateDisplayType({ displayType: ui.FieldDisplayType.HIDDEN }).defaultValue = 'F'; form.addField({ id: 'custpage_usage_report_array', type: ui.FieldType.TEXT, label: 'Usage Reports' }).updateDisplayType({ displayType: ui.FieldDisplayType.HIDDEN }).defaultValue = JSON.stringify(usage_report_array); form.addField({ id: 'custpage_param_email', type: ui.FieldType.TEXT, label: 'Email parameters' }).updateDisplayType({ displayType: ui.FieldDisplayType.HIDDEN }).defaultValue = JSON.stringify(params_email); form.addField({ id: 'custpage_ss_image', type: ui.FieldType.TEXT, label: 'Screenshot Image' }).updateDisplayType({ displayType: ui.FieldDisplayType.HIDDEN }).defaultValue = screenshot_file; form.addField({ id: 'custpage_customer_number_email_sent', type: ui.FieldType.TEXT, label: 'Customer Email Sent' }).updateDisplayType({ displayType: ui.FieldDisplayType.HIDDEN }).defaultValue = customer_number_email_sent; if (!isNullorEmpty(ticket_id)) { if (isTicketNotClosed(status_value)) { form.addSubmitButton({ label: 'Update Ticket' }); } // else { // form.addSubmitButton({ label: 'Reopen Ticket' }); // } } else { form.addSubmitButton({ label: 'Save Ticket' }); // form.addButton({ id: 'custpage_openandnew', label: 'Open & New Ticket', functionName: 'openAndNew()' }); // } // if (isTicketNotClosed(status_value)) { // form.addButton({ id: 'custpage_escalate', label: 'Escalate', functionName: 'onEscalate()' }); } // form.addButton({ id: 'custpage_cancel', label: 'Cancel', functionName: 'onCancel()' }); form.clientScriptFileId = 4813453;//SB=4796340 PROD=4813453 context.response.writePage(form); } else { log.debug({ title: "In else POST part", details: '' }); var created_ticket = context.request.parameters.custpage_created_ticket; log.debug({ title: "created_ticket", details: created_ticket }); var is_ss_changed = context.request.parameters.custpage_is_ss_changed; log.debug({ title: "is_ss_changed", details: is_ss_changed }); if (created_ticket == 'T') { var ticket_id = context.request.parameters.custpage_ticket_id; var selector_number = context.request.parameters.custpage_selector_number; var selector_type = context.request.parameters.custpage_selector_type; var open_new_ticket = context.request.parameters.custpage_open_new_ticket; if (open_new_ticket == 'T') { // If the ticket was just created, and the user clicked on 'Open & New Ticket', // The user is redirected to a new "Open Ticket" page. redirect.toSuitelet({ scriptId: 'customscript_sl_open_ticket_2', deploymentId: 'customdeploy_sl_open_ticket_2', parameters: params2 }); } else { custparam_params = { ticket_id: parseInt(ticket_id), selector_number: selector_number, selector_type: selector_type, } custparam_params = JSON.stringify(custparam_params); log.debug({ title: "custparams", details: custparam_params }); var params2 = { custparam_params: custparam_params }; // If the ticket was just created, the user is redirected to the "Edit Ticket" page redirect.toSuitelet({ scriptId: 'customscript_sl_open_ticket_2', deploymentId: 'customdeploy_sl_open_ticket_2', parameters: params2 }); } } else { var params_email = context.request.parameters.custpage_param_email; params_email = JSON.parse(params_email); var to = params_email.recipient; var email_subject = params_email.subject; var email_body = decodeURIComponent(params_email.body); var cc = null; var bcc = null var emailAttach = null; var attachments_credit_memo_ids = null; var attachments_usage_report_ids = null; var attachments_invoice_ids = null; var customer_id = context.request.parameters.custpage_customer_id; var open_new_ticket = context.request.parameters.custpage_open_new_ticket; if (!isNullorEmpty(params_email.cc)) { cc = params_email.cc; } if (!isNullorEmpty(params_email.bcc)) { bcc = params_email.bcc; } if (!isNullorEmpty(params_email.records)) { emailAttach = params_email.records; } var attachement_files = []; if (!isNullorEmpty(params_email.attachments_credit_memo_ids)) { attachments_credit_memo_ids = params_email.attachments_credit_memo_ids; attachments_credit_memo_ids.forEach(function(record_id) { render.transaction({ entityId: record_id, printMode: render.PrintMode.PDF, formId: number, inCustLocale: boolean }); }); } if (!isNullorEmpty(params_email.attachments_usage_report_ids)) { attachments_usage_report_ids = params_email.attachments_usage_report_ids; attachments_usage_report_ids.forEach(function(record_id) { attachement_files.push(file.load({ id: record_id })); }); } if (!isNullorEmpty(params_email.attachments_invoice_ids)) { attachments_invoice_ids = params_email.attachments_invoice_ids; attachments_invoice_ids.forEach(function(invoice_id) { render.transaction({ entityId: invoice_id, printMode: render.PrintMode.PDF, }) }); } // If the parameter is non null, it means that the "SEND EMAIL" button was clicked. if (!isNullorEmpty(attachement_files)) { try { email.send({ author: 112209, body: email_body, recipients: to, subject: email_subject, attachments: attachement_files, bcc: bcc, cc: cc, relatedRecords: { entityId: customer_id}, }); // 112209 is from MailPlus Team } catch (error) { if (error instanceof error.SuiteScriptError) { return error.name; } } } log.debug({ title: 'open_new_ticket', details: open_new_ticket }); if (open_new_ticket == 'T') { log.debug({ title: 'open ticket page', details: 'open ticket page' }) // If the ticket was just updated, and the user clicked on 'Updated & New Ticket', // The user is redirected to a new "Open Ticket" page. redirect.toSuitelet({ scriptId: 'customscript_sl_open_ticket_2', deploymentId: 'customdeploy_sl_open_ticket_2', }); } else { // If the ticket was updated, the user is redirected to the "View MP Tickets" page redirect.toSuitelet({ scriptId: 'customscript_sl_edit_ticket_2', deploymentId: 'customdeploy_sl_edit_ticket_2', }); } } } } function instructionsBox(ticket_id) { //Important Instructions box var inlineHtml = '<br></br>' inlineHtml += '<div></div>'; inlineHtml += '<div class="form-group container test_section">'; //inlineHtml += '<button type="button" class="btn btn-sm btn-info instruction_button" data-toggle="collapse" data-target="#demo">Click for Instructions</button>'; //inlineHtml += '<div id="demo" style="background-color: #cfeefc !important;border: 1px solid #417ed9;padding: 20px 30px 30px 30px;width:96%;position:absolute" class="collapse"><b><u>IMPORTANT INSTRUCTIONS:</u></b>'; inlineHtml += '<div style=\"background-color: #e3e8e5 !important;border: 2px solid #379E8F;padding: 20px 30px 30px 30px; text-align: left\"><b><u>Mandatory Fields:</u></b>'; inlineHtml += '<ul>'; inlineHtml += '<li><b><u>Ticket Details</u></b>: Total Enquiry Count must be at least 1 i.e. Chat/Email/Phone must have at least 1 incremented and Receiver Details should be filled in if blank</li>'; inlineHtml += '<li><b><u>Issues</u></b>: Owner and Toll Emails must have at least one selected</li>'; inlineHtml += '<li>If you have any issues, please contact Ankith</li>'; inlineHtml += '</ul></div></div><br/>'; return inlineHtml; } function externalBarcodeSource(selector_type, barcodempdl, barcodesource) { var disabled = 'disabled'; var inlineQty = ''; if (selector_type == 'barcode_number') { inlineQty += '<div class="form-group container barcode_section">'; inlineQty += '<div class="row">'; // MPLD field inlineQty += '<div class="col-xs-6 barcodempdl_div">'; inlineQty += '<div class="input-group">'; inlineQty += '<span class="input-group-addon" id="barcodempdl_text">EXTERNAL BARCODE</span>'; inlineQty += '<input id="barcodempdl" value="' + barcodempdl + '" class="form-control barcodempdl" ' + disabled + ' />'; inlineQty += '</div></div>'; // barcode source field inlineQty += '<div class="col-xs-6 barcodesource_div">'; inlineQty += '<div class="input-group">'; inlineQty += '<span class="input-group-addon" id="barcodesource_text">BARCODE SOURCE</span>'; inlineQty += '<input id="barcodesource" value="' + barcodesource + '" class="form-control barcodesource" ' + disabled + ' />'; inlineQty += '</div></div></div></div>'; } return inlineQty; } function tabsSection(customer_number, ticket_id, selector_number, selector_id, selector_type, status_value, customer_name, daytodayphone, daytodayemail, franchisee_name, zee_main_contact_name, zee_email, zee_main_contact_phone, zee_abn, date_stock_used, time_stock_used, final_delivery_text, selected_enquiry_status_id, attachments_hyperlink, owner_list, list_toll_issues, list_resolved_toll_issues, comment, date_created, creator_id, creator_name, status, customer_id, accountsphone, accountsemail, zee_id, list_enquiry_mediums, total_enquiry_count, chat_enquiry_count, phone_enquiry_count, email_enquiry_count, selected_label_id, maap_bank_account_number, maap_parent_bank_account_number, account_manager, list_toll_emails, customer_barcode_number, connote_number, receiveremail, receiverphone, receivername, receiverstate, receiverzip, receiversuburb, receiveraddr1, receiveraddr2, prod_stock_invoice, barcodempdl, barcodesource, list_mp_ticket_issues, list_resolved_mp_ticket_issues, list_invoice_issues, list_resolved_invoice_issues, selected_invoice_method_id, accounts_cc_email, mpex_po_number, customer_po_number, selected_invoice_cycle_id, terms, customer_terms, screenshot_file, browser, login_email_used, operating_system, phone_used, old_sender_name, old_sender_phone, phone_interaction_count, email_interaction_count, escalated_to_it) { var inlineQty = '<div style="margin-top: -10px"><br/>'; // BUTTONS if (!isNullorEmpty(ticket_id)) { if (isTicketNotClosed(status_value) && selector_type != "customer_issue") { inlineQty += '<button style="float: left; margin-left: 10px; margin-right: 5px; background-color: #FBEA51; color: #103D39; font-weight: 700; border-color: transparent; border-width: 2px; border-radius: 15px; height: 30px" type="button" id="updateticketbutton" onclick="">Update & New Ticket</button>'; inlineQty += '<button style="float: left; margin-left: 5x; margin-right: 5px; background-color: #FBEA51; color: #103D39; font-weight: 700; border-color: transparent; border-width: 2px; border-radius: 15px; height: 30px" type="button" id="updatecloseticketbutton" onclick="">Update & Close Ticket</button>'; } else if (!isTicketNotClosed(status_value)) { inlineQty += '<button style="float: left; margin-left: 10px; margin-right: 5px; background-color: #FBEA51; color: #103D39; font-weight: 700; border-color: transparent; border-width: 2px; border-radius: 15px; height: 30px" type="button" id="reopenticketbutton" onclick="">Reopen Ticket</button>'; } } else { //inlineQty += '<button style="float: left; margin-left: 10px; margin-right: 5px; background-color: #FBEA51; color: #103D39; font-weight: 700; border-color: transparent; border-width: 2px; border-radius: 15px; height: 30px" type="button" id="openticketbutton" onclick="">Save Ticket</button>'; inlineQty += '<button style="float: left; margin-left: 10px; margin-right: 5px; background-color: #FBEA51; color: #103D39; font-weight: 700; border-color: transparent; border-width: 2px; border-radius: 15px; height: 30px" type="button" id="opennewticketbutton" onclick="">Save & New Ticket</button>'; } if (isTicketNotClosed(status_value)) { if (!isNullorEmpty(ticket_id) && selector_type != "customer_issue") { inlineQty += '<button style="float: left; margin-left: 5px; margin-right: 5px; background-color: #f4524d; color: #fff; font-weight: 700; border-color: transparent; border-width: 2px; border-radius: 15px; height: 30px" type="button" id="closeticketbutton" onclick="">Close Ticket</button>'; inlineQty += '<button style="float: left; margin-left: 5px; margin-right: 5px; background-color: #f4524d; color: #fff; font-weight: 700; border-color: transparent; border-width: 2px; border-radius: 15px; height: 30px" type="button" id="closenewticketbutton" onclick="">Close & New Ticket</button>'; inlineQty += '<button style="float: left; margin-left: 5px; margin-right: 5px; background-color: #f4524d; color: #fff; font-weight: 700; border-color: transparent; border-width: 2px; border-radius: 15px; height: 30px" type="button" id="closelostbutton" onclick="">Close Ticket - Lost Item</button>'; if (userId == 409635 || userId == 696992 || userId == 766498) { inlineQty += '<button style="float: left; margin-left: 5px; margin-right: 5px; background-color: #FBEA51; color: #103D39; font-weight: 700; border-color: transparent; border-width: 2px; border-radius: 15px; height: 30px" type="button" id="closeunallocatedbutton" onclick="">Close Unallocated Ticket</button>'; } } else if (!isNullorEmpty(ticket_id) && !isNullorEmpty(escalated_to_it)) { inlineQty += '<button style="float: left; margin-left: 5px; margin-right: 5px; background-color: #f4524d; color: #fff; font-weight: 700; border-color: transparent; border-width: 2px; border-radius: 15px; height: 30px" type="button" id="closeresolvedbutton" onclick="">Close - Resolved Ticket</button>'; inlineQty += '<button style="float: left; margin-left: 5px; margin-right: 5px; background-color: #f4524d; color: #fff; font-weight: 700; border-color: transparent; border-width: 2px; border-radius: 15px; height: 30px" type="button" id="closeunresolvedbutton" onclick="">Close - Unresolved Ticket</button>'; } else { inlineQty += '<button style="float: left; margin-left: 5px; margin-right: 5px; background-color: #f4524d; color: #fff; font-weight: 700; border-color: transparent; border-width: 2px; border-radius: 15px; height: 30px" type="button" id="closeticketbutton" onclick="">Close Ticket</button>'; } } // ESCALATE AND CANCEL BUTTONS log.debug({ title: 'debugging', }); log.debug({ title: "selector_type", details: selector_type }); log.debug({ title: "isTicketNotClosed(status_value)", details: isTicketNotClosed(status_value) }); log.debug({ title: "!isNullorEmpty(ticket_id)", details: !isNullorEmpty(ticket_id) }); log.debug({ title: "userId", details: userId }); if (selector_type == "customer_issue" && isTicketNotClosed(status_value) && !isNullorEmpty(ticket_id) && isNullorEmpty(escalated_to_it)) { inlineQty += '<button style="float: left; margin-left: 5px; margin-right: 5px; background-color: #fc9003; color: #fff; font-weight: 700; border-color: transparent; border-width: 2px; border-radius: 15px; height: 30px" type="button" id="escalaterianne" onclick="">Escalate To IT</button>'; } else if (selector_type == "customer_issue" && isTicketNotClosed(status_value) && !isNullorEmpty(ticket_id) && !isNullorEmpty(escalated_to_it) && status_value != 10 && status_value != 17) { inlineQty += '<button style="float: left; margin-left: 5px; margin-right: 5px; background-color: #fc9003; color: #fff; font-weight: 700; border-color: transparent; border-width: 2px; border-radius: 15px; height: 30px" type="button" id="escalateankith" onclick="">Escalate To Ankith</button>'; } else if (selector_type == "customer_issue" && isTicketNotClosed(status_value) && !isNullorEmpty(ticket_id) && status_value == 10) { inlineQty += '<button style="float: left; margin-left: 5px; margin-right: 5px; background-color: #fc9003; color: #fff; font-weight: 700; border-color: transparent; border-width: 2px; border-radius: 15px; height: 30px" type="button" id="escalateunderdev" onclick="">Set Status to Under Development</button>'; } else if (selector_type == "customer_issue" && isTicketNotClosed(status_value) && !isNullorEmpty(ticket_id) && status_value == 17) { inlineQty += '<button style="float: left; margin-left: 5px; margin-right: 5px; background-color: #fc9003; color: #fff; font-weight: 700; border-color: transparent; border-width: 2px; border-radius: 15px; height: 30px" type="button" id="escalateremoveunderdev" onclick="">Remove Under Development Status</button>'; } else if (isTicketNotClosed(status_value) && !isNullorEmpty(ticket_id) && selector_type != "customer_issue") { inlineQty += '<button style="float: left; margin-left: 5px; margin-right: 5px; background-color: #379E8F; color: #fff; font-weight: 700; border-color: transparent; border-width: 2px; border-radius: 15px; height: 30px" type="button" id="escalatebutton" onclick="">' + escalateButton(status_value) + '</button>'; } if (!isNullorEmpty(ticket_id) && !isTicketNotClosed(status_value)) { inlineQty += '<button style="float: left; margin-left: 10px; margin-right: 5px; background-color: #FBEA51; color: #103D39; font-weight: 700; border-color: transparent; border-width: 2px; border-radius: 15px; height: 30px" type="button" id="cancelbutton" onclick="">Cancel</button>'; } else { inlineQty += '<button style="float: left; margin-left: 5px; margin-right: 5px; background-color: #FBEA51; color: #103D39; font-weight: 700; border-color: transparent; border-width: 2px; border-radius: 15px; height: 30px" type="button" id="cancelbutton" onclick="">Cancel</button>'; } // Title if (!isNullorEmpty(ticket_id)) { inlineQty += '<h1 style="display: inline-block; font-size: 25px; margin-top: 20px; font-weight: 700; color: #103D39; text-align: center; width: 100%">Edit Ticket - MPSD' + ticket_id + '</h1>' } else { inlineQty += '<h1 style="display: inline-block; font-size: 25px; font-weight: 700; color: #103D39; text-align: center; width: 100%">Open New Ticket</h1>' } inlineQty += instructionsBox(); // Tabs headers inlineQty += '<style>.nav > li.active > a, .nav > li.active > a:focus, .nav > li.active > a:hover { background-color: #379E8F; color: #fff }'; inlineQty += '.nav > li > a, .nav > li > a:focus, .nav > li > a:hover { margin-left: 5px; margin-right: 5px; border: 2px solid #379E8F; color: #379E8F; }'; inlineQty += '</style>'; // Ticket details header inlineQty += '<div class="form-group container tickets_details_header_section" style="margin-top: 10px">'; inlineQty += '<div class="row">'; inlineQty += '<div class="col-xs-12" >'; inlineQty += '<span">'; inlineQty += '<ul class="nav nav-pills nav-justified" style="margin:0%; ">'; inlineQty += '<li role="presentation" class="active"><a data-toggle="tab" href="#ticketdetails"><b>TICKET DETAILS</b></a></li>'; inlineQty += '<li role="presentation" class=""><a data-toggle="tab" href="#issues"><b>ISSUES</b></a></li>'; if (!isNullorEmpty(ticket_id)) { inlineQty += '<li role="presentation" class=""><a data-toggle="tab" href="#sendemail"><b>SEND EMAIL</b></a></li>'; } else { inlineQty += '<li role="presentation" class=""><a data-toggle="tab" href="#contactdetails"><b>CONTACT DETAILS</b></a></li>'; } if (!isNullorEmpty(ticket_id)) { inlineQty += '<li role="presentation" class=""><a data-toggle="tab" href="#prevtickets"><b>PREVIOUS TICKETS</b></a></li>'; inlineQty += '<li role="presentation" class=""><a data-toggle="tab" href="#prevemails"><b>PREVIOUS EMAILS</b></a></li>'; } //style="background-color: #379E8F" inlineQty += '</ul>'; inlineQty += '</span>'; inlineQty += '</div></div></div>'; // Tabs content inlineQty += '<div class="tab-content">'; // TICKET DETAILS TAB inlineQty += '<div role="tabpanel" class="tab-pane active" id="ticketdetails">'; inlineQty += customerNumberSection(customer_number, ticket_id, selector_type, escalated_to_it, creator_id); inlineQty += selectorSection(ticket_id, selector_number, selector_id, selector_type, status_value); if (!isNullorEmpty(ticket_id)) { inlineQty += ticketSection(dateISOToNetsuite(date_created), creator_id, creator_name, status, connote_number); inlineQty += externalBarcodeSource(selector_type, barcodempdl, barcodesource) } if (isNullorEmpty(ticket_id) || (!isNullorEmpty(ticket_id) && !isNullorEmpty(customer_id)) || !isNullorEmpty(customer_number)) { inlineQty += customerSection(customer_name); inlineQty += daytodayContactSection(daytodayphone, daytodayemail, status_value, selector_type); inlineQty += accountsContactSection(accountsphone, accountsemail, status_value, selector_type); } else if (isNullorEmpty(customer_number) && creator_id == 112209 && !isNullorEmpty(escalated_to_it) && selector_type == "customer_issue" && !isNullorEmpty(ticket_id)) { inlineQty += customerSection(customer_name); inlineQty += daytodayContactSection(daytodayphone, daytodayemail, status_value, selector_type); inlineQty += accountsContactSection(accountsphone, accountsemail, status_value, selector_type); } if(isNullorEmpty(ticket_id) || (!isNullorEmpty(ticket_id) && (selector_type == 'invoice_section'))) { inlineQty += maapBankAccountSection(maap_bank_account_number, maap_parent_bank_account_number, selector_type); } if (isNullorEmpty(ticket_id) || (!isNullorEmpty(ticket_id) && !isNullorEmpty(zee_id)) || !isNullorEmpty(customer_number)) { inlineQty += franchiseeMainContactSection(franchisee_name, zee_main_contact_name, zee_email, zee_main_contact_phone, zee_abn); } inlineQty += mpexStockUsedSection(selector_type, date_stock_used, time_stock_used); inlineQty += finalDeliveryEnquirySection(status_value, selector_type, final_delivery_text, selected_enquiry_status_id, prod_stock_invoice); inlineQty += attachmentsSection(attachments_hyperlink, status_value); if (isNullorEmpty(ticket_id) || (!isNullorEmpty(ticket_id) && (selector_type == 'invoice_number'))) { inlineQty += otherInvoiceFieldsSection(selected_invoice_method_id, accounts_cc_email, mpex_po_number, customer_po_number, selected_invoice_cycle_id, terms, customer_terms, status_value, selector_type); // inlineQty += enquiryMediumSection(list_enquiry_mediums, selected_enquiry_status_id, selector_type); // inlineQty += enquiryCountSection( total_enquiry_count, chat_enquiry_count, phone_enquiry_count, email_enquiry_count, selector_type); inlineQty += openInvoicesSection(ticket_id, selector_type); if (!isNullorEmpty(ticket_id)) { inlineQty += creditMemoSection(selector_type); inlineQty += usageReportSection(selector_type); } } inlineQty += enquiryMediumSection(list_enquiry_mediums, selected_enquiry_status_id, selector_type); inlineQty += enquiryCountSection( total_enquiry_count, chat_enquiry_count, phone_enquiry_count, email_enquiry_count, selector_type, phone_interaction_count, email_interaction_count); if(!isNullorEmpty(ticket_id)) { inlineQty += receiverEmailPhone(selector_type, receiveremail, receiverphone, receivername, receiverstate, receiverzip, receiversuburb, receiveraddr1, receiveraddr2); } //TICKET LABEL DROPDOWN //inlineQty += labelSection(selected_label_id, selector_type, status_value); inlineQty += '</div>'; // ISSUES TAB inlineQty += '<div role="tabpanel" class="tab-pane" id="issues">'; inlineQty += issuesHeader(); inlineQty += customerIssuesSection(ticket_id, selector_type, selector_number, screenshot_file, browser, login_email_used, operating_system, phone_used, old_sender_name, old_sender_phone, status_value); if(selector_type == "barcode_number" || selector_type == "invoice_number"){ inlineQty += reminderSection(status_value); } inlineQty += ownerSection(ticket_id, owner_list, status_value); inlineQty += tollIssuesSection(list_toll_issues, list_resolved_toll_issues, status_value, selector_type); inlineQty += mpTicketIssuesSection(list_mp_ticket_issues, list_resolved_mp_ticket_issues, status_value, selector_type); inlineQty += invoiceIssuesSection(list_invoice_issues, list_resolved_invoice_issues, status_value, selector_type); inlineQty += usernoteSection(selector_type, status_value); inlineQty += commentSection(comment, selector_type, status_value); inlineQty += '</div>'; // CONTACT / EMAILS if (!isNullorEmpty(ticket_id)) { inlineQty += '<div role="tabpanel" class="tab-pane" id="sendemail">'; inlineQty += mpexContactSection(); inlineQty += sendEmailSection(ticket_id, status_value, account_manager, list_toll_emails); //inlineQty += closeReopenSubmitTicketButton(ticket_id, status_value); inlineQty += '</div>'; } else { inlineQty += '<div role="tabpanel" class="tab-pane" id="contactdetails">'; inlineQty += mpexContactSection(); //inlineQty += closeReopenSubmitTicketButton(ticket_id, status_value); inlineQty += '</div>'; } // PREV TICKETS + EMAILS TAB if (!isNullorEmpty(ticket_id)) { // PREV TICKETS TAB inlineQty += '<div role="tabpanel" class="tab-pane" id="prevtickets">'; inlineQty += dataTablePreview(); //inlineQty += closeReopenSubmitTicketButton(ticket_id, status_value); inlineQty += '</div>'; inlineQty += '<div role="tabpanel" class="tab-pane" id="prevemails">'; log.debug({ title: 'before prev email - cust id', details: customer_id }); if(!isNullorEmpty(customer_id)){ inlineQty += previousEmailsSection(customer_id); } //inlineQty += closeReopenSubmitTicketButton(ticket_id, status_value); inlineQty += '</div>'; } inlineQty += '</div></div>'; return inlineQty; } /** * The "Customer number" input field. If there is a Ticket ID, then we are on the Edit Ticket page and * this field is pre-filled. * @param {*} customer_number */ function customerNumberSection(customer_number, ticket_id, selector_type, escalated_to_it, creator_id){ if(isNullorEmpty(customer_number)){ customer_number = ''; } // var disable = isNullorEmpty(ticket_id) ? '': 'disabled'; // Ticket details header var inlineQty = '<div class="form-group container tickets_details_header_section">'; inlineQty += '<div class="row">'; inlineQty += '<div class="col-xs-12 heading2" >'; inlineQty += '<h4><span style="background-color: #379E8F" class="label label-default col-xs-12">TICKET DETAILS</span></h4>'; inlineQty += '</div></div></div>'; // Customer number section inlineQty += '<div class="form-group container customer_number_section">'; inlineQty += '<div class="row">'; //Customer number field inlineQty += '<div class="col-xs-12 customer_number">'; inlineQty += '<div class="input-group">'; inlineQty += '<span class="input-group-addon" id="customer_number_text">CUSTOMER NUMBER</span>'; if(customer_number == '' && isNullorEmpty(ticket_id)){ inlineQty += '<input id="customer_number_value" value=" '+ customer_number +' " class="form-control customer_number">'; } else if (customer_number == '' && creator_id == 112209 && !isNullorEmpty(escalated_to_it) && selector_type == "customer_issue" && !isNullorEmpty(ticket_id)) { inlineQty += '<input id="customer_number_value" value=" '+ customer_number +' " class="form-control customer_number">'; } else{ inlineQty += '<input id="customer_number_value" value=" '+ customer_number +' " class="form-control customer_number" disabled>'; } inlineQty += '</div></div></div></div>'; //Datatable for all tickets asscoiated to current customer number inlineQty += '<div class="row">'; inlineQty += '<div class="form-group container customer_number_tickets">'; inlineQty += '<style> table {font-size: 12px;text-align: center;border: none;} {font-size: 14px;} table th{text-align: center;} .dataTables_wrapper{width:78%; margin-bottom:40px; margin-left: auto; margin-right: auto; margin-top: auto;} </style>'; inlineQty += '<table cellpadding="15" id="customer_number_tickets_preview" class="table table-responsive table-striped customer tablesorter" cellspacing="0" style="width: 100%;">'; inlineQty += '<thead style="color: white;background-color: #379E8F;">'; inlineQty += '<tr class="text-center">'; inlineQty += '</tr>'; inlineQty += '</thead></table>'; inlineQty += '</div></div>'; return inlineQty; } /** * The "Barcode number" OR "Invoice Number" input field. * If there is a TICKET ID, we are in the "Edit Ticket", so we display the Ticket ID field and the selector field is disabled. * @param {Number} ticket_id * @param {String} selector_number * @param {Number} selector_id * @param {String} selector_type * @param {Number} status_value * @return {String} inlineQty */ function selectorSection(ticket_id, selector_number, selector_id, selector_type, status_value) { if (isNullorEmpty(selector_number)) { selector_number = ''; } var inlineQty = '<div class="form-group container selector_section">'; inlineQty += '<div class="row">'; if (!isNullorEmpty(ticket_id)) { // Ticket ID field inlineQty += '<div class="col-xs-6 ticket_id">'; inlineQty += '<div class="input-group">'; inlineQty += '<span class="input-group-addon" id="ticket_id_text">TICKET ID</span>'; inlineQty += '<input id="ticket_id" value="MPSD' + ticket_id + '" class="form-control ticket_id" disabled />'; inlineQty += '</div></div>'; // Selector Number field inlineQty += '<div class="col-xs-6 selector_number">'; inlineQty += '<div class="input-group">'; switch (selector_type) { case 'barcode_number': inlineQty += '<span class="input-group-addon" id="selector_text">BARCODE NUMBER</span>'; break; case 'invoice_number': inlineQty += '<span class="input-group-addon" id="selector_text">INVOICE NUMBER</span>'; break; } inlineQty += '<input id="selector_value" value="' + selector_number + '" class="form-control selector_value" disabled>'; if (selector_type == 'invoice_number') { // Open Invoice record inlineQty += '<div class="input-group-btn">'; inlineQty += '<button id="open_inv" type="button" class="btn btn-default link_inv" data-inv-id="' + selector_id + '" data-toggle="tooltip" data-placement="top" title="Open Invoice">'; inlineQty += '<span class="glyphicon glyphicon-link"></span>'; inlineQty += '</button>'; inlineQty += '</div>'; // Attach Invoice to email if (isTicketNotClosed(status_value)) { inlineQty += '<div class="input-group-btn"><button style="background-color: #379E8F" id="add_inv" type="button" class="btn btn-success add_inv" data-inv-id="' + selector_id + '" data-toggle="tooltip" data-placement="right" title="Attach to email">'; inlineQty += '<span class="glyphicon glyphicon-plus"></span>'; inlineQty += '</button></div>'; } } inlineQty += '</div></div></div></div>'; } else { inlineQty += '<div class="col-xs-12 selector_number">'; inlineQty += '<div class="input-group">'; //Input group addon text switch (selector_type) { case 'barcode_number': inlineQty += '<span class="input-group-addon" id="selector_text">BARCODE NUMBER</span>'; break; case 'invoice_number': inlineQty += '<span class="input-group-addon" id="selector_text">INVOICE NUMBER</span>'; break; case 'customer_issue': inlineQty += '<span class="input-group-addon" id="selector_text">CUSTOMER ISSUE</span>'; break; } inlineQty += '<div class="input-group-btn">'; inlineQty += '<button tabindex="-1" data-toggle="dropdown" class="btn btn-default dropdown-toggle" type="button">'; inlineQty += '<span class="caret"></span>'; inlineQty += '<span class="sr-only">Toggle Dropdown</span>'; inlineQty += '</button>'; inlineQty += '<ul class="dropdown-menu hide" style="list-style:none;margin: 2px 0 0;">'; inlineQty += '<li><a href="#">BARCODE NUMBER</a></li>'; inlineQty += '<li><a href="#">INVOICE NUMBER</a></li>'; //inlineQty += '<li><a href="#">CUSTOMER APP</a></li>'; inlineQty += '<li><a href="#">CUSTOMER PORTAL</a></li>'; inlineQty += '<li><a href="#">UPDATE LABEL</a></li>'; inlineQty += '</ul>'; inlineQty += '</div>'; //Input text switch (selector_type) { case 'barcode_number': inlineQty += '<input id="selector_value" class="form-control selector_value" placeholder="MPEN123456">'; break; case 'invoice_number': inlineQty += '<input id="selector_value" class="form-control selector_value" placeholder="INV123456">'; break; case 'customer_app': inlineQty += '<input id="selector_value" class="form-control selector_value" placeholder="Customer App" disabled value="Customer App">'; break; case 'customer_portal': inlineQty += '<input id="selector_value" class="form-control selector_value" placeholder="Customer Portal" disabled value="Customer Portal">'; break; case 'update_label': inlineQty += '<input id="selector_value" class="form-control selector_value" placeholder="Update Label" disabled value="Update Label">'; break; } inlineQty += '</div></div></div></div>'; } return inlineQty; } /** * The informations regarding the ticket being edited. * @param {String} date_created * @param {Number} creator_id * @param {String} creator_name * @param {String} status * @return {String} inlineQty */ function ticketSection(date_created, creator_id, creator_name, status, connote_number) { if (isNullorEmpty(date_created)) { date_created = ''; } if (isNullorEmpty(creator_name)) { creator_name = ''; } if (isNullorEmpty(status)) { status = ''; } var inlineQty = '<div class="form-group container created_status_section">'; inlineQty += '<div class="row">'; // Date created field inlineQty += '<div class="col-xs-6 date_created">'; inlineQty += '<div class="input-group">'; inlineQty += '<span class="input-group-addon" id="date_created_text">DATE CREATED</span>'; inlineQty += '<input id="date_created" value="' + date_created + '" class="form-control date_created" disabled />'; inlineQty += '</div></div>'; // Creator field inlineQty += '<div class="col-xs-6 creator">'; inlineQty += '<div class="input-group">'; inlineQty += '<span class="input-group-addon" id="creator_text">CREATOR</span>'; inlineQty += '<input id="creator" value="' + creator_name + '" data-creator-id="' + creator_id + '" class="form-control creator" disabled />'; inlineQty += '</div></div></div></div>'; // Status Section inlineQty += '<div class="form-group container status_section">'; inlineQty += '<div class="row">'; // Status field inlineQty += '<div class="col-xs-6 status">'; inlineQty += '<div class="input-group">'; inlineQty += '<span class="input-group-addon" id="status_text">STATUS</span>'; inlineQty += '<input id="status" value="' + status + '" class="form-control status" disabled />'; inlineQty += '</div></div>'; // Customer Status field inlineQty += '<div class="col-xs-6 status">'; inlineQty += '<div class="input-group">'; inlineQty += '<span class="input-group-addon" id="status_text">CONNOTE NUMBER</span>'; inlineQty += '<input id="status" value="' + connote_number + '" class="form-control status" disabled />'; inlineQty += '</div></div></div></div>'; return inlineQty; } /** * The Customer name field. * The customer name field should be automatically filled based on the Selector number value. * @param {String} customer_name * @return {String} inlineQty */ function customerSection(customer_name) { if (isNullorEmpty(customer_name)) { customer_name = ''; } // Customer Section var inlineQty = '<div class="form-group container customer_section">'; inlineQty += '<div class="row">'; // Customer name field inlineQty += '<div class="col-xs-12 customer_name">'; inlineQty += '<div class="input-group">'; inlineQty += '<span class="input-group-addon" id="customer_name_text">CUSTOMER NAME</span>'; inlineQty += '<input id="customer_name" value="' + customer_name + '" class="form-control customer_name" disabled>'; inlineQty += '</div></div></div></div>'; return inlineQty; } /** * The day to day phone and email fields of the customer. * These fields should be automatically filled based on the Selector number value. * @param {String} daytodayphone * @param {String} daytodayemail * @param {Number} status_value * @param {String} selector_type * @return {String} inlineQty */ function daytodayContactSection(daytodayphone, daytodayemail, status_value, selector_type) { if (isNullorEmpty(daytodayphone)) { daytodayphone = ''; } if (isNullorEmpty(daytodayemail)) { daytodayemail = ''; } var disabled = 'disabled'; if ((isFinanceRole(userRole)) && isTicketNotClosed(status_value) && selector_type == 'invoice_number') { disabled = ''; } var inlineQty = '<div class="form-group container daytodaycontact_section">'; inlineQty += '<div class="row">'; // Day to day email field inlineQty += '<div class="col-xs-6 daytodayemail_div">'; inlineQty += '<div class="input-group">'; inlineQty += '<span class="input-group-addon" id="daytodayemail_text">DAY-TO-DAY EMAIL</span>'; inlineQty += '<input id="daytodayemail" type="email" value="' + daytodayemail + '" class="form-control daytodayemail" ' + disabled + ' />'; inlineQty += '<div class="input-group-btn">'; inlineQty += '<button type="button" style="background-color: #379E8F" class="btn btn-success add_as_recipient" data-email="' + daytodayemail + '" data-contact-id="" data-firstname="" data-toggle="tooltip" data-placement="right" title="Add as recipient">'; inlineQty += '<span class="glyphicon glyphicon-envelope"></span>'; inlineQty += '</button>'; inlineQty += '</div>'; inlineQty += '</div></div>'; // Day to day phone field inlineQty += '<div class="col-xs-6 daytodayphone_div">'; inlineQty += '<div class="input-group">'; inlineQty += '<span class="input-group-addon" id="daytodayphone_text">DAY-TO-DAY PHONE</span>'; inlineQty += '<input id="daytodayphone" type="tel" value="' + daytodayphone + '" class="form-control daytodayphone" ' + disabled + ' />'; inlineQty += '<div class="input-group-btn"><button type="button" style="background-color: #379E8F" class="btn btn-success" id="call_daytoday_phone"><span class="glyphicon glyphicon-earphone"></span></button></div>'; inlineQty += '</div></div></div></div>'; return inlineQty; } /** * The receiver phone and email fields. * These fields should be automatically filled based on the Selector number value. * @param {String} daytodayphone * @param {String} daytodayemail * @param {Number} status_value * @param {String} selector_type * @return {String} inlineQty */ function receiverEmailPhone(selector_type, receiveremail, receiverphone, receivername, receiverstate, receiverzip, receiversuburb, receiveraddr1, receiveraddr2) { var disabled = 'disabled'; if (isNullorEmpty(receiveremail) && isNullorEmpty(receiveraddr1) && isNullorEmpty(receiveraddr2) && isNullorEmpty(receivername) && isNullorEmpty(receiverphone) && isNullorEmpty(receiverstate) && isNullorEmpty(receiverzip) && isNullorEmpty(receiversuburb)) { disabled = ''; } var inlineQty = ''; if (selector_type == 'barcode_number') { // Receiver details header var inlineQty = '<div class="form-group container tickets_details_header_section">'; inlineQty += '<div class="row">'; inlineQty += '<div class="col-xs-12 heading2" >'; inlineQty += '<h4><span style="background-color: #379E8F" class="label label-default col-xs-12">RECEIVER DETAILS</span></h4>'; inlineQty += '</div></div></div>'; //First Row inlineQty += '<div class="form-group container receivercontact_section">'; inlineQty += '<div class="row">'; // name field inlineQty += '<div class="col-xs-4 receivername_div">'; inlineQty += '<div class="input-group">'; inlineQty += '<span class="input-group-addon" id="receivername_text">NAME</span>'; inlineQty += '<input id="receivername" value="' + receivername + '" class="form-control receivername" ' + disabled + ' />'; inlineQty += '</div></div>'; // Day to day phone field inlineQty += '<div class="col-xs-4 receiverphone_div">'; inlineQty += '<div class="input-group">'; inlineQty += '<span class="input-group-addon" id="receiverphone_text">PHONE</span>'; inlineQty += '<input id="receiverphone" type="tel" value="' + receiverphone + '" class="form-control receiverphone" ' + disabled + ' />'; inlineQty += '<div class="input-group-btn"><button type="button" style="background-color: #379E8F" class="btn btn-success" id="call_receiver_phone"><span class="glyphicon glyphicon-earphone"></span></button></div>'; inlineQty += '</div></div>'; // Day to day email field inlineQty += '<div class="col-xs-4 receiveremail_div">'; inlineQty += '<div class="input-group">'; inlineQty += '<span class="input-group-addon" id="receiveremail_text">EMAIL</span>'; inlineQty += '<input id="receiveremail" type="email" value="' + receiveremail + '" class="form-control receiveremail" ' + disabled + ' />'; inlineQty += '<div class="input-group-btn">'; inlineQty += '<button type="button" style="background-color: #379E8F" class="btn btn-success add_as_recipient" data-email="' + receiveremail + '" data-contact-id="" data-firstname="" data-toggle="tooltip" data-placement="right" title="Add as recipient">'; inlineQty += '<span class="glyphicon glyphicon-envelope"></span>'; inlineQty += '</button>'; inlineQty += '</div>'; inlineQty += '</div></div>'; inlineQty += '</div></div>'; //2nd Row inlineQty += '<div class="form-group container receivercontact2_section">'; inlineQty += '<div class="row">'; // address1 field inlineQty += '<div class="col-xs-6 receiveraddr1_div">'; inlineQty += '<div class="input-group">'; inlineQty += '<span class="input-group-addon" id="receiveraddr1_text">ADDRESS1</span>'; inlineQty += '<input id="receiveraddr1" value="' + receiveraddr1 + '" class="form-control receiveraddr1" ' + disabled + ' />'; inlineQty += '</div></div>'; // address2 field inlineQty += '<div class="col-xs-6 receiveraddr2_div">'; inlineQty += '<div class="input-group">'; inlineQty += '<span class="input-group-addon" id="receiveraddr2_text">ADDRESS2</span>'; inlineQty += '<input id="receiveraddr2" value="' + receiveraddr2 + '" class="form-control receiveraddr2" ' + disabled + ' />'; inlineQty += '</div></div>'; inlineQty += '</div></div>'; //3rd Row inlineQty += '<div class="form-group container receivercontact3_section">'; inlineQty += '<div class="row">'; // suburb field inlineQty += '<div class="col-xs-4 receiversuburb_div">'; inlineQty += '<div class="input-group">'; inlineQty += '<span class="input-group-addon" id="receiversuburb_text">SUBURB</span>'; inlineQty += '<input id="receiversuburb" value="' + receiversuburb + '" class="form-control receiversuburb" ' + disabled + ' />'; inlineQty += '</div></div>'; // postcode field inlineQty += '<div class="col-xs-4 receiverzip_div">'; inlineQty += '<div class="input-group">'; inlineQty += '<span class="input-group-addon" id="receiverzip_text">POSTCODE</span>'; inlineQty += '<input id="receiverzip" value="' + receiverzip + '" class="form-control receiverzip" ' + disabled + ' />'; inlineQty += '</div></div>'; // state field inlineQty += '<div class="col-xs-4 receiverstate_div">'; inlineQty += '<div class="input-group">'; inlineQty += '<span class="input-group-addon" id="receiverstate_text">STATE</span>'; inlineQty += '<input id="receiverstate" value="' + receiverstate + '" class="form-control receiverstate" ' + disabled + ' />'; inlineQty += '</div></div>'; inlineQty += '</div></div>'; } return inlineQty; } /** * The accounts phone and email fields of the customer. * These fields should be automatically filled based on the Invoice number value. * @param {String} accountsphone * @param {String} accountsemail * @param {Number} status_value * @param {String} selector_type * @return {String} inlineQty */ function accountsContactSection(accountsphone, accountsemail, status_value, selector_type) { if (isNullorEmpty(accountsphone)) { accountsphone = ''; } if (isNullorEmpty(accountsemail)) { accountsemail = ''; } if (selector_type == 'invoice_number') { var inlineQty = '<div class="form-group container accountscontact_section">'; if (isFinanceRole(userRole) && isTicketNotClosed(status_value)) { var disabled = ''; } else { var disabled = 'disabled'; } } else { var inlineQty = '<div class="form-group container accountscontact_section hide">'; var disabled = 'disabled'; } inlineQty += '<div class="row">'; // Accounts email field inlineQty += '<div class="col-xs-6 accountsemail_div">'; inlineQty += '<div class="input-group">'; inlineQty += '<span class="input-group-addon" id="accountsemail_text">ACCOUNTS EMAIL</span>'; inlineQty += '<input id="accountsemail" type="email" value="' + accountsemail + '" class="form-control accountsemail" ' + disabled + ' />'; inlineQty += '<div class="input-group-btn">'; inlineQty += '<button type="button" style="background-color: #379E8F" class="btn btn-success add_as_recipient" data-email="' + accountsemail + '" data-contact-id="" data-firstname="" data-toggle="tooltip" data-placement="right" title="Add as recipient">'; inlineQty += '<span class="glyphicon glyphicon-envelope"></span>'; inlineQty += '</button>'; inlineQty += '</div>'; inlineQty += '</div></div>'; // Accounts phone field inlineQty += '<div class="col-xs-6 accountsphone_div">'; inlineQty += '<div class="input-group">'; inlineQty += '<span class="input-group-addon" id="accountsphone_text">ACCOUNTS PHONE</span>'; inlineQty += '<input id="accountsphone" type="tel" value="' + accountsphone + '" class="form-control accountsphone" ' + disabled + ' />'; inlineQty += '<div class="input-group-btn"><button type="button" style="background-color: #379E8F" class="btn btn-success" id="call_accounts_phone"><span class="glyphicon glyphicon-earphone"></span></button></div>'; inlineQty += '</div></div></div></div>'; return inlineQty; } /** * * @param {Number} maap_bank_account_number * @param {Number} maap_parent_bank_account_number * @param {String} selector_type * @returns {String} inlineQty */ function maapBankAccountSection(maap_bank_account_number, maap_parent_bank_account_number, selector_type) { switch (selector_type) { case 'barcode_number': var inlineQty = '<div class="form-group container accounts_number_section hide">'; break; case 'invoice_number': var inlineQty = '<div class="form-group container accounts_number_section">'; break; } inlineQty += '<div class="row">'; // MAAP Bank Account # field inlineQty += '<div class="col-xs-6 account_number_div">'; inlineQty += '<div class="input-group">'; inlineQty += '<span class="input-group-addon" id="account_number_text">MAAP BANK ACCOUNT #</span>'; inlineQty += '<input id="account_number" type="number" value="' + maap_bank_account_number + '" class="form-control account_number" disabled />'; inlineQty += '</div></div>'; // MAAP Parent Bank Account # field inlineQty += '<div class="col-xs-6 parent_account_number_div">'; inlineQty += '<div class="input-group">'; inlineQty += '<span class="input-group-addon" id="parent_account_number_text">MAAP PARENT BANK ACCOUNT #</span>'; inlineQty += '<input id="parent_account_number" type="number" value="' + maap_parent_bank_account_number + '" class="form-control parent_account_number" disabled />'; inlineQty += '</div></div></div></div>'; return inlineQty; } /** * The Franchisee name, and its main contact name and phone number fields. * These fields should be automatically filled based on the Selector number value. * @param {String} franchisee_name * @param {String} zee_main_contact_name * @param {String} zee_email * @param {String} zee_main_contact_phone * @param {String} zee_abn * @return {String} inlineQty */ function franchiseeMainContactSection(franchisee_name, zee_main_contact_name, zee_email, zee_main_contact_phone, zee_abn) { if (isNullorEmpty(franchisee_name)) { franchisee_name = ''; } if (isNullorEmpty(zee_main_contact_name)) { zee_main_contact_name = ''; } if (isNullorEmpty(zee_email)) { zee_email = ''; } if (isNullorEmpty(zee_main_contact_phone)) { zee_main_contact_phone = ''; } if (isNullorEmpty(zee_abn)) { zee_abn = ''; } var inlineQty = '<div class="form-group container zee_main_contact_section">'; inlineQty += '<div class="row">'; // Franchisee name field inlineQty += '<div class="col-xs-6 franchisee_name">'; inlineQty += '<div class="input-group">'; inlineQty += '<span class="input-group-addon" id="franchisee_name_text">FRANCHISEE NAME</span>'; inlineQty += '<input id="franchisee_name" value="' + franchisee_name + '" class="form-control franchisee_name" disabled>'; inlineQty += '</div></div>'; // Franchisee main contact name field inlineQty += '<div class="col-xs-6 zee_main_contact_name">'; inlineQty += '<div class="input-group">'; inlineQty += '<span class="input-group-addon" id="zee_main_contact_name_text">MAIN CONTACT</span>'; inlineQty += '<input id="zee_main_contact_name" value="' + zee_main_contact_name + '" class="form-control zee_main_contact_name" disabled>'; inlineQty += '</div></div></div></div>'; // Franchisee contact details inlineQty += '<div class="form-group container zee_main_contact_section">'; inlineQty += '<div class="row">'; // Franchisee email field inlineQty += '<div class="col-xs-12 zee_email">'; inlineQty += '<div class="input-group">'; inlineQty += '<span class="input-group-addon" id="zee_email_text">FRANCHISEE EMAIL</span>'; inlineQty += '<input id="zee_email" type="email" value="' + zee_email + '" class="form-control accountsemail" disabled />'; inlineQty += '<div class="input-group-btn">'; var zee_contact_id = '0'; inlineQty += '<button type="button" style="background-color: #379E8F" class="btn btn-success add_as_recipient" data-email="' + zee_email + '" data-contact-id="' + zee_contact_id + '" data-firstname="' + franchisee_name + '" data-toggle="tooltip" data-placement="right" title="Add as recipient">'; inlineQty += '<span class="glyphicon glyphicon-envelope"></span>'; inlineQty += '</button>'; inlineQty += '</div>'; inlineQty += '</div></div></div></div>'; // Franchisee phone and ABN details inlineQty += '<div class="form-group container zee_main_contact_section">'; inlineQty += '<div class="row">'; // Franchisee main contact phone field inlineQty += '<div class="col-xs-6 zee_main_contact_phone">' inlineQty += '<div class="input-group">' inlineQty += '<span class="input-group-addon" id="zee_main_contact_phone_text">FRANCHISEE PHONE</span>'; inlineQty += '<input id="zee_main_contact_phone" type="tel" value="' + zee_main_contact_phone + '" class="form-control zee_main_contact_phone" disabled />'; inlineQty += '<div class="input-group-btn"><button style="background-color: #379E8F" type="button" class="btn btn-success" id="call_zee_main_contact_phone"><span class="glyphicon glyphicon-earphone"></span></button>'; inlineQty += '</div>'; inlineQty += '</div></div>'; // Franchisee ABN number inlineQty += '<div class="col-xs-6 zee_abn">' inlineQty += '<div class="input-group">' inlineQty += '<span class="input-group-addon" id="zee_abn_text">FRANCHISEE ABN</span>' inlineQty += '<input id="zee_abn" class="form-control zee_abn" value="' + zee_abn + '" disabled>' inlineQty += '</div></div></div></div>'; return inlineQty; } /** * The MPEX Date and Time Stock used fields. * Visible only for the barcode records. * @param {String} selector_type * @param {String} date_stock_used * @param {String} time_stock_used * @return {String} inlineQty */ function mpexStockUsedSection(selector_type, date_stock_used, time_stock_used) { if (isNullorEmpty(date_stock_used)) { date_stock_used = '' } if (isNullorEmpty(time_stock_used)) { time_stock_used = '' } var hide_class = (selector_type == 'barcode_number') ? '' : 'hide'; // MPEX Stock Used Section var inlineQty = '<div class="form-group container mpex_stock_used_section ' + hide_class + '">'; inlineQty += '<div class="row">'; // Date Stock Used inlineQty += ' <div class="col-xs-6 date_stock_used">'; inlineQty += '<div class="input-group">'; inlineQty += '<span class="input-group-addon" id="date_stock_used_text">DATE STOCK USED</span>'; inlineQty += '<input id="date_stock_used" class="form-control date_stock_used" value="' + date_stock_used + '" disabled>'; inlineQty += '</div></div>'; // Time Stock Used inlineQty += '<div class="col-xs-6 time_stock_used">'; inlineQty += '<div class="input-group">'; inlineQty += '<span class="input-group-addon" id="time_stock_used_text">TIME STOCK USED</span>'; inlineQty += '<input id="time_stock_used" class="form-control time_stock_used" value="' + time_stock_used + '" disabled>'; inlineQty += '</div></div></div></div>'; return inlineQty; } /** * The MPEX Final Delivery field is visible only for the barcode records. * The Enquiry Status field is not disabled only for the ticket that have not yet been opened. * @param {Number} status_value * @param {String} selector_type * @param {String} final_delivery_text * @param {Number} selected_enquiry_status_id * @return {String} inlineQty */ function finalDeliveryEnquirySection(status_value, selector_type, final_delivery_text, selected_enquiry_status_id, prod_stock_invoice) { if (isNullorEmpty(final_delivery_text)) { final_delivery_text = '' } if (isNullorEmpty(selected_enquiry_status_id)) { selected_enquiry_status_id = '' } var barcode_hide_class = (selector_type == 'barcode_number') ? '' : 'hide'; var nb_col_enquiry_section = (selector_type == 'barcode_number') ? '6' : '12'; var enquiry_disabled = (isTicketNotClosed(status_value)) ? '' : 'disabled'; // Final Delivery + Enquiry Status Section var inlineQty = '<div class="form-group container final_delivery_enquiry_status_section">'; inlineQty += '<div class="row">'; // Final Delivery inlineQty += '<div class="col-xs-6 final_delivery ' + barcode_hide_class + '">'; inlineQty += '<div class="input-group">'; inlineQty += '<span class="input-group-addon" id="final_delivery_text">FINAL DELIVERY</span>'; inlineQty += '<input id="final_delivery" class="form-control final_delivery" value="' + final_delivery_text + '" disabled>'; inlineQty += '</div></div>'; // Final Delivery inlineQty += '<div class="col-xs-6 invoice ' + barcode_hide_class + '">'; inlineQty += '<div class="input-group">'; inlineQty += '<span class="input-group-addon" id="invoice_text">INVOICE</span>'; inlineQty += '<input id="invoice" class="form-control invoice" value="' + prod_stock_invoice + '" disabled>'; inlineQty += '</div></div>'; inlineQty += '</div></div>'; return inlineQty; } /** * Ticket Label Section for if label on mpex was Printed or Handwritten * @param {Number} selected_label_id * @return {String} inlineQty */ function labelSection(selected_label_id, selector_type, status_value){ if (isNullorEmpty(selected_label_id)){ selected_label_id = ''; } var barcodeHideClass = (selector_type == 'barcode_number') ? '' : 'hide'; var labeldisabled = (isTicketNotClosed(status_value)) ? '' : 'disabled'; var inlineQty = '<div class="form-group container label_section '+ barcodeHideClass + '">'; inlineQty += '<div class="row">'; inlineQty += '<div class="col-xs-6 label_div">'; inlineQty += '<div class="input-group">'; inlineQty += '<span class="input-group-addon" id="label_text">TICKET LABEL</span>'; inlineQty += '<select id="label_status" class="form-control label_status" '+ labeldisabled+ '>'; inlineQty += '<option></option>'; var labelColumns = new Array(); labelColumns[0] = search.createColumn({ name: 'name' }); labelColumns[1] = search.createColumn({ name: 'internalId' }); var labelResultSet = search.create({ type: 'customlist_mp_ticket_label', columns: labelColumns, }); labelResultSet.run().each(function (labelResult) { var labelName = labelResult.getValue('name'); var labelId = labelResult.getValue('internalId'); if(selected_label_id == labelId) { inlineQty += '<option value="' + labelId + '"selected>' + labelName + '</option>'; }else{ inlineQty += '<option value="' + labelId + '">' + labelName + '</option>'; } return inlineQty; }); inlineQty += '</select>'; inlineQty += '</div></div></div></div>'; return inlineQty; } /** * Section containing enquiry medium type and the enquiry status of the ticket enquiry * @param list_enquiry_mediums {String}atus and * @param total_enquiry_count {Number} * @param selector_type {String} * @param status_value {Number} * @returns {string} */ function enquiryMediumSection(list_enquiry_mediums, selected_enquiry_status_id, selector_type){ //Search for enquiry mediums var hasEnquiryMediums = (!isNullorEmpty(list_enquiry_mediums)); var enquiryMediumColumns = new Array(); enquiryMediumColumns[0] = search.createColumn({ name: 'name' }); enquiryMediumColumns[1] = search.createColumn({ name: 'internalId' }); var enquiryMediumResultSet = search.create({ type: 'customlist_ticket_enquiry_mediums', columns: enquiryMediumColumns, }); //Ticket Enquiry Header // var inlineQty = '<div class="form-group container ticket_enquiry_header_section">'; // inlineQty += '<div class="row">'; // inlineQty += '<div class="col-xs-12 heading2">'; // inlineQty += '<h4><span style="background-color: #379E8F" class="label label-default col-xs-12">TICKET ENQUIRY DETAILS</span></h4>'; // inlineQty += '</div></div></div>'; //Enquiry Medium HTML var inlineQty = '<div class="form-group container enquiry_medium_section">'; inlineQty += '<div class="row">'; // inlineQty += '<div class="col-xs-6 enquiry_medium_div">'; // inlineQty += '<div class="input-group">'; // inlineQty += '<span class="input-group-addon" id="enquiry_medium_text">ENQUIRY MEDIUM</span>'; // inlineQty += '<select multiple id="enquiry_medium_status" class="form-control enquiry_medium_status" size="'+ enquiryMediumResultSet.length + '" disabled>'; // enquiryMediumResultSet.run().each(function (enquiryMediumResult) { // var enquiryMediumName = enquiryMediumResult.getValue('name'); // var enquiryMediumId = enquiryMediumResult.getValue('internalId'); // var selected = false; // if(hasEnquiryMediums){ // selected = (list_enquiry_mediums.indexOf(enquiryMediumId) !== -1); // } // if(selected) { // inlineQty += '<option value="' + enquiryMediumId + '"selected>' + enquiryMediumName + '</option>'; // }else{ // inlineQty += '<option value="' + enquiryMediumId + '">' + enquiryMediumName + '</option>'; // } // return true; // }); // inlineQty += '</select>'; // inlineQty += '</div></div>'; // Enquiry Status var enquiry_status_columns = new Array(); enquiry_status_columns[0] = search.createColumn({ name: 'name' }); enquiry_status_columns[1] = search.createColumn({ name: 'internalId' }); var enquiryStatusResultSet = search.create({ type: 'customlist_mp_ticket_enquiry', columns: enquiry_status_columns, }); inlineQty += '<div class="col-xs-6 enquiry_status_div">'; inlineQty += '<div class="input-group">'; inlineQty += '<span class="input-group-addon" id="enquiry_status_text">ENQUIRY STATUS</span>'; inlineQty += '<select id="enquiry_status" class="form-control enquiry_status">'; inlineQty += '<option></option>'; enquiryStatusResultSet.run().each(function (enquiryStatusResult) { var enquiry_status_name = enquiryStatusResult.getValue('name'); var enquiry_status_id = enquiryStatusResult.getValue('internalId'); if (enquiry_status_id == selected_enquiry_status_id) { inlineQty += '<option value="' + enquiry_status_id + '" selected>' + enquiry_status_name + '</option>'; } else { inlineQty += '<option value="' + enquiry_status_id + '">' + enquiry_status_name + '</option>'; } return true; }); inlineQty += '</select>'; inlineQty += '</div></div></div></div>'; return inlineQty; } /** * Section containing the total enquiry count and its breakdwn counts of chat, phone and email * @param total_enquiry_count * @param chat_enquiry_count * @param phone_enquiry_count * @param email_enquiry_count * @param selector_type * @returns {string} */ function enquiryCountSection( total_enquiry_count, chat_enquiry_count, phone_enquiry_count, email_enquiry_count, selector_type, phone_interaction_count, email_interaction_count){ if (isNullorEmpty(total_enquiry_count)) { total_enquiry_count = 0;} if (isNullorEmpty(chat_enquiry_count)) { chat_enquiry_count = 0;} if (isNullorEmpty(phone_enquiry_count)) { phone_enquiry_count = 0;} if (isNullorEmpty(email_enquiry_count)) { email_enquiry_count = 0;} if (isNullorEmpty(phone_interaction_count)) { phone_interaction_count = 0;} if (isNullorEmpty(email_interaction_count)) { email_interaction_count = 0;} //Total Enquiry Count HTML // var inlineQty = '<div class="form-group container enquiry_count_section">'; // inlineQty += '<div class="row">'; // inlineQty += '<div class="col-xs-12 total_enquiry_count_div">'; // inlineQty += '<div class="input-group">'; // inlineQty += '<span class="input-group-addon" id="total_enquiry_count_text">ENQUIRY COUNT</span>'; // inlineQty += '<input id="total_enquiry_count" class="form-control enquiry_count" value="' + total_enquiry_count + '" disabled />'; // inlineQty += '</div></div></div></div>'; //Enquiries by chat count var inlineQty = '<div class="form-group container enquiry_count_breakdown_section">'; inlineQty += '<div class="row">'; inlineQty += '<div class="col-xs-4 enquiry_count_by_chat">'; inlineQty += '<div class="input-group">'; inlineQty += '<span class="input-group-addon" id="enquiry_count_by_chat_text"> WEBSITE ENQUIRY </span>'; inlineQty += '<input id="enquiry_count_by_chat" value="' + chat_enquiry_count + '" class="form-control enquiry_count_by_chat" disabled>'; inlineQty += '<div class="input-group-btn">'; inlineQty += '<button type="button" style="background-color: #379E8F" class="btn btn-success increment_enquiry_count_by_chat" data-firstname="" data-toggle="tooltip" data-placement="right" title="Increment Chat Enquiry Count">'; inlineQty += '<span class="glyphicon glyphicon-plus"></span>'; inlineQty += '</button>'; inlineQty += '<button type="button" class="btn btn-danger decrement_enquiry_count_by_chat" data-firstname="" data-toggle="tooltip" data-placement="right" title="Decrement Chat Enquiry Count">'; inlineQty += '<span class="glyphicon glyphicon-minus"></span>'; inlineQty += '</button>'; inlineQty += '</div></div></div>'; inlineQty += '<div class="col-xs-4 enquiry_count_by_phone">'; inlineQty += '<div class="input-group">'; inlineQty += '<span class="input-group-addon" id="enquiry_count_by_phone_text"> PHONE ENQUIRY </span>'; inlineQty += '<input id="enquiry_count_by_phone" value="' + phone_enquiry_count + '" class="form-control enquiry_count_by_phone" disabled>'; inlineQty += '<div class="input-group-btn">'; inlineQty += '<button type="button" style="background-color: #379E8F" class="btn btn-success increment_enquiry_count_by_phone" data-firstname="" data-toggle="tooltip" data-placement="right" title="Increment Phone Enquiry Count">'; inlineQty += '<span class="glyphicon glyphicon-plus"></span>'; inlineQty += '</button>'; inlineQty += '<button type="button" class="btn btn-danger decrement_enquiry_count_by_phone" data-firstname="" data-toggle="tooltip" data-placement="right" title="Decrement Phone Enquiry Count">'; inlineQty += '<span class="glyphicon glyphicon-minus"></span>'; inlineQty += '</button>'; inlineQty += '</div></div></div>'; inlineQty += '<div class="col-xs-4 enquiry_count_by_email">'; inlineQty += '<div class="input-group">'; inlineQty += '<span class="input-group-addon" id="enquiry_count_by_email_text"> EMAIL ENQUIRY </span>'; inlineQty += '<input id="enquiry_count_by_email" value="' + email_enquiry_count + '" class="form-control enquiry_count_by_email" disabled>'; inlineQty += '<div class="input-group-btn">'; inlineQty += '<button type="button" style="background-color: #379E8F" class="btn btn-success increment_enquiry_count_by_email" data-firstname="" data-toggle="tooltip" data-placement="right" title="Increment Email Enquiry Count">'; inlineQty += '<span class="glyphicon glyphicon-plus"></span>'; inlineQty += '</button>'; inlineQty += '<button type="button" class="btn btn-danger decrement_enquiry_count_by_email" data-firstname="" data-toggle="tooltip" data-placement="right" title="Decrement Email Enquiry Count">'; inlineQty += '<span class="glyphicon glyphicon-minus"></span>'; inlineQty += '</button>'; inlineQty += '</div></div></div></div></div>'; if (selector_type == "customer_issue") { inlineQty += '<div class="form-group container interaction_count_breakdown_section">'; inlineQty += '<div class="row">'; inlineQty += '<div class="col-xs-6 interaction_count_by_phone">'; inlineQty += '<div class="input-group">'; inlineQty += '<span class="input-group-addon" id="interaction_count_by_phone_text"> PHONE INTERACTION </span>'; inlineQty += '<input id="interaction_count_by_phone" value="' + phone_interaction_count + '" class="form-control interaction_count_by_phone" disabled>'; inlineQty += '<div class="input-group-btn">'; inlineQty += '<button type="button" style="background-color: #379E8F" class="btn btn-success increment_interaction_count_by_phone" data-firstname="" data-toggle="tooltip" data-placement="right" title="Increment Phone Interaction Count">'; inlineQty += '<span class="glyphicon glyphicon-plus"></span>'; inlineQty += '</button>'; inlineQty += '<button type="button" class="btn btn-danger decrement_interaction_count_by_phone" data-firstname="" data-toggle="tooltip" data-placement="right" title="Decrement Phone interaction Count">'; inlineQty += '<span class="glyphicon glyphicon-minus"></span>'; inlineQty += '</button>'; inlineQty += '</div></div></div>'; inlineQty += '<div class="col-xs-6 interaction_count_by_email">'; inlineQty += '<div class="input-group">'; inlineQty += '<span class="input-group-addon" id="interaction_count_by_email_text"> EMAIL INTERACTION </span>'; inlineQty += '<input id="interaction_count_by_email" value="' + email_interaction_count + '" class="form-control interaction_count_by_email" disabled>'; inlineQty += '<div class="input-group-btn">'; inlineQty += '<button type="button" style="background-color: #379E8F" class="btn btn-success increment_interaction_count_by_email" data-firstname="" data-toggle="tooltip" data-placement="right" title="Increment Email Interaction Count">'; inlineQty += '<span class="glyphicon glyphicon-plus"></span>'; inlineQty += '</button>'; inlineQty += '<button type="button" class="btn btn-danger decrement_interaction_count_by_email" data-firstname="" data-toggle="tooltip" data-placement="right" title="Decrement Email Interaction Count">'; inlineQty += '<span class="glyphicon glyphicon-minus"></span>'; inlineQty += '</button>'; inlineQty += '</div></div></div></div></div>'; } return inlineQty; } /** * These fields should be displayed only for an Invoice ticket, and be edited only by the finance team. * - Invoice Method field * - Accounts cc email field * - MPEX PO # field * - Customer PO # field * - MPEX Invoicing Cycle field * @param {Number} selected_invoice_method_id * @param {String} accounts_cc_email * @param {String} mpex_po_number * @param {String} customer_po_number * @param {Number} selected_invoice_cycle_id * @param {Number} terms * @param {String} customer_terms * @param {Number} status_value * @param {String} selector_type * @return {String} inlineQty */ function otherInvoiceFieldsSection(selected_invoice_method_id, accounts_cc_email, mpex_po_number, customer_po_number, selected_invoice_cycle_id, terms, customer_terms, status_value, selector_type) { if (isNullorEmpty(accounts_cc_email)) { accounts_cc_email = '' } if (isNullorEmpty(mpex_po_number)) { mpex_po_number = '' } if (isNullorEmpty(customer_po_number)) { customer_po_number = '' } if (isNullorEmpty(customer_terms)) { customer_terms = '' } var invoice_method_columns = new Array(); invoice_method_columns[0] = search.createColumn({ name: 'name' }); invoice_method_columns[1] = search.createColumn({ name: 'internalId' }); var invoiceMethodResultSet = search.create({ type: 'customlist_invoice_method', columns: invoice_method_columns, }); switch (selector_type) { case 'barcode_number': var inlineQty = '<div class="form-group container invoice_method_accounts_cc_email_section hide">'; var disabled = 'disabled'; break; case 'invoice_number': var inlineQty = '<div class="form-group container invoice_method_accounts_cc_email_section">'; if (isFinanceRole(userRole) && isTicketNotClosed(status_value)) { var disabled = ''; } else { var disabled = 'disabled'; } break; } inlineQty += '<div class="row">'; // Invoice Method field inlineQty += '<div class="col-xs-6 invoice_method_div">'; inlineQty += '<div class="input-group">'; inlineQty += '<span class="input-group-addon" id="invoice_method_text">INVOICE METHOD</span>'; inlineQty += '<select id="invoice_method" class="form-control" ' + disabled + '>'; inlineQty += '<option></option>'; invoiceMethodResultSet.run().each(function(invoiceMethodResult) { var invoice_method_name = invoiceMethodResult.getValue('name'); var invoice_method_id = invoiceMethodResult.getValue('internalId'); if (invoice_method_id == selected_invoice_method_id) { inlineQty += '<option value="' + invoice_method_id + '" selected>' + invoice_method_name + '</option>'; } else { inlineQty += '<option value="' + invoice_method_id + '">' + invoice_method_name + '</option>'; } return true; }); inlineQty += '</select>'; inlineQty += '</div></div>'; // Accounts cc email field --> inlineQty += '<div class="col-xs-6 accounts_cc_email_div">'; inlineQty += '<div class="input-group">'; inlineQty += '<span class="input-group-addon" id="accounts_cc_email_text">ACCOUNTS CC EMAIL</span>'; inlineQty += '<input id="accounts_cc_email" type="email" value="' + accounts_cc_email + '" class="form-control accounts_cc_email" ' + disabled + '/>'; inlineQty += '<div class="input-group-btn">'; inlineQty += '<button type="button" style="background-color: #379E8F" class="btn btn-success add_as_recipient" data-email="' + accounts_cc_email + '" data-contact-id="" data-firstname="" data-toggle="tooltip" data-placement="right" title="Add as recipient">'; inlineQty += '<span class="glyphicon glyphicon-envelope"></span>'; inlineQty += '</button>'; inlineQty += '</div>'; inlineQty += '</div></div></div></div>'; switch (selector_type) { case 'barcode_number': inlineQty += '<div class="form-group container mpex_customer_po_number_section hide">'; break; case 'invoice_number': inlineQty += '<div class="form-group container mpex_customer_po_number_section">'; break; } inlineQty += '<div class="row">'; // MPEX PO # inlineQty += '<div class="col-xs-6 mpex_po_number_div">'; inlineQty += '<div class="input-group">'; inlineQty += '<span class="input-group-addon" id="mpex_po_number_text">MPEX PO #</span>'; inlineQty += '<input id="mpex_po_number" value="' + mpex_po_number + '" class="form-control mpex_po_number" ' + disabled + '/>'; inlineQty += '</div></div>'; // Customer PO # inlineQty += '<div class="col-xs-6 customer_po_number_div">'; inlineQty += '<div class="input-group">'; inlineQty += '<span class="input-group-addon" id="customer_po_number_text">CUSTOMER PO #</span>'; inlineQty += '<input id="customer_po_number" value="' + customer_po_number + '" class="form-control customer_po_number" ' + disabled + '/>'; inlineQty += '</div></div></div></div>'; // Terms fields switch (selector_type) { case 'barcode_number': inlineQty += '<div class="form-group container terms_section hide">'; break; case 'invoice_number': inlineQty += '<div class="form-group container terms_section">'; break; } inlineQty += '<div class="row">'; // Terms inlineQty += '<div class="col-xs-6 terms_div">'; inlineQty += '<div class="input-group">'; inlineQty += '<span class="input-group-addon" id="terms_text">TERMS</span>'; // Find the text related to the terms value. var terms_options = [{ "value": "", "text": "" }, { "value": "5", "text": "1% 10 Net 30" }, { "value": "6", "text": "2% 10 Net 30" }, { "value": "4", "text": "Due on receipt" }, { "value": "1", "text": "Net 15 Days" }, { "value": "2", "text": "Net 30 Days" }, { "value": "8", "text": "Net 45 Days" }, { "value": "3", "text": "Net 60 Days" }, { "value": "7", "text": "Net 7 Days" }, { "value": "9", "text": "Net 90 Days" }]; var terms_option = findObjectByKey(terms_options, "value", terms); var terms_text = isNullorEmpty(terms_option) ? '' : terms_option.text; inlineQty += '<input id="terms" class="form-control terms" value="' + terms_text + '" disabled/>'; inlineQty += '</div></div>'; // Customer's terms inlineQty += '<div class="col-xs-6 customers_terms_div">'; inlineQty += '<div class="input-group">'; inlineQty += '<span class="input-group-addon" id="customers_terms_text">' + "CUSTOMER'S TERMS</span>"; inlineQty += '<input id="customers_terms" class="form-control customers_terms" value="' + customer_terms + '" ' + disabled + '/>'; inlineQty += '</div></div></div></div>'; // MPEX Invoicing Cycle var invoice_cycle_columns = new Array(); invoice_cycle_columns[0] = search.createColumn({ name: 'name' }); invoice_cycle_columns[1] = search.createColumn({ name: 'internalId' }); var invoiceCycleResultSet = search.create({ type: 'customlist_invoicing_cyle', columns: invoice_cycle_columns, }) switch (selector_type) { case 'barcode_number': inlineQty += '<div class="form-group container mpex_invoicing_cycle_section hide">'; break; case 'invoice_number': inlineQty += '<div class="form-group container mpex_invoicing_cycle_section">'; break; } inlineQty += '<div class="row">'; inlineQty += '<div class="col-xs-12 mpex_invoicing_cycle_div">'; inlineQty += '<div class="input-group">'; inlineQty += '<span class="input-group-addon" id="mpex_invoicing_cycle_text">MPEX INVOICING CYCLE</span>'; inlineQty += '<select id="mpex_invoicing_cycle" class="form-control mpex_invoicing_cycle" ' + disabled + '>'; inlineQty += '<option></option>'; invoiceCycleResultSet.run().each(function (invoiceCycleResult) { var invoice_cycle_name = invoiceCycleResult.getValue('name'); var invoice_cycle_id = invoiceCycleResult.getValue('internalId'); if (invoice_cycle_id == selected_invoice_cycle_id) { inlineQty += '<option value="' + invoice_cycle_id + '" selected>' + invoice_cycle_name + '</option>'; } else { inlineQty += '<option value="' + invoice_cycle_id + '">' + invoice_cycle_name + '</option>'; } return true; }); inlineQty += '</select>'; inlineQty += '</div></div></div></div>'; return inlineQty; } /** * The Attachments field (an editable hyperlink) * @param {String} attachments_hyperlink * @param {Number} status_value * @returns {String} inlineQty */ function attachmentsSection(attachments_hyperlink, status_value) { if (isNullorEmpty(attachments_hyperlink)) { attachments_hyperlink = '' } var disabled = (isTicketNotClosed(status_value)) ? '' : 'disabled'; var inlineQty = '<div class="form-group container attachments_section">'; inlineQty += '<div class="row">'; inlineQty += '<div class="col-xs-12 attachments_div">'; inlineQty += '<div class="input-group">'; inlineQty += '<span class="input-group-addon" id="attachments_text">ATTACHMENTS</span>' inlineQty += '<input id="attachments" class="form-control attachments" type="url" value="' + attachments_hyperlink + '" ' + disabled + '/>'; inlineQty += '</div></div></div></div>'; return inlineQty; } /** * The customer contact details section. * Possibility for the user to add / edit the contacts. * @return {String} inlineQty */ function mpexContactSection() { // Contact details header var inlineQty = '<div class="form-group container mpex_contact_section">'; inlineQty += '<div class="row">'; inlineQty += '<div class="col-xs-12 heading2">'; inlineQty += '<h4><span style="background-color: #379E8F" class="label label-default col-xs-12">CONTACT DETAILS</span></h4>'; inlineQty += '</div>'; inlineQty += '</div></div>'; // Contact table inlineQty += '<div class="form-group container contacts_section" style="font-size: small;">'; inlineQty += '<div class="row">'; inlineQty += '<div class="col-xs-12 contacts_div">'; // Since the table is not displayed correctly when added through suitelet, // It is added with jQuery in the pageInit() function in the client script 'mp_cl_open_ticket.js'. inlineQty += '</div>'; inlineQty += '</div>'; inlineQty += '</div>'; // Add/edit contacts button inlineQty += '<div class="form-group container reviewcontacts_section">'; inlineQty += '<div class="row">'; inlineQty += '<div class="col-xs-4 col-xs-offset-4 reviewcontacts">'; inlineQty += '<input type="button" style="background-color: #379E8F; border-color: #379E8F; font-weight: 700" value="ADD/EDIT CONTACTS" class="form-control btn btn-primary" id="reviewcontacts" />'; inlineQty += '</div></div></div>'; return inlineQty; }; /** * A Datatable displaying the open invoices of the customer * @param {Number} ticket_id * @param {String} selector_type * @return {String} inlineQty */ function openInvoicesSection(ticket_id, selector_type) { if (isNullorEmpty(ticket_id)) { ticket_id = '' } var hide_class_section = (isNullorEmpty(ticket_id) || selector_type != 'invoice_number') ? 'hide' : ''; // Open invoices header var inlineQty = '<div class="form-group container open_invoices open_invoices_header ' + hide_class_section + '">'; inlineQty += '<div class="row">'; inlineQty += '<div class="col-xs-12 heading2">'; inlineQty += '<h4><span style="background-color: #379E8F" class="label label-default col-xs-12">OPEN INVOICES</span></h4>'; inlineQty += '</div></div></div>'; // Open invoices dropdown field inlineQty += '<div class="form-group container open_invoices invoices_dropdown ' + hide_class_section + '">'; inlineQty += '<div class="row">'; inlineQty += '<div class="col-xs-12 invoices_dropdown_div">'; inlineQty += '<div class="input-group">'; inlineQty += '<span class="input-group-addon" id="invoices_dropdown_text">INVOICE STATUS</span>'; inlineQty += '<select id="invoices_dropdown" class="form-control">'; inlineQty += '<option value="open" selected>Open</option>'; inlineQty += '<option value="paidInFull">Paid In Full (last 3 months)</option>'; inlineQty += '</select>'; inlineQty += '</div></div></div></div>'; // Open Invoices Datatable //inlineQty += '<div class="form-group container open_invoices open_invoices_datatable>'; //inlineQty += '</div>'; inlineQty += '<div class="form-group open_invoices open_invoices_table ' + hide_class_section + '">'; inlineQty += dataTable(); // inlineQty += '<div class="row">'; // inlineQty += '<div class="col-xs-18" id="open_invoice_dt_div">'; // // It is inserted as inline html in the script mp_cl_open_ticket // inlineQty += '</div></div></div>'; inlineQty += '</div>' return inlineQty; } function dataTable() { var inlineQty = '<style>table#invoices-preview {font-size: 12px;text-align: center;border: none;}.dataTables_wrapper {font-size: 14px;}table#invoices-preview th{text-align: center;} .bolded{font-weight: bold;}</style>'; inlineQty += '<table id="invoices-preview" class="table table-responsive table-striped customer tablesorter" style="width: 100%; table-layout: fixed">'; inlineQty += '<thead style="color: white;background-color: #379E8F;">'; inlineQty += '<tr class="text-center">'; inlineQty += '</tr>'; inlineQty += '</thead>'; inlineQty += '<tbody id="result_invoices"></tbody>'; inlineQty += '</table>'; return inlineQty; } /** * The Credit Memo Section. * Displays a table of the credit memos linked to the invoice. * Possibility to attach the credit memo PDF to the email. * @param {String} selector_type * @return {String} inlineQty */ function creditMemoSection(selector_type) { var inlineQty = ''; if (selector_type == 'invoice_number') { // Credit Memo Header inlineQty += '<div class="form-group container credit_memo credit_memo_header">'; inlineQty += '<div class="row">'; inlineQty += '<div class="col-xs-12 heading2">'; inlineQty += '<h4><span style="background-color: #379E8F" class="label label-default col-xs-12">CREDIT MEMO</span></h4>'; inlineQty += '</div></div></div>'; // Credit Memo table inlineQty += '<div class="form-group container credit_memo credit_memo_section" style="font-size: small;">'; inlineQty += '<div class="row">'; inlineQty += '<div class="col-xs-12 credit_memo_div">'; // Since the table is not displayed correctly when added through suitelet, // It is added with jQuery in the pageInit() function in the client script 'mp_cl_open_ticket.js'. inlineQty += '</div></div></div>'; } return inlineQty; } function usageReportSection(selector_type) { var inlineQty = ''; if (selector_type == 'invoice_number') { // Usage Report Header inlineQty += '<div class="form-group container usage_report usage_report_header">'; inlineQty += '<div class="row">'; inlineQty += '<div class="col-xs-12 heading2">'; inlineQty += '<h4><span style="background-color: #379E8F" class="label label-default col-xs-12">USAGE REPORT</span></h4>'; inlineQty += '</div></div></div>'; // Usage Report table inlineQty += '<div class="form-group container usage_report usage_report_section" style="font-size: small;">'; inlineQty += '<div class="row">'; inlineQty += '<div class="col-xs-12 usage_report_div">'; // Since the table is not displayed correctly when added through suitelet, // It is added with jQuery in the pageInit() function in the client script 'mp_cl_open_ticket.js'. inlineQty += '</div></div></div>'; } return inlineQty; } /** * The "Send Email" section. * Possibility for the user to send an email to the customer, based on selected templates. * @param {Number} ticket_id * @param {Number} status_value * @param {Object} account_manager * @returns {String} inlineQty */ function sendEmailSection(ticket_id, status_value, account_manager, list_toll_emails) { var has_toll_emails = (!isNullorEmpty(list_toll_emails)); if (isNullorEmpty(ticket_id) || !isTicketNotClosed(status_value)) { // The section is hidden here rather than in the openTicket function, // because we use the section to send an acknoledgement email when a ticket is opened. var inlineQty = '<div id="send_email_container" class="send_email hide">'; } else { var inlineQty = '<div id="send_email_container" class="send_email">'; } // inlineQty += '<div class="form-group container send_email header_section">'; // // Send email header // inlineQty += '<div class="row">'; // inlineQty += '<div class="col-xs-12 heading2">'; // inlineQty += '<h4><span style="background-color: #379E8F" class="label label-default col-xs-12">SEND EMAILS</span></h4>'; // inlineQty += '</div></div></div>'; inlineQty += '<br></br>' // Row addressees inlineQty += '<div class="form-group container send_email adressees_section">'; inlineQty += '<div class="row">'; inlineQty += '<div class="col-xs-12 to_section">'; inlineQty += '<div class="input-group">'; inlineQty += '<span class="input-group-addon">TO<span class="mandatory">*</span></span>'; inlineQty += '<input id="send_to" class="form-control" data-contact-id="" data-firstname=""/>'; inlineQty += '</div></div></div></div>'; // Toll addresses var toll_emails_columns = new Array(); toll_emails_columns[0] = search.createColumn({ name: 'name' }); toll_emails_columns[1] = search.createColumn({ name: 'internalId' }); var tollEmailsResultSet = search.create({ type: 'customlist_toll_emails', columns: toll_emails_columns, }) inlineQty += '<div class="form-group container send_email toll_adressees_section">'; inlineQty += '<div class="row">'; inlineQty += '<div class="col-xs-12 toll_section">'; inlineQty += '<div class="input-group">'; inlineQty += '<span class="input-group-addon">TOLL EMAILS</span>'; inlineQty += '<select multiple id="send_toll" class="form-control" size="' + tollEmailsResultSet.length + '"/>'; tollEmailsResultSet.run().each(function (tollEmailsResultSet){ var tollEmailName = tollEmailsResultSet.getValue('name'); var tollEmailId = tollEmailsResultSet.getValue('internalId'); var selected = false; if(has_toll_emails) { selected = (list_toll_emails.indexOf(tollEmailId) !== -1); } if (selected) { inlineQty += '<option value="' + tollEmailId + '" selected>' + tollEmailName + '</option>'; } else { inlineQty += '<option value="' + tollEmailId + '">' + tollEmailName + '</option>'; } return true; }); inlineQty += '</select>'; inlineQty += '</div></div></div></div>'; // Row ccs addresses inlineQty += '<div class="form-group container send_email cc_adressees_section">'; inlineQty += '<div class="row">'; inlineQty += '<div class="col-xs-6 cc_section">'; inlineQty += '<div class="input-group">'; inlineQty += '<span class="input-group-addon">CC</span>'; inlineQty += '<input id="send_cc" class="form-control"/>'; inlineQty += '</div></div>'; inlineQty += '<div class="col-xs-6 bcc_section">'; inlineQty += '<div class="input-group">'; inlineQty += '<span class="input-group-addon">BCC</span>'; inlineQty += '<input id="send_bcc" class="form-control"/>'; inlineQty += '</div></div></div></div>'; // Row account manager if (isNullorEmpty(account_manager.name)) { account_manager.name = '' } if (isNullorEmpty(account_manager.email)) { account_manager.email = '' } if (!isNullorEmpty(account_manager.email.email)) { inlineQty += '<div class="form-group container send_email acc_manager_section">'; inlineQty += '<div class="row">'; inlineQty += '<div class="col-xs-10 acc_manager_name_section">'; inlineQty += '<div class="input-group">'; inlineQty += '<span class="input-group-addon">ACCOUNT MANAGER</span>'; inlineQty += '<input id="acc_manager" class="form-control" data-email="' + account_manager.email.email + '" value="' + account_manager.name + ' - ' + account_manager.email.email + '" disabled/>'; inlineQty += '</div></div>'; inlineQty += '<div class="col-xs-2 acc_manager_button_section">'; inlineQty += '<button id="acc_manager_button" style="background-color: #379E8F; border-color: #379E8F" type="button" class="btn btn-success btn-block">ADD TO CC</button>'; inlineQty += '</div></div></div>'; } // Row Template inlineQty += '<div class="form-group container send_email template_section">'; inlineQty += '<div class="row">'; inlineQty += '<div class="col-xs-12 template_section">'; inlineQty += '<div class="input-group">'; inlineQty += '<span class="input-group-addon">TEMPLATE<span class="mandatory">*</span></span>'; inlineQty += '<select id="template" class="form-control">'; inlineQty += '<option></option>'; // Load the template options var templatesSearch = search.load({ id: 'customsearch_cctemplate_mp_ticket', type: 'customrecord_camp_comm_template' }); var templatesSearchResults = templatesSearch.run(); templatesSearchResults.each(function(templatesSearchResult) { // var tempId = templatesSearchResult.getValue('internalid'); var tempId = templatesSearchResult["id"]; var tempName = templatesSearchResult.getValue('name'); inlineQty += '<option value="' + tempId + '">' + tempName + '</option>'; return true; }); inlineQty += '</select>'; inlineQty += '</div></div></div></div>'; // Row Subject inlineQty += '<div class="form-group container send_email subject_section">'; inlineQty += '<div class="row">'; inlineQty += '<div class="col-xs-12 subject_section">'; inlineQty += '<div class="input-group">'; inlineQty += '<span class="input-group-addon">SUBJECT<span class="mandatory">*</span></span>'; inlineQty += '<input id="subject" class="form-control" />'; inlineQty += '</div></div></div></div>'; // Row Body inlineQty += '<div class="form-group container send_email body_section">'; inlineQty += '<div class="row">'; inlineQty += '<div class="col-xs-12 body_section">'; inlineQty += '<div id="email_body"></div>'; inlineQty += '</div></div></div>'; // SEND EMAIL button inlineQty += '<div class="form-group container send_email button_section">'; inlineQty += '<div class="row">'; inlineQty += '<div class="col-xs-4 col-xs-offset-4 send_email_btn">'; inlineQty += '<input type="button" style="background-color: #379E8F; border-color: #379E8F; font-weight: 700" value="SEND EMAIL" class="form-control btn btn-primary" id="send_email" />'; inlineQty += '</div></div></div></div>'; return inlineQty; }; /** * Section for the previous emails datatable * @param customer_id * @returns {string} */ function previousEmailsSection(customer_id){ var customerRecord = record.load({ type: record.Type.CUSTOMER, id: customer_id, }); var customer_internal_id = customerRecord.getValue({ fieldId: 'id' }); // Previous Emails header var inlineQty = '<div class="form-group container previous_emails_header">'; inlineQty += '<div class="row">'; inlineQty += '<div class="col-xs-12 heading2">'; inlineQty += '<h4><span style="background-color: #379E8F" class="label label-default col-xs-12">PREVIOUS EMAILS</span></h4>'; inlineQty += '</div></div></div>'; //Searching emails filtered by - internal customer id and dated before the lastmonthonefiscalquarterago (i.e. the past three months) var emailSearch = search.load({ type: 'message', id: 'customsearch_all_messages' }); var emailSearchFilter = [["customer.internalid","anyof",customer_internal_id], "AND", ["messagedate", "after", "lastmonthonefiscalquarterago"]]; //670041, 313070 emailSearch.filterExpression = emailSearchFilter; var resultEmailSet = emailSearch.run(); var allEmails = resultEmailSet.getRange({ start: 0, end: 1000 }); //Previous Emails table setup // inlineQty += '<style> table {font-size: 12px;text-align: center;border: none;} {font-size: 14px;} table th{text-align: center;} .dataTables_wrapper{width:78%; margin:auto;} </style>'; // inlineQty += '<div class="form-group container previous_emails_section">'; // inlineQty += '<table cellpadding="15" id="emails-preview" class="table table-responsive table-striped customer tablesorter" cellspacing="0" style="width: 100%;">'; // inlineQty += '<thead style="color: white;background-color: #CFE0CE;">'; // inlineQty += '<tr class="text-center">'; // inlineQty += '<th scope="col">Message Date</th>'; // inlineQty += '<th scope="col">Author</th>'; // inlineQty += '<th scope="col">Receipients</th>'; // inlineQty += '<th scope="col">Subject</th>'; // inlineQty += '<th scope="col">More</th>'; // inlineQty += '</tr>'; // inlineQty += '</thead>'; // inlineQty += '<tbody>'; inlineQty += '<style>table#emails-preview {font-size: 12px;text-align: center;border: none; background-color: #379E8F}.dataTables_wrapper {font-size: 12px;}table#emails-preview th{background-color: #379E8F; text-align: center;}</style>'; inlineQty += '<table cellpadding="15" id="emails-preview" class="table table-responsive table-striped customer tablesorter" cellspacing="0" style="width: 100%;">'; inlineQty += '<thead style="color: white;background-color: #379E8F;">'; inlineQty += '<tr class="text-center">'; inlineQty += '<th scope="col">Message Date</th>'; inlineQty += '<th scope="col">Author</th>'; inlineQty += '<th scope="col">Receipients</th>'; inlineQty += '<th scope="col">Subject</th>'; inlineQty += '<th scope="col">More</th>'; inlineQty += '</tr>'; inlineQty += '</thead>'; inlineQty += '<tbody>'; allEmails.forEach(function (email) { var messageid = email.searchId; var date = email.getValue('messagedate'); var author = email.getValue('authoremail'); var recipients = email.getText('recipients'); var subject = email.getValue('subject'); var url = "https://1048144-sb3.app.netsuite.com/app/crm/common/crmmessage.nl?id=" + messageid; //Table row data inlineQty += '<tr>'; inlineQty += '<td> ' + date + ' </td>'; inlineQty += '<td> ' + author + ' </td>'; inlineQty += '<td> ' + recipients + ' </td>'; inlineQty += '<td> ' + subject + '</td>'; inlineQty += '<td> <a href='+ url + '> View More </a> </td>'; inlineQty += '</tr>'; }); inlineQty += '</tbody>'; inlineQty += '</table>'; //inlineQty += '</div>'; return inlineQty; } /** * @return {String} inlineQty */ function issuesHeader() { var inlineQty = '<div class="form-group container toll_issues_header_section">'; inlineQty += '<div class="row">'; inlineQty += '<div class="col-xs-12 heading1">'; inlineQty += '<h4><span style="background-color: #379E8F" class="form-group label label-default col-xs-12">ISSUES</span></h4>'; inlineQty += '</div></div></div>'; return inlineQty; } /** * @param {Number} status_value * @return {String} inlineQty */ function reminderSection(status_value) { var hide_class = (!isTicketNotClosed(status_value)) ? 'hide' : ''; var inlineQty = '<div class="form-group container reminder_section ' + hide_class + '">'; inlineQty += '<div class="row">'; // Reminder field inlineQty += '<div class="col-xs-12 reminder">'; inlineQty += '<div class="input-group">'; inlineQty += '<span class="input-group-addon" id="reminder_text">REMINDER</span>'; inlineQty += '<input id="reminder" class="form-control reminder" type="date" />'; inlineQty += '</div></div></div></div>'; return inlineQty; } /** * Based on the selected MP Issue, an Owner is allocated to the ticket. * IT issues have priority over the other issues. * Populated with selectOwner() in the pageInit function on the client script. * @param {Number} ticket_id * @param {Array} owner_list * @param {Number} status_value * @return {String} inlineQty */ function ownerSection(ticket_id, owner_list, status_value) { if (isNullorEmpty(ticket_id)) { // If ticket_id is null, owner_list as well. // In that case, only the creator of the ticket is pre-selected as the owner. var userId = runtime.getCurrentUser().id; log.debug({ title: 'userId', details: userId }) owner_list = [userId]; } var disabled = (!isTicketNotClosed(status_value)) ? 'disabled' : ''; log.debug({ title: 'owner_list', details: owner_list }) var inlineQty = '<div class="form-group container owner_section">'; inlineQty += '<div class="row">'; inlineQty += '<div class="col-xs-12 owner">'; inlineQty += '<div class="input-group">'; inlineQty += '<span class="input-group-addon" id="owner_text">OWNER<span class="mandatory">*</span></span>'; inlineQty += '<select multiple id="owner" class="form-control owner" ' + disabled + '>'; var employeeSearch = search.load({ type: 'employee', id: 'customsearch_active_employees' }); var employeeResultSet = employeeSearch.run(); employeeResultSet.each(function(employeeResult) { var employee_id = employeeResult.id; var employee_firstname = employeeResult.getValue('firstname'); var employee_lastname = employeeResult.getValue('lastname'); var employee_email = employeeResult.getValue('email'); if (owner_list.indexOf(parseInt(employee_id)) != -1) { inlineQty += '<option value="' + employee_id + '" data-email="' + employee_email + '" selected>' + employee_firstname + ' ' + employee_lastname + '</option>'; } else { inlineQty += '<option value="' + employee_id + '" data-email="' + employee_email + '">' + employee_firstname + ' ' + employee_lastname + '</option>'; } return true; }); inlineQty += '</select>'; inlineQty += '</div></div></div></div>'; return inlineQty; } function customerIssueDropdown(){ //Load the customer issue list var col = new Array(); col[0] = search.createColumn({ name: 'name' }); col[1] = search.createColumn({ name: 'internalId' }); var results = search.create({ type: 'customlist_customer_ticket_issues', columns: col, }) var inlineQty = '<div class="form-group container customer_issues_dropdown_section">'; inlineQty += '<div class="row">'; inlineQty += '<div class="col-xs-12">'; inlineQty += '<div class="input-group"><span class="input-group-addon">CUSTOMER ISSUE</span>'; inlineQty += '<select id="customer_issue_dropdown" class="form-control">'; inlineQty += '<option></option>'; for (var i = 0; results != null && i < results.length; i++) {​​​​​ var res = results[i]; var listValue = res.getValue('name'); var listID = res.getValue('internalId'); inlineQty += '<option value="' + listID + '">' + listValue + '</option>'; // if (selected) { // inlineQty += '<option value="' + listID + '" selected>' + listValue + '</option>'; // } else { // inlineQty += '<option value="' + listID + '">' + listValue + '</option>'; // } } inlineQty += '</select>'; inlineQty += '</div></div></div></div>'; return inlineQty; } function customerIssuesSection(ticket_id, selector_type, selector_number, screenshot_file, selected_browser, login_email_used, selected_operating_system, phone_used, old_sender_name, old_sender_phone, status_value){ if (isNullorEmpty(screenshot_file)) { screenshot_file = '';} if (isNullorEmpty(selected_browser)) { selected_browser = '';} if (isNullorEmpty(login_email_used)) { login_email_used = '';} if (isNullorEmpty(selected_operating_system)) { operating_system = '';} if (isNullorEmpty(phone_used)) { phone_used = '';} if (isNullorEmpty(old_sender_name)) { old_sender_name = '';} if (isNullorEmpty(old_sender_phone)) { old_sender_phone = '';} var hide_class_section_mp_app = ((selector_type == "customer_issue") && (selector_number == 'Customer App')) ? '' : 'hide'; var hide_class_section_mp_label = ((selector_type == "customer_issue") && (selector_number == 'Update Label')) ? '' : 'hide'; var is_customer_issue_hide = (selector_type != "customer_issue") ? 'hide': ''; var hide_class_section_mp_portal = ((selector_type == "customer_issue") && (selector_number == 'Customer Portal')) ? '' : 'hide'; var inlineQty = ''; //Screenshot section if(selector_type == "customer_issue" && (selector_number == "Customer App" || selector_number == "Customer Portal") && !isNullorEmpty(ticket_id)){ inlineQty += '<div class="form-group container ss_section">'; inlineQty += '<div class="row">'; inlineQty += '<div class="col-xs-12 screenshot_div">'; inlineQty += '<div class="input-group"><span class="input-group-addon" id="screenshot_text">SCREENSHOT</span>'; inlineQty += '<input type="file" class="form-control" id="screenshot_image" value="'+ screenshot_file + '">'; inlineQty += '</div></div></div></div>'; } // Browser and OS Section inlineQty += '<div class="form-group container browser_os_section ' + hide_class_section_mp_portal + ' ' + is_customer_issue_hide + '">'; inlineQty += '<div class="row">'; inlineQty += '<div class="col-xs-6 browser_div">'; inlineQty += '<div class="input-group"><span class="input-group-addon" id="browser_text">BROWSER</span>'; inlineQty += '<select id="browser_value" class="form-control label_status">'; inlineQty += '<option></option>' var browserColumns = new Array(); browserColumns[0] = search.createColumn({ name: 'name' }); browserColumns[1] = search.createColumn({ name: 'internalId' }); var browserResultSet = search.create({ type: 'customlist_common_browsers', columns: browserColumns }); browserResultSet.run().each(function (browserResult) { var browserName = browserResult.getValue('name'); var browserId = browserResult.getValue('internalId'); if(selected_browser == browserId) { inlineQty += '<option value="' + browserId + '"selected>' + browserName + '</option>'; }else{ inlineQty += '<option value="' + browserId + '">' + browserName + '</option>'; } return inlineQty; }); inlineQty += '</select></div></div>'; inlineQty += '<div class="col-xs-6 os_div">'; inlineQty += '<div class="input-group"><span class="input-group-addon" id="os_text">OPERATING SYSTEM</span>'; inlineQty += '<select id="os_value" class="form-control">'; inlineQty += '<option></option>' var osColumns = new Array(); osColumns[0] = search.createColumn({ name: 'name' }); osColumns[1] = search.createColumn({ name: 'internalId' }); var osResultSet = search.create({ type: 'customlist_common_os', columns: osColumns }); osResultSet.run().each(function (osResult) { var osName = osResult.getValue('name'); var osId = osResult.getValue('internalId'); if(selected_browser == osId) { inlineQty += '<option value="' + osId + '"selected>' + osName + '</option>'; }else{ inlineQty += '<option value="' + osId + '">' + osName + '</option>'; } return inlineQty; }); inlineQty += '</select>'; inlineQty += '</div></div></div></div>'; //Customer App issues - Phone section inlineQty += '<div class="form-group container '+is_customer_issue_hide+' phone_section ' + hide_class_section_mp_app + '">'; inlineQty += '<div class="row">'; inlineQty += '<div class="col-xs-12 phone_div">'; inlineQty += '<div class="input-group"><span class="input-group-addon" id="screenshot_text">PHONE</span>'; inlineQty += '<input type="text" class="form-control" id="phone_used" placeholder=" Google Pixel 3" value="'+ phone_used + '">'; inlineQty += '</div></div></div></div>'; //Login email used section inlineQty += '<div class="form-group container login_email_used_section '+ is_customer_issue_hide +'">'; inlineQty += '<div class="row">'; inlineQty += '<div class="col-xs-12 login_email_div">'; inlineQty += '<div class="input-group">'; inlineQty += '<span class="input-group-addon" id="login_email">LOGIN EMAIL</span>'; inlineQty += '<input id="login_email_text" class="form-control" value="'+ login_email_used + '"/>'; inlineQty += '</div></div></div></div>'; //Sender details name and phone number inlineQty += '<div class="form-group container '+ is_customer_issue_hide +' sender_details_section ' + hide_class_section_mp_label + '">'; inlineQty += '<div class="row">'; inlineQty += '<div class="col-xs-6 sender_name_div">'; inlineQty += '<div class="input-group">'; inlineQty += '<span class="input-group-addon" id="sender_name">SENDER NAME</span>'; inlineQty += '<input id="sender_name_text" class="form-control" value="'+ old_sender_name + '"/>'; inlineQty += '</div></div>'; inlineQty += '<div class="col-xs-6 sender_phone_div">'; inlineQty += '<div class="input-group">'; inlineQty += '<span class="input-group-addon" id="sender_phone">SENDER PHONE</span>'; inlineQty += '<input id="sender_phone_text" class="form-control" value="'+ old_sender_phone + '"/>'; inlineQty += '</div></div></div></div>'; return inlineQty; } /** * The multiselect TOLL issues dropdown * @param {Array} list_toll_issues * @param {Array} list_resolved_toll_issues * @param {Number} status_value * @param {String} selector_type * @return {String} inlineQty */ function tollIssuesSection(list_toll_issues, list_resolved_toll_issues, status_value, selector_type) { // TOLL Issues var has_toll_issues = (!isNullorEmpty(list_toll_issues)); var toll_issues_columns = new Array(); toll_issues_columns[0] = search.createColumn({ name: 'name' }); toll_issues_columns[1] = search.createColumn({ name: 'internalId' }); var tollIssuesResultSet = search.create({ type: 'customlist_cust_prod_stock_toll_issues', columns: toll_issues_columns }); if (!isTicketNotClosed(status_value) || selector_type != 'barcode_number') { var inlineQty = '<div class="form-group container toll_issues_section hide">'; } else { var inlineQty = '<div class="form-group container toll_issues_section">'; } inlineQty += '<div class="row">'; inlineQty += '<div class="col-xs-12 toll_issues">'; inlineQty += '<div class="input-group"><span class="input-group-addon" id="toll_issues_text">TOLL ISSUES<span class="mandatory">*</span></span>'; inlineQty += '<select multiple id="toll_issues" class="form-control toll_issues" size="' + tollIssuesResultSet.length + '">'; tollIssuesResultSet.run().each(function(tollIssueResult) { var issue_name = tollIssueResult.getValue('name'); var issue_id = tollIssueResult.getValue('internalId'); var selected = false; if (has_toll_issues) { selected = (list_toll_issues.indexOf(issue_id) !== -1); } if (selected) { inlineQty += '<option value="' + issue_id + '" selected>' + issue_name + '</option>'; } else { inlineQty += '<option value="' + issue_id + '">' + issue_name + '</option>'; } return true; }); inlineQty += '</select>'; inlineQty += '</div></div></div></div>'; // Resolved TOLL Issues log.debug({ title: 'list_resolved_toll_issues : ', details: list_resolved_toll_issues }); var has_resolved_toll_issues = (!isNullorEmpty(list_resolved_toll_issues)); if (has_resolved_toll_issues) { var text_resolved_toll_issues = ''; tollIssuesResultSet.run().each(function(tollIssueResult) { var issue_name = tollIssueResult.getValue('name'); var issue_id = tollIssueResult.getValue('internalId'); if (list_resolved_toll_issues.indexOf(issue_id) !== -1) { text_resolved_toll_issues += issue_name + '\n'; } return true; }); log.debug({ title: 'text_resolved_toll_issues : ', details: text_resolved_toll_issues }); inlineQty += '<div class="form-group container resolved_toll_issues_section">'; inlineQty += '<div class="row">'; inlineQty += '<div class="col-xs-12 resolved_toll_issues">'; inlineQty += '<div class="input-group">'; inlineQty += '<span class="input-group-addon" id="resolved_toll_issues_text">RESOLVED TOLL ISSUES</span>'; inlineQty += '<textarea id="resolved_toll_issues" class="form-control resolved_toll_issues" rows="' + list_resolved_toll_issues.length + '" disabled>' + text_resolved_toll_issues.trim() + '</textarea>'; inlineQty += '</div></div></div></div>'; } return inlineQty; }; /** * The multiselect MP Ticket issues dropdown * @param {Array} list_mp_ticket_issues * @param {Array} list_resolved_mp_ticket_issues * @param {Number} status_value * @param {String} selector_type * @return {String} inlineQty */ function mpTicketIssuesSection(list_mp_ticket_issues, list_resolved_mp_ticket_issues, status_value, selector_type) { // MP Ticket Issues var has_mp_ticket_issues = !isNullorEmpty(list_mp_ticket_issues); var disabled_mp_issue_field = (isTicketNotClosed(status_value)) ? '' : 'disabled'; log.debug({ title: 'has_mp_ticket_issues : ', details: has_mp_ticket_issues }); if (has_mp_ticket_issues && status_value != 3) { // The MP Ticket issue section is displayed if the status is 'Closed - Unallocated' (status_value == 8) var inlineQty = '<div class="form-group container mp_issues_section">'; } else { var inlineQty = '<div class="form-group container mp_issues_section hide">'; } inlineQty += '<div class="row">'; inlineQty += '<div class="col-xs-12 mp_issues">'; var mp_ticket_issues_columns = new Array(); mp_ticket_issues_columns[0] = search.createColumn({ name: 'name' }); mp_ticket_issues_columns[1] = search.createColumn({ name: 'internalId' }); var mpTicketIssuesResultSet = search.create({ type: 'customlist_mp_ticket_issues', columns: mp_ticket_issues_columns }); inlineQty += '<div class="input-group">' inlineQty += '<span class="input-group-addon" id="mp_issues_text">MP ISSUES<span class="mandatory hide">*</span></span>'; inlineQty += '<select multiple id="mp_issues" class="form-control mp_issues" size="' + mpTicketIssuesResultSet.length + '" ' + disabled_mp_issue_field + '>'; mpTicketIssuesResultSet.run().each(function(mpTicketIssueResult) { var mp_issue_name = mpTicketIssueResult.getValue('name'); var mp_issue_id = mpTicketIssueResult.getValue('internalId'); var selected = false; if (has_mp_ticket_issues) { selected = (list_mp_ticket_issues.indexOf(mp_issue_id) !== -1); } var show_option = (selector_type == 'barcode_number' || (selector_type == 'invoice_number' && mp_issue_id == 4) || (selector_type == "customer_issue")); var selected_option = (selected) ? 'selected' : ''; if (show_option) { inlineQty += '<option value="' + mp_issue_id + '" ' + selected_option + '> ' + mp_issue_name + '</option > '; } return true; }); inlineQty += '</select>'; inlineQty += '</div></div></div></div>'; // Resolved MP Ticket Issues var has_resolved_mp_ticket_issues = !isNullorEmpty(list_resolved_mp_ticket_issues); if (has_resolved_mp_ticket_issues && selector_type != "customer_issue") { var text_resolved_mp_ticket_issues = ''; mpTicketIssuesResultSet.run().each(function(mpTicketIssueResult) { var mp_issue_name = mpTicketIssueResult.getValue('name'); var mp_issue_id = mpTicketIssueResult.getValue('internalId'); if (list_resolved_mp_ticket_issues.indexOf(mp_issue_id) !== -1) { text_resolved_mp_ticket_issues += mp_issue_name + '\n'; } return true; }); inlineQty += '<div class="form-group container resolved_mp_issues_section">'; inlineQty += '<div class="row">'; inlineQty += '<div class="col-xs-12 resolved_mp_issues">'; inlineQty += '<div class="input-group">'; inlineQty += '<span class="input-group-addon" id="resolved_mp_issues_text">RESOLVED MP ISSUES</span>'; inlineQty += '<textarea id="resolved_mp_issues" class="form-control resolved_mp_issues" rows="' + list_resolved_mp_ticket_issues.length + '" disabled>' + text_resolved_mp_ticket_issues.trim() + '</textarea>'; inlineQty += '</div></div></div></div>'; } return inlineQty; } /** * The multiselect Invoice issues dropdown * @param {Array} list_invoice_issues * @param {Array} list_resolved_invoice_issues * @param {Number} status_value * @param {String} selector_type * @return {String} inlineQty */ function invoiceIssuesSection(list_invoice_issues, list_resolved_invoice_issues, status_value, selector_type) { var has_invoice_issues = (!isNullorEmpty(list_invoice_issues)); var invoice_issues_columns = new Array(); invoice_issues_columns[0] = search.createColumn({ name: 'name' }); // Might need to be changed invoice_issues_columns[1] = search.createColumn({ name: 'internalId' }); // Might need to be changed var invoiceIssuesResultSet = search.create({ type: 'customlist_invoice_issues', columns: invoice_issues_columns }); if (!isTicketNotClosed(status_value) || selector_type != 'invoice_number') { var inlineQty = '<div class="form-group container invoice_issues_section hide">'; } else { var inlineQty = '<div class="form-group container invoice_issues_section">'; } inlineQty += '<div class="row">'; inlineQty += '<div class="col-xs-12 invoice_issues">'; inlineQty += '<div class="input-group"><span class="input-group-addon" id="invoice_issues_text">INVOICE ISSUES<span class="mandatory">*</span></span>'; inlineQty += '<select multiple id="invoice_issues" class="form-control invoice_issues">'; invoiceIssuesResultSet.run().each(function(invoiceIssueResult) { var issue_name = invoiceIssueResult.getValue('name'); // Might need to be changed var issue_id = invoiceIssueResult.getValue('internalId'); // Might need to be changed var selected = false; if (has_invoice_issues) { selected = (list_invoice_issues.indexOf(issue_id) != -1); } if (selected) { inlineQty += '<option value="' + issue_id + '" selected>' + issue_name + '</option>'; } else { inlineQty += '<option value="' + issue_id + '">' + issue_name + '</option>'; } return true; }); inlineQty += '</select>'; inlineQty += '</div></div></div></div>'; // Resolved invoice Issues log.debug({ title: 'list_resolved_invoice_issues : ', details: list_resolved_invoice_issues }); var has_resolved_invoice_issues = (!isNullorEmpty(list_resolved_invoice_issues)); if (has_resolved_invoice_issues) { var text_resolved_invoice_issues = ''; invoiceIssuesResultSet.run().each(function(invoiceIssueResult) { var issue_name = invoiceIssueResult.getValue('name'); // Might need to be changed var issue_id = invoiceIssueResult.getValue('internalId'); // Might need to be changed if (list_resolved_invoice_issues.indexOf(issue_id) !== -1) { text_resolved_invoice_issues += issue_name + '\n'; } }); log.debug({ title: 'text_resolved_invoice_issues : ', details: text_resolved_invoice_issues }); inlineQty += '<div class="form-group container resolved_invoice_issues_section">'; inlineQty += '<div class="row">'; inlineQty += '<div class="col-xs-12 resolved_invoice_issues">'; inlineQty += '<div class="input-group">'; inlineQty += '<span class="input-group-addon" id="resolved_invoice_issues_text">RESOLVED INVOICE ISSUES</span>'; inlineQty += '<textarea id="resolved_invoice_issues" class="form-control resolved_invoice_issues" rows="' + list_resolved_invoice_issues.length + '" disabled>' + text_resolved_invoice_issues.trim() + '</textarea>'; inlineQty += '</div></div></div></div>'; } return inlineQty; } /** * @param {String} selector_type * @param {Number} status_value * @return {String} inlineQty */ function usernoteSection(selector_type, status_value) { var usernote_titles_columns = new Array(); usernote_titles_columns[0] = search.createColumn({ name: 'name' }); usernote_titles_columns[1] = search.createColumn({ name: 'internalId' }); var usernoteTitlesResultSet = search.create({ type: 'customlist_user_note_title', columns: usernote_titles_columns }); // Row Title if (selector_type == 'invoice_number' && isTicketNotClosed(status_value)) { var inlineQty = '<div class="form-group container user_note user_note_title_section">'; } else { var inlineQty = '<div class="form-group container user_note user_note_title_section hide">'; } inlineQty += '<div class="row">'; inlineQty += '<div class="col-xs-12 user_note_title_section">'; inlineQty += '<div class="input-group">'; inlineQty += '<span class="input-group-addon">TITLE<span class="mandatory">*</span></span>'; inlineQty += '<select id="user_note_title" class="form-control">'; usernoteTitlesResultSet.run().each(function(usernoteTitleResult) { var title_name = usernoteTitleResult.getValue('name'); var title_id = usernoteTitleResult.getValue('internalId'); if (title_id == 3) { inlineQty += '<option value="' + title_id + '" selected>' + title_name + '</option>'; } else { inlineQty += '<option value="' + title_id + '">' + title_name + '</option>'; } return true; }); inlineQty += '</select>'; inlineQty += '</div></div></div></div>'; // Row User Note Textarea if (selector_type == 'invoice_number' && isTicketNotClosed(status_value)) { inlineQty += '<div class="form-group container user_note user_note_textarea_section">'; } else { inlineQty += '<div class="form-group container user_note user_note_textarea_section hide">'; } inlineQty += '<div class="row">'; inlineQty += '<div class="col-xs-12 user_note_textarea">'; inlineQty += '<div class="input-group">'; inlineQty += '<span class="input-group-addon" id="user_note_textarea_text">USER NOTE<span class="mandatory hide">*</span></span>'; inlineQty += '<textarea id="user_note_textarea" class="form-control user_note_textarea" rows="3"></textarea>'; inlineQty += '</div></div></div></div>'; // User Note table if (selector_type == 'invoice_number') { inlineQty += '<div class="form-group container user_note user_note_section" style="font-size: small;">'; } else { inlineQty += '<div class="form-group container user_note user_note_section hide" style="font-size: small;">'; } inlineQty += '<div class="row">'; inlineQty += '<div class="col-xs-12 user_note_div">'; // Since the table is not displayed correctly when added through suitelet, // It is added with jQuery in the pageInit() function in the client script 'mp_cl_open_ticket.js'. inlineQty += '</div>'; inlineQty += '</div>'; inlineQty += '</div>'; return inlineQty; } /** * Used to pass the values of `date_from` and `date_to` between the scripts and to Netsuite for the records and the search. * @param {String} date_iso "2020-06-01" * @returns {String} date_netsuite "1/6/2020" */ function dateISOToNetsuite(date_iso) { var date_netsuite = ''; if (!isNullorEmpty(date_iso)) { var date_netsuite = format.format({ value: date_iso, type: format.Type.DATETIME }); } return date_netsuite; } /** * The free-from text area for comments. * @param {String} comment * @param {String} selector_type * @param {Number} status_value * @return {String} inlineQty */ function commentSection(comment, selector_type, status_value) { if (isNullorEmpty(comment)) { comment = ''; } else { comment += '\n'; } switch (selector_type) { case 'barcode_number': var inlineQty = '<div class="form-group container comment_section">'; break; case 'invoice_number': var inlineQty = '<div class="form-group container comment_section hide">'; break; case 'customer_issue': var inlineQty = '<div class="form-group container comment_section">'; break; } inlineQty += '<div class="row">'; inlineQty += '<div class="col-xs-12 comment">'; inlineQty += '<div class="input-group">'; inlineQty += '<span class="input-group-addon" id="comment_text">COMMENT<span class="mandatory hide">*</span></span>'; if (isTicketNotClosed(status_value)) { inlineQty += '<textarea id="comment" class="form-control comment" rows="3">' + comment + '</textarea>'; } else { inlineQty += '<textarea id="comment" class="form-control comment" rows="3" readonly>' + comment + '</textarea>'; } inlineQty += '</div></div></div></div>'; return inlineQty; } /** * The table that will display the differents tickets linked to the customer. * @return {String} inlineQty */ function dataTablePreview() { var inlineQty = '<div class="form-group container tickets_datatable_section">'; inlineQty += '<div class="row">'; inlineQty += '<div class="col-xs-12 heading2">'; inlineQty += '<h4><span style="background-color: #379E8F" class="label label-default col-xs-12">PREVIOUS TICKETS</span></h4>'; inlineQty += '</div></div></div>'; inlineQty += '<style>table#tickets-preview {font-size: 12px;text-align: center;border: none; background-color: #379E8F}.dataTables_wrapper {font-size: 12px;}table#tickets-preview th{background-color: #379E8F; text-align: center;}</style>'; inlineQty += '<table cellpadding="15" id="tickets-preview" class="table table-responsive table-striped customer tablesorter" cellspacing="0" style="width: 100%;">'; inlineQty += '<thead style="color: white;background-color: #379E8F;">'; inlineQty += '<tr class="text-center">'; inlineQty += '</tr>'; inlineQty += '</thead>'; inlineQty += '<tbody id="result_tickets"></tbody>'; inlineQty += '</table>'; return inlineQty; } /** * The inline HTML for the close ticket button or the reopen button, * and the submitter button at the bottom of the page. * @param {Number} ticket_id * @param {Number} status_value * @return {String} inlineQty */ function closeReopenSubmitTicketButton(ticket_id, status_value) { var inlineQty = '<div class="form-group container close_reopen_submit_ticket_section">'; inlineQty += '<div class="row">'; log.debug({ title: 'status_value', details: status_value }); log.debug({ title: 'ticket_id', details: ticket_id }); if (isTicketNotClosed(status_value)) { if (!isNullorEmpty(ticket_id)) { inlineQty += '<div class="col-xs-2 close_ticket">'; inlineQty += '<input type="button" value="CLOSE TICKET" style="background-color: #FBEA51; border: 3px solid #379E8F; color: #379E8F; font-weight: 700" class="form-control btn btn-default" id="close_ticket" onclick="closeTicket()"/>'; inlineQty += '</div>'; inlineQty += '<div class="col-xs-3 close_ticket_lost">'; inlineQty += '<input type="button" value="CLOSE TICKET - LOST ITEM" style="background-color: #FBEA51; border: 3px solid #379E8F; color: #379E8F; font-weight: 700" class="form-control btn btn-default" id="close_ticket_lost" onclick="closeTicketLost()"/>'; inlineQty += '</div>'; if (userId == 409635 || userId == 696992 || userId == 766498) { inlineQty += '<div class="col-xs-3 close_unallocated_ticket hide">'; inlineQty += '<input type="button" value="CLOSE UNALLOCATED TICKET" style="background-color: #FBEA51; border: 3px solid #379E8F; color: #379E8F; font-weight: 700" class="form-control btn btn-default" id="close_unallocated_ticket" onclick="closeUnallocatedTicket()" />'; inlineQty += '</div>'; } } inlineQty += '<div class="col-xs-2 submitter">'; inlineQty += '<input type="button" style="background-color: #FBEA51; border: 3px solid #379E8F; color: #379E8F; font-weight: 700" value="UPDATE TICKET" class="form-control btn btn-primary" id="submit_ticket" />'; inlineQty += '</div>'; if (isNullorEmpty(ticket_id)) { inlineQty += '<div class="col-xs-3 open_and_new_ticket_btn">'; inlineQty += '<input type="button" style="background-color: #FBEA51; border: 3px solid #379E8F; color: #379E8F; font-weight: 700" value="OPEN AND NEW TICKET" class="form-control btn btn-primary" id="open_and_new_ticket_btn" />'; inlineQty += '</div>'; } inlineQty += '<style>.escalate:hover {box-shadow: 0 12px 16px 0 rgba(0,0,0,0.24), 0 17px 50px 0 rgba(0,0,0,0.19)}</style>'; inlineQty += '<div class="col-xs-2 escalate">'; inlineQty += '<input type="button" style="background-color: #FBEA51; border: 3px solid #379E8F; color: #379E8F; font-weight: 700" value="ESCALATE" class="form-control btn btn-default" id="escalate" onclick="onEscalate()"/>'; inlineQty += '</div>'; } else { inlineQty += '<div class="col-xs-2 col-xs-offset-2 reopen_ticket">'; inlineQty += '<input type="button" style="background-color: #FBEA51; border: 3px solid #379E8F; color: #379E8F; font-weight: 700" value="REOPEN TICKET" class="form-control btn btn-primary" id="reopen_ticket" />'; inlineQty += '</div>'; } inlineQty += '<div class="col-xs-2 cancel">'; inlineQty += '<input type="button" style="background-color: #FBEA51; border: 3px solid #379E8F; color: #379E8F; font-weight: 700" value="CANCEL" class="form-control btn btn-default" id="cancel" onclick="onCancel()"/>'; inlineQty += '</div>'; inlineQty += '</div></div>'; return inlineQty; } function Ownerjava2jsArray(javaArray) { var jsArray = new Array; if (!isNullorEmpty(javaArray)) { javaArray.forEach(function(javaValue) { var jsValue = parseInt(javaValue); jsArray.push(jsValue); }) } return jsArray; } /** * The output of .getFieldValues is a java String Array. * We want to convert it to a javaScript Array in order to read its values. * @param {Ljava.lang.String} javaArray * @return {Array} jsArray */ function java2jsArray(javaArray) { var jsArray = new Array; if (!isNullorEmpty(javaArray)) { javaArray.forEach(function(javaValue) { var jsValue = javaValue.toString(); jsArray.push(jsValue); }) } return jsArray; } /** * Parse the objects in an array, and returns an object based on the value of one of its keys. * With ES6, this function would simply be `array.find(obj => obj[key] == value)` * @param {Array} array * @param {String} key * @param {*} value * @returns {Object} */ function findObjectByKey(array, key, value) { for (var i = 0; i < array.length; i++) { if (array[i][key] === value) { return array[i]; } } return null; } /** * Returns whether a ticket is closed or not based on its status value. * @param {Number} status_value * @returns {Boolean} is_ticket_closed */ function isTicketNotClosed(status_value) { var is_ticket_not_closed = ((status_value != 3) && (status_value != 8) && (status_value != 15)) ? true : false; return is_ticket_not_closed; } function escalateButton(status) { if (status < 11) { return 'Escalate to 1st Escalation'; } else if (status == 11) { return 'Escalate to 2nd Escalation'; }else if (status == 12) { return 'Escalate to 3rd Escalation'; } else if (status == 13) { return 'Escalate to Final Escalation'; } else { return 'Escalate'; } } /** * Whether the user is from the finance team, * or a Data Systems Co-ordinator, MailPlus Administration or Administrator user. * @param {Number} userRole * @returns {Boolean} */ function isFinanceRole(userRole) { // 1001, 1031 and 1023 are finance roles // 1032 is the Data Systems Co-ordinator role (to be deleted in prod) // 1006 is the Mail Plus Administration role. // 3 is the Administrator role. return ((userRole == 1001 || userRole == 1031 || userRole == 1023) || ((userRole == 1032) || (userRole == 1006) || (userRole == 3))); } function isNullorEmpty(strVal) { return (strVal == null || strVal == '' || strVal == 'null' || strVal == undefined || strVal == 'undefined' || strVal == '- None -'); } return { onRequest: onRequest }; });
/** * * @NApiVersion 2.0 * @NScriptType Suitelet * * Description: Import an excel file of connote numbers to add into processed orders * @Last Modified by: Sruti Desai * */ define(['N/ui/serverWidget', 'N/email', 'N/runtime', 'N/search', 'N/record', 'N/log', 'N/redirect', 'N/format', 'N/task', 'N/file', 'N/error'], function(ui, email, runtime, search, record, log, redirect, format, task, file, error) { var baseURL = 'https://1048144.app.netsuite.com'; if (runtime.EnvType == "SANDBOX") { baseURL = 'https://1048144-sb3.app.netsuite.com'; } var zee = 0; var role = runtime.getCurrentUser().role; if (role == 1000) { //Franchisee zee = runtime.getCurrentUser().id; } function onRequest(context) { if (context.request.method === 'GET') { // Load jQuery var inlineHtml = '<script src="https://code.jquery.com/jquery-1.12.4.min.js" integrity="sha384-nvAa0+6Qg9clwYCGGPpDQLVpLNn0fRaROjHqs13t4Ggj3Ez50XnGQqc/r8MhnRDZ" crossorigin="anonymous"></script>'; // Load Tooltip inlineHtml += '<script src="https://unpkg.com/@popperjs/core@2"></script>'; // Load Bootstrap inlineHtml += '<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/3.4.1/css/bootstrap.min.css" integrity="sha384-HSMxcRTRxnN+Bdg0JdbxYKrThecOKuH5zCYotlSAcp1+c8xmyTe9GYg1l9a69psu" crossorigin="anonymous">'; inlineHtml += '<script src="https://stackpath.bootstrapcdn.com/bootstrap/3.4.1/js/bootstrap.min.js" integrity="sha384-aJ21OjlMXNL5UyIl/XNwTMqvzeRMZH2w8c5cRVpzpU8Y5bApTppSuUkhZXN0VxHd" crossorigin="anonymous"></script>'; // Load DataTables inlineHtml += '<link rel="stylesheet" type="text/css" href="//cdn.datatables.net/1.10.21/css/jquery.dataTables.min.css">'; inlineHtml += '<script type="text/javascript" charset="utf8" src="//cdn.datatables.net/1.10.21/js/jquery.dataTables.min.js"></script>'; // Load Bootstrap-Select inlineHtml += '<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap-select@1.13.14/dist/css/bootstrap-select.min.css">'; inlineHtml += '<script src="https://cdn.jsdelivr.net/npm/bootstrap-select@1.13.14/dist/js/bootstrap-select.min.js"></script>'; // Load Netsuite stylesheet and script inlineHtml += '<link rel="stylesheet" href="https://1048144.app.netsuite.com/core/media/media.nl?id=2060796&c=1048144&h=9ee6accfd476c9cae718&_xt=.css"/>'; inlineHtml += '<script src="https://1048144.app.netsuite.com/core/media/media.nl?id=2060797&c=1048144&h=ef2cda20731d146b5e98&_xt=.js"></script>'; inlineHtml += '<link type="text/css" rel="stylesheet" href="https://1048144.app.netsuite.com/core/media/media.nl?id=2090583&c=1048144&h=a0ef6ac4e28f91203dfe&_xt=.css">'; inlineHtml += '<style>.mandatory{color:red;}</style>'; var form = ui.createForm({ title: 'MPEX Import Connote' }); inlineHtml += '<br></br>'; inlineHtml += dateFilterSection(); form.addSubmitButton({ label: 'Import Connote Numbers' }); form.addField({ id: 'upload_mpex_csv', label: 'IMPORT CONNOTE NUMBERS', type: ui.FieldType.FILE }); form.addField({ id: 'custpage_date_from', type: ui.FieldType.DATE, label: 'date_from' }).updateDisplayType({ displayType: ui.FieldDisplayType.HIDDEN }).defaultValue; form.addField({ id: 'custpage_date_to', type: ui.FieldType.DATE, label: 'date_to' }).updateDisplayType({ displayType: ui.FieldDisplayType.HIDDEN }).defaultValue; form.addField({ id: 'custpage_test', type: ui.FieldType.TEXT, label: 'date_to' }).updateDisplayType({ displayType: ui.FieldDisplayType.HIDDEN }).defaultValue; form.addField({ id: 'custpage_scheduled', type: ui.FieldType.TEXT, label: 'scheduled' }).updateDisplayType({ displayType: ui.FieldDisplayType.HIDDEN }); form.addField({ id: 'preview_table', type: ui.FieldType.INLINEHTML, label: 'preview_table' }).updateLayoutType({ layoutType: ui.FieldLayoutType.OUTSIDEBELOW }).updateBreakType({ breakType: ui.FieldBreakType.STARTROW }).defaultValue = inlineHtml; // form.addField({ // id: 'preview_table', // type: ui.FieldType.INLINEHTML, // label: 'preview_table' // }).updateLayoutType({ // layoutType: ui.FieldLayoutType.OUTSIDEBELOW // }).updateBreakType({ // breakType: ui.FieldBreakType.STARTROW // }).defaultValue = inlineHtml; form.clientScriptFileId = 4686408; //SB cl_id =, PROD cl_id = 4686408 context.response.writePage(form); } else { var fileObj = context.request.files.upload_mpex_csv; var date_from = context.request.parameters.custpage_date_from; var date_to = context.request.parameters.custpage_date_to; if (!isNullorEmpty(date_from) && !isNullorEmpty(date_to)) { date_from = formatDate(date_from); date_to = formatDate(date_to); } log.debug({ title: 'date_from', details: date_from }); log.debug({ title: 'date_to', details: date_to }); if (!isNullorEmpty(fileObj)) { fileObj.folder = 2696109; // Prod=2696109 var file_type = fileObj.fileType; if (file_type == 'CSV') { file_type == 'csv'; var file_name = 'mpex_upload' + '.' + file_type; } fileObj.name = file_name; if (file_type == 'CSV') { // Create file and upload it to the file cabinet. var f_id = fileObj.save(); } else { throw error.create({ message: 'Must be in CSV format', name: 'CSV_ERROR', notifyOff: true }); } } // CALL SCHEDULED SCRIPT var scriptTask = task.create({ taskType: task.TaskType.SCHEDULED_SCRIPT }); scriptTask.scriptId = 'customscript_ss_import_connote'; scriptTask.deploymentId = 'customdeploy_ss_import_connote'; scriptTask.params = { custscript_import_connote_file_id: f_id, custscript_import_connote_index: 0, custscript_import_connote_date_from: date_from, custscript_import_connote_date_to: date_to }; var ss_id = scriptTask.submit(); var file1 = file.load({ id: f_id }); var iterator = file1.lines.iterator(); // skip first line (header) iterator.each(function (line) { log.debug({ title: 'line', details: line }); return false; }); var numLines = 0; var zeeArr = []; iterator.each(function (line) { var csv_values = line.value.split(/,(?=(?:(?:[^"]*"){2})*[^"]*$)/); var zee_id = csv_values[1]; if (zeeArr.indexOf(zee_id) == -1) { zeeArr.push(zee_id); } numLines++; return true; }); // Load jQuery var inlineHtml = '<script src="https://code.jquery.com/jquery-1.12.4.min.js" integrity="sha384-nvAa0+6Qg9clwYCGGPpDQLVpLNn0fRaROjHqs13t4Ggj3Ez50XnGQqc/r8MhnRDZ" crossorigin="anonymous"></script>'; // Load Tooltip inlineHtml += '<script src="https://unpkg.com/@popperjs/core@2"></script>'; // Load Bootstrap inlineHtml += '<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/3.4.1/css/bootstrap.min.css" integrity="sha384-HSMxcRTRxnN+Bdg0JdbxYKrThecOKuH5zCYotlSAcp1+c8xmyTe9GYg1l9a69psu" crossorigin="anonymous">'; inlineHtml += '<script src="https://stackpath.bootstrapcdn.com/bootstrap/3.4.1/js/bootstrap.min.js" integrity="sha384-aJ21OjlMXNL5UyIl/XNwTMqvzeRMZH2w8c5cRVpzpU8Y5bApTppSuUkhZXN0VxHd" crossorigin="anonymous"></script>'; // Load DataTables inlineHtml += '<link rel="stylesheet" type="text/css" href="//cdn.datatables.net/1.10.21/css/jquery.dataTables.min.css">'; inlineHtml += '<script type="text/javascript" charset="utf8" src="//cdn.datatables.net/1.10.21/js/jquery.dataTables.min.js"></script>'; // Load Bootstrap-Select inlineHtml += '<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap-select@1.13.14/dist/css/bootstrap-select.min.css">'; inlineHtml += '<script src="https://cdn.jsdelivr.net/npm/bootstrap-select@1.13.14/dist/js/bootstrap-select.min.js"></script>'; // Load Netsuite stylesheet and script inlineHtml += '<link rel="stylesheet" href="https://1048144.app.netsuite.com/core/media/media.nl?id=2060796&c=1048144&h=9ee6accfd476c9cae718&_xt=.css"/>'; inlineHtml += '<script src="https://1048144.app.netsuite.com/core/media/media.nl?id=2060797&c=1048144&h=ef2cda20731d146b5e98&_xt=.js"></script>'; inlineHtml += '<link type="text/css" rel="stylesheet" href="https://1048144.app.netsuite.com/core/media/media.nl?id=2090583&c=1048144&h=a0ef6ac4e28f91203dfe&_xt=.css">'; inlineHtml += '<style>.mandatory{color:red;}</style>'; var form = ui.createForm({ title: 'MPEX Product Orders (ALL ZEEs)' }); inlineHtml += '<br></br>'; inlineHtml += progressBar(); inlineHtml += dateFilterSection(); // Open Invoices Datatable inlineHtml += '<div class="form-group mpex_orders mpex_orders_table">'; inlineHtml += '<div class="row">'; inlineHtml += '<div class="col-xs-12" id="mpex_orders_dt_div">'; // It is inserted as inline html in the script mp_cl_open_ticket inlineHtml += '</div></div></div>'; form.addSubmitButton({ label: 'Import Connote Numbers' }); form.addField({ id: 'upload_mpex_csv', label: 'IMPORT CONNOTE NUMBERS', type: ui.FieldType.FILE }); form.addField({ id: 'custpage_date_from', type: ui.FieldType.DATE, label: 'date_from' }).updateDisplayType({ displayType: ui.FieldDisplayType.HIDDEN }).defaultValue = date_from; form.addField({ id: 'custpage_scheduled', type: ui.FieldType.TEXT, label: 'scheduled' }).updateDisplayType({ displayType: ui.FieldDisplayType.HIDDEN }).defaultValue = 2; form.addField({ id: 'zee_array', type: ui.FieldType.LONGTEXT, label: 'zee_array' }).updateDisplayType({ displayType: ui.FieldDisplayType.HIDDEN }).defaultValue = zeeArr; form.addField({ id: 'excel_lines', type: ui.FieldType.TEXT, label: 'excel_lines' }).updateDisplayType({ displayType: ui.FieldDisplayType.HIDDEN }).defaultValue = numLines; form.addField({ id: 'custpage_date_to', type: ui.FieldType.DATE, label: 'date_to' }).updateDisplayType({ displayType: ui.FieldDisplayType.HIDDEN }).defaultValue = date_to; form.addField({ id: 'preview_table', type: ui.FieldType.INLINEHTML, label: 'preview_table' }).updateLayoutType({ layoutType: ui.FieldLayoutType.OUTSIDEBELOW }).updateBreakType({ breakType: ui.FieldBreakType.STARTROW }).defaultValue = inlineHtml; form.clientScriptFileId = 4686408; //SB cl_id =, PROD cl_id = 4686408 context.response.writePage(form); } } /** * The date input fields to filter the invoices. * Even if the parameters `date_from` and `date_to` are defined, they can't be initiated in the HTML code. * They are initiated with jQuery in the `pageInit()` function. * @return {String} `inlineQty` */ function dateFilterSection() { var inlineQty = '<div class="form-group container total_amount_section">'; inlineQty += '<div class="row">'; inlineQty += '<div class="col-xs-18 heading1"><h4><span style="background-color:#379E8F" class="label label-default col-xs-12">DATE FILTER</span></h4></div>'; inlineQty += '</div>'; inlineQty += '</div>'; inlineQty += '<div class="form-group date_filter_section">'; inlineQty += '<div class="row">'; // Date from field inlineQty += '<div class="col-xs-6 date_from">'; inlineQty += '<div class="input-group">'; inlineQty += '<span class="input-group-addon" id="date_from_text">From</span>'; inlineQty += '<input id="date_from" class="form-control date_from" type="date"/>'; inlineQty += '</div></div>'; // Date to field inlineQty += '<div class="col-xs-6 date_to">'; inlineQty += '<div class="input-group">'; inlineQty += '<span class="input-group-addon" id="date_to_text">To</span>'; inlineQty += '<input id="date_to" class="form-control date_to" type="date">'; inlineQty += '</div></div></div></div>'; return inlineQty; } /** * Display the progress bar. Initialized at 0, with the maximum value as the number of records that will be moved. * Uses Bootstrap : https://www.w3schools.com/bootstrap/bootstrap_progressbars.asp * @param {String} nb_records_total The number of records that will be moved * @return {String} inlineQty : The inline HTML string of the progress bar. */ function progressBar() { var inlineQty = '<div class="progress ">'; inlineQty += '<div class="progress-bar progress-bar-striped progress-bar-warning" id="progress-records" role="progressbar" aria-valuenow="0" style="width:0%">0%</div>'; inlineQty += '</div>'; return inlineQty; } function formatDate(testDate){ var responseDate=format.format({value:testDate,type:format.Type.DATE}); return responseDate; } /** * Used to pass the values of `date_from` and `date_to` between the scripts and to Netsuite for the records and the search. * @param {String} date_iso "2020-06-01" * @returns {String} date_netsuite "1/6/2020" */ function dateISOToNetsuite(date_iso) { var date_netsuite = ''; if (!isNullorEmpty(date_iso)) { var date_utc = new Date(date_iso); // var date_netsuite = nlapiDateToString(date_utc); var date_netsuite = format.format({ value: date_utc, type: format.Type.DATE }); } return date_netsuite; } function isNullorEmpty(strVal) { return (strVal == null || strVal == '' || strVal == 'null' || strVal == undefined || strVal == 'undefined' || strVal == '- None -'); } return { onRequest: onRequest }; });
860
[{"tag": "KEY", "value": "sha384-aJ21OjlMXNL5UyIl/XNwTMqvzeRMZH2w8c5cRVpzpU8Y5bApTppSuUkhZXN0VxHd", "start": 1577, "end": 1648}, {"tag": "KEY", "value": "sha384-aJ21OjlMXNL5UyIl/XNwTMqvzeRMZH2w8c5cRVpzpU8Y5bApTppSuUkhZXN0VxHd", "start": 8957, "end": 9028}, {"tag": "KEY", "value": "sha384-HSMxcRTRxnN+Bdg0JdbxYKrThecOKuH5zCYotlSAcp1+c8xmyTe9GYg1l9a69psu", "start": 1354, "end": 1425}, {"tag": "KEY", "value": "sha384-HSMxcRTRxnN+Bdg0JdbxYKrThecOKuH5zCYotlSAcp1+c8xmyTe9GYg1l9a69psu", "start": 8734, "end": 8805}, {"tag": "KEY", "value": "sha384-nvAa0+6Qg9clwYCGGPpDQLVpLNn0fRaROjHqs13t4Ggj3Ez50XnGQqc/r8MhnRDZ", "start": 957, "end": 1028}, {"tag": "KEY", "value": "sha384-nvAa0+6Qg9clwYCGGPpDQLVpLNn0fRaROjHqs13t4Ggj3Ez50XnGQqc/r8MhnRDZ", "start": 8337, "end": 8408}]
true
6
/** * * @NApiVersion 2.0 * @NScriptType Suitelet * * Description: Import an excel file of connote numbers to add into processed orders * @Last Modified by: Sruti Desai * */ define(['N/ui/serverWidget', 'N/email', 'N/runtime', 'N/search', 'N/record', 'N/log', 'N/redirect', 'N/format', 'N/task', 'N/file', 'N/error'], function(ui, email, runtime, search, record, log, redirect, format, task, file, error) { var baseURL = 'https://1048144.app.netsuite.com'; if (runtime.EnvType == "SANDBOX") { baseURL = 'https://1048144-sb3.app.netsuite.com'; } var zee = 0; var role = runtime.getCurrentUser().role; if (role == 1000) { //Franchisee zee = runtime.getCurrentUser().id; } function onRequest(context) { if (context.request.method === 'GET') { // Load jQuery var inlineHtml = '<script src="https://code.jquery.com/jquery-1.12.4.min.js" integrity="vqbpgud2ghvjgm1n5hdgjnn5818fzsf2" crossorigin="anonymous"></script>'; // Load Tooltip inlineHtml += '<script src="https://unpkg.com/@popperjs/core@2"></script>'; // Load Bootstrap inlineHtml += '<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/3.4.1/css/bootstrap.min.css" integrity="caf86f4uutaoxfysmf7anj01xl6sv3ps" crossorigin="anonymous">'; inlineHtml += '<script src="https://stackpath.bootstrapcdn.com/bootstrap/3.4.1/js/bootstrap.min.js" integrity="se2xy1bknelxn4y8xzxu3trosptip3q5" crossorigin="anonymous"></script>'; // Load DataTables inlineHtml += '<link rel="stylesheet" type="text/css" href="//cdn.datatables.net/1.10.21/css/jquery.dataTables.min.css">'; inlineHtml += '<script type="text/javascript" charset="utf8" src="//cdn.datatables.net/1.10.21/js/jquery.dataTables.min.js"></script>'; // Load Bootstrap-Select inlineHtml += '<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap-select@1.13.14/dist/css/bootstrap-select.min.css">'; inlineHtml += '<script src="https://cdn.jsdelivr.net/npm/bootstrap-select@1.13.14/dist/js/bootstrap-select.min.js"></script>'; // Load Netsuite stylesheet and script inlineHtml += '<link rel="stylesheet" href="https://1048144.app.netsuite.com/core/media/media.nl?id=2060796&c=1048144&h=9ee6accfd476c9cae718&_xt=.css"/>'; inlineHtml += '<script src="https://1048144.app.netsuite.com/core/media/media.nl?id=2060797&c=1048144&h=ef2cda20731d146b5e98&_xt=.js"></script>'; inlineHtml += '<link type="text/css" rel="stylesheet" href="https://1048144.app.netsuite.com/core/media/media.nl?id=2090583&c=1048144&h=a0ef6ac4e28f91203dfe&_xt=.css">'; inlineHtml += '<style>.mandatory{color:red;}</style>'; var form = ui.createForm({ title: 'MPEX Import Connote' }); inlineHtml += '<br></br>'; inlineHtml += dateFilterSection(); form.addSubmitButton({ label: 'Import Connote Numbers' }); form.addField({ id: 'upload_mpex_csv', label: 'IMPORT CONNOTE NUMBERS', type: ui.FieldType.FILE }); form.addField({ id: 'custpage_date_from', type: ui.FieldType.DATE, label: 'date_from' }).updateDisplayType({ displayType: ui.FieldDisplayType.HIDDEN }).defaultValue; form.addField({ id: 'custpage_date_to', type: ui.FieldType.DATE, label: 'date_to' }).updateDisplayType({ displayType: ui.FieldDisplayType.HIDDEN }).defaultValue; form.addField({ id: 'custpage_test', type: ui.FieldType.TEXT, label: 'date_to' }).updateDisplayType({ displayType: ui.FieldDisplayType.HIDDEN }).defaultValue; form.addField({ id: 'custpage_scheduled', type: ui.FieldType.TEXT, label: 'scheduled' }).updateDisplayType({ displayType: ui.FieldDisplayType.HIDDEN }); form.addField({ id: 'preview_table', type: ui.FieldType.INLINEHTML, label: 'preview_table' }).updateLayoutType({ layoutType: ui.FieldLayoutType.OUTSIDEBELOW }).updateBreakType({ breakType: ui.FieldBreakType.STARTROW }).defaultValue = inlineHtml; // form.addField({ // id: 'preview_table', // type: ui.FieldType.INLINEHTML, // label: 'preview_table' // }).updateLayoutType({ // layoutType: ui.FieldLayoutType.OUTSIDEBELOW // }).updateBreakType({ // breakType: ui.FieldBreakType.STARTROW // }).defaultValue = inlineHtml; form.clientScriptFileId = 4686408; //SB cl_id =, PROD cl_id = 4686408 context.response.writePage(form); } else { var fileObj = context.request.files.upload_mpex_csv; var date_from = context.request.parameters.custpage_date_from; var date_to = context.request.parameters.custpage_date_to; if (!isNullorEmpty(date_from) && !isNullorEmpty(date_to)) { date_from = formatDate(date_from); date_to = formatDate(date_to); } log.debug({ title: 'date_from', details: date_from }); log.debug({ title: 'date_to', details: date_to }); if (!isNullorEmpty(fileObj)) { fileObj.folder = 2696109; // Prod=2696109 var file_type = fileObj.fileType; if (file_type == 'CSV') { file_type == 'csv'; var file_name = 'mpex_upload' + '.' + file_type; } fileObj.name = file_name; if (file_type == 'CSV') { // Create file and upload it to the file cabinet. var f_id = fileObj.save(); } else { throw error.create({ message: 'Must be in CSV format', name: 'CSV_ERROR', notifyOff: true }); } } // CALL SCHEDULED SCRIPT var scriptTask = task.create({ taskType: task.TaskType.SCHEDULED_SCRIPT }); scriptTask.scriptId = 'customscript_ss_import_connote'; scriptTask.deploymentId = 'customdeploy_ss_import_connote'; scriptTask.params = { custscript_import_connote_file_id: f_id, custscript_import_connote_index: 0, custscript_import_connote_date_from: date_from, custscript_import_connote_date_to: date_to }; var ss_id = scriptTask.submit(); var file1 = file.load({ id: f_id }); var iterator = file1.lines.iterator(); // skip first line (header) iterator.each(function (line) { log.debug({ title: 'line', details: line }); return false; }); var numLines = 0; var zeeArr = []; iterator.each(function (line) { var csv_values = line.value.split(/,(?=(?:(?:[^"]*"){2})*[^"]*$)/); var zee_id = csv_values[1]; if (zeeArr.indexOf(zee_id) == -1) { zeeArr.push(zee_id); } numLines++; return true; }); // Load jQuery var inlineHtml = '<script src="https://code.jquery.com/jquery-1.12.4.min.js" integrity="vqbpgud2ghvjgm1n5hdgjnn5818fzsf2" crossorigin="anonymous"></script>'; // Load Tooltip inlineHtml += '<script src="https://unpkg.com/@popperjs/core@2"></script>'; // Load Bootstrap inlineHtml += '<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/3.4.1/css/bootstrap.min.css" integrity="caf86f4uutaoxfysmf7anj01xl6sv3ps" crossorigin="anonymous">'; inlineHtml += '<script src="https://stackpath.bootstrapcdn.com/bootstrap/3.4.1/js/bootstrap.min.js" integrity="se2xy1bknelxn4y8xzxu3trosptip3q5" crossorigin="anonymous"></script>'; // Load DataTables inlineHtml += '<link rel="stylesheet" type="text/css" href="//cdn.datatables.net/1.10.21/css/jquery.dataTables.min.css">'; inlineHtml += '<script type="text/javascript" charset="utf8" src="//cdn.datatables.net/1.10.21/js/jquery.dataTables.min.js"></script>'; // Load Bootstrap-Select inlineHtml += '<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap-select@1.13.14/dist/css/bootstrap-select.min.css">'; inlineHtml += '<script src="https://cdn.jsdelivr.net/npm/bootstrap-select@1.13.14/dist/js/bootstrap-select.min.js"></script>'; // Load Netsuite stylesheet and script inlineHtml += '<link rel="stylesheet" href="https://1048144.app.netsuite.com/core/media/media.nl?id=2060796&c=1048144&h=9ee6accfd476c9cae718&_xt=.css"/>'; inlineHtml += '<script src="https://1048144.app.netsuite.com/core/media/media.nl?id=2060797&c=1048144&h=ef2cda20731d146b5e98&_xt=.js"></script>'; inlineHtml += '<link type="text/css" rel="stylesheet" href="https://1048144.app.netsuite.com/core/media/media.nl?id=2090583&c=1048144&h=a0ef6ac4e28f91203dfe&_xt=.css">'; inlineHtml += '<style>.mandatory{color:red;}</style>'; var form = ui.createForm({ title: 'MPEX Product Orders (ALL ZEEs)' }); inlineHtml += '<br></br>'; inlineHtml += progressBar(); inlineHtml += dateFilterSection(); // Open Invoices Datatable inlineHtml += '<div class="form-group mpex_orders mpex_orders_table">'; inlineHtml += '<div class="row">'; inlineHtml += '<div class="col-xs-12" id="mpex_orders_dt_div">'; // It is inserted as inline html in the script mp_cl_open_ticket inlineHtml += '</div></div></div>'; form.addSubmitButton({ label: 'Import Connote Numbers' }); form.addField({ id: 'upload_mpex_csv', label: 'IMPORT CONNOTE NUMBERS', type: ui.FieldType.FILE }); form.addField({ id: 'custpage_date_from', type: ui.FieldType.DATE, label: 'date_from' }).updateDisplayType({ displayType: ui.FieldDisplayType.HIDDEN }).defaultValue = date_from; form.addField({ id: 'custpage_scheduled', type: ui.FieldType.TEXT, label: 'scheduled' }).updateDisplayType({ displayType: ui.FieldDisplayType.HIDDEN }).defaultValue = 2; form.addField({ id: 'zee_array', type: ui.FieldType.LONGTEXT, label: 'zee_array' }).updateDisplayType({ displayType: ui.FieldDisplayType.HIDDEN }).defaultValue = zeeArr; form.addField({ id: 'excel_lines', type: ui.FieldType.TEXT, label: 'excel_lines' }).updateDisplayType({ displayType: ui.FieldDisplayType.HIDDEN }).defaultValue = numLines; form.addField({ id: 'custpage_date_to', type: ui.FieldType.DATE, label: 'date_to' }).updateDisplayType({ displayType: ui.FieldDisplayType.HIDDEN }).defaultValue = date_to; form.addField({ id: 'preview_table', type: ui.FieldType.INLINEHTML, label: 'preview_table' }).updateLayoutType({ layoutType: ui.FieldLayoutType.OUTSIDEBELOW }).updateBreakType({ breakType: ui.FieldBreakType.STARTROW }).defaultValue = inlineHtml; form.clientScriptFileId = 4686408; //SB cl_id =, PROD cl_id = 4686408 context.response.writePage(form); } } /** * The date input fields to filter the invoices. * Even if the parameters `date_from` and `date_to` are defined, they can't be initiated in the HTML code. * They are initiated with jQuery in the `pageInit()` function. * @return {String} `inlineQty` */ function dateFilterSection() { var inlineQty = '<div class="form-group container total_amount_section">'; inlineQty += '<div class="row">'; inlineQty += '<div class="col-xs-18 heading1"><h4><span style="background-color:#379E8F" class="label label-default col-xs-12">DATE FILTER</span></h4></div>'; inlineQty += '</div>'; inlineQty += '</div>'; inlineQty += '<div class="form-group date_filter_section">'; inlineQty += '<div class="row">'; // Date from field inlineQty += '<div class="col-xs-6 date_from">'; inlineQty += '<div class="input-group">'; inlineQty += '<span class="input-group-addon" id="date_from_text">From</span>'; inlineQty += '<input id="date_from" class="form-control date_from" type="date"/>'; inlineQty += '</div></div>'; // Date to field inlineQty += '<div class="col-xs-6 date_to">'; inlineQty += '<div class="input-group">'; inlineQty += '<span class="input-group-addon" id="date_to_text">To</span>'; inlineQty += '<input id="date_to" class="form-control date_to" type="date">'; inlineQty += '</div></div></div></div>'; return inlineQty; } /** * Display the progress bar. Initialized at 0, with the maximum value as the number of records that will be moved. * Uses Bootstrap : https://www.w3schools.com/bootstrap/bootstrap_progressbars.asp * @param {String} nb_records_total The number of records that will be moved * @return {String} inlineQty : The inline HTML string of the progress bar. */ function progressBar() { var inlineQty = '<div class="progress ">'; inlineQty += '<div class="progress-bar progress-bar-striped progress-bar-warning" id="progress-records" role="progressbar" aria-valuenow="0" style="width:0%">0%</div>'; inlineQty += '</div>'; return inlineQty; } function formatDate(testDate){ var responseDate=format.format({value:testDate,type:format.Type.DATE}); return responseDate; } /** * Used to pass the values of `date_from` and `date_to` between the scripts and to Netsuite for the records and the search. * @param {String} date_iso "2020-06-01" * @returns {String} date_netsuite "1/6/2020" */ function dateISOToNetsuite(date_iso) { var date_netsuite = ''; if (!isNullorEmpty(date_iso)) { var date_utc = new Date(date_iso); // var date_netsuite = nlapiDateToString(date_utc); var date_netsuite = format.format({ value: date_utc, type: format.Type.DATE }); } return date_netsuite; } function isNullorEmpty(strVal) { return (strVal == null || strVal == '' || strVal == 'null' || strVal == undefined || strVal == 'undefined' || strVal == '- None -'); } return { onRequest: onRequest }; });
true
/** * * @NApiVersion 2.0 * @NScriptType Suitelet * * Description: Import an excel file of connote numbers to add into processed orders * @Last Modified by: Sruti Desai * */ define(['N/ui/serverWidget', 'N/email', 'N/runtime', 'N/search', 'N/record', 'N/log', 'N/redirect', 'N/format', 'N/task', 'N/file', 'N/error'], function(ui, email, runtime, search, record, log, redirect, format, task, file, error) { var baseURL = 'https://1048144.app.netsuite.com'; if (runtime.EnvType == "SANDBOX") { baseURL = 'https://1048144-sb3.app.netsuite.com'; } var zee = 0; var role = runtime.getCurrentUser().role; if (role == 1000) { //Franchisee zee = runtime.getCurrentUser().id; } function onRequest(context) { if (context.request.method === 'GET') { // Load jQuery var inlineHtml = '<script src="https://code.jquery.com/jquery-1.12.4.min.js" integrity="PI:KEY:vqbpgud2ghvjgm1n5hdgjnn5818fzsf2END_PI" crossorigin="anonymous"></script>'; // Load Tooltip inlineHtml += '<script src="https://unpkg.com/@popperjs/core@2"></script>'; // Load Bootstrap inlineHtml += '<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/3.4.1/css/bootstrap.min.css" integrity="PI:KEY:caf86f4uutaoxfysmf7anj01xl6sv3psEND_PI" crossorigin="anonymous">'; inlineHtml += '<script src="https://stackpath.bootstrapcdn.com/bootstrap/3.4.1/js/bootstrap.min.js" integrity="PI:KEY:se2xy1bknelxn4y8xzxu3trosptip3q5END_PI" crossorigin="anonymous"></script>'; // Load DataTables inlineHtml += '<link rel="stylesheet" type="text/css" href="//cdn.datatables.net/1.10.21/css/jquery.dataTables.min.css">'; inlineHtml += '<script type="text/javascript" charset="utf8" src="//cdn.datatables.net/1.10.21/js/jquery.dataTables.min.js"></script>'; // Load Bootstrap-Select inlineHtml += '<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap-select@1.13.14/dist/css/bootstrap-select.min.css">'; inlineHtml += '<script src="https://cdn.jsdelivr.net/npm/bootstrap-select@1.13.14/dist/js/bootstrap-select.min.js"></script>'; // Load Netsuite stylesheet and script inlineHtml += '<link rel="stylesheet" href="https://1048144.app.netsuite.com/core/media/media.nl?id=2060796&c=1048144&h=9ee6accfd476c9cae718&_xt=.css"/>'; inlineHtml += '<script src="https://1048144.app.netsuite.com/core/media/media.nl?id=2060797&c=1048144&h=ef2cda20731d146b5e98&_xt=.js"></script>'; inlineHtml += '<link type="text/css" rel="stylesheet" href="https://1048144.app.netsuite.com/core/media/media.nl?id=2090583&c=1048144&h=a0ef6ac4e28f91203dfe&_xt=.css">'; inlineHtml += '<style>.mandatory{color:red;}</style>'; var form = ui.createForm({ title: 'MPEX Import Connote' }); inlineHtml += '<br></br>'; inlineHtml += dateFilterSection(); form.addSubmitButton({ label: 'Import Connote Numbers' }); form.addField({ id: 'upload_mpex_csv', label: 'IMPORT CONNOTE NUMBERS', type: ui.FieldType.FILE }); form.addField({ id: 'custpage_date_from', type: ui.FieldType.DATE, label: 'date_from' }).updateDisplayType({ displayType: ui.FieldDisplayType.HIDDEN }).defaultValue; form.addField({ id: 'custpage_date_to', type: ui.FieldType.DATE, label: 'date_to' }).updateDisplayType({ displayType: ui.FieldDisplayType.HIDDEN }).defaultValue; form.addField({ id: 'custpage_test', type: ui.FieldType.TEXT, label: 'date_to' }).updateDisplayType({ displayType: ui.FieldDisplayType.HIDDEN }).defaultValue; form.addField({ id: 'custpage_scheduled', type: ui.FieldType.TEXT, label: 'scheduled' }).updateDisplayType({ displayType: ui.FieldDisplayType.HIDDEN }); form.addField({ id: 'preview_table', type: ui.FieldType.INLINEHTML, label: 'preview_table' }).updateLayoutType({ layoutType: ui.FieldLayoutType.OUTSIDEBELOW }).updateBreakType({ breakType: ui.FieldBreakType.STARTROW }).defaultValue = inlineHtml; // form.addField({ // id: 'preview_table', // type: ui.FieldType.INLINEHTML, // label: 'preview_table' // }).updateLayoutType({ // layoutType: ui.FieldLayoutType.OUTSIDEBELOW // }).updateBreakType({ // breakType: ui.FieldBreakType.STARTROW // }).defaultValue = inlineHtml; form.clientScriptFileId = 4686408; //SB cl_id =, PROD cl_id = 4686408 context.response.writePage(form); } else { var fileObj = context.request.files.upload_mpex_csv; var date_from = context.request.parameters.custpage_date_from; var date_to = context.request.parameters.custpage_date_to; if (!isNullorEmpty(date_from) && !isNullorEmpty(date_to)) { date_from = formatDate(date_from); date_to = formatDate(date_to); } log.debug({ title: 'date_from', details: date_from }); log.debug({ title: 'date_to', details: date_to }); if (!isNullorEmpty(fileObj)) { fileObj.folder = 2696109; // Prod=2696109 var file_type = fileObj.fileType; if (file_type == 'CSV') { file_type == 'csv'; var file_name = 'mpex_upload' + '.' + file_type; } fileObj.name = file_name; if (file_type == 'CSV') { // Create file and upload it to the file cabinet. var f_id = fileObj.save(); } else { throw error.create({ message: 'Must be in CSV format', name: 'CSV_ERROR', notifyOff: true }); } } // CALL SCHEDULED SCRIPT var scriptTask = task.create({ taskType: task.TaskType.SCHEDULED_SCRIPT }); scriptTask.scriptId = 'customscript_ss_import_connote'; scriptTask.deploymentId = 'customdeploy_ss_import_connote'; scriptTask.params = { custscript_import_connote_file_id: f_id, custscript_import_connote_index: 0, custscript_import_connote_date_from: date_from, custscript_import_connote_date_to: date_to }; var ss_id = scriptTask.submit(); var file1 = file.load({ id: f_id }); var iterator = file1.lines.iterator(); // skip first line (header) iterator.each(function (line) { log.debug({ title: 'line', details: line }); return false; }); var numLines = 0; var zeeArr = []; iterator.each(function (line) { var csv_values = line.value.split(/,(?=(?:(?:[^"]*"){2})*[^"]*$)/); var zee_id = csv_values[1]; if (zeeArr.indexOf(zee_id) == -1) { zeeArr.push(zee_id); } numLines++; return true; }); // Load jQuery var inlineHtml = '<script src="https://code.jquery.com/jquery-1.12.4.min.js" integrity="PI:KEY:vqbpgud2ghvjgm1n5hdgjnn5818fzsf2END_PI" crossorigin="anonymous"></script>'; // Load Tooltip inlineHtml += '<script src="https://unpkg.com/@popperjs/core@2"></script>'; // Load Bootstrap inlineHtml += '<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/3.4.1/css/bootstrap.min.css" integrity="PI:KEY:caf86f4uutaoxfysmf7anj01xl6sv3psEND_PI" crossorigin="anonymous">'; inlineHtml += '<script src="https://stackpath.bootstrapcdn.com/bootstrap/3.4.1/js/bootstrap.min.js" integrity="PI:KEY:se2xy1bknelxn4y8xzxu3trosptip3q5END_PI" crossorigin="anonymous"></script>'; // Load DataTables inlineHtml += '<link rel="stylesheet" type="text/css" href="//cdn.datatables.net/1.10.21/css/jquery.dataTables.min.css">'; inlineHtml += '<script type="text/javascript" charset="utf8" src="//cdn.datatables.net/1.10.21/js/jquery.dataTables.min.js"></script>'; // Load Bootstrap-Select inlineHtml += '<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap-select@1.13.14/dist/css/bootstrap-select.min.css">'; inlineHtml += '<script src="https://cdn.jsdelivr.net/npm/bootstrap-select@1.13.14/dist/js/bootstrap-select.min.js"></script>'; // Load Netsuite stylesheet and script inlineHtml += '<link rel="stylesheet" href="https://1048144.app.netsuite.com/core/media/media.nl?id=2060796&c=1048144&h=9ee6accfd476c9cae718&_xt=.css"/>'; inlineHtml += '<script src="https://1048144.app.netsuite.com/core/media/media.nl?id=2060797&c=1048144&h=ef2cda20731d146b5e98&_xt=.js"></script>'; inlineHtml += '<link type="text/css" rel="stylesheet" href="https://1048144.app.netsuite.com/core/media/media.nl?id=2090583&c=1048144&h=a0ef6ac4e28f91203dfe&_xt=.css">'; inlineHtml += '<style>.mandatory{color:red;}</style>'; var form = ui.createForm({ title: 'MPEX Product Orders (ALL ZEEs)' }); inlineHtml += '<br></br>'; inlineHtml += progressBar(); inlineHtml += dateFilterSection(); // Open Invoices Datatable inlineHtml += '<div class="form-group mpex_orders mpex_orders_table">'; inlineHtml += '<div class="row">'; inlineHtml += '<div class="col-xs-12" id="mpex_orders_dt_div">'; // It is inserted as inline html in the script mp_cl_open_ticket inlineHtml += '</div></div></div>'; form.addSubmitButton({ label: 'Import Connote Numbers' }); form.addField({ id: 'upload_mpex_csv', label: 'IMPORT CONNOTE NUMBERS', type: ui.FieldType.FILE }); form.addField({ id: 'custpage_date_from', type: ui.FieldType.DATE, label: 'date_from' }).updateDisplayType({ displayType: ui.FieldDisplayType.HIDDEN }).defaultValue = date_from; form.addField({ id: 'custpage_scheduled', type: ui.FieldType.TEXT, label: 'scheduled' }).updateDisplayType({ displayType: ui.FieldDisplayType.HIDDEN }).defaultValue = 2; form.addField({ id: 'zee_array', type: ui.FieldType.LONGTEXT, label: 'zee_array' }).updateDisplayType({ displayType: ui.FieldDisplayType.HIDDEN }).defaultValue = zeeArr; form.addField({ id: 'excel_lines', type: ui.FieldType.TEXT, label: 'excel_lines' }).updateDisplayType({ displayType: ui.FieldDisplayType.HIDDEN }).defaultValue = numLines; form.addField({ id: 'custpage_date_to', type: ui.FieldType.DATE, label: 'date_to' }).updateDisplayType({ displayType: ui.FieldDisplayType.HIDDEN }).defaultValue = date_to; form.addField({ id: 'preview_table', type: ui.FieldType.INLINEHTML, label: 'preview_table' }).updateLayoutType({ layoutType: ui.FieldLayoutType.OUTSIDEBELOW }).updateBreakType({ breakType: ui.FieldBreakType.STARTROW }).defaultValue = inlineHtml; form.clientScriptFileId = 4686408; //SB cl_id =, PROD cl_id = 4686408 context.response.writePage(form); } } /** * The date input fields to filter the invoices. * Even if the parameters `date_from` and `date_to` are defined, they can't be initiated in the HTML code. * They are initiated with jQuery in the `pageInit()` function. * @return {String} `inlineQty` */ function dateFilterSection() { var inlineQty = '<div class="form-group container total_amount_section">'; inlineQty += '<div class="row">'; inlineQty += '<div class="col-xs-18 heading1"><h4><span style="background-color:#379E8F" class="label label-default col-xs-12">DATE FILTER</span></h4></div>'; inlineQty += '</div>'; inlineQty += '</div>'; inlineQty += '<div class="form-group date_filter_section">'; inlineQty += '<div class="row">'; // Date from field inlineQty += '<div class="col-xs-6 date_from">'; inlineQty += '<div class="input-group">'; inlineQty += '<span class="input-group-addon" id="date_from_text">From</span>'; inlineQty += '<input id="date_from" class="form-control date_from" type="date"/>'; inlineQty += '</div></div>'; // Date to field inlineQty += '<div class="col-xs-6 date_to">'; inlineQty += '<div class="input-group">'; inlineQty += '<span class="input-group-addon" id="date_to_text">To</span>'; inlineQty += '<input id="date_to" class="form-control date_to" type="date">'; inlineQty += '</div></div></div></div>'; return inlineQty; } /** * Display the progress bar. Initialized at 0, with the maximum value as the number of records that will be moved. * Uses Bootstrap : https://www.w3schools.com/bootstrap/bootstrap_progressbars.asp * @param {String} nb_records_total The number of records that will be moved * @return {String} inlineQty : The inline HTML string of the progress bar. */ function progressBar() { var inlineQty = '<div class="progress ">'; inlineQty += '<div class="progress-bar progress-bar-striped progress-bar-warning" id="progress-records" role="progressbar" aria-valuenow="0" style="width:0%">0%</div>'; inlineQty += '</div>'; return inlineQty; } function formatDate(testDate){ var responseDate=format.format({value:testDate,type:format.Type.DATE}); return responseDate; } /** * Used to pass the values of `date_from` and `date_to` between the scripts and to Netsuite for the records and the search. * @param {String} date_iso "2020-06-01" * @returns {String} date_netsuite "1/6/2020" */ function dateISOToNetsuite(date_iso) { var date_netsuite = ''; if (!isNullorEmpty(date_iso)) { var date_utc = new Date(date_iso); // var date_netsuite = nlapiDateToString(date_utc); var date_netsuite = format.format({ value: date_utc, type: format.Type.DATE }); } return date_netsuite; } function isNullorEmpty(strVal) { return (strVal == null || strVal == '' || strVal == 'null' || strVal == undefined || strVal == 'undefined' || strVal == '- None -'); } return { onRequest: onRequest }; });
/** *@NApiVersion 2.0 *@NScriptType Suitelet * * Module Description - * * NSVersion Date Author * 2.00 2020-11-26 13:12:36 Ravija Maheshwari */ define(['N/ui/serverWidget', 'N/email', 'N/runtime', 'N/search', 'N/record', 'N/http', 'N/log', 'N/redirect', 'N/format', 'N/currentRecord'], function(ui, email, runtime, search, record, http, log, redirect, format, currentRecord) { function onRequest(context) { //Setup var baseURL = 'https://system.na2.netsuite.com'; if (runtime.EnvType == "SANDBOX") { baseURL = 'https://system.sandbox.netsuite.com'; } var zee = 0; var role = runtime.getCurrentUser().role; if (role == 1000) { zee = runtime.getCurrentUser().id; } else if (role == 3) { //Administrator zee = 6; //test } else if (role == 1032) { // System Support zee = 425904; //test-AR } if(context.request.method === 'GET'){ var form = ui.createForm({ title: 'Cancel Scheduled Price Change - Customer List' }); //Load Jquery var inlinehtml2 = '<script src="https://code.jquery.com/jquery-1.12.4.min.js" integrity="sha384-nvAa0+6Qg9clwYCGGPpDQLVpLNn0fRaROjHqs13t4Ggj3Ez50XnGQqc/r8MhnRDZ" crossorigin="anonymous"></script>'; // Load DataTables inlinehtml2 += '<link rel="stylesheet" type="text/css" href="//cdn.datatables.net/1.10.21/css/jquery.dataTables.min.css">'; inlinehtml2 += '<script type="text/javascript" charset="utf8" src="//cdn.datatables.net/1.10.21/js/jquery.dataTables.min.js"></script>'; // Load Bootstrap inlinehtml2 += '<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/3.4.1/css/bootstrap.min.css" integrity="sha384-HSMxcRTRxnN+Bdg0JdbxYKrThecOKuH5zCYotlSAcp1+c8xmyTe9GYg1l9a69psu" crossorigin="anonymous">'; inlinehtml2 += '<script src="https://stackpath.bootstrapcdn.com/bootstrap/3.4.1/js/bootstrap.min.js" integrity="sha384-aJ21OjlMXNL5UyIl/XNwTMqvzeRMZH2w8c5cRVpzpU8Y5bApTppSuUkhZXN0VxHd" crossorigin="anonymous"></script>'; // Load Netsuite stylesheet and script inlinehtml2 += '<link rel="stylesheet" href="https://1048144.app.netsuite.com/core/media/media.nl?id=2060796&c=1048144&h=9ee6accfd476c9cae718&_xt=.css"/>'; inlinehtml2 += '<script src="https://1048144.app.netsuite.com/core/media/media.nl?id=2060797&c=1048144&h=ef2cda20731d146b5e98&_xt=.js"></script>'; inlinehtml2 += '<link type="text/css" rel="stylesheet" href="https://1048144.app.netsuite.com/core/media/media.nl?id=2090583&c=1048144&h=a0ef6ac4e28f91203dfe&_xt=.css">'; inlinehtml2 += '<style>.mandatory{color:red;}</style>'; inlinehtml2 += '<link href="//netdna.bootstrapcdn.com/bootstrap/3.3.2/css/bootstrap.min.css" rel="stylesheet"><script src="//netdna.bootstrapcdn.com/bootstrap/3.3.2/js/bootstrap.min.js"></script><link rel="stylesheet" href="https://1048144.app.netsuite.com/core/media/media.nl?id=2060796&c=1048144&h=9ee6accfd476c9cae718&_xt=.css"/><script src="https://1048144.app.netsuite.com/core/media/media.nl?id=2060797&c=1048144&h=ef2cda20731d146b5e98&_xt=.js"></script><link type="text/css" rel="stylesheet" href="https://1048144.app.netsuite.com/core/media/media.nl?id=2090583&c=1048144&h=a0ef6ac4e28f91203dfe&_xt=.css">'; //Instructions inlinehtml2 += '<button type="button" class="btn btn-sm btn-info instruction_button" data-toggle="collapse" data-target="#demo">Click for Instructions</button><div id="demo" style="background-color: #cfeefc !important;border: 1px solid #417ed9;padding: 10px 10px 10px 20px;width:96%;position:absolute; z-index: 9999;" class="collapse"><b><u>IMPORTANT INSTRUCTIONS:</u></b><ul><li>Functionalities available on the Customer listing/table:<ul><li><b>Sort</b><ul><li>Click on column headers to sort customer list according to the values in the columns. This is default to "Customer Name".</li><li>Hold "Shift" and click another column to sort according to multiple columns.</li></ul></li><li><b>Search</b><ul><li>You can search for specific customer by typing into the "Search" field</li></ul></li></ul></li><li>Clickable Actions available per customer:</li><ul><li><button class="btn-xs btn-default" disabled>UPLOAD SCF</button> - <ul><li>Available for customers with missing Service Commencement Forms (SCF) in the system. You will need to upload the latest signed SCF for each relevant customers which outlines the service commencement date along with the Service(s) and Price(s).</li></ul></li><li><button class="btn-xs btn-warning" disabled>REVIEW</button> / <button class="btn-xs btn-primary" disabled>EDIT</button> - <ul><li>Review or Edit customer details (eg. Addresses, Service and Pricing, Packages) to set them up for Run Digitalisation.</li><li>Any service added needs to be scheduled on the Run Scheduler.</li><li>Any service deleted will be removed from your run. It will no longer appear on the calendar and app.</li></ul></li><li><button class="btn-xs btn-danger" disabled>COVID CANCEL</button> - <ul><li>You may Cancel non-active customers providing details and reasons around the Cancellation.</li><li>You <b><u>DO NOT NEED</u></b> to cancel customers with <b><u>Adhoc</u></b> arrangements.</li></ul></li><li><button class="btn-xs btn-default" disabled>Duplicate COMMREG</button> - <ul><li>Please contact <b><u>Head Office</u></b> if you see this Action against any customer</li></ul></li></ul></li></ul></ul></div>'; //If role is Admin or System Support, add dropdown to select zee if (role != 1000) { inlinehtml2 += zeeDropDown(context); } //Set zee if one is chosen if (!isNullorEmpty(context.request.parameters.zee)) { zee = context.request.parameters.zee; } inlinehtml2 += populateCustomerTable(zee, baseURL); //Set inlineQty for Instruction button and zee dropdown form.addField({ id: 'preview_table', type: ui.FieldType.INLINEHTML, label: 'preview table' }).defaultValue = inlinehtml2; form.clientScriptFileId = 4563740; context.response.writePage(form); } } /** * Returns inlineHtml which contains the dropdown to choose zees * @param {} context */ function zeeDropDown(context){ var inlineHtml = '<div class="col-xs-12 admin_section" margin-top:30px "><b>Select Zee</b> <select class="form-control zee_dropdown" >'; //WS Edit: Updated Search to SMC Franchisee (exc Old/Inactives) //Search: SMC - Franchisees var searched_zee = search.load({ type: search.Type.PARTNER, id: 'customsearch_smc_franchisee' }); var resultSet_zee = searched_zee.run(); var count_zee = 0; var zee_id; inlineHtml += '<option value=""></option>' resultSet_zee.each(function(searchResult_zee) { zee_id = searchResult_zee.getValue({name: 'internalid'}); // WS Edit: Updated entityid to companyname zee_name = searchResult_zee.getValue({name:'companyname'}); if (context.request.parameters.zee == zee_id) { inlineHtml += '<option value="' + zee_id + '" selected="selected">' + zee_name + '</option>'; } else { inlineHtml += '<option value="' + zee_id + '">' + zee_name + '</option>'; } return true; }); inlineHtml += '</select></div>'; return inlineHtml; } function populateCustomerTable(zee, baseURL){ var inlineQty = '<style> table#customer {font-size: 14px;text-align: center;border: none; font-weight: bold;} table th{text-align: center;} </style>'; inlineQty += '<div class="form-group container-fluid customers_preview_section">'; inlineQty += '<table cellpadding="15" id="customers-preview" class="table table-responsive table-striped customer tablesorter" cellspacing="0">'; inlineQty += '<thead style="color: white;background-color: #607799;">'; inlineQty += '<tr class="text-center">'; inlineQty += '<th scope="col">Review Complete</th>'; inlineQty += '<th scope="col">ID</th>'; inlineQty += '<th scope="col">Customer Name</th>'; inlineQty += '<th scope="col">Date of Last price Increase</th>'; inlineQty += '<th scope="col">Action</th>'; inlineQty += '</tr>'; inlineQty += '</thead>'; inlineQty += '<tbody>'; /** * Description - Get the list of Customer that have Trial or Signed Status for a particular zee */ //Load customer record var zeeRecord = record.load({ type: record.Type.PARTNER, id: zee, isDynamic: true }); var name = zeeRecord.getValue({fieldId: 'companyname'}); log.debug({ title: 'zee rec name', details: name }); //Search: SMC - Customer var customerSearch = search.load({ type: search.Type.CUSTOMER, id: 'customsearch_smc_customer' }); var filter = search.createFilter({ name:'partner', join: null, operator: search.Operator.ANYOF, values: zee, }); customerSearch.filters.push(filter); var resultSetCustomer = customerSearch.run(); resultSetCustomer.each(function(searchResult){ log.debug({ title: 'search result', details: searchResult }); var custid = searchResult.getValue({ name: 'internalid', join: null, summary: search.Summary.GROUP }); var entityid = searchResult.getValue({ name: 'entityid', join: null, summary: search.Summary.GROUP }); var companyname = searchResult.getValue({ name: 'companyname', join: null, summary: search.Summary.GROUP }); var last_price_increase = searchResult.getValue({ name: 'custentity_date_of_last_price_increase', join: null, summary: search.Summary.GROUP }); //Retrieve column values to Identify Reviewed Services and Correct CommReg var serviceCount = searchResult.getValue({ name: 'formulanumeric', join: null, summary: search.Summary.MAX }); //Retrieve column values to Identify Reviewed Services and Correct CommReg //Count of Reviewed Services var serviceCount = searchResult.getValue({ name: 'formulanumeric', join: null, summary: search.Summary.MAX }); //Count of Correct CommReg var commRegCount = searchResult.getValue({ name: 'formulacurrency', join: null, summary: search.Summary.COUNT }); if (commRegCount == 0) { inlineQty += '<tr><td></td><td><a href="' + baseURL + '/app/common/entity/custjob.nl?id=' + custid + '"><p style="text-align:left;">' + entityid + '</p></a></td><td ><p style="text-align:left;">' + companyname + '</p></td><td>' + last_price_increase + '</td><td><div class="row"><div class="col-sm-6"><input type="button" class="commRegUpload form-control btn-default" id="commRegUpload_'+custid+'" value="UPLOAD SCF"></div><div class="col-sm-6"><input type="button" class="form-control btn-danger cancel_customer" value="CANCEL" id="cancel_customer_'+custid+'"></div></div></td></tr>'; } else if (commRegCount > 1) { inlineQty += '<tr><td></td><td><a href="' + baseURL + '/app/common/entity/custjob.nl?id=' + custid + '"><p style="text-align:left;">' + entityid + '</p></a></td><td ><p style="text-align:left;">' + companyname + '</p></td><td>' + last_price_increase + '</td><td><div class="row"><div class="col-sm-6"><input type="button" class="form-control btn-default" value="Duplicate COMMREG"></div><div class="col-sm-6"><input type="button" class="form-control btn-danger cancel_customer" value="CANCEL" id="cancel_customer_'+custid+'"></div></div></td></tr>'; } else if (serviceCount == 0) { //If no service record present for customer, Review button will be shown inlineQty += '<tr><td></td><td><a href="' + baseURL + '/app/common/entity/custjob.nl?id=' + custid + '"><p style="text-align:left;">' + entityid + '</p></a></td><td><p style="text-align:left;">' + companyname + '</p></td><td>' + last_price_increase + '</td><td><div class="row"><div class="col-sm-6"><input type="button" class="review_customer form-control btn-warning" value="REVIEW" id="review_customer_'+custid+'" ></div><div class="col-sm-6"><input type="button" class="form-control btn-danger cancel_customer" value="CANCEL" id="cancel_customer_'+custid+'"></div></div></td></tr>'; } else { //If service record is present for customer, Edit button is shown inlineQty += '<tr class="dynatable-editable"><td style="text-align: center;"><img src="https://1048144.app.netsuite.com/core/media/media.nl?id=1990778&c=1048144&h=e7f4f60576de531265f7" height="25" width="25"></td><td><a href="' + baseURL + '/app/common/entity/custjob.nl?id=' + custid + '"><p style="text-align:left;">' + entityid + '</p></a></td><td><p style="text-align:left;">' + companyname + '</p></td><td>' + last_price_increase + '</td><td><div class="row"><div class="col-sm-6"><input type="button" class="edit_customer form-control btn-primary" value="EDIT" id="edit_customer_'+custid+'"></div><div class="col-sm-6"><input type="button" class="form-control btn-danger cancel_customer" value="CANCEL" id="cancel_customer_'+custid+'"></div></div></td></tr>'; } return true; }); inlineQty += '</tbody>'; inlineQty += '</table><br/>'; return inlineQty; } /** * Is Null or Empty. * * @param {Object} strVal */ function isNullorEmpty(strVal) { return (strVal == null || strVal == '' || strVal == 'null' || strVal == undefined || strVal == 'undefined' || strVal == '- None -'); } return { onRequest: onRequest }; });
1,116
[{"tag": "KEY", "value": "sha384-aJ21OjlMXNL5UyIl/XNwTMqvzeRMZH2w8c5cRVpzpU8Y5bApTppSuUkhZXN0VxHd", "start": 2110, "end": 2181}, {"tag": "KEY", "value": "sha384-HSMxcRTRxnN+Bdg0JdbxYKrThecOKuH5zCYotlSAcp1+c8xmyTe9GYg1l9a69psu", "start": 1886, "end": 1957}, {"tag": "KEY", "value": "sha384-nvAa0+6Qg9clwYCGGPpDQLVpLNn0fRaROjHqs13t4Ggj3Ez50XnGQqc/r8MhnRDZ", "start": 1287, "end": 1358}]
true
3
/** *@NApiVersion 2.0 *@NScriptType Suitelet * * Module Description - * * NSVersion Date Author * 2.00 2020-11-26 13:12:36 Ravija Maheshwari */ define(['N/ui/serverWidget', 'N/email', 'N/runtime', 'N/search', 'N/record', 'N/http', 'N/log', 'N/redirect', 'N/format', 'N/currentRecord'], function(ui, email, runtime, search, record, http, log, redirect, format, currentRecord) { function onRequest(context) { //Setup var baseURL = 'https://system.na2.netsuite.com'; if (runtime.EnvType == "SANDBOX") { baseURL = 'https://system.sandbox.netsuite.com'; } var zee = 0; var role = runtime.getCurrentUser().role; if (role == 1000) { zee = runtime.getCurrentUser().id; } else if (role == 3) { //Administrator zee = 6; //test } else if (role == 1032) { // System Support zee = 425904; //test-AR } if(context.request.method === 'GET'){ var form = ui.createForm({ title: 'Cancel Scheduled Price Change - Customer List' }); //Load Jquery var inlinehtml2 = '<script src="https://code.jquery.com/jquery-1.12.4.min.js" integrity="vqbpgud2ghvjgm1n5hdgjnn5818fzsf2" crossorigin="anonymous"></script>'; // Load DataTables inlinehtml2 += '<link rel="stylesheet" type="text/css" href="//cdn.datatables.net/1.10.21/css/jquery.dataTables.min.css">'; inlinehtml2 += '<script type="text/javascript" charset="utf8" src="//cdn.datatables.net/1.10.21/js/jquery.dataTables.min.js"></script>'; // Load Bootstrap inlinehtml2 += '<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/3.4.1/css/bootstrap.min.css" integrity="9jnerlff23u8ed01np9g6ysbhsh0dvcs" crossorigin="anonymous">'; inlinehtml2 += '<script src="https://stackpath.bootstrapcdn.com/bootstrap/3.4.1/js/bootstrap.min.js" integrity="vqbpgud2ghvjgm1n5hdgjnn5818fzsf2" crossorigin="anonymous"></script>'; // Load Netsuite stylesheet and script inlinehtml2 += '<link rel="stylesheet" href="https://1048144.app.netsuite.com/core/media/media.nl?id=2060796&c=1048144&h=9ee6accfd476c9cae718&_xt=.css"/>'; inlinehtml2 += '<script src="https://1048144.app.netsuite.com/core/media/media.nl?id=2060797&c=1048144&h=ef2cda20731d146b5e98&_xt=.js"></script>'; inlinehtml2 += '<link type="text/css" rel="stylesheet" href="https://1048144.app.netsuite.com/core/media/media.nl?id=2090583&c=1048144&h=a0ef6ac4e28f91203dfe&_xt=.css">'; inlinehtml2 += '<style>.mandatory{color:red;}</style>'; inlinehtml2 += '<link href="//netdna.bootstrapcdn.com/bootstrap/3.3.2/css/bootstrap.min.css" rel="stylesheet"><script src="//netdna.bootstrapcdn.com/bootstrap/3.3.2/js/bootstrap.min.js"></script><link rel="stylesheet" href="https://1048144.app.netsuite.com/core/media/media.nl?id=2060796&c=1048144&h=9ee6accfd476c9cae718&_xt=.css"/><script src="https://1048144.app.netsuite.com/core/media/media.nl?id=2060797&c=1048144&h=ef2cda20731d146b5e98&_xt=.js"></script><link type="text/css" rel="stylesheet" href="https://1048144.app.netsuite.com/core/media/media.nl?id=2090583&c=1048144&h=a0ef6ac4e28f91203dfe&_xt=.css">'; //Instructions inlinehtml2 += '<button type="button" class="btn btn-sm btn-info instruction_button" data-toggle="collapse" data-target="#demo">Click for Instructions</button><div id="demo" style="background-color: #cfeefc !important;border: 1px solid #417ed9;padding: 10px 10px 10px 20px;width:96%;position:absolute; z-index: 9999;" class="collapse"><b><u>IMPORTANT INSTRUCTIONS:</u></b><ul><li>Functionalities available on the Customer listing/table:<ul><li><b>Sort</b><ul><li>Click on column headers to sort customer list according to the values in the columns. This is default to "Customer Name".</li><li>Hold "Shift" and click another column to sort according to multiple columns.</li></ul></li><li><b>Search</b><ul><li>You can search for specific customer by typing into the "Search" field</li></ul></li></ul></li><li>Clickable Actions available per customer:</li><ul><li><button class="btn-xs btn-default" disabled>UPLOAD SCF</button> - <ul><li>Available for customers with missing Service Commencement Forms (SCF) in the system. You will need to upload the latest signed SCF for each relevant customers which outlines the service commencement date along with the Service(s) and Price(s).</li></ul></li><li><button class="btn-xs btn-warning" disabled>REVIEW</button> / <button class="btn-xs btn-primary" disabled>EDIT</button> - <ul><li>Review or Edit customer details (eg. Addresses, Service and Pricing, Packages) to set them up for Run Digitalisation.</li><li>Any service added needs to be scheduled on the Run Scheduler.</li><li>Any service deleted will be removed from your run. It will no longer appear on the calendar and app.</li></ul></li><li><button class="btn-xs btn-danger" disabled>COVID CANCEL</button> - <ul><li>You may Cancel non-active customers providing details and reasons around the Cancellation.</li><li>You <b><u>DO NOT NEED</u></b> to cancel customers with <b><u>Adhoc</u></b> arrangements.</li></ul></li><li><button class="btn-xs btn-default" disabled>Duplicate COMMREG</button> - <ul><li>Please contact <b><u>Head Office</u></b> if you see this Action against any customer</li></ul></li></ul></li></ul></ul></div>'; //If role is Admin or System Support, add dropdown to select zee if (role != 1000) { inlinehtml2 += zeeDropDown(context); } //Set zee if one is chosen if (!isNullorEmpty(context.request.parameters.zee)) { zee = context.request.parameters.zee; } inlinehtml2 += populateCustomerTable(zee, baseURL); //Set inlineQty for Instruction button and zee dropdown form.addField({ id: 'preview_table', type: ui.FieldType.INLINEHTML, label: 'preview table' }).defaultValue = inlinehtml2; form.clientScriptFileId = 4563740; context.response.writePage(form); } } /** * Returns inlineHtml which contains the dropdown to choose zees * @param {} context */ function zeeDropDown(context){ var inlineHtml = '<div class="col-xs-12 admin_section" margin-top:30px "><b>Select Zee</b> <select class="form-control zee_dropdown" >'; //WS Edit: Updated Search to SMC Franchisee (exc Old/Inactives) //Search: SMC - Franchisees var searched_zee = search.load({ type: search.Type.PARTNER, id: 'customsearch_smc_franchisee' }); var resultSet_zee = searched_zee.run(); var count_zee = 0; var zee_id; inlineHtml += '<option value=""></option>' resultSet_zee.each(function(searchResult_zee) { zee_id = searchResult_zee.getValue({name: 'internalid'}); // WS Edit: Updated entityid to companyname zee_name = searchResult_zee.getValue({name:'companyname'}); if (context.request.parameters.zee == zee_id) { inlineHtml += '<option value="' + zee_id + '" selected="selected">' + zee_name + '</option>'; } else { inlineHtml += '<option value="' + zee_id + '">' + zee_name + '</option>'; } return true; }); inlineHtml += '</select></div>'; return inlineHtml; } function populateCustomerTable(zee, baseURL){ var inlineQty = '<style> table#customer {font-size: 14px;text-align: center;border: none; font-weight: bold;} table th{text-align: center;} </style>'; inlineQty += '<div class="form-group container-fluid customers_preview_section">'; inlineQty += '<table cellpadding="15" id="customers-preview" class="table table-responsive table-striped customer tablesorter" cellspacing="0">'; inlineQty += '<thead style="color: white;background-color: #607799;">'; inlineQty += '<tr class="text-center">'; inlineQty += '<th scope="col">Review Complete</th>'; inlineQty += '<th scope="col">ID</th>'; inlineQty += '<th scope="col">Customer Name</th>'; inlineQty += '<th scope="col">Date of Last price Increase</th>'; inlineQty += '<th scope="col">Action</th>'; inlineQty += '</tr>'; inlineQty += '</thead>'; inlineQty += '<tbody>'; /** * Description - Get the list of Customer that have Trial or Signed Status for a particular zee */ //Load customer record var zeeRecord = record.load({ type: record.Type.PARTNER, id: zee, isDynamic: true }); var name = zeeRecord.getValue({fieldId: 'companyname'}); log.debug({ title: 'zee rec name', details: name }); //Search: SMC - Customer var customerSearch = search.load({ type: search.Type.CUSTOMER, id: 'customsearch_smc_customer' }); var filter = search.createFilter({ name:'partner', join: null, operator: search.Operator.ANYOF, values: zee, }); customerSearch.filters.push(filter); var resultSetCustomer = customerSearch.run(); resultSetCustomer.each(function(searchResult){ log.debug({ title: 'search result', details: searchResult }); var custid = searchResult.getValue({ name: 'internalid', join: null, summary: search.Summary.GROUP }); var entityid = searchResult.getValue({ name: 'entityid', join: null, summary: search.Summary.GROUP }); var companyname = searchResult.getValue({ name: 'companyname', join: null, summary: search.Summary.GROUP }); var last_price_increase = searchResult.getValue({ name: 'custentity_date_of_last_price_increase', join: null, summary: search.Summary.GROUP }); //Retrieve column values to Identify Reviewed Services and Correct CommReg var serviceCount = searchResult.getValue({ name: 'formulanumeric', join: null, summary: search.Summary.MAX }); //Retrieve column values to Identify Reviewed Services and Correct CommReg //Count of Reviewed Services var serviceCount = searchResult.getValue({ name: 'formulanumeric', join: null, summary: search.Summary.MAX }); //Count of Correct CommReg var commRegCount = searchResult.getValue({ name: 'formulacurrency', join: null, summary: search.Summary.COUNT }); if (commRegCount == 0) { inlineQty += '<tr><td></td><td><a href="' + baseURL + '/app/common/entity/custjob.nl?id=' + custid + '"><p style="text-align:left;">' + entityid + '</p></a></td><td ><p style="text-align:left;">' + companyname + '</p></td><td>' + last_price_increase + '</td><td><div class="row"><div class="col-sm-6"><input type="button" class="commRegUpload form-control btn-default" id="commRegUpload_'+custid+'" value="UPLOAD SCF"></div><div class="col-sm-6"><input type="button" class="form-control btn-danger cancel_customer" value="CANCEL" id="cancel_customer_'+custid+'"></div></div></td></tr>'; } else if (commRegCount > 1) { inlineQty += '<tr><td></td><td><a href="' + baseURL + '/app/common/entity/custjob.nl?id=' + custid + '"><p style="text-align:left;">' + entityid + '</p></a></td><td ><p style="text-align:left;">' + companyname + '</p></td><td>' + last_price_increase + '</td><td><div class="row"><div class="col-sm-6"><input type="button" class="form-control btn-default" value="Duplicate COMMREG"></div><div class="col-sm-6"><input type="button" class="form-control btn-danger cancel_customer" value="CANCEL" id="cancel_customer_'+custid+'"></div></div></td></tr>'; } else if (serviceCount == 0) { //If no service record present for customer, Review button will be shown inlineQty += '<tr><td></td><td><a href="' + baseURL + '/app/common/entity/custjob.nl?id=' + custid + '"><p style="text-align:left;">' + entityid + '</p></a></td><td><p style="text-align:left;">' + companyname + '</p></td><td>' + last_price_increase + '</td><td><div class="row"><div class="col-sm-6"><input type="button" class="review_customer form-control btn-warning" value="REVIEW" id="review_customer_'+custid+'" ></div><div class="col-sm-6"><input type="button" class="form-control btn-danger cancel_customer" value="CANCEL" id="cancel_customer_'+custid+'"></div></div></td></tr>'; } else { //If service record is present for customer, Edit button is shown inlineQty += '<tr class="dynatable-editable"><td style="text-align: center;"><img src="https://1048144.app.netsuite.com/core/media/media.nl?id=1990778&c=1048144&h=e7f4f60576de531265f7" height="25" width="25"></td><td><a href="' + baseURL + '/app/common/entity/custjob.nl?id=' + custid + '"><p style="text-align:left;">' + entityid + '</p></a></td><td><p style="text-align:left;">' + companyname + '</p></td><td>' + last_price_increase + '</td><td><div class="row"><div class="col-sm-6"><input type="button" class="edit_customer form-control btn-primary" value="EDIT" id="edit_customer_'+custid+'"></div><div class="col-sm-6"><input type="button" class="form-control btn-danger cancel_customer" value="CANCEL" id="cancel_customer_'+custid+'"></div></div></td></tr>'; } return true; }); inlineQty += '</tbody>'; inlineQty += '</table><br/>'; return inlineQty; } /** * Is Null or Empty. * * @param {Object} strVal */ function isNullorEmpty(strVal) { return (strVal == null || strVal == '' || strVal == 'null' || strVal == undefined || strVal == 'undefined' || strVal == '- None -'); } return { onRequest: onRequest }; });
true
/** *@NApiVersion 2.0 *@NScriptType Suitelet * * Module Description - * * NSVersion Date Author * 2.00 2020-11-26 13:12:36 Ravija Maheshwari */ define(['N/ui/serverWidget', 'N/email', 'N/runtime', 'N/search', 'N/record', 'N/http', 'N/log', 'N/redirect', 'N/format', 'N/currentRecord'], function(ui, email, runtime, search, record, http, log, redirect, format, currentRecord) { function onRequest(context) { //Setup var baseURL = 'https://system.na2.netsuite.com'; if (runtime.EnvType == "SANDBOX") { baseURL = 'https://system.sandbox.netsuite.com'; } var zee = 0; var role = runtime.getCurrentUser().role; if (role == 1000) { zee = runtime.getCurrentUser().id; } else if (role == 3) { //Administrator zee = 6; //test } else if (role == 1032) { // System Support zee = 425904; //test-AR } if(context.request.method === 'GET'){ var form = ui.createForm({ title: 'Cancel Scheduled Price Change - Customer List' }); //Load Jquery var inlinehtml2 = '<script src="https://code.jquery.com/jquery-1.12.4.min.js" integrity="PI:KEY:vqbpgud2ghvjgm1n5hdgjnn5818fzsf2END_PI" crossorigin="anonymous"></script>'; // Load DataTables inlinehtml2 += '<link rel="stylesheet" type="text/css" href="//cdn.datatables.net/1.10.21/css/jquery.dataTables.min.css">'; inlinehtml2 += '<script type="text/javascript" charset="utf8" src="//cdn.datatables.net/1.10.21/js/jquery.dataTables.min.js"></script>'; // Load Bootstrap inlinehtml2 += '<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/3.4.1/css/bootstrap.min.css" integrity="PI:KEY:9jnerlff23u8ed01np9g6ysbhsh0dvcsEND_PI" crossorigin="anonymous">'; inlinehtml2 += '<script src="https://stackpath.bootstrapcdn.com/bootstrap/3.4.1/js/bootstrap.min.js" integrity="PI:KEY:vqbpgud2ghvjgm1n5hdgjnn5818fzsf2END_PI" crossorigin="anonymous"></script>'; // Load Netsuite stylesheet and script inlinehtml2 += '<link rel="stylesheet" href="https://1048144.app.netsuite.com/core/media/media.nl?id=2060796&c=1048144&h=9ee6accfd476c9cae718&_xt=.css"/>'; inlinehtml2 += '<script src="https://1048144.app.netsuite.com/core/media/media.nl?id=2060797&c=1048144&h=ef2cda20731d146b5e98&_xt=.js"></script>'; inlinehtml2 += '<link type="text/css" rel="stylesheet" href="https://1048144.app.netsuite.com/core/media/media.nl?id=2090583&c=1048144&h=a0ef6ac4e28f91203dfe&_xt=.css">'; inlinehtml2 += '<style>.mandatory{color:red;}</style>'; inlinehtml2 += '<link href="//netdna.bootstrapcdn.com/bootstrap/3.3.2/css/bootstrap.min.css" rel="stylesheet"><script src="//netdna.bootstrapcdn.com/bootstrap/3.3.2/js/bootstrap.min.js"></script><link rel="stylesheet" href="https://1048144.app.netsuite.com/core/media/media.nl?id=2060796&c=1048144&h=9ee6accfd476c9cae718&_xt=.css"/><script src="https://1048144.app.netsuite.com/core/media/media.nl?id=2060797&c=1048144&h=ef2cda20731d146b5e98&_xt=.js"></script><link type="text/css" rel="stylesheet" href="https://1048144.app.netsuite.com/core/media/media.nl?id=2090583&c=1048144&h=a0ef6ac4e28f91203dfe&_xt=.css">'; //Instructions inlinehtml2 += '<button type="button" class="btn btn-sm btn-info instruction_button" data-toggle="collapse" data-target="#demo">Click for Instructions</button><div id="demo" style="background-color: #cfeefc !important;border: 1px solid #417ed9;padding: 10px 10px 10px 20px;width:96%;position:absolute; z-index: 9999;" class="collapse"><b><u>IMPORTANT INSTRUCTIONS:</u></b><ul><li>Functionalities available on the Customer listing/table:<ul><li><b>Sort</b><ul><li>Click on column headers to sort customer list according to the values in the columns. This is default to "Customer Name".</li><li>Hold "Shift" and click another column to sort according to multiple columns.</li></ul></li><li><b>Search</b><ul><li>You can search for specific customer by typing into the "Search" field</li></ul></li></ul></li><li>Clickable Actions available per customer:</li><ul><li><button class="btn-xs btn-default" disabled>UPLOAD SCF</button> - <ul><li>Available for customers with missing Service Commencement Forms (SCF) in the system. You will need to upload the latest signed SCF for each relevant customers which outlines the service commencement date along with the Service(s) and Price(s).</li></ul></li><li><button class="btn-xs btn-warning" disabled>REVIEW</button> / <button class="btn-xs btn-primary" disabled>EDIT</button> - <ul><li>Review or Edit customer details (eg. Addresses, Service and Pricing, Packages) to set them up for Run Digitalisation.</li><li>Any service added needs to be scheduled on the Run Scheduler.</li><li>Any service deleted will be removed from your run. It will no longer appear on the calendar and app.</li></ul></li><li><button class="btn-xs btn-danger" disabled>COVID CANCEL</button> - <ul><li>You may Cancel non-active customers providing details and reasons around the Cancellation.</li><li>You <b><u>DO NOT NEED</u></b> to cancel customers with <b><u>Adhoc</u></b> arrangements.</li></ul></li><li><button class="btn-xs btn-default" disabled>Duplicate COMMREG</button> - <ul><li>Please contact <b><u>Head Office</u></b> if you see this Action against any customer</li></ul></li></ul></li></ul></ul></div>'; //If role is Admin or System Support, add dropdown to select zee if (role != 1000) { inlinehtml2 += zeeDropDown(context); } //Set zee if one is chosen if (!isNullorEmpty(context.request.parameters.zee)) { zee = context.request.parameters.zee; } inlinehtml2 += populateCustomerTable(zee, baseURL); //Set inlineQty for Instruction button and zee dropdown form.addField({ id: 'preview_table', type: ui.FieldType.INLINEHTML, label: 'preview table' }).defaultValue = inlinehtml2; form.clientScriptFileId = 4563740; context.response.writePage(form); } } /** * Returns inlineHtml which contains the dropdown to choose zees * @param {} context */ function zeeDropDown(context){ var inlineHtml = '<div class="col-xs-12 admin_section" margin-top:30px "><b>Select Zee</b> <select class="form-control zee_dropdown" >'; //WS Edit: Updated Search to SMC Franchisee (exc Old/Inactives) //Search: SMC - Franchisees var searched_zee = search.load({ type: search.Type.PARTNER, id: 'customsearch_smc_franchisee' }); var resultSet_zee = searched_zee.run(); var count_zee = 0; var zee_id; inlineHtml += '<option value=""></option>' resultSet_zee.each(function(searchResult_zee) { zee_id = searchResult_zee.getValue({name: 'internalid'}); // WS Edit: Updated entityid to companyname zee_name = searchResult_zee.getValue({name:'companyname'}); if (context.request.parameters.zee == zee_id) { inlineHtml += '<option value="' + zee_id + '" selected="selected">' + zee_name + '</option>'; } else { inlineHtml += '<option value="' + zee_id + '">' + zee_name + '</option>'; } return true; }); inlineHtml += '</select></div>'; return inlineHtml; } function populateCustomerTable(zee, baseURL){ var inlineQty = '<style> table#customer {font-size: 14px;text-align: center;border: none; font-weight: bold;} table th{text-align: center;} </style>'; inlineQty += '<div class="form-group container-fluid customers_preview_section">'; inlineQty += '<table cellpadding="15" id="customers-preview" class="table table-responsive table-striped customer tablesorter" cellspacing="0">'; inlineQty += '<thead style="color: white;background-color: #607799;">'; inlineQty += '<tr class="text-center">'; inlineQty += '<th scope="col">Review Complete</th>'; inlineQty += '<th scope="col">ID</th>'; inlineQty += '<th scope="col">Customer Name</th>'; inlineQty += '<th scope="col">Date of Last price Increase</th>'; inlineQty += '<th scope="col">Action</th>'; inlineQty += '</tr>'; inlineQty += '</thead>'; inlineQty += '<tbody>'; /** * Description - Get the list of Customer that have Trial or Signed Status for a particular zee */ //Load customer record var zeeRecord = record.load({ type: record.Type.PARTNER, id: zee, isDynamic: true }); var name = zeeRecord.getValue({fieldId: 'companyname'}); log.debug({ title: 'zee rec name', details: name }); //Search: SMC - Customer var customerSearch = search.load({ type: search.Type.CUSTOMER, id: 'customsearch_smc_customer' }); var filter = search.createFilter({ name:'partner', join: null, operator: search.Operator.ANYOF, values: zee, }); customerSearch.filters.push(filter); var resultSetCustomer = customerSearch.run(); resultSetCustomer.each(function(searchResult){ log.debug({ title: 'search result', details: searchResult }); var custid = searchResult.getValue({ name: 'internalid', join: null, summary: search.Summary.GROUP }); var entityid = searchResult.getValue({ name: 'entityid', join: null, summary: search.Summary.GROUP }); var companyname = searchResult.getValue({ name: 'companyname', join: null, summary: search.Summary.GROUP }); var last_price_increase = searchResult.getValue({ name: 'custentity_date_of_last_price_increase', join: null, summary: search.Summary.GROUP }); //Retrieve column values to Identify Reviewed Services and Correct CommReg var serviceCount = searchResult.getValue({ name: 'formulanumeric', join: null, summary: search.Summary.MAX }); //Retrieve column values to Identify Reviewed Services and Correct CommReg //Count of Reviewed Services var serviceCount = searchResult.getValue({ name: 'formulanumeric', join: null, summary: search.Summary.MAX }); //Count of Correct CommReg var commRegCount = searchResult.getValue({ name: 'formulacurrency', join: null, summary: search.Summary.COUNT }); if (commRegCount == 0) { inlineQty += '<tr><td></td><td><a href="' + baseURL + '/app/common/entity/custjob.nl?id=' + custid + '"><p style="text-align:left;">' + entityid + '</p></a></td><td ><p style="text-align:left;">' + companyname + '</p></td><td>' + last_price_increase + '</td><td><div class="row"><div class="col-sm-6"><input type="button" class="commRegUpload form-control btn-default" id="commRegUpload_'+custid+'" value="UPLOAD SCF"></div><div class="col-sm-6"><input type="button" class="form-control btn-danger cancel_customer" value="CANCEL" id="cancel_customer_'+custid+'"></div></div></td></tr>'; } else if (commRegCount > 1) { inlineQty += '<tr><td></td><td><a href="' + baseURL + '/app/common/entity/custjob.nl?id=' + custid + '"><p style="text-align:left;">' + entityid + '</p></a></td><td ><p style="text-align:left;">' + companyname + '</p></td><td>' + last_price_increase + '</td><td><div class="row"><div class="col-sm-6"><input type="button" class="form-control btn-default" value="Duplicate COMMREG"></div><div class="col-sm-6"><input type="button" class="form-control btn-danger cancel_customer" value="CANCEL" id="cancel_customer_'+custid+'"></div></div></td></tr>'; } else if (serviceCount == 0) { //If no service record present for customer, Review button will be shown inlineQty += '<tr><td></td><td><a href="' + baseURL + '/app/common/entity/custjob.nl?id=' + custid + '"><p style="text-align:left;">' + entityid + '</p></a></td><td><p style="text-align:left;">' + companyname + '</p></td><td>' + last_price_increase + '</td><td><div class="row"><div class="col-sm-6"><input type="button" class="review_customer form-control btn-warning" value="REVIEW" id="review_customer_'+custid+'" ></div><div class="col-sm-6"><input type="button" class="form-control btn-danger cancel_customer" value="CANCEL" id="cancel_customer_'+custid+'"></div></div></td></tr>'; } else { //If service record is present for customer, Edit button is shown inlineQty += '<tr class="dynatable-editable"><td style="text-align: center;"><img src="https://1048144.app.netsuite.com/core/media/media.nl?id=1990778&c=1048144&h=e7f4f60576de531265f7" height="25" width="25"></td><td><a href="' + baseURL + '/app/common/entity/custjob.nl?id=' + custid + '"><p style="text-align:left;">' + entityid + '</p></a></td><td><p style="text-align:left;">' + companyname + '</p></td><td>' + last_price_increase + '</td><td><div class="row"><div class="col-sm-6"><input type="button" class="edit_customer form-control btn-primary" value="EDIT" id="edit_customer_'+custid+'"></div><div class="col-sm-6"><input type="button" class="form-control btn-danger cancel_customer" value="CANCEL" id="cancel_customer_'+custid+'"></div></div></td></tr>'; } return true; }); inlineQty += '</tbody>'; inlineQty += '</table><br/>'; return inlineQty; } /** * Is Null or Empty. * * @param {Object} strVal */ function isNullorEmpty(strVal) { return (strVal == null || strVal == '' || strVal == 'null' || strVal == undefined || strVal == 'undefined' || strVal == '- None -'); } return { onRequest: onRequest }; });
/** * sh_sdf_cl_example.js * * Example file to be imported into the SDF Project for Lesson 4 of the SuiteHub SDF Course * * @module sh_sdf_cl_example * * @copyright 2023 Salto * @author Eric T Grubaugh <eric@stoic.software> * * @NApiVersion 2.1 * @NModuleScope Public * @NScriptType ClientScript */ define([], () => { /** * Display a thank you to the user * * @gov 0 * * @param {Object} context * * @see [Help:pageInit]{@link https://system.netsuite.com/app/help/helpcenter.nl?fid=section_4410597671.html} */ function pageInit(context) { console.info(` *** THANK YOU for watching Lesson 4 of the Intro to SDF Course on SUITEHUB!" ***`); } return /** @alias module:sh_sdf_cl_example.js */ { pageInit }; });
752
[{"tag": "EMAIL", "value": "eric@stoic.software", "start": 211, "end": 230}]
true
1
/** * sh_sdf_cl_example.js * * Example file to be imported into the SDF Project for Lesson 4 of the SuiteHub SDF Course * * @module sh_sdf_cl_example * * @copyright 2023 Salto * @author Eric T Grubaugh <nnheo@example.com> * * @NApiVersion 2.1 * @NModuleScope Public * @NScriptType ClientScript */ define([], () => { /** * Display a thank you to the user * * @gov 0 * * @param {Object} context * * @see [Help:pageInit]{@link https://system.netsuite.com/app/help/helpcenter.nl?fid=section_4410597671.html} */ function pageInit(context) { console.info(` *** THANK YOU for watching Lesson 4 of the Intro to SDF Course on SUITEHUB!" ***`); } return /** @alias module:sh_sdf_cl_example.js */ { pageInit }; });
true
/** * sh_sdf_cl_example.js * * Example file to be imported into the SDF Project for Lesson 4 of the SuiteHub SDF Course * * @module sh_sdf_cl_example * * @copyright 2023 Salto * @author Eric T Grubaugh <PI:EMAIL:nnheo@example.comEND_PI> * * @NApiVersion 2.1 * @NModuleScope Public * @NScriptType ClientScript */ define([], () => { /** * Display a thank you to the user * * @gov 0 * * @param {Object} context * * @see [Help:pageInit]{@link https://system.netsuite.com/app/help/helpcenter.nl?fid=section_4410597671.html} */ function pageInit(context) { console.info(` *** THANK YOU for watching Lesson 4 of the Intro to SDF Course on SUITEHUB!" ***`); } return /** @alias module:sh_sdf_cl_example.js */ { pageInit }; });
/** * @NApiVersion 2.x * @NScriptType Suitelet * @NModuleScope SameAccount */ define(['N/file', 'N/record', 'N/render', 'N/ui/serverWidget', 'SuiteScripts/CustomScripts/SuitePDF/api/estimate', 'SuiteScripts/CustomScripts/SuiteBox/api/suitebox', '../../Library/handlebars', '../../Library/handlebars/handlebarshelper'], /** * @param {file} file * @param {record} record * @param {render} render */ function (file, record, render, serverWidget, estimate, suitebox, handlebars, handlebarshelper) { /** * Definition of the Suitelet script trigger point. * * @param {Object} context * @param {ServerRequest} context.request - Encapsulation of the incoming request * @param {ServerResponse} context.response - Encapsulation of the Suitelet response * @Since 2015.2 */ function onRequest(context) { var paramReq = context.request.parameters; var idRec = paramReq.recid; var sType = paramReq.rectype; var sAction = paramReq.action; var sPdfTemplate = ''; var sTemplate = file.load({ id: 'SuiteScripts/CustomScripts/SuiteBox/template/pdfobject.html' }).getContents(); var retMe = { status: '', response: '' }; var idFolder = '156766524816'; var idSignedFolder = '156767063747'; var sEmail = ''; if (sAction == 'upload') { var pdfFile = render.xmlToPdf({ xmlString: 'Test Box Sign' }); pdfFile.name = 'TestBoxSign2.pdf'; var stbxFolder = suitebox.updateFolder({ data: { 'folder_upload_email': { 'access': 'open' }, id: idFolder } }); if (stbxFolder.status == 'SUCCESS') { sEmail = stbxFolder.response.data.folder_upload_email.email; log.audit({ title: 'sEmail', details: 'sEmail: ' + sEmail }); } else if (stbxFolder.status == 'FAILED') { log.audit({ title: 'stbxFolder', details: 'FAILED' }); } var stbxUpload = suitebox.emailUpload2({ data: { author: 171596, email: sEmail, subject: 'subject', body: 'body', attachments: [pdfFile] } }); if (stbxUpload.status == 'SUCCESS') { retMe.status = 'SUCCESS'; retMe.response = { message: 'Uploading in Progress.' }; } else{ retMe.status = 'FAILED'; retMe.response = { message : stbxUpload.response.message }; } context.response.setHeader({ name: 'Content-Type', value: 'application/json' }); context.response.write(JSON.stringify(retMe)); } else if (sAction == 'checkfile') { var stbxItems = suitebox.folderItems({ data: { 'folder': idFolder, 'name': 'TestBoxSign2.pdf' } }); if (stbxItems.status == 'SUCCESS') { var objFile = stbxItems.response.data.filter( function(file){ return file.name == 'TestBoxSign2.pdf'; } ); if(objFile.length > 0){ retMe.status = 'SUCCESS'; retMe.response = { id : objFile[0].id } } else{ retMe.status = 'SUCCESS'; retMe.response = { message: 'Uploading in Progress.' }; } } else{ retMe.status = 'FAILED'; retMe.response = { message : stbxItems.response.message } } context.response.setHeader({ name: 'Content-Type', value: 'application/json' }); context.response.write(JSON.stringify(retMe)); } else if (sAction == 'sign') { var stbxSign = suitebox.requestSign({ data: { 'signers': [{ 'role': 'signer', 'email': 'patrick.alcomendas@servicerocket.com' } ], 'source_files': [{ 'type': 'file', 'id': stbxItems.response.data[0].id } ], 'parent_folder': { 'type': 'folder', 'id': idSignedFolder } } }); if (stbxSign.status == 'SUCCESS') { retMe.status = 'SUCCESS'; retMe.response.message = 'Sign Request Created.'; } else{ retMe.status = 'FAILED'; retMe.response.message = stbxSign.response.message; } context.response.setHeader({ name: 'Content-Type', value: 'application/json' }); context.response.write(JSON.stringify(retMe)); var x = 1; } else{ var objForm = serverWidget.createForm({ title: 'BoxSign 1.0' }); var fldHtml = objForm.addField({ id: 'custpage_htmlfield', type: serverWidget.FieldType.INLINEHTML, label: 'HTML' }); var sHandlebar = handlebars.compile(sTemplate); handlebars = handlebarshelper.register(handlebars); var sHtmlTemplate = sHandlebar({ type: sType, id: idRec }); fldHtml.defaultValue = sHtmlTemplate; context.response.writePage(objForm); } } return { onRequest: onRequest }; });
820
[{"tag": "EMAIL", "value": "patrick.alcomendas@servicerocket.com", "start": 4419, "end": 4455}]
true
1
/** * @NApiVersion 2.x * @NScriptType Suitelet * @NModuleScope SameAccount */ define(['N/file', 'N/record', 'N/render', 'N/ui/serverWidget', 'SuiteScripts/CustomScripts/SuitePDF/api/estimate', 'SuiteScripts/CustomScripts/SuiteBox/api/suitebox', '../../Library/handlebars', '../../Library/handlebars/handlebarshelper'], /** * @param {file} file * @param {record} record * @param {render} render */ function (file, record, render, serverWidget, estimate, suitebox, handlebars, handlebarshelper) { /** * Definition of the Suitelet script trigger point. * * @param {Object} context * @param {ServerRequest} context.request - Encapsulation of the incoming request * @param {ServerResponse} context.response - Encapsulation of the Suitelet response * @Since 2015.2 */ function onRequest(context) { var paramReq = context.request.parameters; var idRec = paramReq.recid; var sType = paramReq.rectype; var sAction = paramReq.action; var sPdfTemplate = ''; var sTemplate = file.load({ id: 'SuiteScripts/CustomScripts/SuiteBox/template/pdfobject.html' }).getContents(); var retMe = { status: '', response: '' }; var idFolder = '156766524816'; var idSignedFolder = '156767063747'; var sEmail = ''; if (sAction == 'upload') { var pdfFile = render.xmlToPdf({ xmlString: 'Test Box Sign' }); pdfFile.name = 'TestBoxSign2.pdf'; var stbxFolder = suitebox.updateFolder({ data: { 'folder_upload_email': { 'access': 'open' }, id: idFolder } }); if (stbxFolder.status == 'SUCCESS') { sEmail = stbxFolder.response.data.folder_upload_email.email; log.audit({ title: 'sEmail', details: 'sEmail: ' + sEmail }); } else if (stbxFolder.status == 'FAILED') { log.audit({ title: 'stbxFolder', details: 'FAILED' }); } var stbxUpload = suitebox.emailUpload2({ data: { author: 171596, email: sEmail, subject: 'subject', body: 'body', attachments: [pdfFile] } }); if (stbxUpload.status == 'SUCCESS') { retMe.status = 'SUCCESS'; retMe.response = { message: 'Uploading in Progress.' }; } else{ retMe.status = 'FAILED'; retMe.response = { message : stbxUpload.response.message }; } context.response.setHeader({ name: 'Content-Type', value: 'application/json' }); context.response.write(JSON.stringify(retMe)); } else if (sAction == 'checkfile') { var stbxItems = suitebox.folderItems({ data: { 'folder': idFolder, 'name': 'TestBoxSign2.pdf' } }); if (stbxItems.status == 'SUCCESS') { var objFile = stbxItems.response.data.filter( function(file){ return file.name == 'TestBoxSign2.pdf'; } ); if(objFile.length > 0){ retMe.status = 'SUCCESS'; retMe.response = { id : objFile[0].id } } else{ retMe.status = 'SUCCESS'; retMe.response = { message: 'Uploading in Progress.' }; } } else{ retMe.status = 'FAILED'; retMe.response = { message : stbxItems.response.message } } context.response.setHeader({ name: 'Content-Type', value: 'application/json' }); context.response.write(JSON.stringify(retMe)); } else if (sAction == 'sign') { var stbxSign = suitebox.requestSign({ data: { 'signers': [{ 'role': 'signer', 'email': 'hzdkv@example.com' } ], 'source_files': [{ 'type': 'file', 'id': stbxItems.response.data[0].id } ], 'parent_folder': { 'type': 'folder', 'id': idSignedFolder } } }); if (stbxSign.status == 'SUCCESS') { retMe.status = 'SUCCESS'; retMe.response.message = 'Sign Request Created.'; } else{ retMe.status = 'FAILED'; retMe.response.message = stbxSign.response.message; } context.response.setHeader({ name: 'Content-Type', value: 'application/json' }); context.response.write(JSON.stringify(retMe)); var x = 1; } else{ var objForm = serverWidget.createForm({ title: 'BoxSign 1.0' }); var fldHtml = objForm.addField({ id: 'custpage_htmlfield', type: serverWidget.FieldType.INLINEHTML, label: 'HTML' }); var sHandlebar = handlebars.compile(sTemplate); handlebars = handlebarshelper.register(handlebars); var sHtmlTemplate = sHandlebar({ type: sType, id: idRec }); fldHtml.defaultValue = sHtmlTemplate; context.response.writePage(objForm); } } return { onRequest: onRequest }; });
true
/** * @NApiVersion 2.x * @NScriptType Suitelet * @NModuleScope SameAccount */ define(['N/file', 'N/record', 'N/render', 'N/ui/serverWidget', 'SuiteScripts/CustomScripts/SuitePDF/api/estimate', 'SuiteScripts/CustomScripts/SuiteBox/api/suitebox', '../../Library/handlebars', '../../Library/handlebars/handlebarshelper'], /** * @param {file} file * @param {record} record * @param {render} render */ function (file, record, render, serverWidget, estimate, suitebox, handlebars, handlebarshelper) { /** * Definition of the Suitelet script trigger point. * * @param {Object} context * @param {ServerRequest} context.request - Encapsulation of the incoming request * @param {ServerResponse} context.response - Encapsulation of the Suitelet response * @Since 2015.2 */ function onRequest(context) { var paramReq = context.request.parameters; var idRec = paramReq.recid; var sType = paramReq.rectype; var sAction = paramReq.action; var sPdfTemplate = ''; var sTemplate = file.load({ id: 'SuiteScripts/CustomScripts/SuiteBox/template/pdfobject.html' }).getContents(); var retMe = { status: '', response: '' }; var idFolder = '156766524816'; var idSignedFolder = '156767063747'; var sEmail = ''; if (sAction == 'upload') { var pdfFile = render.xmlToPdf({ xmlString: 'Test Box Sign' }); pdfFile.name = 'TestBoxSign2.pdf'; var stbxFolder = suitebox.updateFolder({ data: { 'folder_upload_email': { 'access': 'open' }, id: idFolder } }); if (stbxFolder.status == 'SUCCESS') { sEmail = stbxFolder.response.data.folder_upload_email.email; log.audit({ title: 'sEmail', details: 'sEmail: ' + sEmail }); } else if (stbxFolder.status == 'FAILED') { log.audit({ title: 'stbxFolder', details: 'FAILED' }); } var stbxUpload = suitebox.emailUpload2({ data: { author: 171596, email: sEmail, subject: 'subject', body: 'body', attachments: [pdfFile] } }); if (stbxUpload.status == 'SUCCESS') { retMe.status = 'SUCCESS'; retMe.response = { message: 'Uploading in Progress.' }; } else{ retMe.status = 'FAILED'; retMe.response = { message : stbxUpload.response.message }; } context.response.setHeader({ name: 'Content-Type', value: 'application/json' }); context.response.write(JSON.stringify(retMe)); } else if (sAction == 'checkfile') { var stbxItems = suitebox.folderItems({ data: { 'folder': idFolder, 'name': 'TestBoxSign2.pdf' } }); if (stbxItems.status == 'SUCCESS') { var objFile = stbxItems.response.data.filter( function(file){ return file.name == 'TestBoxSign2.pdf'; } ); if(objFile.length > 0){ retMe.status = 'SUCCESS'; retMe.response = { id : objFile[0].id } } else{ retMe.status = 'SUCCESS'; retMe.response = { message: 'Uploading in Progress.' }; } } else{ retMe.status = 'FAILED'; retMe.response = { message : stbxItems.response.message } } context.response.setHeader({ name: 'Content-Type', value: 'application/json' }); context.response.write(JSON.stringify(retMe)); } else if (sAction == 'sign') { var stbxSign = suitebox.requestSign({ data: { 'signers': [{ 'role': 'signer', 'email': 'PI:EMAIL:hzdkv@example.comEND_PI' } ], 'source_files': [{ 'type': 'file', 'id': stbxItems.response.data[0].id } ], 'parent_folder': { 'type': 'folder', 'id': idSignedFolder } } }); if (stbxSign.status == 'SUCCESS') { retMe.status = 'SUCCESS'; retMe.response.message = 'Sign Request Created.'; } else{ retMe.status = 'FAILED'; retMe.response.message = stbxSign.response.message; } context.response.setHeader({ name: 'Content-Type', value: 'application/json' }); context.response.write(JSON.stringify(retMe)); var x = 1; } else{ var objForm = serverWidget.createForm({ title: 'BoxSign 1.0' }); var fldHtml = objForm.addField({ id: 'custpage_htmlfield', type: serverWidget.FieldType.INLINEHTML, label: 'HTML' }); var sHandlebar = handlebars.compile(sTemplate); handlebars = handlebarshelper.register(handlebars); var sHtmlTemplate = sHandlebar({ type: sType, id: idRec }); fldHtml.defaultValue = sHtmlTemplate; context.response.writePage(objForm); } } return { onRequest: onRequest }; });
/** * * Customer Search Portlet * * @NApiVersion 2.x * @NScriptType Portlet * @author trungpv <trung@lexor.com> */ define(["N/search", "N/ui/serverWidget"], function(search, serverWidget) { function render(params) { var portlet = params.portlet; portlet.title = "Customer Search"; var html = ""; try { html += buildSalesRepsHTMLTable(); } catch (error) { html = "Sorry, something went wrong."; } portlet.html = html; } /** * Helper Functions */ /** * Replace all * @param {*} string * @param {*} target * @param {*} replacement */ function replaceAll(string, target, replacement) { return string.split(target).join(replacement); } /** * Convert Name * @param {*} firstname * @param {*} middlename * @param {*} lastname */ function getName(firstname, middlename, lastname) { var name = ""; name += firstname !== "" ? firstname : ""; name += middlename !== "" ? " " + middlename : ""; name += lastname !== "" ? " " + lastname : ""; return name; } /** * Build Sales Reps HTML Table */ function buildSalesRepsHTMLTable() { var html = '<table style="width:100%">'; const header = "<tr><th>SALES REP</th><th>EMAIL</th><th>Turn</th></tr>"; const rowTemplate = "<tr><td>__NAME__</td><td>__EMAIL__</td><td>__TURN__</td></tr>"; html += header; var salesReps = search.create({ type: search.Type.EMPLOYEE, filters: [ { name: "salesrep", operator: search.Operator.IS, values: "T" }, { name: "isinactive", operator: search.Operator.IS, values: "F" } ], columns: ["firstname", "middlename", "lastname", "email"] }); var searchResults = salesReps.run().getRange({ start: 0, end: 1000 }); for (var index = 0; index < searchResults.length; index++) { var element = searchResults[index]; var row = rowTemplate; row = replaceAll( row, "__NAME__", getName( element.getValue({ name: "firstname" }), element.getValue({ name: "middlename" }), element.getValue({ name: "lastname" }) ) ); row = replaceAll(row, "__EMAIL__", element.getValue({ name: "email" })); row = replaceAll(row, "__TURN__", index + 1); html += row; } html += "</table>"; return html; } return { render: render }; });
1,174
[{"tag": "EMAIL", "value": "trung@lexor.com", "start": 101, "end": 116}]
true
1
/** * * Customer Search Portlet * * @NApiVersion 2.x * @NScriptType Portlet * @author trungpv <envkt@example.com> */ define(["N/search", "N/ui/serverWidget"], function(search, serverWidget) { function render(params) { var portlet = params.portlet; portlet.title = "Customer Search"; var html = ""; try { html += buildSalesRepsHTMLTable(); } catch (error) { html = "Sorry, something went wrong."; } portlet.html = html; } /** * Helper Functions */ /** * Replace all * @param {*} string * @param {*} target * @param {*} replacement */ function replaceAll(string, target, replacement) { return string.split(target).join(replacement); } /** * Convert Name * @param {*} firstname * @param {*} middlename * @param {*} lastname */ function getName(firstname, middlename, lastname) { var name = ""; name += firstname !== "" ? firstname : ""; name += middlename !== "" ? " " + middlename : ""; name += lastname !== "" ? " " + lastname : ""; return name; } /** * Build Sales Reps HTML Table */ function buildSalesRepsHTMLTable() { var html = '<table style="width:100%">'; const header = "<tr><th>SALES REP</th><th>EMAIL</th><th>Turn</th></tr>"; const rowTemplate = "<tr><td>__NAME__</td><td>__EMAIL__</td><td>__TURN__</td></tr>"; html += header; var salesReps = search.create({ type: search.Type.EMPLOYEE, filters: [ { name: "salesrep", operator: search.Operator.IS, values: "T" }, { name: "isinactive", operator: search.Operator.IS, values: "F" } ], columns: ["firstname", "middlename", "lastname", "email"] }); var searchResults = salesReps.run().getRange({ start: 0, end: 1000 }); for (var index = 0; index < searchResults.length; index++) { var element = searchResults[index]; var row = rowTemplate; row = replaceAll( row, "__NAME__", getName( element.getValue({ name: "firstname" }), element.getValue({ name: "middlename" }), element.getValue({ name: "lastname" }) ) ); row = replaceAll(row, "__EMAIL__", element.getValue({ name: "email" })); row = replaceAll(row, "__TURN__", index + 1); html += row; } html += "</table>"; return html; } return { render: render }; });
true
/** * * Customer Search Portlet * * @NApiVersion 2.x * @NScriptType Portlet * @author trungpv <PI:EMAIL:envkt@example.comEND_PI> */ define(["N/search", "N/ui/serverWidget"], function(search, serverWidget) { function render(params) { var portlet = params.portlet; portlet.title = "Customer Search"; var html = ""; try { html += buildSalesRepsHTMLTable(); } catch (error) { html = "Sorry, something went wrong."; } portlet.html = html; } /** * Helper Functions */ /** * Replace all * @param {*} string * @param {*} target * @param {*} replacement */ function replaceAll(string, target, replacement) { return string.split(target).join(replacement); } /** * Convert Name * @param {*} firstname * @param {*} middlename * @param {*} lastname */ function getName(firstname, middlename, lastname) { var name = ""; name += firstname !== "" ? firstname : ""; name += middlename !== "" ? " " + middlename : ""; name += lastname !== "" ? " " + lastname : ""; return name; } /** * Build Sales Reps HTML Table */ function buildSalesRepsHTMLTable() { var html = '<table style="width:100%">'; const header = "<tr><th>SALES REP</th><th>EMAIL</th><th>Turn</th></tr>"; const rowTemplate = "<tr><td>__NAME__</td><td>__EMAIL__</td><td>__TURN__</td></tr>"; html += header; var salesReps = search.create({ type: search.Type.EMPLOYEE, filters: [ { name: "salesrep", operator: search.Operator.IS, values: "T" }, { name: "isinactive", operator: search.Operator.IS, values: "F" } ], columns: ["firstname", "middlename", "lastname", "email"] }); var searchResults = salesReps.run().getRange({ start: 0, end: 1000 }); for (var index = 0; index < searchResults.length; index++) { var element = searchResults[index]; var row = rowTemplate; row = replaceAll( row, "__NAME__", getName( element.getValue({ name: "firstname" }), element.getValue({ name: "middlename" }), element.getValue({ name: "lastname" }) ) ); row = replaceAll(row, "__EMAIL__", element.getValue({ name: "email" })); row = replaceAll(row, "__TURN__", index + 1); html += row; } html += "</table>"; return html; } return { render: render }; });
/** * * @NApiVersion 2.0 * @NScriptType ClientScript * * Description: A ticketing system for the Customer Service. * @Last Modified by: Sruti Desai * */ define(['N/error', 'N/runtime', 'N/search', 'N/url', 'N/record', 'N/format', 'N/email', 'N/currentRecord', 'N/https'], function(error, runtime, search, url, record, format, email, currentRecord, https) { var baseURL = 'https://1048144.app.netsuite.com'; if (runtime.envType == "SANDBOX") { baseURL = 'https://1048144-sb3.app.netsuite.com'; } var role = runtime.getCurrentUser().role; var userRole = runtime.getCurrentUser().role; var userId = runtime.getCurrentUser().id; /** * On page initialisation */ var currRec = currentRecord.get(); function pageInit() { var currRec = currentRecord.get(); //Remove Chrome's incessant "Leave Site" warning window.onbeforeunload = null; //background-colors $("#NS_MENU_ID0-item0").css("background-color", "#CFE0CE"); $("#NS_MENU_ID0-item0 a").css("background-color", "#CFE0CE"); $("#body").css("background-color", "#CFE0CE"); $("#tr_submitter").css("margin-left", "10px"); var ticketsDataSet = []; var invoicesDataSet = []; $(document).ready(function() { console.log('doc ready'); $('#email_body').summernote(); $('#owner, #toll_issues, #mp_issues, #invoice_issues, #enquiry_medium_status, #send_toll').selectpicker(); $('#tickets-preview').DataTable({ data: ticketsDataSet, columns: [{ title: "ID" }, { title: "Date created" }, { title: "Date closed" }, { title: "Barcode Number" }, { title: "Status" }, { title: "TOLL Issues" }, { title: "Resolved TOLL Issues" }, { title: "Comment" }] }); $('#emails-preview').DataTable(); var invoice_table = $('#invoices-preview').DataTable({ data: invoicesDataSet, columns: [{ title: "Invoice Date", type: "date" }, { title: "Invoice #" }, { title: "Status" }, { title: "Invoice Type" }, { title: "Amount Due", type: "num-fmt" }, { title: "Total Amount", type: "num-fmt" }, { title: "Overdue" }, { title: "Invoice ID" }, { title: "Action" }], columnDefs: [{ visible: false, targets: -2, }, { targets: -1, data: null, render: function(data, type, row, meta) { var selector_id = currRec.getValue({ fieldId: 'custpage_selector_id' }); var disabled = (data[7] == selector_id) ? 'disabled' : ''; return '<button class="btn btn-success add_inv glyphicon glyphicon-plus" type="button" data-inv-id="' + data[7] + '" data-toggle="tooltip" data-placement="right" title="Attach to email" ' + disabled + '></button>'; } }] }); $('#invoices-preview thead tr').addClass('text-center'); // Adapted from https://datatables.net/extensions/fixedheader/examples/options/columnFiltering.html // Adds a row to the table head row, and adds search filters to each column. $('#invoices-preview thead tr').clone(true).appendTo('#invoices-preview thead'); $('#invoices-preview thead tr:eq(3) th').each(function(i) { var title = $(this).text(); $(this).html('<input style="width: 80%" type="text" placeholder="Search ' + title + '" />'); $('input', this).on('keyup change', function() { if (invoice_table.column(i).search() !== this.value) { invoice_table .column(i) .search(this.value) .draw(); } }); }); //var invoice_table = $('#invoices-preview').DataTable(); invoice_table.on('click', 'button.add_inv', function() { attachFileButton.call(this) }); }); console.log('Page init'); if (window.location.search.substr(1) == "script=1243&deploy=1" || window.location.search.substr(1) == "script=976&deploy=1&compid=1048144_SB3" || window.location.search.substr(1) == "script=1243&deploy=1&compid=1048144_SB3&whence=") { currRec.setValue({ fieldId: 'custpage_selector_number', value: '' }); currRec.setValue({ fieldId: 'custpage_selector_type', value: "barcode_number"}); } var selector_number = currRec.getValue({ fieldId: 'custpage_selector_number' }); var selector_type = currRec.getValue({ fieldId: 'custpage_selector_type' }); var ticket_id = currRec.getValue({ fieldId: 'custpage_ticket_id' }); var status_value = currRec.getValue({ fieldId: 'custpage_ticket_status_value' }); var customer_number = currRec.getValue({ fieldId: 'custpage_customer_number' }); //Toggling show/hide for the tickets associated to customer number if (!isNullorEmpty(customer_number) && isNullorEmpty(selector_number)) { $('#customer_number_tickets_preview').show(); } else { $('#customer_number_tickets_preview').hide(); } // The inline html of the <table> tag is not correctly displayed inside div.col-xs-12.contacts_div when added with Suitelet. // Hence, the html code is added using jQuery when the page loads. var inline_html_contact_table = '<table cellpadding="15" id="contacts" class="table table-responsive table-striped contacts tablesorter" cellspacing="0" style="width: 100%;border: 0"><thead style="color: white;background-color: #379E8F;"><tr><th style="vertical-align: middle;text-align: center;" id="col_name"><b>NAME</b></th><th style="vertical-align: middle;text-align: center;" id="col_phone"><b>PHONE</b></th><th style="vertical-align: middle;text-align: center;" id="col_email"><b>EMAIL</b></th><th style="vertical-align: middle;text-align: center;" id="col_role"><b>ROLE</b></th><th style="vertical-align: middle;text-align: center;" id="col_add_as_recipient"><b>ADD AS RECIPIENT</b></th></tr></thead><tbody></tbody></table>'; $('div.col-xs-12.contacts_div').html(inline_html_contact_table); // Like the contacts table, the html code of the usernote table is added using jQuery when the page loads. var inline_html_usernote_table = '<table cellpadding="15" id="user_note" class="table table-responsive table-striped contacts tablesorter" cellspacing="0" style="width: 100%;border: 0"><thead style="color: white;background-color: #379E8F;"><tr><th style="vertical-align: middle;text-align: center;" id="usernote_title"><b>TITLE</b></th><th style="vertical-align: middle;text-align: center;" id="usernote_name"><b>NAME</b></th><th style="vertical-align: middle;text-align: center;" id="usernote_date"><b>DATE</b></th><th style="vertical-align: middle;text-align: center;" id="usernote_comment"><b>USER NOTE</b></th></tr></thead><tbody></tbody></table>'; $('div.col-xs-12.user_note_div').html(inline_html_usernote_table); //Credit memo display displayed conditionally if (selector_type == 'invoice_number' && !isNullorEmpty(ticket_id)) { var inline_html_credit_memo_table = htmlCreditMemoTable(status_value); $('div.col-xs-12.credit_memo_div').html(inline_html_credit_memo_table); var inline_html_usage_report_table = htmlUsageReportTable(status_value); $('div.col-xs-12.usage_report_div').html(inline_html_usage_report_table); } // The value of the submitter button at the bottom of the page is directly linked to the value of the button at the top. // var submit_btn_val = $('#submitter').val().toUpperCase(); // $('#submit_ticket').val(submit_btn_val); if (!isNullorEmpty(selector_number)) { console.log('!isNullorEmpty(selector_number) : ', !isNullorEmpty(selector_number)); // If we updated the contacts, we have the parameter 'custpage_selector_number' and no parameter for 'custpage_ticket_id'. if (isNullorEmpty(ticket_id)) { console.log('isNullorEmpty(ticket_id) : ', isNullorEmpty(ticket_id)); $('#selector_value').val(selector_number); if (validateSelectorInput()) { displayCustomerInfo(); } // If we come from the edit_ticket page, we have the parameters 'custpage_selector_number' and' custpage_ticket_id'. } else { console.log('isNullorEmpty(ticket_id) : ', isNullorEmpty(ticket_id)); createContactsRows(); // If the ticket status is "Open, the acknoledgement template shall be selected. if (status_value != 3) { $('#template option:selected').attr('selected', false); $('#template option[value="66"]').attr('selected', true); // Select the acknoledgement template loadTemplate(); } if (selector_type == 'invoice_number') { updateInvoicesDatatable(); createCreditMemoRows(status_value); createUsageReportRows(status_value); createUsernoteRows(ticket_id); } else if (selector_type == 'barcode_number') { selectEnquiryMedium(); selectTollEmails(); selectOwner(); setReminderDate(); hideCloseTicketButton(); updateTicketsDatatable(); } else { //selector_type == 'customer_issue' selectEnquiryMedium(); } } } $('[data-toggle="tooltip"]').tooltip(); updateButtonsWidth(); $('.input-group-btn button').click(function(e) { $(e.currentTarget).next('ul').toggleClass('hide'); $(e.currentTarget).next('ul').toggleClass('show'); }); $('#screenshot_image').on('change', function() { var file = $('#screenshot_image')[0].files[0]; if (file && (file.type == "image/jpeg" || file.type == "image/png")) { //continue } else { showAlert('Please enter a screenshot image of type .png or .jpeg'); } }); //Change display depending on which selector is chosen $('.dropdown-menu li a').click(function(e) { console.log("in selector dropdown li a"); e.preventDefault(); setupSelectorInput($(this).text()); var selector_type = $('#selector_text').text().toLowerCase().split(' ').join('_'); currRec.setValue({ fieldId: 'custpage_selector_type', value: selector_type}); updateTicketsDatatableHeaders(selector_type); switch (selector_type) { case 'barcode_number': $('#daytodayemail').attr('disabled', true); $('#daytodayphone').attr('disabled', true); $('#accountsemail').attr('disabled', true); $('#accountsphone').attr('disabled', true); $('.accountscontact_section').addClass('hide'); $('.accountscontact_section').addClass('hide'); $('.accounts_number_section').addClass('hide'); $('.mpex_stock_used_section').removeClass('hide'); $('.final_delivery').removeClass('hide'); $('.enquiry_status_div').removeClass('col-xs-12'); $('.enquiry_status_div').addClass('col-xs-6'); $('.label_section').removeClass('hide'); $('.enquiry_medium_section').removeClass('hide'); $('.ticket_enquiry_header_section').removeClass('hide'); $('.enquiry_status_div').removeClass('hide'); $('.enquiry_count_section').removeClass('hide'); $('.enquiry_count_breakdown_section').removeClass('hide'); $('.interaction_count_breakdown_section').removeClass('hide'); $('.invoice_method_accounts_cc_email_section').addClass('hide'); $('.mpex_customer_po_number_section').addClass('hide'); $('.terms_section').addClass('hide'); $('.mpex_invoicing_cycle_section').addClass('hide'); $('.ss_section').addClass('hide'); $('.browser_os_section').addClass('hide'); $('.phone_section').addClass('hide'); $('.login_email_section').addClass('hide'); $('.sender_details_section').addClass('hide'); $('.login_email_used_section').addClass('hide'); // Add MP Issues options var mp_ticket_issues_columns = new Array(); mp_ticket_issues_columns[0] = search.createColumn({ name: 'name' }); mp_ticket_issues_columns[1] = search.createColumn({ name: 'internalId' }); var mpTicketIssuesResultSet = search.create({ type: 'customlist_mp_ticket_issues', columns: mp_ticket_issues_columns }); var mp_issues_option_inline_html = ''; mpTicketIssuesResultSet.each(function(mpTicketIssueResult) { var mp_issue_name = mpTicketIssueResult.getValue('name'); var mp_issue_id = mpTicketIssueResult.getValue('internalId'); mp_issues_option_inline_html += '<option value="' + mp_issue_id + '">' + mp_issue_name + '</option >'; return true; }); $('#mp_issues').html(mp_issues_option_inline_html); $('#mp_issues').selectpicker('refresh'); $('.toll_issues_section').removeClass('hide'); $('.resolved_toll_issues_section').removeClass('hide'); $('.open_invoices').addClass('hide'); $('.invoice_issues_section').addClass('hide'); $('.resolved_invoice_issues_section').addClass('hide'); $('.user_note').addClass('hide'); $('.comment_section').removeClass('hide'); $('.reminder_section').removeClass('hide'); $('.login_email_used_section').addClass('hide'); var owner_list = [userId]; console.log(owner_list); $('#owner').selectpicker('val', owner_list); break; case 'invoice_number': if (isFinanceRole(userRole)) { $('#daytodayemail').attr('disabled', false); $('#daytodayphone').attr('disabled', false); $('#accountsemail').attr('disabled', false); $('#accountsphone').attr('disabled', false); $('#invoice_method').attr('disabled', false); $('#accounts_cc_email').attr('disabled', false); $('#mpex_po_number').attr('disabled', false); $('#customer_po_number').attr('disabled', false); $('#mpex_invoicing_cycle').attr('disabled', false); } $('.accountscontact_section').removeClass('hide'); $('.accounts_number_section').removeClass('hide'); $('.mpex_stock_used_section').addClass('hide'); $('.final_delivery').addClass('hide'); $('.enquiry_status_div').addClass('col-xs-12'); $('.enquiry_status_div').removeClass('col-xs-6'); $('.label_section').addClass('hide'); $('.enquiry_medium_section').addClass('hide'); $('.ticket_enquiry_header_section').addClass('hide'); $('.enquiry_status_div').addClass('hide'); $('.enquiry_count_section').addClass('hide'); $('.enquiry_count_breakdown_section').addClass('hide'); $('.interaction_count_breakdown_section').addClass('hide'); $('.ss_section').addClass('hide'); $('.browser_os_section').addClass('hide'); $('.phone_section').addClass('hide'); $('.login_email_section').addClass('hide'); $('.sender_details_section').addClass('hide'); $('.invoice_method_accounts_cc_email_section').removeClass('hide'); $('.mpex_customer_po_number_section').removeClass('hide'); $('.terms_section').removeClass('hide'); $('.mpex_invoicing_cycle_section').removeClass('hide'); $('.open_invoices').removeClass('hide'); // Remove MP Issues options $('#mp_issues option').each(function() { if ($(this).val() != 4) { $(this).remove(); } }); $('#mp_issues').selectpicker('refresh'); $('.toll_issues_section').addClass('hide'); $('.resolved_toll_issues_section').addClass('hide'); $('.invoice_issues_section').removeClass('hide'); $('.resolved_invoice_issues_section').removeClass('hide'); $('.user_note').removeClass('hide'); $('.comment_section').addClass('hide'); $('.reminder_section').removeClass('hide'); //Set Owner to current user var owner_list = [userId]; $('#owner').selectpicker('val', owner_list); break; case 'customer_issue': $('#daytodayemail').attr('disabled', true); $('#daytodayphone').attr('disabled', true); $('#accountsemail').attr('disabled', true); $('#accountsphone').attr('disabled', true); $('.invoice_issues_section').addClass('hide'); $('.user_note_title_section').addClass('hide'); $('.user_note_textarea_section').addClass('hide'); $('.user_note_section').addClass('hide'); $('.accountscontact_section').addClass('hide'); $('.accountscontact_section').addClass('hide'); $('.accounts_number_section').addClass('hide'); $('.mpex_stock_used_section').removeClass('hide'); $('.final_delivery').removeClass('hide'); $('.enquiry_status_div').removeClass('col-xs-12'); $('.enquiry_status_div').addClass('col-xs-6'); $('.label_section').removeClass('hide'); $('.enquiry_medium_section').removeClass('hide'); $('.ticket_enquiry_header_section').removeClass('hide'); $('.enquiry_status_div').removeClass('hide'); $('.enquiry_count_section').removeClass('hide'); $('.enquiry_count_breakdown_section').removeClass('hide'); $('.interaction_count_breakdown_section').removeClass('hide'); $('.reminder_section').addClass('hide'); $('.toll_issues_section').addClass('hide'); $('.login_email_used_section').removeClass('hide'); var current_customer_issue = $('#selector_value').val(); switch (current_customer_issue) { case 'Customer App': //App related fields $('.browser_os_section').addClass('hide'); $('.sender_details_section').addClass('hide'); $('.phone_section').removeClass('hide'); //Set current chosen option to Customer App var mp_issues_option_inline_html = '<option value="10" selected> Customer App Issue</option>'; $('#mp_issues').html(mp_issues_option_inline_html); //Requires double refresh. One for the dropwdown chnage and sceond for selection $('#mp_issues').selectpicker('refresh'); $('#mp_issues').selectpicker('refresh') break; case 'Customer Portal': //Portal related fields $('.phone_section').addClass('hide'); $('.browser_os_section').removeClass('hide'); $('.sender_details_section').addClass('hide'); var mp_issues_option_inline_html = '<option value="9" selected> Customer Portal Issue</option>'; $('#mp_issues').html(mp_issues_option_inline_html); //Requires double refresh. One for the dropwdown chnage and sceond for selection $('#mp_issues').selectpicker('refresh'); $('#mp_issues').selectpicker('refresh') break; case 'Update Label': //Label fields $('.browser_os_section').addClass('hide'); $('.phone_section').addClass('hide'); $('.sender_details_section').removeClass('hide'); var mp_issues_option_inline_html = '<option value="11" selected> Update Customer Label Issue</option>'; $('#mp_issues').html(mp_issues_option_inline_html); //Requires double refresh. One for the dropwdown chnage and sceond for selection $('#mp_issues').selectpicker('refresh'); $('#mp_issues').selectpicker('refresh'); break; } //Set Owner to Rianne Mansell var owner_list = ['1132504']; $('#owner').selectpicker('val', owner_list); break; } $(this).closest("ul").toggleClass('hide'); $(this).closest("ul").toggleClass('show'); }); $('#open_inv').click(function() { var invoice_id = $(this).data('inv-id'); var compid = (runtime.envType == "SANDBOX") ? '1048144_SB3' : '1048144'; var invoice_link = baseURL + '/app/accounting/transactions/custinvc.nl?id=' + invoice_id + '&compid=' + compid + '&cf=116&whence='; console.log("invoice_link", invoice_link); window.open(invoice_link, "_blank", "height=750,width=650,modal=yes,alwaysRaised=yes"); }) updateEnquiryMediumAndCount(); $('#reviewcontacts').click(function() { console.log("1234"); addEditContact(); }); $('#invoices_dropdown').change(function() { var invoice_status_filter = $(this, 'option:selected').val(); if (invoice_status_filter == 'open') { var invoice_section_header = 'OPEN INVOICES'; } else if (invoice_status_filter == 'paidInFull') { var invoice_section_header = 'PAID INVOICES'; } $('.open_invoices_header div div h4 span').text(invoice_section_header); updateInvoicesDatatable(); }); $('.add_as_recipient').click(function() { var email_address = $(this).data('email'); console.log(email_address); if (!isNullorEmpty(email_address)) { $(this).toggleClass('btn-success'); $(this).toggleClass('btn-danger'); if ($(this).attr('data-original-title') == 'Add as recipient') { $(this).attr('data-original-title', 'Remove recipient'); } else { $(this).attr('data-original-title', 'Add as recipient'); } $('[data-toggle="tooltip"]').tooltip(); // Convert "TO" text field to email adresses array console.log($('#send_to')); var send_to_values = $('#send_to').val().split(','); var send_to_array = []; send_to_values.forEach(function(email_address_in_send_to) { email_address_in_send_to = email_address_in_send_to.trim(); if (!isNullorEmpty(email_address_in_send_to)) { send_to_array.push(email_address_in_send_to); } }); // Add or remove selected email adress from array var firstname = $(this).data('firstname'); var firstname_array = $('#send_to').data('firstname'); if (!isNullorEmpty(firstname_array)) { firstname_array = JSON.parse($('#send_to').data('firstname')); } else { firstname_array = []; } var contact_id = $(this).data('contact-id'); var contact_id_array = $('#send_to').data('contact-id'); if (!isNullorEmpty(contact_id_array)) { contact_id_array = JSON.parse(contact_id_array); } else { contact_id_array = []; } var index_of_email_address = send_to_array.indexOf(email_address); if (index_of_email_address == -1 && $(this).hasClass('btn-danger') && !isNullorEmpty(email_address)) { send_to_array.push(email_address); if (!isNullorEmpty(firstname)) { firstname_array.push(firstname); } if (!isNullorEmpty(contact_id) || contact_id == 0) { contact_id_array.push(contact_id); } } else if ($(this).hasClass('btn-success')) { send_to_array.splice(index_of_email_address, 1); if (!isNullorEmpty(firstname)) { firstname_array.splice(firstname, 1); } if (!isNullorEmpty(contact_id)) { contact_id_array.splice(contact_id, 1); } } firstname_array = JSON.stringify(firstname_array); contact_id_array = JSON.stringify(contact_id_array); // Convert array to text field var send_to = ''; send_to_array.forEach(function(email_address) { send_to += email_address + ', '; }); send_to = send_to.slice(0, -2); console.log('send_to : ', send_to); $('#send_to').val(send_to); $('#send_to').data('firstname', firstname_array); $('#send_to').data('contact-id', contact_id_array); } }); $('#credit_memo tbody td[headers="credit_memo_action"] button, #usage_report tbody td[headers="usage_report_action"] button, button#add_inv').on('click', function() { attachFileButton.call(this) }); $('#acc_manager_button').click(function() { var account_manager_email = $('#acc_manager').data('email'); var send_cc_field = $('#send_cc').val(); if (isNullorEmpty(send_cc_field)) { $('#send_cc').val(account_manager_email); } else { $('#send_cc').val(send_cc_field + ', ' + account_manager_email); } }); $('#template').change(function() { loadTemplate() }); $('#send_email').click(function() { sendEmail() }); $('#toll_issues, #invoice_issues').on('change', function() { hideCloseTicketButton() }); $('#mp_issues').change(function() { selectOwner(); hideCloseTicketButton(); }); $('#cancelbutton').click(function() { onCancel() }); $('#closeticketbutton').click(function() { closeTicket(selector_type, '') }); $('#closenewticketbutton').click(function() { console.log("in close new"); closeNewTicket() }); $('#closelostbutton').click(function() { closeTicketLost() }); $('#closeunallocatedbutton').click(function() { closeUnallocatedTicket() }); $('#reopenticketbutton').click(function() { reopenTicket() }); $('#updateticketbutton').click(function() { updateAndNew(); }); $('#updatecloseticketbutton').click(function() { console.log("btn clicked"); if (confirm("Are you sure you want to update and close this ticket?\n\nThis action cannot be undone.")) { console.log('Update & Closed Started'); updateSaveRecord(); updateCloseTicket(); console.log("Update finished"); //updateCloseTicket(); } }); $('#openticketbutton').click(function() { console.log("hi"); //saveRecord(); $('#submitter').trigger('click'); }); $('#opennewticketbutton').click(function() { openAndNew(); }); $('#escalatebutton').click(function() { escalateTicket(ticket_id, selector_number, selector_type); }); $('#escalaterianne').click(function() { console.log("Escalating to rianne"); var ticketRecord = record.load({ type: 'customrecord_mp_ticket', id: parseInt(ticket_id), }); var comments = $('#comment').val(); console.log('comments', comments); if (isNullorEmpty(comments)) { console.log('Enter comment before Escalation', comments); showAlert('Please enter a Comment before escalating to IT'); return false; } if (isNullorEmpty(ticketRecord.getValue({fieldId: 'custrecord_date_escalated_it'}))) { ticketRecord.setValue({fieldId: 'custrecord_date_escalated_it', value: new Date()}); var owner_list = ['1132504']; $('#owner').selectpicker('val', owner_list); ticketRecord.setValue({fieldId: 'custrecord_owner', value: owner_list}); ticketRecord.save({ enableSourcing: true, ignoreMandatoryFields: true }); sendCustomerTicketEmail('', parseInt(ticket_id), customer_number, selector_type, selector_number, $("#browser_value option:selected").text(), $('#os_value option:selected').text(), $('#login_email_text').val(), '', '', ["rianne.mansell@mailplus.com.au"]); var output = url.resolveScript({ deploymentId: 'customdeploy_sl_edit_ticket_2', scriptId: 'customscript_sl_edit_ticket_2', }); var upload_url = baseURL + output; window.open(upload_url, "_self", "height=750,width=650,modal=yes,alwaysRaised=yes"); } else { console.log('didnt work for some reason'); } }); $('#escalateankith').click(function() { var ticketRecord = record.load({ type: 'customrecord_mp_ticket', id: parseInt(ticket_id), }); var interaction_count_by_phone = $('#interaction_count_by_phone').val(); var interaction_count_by_email = $('#interaction_count_by_email').val(); var customer_number = $('#customer_number_value').val().trim(); var creator_id = ticketRecord.getValue({fieldId: 'custrecord_creator'}); var escalated_to_it = ticketRecord.getValue({ fieldId: 'custrecord_date_escalated_it' }); var first_interaction = ticketRecord.getValue({ fieldId: 'custrecord_first_interaction_date' }); if (isNullorEmpty(customer_number) && creator_id == 112209 && !isNullorEmpty(escalated_to_it) && selector_type == "customer_issue" && !isNullorEmpty(ticket_id)) { console.log('Enter customer number before Escalation'); showAlert('Please enter a Customer Number'); return false; } else if (isNullorEmpty(first_interaction) && interaction_count_by_phone == 0 && interaction_count_by_email == 0) { console.log('Incrememnt interaction count before Escalation'); showAlert('Please Interact with Customer before Escalation'); return false; } ticketRecord.setValue({fieldId: 'custrecord_ticket_status', value: 10}); var owner_list = ['409635']; $('#owner').selectpicker('val', owner_list); ticketRecord.setValue({fieldId: 'custrecord_owner', value: owner_list}); ticketRecord.save({ enableSourcing: true, ignoreMandatoryFields: true }); var subject = 'MPSD' + ticket_id + ' - Customer Issue Ticket Escalated'; var customer_id = ticketRecord.getValue({fieldId: 'custrecord_customer1'}); var login_email = ticketRecord.getText({fieldId: 'custrecord_login_email'}); sendCustomerTicketEmail(subject, parseInt(ticket_id), customer_number, selector_type, selector_number, $("#browser_value option:selected").text(), $('#os_value option:selected').text(), $('#login_email_text').val(), '', '', ["ankith.ravindran@mailplus.com.au"]); if (!isNullorEmpty(login_email)) { sendCustomerEscalateEmail('MailPlus [MPSD' + parseInt(ticket_id) + '] - Your IT ticket has been escalated - Customer Portal', [login_email], 120, customer_id); } var output = url.resolveScript({ deploymentId: 'customdeploy_sl_edit_ticket_2', scriptId: 'customscript_sl_edit_ticket_2', }); var upload_url = baseURL + output; window.open(upload_url, "_self", "height=750,width=650,modal=yes,alwaysRaised=yes"); }); $('#escalateunderdev').click(function() { saveRecord(); var ticketRecord = record.load({ type: 'customrecord_mp_ticket', id: parseInt(ticket_id), }); ticketRecord.setValue({fieldId: 'custrecord_ticket_status', value: 17}); ticketRecord.save({ enableSourcing: true, ignoreMandatoryFields: true }); location.reload(); }); $('#escalateremoveunderdev').click(function() { saveRecord(); var ticketRecord = record.load({ type: 'customrecord_mp_ticket', id: parseInt(ticket_id), }); ticketRecord.setValue({fieldId: 'custrecord_ticket_status', value: 10}); ticketRecord.save({ enableSourcing: true, ignoreMandatoryFields: true }); location.reload(); }); $('#closeresolvedbutton').click(function() { closeTicket(selector_type, 15); }); $('#closeunresolvedbutton').click(function() { closeTicket(selector_type, 16); }); // Prevent the ticket to be submitted on enter. $('input, textarea').keydown(function(e) { if (e.keyCode == 13) { e.preventDefault(); return false; } }); // Add a newline at the end of the comment textarea when enter is pressed // This will not create the newline where the cursor is in the text $('textarea#comment').keydown(function(e) { if (e.keyCode == 13) { var comment = $(this).val(); comment += '\n'; $(this).val(comment); return false; } }); //Event listener for customer number input and selector value input $('#customer_number_value, #selector_value').change(function() { checkMandatoryFields(); }); } function escalateTicket(ticket_id, selector_number, selector_type) { var answer = window.confirm("Are you sure you want to escalate this ticket?"); if (answer) { //SET FIELDS IN RECORD //some code // REDIRECT TO URL console.log("IN HERE"); var params = { ticket_id: parseInt(ticket_id), selector_number: selector_number, selector_type: selector_type }; params = JSON.stringify(params); var output = url.resolveScript({ deploymentId: 'customdeploy_sl_ticketing_escalate', scriptId: 'customscript_sl_ticketing_escalate', }); var upload_url = baseURL + output + '&custparam_params=' + params; var ticketRecord = record.load({ type: 'customrecord_mp_ticket', id: Math.floor(ticket_id), }); var customerstatus = ticketRecord.getValue({fieldId: 'custrecord_mp_ticket_customer_status'}); var ticketstatus = ticketRecord.getValue({fieldId: 'custrecord_ticket_status'}); var customer_id = ticketRecord.getValue({fieldId: 'custrecord_customer1'}); var customer_barcode_number = ticketRecord.getValue({ fieldId : 'custrecord_barcode_number'}); var ticket_name = ticketRecord.getText({fieldId: 'name'}); console.log('customerstatus', customerstatus); if (parseInt(customerstatus) < 4 ) { console.log(customerstatus); ticketRecord.setValue({fieldId: 'custrecord_mp_ticket_customer_status', value: parseInt(customerstatus) + 1}); } if (parseInt(ticketstatus) < 11 ) { console.log(ticketstatus); ticketRecord.setValue({fieldId: 'custrecord_ticket_status', value: 11}); } else if (parseInt(ticketstatus) < 14) { console.log(ticketstatus); ticketRecord.setValue({fieldId: 'custrecord_ticket_status', value: parseInt(ticketstatus) + 1}); } ticketRecord.save({ enableSourcing: true, }) //Send email to Receiver var barcodeRecord = record.load({ type: 'customrecord_customer_product_stock', id: customer_barcode_number, }); var receiveremail = barcodeRecord.getValue({fieldId: 'custrecord_receiver_email'}); var barcodeName = barcodeRecord.getValue({fieldId: 'name'}); var ticketRecord = record.load({ type: 'customrecord_mp_ticket', id: Math.floor(ticket_id), }) var ticketstatus = ticketRecord.getValue({fieldId: 'custrecord_ticket_status'}); if (!isNullorEmpty(receiveremail)) { if (ticketstatus == 11) { sendCustomerEscalateEmail('MailPlus [' + ticket_name + '] - Support enquiry | Stage 1 - ' + barcodeName, [receiveremail], 109, customer_id); } else if (ticketstatus == 12) { sendCustomerEscalateEmail('MailPlus [' + ticket_name + '] - Support enquiry | Stage 2 - ' + barcodeName, [receiveremail], 110, customer_id); } else if (ticketstatus == 13) { sendCustomerEscalateEmail('MailPlus [' + ticket_name + '] - Support enquiry | Stage 3 - ' + barcodeName, [receiveremail], 111, customer_id); } } //Send email to TOLL var toll_issues = ticketRecord.getText({ fieldId: 'custrecord_toll_issues' }); var mp_issues = ticketRecord.getText({ fieldId: 'custrecord_mp_ticket_issue' }); var body = 'MP Ticket ID: ' + ticket_name + '\n Barcode: ' + barcodeName + '\nToll Issues: ' + toll_issues + '\nMP Issues: ' + mp_issues; // if (ticketstatus == 11) { // email.send({ // author: 112209, // body: body, // recipients: ['sruti.desai@mailplus.com.au'], // subject: 'Ticket Escalated: Escalation 1- ' + ticket_name, // relatedRecords: {record: ticket_id, recordtype: 1042} // }); // } else if (ticketstatus == 12) { // email.send({ // author: 112209, // body: body, // recipients: ['sruti.desai@mailplus.com.au'], // subject: 'Ticket Escalated: Escalation 2- ' + ticket_name, // relatedRecords: {record: ticket_id, recordtype: 1042}, // }); // } else if (ticketstatus == 13) { // email.send({ // author: 112209, // body: body, // recipients: ['sruti.desai@mailplus.com.au'], // subject: 'Ticket Escalated: Escalation 3- ' + ticket_name, // relatedRecords: {record: ticket_id, recordtype: 1042}, // }); // } console.log("upload", upload_url) window.open(upload_url, '_self'); } else { //some code } } /** * Function to sent emails when a customer associated ticket is escalated */ function sendCustomerEscalateEmail(subject, recipients, template, customer_id) { var sales_rep = encodeURIComponent(runtime.getCurrentUser().name); var userid = encodeURIComponent(runtime.getCurrentUser().id); var suiteletUrl = url.resolveScript({ scriptId: 'customscript_merge_email', deploymentId: 'customdeploy_merge_email', returnExternalUrl: true }); suiteletUrl += '&rectype=customer&template='; suiteletUrl += template + '&recid=' + customer_id + '&salesrep=' + sales_rep + '&dear=' + '' + '&contactid=' + null + '&userid=' + userid; console.log(suiteletUrl); var response = https.get({ url: suiteletUrl }); var emailHtml = response.body; if (!isNullorEmpty(customer_id)) { email.send({ author: 112209, body: emailHtml, recipients: recipients, subject: subject, relatedRecords: { entityId: customer_id} }); } else { email.send({ author: 112209, body: emailHtml, recipients: recipients, subject: subject, }); } } function commentsDate() { var today = new Date(); var dd = today.getDate(); var mm = today.getMonth()+1; var yyyy = today.getFullYear(); if(dd<10) { dd='0'+dd; } if(mm<10) { mm='0'+mm; } today = mm+'/'+dd+'/'+yyyy; return today; } function saveRecord(context) { var currRec = currentRecord.get(); var status_value = currRec.getValue({ fieldId: 'custpage_ticket_status_value' }); var selector_issue = currRec.getValue({ fieldId: 'custpage_selector_issue' }); //set to T onEscalate var selector_type = currRec.getValue({ fieldId: 'custpage_selector_type' }); var customer_number = currRec.getValue({ fieldId: 'custpage_customer_number' }); var selector_number = $('#selector_value').val(); console.log('status_value' + status_value) console.log('selector_issue ' + selector_issue) console.log('selector_type ' + selector_type) console.log('selector_number ' + selector_number) if (selector_type == 'customer_issue') { if (isNullorEmpty(customer_number)) { showAlert('Please enter a customer number'); return false; } } if (isTicketNotClosed(status_value) && !isNullorEmpty(selector_type)) { // Barcode/Inv associated tickets - check that a TOLL Issue or an Invoice Issue has been selected. // Customer number associated ticket - check that a customer number has been entered switch (selector_type) { case 'barcode_number': var toll_issues_length = $('#toll_issues option:selected').length; if (toll_issues_length == 0) { showAlert('Please select a TOLL Issue<br>'); return false; } break; case 'invoice_number': var invoice_issues_length = $('#invoice_issues option:selected').length; if (invoice_issues_length == 0) { showAlert('Please select an Invoice Issue<br>'); return false; } break; case 'customer_issue': var login_email_used = $('#login_email_text').val(); if (!isNullorEmpty(login_email_used) && !validateEmail(login_email_used)) { showAlert('User login email format is invalid. Please enter email again <br>'); return false; } break; } } if (role == 1005) { var owner_length = $('#owner option:selected').length; if (owner_length == 0) { showAlert('Please select an Owner<br>'); return false; } } else { var owner_length = $('#owner option:selected').length; var checkTicketOwner = currRec.getValue({ fieldId: 'custpage_ticket_id' }); if (!isNullorEmpty(checkTicketOwner)) { var checkTicketOwnerRec = record.load({ type: 'customrecord_mp_ticket', id: parseInt(checkTicketOwner) }); var owners = checkTicketOwnerRec.getValue({ fieldId: 'custrecord_owner'}); if (isNullorEmpty(owners) && owner_length == 0) { showAlert('Please select an Owner<br>'); return false; } } else { if (owner_length == 0) { showAlert('Please select an Owner<br>'); return false; } } } if (selector_issue == 'T') { var to = $('#owner option:selected').map(function() { return $(this).data('email') }); to = $.makeArray(to); var email_sent = sendInformationEmailTo(selector_type, to, true) if (!email_sent) { return false; } } var ticket_id = currRec.getValue({ fieldId: 'custpage_ticket_id' }); console.log("Ticket id = " + ticket_id); if (isNullorEmpty(ticket_id)) { var ticketRecord = record.create({ type: 'customrecord_mp_ticket', }); currRec.setValue({ fieldId: 'custpage_created_ticket', value: 'T' }); ticketRecord.setValue({ fieldId: 'custrecord_email_sent', value: false }); } else { ticket_id = parseInt(ticket_id); try { var ticketRecord = record.load({ type: 'customrecord_mp_ticket', id: ticket_id }); } catch (e) { if (e instanceof error.SuiteScriptError) { if (e.name == "SSS_MISSING_REQD_ARGUMENT") { console.log('Error to load the ticket record with ticket_id : ' + ticket_id); } } } } currRec.setValue({ fieldId: 'custpage_selector_number', value: selector_number }); var selector_id = currRec.getValue({ fieldId: 'custpage_selector_id' }); // Save customer number var customer_number = $('#customer_number_value').val(); console.log('Saving customer number = ' + customer_number); ticketRecord.setValue({ fieldId: 'custrecord_cust_number', value: customer_number }); // Save Enquiry status var enquiry_status_val = $('#enquiry_status option:selected').val(); if (!isNullorEmpty(enquiry_status_val)) { ticketRecord.setValue({ fieldId: 'custrecord_enquiry_status', value: enquiry_status_val }); } var attachments_hyperlink = $('#attachments').val(); if (!isNullorEmpty(attachments_hyperlink)) { ticketRecord.setValue({ fieldId: 'custrecord_mp_ticket_attachments', value: attachments_hyperlink }); } // Save Ticket Label var label = $('#label_status option:selected').val(); if (!isNullorEmpty(label)) { ticketRecord.setValue({ fieldId: 'custrecord_ticket_label', value: label }); } //Save Enquiry medium var enquiry_medium = $('#enquiry_status option:selected').val(); if (!isNullorEmpty(enquiry_medium)) { ticketRecord.setValue({ fieldId: 'custrecord_enquiry_medium', value: enquiry_medium }); } var total_enquiry_count = 0; if (!isNullorEmpty($('#enquiry_count_by_chat').val())) { total_enquiry_count += parseInt($('#enquiry_count_by_chat').val()); } if (!isNullorEmpty($('#enquiry_count_by_phone').val())) { total_enquiry_count += parseInt($('#enquiry_count_by_phone').val()); } if (!isNullorEmpty($('#enquiry_count_by_email').val())) { total_enquiry_count += parseInt($('#enquiry_count_by_email').val()); } ticketRecord.setValue({ fieldId: 'custrecord_enquiry_count', value: total_enquiry_count }); var enquiry_count_by_chat = $('#enquiry_count_by_chat').val(); if (!isNullorEmpty(enquiry_count_by_chat)) { ticketRecord.setValue({ fieldId: 'custrecord_chat_enquiry_count', value: enquiry_count_by_chat }); } var enquiry_count_by_phone = $('#enquiry_count_by_phone').val(); if (!isNullorEmpty(enquiry_count_by_phone)) { ticketRecord.setValue({ fieldId: 'custrecord_phone_enquiry_count', value: enquiry_count_by_phone }); } var enquiry_count_by_email = $('#enquiry_count_by_email').val(); if (!isNullorEmpty(enquiry_count_by_email)) { ticketRecord.setValue({ fieldId: 'custrecord_email_enquiry_count', value: enquiry_count_by_email }); } var interaction_count_by_phone = $('#interaction_count_by_phone').val(); var interaction_count_by_email = $('#interaction_count_by_email').val(); if (isNullorEmpty(ticketRecord.getValue({ fieldId: 'custrecord_first_interaction_date'}))) { if (!isNullorEmpty(interaction_count_by_email) || !isNullorEmpty(interaction_count_by_phone)) { ticketRecord.setValue({ fieldId: 'custrecord_first_interaction_date', value: new Date()}); } } if (!isNullorEmpty(interaction_count_by_phone)) { ticketRecord.setValue({ fieldId: 'custrecord_phone_interaction_count', value: interaction_count_by_phone }); } if (!isNullorEmpty(interaction_count_by_email)) { ticketRecord.setValue({ fieldId: 'custrecord_email_interaction_count', value: interaction_count_by_email }); } //Check Enquiry is Selected if (isNullorEmpty(enquiry_count_by_chat) && isNullorEmpty(enquiry_count_by_phone) && isNullorEmpty(enquiry_count_by_email)) { showAlert('Please select an Enquiry Type<br>'); return false; } else if(total_enquiry_count == 0) { showAlert('Please select an Enquiry Type<br>'); return false; } //Save Medium list saveMediumList(enquiry_count_by_chat, enquiry_count_by_phone, enquiry_count_by_email, ticketRecord); ticketRecord = setTicketStatus(ticketRecord); ticketRecord = setCreator(ticketRecord); ticketRecord.setValue({ fieldId: 'altname', value: selector_number }); var owner_email_list = $('#owner option:selected').map(function() { return $(this).data('email') }); owner_email_list = $.makeArray(owner_email_list); var zee_id = currRec.getValue({ fieldId: 'custpage_zee_id' }); ticketRecord.setValue({ fieldId: 'custrecord_zee', value: zee_id }); console.log("sending email..." + selector_type); if (!isNullorEmpty(selector_type)) { switch (selector_type) { case 'barcode_number': ticketRecord.setValue({ fieldId: 'custrecord_barcode_number', value: selector_id }); // Save Reminder date var reminder_date = $('#reminder').val(); if (!isNullorEmpty(reminder_date)) { reminder_date = new Date(reminder_date); reminder_date = format.parse({ value: reminder_date, type: format.Type.DATE }); ticketRecord.setValue({ fieldId: 'custrecord_reminder', value: reminder_date }); } break; case 'invoice_number': ticketRecord.setValue({ fieldId: 'custrecord_invoice_number', value: selector_id }); var customer_id = currRec.getValue({ fieldId: 'custpage_customer_id' }); ticketRecord.setValue({ fieldId: 'custrecord_customer1', value: customer_id }); if (isFinanceRole(userRole)) { var daytodayemail = $('#daytodayemail').val(); var daytodayphone = $('#daytodayphone').val(); var accountsemail = $('#accountsemail').val(); var accountsphone = $('#accountsphone').val(); var selected_invoice_method_id = $('#invoice_method option:selected').val(); var accounts_cc_email = $('#accounts_cc_email').val(); var mpex_po_number = $('#mpex_po_number').val(); var customer_po_number = $('#customer_po_number').val(); var customer_terms = $('#customers_terms').val(); var selected_invoice_cycle_id = $('#mpex_invoicing_cycle option:selected').val(); var customerRecord = record.load({ type: 'customer', id: customer_id }); customerRecord.setValue({ fieldId: 'custentity_email_service', value: daytodayemail }); customerRecord.setValue({ fieldId: 'phone', value: daytodayphone }); customerRecord.setValue({ fieldId: 'email', value: accountsemail }); customerRecord.setValue({ fieldId: 'altphone', value: accountsphone }); customerRecord.setValue({ fieldId: 'custentity_invoice_method', value: selected_invoice_method_id }); customerRecord.setValue({ fieldId: 'custentity_accounts_cc_email', value: accounts_cc_email }); customerRecord.setValue({ fieldId: 'custentity_mpex_po', value: mpex_po_number }); customerRecord.setValue({ fieldId: 'custentity11', value: customer_po_number }); customerRecord.setValue({ fieldId: 'custentity_finance_terms', value: customer_terms }); customerRecord.setValue({ fieldId: 'custentity_mpex_invoicing_cycle', value: selected_invoice_cycle_id }); customerRecord.save({}) // Save Reminder date var reminder_date = $('#reminder').val(); if (!isNullorEmpty(reminder_date)) { reminder_date = new Date(reminder_date); reminder_date = format.parse({ value: reminder_date, type: format.Type.DATE }); ticketRecord.setValue({ fieldId: 'custrecord_reminder', value: reminder_date}); } } break; case 'customer_issue': var screenshot_image = currRec.getValue({ fieldId: 'custpage_ss_image' }); if (!isNullorEmpty(screenshot_image)) { ticketRecord.setValue({ fieldId: 'custrecord_screenshot', value: screenshot_image}); } var customer_id = currRec.getValue({ fieldId: 'custpage_customer_id' }); if (!isNullorEmpty(customer_id)) { ticketRecord.setValue({ fieldId: 'custrecord_customer1', value: customer_id}); } var customer_issue_type = $('#selector_value').val(); if (!isNullorEmpty(customer_issue_type)) { ticketRecord.setValue({ fieldId: 'custrecord_customer_issue', value: customer_issue_type}); } var login_email_used = $('#login_email_text').val(); if (!isNullorEmpty(login_email_used)) { ticketRecord.setValue({ fieldId: 'custrecord_login_email', value: login_email_used}); } var is_customer_number_email_sent = currRec.getValue({ fieldId: 'custpage_customer_number_email_sent' }); console.log("cust iss typ", customer_issue_type); switch (customer_issue_type) { case 'Customer App': console.log("in cust app"); var phone_used = $('#phone_used').val(); if (!isNullorEmpty(phone_used)) { ticketRecord.setValue({ fieldId: 'custrecord_phone_used', value: phone_used}); } if (is_customer_number_email_sent == 'F' && !isNullorEmpty(ticket_id)) { sendCustomerTicketEmail('',ticket_id, customer_number, selector_type, selector_number, '', '', login_email_used, '', '', owner_email_list); ticketRecord.setValue({ fieldId: 'custrecord_customer_number_email_sent', value: true }); } break; case 'Customer Portal': var browser = $("#browser_value option:selected").val(); if (!isNullorEmpty(browser)) { ticketRecord.setValue({ fieldId: 'custrecord_browser', value: browser}); } var os_used = $('#os_value option:selected').val(); if (!isNullorEmpty(os_used)) { ticketRecord.setValue({ fieldId: 'custrecord_operating_system', value: os_used}); } if (is_customer_number_email_sent == 'F' && !isNullorEmpty(ticket_id)) { sendCustomerTicketEmail('',ticket_id, customer_number, selector_type, selector_number, $("#browser_value option:selected").text(), $('#os_value option:selected').text(), login_email_used, '', '', owner_email_list); ticketRecord.setValue({ fieldId: 'custrecord_customer_number_email_sent', value: true }); } break; case 'Update Label': var sender_name = $('#sender_name_text').val(); if (!isNullorEmpty(sender_name)) { ticketRecord.setValue({ fieldId: 'custrecord_sender_name', value: sender_name}); } var sender_phone = $('#sender_phone_text').val(); if (!isNullorEmpty(sender_phone)) { ticketRecord.setValue({ fieldId: 'custrecord_sender_phone', value: sender_phone}); } if (is_customer_number_email_sent == 'F' && !isNullorEmpty(ticket_id)) { sendCustomerTicketEmail('',ticket_id, customer_number, selector_type, selector_number, '', '', login_email_used, sender_name, sender_phone, owner_email_list); ticketRecord.setValue({ fieldId: 'custrecord_customer_number_email_sent', value: true }); } break; } break; } } ticketRecord = updateIssues(ticketRecord); //Owner var owner_list = new Array; $('#owner option:selected').each(function() { owner_list.push($(this).val()); }); if (!isNullorEmpty(ticket_id)) { // Send email to new owners. var old_owner_list = ticketRecord.getValue({ fieldId: 'custrecord_owner' }); if (!isNullorEmpty(old_owner_list)) { var only_new_owner_ids = []; var only_new_owner_email_address = []; owner_list.forEach(function(new_owner_id) { if (old_owner_list.indexOf(new_owner_id) == -1) { only_new_owner_ids.push(new_owner_id); only_new_owner_email_address.push($('#owner [value="' + new_owner_id + '"]').data('email')); } }) } else { var only_new_owner_ids = owner_list; var only_new_owner_email_address = []; owner_list.forEach(function(owner_id) { only_new_owner_email_address.push($('#owner [value="' + owner_id + '"]').data('email')); }) } console.log('selector_issue ' + selector_issue); console.log('only_new_owner_email_address ' + only_new_owner_email_address); console.log('selector_type ' + selector_type); // If there is an issue, all the owners have already received an email. if (selector_issue == 'F' && (!isNullorEmpty(only_new_owner_email_address))) { console.log('ISSUE'); var email_sent = sendInformationEmailTo(selector_type, only_new_owner_email_address, false); if (!email_sent) { return false; } } else if (selector_type == 'customer_issue') { var login_email_used = $('#login_email_text').val(); var customer_issue_type = $('#selector_value').val(); switch (customer_issue_type) { case 'Customer App': var phone_used = $('#phone_used').val(); var os_used = $('#os_value option:selected').val(); var browser = $("#browser_value option:selected").val() sendCustomerTicketEmail('',ticket_id, customer_number, selector_type, selector_number, $("#browser_value option:selected").text(), $('#os_value option:selected').text(), login_email_used, '', '', only_new_owner_email_address); break; case 'Customer Portal': var browser = $('#browser_value').val(); sendCustomerTicketEmail('',ticket_id, customer_number, selector_type, selector_number, $("#browser_value option:selected").text(), '', login_email_used, '', '', only_new_owner_email_address); break; case 'Update Label': var sender_phone = $('#sender_phone_text').val(); var sender_name = $('#sender_name_text').val(); sendCustomerTicketEmail('',ticket_id, customer_number, selector_type, selector_number, '', '', login_email_used, sender_name, sender_phone, only_new_owner_email_address); break; } } } // Save Owner list console.log(owner_list); ticketRecord.setValue({ fieldId: 'custrecord_owner', value: owner_list }); console.log("oList", ticketRecord.getValue({ fieldId: 'custrecord_owner'})); //cxcxc // Save Comment switch (selector_type) { case 'barcode_number': var comment = $('#comment').val(); break; case 'invoice_number': var comment = ticketRecord.getValue({ fieldId: 'custrecord_comment' }); if (isNullorEmpty(comment)) { comment = '' }; var selected_title = $('#user_note_title option:selected').text(); var usernote_textarea = $('#user_note_textarea').val(); var date = new Date; var date_time_now = format.parse({ value: date, type: format.Type.DATETIMETZ}); var date_now = format.parse({ value: date, type: format.Type.DATE}); var time_now = format.parse({ value: date, type: format.Type.TIMEOFDAY}); if (!isNullorEmpty(usernote_textarea)) { if (!isNullorEmpty(comment)) { comment += '\n'; } var usernote = '[' + selected_title + '] - [' + userName + '] - [' + date_time_now + '] - ' + usernote_textarea; // Save usernote on Customer record var userNote = record.create({ type: 'note', }); userNote.setValue({ fieldId: 'title', value: selected_title}); userNote.setValue({ fieldId: 'notedate', value: date_now}); userNote.setValue({ fieldId: 'time', value: time_now}); userNote.setValue({ fieldId: 'note', value: usernote_textarea}); userNote.setValue({ fieldId: 'entity', value: customer_id}); if (!isNullorEmpty(customer_id)) { userNote.save({}) } comment += usernote; } break; case 'customer_issue': var comment = $('#comment').val(); break; } if (!isNullorEmpty(comment)) { var original_comment = ticketRecord.getValue({ fieldId: 'custrecord_comment'} ); var total_comment = $('#comment').val(); var new_comment = total_comment.split(original_comment).join(''); var new_comment = total_comment.split(original_comment).join(''); var new_comment2 = new_comment.split("\n").join(''); var date_netsuite = format.format({ value: new Date(), type: format.Type.DATETIME }); console.log("new_comment", new_comment); console.log("new_comment2", new_comment2); var comment_with_date = total_comment; if (!isNullorEmpty(new_comment2)) { comment_with_date = "\n" + original_comment + "\n" + date_netsuite + " - " + new_comment2 + "\n"; } console.log('comment_with_date', comment_with_date); ticketRecord.setValue({ fieldId: 'custrecord_comment', value: comment_with_date} ); } var ticket_id = ticketRecord.save({ enableSourcing: true, }); currRec.setValue({ fieldId: 'custpage_ticket_id', value: ticket_id} ); if (!isNullorEmpty(selector_id) && (selector_type == 'barcode_number')) { try { var list_toll_issues = new Array; $('#toll_issues option:selected').each(function() { list_toll_issues.push($(this).val()); }); var barcodeRecord = record.load({ type: 'customrecord_customer_product_stock', id: selector_id }); console.log("ticket_id", ticket_id); console.log("list_toll_issues", list_toll_issues); barcodeRecord.setValue({ fieldId: 'custrecord_mp_ticket', value: ticket_id} ); barcodeRecord.setValue({ fieldId: 'custrecord_cust_prod_stock_toll_issues ', value: list_toll_issues }); var rec_email = $('#receiveremail').val(); var rec_name = $('#receivername').val(); var rec_state = $('#receiverstate').val(); var rec_zip = $('#receiverzip').val(); var rec_addr1 = $('#receiveraddr1').val(); var rec_addr2 = $('#receiveraddr2').val(); var rec_city = $('#receiversuburb').val(); var rec_phone = $('#receiverphone').val(); //Check if Rec details are to be updated if (!$("#receiveremail").is(":disabled")) { if (!isNullorEmpty(rec_email)) { barcodeRecord.setValue({ fieldId: 'custrecord_receiver_email', value: rec_email }); } if (!isNullorEmpty(rec_name)) { barcodeRecord.setValue({ fieldId: 'custrecord_receiver_name', value: rec_name }); } if (!isNullorEmpty(rec_state)) { barcodeRecord.setValue({ fieldId: 'custrecord_receiver_state', value: rec_state }); } if (!isNullorEmpty(rec_zip)) { barcodeRecord.setValue({ fieldId: 'custrecord_receiver_postcode', value: rec_zip }); } if (!isNullorEmpty(rec_addr1)) { barcodeRecord.setValue({ fieldId: 'custrecord_receiver_addr1', value: rec_addr1 }); } if (!isNullorEmpty(rec_addr2)) { barcodeRecord.setValue({ fieldId: 'custrecord_receiver_addr2', value: rec_addr2 }); } if (!isNullorEmpty(rec_city)) { barcodeRecord.setValue({ fieldId: 'custrecord_receiver_suburb', value: rec_city }); } if (!isNullorEmpty(rec_phone)) { barcodeRecord.setValue({ fieldId: 'custrecord_receiver_phone', value: rec_phone }); } } barcodeRecord.save({ enableSourcing: true, }); } catch (e) { console.log('Error to load the barcode record with barcode_id : ' + selector_id); } } return true; } /** * Takes action depending on which of the two fields (Customer number or Barcode/Inv number) is filled */ function checkMandatoryFields() { var currRec = currentRecord.get(); console.log("checkMandatoryField"); var selector_number = $('#selector_value').val().trim().toUpperCase(); var customer_number = $('#customer_number_value').val().trim(); var selector_type = $('#selector_text').text().toLowerCase().split(' ').join('_'); var ticket_records = null; if (!isNullorEmpty(customer_number) && isCustomerNumberValid(customer_number)) { currRec.setValue({ fieldId: 'custpage_customer_number', value: customer_number }); var customer_id = getCustomerID(customer_number); console.log("cid", customer_id); currRec.setValue({ fieldId: 'custpage_customer_id', value: customer_id }); if (!isNullorEmpty(selector_number)) { switch (selector_type) { case "barcode_number": case "invoice_number": displayCustomerInfo(); break; case "customer_issue": } } ticket_records = searchTicketRecords(customer_number); console.log('Current tickets on customer number ' + customer_number + ': ' + ticket_records); var customer_record = customerLinkedToCustomerNum(customer_number); if (!isNullorEmpty(customer_record)) { //Display franchisee details displayFranchiseeInfo(customer_record); } if (!isNullorEmpty(ticket_records)) { //If tickets exist with this customer number, display customer number tickets datatable updateCustomerNumTicketsTable(ticket_records); } else { console.log('Removing table'); //Remove tickets datatable $('#customer_number_tickets_preview_wrapper').hide(); //Show no ticket exists info box $('#info').text('No ticket exists for the customer '); $('#info').parent().show(); } } if (!isNullorEmpty(selector_number) && isNullorEmpty(customer_number)) { switch (selector_type) { case "barcode_number": if (validateSelectorInput()) { displayCustomerInfo(); } break; case "invoice_number": if (validateSelectorInput()) { displayCustomerInfo(); } break; case "customer_issue": break; } } if (isNullorEmpty(customer_number) && isNullorEmpty(selector_number)) { showAlert('Please enter a customer number or a barcode/invoice number'); //Remove tickets datatable $('#customer_number_tickets_preview_wrapper').hide(); //Reload page var output = url.resolveScript({ deploymentId: 'customdeploy_sl_open_ticket_2', scriptId: 'customscript_sl_open_ticket_2', }) var upload_url = baseURL + output; window.open(upload_url, "_self", "height=750,width=650,modal=yes,alwaysRaised=yes"); } } function updateCustomerNumTicketsTable(ticket_records_dataset) { console.log('Inside update customer tickets table'); $('#customer_number_tickets_preview_wrapper').show(); $('#customer_number_tickets_preview').show(); if (!($.fn.dataTable.isDataTable('#customer_number_tickets_preview'))) { //Initialise new datatable $('#customer_number_tickets_preview').DataTable({ data: ticket_records_dataset, select: { style: 'single' }, columns: [{ title: "ID" }, { title: "Customer Number" }, { title: "Name" }, { title: "Barcode Number" }, { title: "Invoice Number" }, { title: "Customer Issue" }, { title: "Owner" }, { title: "Date created" }] }); //Row selection $('#customer_number_tickets_preview tbody').on('click', 'tr', function() { if ($(this).hasClass('selected')) { $(this).removeClass('selected'); } else { $('#customer_number_tickets_preview tr.selected').removeClass('selected'); $(this).addClass('selected'); var selected_row = $('#customer_number_tickets_preview > tbody > tr.selected'); updateFields(selected_row); } }); } else { //Update datatable rows var datatable = $('#customer_number_tickets_preview').DataTable().clear(); datatable.rows.add(ticket_records_dataset); datatable.draw(); } } function updateFields(selected_row) { //All tickets in here always exist so we can directly redirect to the Edit ticket page console.log('Inside update fields'); var barcode_number = selected_row.children()[3].textContent.trim(); var invoice_number = selected_row.children()[4].textContent.trim(); var customer_issue_type = selected_row.children()[5].textContent.trim(); var ticket_id = selected_row.children()[0].textContent.trim(); if (!isNullorEmpty(barcode_number) || !isNullorEmpty(invoice_number)) { var selector_type = isNullorEmpty(barcode_number) ? "invoice_number" : "barcode_number"; currRec.setValue({ fieldId: 'custpage_selector_type', value: selector_type }); //Set selector value var selector_number = isNullorEmpty(barcode_number) ? invoice_number : barcode_number; $('#selector_value').val(selector_number); // If a ticket already exists for the barcode number, the user is redirected to the "Edit Ticket" page. if (ticketLinkedToSelector(selector_number)) { console.log('ticket linked to barcode') var ticket_id = currRec.getValue({ fieldId: 'custpage_ticket_id' }); var params = { ticket_id: parseInt(ticket_id), selector_number: selector_number, selector_type: selector_type }; params = JSON.stringify(params); var output = url.resolveScript({ deploymentId: 'customdeploy_sl_open_ticket_2', scriptId: 'customscript_sl_open_ticket_2', }); var upload_url = baseURL + output + '&custparam_params=' + params; window.open(upload_url, "_self", "height=750,width=650,modal=yes,alwaysRaised=yes"); } displayCustomerInfo(); } else { var selector_type = "customer_issue"; currRec.setValue({ fieldId: 'custpage_selector_type', value: selector_type }); currRec.setValue({ fieldId: 'custpage_selector_number', value: customer_issue_type }); console.log('In displayCustomerIssueInfo - ' + customer_issue_type); var params = { ticket_id: parseInt(ticket_id.slice(4, 8)), selector_number: customer_issue_type, selector_type: selector_type }; params = JSON.stringify(params); var output = url.resolveScript({ deploymentId: 'customdeploy_sl_open_ticket_2', scriptId: 'customscript_sl_open_ticket_2', }); var upload_url = baseURL + output + '&custparam_params=' + params; window.open(upload_url, "_self", "height=750,width=650,modal=yes,alwaysRaised=yes"); } } /** * Updates the enquiry medium multi-select field and the enquiry count by chat, phone and email fields in the client side */ function updateEnquiryMediumAndCount() { $('.increment_enquiry_count_by_chat, .increment_enquiry_count_by_phone, .increment_enquiry_count_by_email').click(function() { console.log("Clicked increment"); //Get total enquiry count and increment by 1 var total_enquiry_count = $('#total_enquiry_count').val(); $('#total_enquiry_count').val(++total_enquiry_count); if (this.className.indexOf('increment_enquiry_count_by_chat') !== -1) { console.log("In chat click"); //Get chat enquiry count and increment by 1 var enquiry_count_by_chat = $('#enquiry_count_by_chat').val(); $('#enquiry_count_by_chat').val(++enquiry_count_by_chat); //Select the chat option in medium list $('#enquiry_medium_status option[value="3"]').prop('selected', true); } if (this.className.indexOf('increment_enquiry_count_by_phone') !== -1) { //Get phone enquiry count and increment by 1 var enquiry_count_by_phone = $('#enquiry_count_by_phone').val(); $('#enquiry_count_by_phone').val(++enquiry_count_by_phone); //Select the phone option in medium list $('#enquiry_medium_status option[value="1"]').prop('selected', true); } if (this.className.indexOf('increment_enquiry_count_by_email') !== -1) { //Get email enquiry count and increment by 1 var enquiry_count_by_email = $('#enquiry_count_by_email').val(); $('#enquiry_count_by_email').val(++enquiry_count_by_email); //Select the email option in medium list $('#enquiry_medium_status option[value="2"]').prop('selected', true); } //Get medium list and update it var medium_list = $('#enquiry_medium_status option:selected').map(function() { return $(this).val() }); medium_list = $.makeArray(medium_list); $('#enquiry_medium_status').val(medium_list).trigger('change'); }); $('.decrement_enquiry_count_by_chat, .decrement_enquiry_count_by_phone, .decrement_enquiry_count_by_email').click(function() { var total_enquiry_count = $('#total_enquiry_count').val(); if (this.className.indexOf('decrement_enquiry_count_by_chat') !== -1) { var enquiry_count_by_chat = $('#enquiry_count_by_chat').val(); if (enquiry_count_by_chat > 0) { $('#enquiry_count_by_chat').val(--enquiry_count_by_chat); $('#total_enquiry_count').val(--total_enquiry_count); } if (enquiry_count_by_chat === 0) { //Unselect medium list option $('#enquiry_medium_status option[value="3"]').prop('selected', false); } } if (this.className.indexOf('decrement_enquiry_count_by_phone') !== -1) { var enquiry_count_by_phone = $('#enquiry_count_by_phone').val(); if (enquiry_count_by_phone > 0) { $('#enquiry_count_by_phone').val(--enquiry_count_by_phone); $('#total_enquiry_count').val(--total_enquiry_count); } if (enquiry_count_by_phone === 0) { $('#enquiry_medium_status option[value="1"]').prop('selected', false); } } if (this.className.indexOf('decrement_enquiry_count_by_email') !== -1) { var enquiry_count_by_email = $('#enquiry_count_by_email').val(); if (enquiry_count_by_email > 0) { $('#enquiry_count_by_email').val(--enquiry_count_by_email); $('#total_enquiry_count').val(--total_enquiry_count); } if (enquiry_count_by_email === 0) { $('#enquiry_medium_status option[value="2"]').prop('selected', false); } } //Get medium list and update it var medium_list = $('#enquiry_medium_status option:selected').map(function() { return $(this).val() }); medium_list = $.makeArray(medium_list); $('#enquiry_medium_status').val(medium_list).trigger('change'); }); $('.increment_interaction_count_by_chat, .increment_interaction_count_by_phone, .increment_interaction_count_by_email').click(function() { console.log("Clicked increment"); //Get total interaction count and increment by 1 var total_interaction_count = $('#total_interaction_count').val(); $('#total_interaction_count').val(++total_interaction_count); if (this.className.indexOf('increment_interaction_count_by_chat') !== -1) { console.log("In chat click"); //Get chat interaction count and increment by 1 var interaction_count_by_chat = $('#interaction_count_by_chat').val(); $('#interaction_count_by_chat').val(++interaction_count_by_chat); } if (this.className.indexOf('increment_interaction_count_by_phone') !== -1) { //Get phone interaction count and increment by 1 var interaction_count_by_phone = $('#interaction_count_by_phone').val(); $('#interaction_count_by_phone').val(++interaction_count_by_phone); } if (this.className.indexOf('increment_interaction_count_by_email') !== -1) { //Get email interaction count and increment by 1 var interaction_count_by_email = $('#interaction_count_by_email').val(); $('#interaction_count_by_email').val(++interaction_count_by_email); //Select the email option in medium list } }); $('.decrement_interaction_count_by_chat, .decrement_interaction_count_by_phone, .decrement_interaction_count_by_email').click(function() { var total_interaction_count = $('#total_interaction_count').val(); if (this.className.indexOf('decrement_interaction_count_by_chat') !== -1) { var interaction_count_by_chat = $('#interaction_count_by_chat').val(); if (interaction_count_by_chat > 0) { $('#interaction_count_by_chat').val(--interaction_count_by_chat); $('#total_interaction_count').val(--total_interaction_count); } } if (this.className.indexOf('decrement_interaction_count_by_phone') !== -1) { var interaction_count_by_phone = $('#interaction_count_by_phone').val(); if (interaction_count_by_phone > 0) { $('#interaction_count_by_phone').val(--interaction_count_by_phone); $('#total_interaction_count').val(--total_interaction_count); } if (interaction_count_by_phone === 0) { $('#interaction_medium_status option[value="1"]').prop('selected', false); } } if (this.className.indexOf('decrement_interaction_count_by_email') !== -1) { var interaction_count_by_email = $('#interaction_count_by_email').val(); if (interaction_count_by_email > 0) { $('#interaction_count_by_email').val(--interaction_count_by_email); $('#total_interaction_count').val(--total_interaction_count); } if (interaction_count_by_email === 0) { $('#interaction_medium_status option[value="2"]').prop('selected', false); } } //Get medium list and update it var medium_list = $('#interaction_medium_status option:selected').map(function() { return $(this).val() }); medium_list = $.makeArray(medium_list); $('#interaction_medium_status').val(medium_list).trigger('change'); }); } function openAndNew() { var currRec = currentRecord.get(); currRec.setValue({ fieldId: 'custpage_open_new_ticket', value: 'T' }); // Trigger the submit function. $('#submitter').trigger('click'); } function updateAndNew() { var currRec = currentRecord.get(); currRec.setValue({ fieldId: 'custpage_open_new_ticket', value: 'T' }); // Trigger the submit function. $('#submitter').trigger('click'); } /** * Function to save the medium list depending on chat, phone and email enquiry values */ function saveMediumList(enquiry_count_by_chat, enquiry_count_by_phone, enquiry_count_by_email, ticketRecord) { var medium_list = $('#enquiry_medium_status option:selected').map(function() { return $(this).val() }); medium_list = $.makeArray(medium_list); if (enquiry_count_by_phone >= 1 && medium_list.indexOf("1") === -1) { medium_list.push("1"); } if (enquiry_count_by_email >= 1 && medium_list.indexOf("2") === -1) { medium_list.push("2"); } if (enquiry_count_by_chat >= 1 && medium_list.indexOf("3") === -1) { medium_list.push("3"); } if (enquiry_count_by_phone === "0") { var index = medium_list.indexOf("1"); if (index > -1) { medium_list.splice(index, 1); } } if (enquiry_count_by_email === "0") { var index = medium_list.indexOf("2"); if (index > -1) { medium_list.splice(index, 1); } } if (enquiry_count_by_chat === "0") { var index = medium_list.indexOf("3"); if (index > -1) { medium_list.splice(index, 1); } } ticketRecord.setValue({ fieldId: 'custrecord_enquiry_medium', value: medium_list }); } /** * Triggered when a customer calls for an issue with a barcode that is not his. * Reorganize the shown sections. */ function onEscalate() { console.log("onesc"); var currRec = currentRecord.get(); currRec.setValue({ fieldId: 'custpage_selector_issue', value: 'T' }); //Set status to Escalated // currRec.setValue({ fieldId: 'custpage_ticket_status_value', value: 10) }; $('#submitter').val('Escalate to Owner'); $('#submit_ticket').val('ESCALATE TO OWNER'); // Hide the "Escalate" button $('#tbl_custpage_escalate').closest('td').hide(); $('#tbl_custpage_escalate').closest('td').prev().hide(); $('.open_and_new_ticket_btn').addClass('hide'); $('.escalate').addClass('hide'); updateButtonsWidth(); // Hide the contacts fields and contact details sections $('.daytodaycontact_section').addClass('hide'); $('.zee_main_contact_section').addClass('hide'); $('.mpex_stock_used_section').addClass('hide'); $('.final_delivery_section').addClass('hide'); $('.mpex_contact_section').addClass('hide'); $('.contacts_section').addClass('hide'); $('.reviewcontacts_section').addClass('hide'); // Hide the send email section $('#send_email_container').addClass('hide'); // Show that the Issue Customer Name, the MP Issue and the Comment are mandatory $('.mandatory').removeClass('hide'); // Show the "MP Issues" field and the "Owner" text area $('.mp_issues_section').removeClass('hide'); selectOwner(); // Hide the tickets datatable $('.tickets_datatable_section').addClass('hide'); $('#tickets-preview_wrapper').addClass('hide'); //Hide tickets enquiry section $('.ticket_enquiry_header_section').addClass('hide'); $('.enquiry_medium_section').addClass('hide'); $('.enquiry_count_breakdown_section').addClass('hide'); $('.interaction_count_breakdown_section').addClass('hide'); $('.ticket_enquiry_header_section').addClass('hide'); $('.label_section').addClass('hide'); //Hide previous emails section $('.previous_emails_header').addClass('hide'); $('.previous_emails_section').addClass('hide'); //Hide customer ticket related issues $('.ss_section').addClass('hide'); $('.browser_os_section').addClass('hide'); $('.phone_section').addClass('hide'); $('.login_email_used_section').addClass('hide'); var selector_type = currRec.getValue({ fieldId: 'custpage_selector_type' }); if (selector_type == "customer_issue") { var selector_number = currRec.getValue({ fieldId: 'custpage_selector_number' }); if (selector_number == "Customer App") { //Set current chosen option to Customer App var mp_issues_option_inline_html = '<option value="10" selected> Customer App Issue</option>'; } else if (selector_number == "Customer Portal") { //Set current chosen option to Customer Portal var mp_issues_option_inline_html = '<option value="9" selected> Customer App Issue</option>'; } else if (selector_number == "Update Label") { //Set current chosen option to Update Label var mp_issues_option_inline_html = '<option value="11" selected> Customer App Issue</option>'; } $('#mp_issues').html(mp_issues_option_inline_html); //Requires double refresh. One for the dropwdown chnage and sceond for selection $('#mp_issues').selectpicker('refresh'); $('#mp_issues').selectpicker('refresh') } } /** * If the barcode number validation raises an error, the fields are cleared. * The informations linked to the previous barcode are deleted. */ function clearFields() { $('#customer_name').val(''); // Unselect all TOLL Issues fields $('#toll_issues option:selected').each(function() { $(this).attr('selected', false); }); $('#comment').val(''); } /** * Called when "Escalate to Owner" is clicked. * Check that in case of an issue with a barcode, the mandatory fields are filled. * @param {String} selector_type * @returns {Boolean} */ function validateIssueFields(selector_type) { var alertMessage = ''; var return_value = true; var toll_issues_length = $('#toll_issues option:selected').length; var mp_issues_length = $('#mp_issues option:selected').length; var invoice_issues_length = $('#invoice_issues option:selected').length; var comment = $('#comment').val(); var usernote = $('#user_note_textarea').val(); switch (selector_type) { case 'barcode_number': if (toll_issues_length == 0) { alertMessage += 'Please select a TOLL Issue<br>'; return_value = false; } if (isNullorEmpty(comment)) { alertMessage += 'Please type a comment<br>'; return_value = false; } break; case 'invoice_number': if (invoice_issues_length == 0) { alertMessage += 'Please select an Invoice Issue<br>'; return_value = false; } if (isNullorEmpty(usernote)) { alertMessage += 'Please type a User Note<br>'; return_value = false; } break; } if (return_value == true && mp_issues_length == 0) { alertMessage += 'Please select an MP Issue<br>'; return_value = false; } if (return_value == false) { showAlert(alertMessage); } else { $('#alert').parent().hide(); } return return_value; } /** * Send the email with the information regarding the ticket to the email adresses in the array 'to'. * @param {String} selector_type * @param {Array} to * @param {Boolean} is_issue * @returns {Boolean} Whether the email was sent or not. */ function sendInformationEmailTo(selector_type, to, is_issue) { console.log("sek type", selector_type); console.log("to", to); console.log("is_issue", is_issue); // There is an issue with the barcode // The owner should be contacted. if (is_issue) { var validate_issue_fields = validateIssueFields(selector_type); if (!validate_issue_fields) { return false; } } var selector_number = $('#selector_value').val(); var customer_name = $('#customer_name').val(); var comment = $('#comment').val(); var selected_title = $('#user_note_title option:selected').text(); var usernote_textarea = $('#user_note_textarea').val(); var date = new Date(); var email_subject = 'MP Ticket issue - ' + selector_number; var email_body = ''; email_body += 'Environment : ' + runtime.envType + '\n'; email_body += 'Date & Time : ' + formatDate(date) + '\n'; switch (selector_type) { case 'barcode_number': email_body += 'Barcode Number : ' + selector_number + '\n'; break; case 'invoice_number': email_body += 'Invoice Number : ' + selector_number + '\n'; break; case 'customer_issue': email_body += 'Customer associated ticket : ' + selector_number + '\n'; break; } email_body += 'Customer Name : ' + customer_name + '\n'; switch (selector_type) { case 'barcode_number': email_body += 'TOLL Issues : '; $('#toll_issues option:selected').each(function() { email_body += $(this).text() + '\n'; }); break; case 'invoice_number': email_body += 'Invoice Issues : '; $('#invoice_issues option:selected').each(function() { email_body += $(this).text() + '\n'; }); break; } email_body += 'MP Issues : '; $('#mp_issues option:selected').each(function() { email_body += $(this).text() + '\n'; }); if (selector_type == 'invoice_number') { if (!isNullorEmpty(comment.trim())) { comment += '\n'; } var date = new Date(); var dnow = format.parse({ value: date, type: format.Type.DATETIMETZ }); var usernote = '[' + selected_title + '] - [' + userName + '] - [' + dnow + '] - ' + usernote_textarea; comment += usernote; } email_body += 'Comment : ' + comment; var cc = [] //CC email addresses // Now the escalation and information emails are sent from the user addresses. console.log("emailsend"); email.send({ author: 112209, body: email_body, recipients: to, subject: email_subject, cc: cc, }); // 112209 is from MailPlus Team return true; } /** * Redirect to the "View MP Tickets" page without saving any changes. */ function onCancel() { console.log("cancel"); var status_value = currRec.getValue({ fieldId: 'custpage_ticket_status_value' }); if (isTicketNotClosed(status_value)) { var output = url.resolveScript({ deploymentId: 'customdeploy_sl_edit_ticket_2', scriptId: 'customscript_sl_edit_ticket_2', }); var upload_url = baseURL + output; } else { var output = url.resolveScript({ deploymentId: 'customdeploy_sl_edit_closed_ticket_2', scriptId: 'customscript_sl_edit_closed_ticket_2', }); var upload_url = baseURL + output; } window.open(upload_url, "_self", "height=750,width=650,modal=yes,alwaysRaised=yes"); } /** * Function to return the customer id given a customer number * @param {*} customer_number */ function getCustomerID(customer_number) { var customer_search = search.load({ type: 'customer', id: 'customsearch_customer_name_2' }); customer_search.filters.push(search.createFilter({ name: 'entityid', operator: 'haskeywords', values: customer_number, })); var result_set = customer_search.run().getRange({ start: 0, end: 1000 }); result_set.forEach(function(search_value) { console.log("search va", search_value); }); var customerId = result_set[0].id; console.log(customerId, "custid"); return customerId; } /** * Checks that the given customer number is valid * Returns the customer record if found, else returns null */ function isCustomerNumberValid(customer_number) { if (!isNullorEmpty(customer_number)) { var customer_search = search.load({ type: 'customer', id: 'customsearch_customer_name_2' }); var new_filter = search.createFilter({ name: 'entityid', operator: 'is', values: customer_number, }) customer_search.filters.push(new_filter); try { var result_set = customer_search.run(); if (result_set.getRange({ start: 0, end: 1000 }) != null && result_set.getRange({ start: 0, end: 1000 }).length > 0) { // Customer found. return true; } else { //Customer does not exist in record showAlert('Enter a valid customer number. Customer ' + customer_number + ' does not exist'); return false; } } catch (error) { //Undefined ID error return false; } } else { showAlert('Enter a customer number'); return false; } } /** * - If the barcode record exists but there is an MP Ticket issue with the record, * the onEscalate function is called. * @return {Boolean} Whether or not all the input has been filled. */ function validateSelectorInput() { console.log('In validateSelectorInput()'); var selector_number = $('#selector_value').val().trim().toUpperCase(); $('#selector_value').val(selector_number); var selector_type = $('#selector_text').text().toLowerCase().split(' ').join('_'); console.log(selector_number); console.log(selector_type); var alertMessage = ''; var return_value = true; var keep_selector_number = false; if (isNullorEmpty(selector_number)) { switch (selector_type) { case 'invoice_number': alertMessage += 'Please enter the Invoice Number<br>'; break; case 'barcode_number': alertMessage += 'Please enter the Barcode Number<br>'; break; default: alertMessage += 'Please enter a selector number or a customer issue <br>'; } return_value = false; } if ((return_value == true) && (!checkSelectorFormat(selector_number, selector_type))) { switch (selector_type) { case 'invoice_number': alertMessage += 'The Invoice Number format is incorrect<br>'; break; case 'barcode_number': alertMessage += 'The Barcode Number format is incorrect<br>'; break; } return_value = false; } // If a ticket already exists for the barcode number, the user is redirected to the "Edit Ticket" page. if (return_value && ticketLinkedToSelector(selector_number)) { console.log('tic ket linked to barcode') var ticket_id = currRec.getValue({ fieldId: 'custpage_ticket_id' }); var params = { ticket_id: parseInt(ticket_id), selector_number: selector_number, selector_type: selector_type }; params = JSON.stringify(params); var output = url.resolveScript({ deploymentId: 'customdeploy_sl_open_ticket_2', scriptId: 'customscript_sl_open_ticket_2', }); var upload_url = baseURL + output + '&custparam_params=' + params; window.open(upload_url, "_self", "height=750,width=650,modal=yes,alwaysRaised=yes"); } if (return_value) { console.log('Escalate to owner cases'); switch (selector_type) { //Escalate to owner cases case 'invoice_number': var activeInvoiceResults = getSelectorRecords(selector_number, selector_type); if ((isNullorEmpty(activeInvoiceResults))) { alertMessage += 'No invoice record exists for the invoice number ' + selector_number + '<br>'; keep_selector_number = true; $('.customer_section').addClass('hide'); clearFields(); currRec.setValue({ fieldId: 'custpage_selector_id', value: '' }); return_value = false; } break; case 'barcode_number': var activeBarcodeResults = getSelectorRecords(selector_number, selector_type); console.log("absdhskhd"); if ((isNullorEmpty(activeBarcodeResults))) { console.log("aasnj"); alertMessage += 'No active barcode record exists for the barcode number ' + selector_number + '<br>'; // $('#mp_issues option[value="1"]').prop('selected', true); // $('#mp_issues option[value="2"]').prop('selected', true); // $('#mp_issues option[value="3"]').prop('selected', true); var mp_issues_list = [1, 2, 3]; $('#mp_issues').selectpicker('val', mp_issues_list); keep_selector_number = true; $('.customer_section').addClass('hide'); clearFields(); currRec.setValue({ fieldId: 'custpage_selector_id', value: '' }); onEscalate(); return_value = false; } console.log("baasnj"); if ((!zeeLinkedToBarcode(activeBarcodeResults))) { alertMessage += 'No franchisee is associated to the barcode ' + selector_number + '<br>'; console.log("casnj"); // $('#mp_issues option[value="1"]').prop('selected', true); // $('#mp_issues option[value="3"]').prop('selected', true); var mp_issues_list = [1, 3]; $('#mp_issues').selectpicker('val', mp_issues_list); keep_selector_number = true; $('.customer_section').addClass('hide'); clearFields(); onEscalate(); return_value = false; } console.log("adasnj"); if ((!customerLinkedToBarcode(activeBarcodeResults))) { alertMessage += 'No customer is associated to the barcode ' + selector_number + '<br>'; console.log("easnj"); //$('#mp_issues option[value="1"]').prop('selected', true); var mp_issues_list = [1]; $('#mp_issues').selectpicker('val', mp_issues_list); keep_selector_number = true; $('.customer_section').addClass('hide'); clearFields(); onEscalate(); return_value = false; } break; } } // if (return_value == false) { // if (!keep_selector_number) { // var last_correct_selector_number = currRec.getValue({ fieldId: 'custpage_selector_number' }); // $('#selector_value').val(last_correct_selector_number); // } // showAlert(alertMessage); // } else { // $('#alert').parent().hide(); // } if (return_value == false) { console.log('Lastcase'); showAlert(alertMessage); } else { $('#alert').parent().hide(); } return return_value; } /** * Displays error messages in the alert box on top of the page. * @param {String} message The message to be displayed. */ function showAlert(message) { $('#danger-alert').html('<button type="button" class="close" id="close-alert" data-dismiss="alert" aria-label="Close"><span aria-hidden="true">&times;</span></button>' + message); $('#danger-alert').parent().show(); $("#danger-alert").fadeTo(3000, 500).slideUp(500, function() { $("#danger-alert").slideUp(500); }); $('html, body').animate({ scrollTop: 0 }, 800) } /** * Check that if the selector is a barcode number, it starts with 'MPE', * followed by either 'B', 'C', 'D', 'F', 'N' or 'T', * and then finishes by 6 digits. * * If it's an invoice, it should start with 'INV' and then finishes by 6 digits. * @param {String} selector_number * @param {String} selector_type * @returns {Boolean} */ function checkSelectorFormat(selector_number, selector_type) { switch (selector_type) { case 'barcode_number': var barcodeFormat = /^MPE[BCDFNTG]\d{6}$/; var connoteFormat = /^MPXL\d{6}$/; var onlyNumbers = /^\d{20}$/; if (barcodeFormat.test(selector_number) || connoteFormat.test(selector_number) || onlyNumbers.test(selector_number)) { return true; } return false; case 'invoice_number': var invoiceFormat = /^INV\d{6}$/; return invoiceFormat.test(selector_number); } } /** * Searches for an opened ticket linked to this selector number. * The barcode record might not exist, but the ticket associated to the selector number can. * @param {String} selector_number * @returns {Boolean} */ function ticketLinkedToSelector(selector_number) { console.log("selector number", selector_number); var activeTicketFilterExpression = [ [["custrecord_barcode_number", "is", selector_number], "OR", ["altname", "is", selector_number]], 'AND', ["custrecord_ticket_status", "noneof", '3'] ]; var activeTicketsResults = search.create({ type: 'customrecord_mp_ticket', filterExpression: activeTicketFilterExpression }); activeTicketsResults.filters.push(search.createFilter({ name: 'custrecord_ticket_status', operator: search.Operator.NONEOF, values: 3 })); activeTicketsResults.filters.push(search.createFilter({ name: 'formulatext', operator: search.Operator.IS, values: selector_number, formula: '{altname}' })); if (activeTicketsResults.runPaged().count < 1) { console.log("change filters1"); activeTicketsResults.filters.pop(); activeTicketsResults.filters.push(search.createFilter({ name: 'formulatext', operator: search.Operator.IS, values: selector_number, formula: '{custrecord_barcode_number.custrecord_connote_number}' })); } if (activeTicketsResults.runPaged().count < 1) { console.log("change filters2"); activeTicketsResults.filters.pop(); activeTicketsResults.filters.push(search.createFilter({ name: 'formulatext', operator: search.Operator.IS, values: selector_number, formula: '{custrecord_barcode_number.name}' })); } var searchResultCount = activeTicketsResults.runPaged().count; console.log("CNTTTT", searchResultCount); if (isNullorEmpty(activeTicketsResults) || searchResultCount < 1) { console.log("ISNULL") return false; } else { // If an active ticket exists for the barcode number, the ticket_id is saved. // The validate function then redirects the user to its "Edit Ticket" page. var ticket_id = ''; activeTicketsResults.run().each(function(value) { console.log(value); console.log("id", value.id); ticket_id = value.id; return true; }); //console.log("AR2", activeTicketsRes); console.log("matching ticket_id", ticket_id); currRec.setValue({ fieldId: 'custpage_ticket_id', value: ticket_id }); return true; } } /** * Searches for the active barcodes records with the name `barcode_number`, * or for the active invoice records with the name `invoice_number`, * There is normally only one such record. * @param {String} selector_number * @param {String} selector_type * @returns {nlobjSearchResult[]} An array of nlobjSearchResult objects corresponding to the searched records. */ function getSelectorRecords(selector_number, selector_type) { switch (selector_type) { case 'barcode_number': var filterExpression = [ [["name", "is", selector_number], "OR", ["custrecord_connote_number", "is", selector_number]], 'AND', ["isinactive", "is", 'F'] ]; var activeBarcodeColumns = new Array(); activeBarcodeColumns[0] = search.createColumn({ name: 'custrecord_cust_prod_stock_customer', join: null, summary: null }); activeBarcodeColumns[1] = search.createColumn({ name: 'custrecord_cust_prod_stock_zee', join: null, summary: null }); activeBarcodeColumns[2] = search.createColumn({ name: 'custrecord_cust_prod_stock_toll_issues', join: null, summary: null }); activeBarcodeColumns[3] = search.createColumn({ name: 'custrecord_mp_ticket', join: null, summary: null }); activeBarcodeColumns[4] = search.createColumn({ name: 'custrecord_cust_date_stock_used', join: null, summary: null }); activeBarcodeColumns[5] = search.createColumn({ name: 'custrecord_cust_time_stock_used', join: null, summary: null }); activeBarcodeColumns[6] = search.createColumn({ name: 'custrecord_cust_prod_stock_final_del', join: null, summary: null }); activeBarcodeColumns[7] = search.createColumn({ name: 'name', join: null, summary: null }); var activeSelectorResults = search.create({ type: 'customrecord_customer_product_stock', filterExpression: filterExpression, columns: activeBarcodeColumns }); var connoteFormat = /^MPXL\d{6}$/; if (connoteFormat.test(selector_number)) { console.log('connote'); activeSelectorResults.filters.push(search.createFilter({ name: 'custrecord_connote_number', operator: search.Operator.IS, values: selector_number, })); } else { console.log('else'); activeSelectorResults.filters.push(search.createFilter({ name: 'name', operator: search.Operator.IS, values: selector_number, })); } activeSelectorResults.filters.push(search.createFilter({ name: 'isinactive', operator: search.Operator.IS, values: false, })); break; case 'invoice_number': var filterExpression = [ ["tranid", "is", selector_number] ]; var invoiceColumns = new Array(); invoiceColumns[0] = search.createColumn({ name: 'entity', join: null, summary: null }); invoiceColumns[1] = search.createColumn({ name: 'partner', join: null, summary: null }); var activeSelectorResults = search.create({ type: 'invoice', join: null, filterExpression: filterExpression, columns: invoiceColumns }); break; } console.log("abc"); console.log(activeSelectorResults); if (!isNullorEmpty(activeSelectorResults)) { var selector_id = ''; activeSelectorResults.run().each(function(search_res) { console.log("ID", search_res.id); selector_id = search_res.id; return true; }); console.log('selector_id val', selector_id); currRec.setValue({ fieldId: 'custpage_selector_id', value: selector_id }); } return activeSelectorResults; } /** * Verifies that the barcode record is associated to a customer * @param {nlobjSearchResult[]} activeBarcodeResults Result of getSelectorRecords(selector_number, selector_type) * @returns {Boolean} */ function customerLinkedToBarcode(activeBarcodeResults) { // var activeBarcodeResult = activeBarcodeResults[0]; // var customer_id = activeBarcodeResult.getValue('custrecord_cust_prod_stock_customer'); // if (isNullorEmpty(customer_id)) { // return false; // } else { // return true; // } var customer_id; activeBarcodeResults.run().each(function(search_val) { customer_id = search_val.getValue({ name: 'custrecord_cust_prod_stock_customer' }); if (isNullorEmpty(customer_id)) { return true; } else { return false; } }); if (isNullorEmpty(customer_id)) { return false; } else { return true; } } /** * Verifies that the barcode record is associated to a franchisee * @param {nlobjSearchResult[]} activeBarcodeResults Result of getSelectorRecords(selector_number, selector_type) * @returns {Boolean} */ function zeeLinkedToBarcode(activeBarcodeResults) { //var activeBarcodeResult = activeBarcodeResults[0]; var zee_id; activeBarcodeResults.run().each(function(search_val) { zee_id = search_val.getValue({name: 'custrecord_cust_prod_stock_zee' }); console.log("zee", zee_id); if (isNullorEmpty(zee_id)) { return true; } else { return false; } }); if (isNullorEmpty(zee_id)) { return false; } else { return true; } } /** * Returns the customer record for a given customer number * If record does not exist, returns null * @param {*} customer_number */ function customerLinkedToCustomerNum(customer_number) { if (!isNullorEmpty(customer_number)) { var customer_search = search.load({ type: 'customer', id: 'customsearch_customer_name_2' }); var new_filter = search.createFilter({ name: 'entityid', operator: 'haskeywords', values: customer_number, }); customer_search.filters.push(new_filter); try { var result_set = customer_search.run(); if (result_set.getRange({ start: 0, end: 1000 }) != null && result_set.getRange({ start: 0, end: 1000 }).length >= 1) { // Customer found. return result_set.getRange({ start: 0, end: 1000 })[0]; } else { // Customer does not exist in record return null; } } catch (error) { //Undefined ID error return showAlert(error); } } } /** * Displays the informations linked to a selector record. * @returns {Boolean} Whether the function worked well or not. */ function displayCustomerInfo() { console.log('In displayCustomerInfo()'); var selector_number = $('#selector_value').val().trim().toUpperCase(); currRec.setValue({ fieldId: 'custpage_selector_number', value: selector_number }); var selector_type = currRec.getValue({ fieldId: 'custpage_selector_type' }); var activeSelectorResults = getSelectorRecords(selector_number, selector_type); var activeSelectorResult; var selector_id = ''; activeSelectorResults.run().each(function(search_val) { selector_id = search_val.id; activeSelectorResult = search_val; console.log("selector_id", selector_id); }); console.log("asr", activeSelectorResult); //var selector_id = activeSelectorResult.getId(); console.log('selector_id : ', selector_id); console.log('activeSelectorResult : ', activeSelectorResult); currRec.setValue({ fieldId: 'custpage_selector_id', value: selector_id }); switch (selector_type) { case 'barcode_number': var customer_name = activeSelectorResult.getText('custrecord_cust_prod_stock_customer'); var customer_id = activeSelectorResult.getValue('custrecord_cust_prod_stock_customer'); currRec.setValue({ fieldId: 'custpage_customer_id', value: customer_id }); var zee_name = activeSelectorResult.getText('custrecord_cust_prshowAlod_stock_zee'); var zee_id = activeSelectorResult.getValue('custrecord_cust_prod_stock_zee'); var date_stock_used = activeSelectorResult.getValue('custrecord_cust_date_stock_used'); var time_stock_used = activeSelectorResult.getValue('custrecord_cust_time_stock_used'); var final_delivery_val = activeSelectorResult.getValue('custrecord_cust_prod_stock_final_del'); var final_delivery = activeSelectorResult.getText('custrecord_cust_prod_stock_final_del'); //Show the required fields $('.mpex_stock_used_section').show(); $('.final_delivery_enquiry_status_section').show(); //Update values $('#date_stock_used').val(date_stock_used); $('#time_stock_used').val(time_stock_used); $('#final_delivery').attr('data-val', final_delivery_val); $('#final_delivery').val(final_delivery); break; case 'invoice_number': var customer_name = activeSelectorResult.getText('entity'); var customer_id = activeSelectorResult.getValue('entity'); currRec.setValue({ fieldId: 'custpage_customer_id', value: customer_id }); var zee_name = activeSelectorResult.getText('partner'); var zee_id = activeSelectorResult.getValue('partner'); break; } $('#customer_name').val(customer_name); // Load customer record try { var customerRecord = record.load({ type: 'customer', id: customer_id }); var zee_id = customerRecord.getValue({ fieldId: 'partner' }); var daytodayphone = customerRecord.getValue({ fieldId: 'phone' }); var daytodayemail = customerRecord.getValue({ fieldId: 'custentity_email_service' }); var entityid = customerRecord.getValue({ fieldId: 'entityid' }); // Set new customer number value $('#customer_number_value').val(entityid); currRec.setValue({ fieldId: 'custpage_customer_number', value: entityid }); if (selector_type == 'invoice_number') { var accountsphone = customerRecord.getValue({ fieldId: 'altphone' }); var accountsemail = customerRecord.getValue({ fieldId: 'email' }); var maap_bank_account_number = customerRecord.getValue({ fieldId: 'custentity_maap_bankacctno' }); var maap_parent_bank_account_number = customerRecord.getValue({ fieldId: 'custentity_maap_bankacctno_parent' }); var selected_invoice_method_id = customerRecord.getValue({ fieldId: 'custentity_invoice_method' }); var accounts_cc_email = customerRecord.getValue({ fieldId: 'custentity_accounts_cc_email' }); var mpex_po_number = customerRecord.getValue({ fieldId: 'custentity_mpex_po' }); var customer_po_number = customerRecord.getValue({ fieldId: 'custentity11' }); var mpex_invoicing_cycle = customerRecord.getValue({ fieldId: 'custentity_mpex_invoicing_cycle' }); } // Load Franchisee record var zeeRecord = record.load({ type: 'partner', id: zee_id }); var zee_name = zeeRecord.getValue({ fieldId: 'companyname' }); var zee_main_contact_name = zeeRecord.getValue({ fieldId: 'custentity3' }); var zee_email = zeeRecord.getValue({ fieldId: 'email' }); var zee_main_contact_phone = zeeRecord.getValue({ fieldId: 'custentity2' }); $('#daytodayphone').val(daytodayphone); $('#daytodayemail').val(daytodayemail); if (selector_type == 'invoice_number') { $('#accountsphone').val(accountsphone); $('#accountsemail').val(accountsemail); $('#account_number').val(maap_bank_account_number); $('#parent_account_number').val(maap_parent_bank_account_number); // Unselect Invoice all method options fields $('#invoice_method option:selected').each(function() { $(this).attr('selected', false); }); // Select the right invoice method option $('#invoice_method option[value=' + selected_invoice_method_id + ']').prop('selected', true); $('#accounts_cc_email').val(accounts_cc_email); $('#mpex_po_number').val(mpex_po_number); $('#customer_po_number').val(customer_po_number); $('#mpex_invoicing_cycle').val(mpex_invoicing_cycle); } $('#zee_main_contact_name').val(zee_main_contact_name); $('#zee_email').val(zee_email); $('#zee_main_contact_phone').val(zee_main_contact_phone); } catch (e) { if (e instanceof error.SuiteScriptError) { if (error.name == "SSS_MISSING_REQD_ARGUMENT") { console.log('Error to load the customer record with customer_id : ' + customer_id); } } } currRec.setValue({ fieldId: 'custpage_zee_id', value: zee_id }); $('#franchisee_name').val(zee_name); // Contacts details createContactsRows(); switch (selector_type) { case 'barcode_number': // TOLL Issues // Unselect all TOLL Issues fields $('#toll_issues option:selected').each(function() { $(this).attr('selected', false); }); // Select the corresponding TOLL issues var toll_issues = activeSelectorResult.getValue({name: 'custrecord_cust_prod_stock_toll_issues' }); if (!isNullorEmpty(toll_issues)) { toll_issues = toll_issues.split(','); toll_issues.forEach(function(toll_value) { $('#toll_issues option[value=' + toll_value + ']').prop('selected', true); }); } break; case 'invoice_number': // Invoice Issues // If the ticket is not opened yet, there are no Invoice Issues yet. updateInvoicesDatatable(); break; } // Display the tickets linked to the customer in the datatable updateTicketsDatatable(); setReminderDate(); return true; } function searchTicketRecords(customer_number) { var all_ticket_search = search.load({ type: 'customrecord_mp_ticket', id: 'customsearch_ticket_by_custnum' }); var new_filter = search.createFilter({ name: 'custrecord_cust_number', operator: 'contains', values: customer_number, }) all_ticket_search.filters.push(new_filter); var tickets_result_set = all_ticket_search.run().getRange({ start: 0, end: 1000 }); var ticket_records = []; if (!isNullorEmpty(tickets_result_set)) { for (var i = 0; i < tickets_result_set.length; i++) { var ticket_id = tickets_result_set[i].getValue('name'); var cust_number = tickets_result_set[i].getValue('custrecord_cust_number'); var cust_name = tickets_result_set[i].getText('custrecord_customer1'); var barcode_num = tickets_result_set[i].getText('custrecord_barcode_number'); var invoice_num = tickets_result_set[i].getText('custrecord_invoice_number'); var customer_issue = tickets_result_set[i].getValue('custrecord_customer_issue'); var owner = tickets_result_set[i].getText('owner'); var date_created = tickets_result_set[i].getValue('created'); ticket_records.push([ticket_id, cust_number, cust_name, barcode_num, invoice_num, customer_issue, owner, date_created]); } } return ticket_records; } /** * Displays the invoices linked to the customer into a datatable. * @returns {Boolean} Whether the function worked well or not. */ function updateInvoicesDatatable() { var compid = (runtime.envType == "SANDBOX") ? '1048144_SB3' : '1048144'; var customer_id = currRec.getValue({ fieldId: 'custpage_customer_id' }); var invoice_status_filter = $('#invoices_dropdown option:selected').val(); console.log("inv filter", invoice_status_filter); var invoicesSearchResults = loadInvoicesSearch(customer_id, invoice_status_filter); $('#result_invoices').empty(); var invoicesDataSet = []; if (isNullorEmpty(invoicesSearchResults)) { if (isNullorEmpty(customer_id)) { $('#info').text('No customer is associated to this invoice.'); $('#info').parent().show(); return true; } else { try { var customerRecord = record.load({ type: record.Type.CUSTOMER, id: customer_id, isDynamic: true }); var customer_name = customerRecord.getValue({ fieldId: 'altname' }); console.log(customer_name); return true; } catch (error) { if (error instanceof error.SuiteScriptError) { if (error.name == "SSS_MISSING_REQD_ARGUMENT") { console.log('Error to load the customer record with customer_id : ' + customer_id); } } } } } var today = new Date; invoicesSearchResults.each(function(invoiceResult) { var status = invoiceResult.getValue('statusref'); if (status == invoice_status_filter) { var invoice_date = invoiceResult.getValue('trandate'); invoice_date = invoice_date.split(' ')[0]; invoice_date = dateCreated2DateSelectedFormat(invoice_date); var re = /Invoice #([\w]+)/; var invoice_number = invoiceResult.getValue('invoicenum'); invoice_number = invoice_number.replace(re, '$1'); var invoice_id = invoiceResult.id; var invoice_link = baseURL + '/app/accounting/transactions/custinvc.nl?id=' + invoice_id + '&compid=' + compid + '&cf=116&whence='; invoice_number = '<a href="' + invoice_link + '">' + invoice_number + '</a>'; var status_text = invoiceResult.getText('statusref'); var invoice_type = invoiceResult.getText('custbody_inv_type'); var amount_due = invoiceResult.getValue('amountremaining'); var total_amount = invoiceResult.getValue('total'); var due_date_string = invoiceResult.getValue('duedate'); var overdue = ''; if (!isNullorEmpty(due_date_string)) { due_date = stringToDate(due_date_string); var days_overdue = Math.ceil((today - due_date) / 86400000); if (days_overdue > 0) { overdue = days_overdue + ' days (' + due_date_string + ')'; } else { overdue = 'Due date : ' + due_date_string; } } amount_due = financial(amount_due); total_amount = financial(total_amount); invoicesDataSet.push([invoice_date, invoice_number, status_text, invoice_type, amount_due, total_amount, overdue, invoice_id]); } return true; }); // Update datatable rows. var datatable = $('#invoices-preview').DataTable(); datatable.clear(); datatable.rows.add(invoicesDataSet); datatable.draw(); $('[data-toggle="tooltip"]').tooltip(); return true; } /** * Update the headers of the tickets preview datatable, depending on the selector_type. * @param {String} selector_type */ function updateTicketsDatatableHeaders(selector_type) { var table = $('#tickets-preview').DataTable(); var header_cells = table.columns([3, 5, 6]).header().to$(); switch (selector_type) { case 'barcode_number': $.each(header_cells, function(index) { switch (index) { case 0: $(this).text('Barcode Number'); break; case 1: $(this).text('TOLL Issues'); break; case 2: $(this).text('Resolved TOLL Issues'); break; default: break; } }); break; case 'invoice_number': $.each(header_cells, function(index) { switch (index) { case 0: $(this).text('Invoice Number'); break; case 1: $(this).text('Invoice Issues'); break; case 2: $(this).text('Resolved Invoice Issues'); break; default: break; } }); break; } } /** * Displays the tickets linked to the customer into a datatable. * @returns {Boolean} Whether the function worked well or not. */ function updateTicketsDatatable() { var customer_id = currRec.getValue({ fieldId: 'custpage_customer_id' }); var selector_type = currRec.getValue({ fieldId: 'custpage_selector_type' }); var ticketSearchResults = loadTicketsSearch(customer_id); if (!isNullorEmpty(ticketSearchResults)) { ticketSearchResults.filters.push( search.createFilter({ name: 'custrecord_customer1', operator: search.Operator.IS, values: customer_id, }) ); } //console.log("cnt", searchResultCount); console.log('update tickets datatable'); updateTicketsDatatableHeaders(selector_type); $('#result_tickets').empty(); var ticketsDataSet = []; if (isNullorEmpty(ticketSearchResults)) { if (isNullorEmpty(customer_id)) { $('#info').text('No customer is associated to this ticket.'); $('#info').parent().show(); return true; } else { try { var customerRecord = record.load({ type: 'customer', id: customer_id }); var customer_name = customerRecord.getValue({ fieldId: 'altname' }); $('#info').text('No ticket exists for the customer ' + customer_name); $('#info').parent().show(); return true; } catch (e) { if (e instanceof error.SuiteScriptError) { if (e.name == "SSS_MISSING_REQD_ARGUMENT") { console.log('Error to load the customer record with customer_id : ' + customer_id); } } } } } ticketSearchResults.run().each(function(ticketResult) { switch (selector_type) { case 'barcode_number': var ticket_id = ticketResult.getValue('name'); var date_created = ticketResult.getValue('created'); var date_closed = ticketResult.getValue('custrecord_date_closed'); var barcode_number = ticketResult.getText('custrecord_barcode_number'); var status = ticketResult.getText('custrecord_ticket_status'); var toll_issues = ticketResult.getText('custrecord_toll_issues'); toll_issues = toll_issues.split(',').join('<br>'); var resolved_toll_issues = ticketResult.getText('custrecord_resolved_toll_issues'); resolved_toll_issues = resolved_toll_issues.split(',').join('<br>'); var comment = ticketResult.getValue('custrecord_comment'); ticketsDataSet.push([ticket_id, date_created, date_closed, barcode_number, status, toll_issues, resolved_toll_issues, comment]); break; case 'invoice_number': var ticket_id = ticketResult.getValue('name'); var date_created = ticketResult.getValue('created'); var date_closed = ticketResult.getValue('custrecord_date_closed'); var re = /Invoice #([\w]+)/; var invoice_number = ticketResult.getText('custrecord_invoice_number'); invoice_number = invoice_number.replace(re, '$1'); var status = ticketResult.getText('custrecord_ticket_status'); var invoice_issues = ticketResult.getText('custrecord_invoice_issues'); invoice_issues = invoice_issues.split(',').join('<br>'); var resolved_invoice_issues = ticketResult.getText('custrecord_resolved_invoice_issues'); resolved_invoice_issues = resolved_invoice_issues.split(',').join('<br>'); var comment = ticketResult.getValue('custrecord_comment'); comment = comment.split('\n').join('<br>'); ticketsDataSet.push([ticket_id, date_created, date_closed, invoice_number, status, invoice_issues, resolved_invoice_issues, comment]); break; } return true; }); // Update datatable rows. var datatable = $('#tickets-preview').dataTable().api(); datatable.clear(); datatable.rows.add(ticketsDataSet); datatable.draw(); return true; } /** * Load the result set of the invoices records linked to the customer. * @param {String} customer_id * @param {String} invoice_status * @return {nlobjSearchResultSet} invoicesResultSet */ // function loadInvoicesSearch(customer_id, invoice_status) { // if (!isNullorEmpty(customer_id)) { // var invoicesSearch = search.load({ type: 'invoice', id: 'customsearch_mp_ticket_invoices_datatabl' }); // var invoicesFilterExpression = invoicesSearch.filterExpression; // invoicesFilterExpression.push('AND', ['entity', 'is', customer_id]); // if (invoice_status == 'open') { // invoicesFilterExpression.push('AND', ["status", "anyof", "CustInvc:A"]); // Open Invoices // } else if (invoice_status == 'paidInFull') { // invoicesFilterExpression.push('AND', ["status", "anyof", "CustInvc:B"]); // Paid in Full // var today_date = new Date(); // var today_day = today_date.getDate(); // var today_month = today_date.getMonth(); // var today_year = today_date.getFullYear(); // var date_3_months_ago = new Date(Date.UTC(today_year, today_month - 3, today_day)); // var date_3_months_ago_string = format.parse({ value: date_3_months_ago, type: format.Type.DATE }); // invoicesFilterExpression.push('AND', ["trandate", "after", date_3_months_ago_string]); // } // console.log('invoicesFilterExpression : ', invoicesFilterExpression); // invoicesSearch.filterExpression = invoicesFilterExpression; // invoicesResultSet = invoicesSearch.run(); // } // console.log("inv res set", invoicesResultSet) // return invoicesResultSet; // } /** * Load the result set of the invoices records linked to the customer. * @param {String} customer_id * @param {String} invoice_status * @return {nlobjSearchResultSet} invoicesResultSet */ function loadInvoicesSearch(customer_id, invoice_status) { var invoicesResultSet; if (!isNullorEmpty(customer_id)) { var invoicesSearch = search.load({ id: 'customsearch_mp_ticket_invoices_datatabl', type: search.Type.INVOICE }); var invoicesFilterExpression = invoicesSearch.filterExpression; invoicesFilterExpression.push('AND'); invoicesFilterExpression.push(['entity', search.Operator.IS, customer_id]); console.log("inv status", invoice_status); // Open Invoices if (invoice_status == 'open' || isNullorEmpty(invoice_status)) { invoicesFilterExpression.push('AND', ["status", search.Operator.ANYOF, "CustInvc:A"]); // Open Invoices } else if (invoice_status == 'paidInFull') { invoicesFilterExpression.push('AND', ["status", search.Operator.ANYOF, "CustInvc:B"]); // Paid in Full var today_date = new Date(); var today_day = today_date.getDate(); var today_month = today_date.getMonth(); var today_year = today_date.getFullYear(); var date_3_months_ago = new Date(Date.UTC(today_year, today_month - 3, today_day)); var date_3_months_ago_string = formatDate(date_3_months_ago); invoicesFilterExpression.push('AND', ["trandate", search.Operator.AFTER, date_3_months_ago_string]); } invoicesSearch.filterExpression = invoicesFilterExpression; invoicesResultSet = invoicesSearch.run(); var searchResultCount = invoicesSearch.runPaged().count; console.log("cnt", searchResultCount); } return invoicesResultSet; } /** * Load the result set of the tickets records linked to the customer. * WARNING : This method returns only 1000 results. If we want more results, we need to use a saved search * @param {String} customer_id * @return {Array} An array of nlobjSearchResult objects, containing the different ticket records. */ function loadTicketsSearch(customer_id) { var ticketSearchResults = new Array; console.log("custid", customer_id); // If a ticket is opened for a barcode that is not allocated to a customer, // there will be no customer_id. if (!isNullorEmpty(customer_id)) { var filterExpression = search.createFilter({ name: 'custrecord_customer1', operator: 'is', values: customer_id, }); var ticketsColumns = new Array(); ticketsColumns[0] = search.createColumn({ name: 'name' }); ticketsColumns[1] = search.createColumn({ name: 'created' }); ticketsColumns[2] = search.createColumn({ name: 'custrecord_date_closed' }); ticketsColumns[3] = search.createColumn({ name: 'custrecord_barcode_number' }); ticketsColumns[4] = search.createColumn({ name: 'custrecord_invoice_number' }); ticketsColumns[5] = search.createColumn({ name: 'custrecord_ticket_status' }); ticketsColumns[6] = search.createColumn({ name: 'custrecord_toll_issues' }); ticketsColumns[7] = search.createColumn({ name: 'custrecord_resolved_toll_issues' }); ticketsColumns[8] = search.createColumn({ name: 'custrecord_invoice_issues' }); ticketsColumns[9] = search.createColumn({ name: 'custrecord_resolved_invoice_issues' }); ticketsColumns[10] = search.createColumn({ name: 'custrecord_comment' }); ticketSearchResults = search.create({ type: 'customrecord_mp_ticket', filter: filterExpression, columns: ticketsColumns }); } return ticketSearchResults; } /** * Triggered by a click on the button 'ADD/EDIT CONTACTS' ('#reviewcontacts') * Open the 'ticket_contact' page with the parameters : * - Customer ID * - Barcode Number * - Script ID : 'customscript_sl_open_ticket' * - Deployment ID : 'customdeploy_sl_open_ticket' */ function addEditContact() { var customer_id = currRec.getValue({ fieldId: 'custpage_customer_id' }); if (!isNullorEmpty(customer_id)) { var selector_number = currRec.getValue({ fieldId: 'custpage_selector_number' }); var selector_type = currRec.getValue({ fieldId: 'custpage_selector_type' }); var params = { custid: parseInt(customer_id), selector_number: selector_number, selector_type: selector_type, id: 'customscript_sl_open_ticket_2', deploy: 'customdeploy_sl_open_ticket_2' }; params = JSON.stringify(params); var output = url.resolveScript({ deploymentId: 'customdeploy_sl_ticket_contact', scriptId: 'customscript_sl_ticket_contact', }) var upload_url = baseURL + output + '&params=' + params; window.open(upload_url, "_self", "height=750,width=650,modal=yes,alwaysRaised=yes"); } else { $('#info').parent().hide(); showAlert('No customer is associated to this ticket.'); } } /** * Loads the result set of all the contacts linked to a Customer. * @returns {nlobjSearchResultSet} contactsResultSet */ function loadContactsList() { var currRec = currentRecord.get(); var customer_id = currRec.getValue({ fieldId: 'custpage_customer_id' }); var contactsResultSet = []; // If a ticket is opened for a barcode that is not allocated to a customer, // there will be no customer_id. if (!isNullorEmpty(customer_id)) { var contactsSearch = search.load({ type: 'contact', id: 'customsearch_salesp_contacts' }); var contactsFilterExpression = [ ['company', 'is', customer_id], 'AND', ['isinactive', 'is', 'F'] ]; contactsSearch.filterExpression = contactsFilterExpression; contactsResultSet = contactsSearch.run(); } return contactsResultSet; } /** * Dispalys fields related to customer and frnachisee and hides the remaining. */ function displayFranchiseeInfo(customer_record) { var customer_name = customer_record.getValue('companyname'); var daytodayemail = customer_record.getValue('email'); var daytodayphone = customer_record.getValue('phone'); var zee_name = customer_record.getText('partner'); var zee_email = customer_record.getValue({ name: 'email', join: 'partner', summary: null }); var zee_contact_name = customer_record.getValue({ name: 'custentity3', join: 'partner', summary: null }); var zee_abn = customer_record.getValue({ name: 'custentity_abn_franchiserecord', join: 'partner', summary: null }); var zee_phone = customer_record.getValue({ name: 'custentity2', join: 'partner', summary: null }); //Ticket details section $('.customer_name').val(customer_name); $('#daytodayemail').val(daytodayemail); $('#daytodayphone').val(daytodayphone); $('#franchisee_name').val(zee_name); $('#zee_email').val(zee_email); $('#zee_main_contact_name').val(zee_contact_name); $('#zee_main_contact_phone').val(zee_phone); $('#zee_abn').val(zee_abn); createContactsRows(); } /** * - Populates the Contacts table by adding contacts details at each row. * - If there is a ticket_id (which means we are in edit mode), * adds the contact to the "To" field of the "Send Email" section. */ function createContactsRows() { var contactsResultSet = loadContactsList(); console.log(contactsResultSet); // Used for the Contacts Table. var inline_contacts_table_html = ''; // If a ticket is opened for a barcode that is not allocated to a customer, // there will be no contacts. if (!isNullorEmpty(contactsResultSet)) { contactsResultSet.each(function(contactResult) { var contact_id = contactResult.getValue('internalid'); var salutation = contactResult.getValue('salutation'); var first_name = contactResult.getValue('firstname'); var last_name = contactResult.getValue('lastname'); var contact_name = salutation + ' ' + first_name + ' ' + last_name; var contact_email = contactResult.getValue('email'); var contact_phone = contactResult.getValue('phone'); var contact_role_value = contactResult.getValue('contactrole'); var contact_role_text = contactResult.getText('contactrole'); var add_as_recipient_btn = '<button style="background-color: #379E8F; border-color: #379E8F" class="btn btn-success add_as_recipient glyphicon glyphicon-envelope" type="button" data-email="' + contact_email + '" data-firstname="' + first_name + '" data-contact-id="' + contact_id + '" data-toggle="tooltip" data-placement="right" title="Add as recipient"></button>'; inline_contacts_table_html += '<tr class="text-center">'; inline_contacts_table_html += '<td headers="col_name">' + contact_name + '</td>'; inline_contacts_table_html += '<td headers="col_phone">' + contact_phone + '</td>'; inline_contacts_table_html += '<td headers="col_email">' + contact_email + '</td>'; inline_contacts_table_html += '<td headers="col_role">'; inline_contacts_table_html += '<span class="role_value" hidden>' + contact_role_value + '</span>'; inline_contacts_table_html += '<span class="role_text">' + contact_role_text + '</span>'; inline_contacts_table_html += '</td>'; inline_contacts_table_html += '<td headers="col_add_as_recipient">' + add_as_recipient_btn + '</td>'; inline_contacts_table_html += '</tr>'; return true; }); } $('#contacts tbody').html(inline_contacts_table_html); } /** * Populates the Usernote table by adding the usernotes at each row. */ function createUsernoteRows(ticket_id) { // Used for the UserNote Table. var inline_usernote_table_html = ''; ticket_id = parseInt(ticket_id); var ticketRecord = record.load({ type: 'customrecord_mp_ticket', id: ticket_id }); var comment = ticketRecord.getValue({ fieldId: 'custrecord_comment' }); if (!isNullorEmpty(comment)) { var comments = comment.split('\n'); // This regExp matches any content inside brackets, that is not brackets. var re = /\[([^\[\]]+)\]/g; comments.forEach(function(value, index, comments_array) { // Iterate the array from the last element to the first, in order to display the most recent usernote on top. var nb_usernotes = comments_array.length; var usernote = comments_array[nb_usernotes - index - 1]; var usernote_array = usernote.split(' - '); var match_brackets_content_iterator = re[Symbol.matchAll](usernote); // match_brackets_content_array is an array of arrays. // Each of its element contains the matched string (with the brackets), // and the string inside the brackets (which is used for `usernote_title`, `usernote_name` and `usernote_date`. var match_brackets_content_array = Array.from(match_brackets_content_iterator, function(x) { return (x[1]) }); var usernote_title = match_brackets_content_array[0]; var usernote_name = match_brackets_content_array[1]; var usernote_date = match_brackets_content_array[2]; var usernote_text = usernote_array[usernote_array.length - 1]; inline_usernote_table_html += '<tr class="text-center">'; inline_usernote_table_html += '<td headers="col_usernote_title">' + usernote_title + '</td>'; inline_usernote_table_html += '<td headers="col_usernote_name">' + usernote_name + '</td>'; inline_usernote_table_html += '<td headers="col_usernote_date">' + usernote_date + '</td>'; inline_usernote_table_html += '<td headers="col_usernote_comment">' + usernote_text + '</td>'; inline_usernote_table_html += '</tr>'; }); } $('#user_note tbody').html(inline_usernote_table_html); } /** * Function to select TOLL emails */ function selectTollEmails() { var toll_emails = $('#send_toll option:selected').map(function() { return $(this).val() }); toll_emails = $.makeArray(toll_emails); $('toll_emails').selectpicker('val', toll_emails); } /** * Function to select the enquiry medium */ function selectEnquiryMedium() { var medium_list = $('#enquiry_medium_status option:selected').map(function() { return $(this).val() }); medium_list = $.makeArray(medium_list); $('enquiry_medium_status').selectpicker('val', medium_list); } /** * For barcode tickets currently * Based on the selected MP Issue, an Owner is allocated to the ticket. * IT issues have priority over the other issues. */ function selectOwner() { var owner_list = $('#owner option:selected').map(function() { return $(this).val() }); console.log("owner_list", owner_list) owner_list = $.makeArray(owner_list); var list_mp_ticket_issues = $('#mp_issues option:selected').map(function() { return $(this).val() }); list_mp_ticket_issues = $.makeArray(list_mp_ticket_issues); console.log(list_mp_ticket_issues); if (list_mp_ticket_issues.length != 0) { var it_issue = false; var other_issue = '0'; list_mp_ticket_issues.forEach(function(mp_ticket_issue_value) { if (mp_ticket_issue_value < 5) { it_issue = true; } else { other_issue = mp_ticket_issue_value; } }); if (it_issue) { // IT Issue owner_list = owner_list.concat([409635, 696992]); // Select Ankith Ravindran and Raine Giderson. } else if (other_issue != '0') { switch (other_issue) { case '5': // Operational Issue owner_list.push(25537); // Select Michael McDaid. break; case '6': // Finance Issue owner_list.push(280700); // Select Vira Nathania. break; case '7': // Customer Service Issue owner_list.push(386344); // Select Jessica Roberts. break; case '10': // Customer App Issue owner_list = [1132504]; // Select Rianne Mansell break; case '9': // Customer App Issue owner_list = [1132504]; // Select Rianne Mansell break; case '11': // Customer App Issue owner_list = [1132504]; // Select Rianne Mansell break; } } } $('#owner').selectpicker('val', owner_list); } /** * Function triggered when the '#template' input field is blurred. * Load the subject of the email and the body of the template. */ function loadTemplate() { var currRec = currentRecord.get(); var template_id = $('#template option:selected').val(); console.log('template_id : ', template_id); try { var templateRecord = record.load({ type: 'customrecord_camp_comm_template', id: template_id, isDynamic: true }); var template_subject = templateRecord.getValue({ fieldId: 'custrecord_camp_comm_subject' }); console.log("templateRecord", templateRecord); console.log("tempsubj", template_subject); } catch (e) { //if (e instanceof error.SuiteScriptError) { if (e.name == "SSS_MISSING_REQD_ARGUMENT") { console.log('Error to load the template with template_id : ' + template_id); } //} } var customer_id = currRec.getValue({ fieldId: 'custpage_customer_id' }); var sales_rep = encodeURIComponent(runtime.getCurrentUser().name); console.log($('#send_to')) var first_name = $('#send_to').data("firstname"); console.log(first_name) var dear = encodeURIComponent(first_name); var contact_id = ''; var contact_id_array = $('#send_to').data('contact-id'); if (!isNullorEmpty(contact_id_array)) { contact_id_array = JSON.parse(contact_id_array); if (!isNullorEmpty(contact_id_array)) { contact_id = contact_id_array[0].toString(); if (contact_id == '0' && !isNullorEmpty(contact_id[1])) { contact_id = ''; } } } console.log('contact_id : ', contact_id); var userid = encodeURIComponent(runtime.getCurrentUser().id); // var url = 'https://1048144.extforms.netsuite.com/app/site/hosting/scriptlet.nl?script=395&deploy=1&compid=1048144&h=6d4293eecb3cb3f4353e&rectype=customer&template='; // if (runtime.envType == "SANDBOX") { // var url = 'https://1048144-sb3.extforms.netsuite.com/app/site/hosting/scriptlet.nl?script=395&deploy=1&compid=1048144_SB3&h=9c35dc467fbdfafcfeaa&rectype=customer&template='; // } // url += template_id + '&recid=' + customer_id + '&salesrep=' + sales_rep + '&dear=' + dear + '&contactid=' + contact_id + '&userid=' + userid; var suiteletUrl = url.resolveScript({ scriptId: 'customscript_merge_email', deploymentId: 'customdeploy_merge_email', returnExternalUrl: true }); console.log('suiteletUrl', suiteletUrl); suiteletUrl += '&rectype=customer&template='; //var template_id = 94; // var newLeadEmailTemplateRecord = record.load({ // type: 'customrecord_camp_comm_template', // id: template_id, // isDynamic: true // }); //var templateSubject = template_subject; var emailAttach = new Object(); emailAttach['entity'] = customer_id; //https://1048144-sb3.extforms.netsuite.com/app/site/hosting/scriptlet.nl?script=395&deploy=1&compid=1048144_SB3&h=9c35dc467fbdfafcfeaa&rectype=customer&template=91&recid=780069&salesrep=Sruti%20Desai&dear=&contactid=&userid=1115209 suiteletUrl += template_id + '&recid=' + customer_id + '&salesrep=' + sales_rep + '&dear=' + dear + '&contactid=' + null + '&userid=' + userid; // var headerObj = { // name: 'Accept-Language', // value: 'en-us' // }; console.log('suiteletUrl', suiteletUrl); // var response = https.get({ // url: suiteletUrl, // }); // var emailHtml = response.body; var response = https.get({ url: suiteletUrl }); console.log("response", response); // console.log("URL", url); // suiteletUrl = http.request({ // method: http.Method.GET, // url: url, // }) // // urlCall = http.get({ // // url: url, // // }); // console.log(urlCall); var emailHtml = response.body; $('#email_body').summernote('code', emailHtml); var ticket_id = currRec.getValue({ fieldId: 'custpage_ticket_id' }); ticket_id = parseInt(ticket_id); var selector_number = currRec.getValue({ fieldId: 'custpage_selector_number' }); var subject = 'MailPlus [MPSD' + ticket_id + '] - ' + template_subject + ' - ' + selector_number; $('#subject').val(subject); } /** * Check that the fields "To", "Template" and "Subject" are non-empty. * @returns {Boolean} */ function validateEmailFields() { var alertMessage = ''; var return_value = true; var send_to_val = $('#send_to').val(); var send_toll_val = $('#send_toll').val(); if (isNullorEmpty(send_to_val) && isNullorEmpty(send_toll_val)) { return_value = false; alertMessage += 'Please select a recipient.<br>'; } var template_val = $('#template option:selected').val(); if (isNullorEmpty(template_val)) { return_value = false; alertMessage += 'Please select a template.<br>'; } else { var subject_val = $('#subject').val(); if (isNullorEmpty(subject_val)) { return_value = false; alertMessage += 'Please enter a subject.<br>'; } } if (return_value == false) { showAlert(alertMessage); } else { $('#alert').parent().hide(); } return return_value; } /** * Function to sent emails when a customer associated ticket is opened */ function sendCustomerTicketEmail(subject, ticket_id, customer_number, selector_type, selector_number, browser, os, login_email_used, sender_name, sender_phone, send_to) { console.log("in email fn ", send_to); if (isNullorEmpty(browser)) { browser = " - " }; if (isNullorEmpty(os)) { os = " - " }; if (isNullorEmpty(login_email_used)) { login_email_used = " - " }; if (isNullorEmpty(sender_name)) { sender_name = " - " }; if (isNullorEmpty(sender_phone)) { sender_phone = " - " }; var url = "https://1048144.app.netsuite.com/app/site/hosting/scriptlet.nl?script=1243&deploy=1&compid=1048144&"; if (runtime.envType == "SANDBOX") { var url = "https://1048144-sb3.app.netsuite.com/app/site/hosting/scriptlet.nl?script=1243&deploy=1&compid=1048144_SB3"; } var contactEmail = ["ankith.ravindran@mailplus.com.au"]; var custparam_params = new Object(); custparam_params['ticket_id'] = parseInt(ticket_id); custparam_params['selector_number'] = selector_number; custparam_params['selector_type'] = selector_type; var ticket_url = url + "&custparam_params=" + encodeURIComponent(JSON.stringify(custparam_params)); if (isNullorEmpty(subject)){ subject = 'MPSD' + ticket_id + ' - New Customer Ticket Opened'; } var body = '' + selector_number + ' Ticket Details <br>'; body += 'Customer number : ' + customer_number + ' <br>'; body += 'Login email used : ' + login_email_used + ' <br>'; switch (selector_number) { case 'Customer App': body += 'Browser : ' + browser + ' <br>'; body += 'Operating system : ' + os + ' <br>'; break; case 'Customer Portal': body += 'Browser : ' + browser + ' <br>'; break; case 'Update Label': body += 'Sender name : ' + sender_name + ' <br>'; body += 'Sender phone : ' + sender_phone + ' <br>'; break; } body += '<a href="' + ticket_url + '"> Open ticket page </a><br>'; body += 'Next reminder time: ' + getNextReminderTime() + ' <br>'; var file = $('#screenshot_image')[0]; if (file && (typeof file.files[0] != 'undefined')) { file = file.files[0]; if ((file.type == "image/jpeg" || file.type == "image/png") && (file.name)) { var fr = new FileReader(); fr.onload = function(e) { body += '<img src=" ' + e.target.result + '">'; console.log("email send", send_to); if (!isNullorEmpty(send_to)) { email.send({ author: userId, body: body, recipients: send_to, subject: subject, cc: contactEmail, }); } } fr.readAsDataURL(file); } } else { if (!isNullorEmpty(send_to)) { console.log("email send", send_to); email.send({ author: userId, body: body, recipients: send_to, subject: subject, cc: contactEmail, }) } } console.log("EMAIL WORKED"); } /** * Triggered by a click on the button 'SEND EMAIL' ('#send_email') * Send the selected email to the selected contact, and reloads the page. */ function sendEmail() { if (validateEmailFields()) { // Send Email // Convert "TO" text field to email adresses array var send_to_values = $('#send_to').val().split(','); var send_to = []; if (!isNullorEmpty(send_to_values)) { send_to_values.forEach(function(email_address) { email_address = email_address.trim(); if (!isNullorEmpty(email_address)) { send_to.push(email_address); } }); } console.log("send_to", send_to); var send_toll_values = $('#send_toll').val(); var send_toll_to = []; if (!isNullorEmpty(send_toll_values)) { for (var i = 0; i < send_toll_values.length; i++) { send_toll_to.push($('#send_toll option:selected').val(send_toll_values)[i].text); } } // CC Field var cc_values = $('#send_cc').val().split(','); var cc = []; cc_values.forEach(function(email_address) { cc.push(email_address.trim()); return true; }); if (isNullorEmpty(cc)) { cc = null; } console.log("cc", cc); // BCC Field var bcc_values = $('#send_bcc').val().split(','); var bcc = []; bcc_values.forEach(function(email_address) { bcc.push(email_address.trim()); return true; }); if (isNullorEmpty(bcc)) { bcc = null; } console.log("bcc", bcc); var email_subject = $('#subject').val(); var email_body = $('#email_body').summernote('code'); var customer_id = currRec.getValue({ fieldId: 'custpage_customer_id' }); var ticket_id = currRec.getValue({ fieldId: 'custpage_ticket_id' }); ticket_id = parseInt(ticket_id); var params_email = currRec.getValue({ fieldId: 'custpage_param_email' }); params_email = JSON.parse(params_email); params_email.recipient = send_to; params_email.subject = email_subject; params_email.body = encodeURIComponent(email_body); params_email.cc = cc; params_email.bcc = bcc; params_email.records = {entityId: customer_id}; var attachments_credit_memo_ids = params_email.attachments_credit_memo_ids; var attachments_usage_report_ids = params_email.attachments_usage_report_ids; var attachments_invoice_ids = params_email.attachments_invoice_ids; params_email = JSON.stringify(params_email); if (!isNullorEmpty(attachments_credit_memo_ids) || !isNullorEmpty(attachments_usage_report_ids) || !isNullorEmpty(attachments_invoice_ids)) { // Send email using the response part of this suitelet script. currRec.setValue({ fieldId: 'custpage_param_email', value: params_email }); setRecordStatusToInProgress(ticket_id); // Trigger the submit function. $('#submitter').trigger('click'); } else { send_to = send_to.concat(send_toll_to); console.log("Final send " + send_to); // If there are no attachments, it's faster to directly use nlapiSendEmail() from the client script. // console.log("email send", recipients); if (!isNullorEmpty(customer_id) && !isNullorEmpty(send_to)) { email.send({ author: userId, body: email_body, recipients: send_to, subject: email_subject, relatedRecords: { entityId: customer_id}, bcc: bcc, cc: cc, }) } else { email.send({ author: userId, body: email_body, recipients: send_to, subject: email_subject, bcc: bcc, cc: cc, }) } // 112209 is from MailPlus Team var selector_number = currRec.getValue({ fieldId: 'custpage_selector_number' }); var selector_type = currRec.getValue({ fieldId: 'custpage_selector_type' }); setRecordStatusToInProgress(ticket_id); // Reload the page var params = { ticket_id: parseInt(ticket_id), selector_number: selector_number, selector_type: selector_type, }; params = JSON.stringify(params); var output = url.resolveScript({ deploymentId: 'customdeploy_sl_open_ticket_2', scriptId: 'customscript_sl_open_ticket_2', }) var upload_url = baseURL + output + '&custparam_params=' + params; window.open(upload_url, "_self", "height=750,width=650,modal=yes,alwaysRaised=yes"); } } else { return false; } } /** * Set record status to 'In Progress'. * @param {Number} ticket_id */ function setRecordStatusToInProgress(ticket_id) { try { var ticketRecord = record.load({ type: 'customrecord_mp_ticket', id: ticket_id }); var status_value = ticketRecord.getValue({ fieldId: 'custrecord_ticket_status' }); var invoice_id = ticketRecord.getValue({ fieldId: 'custrecord_invoice_number' }); if (isNullorEmpty(status_value) || status_value == 1) { //Ticket is open var selector_number = currRec.getValue({ fieldId: 'custpage_selector_number' }); if (isFinanceRoleOnly(userRole) && !isNullorEmpty(invoice_id)) { ticketRecord.setValue({ fieldId: 'custrecord_ticket_status', value: 6 }); } else if (!isNullorEmpty(selector_number) && selector_number == "Customer App") { console.log('Setting ticket status to In progress - IT'); ticketRecord.setValue({ fieldId: 'custrecord_ticket_status', value: 4 }); //In progress - Developers } else { ticketRecord.setValue({ fieldId: 'custrecord_ticket_status', value: 2 }); } ticketRecord.setValue({ fieldId: 'custrecord_email_sent', value: true }); ticketRecord.save({ enableSourcing: true, }) } } catch (e) { console.log("e", e); //if (e instanceof error.SuiteScriptError) { if (e.name == "SSS_MISSING_REQD_ARGUMENT") { console.log('Error to Set record status to In Progress with ticket_id : ' + ticket_id); } //} } } /** * - Triggered by any changes on the TOLL Issues, Invoice Issues or MP Ticket Issues fields. * - Display the button 'CLOSE TICKET' only when there are no selected issues. * - Display the button 'CLOSE UNALLOCATED TICKET' only if the user is Ankith Ravindran or Raine Giderson * and if the issues 'No allocated customer' or 'No allocated franchisee' are selected. */ function hideCloseTicketButton() { // Check that there are no selected issues. var selector_type = currRec.getValue({ fieldId: 'custpage_selector_type' }); var toll_issues_length = $('#toll_issues option:selected').length; var invoice_issues_length = $('#invoice_issues option:selected').length; var mp_issues_length = $('#mp_issues option:selected').length; // Show the 'Close Ticket' Button switch (selector_type) { case 'barcode_number': if ((toll_issues_length == 0) && (mp_issues_length == 0)) { $('.close_ticket').removeClass('hide'); $('.close_ticket_lost').removeClass('hide'); } else { $('.close_ticket').addClass('hide'); $('.close_ticket_lost').addClass('hide'); } break; case 'invoice_number': if ((invoice_issues_length == 0) && (mp_issues_length == 0)) { $('.close_ticket').removeClass('hide'); $('.close_ticket_lost').removeClass('hide'); } else { $('.close_ticket').addClass('hide'); $('.close_ticket_lost').addClass('hide'); } break; } // Show the 'Close Unallocated' button. var mp_issues_selected = $('#mp_issues option:selected').map(function() { return $(this).val() }); mp_issues_selected = $.makeArray(mp_issues_selected); // '1' is the MP Issue 'No Allocated Customer' // '3' is the MP Issue 'No Allocated Franchisee' var is_no_allocated_mp_issue = (mp_issues_selected.indexOf('1') != -1 || mp_issues_selected.indexOf('3') != -1); // '409635' is the user ID of Ankith Ravindran // '696992' is the user ID of Raine Giderson // '766498' is the user ID of RaphaΓ«l Chalicarne var is_user_ankith_or_raine = (userId == '409635' || userId == '696992' || userId == '766498'); var can_show_close_unallocated_button = (is_no_allocated_mp_issue && is_user_ankith_or_raine); if (can_show_close_unallocated_button) { $('.close_unallocated_ticket').removeClass('hide'); } else { $('.close_unallocated_ticket').addClass('hide'); } updateButtonsWidth(); } function updateSaveRecord() { var currRec = currentRecord.get(); var status_value = currRec.getValue({ fieldId: 'custpage_ticket_status_value' }); var selector_issue = currRec.getValue({ fieldId: 'custpage_selector_issue' }); //set to T onEscalate var selector_type = currRec.getValue({ fieldId: 'custpage_selector_type' }); var customer_number = currRec.getValue({ fieldId: 'custpage_customer_number' }); var selector_number = $('#selector_value').val(); console.log('status_value' + status_value) console.log('selector_issue ' + selector_issue) console.log('selector_type ' + selector_type) console.log('selector_number ' + selector_number) if (selector_type == 'customer_issue') { if (isNullorEmpty(customer_number)) { showAlert('Please enter a customer number'); return false; } } // if (isTicketNotClosed(status_value) && !isNullorEmpty(selector_type)) { // // Barcode/Inv associated tickets - check that a TOLL Issue or an Invoice Issue has been selected. // // Customer number associated ticket - check that a customer number has been entered // switch (selector_type) { // case 'barcode_number': // var toll_issues_length = $('#toll_issues option:selected').length; // if (toll_issues_length == 0) { // showAlert('Please select a TOLL Issue<br>'); // return false; // } // break; // case 'invoice_number': // var invoice_issues_length = $('#invoice_issues option:selected').length; // if (invoice_issues_length == 0) { // showAlert('Please select an Invoice Issue<br>'); // return false; // } // break; // case 'customer_issue': // var login_email_used = $('#login_email_text').val(); // if (!isNullorEmpty(login_email_used) && !validateEmail(login_email_used)) { // showAlert('User login email format is invalid. Please enter email again <br>'); // return false; // } // break; // } // } if (role == 1005) { var owner_length = $('#owner option:selected').length; if (owner_length == 0) { showAlert('Please select an Owner<br>'); return false; } } else { var owner_length = $('#owner option:selected').length; var checkTicketOwner = currRec.getValue({ fieldId: 'custpage_ticket_id' }); if (!isNullorEmpty(checkTicketOwner)) { var checkTicketOwnerRec = record.load({ type: 'customrecord_mp_ticket', id: parseInt(checkTicketOwner) }); var owners = checkTicketOwnerRec.getValue({ fieldId: 'custrecord_owner'}); if (isNullorEmpty(owners) && owner_length == 0) { showAlert('Please select an Owner<br>'); return false; } } else { if (owner_length == 0) { showAlert('Please select an Owner<br>'); return false; } } } if (selector_issue == 'T') { var to = $('#owner option:selected').map(function() { return $(this).data('email') }); to = $.makeArray(to); var email_sent = sendInformationEmailTo(selector_type, to, true) if (!email_sent) { return false; } } var ticket_id = currRec.getValue({ fieldId: 'custpage_ticket_id' }); console.log("Ticket id = " + ticket_id); if (isNullorEmpty(ticket_id)) { var ticketRecord = record.create({ type: 'customrecord_mp_ticket', }); currRec.setValue({ fieldId: 'custpage_created_ticket', value: 'T' }); ticketRecord.setValue({ fieldId: 'custrecord_email_sent', value: false }); console.log("DOES FALSE WORK", ticketRecord.getValue({ fieldId: 'custrecord_email_sent' })) } else { ticket_id = parseInt(ticket_id); try { var ticketRecord = record.load({ type: 'customrecord_mp_ticket', id: ticket_id }); } catch (e) { if (e instanceof error.SuiteScriptError) { if (e.name == "SSS_MISSING_REQD_ARGUMENT") { console.log('Error to load the ticket record with ticket_id : ' + ticket_id); } } } } currRec.setValue({ fieldId: 'custpage_selector_number', value: selector_number }); var selector_id = currRec.getValue({ fieldId: 'custpage_selector_id' }); // Save customer number var customer_number = $('#customer_number_value').val(); console.log('Saving customer number = ' + customer_number); ticketRecord.setValue({ fieldId: 'custrecord_cust_number', value: customer_number }); // Save Enquiry status var enquiry_status_val = $('#enquiry_status option:selected').val(); if (!isNullorEmpty(enquiry_status_val)) { ticketRecord.setValue({ fieldId: 'custrecord_enquiry_status', value: enquiry_status_val }); } var attachments_hyperlink = $('#attachments').val(); if (!isNullorEmpty(attachments_hyperlink)) { ticketRecord.setValue({ fieldId: 'custrecord_mp_ticket_attachments', value: attachments_hyperlink }); } // Save Ticket Label var label = $('#label_status option:selected').val(); if (!isNullorEmpty(label)) { ticketRecord.setValue({ fieldId: 'custrecord_ticket_label', value: label }); } //Save Enquiry medium var enquiry_medium = $('#enquiry_status option:selected').val(); if (!isNullorEmpty(enquiry_medium)) { ticketRecord.setValue({ fieldId: 'custrecord_enquiry_medium', value: enquiry_medium }); } var total_enquiry_count = 0; if (!isNullorEmpty($('#enquiry_count_by_chat').val())) { total_enquiry_count += parseInt($('#enquiry_count_by_chat').val()); } if (!isNullorEmpty($('#enquiry_count_by_phone').val())) { total_enquiry_count += parseInt($('#enquiry_count_by_phone').val()); } if (!isNullorEmpty($('#enquiry_count_by_email').val())) { total_enquiry_count += parseInt($('#enquiry_count_by_email').val()); } ticketRecord.setValue({ fieldId: 'custrecord_enquiry_count', value: total_enquiry_count }); var enquiry_count_by_chat = $('#enquiry_count_by_chat').val(); if (!isNullorEmpty(enquiry_count_by_chat)) { ticketRecord.setValue({ fieldId: 'custrecord_chat_enquiry_count', value: enquiry_count_by_chat }); } var enquiry_count_by_phone = $('#enquiry_count_by_phone').val(); if (!isNullorEmpty(enquiry_count_by_phone)) { ticketRecord.setValue({ fieldId: 'custrecord_phone_enquiry_count', value: enquiry_count_by_phone }); } var enquiry_count_by_email = $('#enquiry_count_by_email').val(); if (!isNullorEmpty(enquiry_count_by_email)) { ticketRecord.setValue({ fieldId: 'custrecord_email_enquiry_count', value: enquiry_count_by_email }); } var interaction_count_by_phone = $('#interaction_count_by_phone').val(); var interaction_count_by_email = $('#interaction_count_by_email').val(); if (isNullorEmpty(ticketRecord.getValue({ fieldId: 'custrecord_first_interaction_date'}))) { if (!isNullorEmpty(interaction_count_by_email) || !isNullorEmpty(interaction_count_by_phone)) { ticketRecord.setValue({ fieldId: 'custrecord_first_interaction_date', value: new Date()}); } } if (!isNullorEmpty(interaction_count_by_phone)) { ticketRecord.setValue({ fieldId: 'custrecord_phone_interaction_count', value: interaction_count_by_phone }); } if (!isNullorEmpty(interaction_count_by_email)) { ticketRecord.setValue({ fieldId: 'custrecord_email_interaction_count', value: interaction_count_by_email }); } //Check Enquiry is Selected if (isNullorEmpty(enquiry_count_by_chat) && isNullorEmpty(enquiry_count_by_phone) && isNullorEmpty(enquiry_count_by_email)) { showAlert('Please select an Enquiry Type<br>'); return false; } else if(total_enquiry_count == 0) { showAlert('Please select an Enquiry Type<br>'); return false; } //Save Medium list saveMediumList(enquiry_count_by_chat, enquiry_count_by_phone, enquiry_count_by_email, ticketRecord); ticketRecord = setTicketStatus(ticketRecord); ticketRecord = setCreator(ticketRecord); ticketRecord.setValue({ fieldId: 'altname', value: selector_number }); var owner_email_list = $('#owner option:selected').map(function() { return $(this).data('email') }); owner_email_list = $.makeArray(owner_email_list); var zee_id = currRec.getValue({ fieldId: 'custpage_zee_id' }); ticketRecord.setValue({ fieldId: 'custrecord_zee', value: zee_id }); if (!isNullorEmpty(selector_type)) { switch (selector_type) { case 'barcode_number': ticketRecord.setValue({ fieldId: 'custrecord_barcode_number', value: selector_id }); // Save Reminder date var reminder_date = $('#reminder').val(); if (!isNullorEmpty(reminder_date)) { reminder_date = new Date(reminder_date); console.log(reminder_date); reminder_date = format.parse({ value: reminder_date, type: format.Type.DATE }); console.log("rem date", reminder_date); ticketRecord.setValue({ fieldId: 'custrecord_reminder', value: reminder_date }); } break; case 'invoice_number': ticketRecord.setValue({ fieldId: 'custrecord_invoice_number', value: selector_id }); var customer_id = currRec.getValue({ fieldId: 'custpage_customer_id' }); ticketRecord.setValue({ fieldId: 'custrecord_customer1', value: customer_id }); if (isFinanceRole(userRole)) { var daytodayemail = $('#daytodayemail').val(); var daytodayphone = $('#daytodayphone').val(); var accountsemail = $('#accountsemail').val(); var accountsphone = $('#accountsphone').val(); var selected_invoice_method_id = $('#invoice_method option:selected').val(); var accounts_cc_email = $('#accounts_cc_email').val(); var mpex_po_number = $('#mpex_po_number').val(); var customer_po_number = $('#customer_po_number').val(); var customer_terms = $('#customers_terms').val(); var selected_invoice_cycle_id = $('#mpex_invoicing_cycle option:selected').val(); var customerRecord = record.load({ type: 'customer', id: customer_id }); customerRecord.setValue({ fieldId: 'custentity_email_service', value: daytodayemail }); customerRecord.setValue({ fieldId: 'phone', value: daytodayphone }); customerRecord.setValue({ fieldId: 'email', value: accountsemail }); customerRecord.setValue({ fieldId: 'altphone', value: accountsphone }); customerRecord.setValue({ fieldId: 'custentity_invoice_method', value: selected_invoice_method_id }); customerRecord.setValue({ fieldId: 'custentity_accounts_cc_email', value: accounts_cc_email }); customerRecord.setValue({ fieldId: 'custentity_mpex_po', value: mpex_po_number }); customerRecord.setValue({ fieldId: 'custentity11', value: customer_po_number }); customerRecord.setValue({ fieldId: 'custentity_finance_terms', value: customer_terms }); customerRecord.setValue({ fieldId: 'custentity_mpex_invoicing_cycle', value: selected_invoice_cycle_id }); customerRecord.save({}) // Save Reminder date var reminder_date = $('#reminder').val(); if (!isNullorEmpty(reminder_date)) { reminder_date = new Date(reminder_date); reminder_date = format.parse({ value: reminder_date, type: format.Type.DATE }); ticketRecord.setValue({ fieldId: 'custrecord_reminder', value: reminder_date}); } } break; case 'customer_issue': var screenshot_image = currRec.getValue({ fieldId: 'custpage_ss_image' }); if (!isNullorEmpty(screenshot_image)) { ticketRecord.setValue({ fieldId: 'custrecord_screenshot', value: screenshot_image}); } var customer_id = currRec.getValue({ fieldId: 'custpage_customer_id' }); if (!isNullorEmpty(customer_id)) { ticketRecord.setValue({ fieldId: 'custrecord_customer1', value: customer_id}); } var customer_issue_type = $('#selector_value').val(); if (!isNullorEmpty(customer_issue_type)) { ticketRecord.setValue({ fieldId: 'custrecord_customer_issue', value: customer_issue_type}); } var login_email_used = $('#login_email_text').val(); if (!isNullorEmpty(login_email_used)) { ticketRecord.setValue({ fieldId: 'custrecord_login_email', value: login_email_used}); } var is_customer_number_email_sent = currRec.getValue({ fieldId: 'custpage_customer_number_email_sent' }); switch (customer_issue_type) { case 'Customer App': var phone_used = $('#phone_used').val(); if (!isNullorEmpty(phone_used)) { ticketRecord.setValue({ fieldId: 'custrecord_phone_used', value: phone_used}); } if (is_customer_number_email_sent == 'F' && !isNullorEmpty(ticket_id)) { sendCustomerTicketEmail('',ticket_id, customer_number, selector_type, selector_number, '', '', login_email_used, '', '', owner_email_list); ticketRecord.setValue({ fieldId: 'custrecord_customer_number_email_sent', value: true }); } break; case 'Customer Portal': var browser = $("#browser_value option:selected").val(); if (!isNullorEmpty(browser)) { ticketRecord.setValue({ fieldId: 'custrecord_browser', value: browser}); } var os_used = $('#os_value option:selected').val(); if (!isNullorEmpty(os_used)) { ticketRecord.setValue({ fieldId: 'custrecord_operating_system', value: os_used}); } if (is_customer_number_email_sent == 'F' && !isNullorEmpty(ticket_id)) { sendCustomerTicketEmail('',ticket_id, customer_number, selector_type, selector_number, $("#browser_value option:selected").text(), $('#os_value option:selected').text(), login_email_used, '', '', owner_email_list); ticketRecord.setValue({ fieldId: 'custrecord_customer_number_email_sent', value: true }); } break; case 'Update Label': var sender_name = $('#sender_name_text').val(); if (!isNullorEmpty(sender_name)) { ticketRecord.setValue({ fieldId: 'custrecord_sender_name', value: sender_name}); } var sender_phone = $('#sender_phone_text').val(); if (!isNullorEmpty(sender_phone)) { ticketRecord.setValue({ fieldId: 'custrecord_sender_phone', value: sender_phone}); } if (is_customer_number_email_sent == 'F' && !isNullorEmpty(ticket_id)) { sendCustomerTicketEmail('',ticket_id, customer_number, selector_type, selector_number, '', '', login_email_used, sender_name, sender_phone, owner_email_list); ticketRecord.setValue({ fieldId: 'custrecord_customer_number_email_sent', value: true }); } break; } break; } } ticketRecord = updateIssues(ticketRecord); //Owner var owner_list = new Array; $('#owner option:selected').each(function() { owner_list.push($(this).val()); }); if (!isNullorEmpty(ticket_id)) { // Send email to new owners. var old_owner_list = ticketRecord.getValue({ fieldId: 'custrecord_owner' }); if (!isNullorEmpty(old_owner_list)) { var only_new_owner_ids = []; var only_new_owner_email_address = []; owner_list.forEach(function(new_owner_id) { if (old_owner_list.indexOf(new_owner_id) == -1) { only_new_owner_ids.push(new_owner_id); only_new_owner_email_address.push($('#owner [value="' + new_owner_id + '"]').data('email')); } }) } else { var only_new_owner_ids = owner_list; var only_new_owner_email_address = []; owner_list.forEach(function(owner_id) { only_new_owner_email_address.push($('#owner [value="' + owner_id + '"]').data('email')); }) } // If there is an issue, all the owners have already received an email. if (selector_issue == 'F' && (!isNullorEmpty(only_new_owner_email_address))) { var email_sent = sendInformationEmailTo(selector_type, only_new_owner_email_address, false); if (!email_sent) { return false; } } else if (selector_type == 'customer_issue') { var login_email_used = $('#login_email_text').val(); var customer_issue_type = $('#selector_value').val(); switch (customer_issue_type) { case 'Customer App': var phone_used = $('#phone_used').val(); var os_used = $('#os_value option:selected').val(); var browser = $("#browser_value option:selected").val() sendCustomerTicketEmail('',ticket_id, customer_number, selector_type, selector_number, $("#browser_value option:selected").text(), $('#os_value option:selected').text(), login_email_used, '', '', only_new_owner_email_address); break; case 'Customer Portal': var browser = $('#browser_value').val(); sendCustomerTicketEmail('',ticket_id, customer_number, selector_type, selector_number, $("#browser_value option:selected").text(), '', login_email_used, '', '', only_new_owner_email_address); break; case 'Update Label': var sender_phone = $('#sender_phone_text').val(); var sender_name = $('#sender_name_text').val(); sendCustomerTicketEmail('',ticket_id, customer_number, selector_type, selector_number, '', '', login_email_used, sender_name, sender_phone, only_new_owner_email_address); break; } } } // Save Owner list console.log(owner_list); ticketRecord.setValue({ fieldId: 'custrecord_owner', value: owner_list }); console.log("oList", ticketRecord.getValue({ fieldId: 'custrecord_owner'})); //cxcxc // Save Comment switch (selector_type) { case 'barcode_number': var comment = $('#comment').val(); break; case 'invoice_number': var comment = ticketRecord.getValue({ fieldId: 'custrecord_comment' }); if (isNullorEmpty(comment)) { comment = '' }; var selected_title = $('#user_note_title option:selected').text(); var usernote_textarea = $('#user_note_textarea').val(); var date = new Date; var date_time_now = format.parse({ value: date, type: format.Type.DATETIMETZ}); var date_now = format.parse({ value: date, type: format.Type.DATE}); var time_now = format.parse({ value: date, type: format.Type.TIMEOFDAY}); if (!isNullorEmpty(usernote_textarea)) { if (!isNullorEmpty(comment)) { comment += '\n'; } var usernote = '[' + selected_title + '] - [' + userName + '] - [' + date_time_now + '] - ' + usernote_textarea; // Save usernote on Customer record var userNote = record.create({ type: 'note', }); userNote.setValue({ fieldId: 'title', value: selected_title}); userNote.setValue({ fieldId: 'notedate', value: date_now}); userNote.setValue({ fieldId: 'time', value: time_now}); userNote.setValue({ fieldId: 'note', value: usernote_textarea}); userNote.setValue({ fieldId: 'entity', value: customer_id}); if (!isNullorEmpty(customer_id)) { userNote.save({}) } comment += usernote; } break; case 'customer_issue': var comment = $('#comment').val(); break; } if (!isNullorEmpty(comment)) { var original_comment = ticketRecord.getValue({ fieldId: 'custrecord_comment'} ); var total_comment = $('#comment').val(); var new_comment = total_comment.split(original_comment).join(''); var new_comment = total_comment.split(original_comment).join(''); var new_comment2 = new_comment.split("\n").join(''); //"good_luck_buddy".replace(/\n/,'&').split('&') //["good","luck_buddy"] var date_netsuite = format.format({ value: new Date(), type: format.Type.DATETIME }); console.log("new_comment", new_comment); console.log("new_comment2", new_comment2); var comment_with_date = total_comment; if (!isNullorEmpty(new_comment2)) { comment_with_date = "\n" + original_comment + "\n" + date_netsuite + " - " + new_comment2 + "\n"; } console.log('comment_with_date', comment_with_date); ticketRecord.setValue({ fieldId: 'custrecord_comment', value: comment_with_date} ); } var ticket_id = ticketRecord.save({ enableSourcing: true, }); currRec.setValue({ fieldId: 'custpage_ticket_id', value: ticket_id} ); if (!isNullorEmpty(selector_id) && (selector_type == 'barcode_number')) { try { var list_toll_issues = new Array; $('#toll_issues option:selected').each(function() { list_toll_issues.push($(this).val()); }); var barcodeRecord = record.load({ type: 'customrecord_customer_product_stock', id: selector_id }); console.log("ticket_id", ticket_id); console.log("list_toll_issues", list_toll_issues); barcodeRecord.setValue({ fieldId: 'custrecord_mp_ticket', value: ticket_id} ); barcodeRecord.setValue({ fieldId: 'custrecord_cust_prod_stock_toll_issues ', value: list_toll_issues }); var rec_email = $('#receiveremail').val(); var rec_name = $('#receivername').val(); var rec_state = $('#receiverstate').val(); var rec_zip = $('#receiverzip').val(); var rec_addr1 = $('#receiveraddr1').val(); var rec_addr2 = $('#receiveraddr2').val(); var rec_city = $('#receiversuburb').val(); var rec_phone = $('#receiverphone').val(); //Check if Rec details are to be updated if (!$("#receiveremail").is(":disabled")) { if (!isNullorEmpty(rec_email)) { barcodeRecord.setValue({ fieldId: 'custrecord_receiver_email', value: rec_email }); } if (!isNullorEmpty(rec_name)) { barcodeRecord.setValue({ fieldId: 'custrecord_receiver_name', value: rec_name }); } if (!isNullorEmpty(rec_state)) { barcodeRecord.setValue({ fieldId: 'custrecord_receiver_state', value: rec_state }); } if (!isNullorEmpty(rec_zip)) { barcodeRecord.setValue({ fieldId: 'custrecord_receiver_postcode', value: rec_zip }); } if (!isNullorEmpty(rec_addr1)) { barcodeRecord.setValue({ fieldId: 'custrecord_receiver_addr1', value: rec_addr1 }); } if (!isNullorEmpty(rec_addr2)) { barcodeRecord.setValue({ fieldId: 'custrecord_receiver_addr2', value: rec_addr2 }); } if (!isNullorEmpty(rec_city)) { barcodeRecord.setValue({ fieldId: 'custrecord_receiver_suburb', value: rec_city }); } if (!isNullorEmpty(rec_phone)) { barcodeRecord.setValue({ fieldId: 'custrecord_receiver_phone', value: rec_phone }); } } barcodeRecord.save({ enableSourcing: true, }); } catch (e) { //if (e instanceof error.SuiteScriptError) { // if (e.name == "SSS_MISSING_REQD_ARGUMENT") { console.log('Error to load the barcode record with barcode_id : ' + selector_id); // } //} } } return true; } /** * Triggered by a click on the button 'UPDATE CLOSE TICKET' ('#close_ticket') * Set the date of closure, and the status as "Closed". */ function updateCloseTicket() { console.log('In update&close function'); var date = new Date; var dnow = format.parse({ value: date, type: format.Type.DATETIMETZ }); var ticket_id = currRec.getValue({ fieldId: 'custpage_ticket_id' }); ticket_id = parseInt(ticket_id); var ticketRecord = record.load({ type: 'customrecord_mp_ticket', id: ticket_id }); ticketRecord.setValue({ fieldId: 'custrecord_date_closed', value: dnow }); ticketRecord.setValue({ fieldId: 'custrecord_ticket_status', value: 3 }); ticketRecord.setValue({ fieldId: 'custrecord_mp_ticket_customer_status', value: 5 }); ticketRecord.setValue({ fieldId: 'custrecord_reminder', value: null }); console.log('All values have been set part1'); // Save issues and resolved issues ticketRecord = updateIssues(ticketRecord); var ticket_name = ticketRecord.getText({fieldId: 'name'}); var customer_barcode_number = ticketRecord.getValue({ fieldId : 'custrecord_barcode_number'}); var customer_id = ticketRecord.getValue({fieldId: 'custrecord_customer1'}); try { var barcodeRecord = record.load({ type: 'customrecord_customer_product_stock', id: customer_barcode_number, }); var receiveremail = barcodeRecord.getValue({fieldId: 'custrecord_receiver_email'}); var barcodeName = barcodeRecord.getValue({fieldId: 'name'}); console.log('All values have been set part2'); //Send Email To Customer if (!isNullorEmpty(receiveremail)) { sendCustomerEscalateEmail('MailPlus [' + ticket_name + '] - Ticket Closed - ' + barcodeName, [receiveremail], 114, customer_id); } } catch(e) { console.log("Failed to load barcode because no customer linked"); } console.log('Email sent'); ticketRecord.save({ enableSourcing: true, }) console.log('Redirecting to edit tickets page'); // Redirect to the "View MP Tickets" page var output = url.resolveScript({ deploymentId: 'customdeploy_sl_edit_ticket_2', scriptId: 'customscript_sl_edit_ticket_2', }) var upload_url = baseURL + output; window.open(upload_url, "_self", "height=750,width=650,modal=yes,alwaysRaised=yes"); } function closeTicket(selector_type, status_num) { if (selector_type == "customer_issue") { closeCustIssueTicket(selector_type, status_num); } else { closeBarcodeTicket() } } /** * Triggered by a click on the button 'CLOSE TICKET' ('#close_ticket') * Set the date of closure, and the status as "Closed". */ function closeBarcodeTicket() { if (confirm("Are you sure you want to close this ticket?\n\nThis action cannot be undone.")) { var date = new Date; var dnow = format.parse({ value: date, type: format.Type.DATETIMETZ }); updateSaveRecord(); var ticket_id = currRec.getValue({ fieldId: 'custpage_ticket_id' }); ticket_id = parseInt(ticket_id); var ticketRecord = record.load({ type: 'customrecord_mp_ticket', id: ticket_id }); var customer_id = ticketRecord.getValue({fieldId: 'custrecord_customer1'}); ticketRecord.setValue({ fieldId: 'custrecord_ticket_status', value: 3 }); ticketRecord.setValue({ fieldId: 'custrecord_date_closed', value: dnow }); ticketRecord.setValue({ fieldId: 'custrecord_mp_ticket_customer_status', value: 5 }); ticketRecord.setValue({ fieldId: 'custrecord_reminder', value: null }); // Save issues and resolved issues ticketRecord = updateIssues(ticketRecord); var ticket_name = ticketRecord.getText({fieldId: 'name'}); var customer_barcode_number = ticketRecord.getValue({ fieldId : 'custrecord_barcode_number'}); var customer_id = ticketRecord.getValue({fieldId: 'custrecord_customer1'}); try { var barcodeRecord = record.load({ type: 'customrecord_customer_product_stock', id: customer_barcode_number, }); var receiveremail = barcodeRecord.getValue({fieldId: 'custrecord_receiver_email'}); var barcodeName = barcodeRecord.getValue({fieldId: 'name'}); //Send Email To Customer if (!isNullorEmpty(receiveremail)) { sendCustomerEscalateEmail('MailPlus [' + ticket_name + '] - Ticket Closed - ' + barcodeName, [receiveremail], 114, customer_id); } } catch(e) { console.log("Failed to load barcode because no customer linked"); } ticketRecord.save({ enableSourcing: true, }) // Redirect to the "View MP Tickets" page var output = url.resolveScript({ deploymentId: 'customdeploy_sl_edit_ticket_2', scriptId: 'customscript_sl_edit_ticket_2', }) var upload_url = baseURL + output; window.open(upload_url, "_self", "height=750,width=650,modal=yes,alwaysRaised=yes"); } } function closeCustIssueTicket(selector_type, status_num) { if (confirm("Are you sure you want to close this ticket?\n\nThis action cannot be undone.")) { var ticket_id = parseInt(currRec.getValue({ fieldId: 'custpage_ticket_id' })); var ticketRecord = record.load({ type: 'customrecord_mp_ticket', id: ticket_id }); var customer_id = ticketRecord.getValue({fieldId: 'custrecord_customer1'}); var login_email = $('#login_email_text').val(); var customer_number = $('#customer_number_value').val().trim(); var creator_id = ticketRecord.getValue({fieldId: 'custrecord_creator'}); var escalated_to_it = ticketRecord.getValue({ fieldId: 'custrecord_date_escalated_it' }); if (isNullorEmpty(login_email)) { console.log('No LOGIN EMAIL'); showAlert('Please enter a valid Login Email'); return false; } if (isNullorEmpty(customer_number) && creator_id == 112209 && !isNullorEmpty(escalated_to_it) && selector_type == "customer_issue" && !isNullorEmpty(ticket_id)) { console.log('CUSTOMER NUMBER MISSING'); showAlert('Please enter a Customer Number'); return false; } updateSaveRecord(); var ticketRecord = record.load({ type: 'customrecord_mp_ticket', id: ticket_id }); var date = new Date; var dnow = format.parse({ value: date, type: format.Type.DATETIMETZ }); ticketRecord.setValue({ fieldId: 'custrecord_date_closed', value: dnow }); if (isNullorEmpty(status_num)) { ticketRecord.setValue({ fieldId: 'custrecord_ticket_status', value: 15 }); sendCustomerEscalateEmail('MailPlus [MPSD' + ticket_id + '] - Your IT ticket has been resolved - Customer Portal', [login_email], 121, customer_id); } else { if (status_num == 15) { sendCustomerEscalateEmail('MailPlus [MPSD' + ticket_id + '] - Your IT ticket has been resolved - Customer Portal', [login_email], 121, customer_id); } ticketRecord.setValue({ fieldId: 'custrecord_ticket_status', value: status_num }); } ticketRecord.setValue({ fieldId: 'custrecord_mp_ticket_customer_status', value: 5 }); ticketRecord.setValue({ fieldId: 'custrecord_reminder', value: null }); // Save issues and resolved issues ticketRecord = updateIssues(ticketRecord); var customer_id = ticketRecord.getValue({fieldId: 'custrecord_customer1'}); ticketRecord.save({ enableSourcing: true, }); // Redirect to the "View MP Tickets" page var output = url.resolveScript({ deploymentId: 'customdeploy_sl_edit_ticket_2', scriptId: 'customscript_sl_edit_ticket_2', }) var upload_url = baseURL + output; window.open(upload_url, "_self", "height=750,width=650,modal=yes,alwaysRaised=yes"); } } /** * Triggered by a click on the button 'CLOSE TICKET' ('#close_ticket') * Set the date of closure, and the status as "Closed". */ function closeNewTicket() { if (confirm("Are you sure you want to close this ticket and open a new ticket?\n\nThis action cannot be undone.")) { updateSaveRecord(); var date = new Date; var dnow = format.parse({ value: date, type: format.Type.DATETIMETZ }); var ticket_id = currRec.getValue({ fieldId: 'custpage_ticket_id' }); ticket_id = parseInt(ticket_id); var ticketRecord = record.load({ type: 'customrecord_mp_ticket', id: ticket_id }); ticketRecord.setValue({ fieldId: 'custrecord_date_closed', value: dnow }); ticketRecord.setValue({ fieldId: 'custrecord_ticket_status', value: 3 }); ticketRecord.setValue({ fieldId: 'custrecord_mp_ticket_customer_status', value: 5 }); ticketRecord.setValue({ fieldId: 'custrecord_reminder', value: null }); // Save issues and resolved issues ticketRecord = updateIssues(ticketRecord); var ticket_name = ticketRecord.getText({fieldId: 'name'}); var customer_barcode_number = ticketRecord.getValue({ fieldId : 'custrecord_barcode_number'}); var customer_id = ticketRecord.getValue({fieldId: 'custrecord_customer1'}); try { var barcodeRecord = record.load({ type: 'customrecord_customer_product_stock', id: customer_barcode_number, }); var receiveremail = barcodeRecord.getValue({fieldId: 'custrecord_receiver_email'}); var barcodeName = barcodeRecord.getValue({fieldId: 'name'}); //Send Email To Customer if (!isNullorEmpty(receiveremail)) { sendCustomerEscalateEmail('MailPlus [' + ticket_name + '] - Ticket Closed - ' + barcodeName, [receiveremail], 114, customer_id); } } catch(e) { console.log("Failed to load barcode because no customer linked"); } ticketRecord.save({ enableSourcing: true, }) // Redirect to the Open New Ticket" page // var output = url.resolveScript({ // deploymentId: 'customdeploy_sl_edit_ticket_2', // scriptId: 'customscript_sl_edit_ticket_2', // }) var output = url.resolveScript({ deploymentId: 'customdeploy_sl_open_ticket_2', scriptId: 'customscript_sl_open_ticket_2', }); var upload_url = baseURL + output; window.open(upload_url, "_self", "height=750,width=650,modal=yes,alwaysRaised=yes"); } } /** * Triggered by a click on the button 'CLOSE TICKET - LOST ITEM' ('#close_ticket_lost') * Set the date of closure, and the status as "Closed - Lost Item". */ function closeTicketLost() { if (confirm("Are you sure you want to close this ticket and set it as Closed-Lost?\n\nThis action cannot be undone.")) { updateSaveRecord(); var date = new Date; var dnow = format.parse({ value: date, type: format.Type.DATETIMETZ }); var ticket_id = currRec.getValue({ fieldId: 'custpage_ticket_id' }); ticket_id = parseInt(ticket_id); var ticketRecord = record.load({ type: 'customrecord_mp_ticket', id: ticket_id }); ticketRecord.setValue({ fieldId: 'custrecord_date_closed', value: dnow }); ticketRecord.setValue({ fieldId: 'custrecord_ticket_status', value: 9 }); ticketRecord.setValue({ fieldId: 'custrecord_mp_ticket_customer_status', value: 5 }); ticketRecord.setValue({ fieldId: 'custrecord_reminder', value: null }); // Save issues and resolved issues ticketRecord = updateIssues(ticketRecord); ticketRecord.save({ enableSourcing: true, }); var ticket_name = ticketRecord.getText({fieldId: 'name'}); var customer_barcode_number = ticketRecord.getValue({ fieldId : 'custrecord_barcode_number'}); var customer_id = ticketRecord.getValue({fieldId: 'custrecord_customer1'}); var barcodeRecord = record.load({ type: 'customrecord_customer_product_stock', id: customer_barcode_number, }); var receiveremail = barcodeRecord.getValue({fieldId: 'custrecord_receiver_email'}); var barcodeName = barcodeRecord.getValue({fieldId: 'name'}); //Send Email To Customer if (!isNullorEmpty(receiveremail)) { sendCustomerEscalateEmail('MailPlus [' + ticket_name + '] - Lost In Transit - ' + barcodeName, [receiveremail], 113, customer_id); } var product_order = barcodeRecord.getValue({fieldId: 'custrecord_prod_stock_prod_order'}); var invoice = barcodeRecord.getValue({fieldId: 'custrecord_prod_stock_invoice'}); var userNoteId = barcodeRecord.getValue({fieldId: 'recordid'}); console.log("Invoice", invoice); console.log("product order", product_order); var params = { ticket_id: parseInt(ticket_id), selector_number: barcodeName, selector_type: 'barcode_number' }; params = JSON.stringify(params); var output = url.resolveScript({ deploymentId: 'customdeploy_sl_open_ticket_2', scriptId: 'customscript_sl_open_ticket_2', }); var ticket_url = baseURL + output + '&custparam_params=' + params; //CREDIT MEMO SECTION if (!isNullorEmpty(invoice) && isNullorEmpty(product_order)) { //Error- Send Email to Ankith body = "There's an error with the barcode as only the Invoice field is filled and the Product Order field is not (within the barcode record). Please see below barcode details\n\nMP Ticket: " + ticket_name + '\nBarcode: ' + barcodeName + '\nProduct Order: ' + product_order + '\nTicket URL: ' + ticket_url; email.send({ author: 112209, body: body, recipients: ['sruti.desai@mailplus.com.au', 'ankith.ravindran@mailplus.com.au'], subject: "Test Error MPEX Barcode Credit- LIT " + barcodeName, relatedRecords: {entityId: customer_id}, }); } else if (!isNullorEmpty(invoice) && !isNullorEmpty(product_order)) { //SEND EMAIL TO FIONA + POPIE --> change to raine after mat leave body = 'MP Ticket: ' + ticket_name + '\nBarcode: ' + barcodeName + '\nProduct Order: ' + product_order + '\nInvoice: ' + invoice + '\nTicket URL: ' + ticket_url; email.send({ author: 112209, body: body, recipients: ['sruti.desai@mailplus.com.au', 'fiona.harrison@mailplus.com.au', 'popie.popie@mailplus.com.au'], subject: "MPEX Barcode Credit- LIT " + barcodeName, relatedRecords: {entityId: customer_id} }) } else { //SEND EMAIL TO FIONA console.log("in here"); body = 'MP Ticket: ' + ticket_name + '\nBarcode: ' + barcodeName + '\nProduct Order: ' + product_order + '\nTicket URL: ' + ticket_url; email.send({ author: 112209, body: body, recipients: ['sruti.desai@mailplus.com.au', 'fiona.harrison@mailplus.com.au'], subject: "MPEX Barcode Credit- LIT " + barcodeName, relatedRecords: {entityId: customer_id} }) } // Create User Note under Barcode Record var userNote = record.create({ type: record.Type.NOTE, isDynamic: true, }); // Record Type i.e Cust Product Stock userNote.setValue({fieldId: 'recordtype', value: 1014}); // Record ID userNote.setValue({fieldId: 'record', value: parseInt(userNoteId) }); //Title userNote.setValue({fieldId: 'title', value: 'Barcode Status- LIT'}); //Memo userNote.setValue({fieldId: 'note', value: 'Barcode ' + barcodeName + ' has been set to status Lost in Transit'}); userNote.save({ enableSourcing: true, ignoreMandatoryFields: true }); // Redirect to the "View MP Tickets" page var output = url.resolveScript({ deploymentId: 'customdeploy_sl_edit_ticket_2', scriptId: 'customscript_sl_edit_ticket_2', }) var upload_url = baseURL + output; window.open(upload_url, "_self", "height=750,width=650,modal=yes,alwaysRaised=yes"); } } /** * Triggered by a click on the button 'CLOSE UNALLOCATED TICKET' ('#close_unallocated_ticket') * Set the date of closure, and the status as "Closed - Unallocated". */ function closeUnallocatedTicket() { if (confirm("Are you sure you want to close this ticket?\n\nThis action cannot be undone.")) { updateSaveRecord(); var date = new Date; var dnow = format.parse({ value: date, type: format.Type.DATETIMETZ }); var ticket_id = currRec.getValue({ fieldId: 'custpage_ticket_id' }); ticket_id = parseInt(ticket_id); var ticketRecord = record.load({ type: 'customrecord_mp_ticket', id: ticket_id }); ticketRecord.setValue({ fieldId: 'custrecord_date_closed', value: dnow }); ticketRecord.setValue({ fieldId: 'custrecord_ticket_status', value: 8 }); ticketRecord.setValue({ fieldId: 'custrecord_mp_ticket_customer_status', value: 5 }); ticketRecord.setValue({ fieldId: 'custrecord_reminder', value: null }); // Save issues and resolved issues ticketRecord = updateIssues(ticketRecord); ticketRecord.save({ enableSourcing: true, }); // Redirect to the "View MP Tickets" page var output = url.resolveScript({ deploymentId: 'customdeploy_sl_edit_ticket_2', scriptId: 'customscript_sl_edit_ticket_2', }) var upload_url = baseURL + output; window.open(upload_url, "_self", "height=750,width=650,modal=yes,alwaysRaised=yes"); } } /** * Set the status of the ticket based on the MP ticket Values. * @param {nlobjRecord} ticketRecord * @returns {nlobjRecord} ticketRecord */ function setTicketStatus(ticketRecord) { var current_status = ticketRecord.getValue({ fieldId: 'custrecord_ticket_status' }); var list_mp_ticket_issues = new Array; $('#mp_issues option:selected').each(function() { list_mp_ticket_issues.push($(this).val()); }); ticketRecord.setValue({ fieldId: 'custrecord_mp_ticket_customer_status', value: 1 }); if (currRec.getValue({ fieldId: 'custpage_selector_issue'}) == 'T') { //Set status to escalated //console.log("Changing status to escalated"); //ticketRecord.setValue({ fieldId: 'custrecord_ticket_status', value: 10 }); } else if (isNullorEmpty(current_status)) { ticketRecord.setValue({ fieldId: 'custrecord_ticket_status', value: 1 }); } else if (list_mp_ticket_issues.length != 0) { var it_issue = false; var other_issue = '0'; list_mp_ticket_issues.forEach(function(mp_ticket_issue_value) { if (mp_ticket_issue_value < 5) { it_issue = true; } else { other_issue = mp_ticket_issue_value; } }); if (it_issue) { ticketRecord.setValue({ fieldId: 'custrecord_ticket_status', value: 4 }); } else if (other_issue != '0') { switch (other_issue) { case '5': // Operational Issue ticketRecord.setValue({ fieldId: 'custrecord_ticket_status', value: 5 }); break; case '6': // Finance Issue ticketRecord.setValue({ fieldId: 'custrecord_ticket_status', value: 6 }); break; case '7': // Customer Service Issue ticketRecord.setValue({ fieldId: 'custrecord_ticket_status', value: 2 }); break; } } } else { // If there are no more MP Ticket issues, if (current_status >= 4) { var email_sent = ticketRecord.getValue({ fieldId: 'custrecord_email_sent' }); console.log(email_sent); if (email_sent) { //If an email has ever been sent to the customer, the status is updated to 'In progress - Customer service' ticketRecord.setValue({ fieldId: 'custrecord_ticket_status', value: 2 }); } else { // If no email has ever been sent to the customer, the status is updated to 'Open' ticketRecord.setValue({ fieldId: 'custrecord_ticket_status', value: 1 }); } } } return ticketRecord; } /** * Set the creator of the ticket if there is none. * @param {nlobjRecord} ticketRecord * @returns {nlobjRecord} ticketRecord */ function setCreator(ticketRecord) { var creator_id = ticketRecord.getValue({ fieldId: 'custrecord_creator' }); if (isNullorEmpty(creator_id)) { var user_id = parseInt(runtime.getCurrentUser().id); ticketRecord.setValue({ fieldId: 'custrecord_creator', value: user_id }); } return ticketRecord; } /** * If we work with a barcode ticket, the TOLL Issues and MP Ticket Issues are added to the record. * If we work with an invoice ticket, the Invoice Issues are added to the record. * If issues have been deleted from any of these fields, they are saved in the resolved fields. * @param {nlobjRecord} ticketRecord * @returns {nlobjRecord} ticketRecord */ function updateIssues(ticketRecord) { var ticket_id = currRec.getValue({ fieldId: 'custpage_ticket_id' }); var selector_type = currRec.getValue({ fieldId: 'custpage_selector_type' }); switch (selector_type) { case 'barcode_number': // Save TOLL Issues var list_toll_issues = new Array; $('#toll_issues option:selected').each(function() { list_toll_issues.push($(this).val()); }); // Save resolved TOLL Issues if (!isNullorEmpty(ticket_id)) { var old_list_toll_issues = ticketRecord.getValue({ fieldId: 'custrecord_toll_issues' }); if (!isNullorEmpty(old_list_toll_issues)) { if (typeof(old_list_toll_issues) == "string") { old_list_toll_issues = [old_list_toll_issues]; } var list_resolved_toll_issues = ticketRecord.getValue({fieldId: 'custrecord_resolved_toll_issues' }); if (isNullorEmpty(list_resolved_toll_issues)) { list_resolved_toll_issues = new Array; } else if (typeof(list_resolved_toll_issues) == "string") { list_resolved_toll_issues = [list_resolved_toll_issues]; } old_list_toll_issues.forEach(function(old_toll_issue) { // If a TOLL issue of the old list is not in the new list, // it means that the issue was resolved. if (list_toll_issues.indexOf(old_toll_issue) == -1) { list_resolved_toll_issues.push(old_toll_issue); } }); ticketRecord.setValue({ fieldId: 'custrecord_resolved_toll_issues', value: list_resolved_toll_issues }); } } console.log("list_toll_issues", list_toll_issues); ticketRecord.setValue({ fieldId: 'custrecord_toll_issues', value: list_toll_issues }); break; case 'invoice_number': // Save Invoice Issues var list_invoice_issues = new Array; $('#invoice_issues option:selected').each(function() { list_invoice_issues.push($(this).val()); }); // Save resolved INVOICE Issues if (!isNullorEmpty(ticket_id)) { var old_list_invoice_issues = ticketRecord.getValue({ fieldId: 'custrecord_invoice_issues' }); if (!isNullorEmpty(old_list_invoice_issues)) { if (typeof(old_list_invoice_issues) == "string") { old_list_invoice_issues = [old_list_invoice_issues]; } var list_resolved_invoice_issues = ticketRecord.getValue({ fieldId: 'custrecord_resolved_invoice_issues' }); if (isNullorEmpty(list_resolved_invoice_issues)) { list_resolved_invoice_issues = new Array; } else if (typeof(list_resolved_invoice_issues) == "string") { list_resolved_invoice_issues = [list_resolved_invoice_issues]; } old_list_invoice_issues.forEach(function(old_invoice_issue) { // If an invoice issue of the old list is not in the new list, // it means that the issue was resolved. if (list_invoice_issues.indexOf(old_invoice_issue) == -1) { list_resolved_invoice_issues.push(old_invoice_issue); } }); ticketRecord.setValue({ fieldId: 'custrecord_resolved_invoice_issues', value: list_resolved_invoice_issues }); } } ticketRecord.setValue({ fieldId: 'custrecord_invoice_issues', value: list_invoice_issues }); break; } // Save MP Ticket Issues var list_mp_ticket_issues = new Array; $('#mp_issues option:selected').each(function() { list_mp_ticket_issues.push($(this).val()); }); // Save resolved MP Ticket Issues if (!isNullorEmpty(ticket_id) && selector_type != "customer_issue") { var old_list_mp_ticket_issues = ticketRecord.getValue({ fieldId: 'custrecord_mp_ticket_issue' }); if (!isNullorEmpty(old_list_mp_ticket_issues)) { old_list_mp_ticket_issues = Array.from(old_list_mp_ticket_issues); var list_resolved_mp_ticket_issues = ticketRecord.getValue({ fieldId: 'custrecord_resolved_mp_ticket_issue' }); if (isNullorEmpty(list_resolved_mp_ticket_issues)) { list_resolved_mp_ticket_issues = new Array; } else { list_resolved_mp_ticket_issues = Array.from(list_resolved_mp_ticket_issues); } old_list_mp_ticket_issues.forEach(function(old_mp_ticket_issue) { // If a MP Ticket issue of the old list is not in the new list, // it means that the issue was resolved. if (list_mp_ticket_issues.indexOf(old_mp_ticket_issue) == -1) { list_resolved_mp_ticket_issues.push(old_mp_ticket_issue); } }); ticketRecord.setValue({ fieldId: 'custrecord_resolved_mp_ticket_issue', value: list_resolved_mp_ticket_issues }); } } ticketRecord.setValue({ fieldId: 'custrecord_mp_ticket_issue', value: list_mp_ticket_issues }); return ticketRecord; } /** * Triggered by a click on the button 'REOPEN TICKET' ('#reopen_ticket') * Set the ticket record as active. * Deletes the date of closure, * Set the status as "Open". */ function reopenTicket() { console.log("in reopen"); console.log("customer number"); var ticket_id = currRec.getValue({ fieldId: 'custpage_ticket_id' }); ticket_id = parseInt(ticket_id); var selector_number = currRec.getValue({ fieldId: 'custpage_selector_number' }); var selector_type = currRec.getValue({ fieldId: 'custpage_selector_type' }); var customer_number = currRec.getValue({ fieldId: 'custpage_customer_number' }); var ticketRecord = record.load({ type: 'customrecord_mp_ticket', id: ticket_id }); ticketRecord.setValue({ fieldId: 'custrecord_date_closed', value: null }); ticketRecord.setValue({ fieldId: 'custrecord_ticket_status', value: 1 }); ticketRecord.setValue({ fieldId: 'custrecord_mp_ticket_customer_status', value: 1 }); // Save Reminder date setReminderDate(); var reminder_date = $('#reminder').val(); console.log("rem3", reminder_date); if (!isNullorEmpty(reminder_date)) { reminder_date = new Date(reminder_date); reminder_date = format.parse({ value: reminder_date, type: format.Type.DATE}); ticketRecord.setValue({ fieldId: 'custrecord_reminder', value: reminder_date }); } // Set new Creator and new Owner ticketRecord.setValue({ fieldId: 'custrecord_creator', value: userId }); ticketRecord.setValue({ fieldId: 'custrecord_owner', value: [userId] }); ticketRecord.save({ enableSourcing: true, }); // Reload the page var params = { ticket_id: parseInt(ticket_id), selector_number: selector_number, selector_type: selector_type, customer_number: customer_number, }; params = JSON.stringify(params); var output = url.resolveScript({ deploymentId: 'customdeploy_sl_open_ticket_2', scriptId: 'customscript_sl_open_ticket_2', }); var upload_url = baseURL + output + '&custparam_params=' + params; window.open(upload_url, "_self", "height=750,width=650,modal=yes,alwaysRaised=yes"); console.log("in reopen"); } /** * Lookup for the Credit Memo associated to an invoice. * @returns {nlobjSearchResult[]} creditMemoResults */ function searchCreditMemo() { var selector_type = currRec.getValue({ fieldId: 'custpage_selector_type' }); if (selector_type == 'invoice_number') { var selector_id = currRec.getValue({ fieldId: 'custpage_selector_id' }); var creditMemoResults = search.create({ type: 'creditmemo', filter: [ search.createFilter({ name: 'mainline', operator: 'is', values: 'T', }), search.createFilter({ name: 'createdfrom', operator: 'is', values: selector_id, }) ], columns: [ search.createColumn({ name: 'tranid', summary: 'group' }), search.createColumn({ name: 'trandate', summary: 'group' }), search.createColumn({ name: 'entity', summary: 'group' }), search.createColumn({ name: 'createdfrom', summary: 'group' }), search.createColumn({ name: 'internalid', summary: 'group' }) ] }); return creditMemoResults.run(); } else { return null; } } /** * searchCreditMemo() searches for Credit Memos linked to the current invoice. * If there are results, they are displayed in the table '#credit_memo'. * Otherwise, the section containing the table is hidden. * @param {Number} status_value */ function createCreditMemoRows(status_value) { var inline_credit_memo_table_html = ''; var compid = (runtime.envType == "SANDBOX") ? '1048144_SB3' : '1048144'; console.log("sv", status_value); var creditMemoResults = searchCreditMemo(); if (!isNullorEmpty(creditMemoResults)) { $('.credit_memo').removeClass('hide'); creditMemoResults.each(function(creditMemoResult) { console.log("CMR", creditMemoResult); var credit_memo_number = creditMemoResult.getValue({ name:'tranid', join: null, summary: 'group' }); var credit_memo_date = creditMemoResult.getValue({ name:'trandate', join: null, summary: 'group' }); var credit_memo_customer_name = creditMemoResult.getText({ name: 'entity', join: null, summary: 'group' }); var credit_memo_customer_id = creditMemoResult.getValue({ name:'entity', join: null, summary: 'group' }); var credit_memo_customer_link = baseURL + '/app/common/entity/custjob.nl?id=' + credit_memo_customer_id; var credit_memo_created_from_id = creditMemoResult.getValue({ name:'createdfrom', join: null, summary: 'group' }); var credit_memo_created_from = creditMemoResult.getText({ name: 'createdfrom', join: null, summary: 'group' }); var invoice_link = baseURL + '/app/accounting/transactions/custinvc.nl?id=' + credit_memo_created_from_id + '&compid=' + compid + '&cf=116&whence='; var credit_memo_id = creditMemoResult.getText({ name: 'internalid', join: null, summary: 'group' }); var credit_memo_link = baseURL + '/app/accounting/transactions/custcred.nl?id=' + credit_memo_id + '&whence='; var credit_memo_url = baseURL + '/app/accounting/print/hotprint.nl?regular=T&sethotprinter=T&formnumber=106&trantype=custcred&id=' + credit_memo_id + '&label=Credit+Memo&printtype=transaction'; var credit_memo_action_button = '<button class="btn btn-success add_cm glyphicon glyphicon-plus" type="button" data-toggle="tooltip" data-placement="right" data-cm-id="' + credit_memo_id + '" data-cm-url="' + credit_memo_url + '" title="Attach to email"></button>'; inline_credit_memo_table_html += '<tr class="text-center">'; inline_credit_memo_table_html += '<td headers="credit_memo_number"><a href="' + credit_memo_link + '">' + credit_memo_number + '</a></td>'; inline_credit_memo_table_html += '<td headers="credit_memo_date">' + credit_memo_date + '</td>'; inline_credit_memo_table_html += '<td headers="credit_memo_customer"><a href="' + credit_memo_customer_link + '">' + credit_memo_customer_name + '</td>'; inline_credit_memo_table_html += '<td headers="credit_memo_invoice_number"><a href="' + invoice_link + '">' + credit_memo_created_from + '</td>'; if (isTicketNotClosed(status_value)) { inline_credit_memo_table_html += '<td headers="credit_memo_action">' + credit_memo_action_button + '</td>'; } inline_credit_memo_table_html += '</tr>'; }); } else { $('.credit_memo').addClass('hide'); } $('#credit_memo tbody').html(inline_credit_memo_table_html); // Each time the table is redrawn, we trigger tooltip for the new cells. $('[data-toggle="tooltip"]').tooltip(); } /** * In the suitelet script, if the ticket record concerns an invoice, * the associated usage reports id are saved. * The files are loaded and their filenames and url are saved into the array of objects 'usage_report_array'. * This array is parsed and if the ids are not null, a row is added to the '#usage_report' table. * Otherwise, the section containing the table is hidden. * @param {Number} status_value */ function createUsageReportRows(status_value) { var inline_usage_report_table_html = ''; var usage_report_array = currRec.getValue({ fieldId: 'custpage_usage_report_array' }); usage_report_array = JSON.parse(usage_report_array); console.log('usage_report_array : ', usage_report_array); if (!isNullorEmpty(usage_report_array)) { usage_report_array.forEach(function(usage_report_obj) { var usage_report_id = usage_report_obj.id; if (!isNullorEmpty(usage_report_id)) { var usage_report_filename = usage_report_obj.name; var usage_report_link = usage_report_obj.url; var usage_report_action_button = '<button class="btn btn-success add_ur glyphicon glyphicon-plus" type="button" data-toggle="tooltip" data-placement="right" data-ur-id="' + usage_report_id + '" title="Attach to email"></button>'; inline_usage_report_table_html += '<tr class="text-center">'; inline_usage_report_table_html += '<td headers="usage_report_filename"><a href="' + usage_report_link + '">' + usage_report_filename + '</a></td>'; if (isTicketNotClosed(status_value)) { inline_usage_report_table_html += '<td headers="usage_report_action">' + usage_report_action_button + '</td>'; } inline_usage_report_table_html += '</tr>'; } }); } else { $('.usage_report').addClass('hide'); } $('#usage_report tbody').html(inline_usage_report_table_html); // Each time the table is redrawn, we trigger tooltip for the new cells. $('[data-toggle="tooltip"]').tooltip(); } /** * Depending on the number of buttons at the end of the page, their width and offset should change. * If there are 2 buttons, they have a width of 4 cols and an offset of 2 cols. * If there are 3 buttons, they have a width of 4 cols. * If there are 4 buttons, they have a width of 3 cols. */ function updateButtonsWidth() { var nb_buttons = $('.close_reopen_submit_ticket_section .row div:not(.hide)').length; $('.close_reopen_submit_ticket_section .row div').removeClass('col-xs-offset-2'); switch (nb_buttons) { case 2: $('.close_reopen_submit_ticket_section .row div').addClass('col-xs-4'); $('.close_reopen_submit_ticket_section .row div').removeClass('col-xs-3'); $('.close_reopen_submit_ticket_section .row div:not(.hide)').eq(0).addClass('col-xs-offset-2'); break; case 3: $('.close_reopen_submit_ticket_section .row div').addClass('col-xs-4'); $('.close_reopen_submit_ticket_section .row div').removeClass('col-xs-3'); break; case 4: $('.close_reopen_submit_ticket_section .row div').removeClass('col-xs-4'); $('.close_reopen_submit_ticket_section .row div').addClass('col-xs-3'); break; } } /** * Converts the selector field into either "Invoice number"/"Barcode number"/ "Customer App" * @param {String} selector_name */ function setupSelectorInput(selector_name) { $('#selector_text').text(selector_name); switch (selector_name) { case 'INVOICE NUMBER': $('#selector_value').attr('placeholder', 'INV123456'); $('#selector_value').removeAttr('value'); $('#selector_value').removeAttr('disabled'); break; case 'BARCODE NUMBER': $('#selector_value').attr('placeholder', 'MPEN123456'); $('#selector_value').removeAttr('value'); $('#selector_value').removeAttr('disabled'); break; case 'CUSTOMER APP': $('#selector_text').text("CUSTOMER ISSUE"); $('#selector_value').attr('value', 'Customer App'); $('#selector_value').attr('disabled', 'disabled'); break; case 'CUSTOMER PORTAL': $('#selector_text').text("CUSTOMER ISSUE"); $('#selector_value').attr('value', 'Customer Portal'); $('#selector_value').attr('disabled', 'disabled'); break; case 'UPDATE LABEL': $('#selector_text').text("CUSTOMER ISSUE"); $('#selector_value').attr('value', 'Update Label'); $('#selector_value').attr('disabled', 'disabled'); break; // case 'UPDATE CUSTOMER DETAILS': // $('#selector_text').text("CUSTOMER ISSUE"); // $('#selector_value').attr('value', 'Update Customer Details'); // $('#selector_value').attr('disabled', 'disabled'); // break; } } /** * Format a date object to the string 'dd/mm/yyyy hh:mm [am/pm]' * @param {Date} date * @returns {String} date_string */ function formatDate(testDate){ console.log('testDate: '+testDate); var responseDate=format.format({value:testDate,type:format.Type.DATE}); console.log('responseDate: '+responseDate); return responseDate; } /** * Converts the date string in the "invoice_date" table to the format of "date_selected". * @param {String} invoice_date ex: '4/6/2020' * @returns {String} date ex: '2020-06-04' */ function dateCreated2DateSelectedFormat(invoice_date) { // date_created = '4/6/2020' var date_array = invoice_date.split('/'); // date_array = ["4", "6", "2020"] var year = date_array[2]; var month = date_array[1]; if (month < 10) { month = '0' + month; } var day = date_array[0]; if (day < 10) { day = '0' + day; } return year + '-' + month + '-' + day; } /** * Calculates the reminder date based on the current date and the selector_type. */ function setReminderDate() { var ticket_id = currRec.getValue({ fieldId: 'custpage_ticket_id' }); var status_value = currRec.getValue({ fieldId: 'custpage_ticket_status_value' }); if (isNullorEmpty(ticket_id) || !isTicketNotClosed(status_value)) { var selector_type = currRec.getValue({ fieldId: 'custpage_selector_type' }); var today = new Date(); var today_day_in_month = today.getDate(); var today_day_in_week = today.getDay(); var today_month = today.getMonth(); var today_year = today.getFullYear(); switch (selector_type) { case 'barcode_number': var addNbDays = 1; if (today_day_in_week == 5) { addNbDays += 2; } break; case 'invoice_number': var addNbDays = 3; if (today_day_in_week == 3 || today_day_in_week == 4 || today_day_in_week == 5) { addNbDays += 2; } break; } var reminder_date = new Date(Date.UTC(today_year, today_month, today_day_in_month + addNbDays)); reminder_date = reminder_date.toISOString().split('T')[0]; } else { ticket_id = parseInt(ticket_id); var ticketRecord = record.load({ type: 'customrecord_mp_ticket', id: ticket_id }); var ticket_reminder_date = ticketRecord.getValue({ fieldId: 'custrecord_reminder' }); var reminder_date = ''; if (!isNullorEmpty(ticket_reminder_date)) { ticket_reminder_date = format.parse({ value: ticket_reminder_date, type: format.Type.DATE }); var reminder_date_day_in_month = ticket_reminder_date.getDate(); var reminder_date_month = ticket_reminder_date.getMonth(); var reminder_date_year = ticket_reminder_date.getFullYear(); reminder_date = new Date(Date.UTC(reminder_date_year, reminder_date_month, reminder_date_day_in_month)); reminder_date = reminder_date.toISOString().split('T')[0]; } } $('#reminder').val(reminder_date); } /** * Creates the inline HTML of the Credit Memo table, * with a button for the attachments if the ticket is not closed. * @param {Number} status_value * @returns {String} inline_html_credit_memo_table */ function htmlCreditMemoTable(status_value) { var inline_html_credit_memo_table = '<table cellpadding="15" id="credit_memo" class="table table-responsive table-striped contacts tablesorter" cellspacing="0" style="width: 100%;border: 0">'; inline_html_credit_memo_table += '<thead style="color: white;background-color: #379E8F;">'; inline_html_credit_memo_table += '<tr>'; inline_html_credit_memo_table += '<th style="vertical-align: middle;text-align: center;" id="credit_memo_number">'; inline_html_credit_memo_table += '<b>CREDIT #</b>'; inline_html_credit_memo_table += '</th>'; inline_html_credit_memo_table += '<th style="vertical-align: middle;text-align: center;" id="credit_memo_date">'; inline_html_credit_memo_table += '<b>DATE</b>'; inline_html_credit_memo_table += '</th>'; inline_html_credit_memo_table += '<th style="vertical-align: middle;text-align: center;" id="credit_memo_customer">'; inline_html_credit_memo_table += '<b>CUSTOMER</b>'; inline_html_credit_memo_table += '</th>'; inline_html_credit_memo_table += '<th style="vertical-align: middle;text-align: center;" id="credit_memo_invoice_number">'; inline_html_credit_memo_table += '<b>CREATED FROM</b>'; inline_html_credit_memo_table += '</th>'; if (isTicketNotClosed(status_value)) { inline_html_credit_memo_table += '<th style="vertical-align: middle;text-align: center;" id="credit_memo_action">'; inline_html_credit_memo_table += '<b>ATTACH TO EMAIL</b>'; inline_html_credit_memo_table += '</th>'; } inline_html_credit_memo_table += '</tr>'; inline_html_credit_memo_table += '</thead>'; inline_html_credit_memo_table += '<tbody></tbody>'; inline_html_credit_memo_table += '</table>'; return inline_html_credit_memo_table; } function htmlUsageReportTable(status_value) { var inline_html_usage_report_table = '<table cellpadding="15" id="usage_report" class="table table-responsive table-striped contacts tablesorter" cellspacing="0" style="width: 100%;border: 0"><thead style="color: white;background-color: #379E8F;">'; inline_html_usage_report_table += '<tr>'; inline_html_usage_report_table += '<th style="vertical-align: middle;text-align: center;" id="usage_report_filename">'; inline_html_usage_report_table += '<b>FILE NAME</b>'; inline_html_usage_report_table += '</th>'; if (isTicketNotClosed(status_value)) { inline_html_usage_report_table += '<th style="vertical-align: middle;text-align: center;" id="usage_report_action">'; inline_html_usage_report_table += '<b>ATTACH TO EMAIL</b>'; inline_html_usage_report_table += '</th>'; } inline_html_usage_report_table += '</tr>'; inline_html_usage_report_table += '</thead>'; inline_html_usage_report_table += '<tbody></tbody>'; inline_html_usage_report_table += '</table>'; return inline_html_usage_report_table; } /** * This function is triggered when a button is clicked to attach a file. * It stores the file id in the right array of the object 'params_email'. */ function attachFileButton() { $(this).toggleClass('btn-success'); $(this).toggleClass('btn-danger'); if ($(this).attr('id') == 'add_inv') { $(this).find('span.glyphicon').toggleClass('glyphicon-minus'); $(this).find('span.glyphicon').toggleClass('glyphicon-plus'); } else { $(this).toggleClass('glyphicon-minus'); $(this).toggleClass('glyphicon-plus'); } // Tooltip seems to set the 'title' attribute to 'data-original-title'. // The only way to have tooltip take into account the change of title is to modifiy the attribute 'data-original-title'. // Using the jQuery method 'data()' doesn't work. if ($(this).attr('data-original-title') == 'Attach to email') { $(this).attr('data-original-title', 'Remove from email'); } else { $(this).attr('data-original-title', 'Attach to email'); } $('[data-toggle="tooltip"]').tooltip(); var attachment_id = ''; var attachment_ids_array_name = ''; if ($(this).hasClass('add_ur')) { attachment_id = $(this).data('ur-id'); attachment_ids_array_name = 'attachments_usage_report_ids'; } else if ($(this).hasClass('add_cm')) { attachment_id = $(this).data('cm-id'); attachment_ids_array_name = 'attachments_credit_memo_ids'; } else if ($(this).hasClass('add_inv')) { attachment_id = $(this).data('inv-id'); attachment_ids_array_name = 'attachments_invoice_ids'; } addIdToAttachmentList(attachment_ids_array_name, attachment_id); } /** * Adds or remove the id of a record to be attached (or removed) to the email that will be sent in the function sendEmail(); * @param {String} attachment_ids_array_name * @param {Number} id */ function addIdToAttachmentList(attachment_ids_array_name, id) { var params_email = currRec.getValue({ fieldId: 'custpage_param_email' }); params_email = JSON.parse(params_email); var attachment_ids_array = params_email[attachment_ids_array_name]; var index_of_id_elem = attachment_ids_array.indexOf(id); if (index_of_id_elem == -1) { attachment_ids_array.push(id); } else { attachment_ids_array.splice(index_of_id_elem, 1); } params_email[attachment_ids_array_name] = attachment_ids_array; params_email = JSON.stringify(params_email); currRec.setValue({ fieldId: 'custpage_param_email', value: params_email }); } /** * @param {Number} x * @returns {String} The same number, formatted in Australian dollars. */ function financial(x) { if (typeof(x) === 'string') { x = parseFloat(x); } if (isNullorEmpty(x)) { return "$0.00"; } else { return x.toLocaleString('en-AU', { style: 'currency', currency: 'AUD' }); } } /** * Returns whether a ticket is closed or not based on its status value. * @param {Number} status_value * @returns {Boolean} is_ticket_closed */ function isTicketNotClosed(status_value) { var is_ticket_not_closed = ((status_value != 3) && (status_value != 8)) ? true : false; return is_ticket_not_closed; } /** * Whether the user is from the finance team, * or a Data Systems Co-ordinator, MailPlus Administration or Administrator user. * @param {Number} userRole * @returns {Boolean} */ function isFinanceRole(userRole) { // 1001, 1031 and 1023 are finance roles // 1032 is the Data Systems Co-ordinator role (to be deleted in prod) // 1006 is the Mail Plus Administration role. // 3 is the Administrator role. return ((userRole == 1001 || userRole == 1031 || userRole == 1023) || ((userRole == 1032) || (userRole == 1006) || (userRole == 3))); } /** * Whether the user is from the finance team. * @param {Number} userRole * @returns {Boolean} */ function isFinanceRoleOnly(userRole) { // 1001, 1031 and 1023 are finance roles return (userRole == 1001 || userRole == 1031 || userRole == 1023); } function validateEmail(email) { var re = /^(([^<>()[\]\\.,;:\s@"]+(\.[^<>()[\]\\.,;:\s@"]+)*)|(".+"))@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/; return re.test(String(email).toLowerCase()); } function getBase64(file) { return new Promise(function(resolve) { var reader = new FileReader(); reader.onloadend = function() { resolve(reader.result) } reader.readAsDataURL(file); }); } /** * Function to get the next email reminder time. * Adds +2 hours to the current date. */ function getNextReminderTime() { var today = new Date(); //Adding 19 hours to PST will give Australia/ Sydney timezone today.setHours(today.getHours() + 19); var currentHours = today.getHours(); log.debug({ title: 'currentHours + 2', details: currentHours + 2 }); if (currentHours + 2 > 16) { //Current hours + 2 hours is past 5. next reminder will be sent the next day at 9 am today.setDate(today.getDate() + 1); today.setHours(9); today.setMinutes(0); today.setSeconds(0); } else if (currentHours + 2 < 9) { //Current hours + 2 hours is before 9 am. Edge case but this is unlikely to happen since script does not run outside 9-5 today.setHours(9); today.setMinutes(0); today.setSeconds(0); } else { // Set next reminder time to today + 2 hours today.setHours(today.getHours() + 2); } return today; } function stringToDate(val) { return format.parse({value:val, type: format.Type.DATE}) } function isNullorEmpty(strVal) { return (strVal == null || strVal == '' || strVal == 'null' || strVal == undefined || strVal == 'undefined' || strVal == '- None -'); } return { pageInit: pageInit, saveRecord: saveRecord, closeTicket: closeTicket, closeTicketLost: closeTicketLost, closeUnallocatedTicket: closeUnallocatedTicket, onEscalate: onEscalate, onCancel: onCancel }; } );
107
[{"tag": "EMAIL", "value": "rianne.mansell@mailplus.com.au", "start": 33659, "end": 33689}, {"tag": "EMAIL", "value": "ankith.ravindran@mailplus.com.au", "start": 36491, "end": 36523}, {"tag": "EMAIL", "value": "sruti.desai@mailplus.com.au", "start": 43711, "end": 43738}, {"tag": "EMAIL", "value": "sruti.desai@mailplus.com.au", "start": 44131, "end": 44158}, {"tag": "EMAIL", "value": "sruti.desai@mailplus.com.au", "start": 44552, "end": 44579}, {"tag": "EMAIL", "value": "ankith.ravindran@mailplus.com.au", "start": 175074, "end": 175106}, {"tag": "EMAIL", "value": "sruti.desai@mailplus.com.au", "start": 232525, "end": 232552}, {"tag": "EMAIL", "value": "ankith.ravindran@mailplus.com.au", "start": 232556, "end": 232588}, {"tag": "EMAIL", "value": "sruti.desai@mailplus.com.au", "start": 233263, "end": 233290}, {"tag": "EMAIL", "value": "fiona.harrison@mailplus.com.au", "start": 233294, "end": 233324}, {"tag": "EMAIL", "value": "popie.popie@mailplus.com.au", "start": 233328, "end": 233355}, {"tag": "EMAIL", "value": "sruti.desai@mailplus.com.au", "start": 233922, "end": 233949}, {"tag": "EMAIL", "value": "fiona.harrison@mailplus.com.au", "start": 233953, "end": 233983}]
true
13
/** * * @NApiVersion 2.0 * @NScriptType ClientScript * * Description: A ticketing system for the Customer Service. * @Last Modified by: Sruti Desai * */ define(['N/error', 'N/runtime', 'N/search', 'N/url', 'N/record', 'N/format', 'N/email', 'N/currentRecord', 'N/https'], function(error, runtime, search, url, record, format, email, currentRecord, https) { var baseURL = 'https://1048144.app.netsuite.com'; if (runtime.envType == "SANDBOX") { baseURL = 'https://1048144-sb3.app.netsuite.com'; } var role = runtime.getCurrentUser().role; var userRole = runtime.getCurrentUser().role; var userId = runtime.getCurrentUser().id; /** * On page initialisation */ var currRec = currentRecord.get(); function pageInit() { var currRec = currentRecord.get(); //Remove Chrome's incessant "Leave Site" warning window.onbeforeunload = null; //background-colors $("#NS_MENU_ID0-item0").css("background-color", "#CFE0CE"); $("#NS_MENU_ID0-item0 a").css("background-color", "#CFE0CE"); $("#body").css("background-color", "#CFE0CE"); $("#tr_submitter").css("margin-left", "10px"); var ticketsDataSet = []; var invoicesDataSet = []; $(document).ready(function() { console.log('doc ready'); $('#email_body').summernote(); $('#owner, #toll_issues, #mp_issues, #invoice_issues, #enquiry_medium_status, #send_toll').selectpicker(); $('#tickets-preview').DataTable({ data: ticketsDataSet, columns: [{ title: "ID" }, { title: "Date created" }, { title: "Date closed" }, { title: "Barcode Number" }, { title: "Status" }, { title: "TOLL Issues" }, { title: "Resolved TOLL Issues" }, { title: "Comment" }] }); $('#emails-preview').DataTable(); var invoice_table = $('#invoices-preview').DataTable({ data: invoicesDataSet, columns: [{ title: "Invoice Date", type: "date" }, { title: "Invoice #" }, { title: "Status" }, { title: "Invoice Type" }, { title: "Amount Due", type: "num-fmt" }, { title: "Total Amount", type: "num-fmt" }, { title: "Overdue" }, { title: "Invoice ID" }, { title: "Action" }], columnDefs: [{ visible: false, targets: -2, }, { targets: -1, data: null, render: function(data, type, row, meta) { var selector_id = currRec.getValue({ fieldId: 'custpage_selector_id' }); var disabled = (data[7] == selector_id) ? 'disabled' : ''; return '<button class="btn btn-success add_inv glyphicon glyphicon-plus" type="button" data-inv-id="' + data[7] + '" data-toggle="tooltip" data-placement="right" title="Attach to email" ' + disabled + '></button>'; } }] }); $('#invoices-preview thead tr').addClass('text-center'); // Adapted from https://datatables.net/extensions/fixedheader/examples/options/columnFiltering.html // Adds a row to the table head row, and adds search filters to each column. $('#invoices-preview thead tr').clone(true).appendTo('#invoices-preview thead'); $('#invoices-preview thead tr:eq(3) th').each(function(i) { var title = $(this).text(); $(this).html('<input style="width: 80%" type="text" placeholder="Search ' + title + '" />'); $('input', this).on('keyup change', function() { if (invoice_table.column(i).search() !== this.value) { invoice_table .column(i) .search(this.value) .draw(); } }); }); //var invoice_table = $('#invoices-preview').DataTable(); invoice_table.on('click', 'button.add_inv', function() { attachFileButton.call(this) }); }); console.log('Page init'); if (window.location.search.substr(1) == "script=1243&deploy=1" || window.location.search.substr(1) == "script=976&deploy=1&compid=1048144_SB3" || window.location.search.substr(1) == "script=1243&deploy=1&compid=1048144_SB3&whence=") { currRec.setValue({ fieldId: 'custpage_selector_number', value: '' }); currRec.setValue({ fieldId: 'custpage_selector_type', value: "barcode_number"}); } var selector_number = currRec.getValue({ fieldId: 'custpage_selector_number' }); var selector_type = currRec.getValue({ fieldId: 'custpage_selector_type' }); var ticket_id = currRec.getValue({ fieldId: 'custpage_ticket_id' }); var status_value = currRec.getValue({ fieldId: 'custpage_ticket_status_value' }); var customer_number = currRec.getValue({ fieldId: 'custpage_customer_number' }); //Toggling show/hide for the tickets associated to customer number if (!isNullorEmpty(customer_number) && isNullorEmpty(selector_number)) { $('#customer_number_tickets_preview').show(); } else { $('#customer_number_tickets_preview').hide(); } // The inline html of the <table> tag is not correctly displayed inside div.col-xs-12.contacts_div when added with Suitelet. // Hence, the html code is added using jQuery when the page loads. var inline_html_contact_table = '<table cellpadding="15" id="contacts" class="table table-responsive table-striped contacts tablesorter" cellspacing="0" style="width: 100%;border: 0"><thead style="color: white;background-color: #379E8F;"><tr><th style="vertical-align: middle;text-align: center;" id="col_name"><b>NAME</b></th><th style="vertical-align: middle;text-align: center;" id="col_phone"><b>PHONE</b></th><th style="vertical-align: middle;text-align: center;" id="col_email"><b>EMAIL</b></th><th style="vertical-align: middle;text-align: center;" id="col_role"><b>ROLE</b></th><th style="vertical-align: middle;text-align: center;" id="col_add_as_recipient"><b>ADD AS RECIPIENT</b></th></tr></thead><tbody></tbody></table>'; $('div.col-xs-12.contacts_div').html(inline_html_contact_table); // Like the contacts table, the html code of the usernote table is added using jQuery when the page loads. var inline_html_usernote_table = '<table cellpadding="15" id="user_note" class="table table-responsive table-striped contacts tablesorter" cellspacing="0" style="width: 100%;border: 0"><thead style="color: white;background-color: #379E8F;"><tr><th style="vertical-align: middle;text-align: center;" id="usernote_title"><b>TITLE</b></th><th style="vertical-align: middle;text-align: center;" id="usernote_name"><b>NAME</b></th><th style="vertical-align: middle;text-align: center;" id="usernote_date"><b>DATE</b></th><th style="vertical-align: middle;text-align: center;" id="usernote_comment"><b>USER NOTE</b></th></tr></thead><tbody></tbody></table>'; $('div.col-xs-12.user_note_div').html(inline_html_usernote_table); //Credit memo display displayed conditionally if (selector_type == 'invoice_number' && !isNullorEmpty(ticket_id)) { var inline_html_credit_memo_table = htmlCreditMemoTable(status_value); $('div.col-xs-12.credit_memo_div').html(inline_html_credit_memo_table); var inline_html_usage_report_table = htmlUsageReportTable(status_value); $('div.col-xs-12.usage_report_div').html(inline_html_usage_report_table); } // The value of the submitter button at the bottom of the page is directly linked to the value of the button at the top. // var submit_btn_val = $('#submitter').val().toUpperCase(); // $('#submit_ticket').val(submit_btn_val); if (!isNullorEmpty(selector_number)) { console.log('!isNullorEmpty(selector_number) : ', !isNullorEmpty(selector_number)); // If we updated the contacts, we have the parameter 'custpage_selector_number' and no parameter for 'custpage_ticket_id'. if (isNullorEmpty(ticket_id)) { console.log('isNullorEmpty(ticket_id) : ', isNullorEmpty(ticket_id)); $('#selector_value').val(selector_number); if (validateSelectorInput()) { displayCustomerInfo(); } // If we come from the edit_ticket page, we have the parameters 'custpage_selector_number' and' custpage_ticket_id'. } else { console.log('isNullorEmpty(ticket_id) : ', isNullorEmpty(ticket_id)); createContactsRows(); // If the ticket status is "Open, the acknoledgement template shall be selected. if (status_value != 3) { $('#template option:selected').attr('selected', false); $('#template option[value="66"]').attr('selected', true); // Select the acknoledgement template loadTemplate(); } if (selector_type == 'invoice_number') { updateInvoicesDatatable(); createCreditMemoRows(status_value); createUsageReportRows(status_value); createUsernoteRows(ticket_id); } else if (selector_type == 'barcode_number') { selectEnquiryMedium(); selectTollEmails(); selectOwner(); setReminderDate(); hideCloseTicketButton(); updateTicketsDatatable(); } else { //selector_type == 'customer_issue' selectEnquiryMedium(); } } } $('[data-toggle="tooltip"]').tooltip(); updateButtonsWidth(); $('.input-group-btn button').click(function(e) { $(e.currentTarget).next('ul').toggleClass('hide'); $(e.currentTarget).next('ul').toggleClass('show'); }); $('#screenshot_image').on('change', function() { var file = $('#screenshot_image')[0].files[0]; if (file && (file.type == "image/jpeg" || file.type == "image/png")) { //continue } else { showAlert('Please enter a screenshot image of type .png or .jpeg'); } }); //Change display depending on which selector is chosen $('.dropdown-menu li a').click(function(e) { console.log("in selector dropdown li a"); e.preventDefault(); setupSelectorInput($(this).text()); var selector_type = $('#selector_text').text().toLowerCase().split(' ').join('_'); currRec.setValue({ fieldId: 'custpage_selector_type', value: selector_type}); updateTicketsDatatableHeaders(selector_type); switch (selector_type) { case 'barcode_number': $('#daytodayemail').attr('disabled', true); $('#daytodayphone').attr('disabled', true); $('#accountsemail').attr('disabled', true); $('#accountsphone').attr('disabled', true); $('.accountscontact_section').addClass('hide'); $('.accountscontact_section').addClass('hide'); $('.accounts_number_section').addClass('hide'); $('.mpex_stock_used_section').removeClass('hide'); $('.final_delivery').removeClass('hide'); $('.enquiry_status_div').removeClass('col-xs-12'); $('.enquiry_status_div').addClass('col-xs-6'); $('.label_section').removeClass('hide'); $('.enquiry_medium_section').removeClass('hide'); $('.ticket_enquiry_header_section').removeClass('hide'); $('.enquiry_status_div').removeClass('hide'); $('.enquiry_count_section').removeClass('hide'); $('.enquiry_count_breakdown_section').removeClass('hide'); $('.interaction_count_breakdown_section').removeClass('hide'); $('.invoice_method_accounts_cc_email_section').addClass('hide'); $('.mpex_customer_po_number_section').addClass('hide'); $('.terms_section').addClass('hide'); $('.mpex_invoicing_cycle_section').addClass('hide'); $('.ss_section').addClass('hide'); $('.browser_os_section').addClass('hide'); $('.phone_section').addClass('hide'); $('.login_email_section').addClass('hide'); $('.sender_details_section').addClass('hide'); $('.login_email_used_section').addClass('hide'); // Add MP Issues options var mp_ticket_issues_columns = new Array(); mp_ticket_issues_columns[0] = search.createColumn({ name: 'name' }); mp_ticket_issues_columns[1] = search.createColumn({ name: 'internalId' }); var mpTicketIssuesResultSet = search.create({ type: 'customlist_mp_ticket_issues', columns: mp_ticket_issues_columns }); var mp_issues_option_inline_html = ''; mpTicketIssuesResultSet.each(function(mpTicketIssueResult) { var mp_issue_name = mpTicketIssueResult.getValue('name'); var mp_issue_id = mpTicketIssueResult.getValue('internalId'); mp_issues_option_inline_html += '<option value="' + mp_issue_id + '">' + mp_issue_name + '</option >'; return true; }); $('#mp_issues').html(mp_issues_option_inline_html); $('#mp_issues').selectpicker('refresh'); $('.toll_issues_section').removeClass('hide'); $('.resolved_toll_issues_section').removeClass('hide'); $('.open_invoices').addClass('hide'); $('.invoice_issues_section').addClass('hide'); $('.resolved_invoice_issues_section').addClass('hide'); $('.user_note').addClass('hide'); $('.comment_section').removeClass('hide'); $('.reminder_section').removeClass('hide'); $('.login_email_used_section').addClass('hide'); var owner_list = [userId]; console.log(owner_list); $('#owner').selectpicker('val', owner_list); break; case 'invoice_number': if (isFinanceRole(userRole)) { $('#daytodayemail').attr('disabled', false); $('#daytodayphone').attr('disabled', false); $('#accountsemail').attr('disabled', false); $('#accountsphone').attr('disabled', false); $('#invoice_method').attr('disabled', false); $('#accounts_cc_email').attr('disabled', false); $('#mpex_po_number').attr('disabled', false); $('#customer_po_number').attr('disabled', false); $('#mpex_invoicing_cycle').attr('disabled', false); } $('.accountscontact_section').removeClass('hide'); $('.accounts_number_section').removeClass('hide'); $('.mpex_stock_used_section').addClass('hide'); $('.final_delivery').addClass('hide'); $('.enquiry_status_div').addClass('col-xs-12'); $('.enquiry_status_div').removeClass('col-xs-6'); $('.label_section').addClass('hide'); $('.enquiry_medium_section').addClass('hide'); $('.ticket_enquiry_header_section').addClass('hide'); $('.enquiry_status_div').addClass('hide'); $('.enquiry_count_section').addClass('hide'); $('.enquiry_count_breakdown_section').addClass('hide'); $('.interaction_count_breakdown_section').addClass('hide'); $('.ss_section').addClass('hide'); $('.browser_os_section').addClass('hide'); $('.phone_section').addClass('hide'); $('.login_email_section').addClass('hide'); $('.sender_details_section').addClass('hide'); $('.invoice_method_accounts_cc_email_section').removeClass('hide'); $('.mpex_customer_po_number_section').removeClass('hide'); $('.terms_section').removeClass('hide'); $('.mpex_invoicing_cycle_section').removeClass('hide'); $('.open_invoices').removeClass('hide'); // Remove MP Issues options $('#mp_issues option').each(function() { if ($(this).val() != 4) { $(this).remove(); } }); $('#mp_issues').selectpicker('refresh'); $('.toll_issues_section').addClass('hide'); $('.resolved_toll_issues_section').addClass('hide'); $('.invoice_issues_section').removeClass('hide'); $('.resolved_invoice_issues_section').removeClass('hide'); $('.user_note').removeClass('hide'); $('.comment_section').addClass('hide'); $('.reminder_section').removeClass('hide'); //Set Owner to current user var owner_list = [userId]; $('#owner').selectpicker('val', owner_list); break; case 'customer_issue': $('#daytodayemail').attr('disabled', true); $('#daytodayphone').attr('disabled', true); $('#accountsemail').attr('disabled', true); $('#accountsphone').attr('disabled', true); $('.invoice_issues_section').addClass('hide'); $('.user_note_title_section').addClass('hide'); $('.user_note_textarea_section').addClass('hide'); $('.user_note_section').addClass('hide'); $('.accountscontact_section').addClass('hide'); $('.accountscontact_section').addClass('hide'); $('.accounts_number_section').addClass('hide'); $('.mpex_stock_used_section').removeClass('hide'); $('.final_delivery').removeClass('hide'); $('.enquiry_status_div').removeClass('col-xs-12'); $('.enquiry_status_div').addClass('col-xs-6'); $('.label_section').removeClass('hide'); $('.enquiry_medium_section').removeClass('hide'); $('.ticket_enquiry_header_section').removeClass('hide'); $('.enquiry_status_div').removeClass('hide'); $('.enquiry_count_section').removeClass('hide'); $('.enquiry_count_breakdown_section').removeClass('hide'); $('.interaction_count_breakdown_section').removeClass('hide'); $('.reminder_section').addClass('hide'); $('.toll_issues_section').addClass('hide'); $('.login_email_used_section').removeClass('hide'); var current_customer_issue = $('#selector_value').val(); switch (current_customer_issue) { case 'Customer App': //App related fields $('.browser_os_section').addClass('hide'); $('.sender_details_section').addClass('hide'); $('.phone_section').removeClass('hide'); //Set current chosen option to Customer App var mp_issues_option_inline_html = '<option value="10" selected> Customer App Issue</option>'; $('#mp_issues').html(mp_issues_option_inline_html); //Requires double refresh. One for the dropwdown chnage and sceond for selection $('#mp_issues').selectpicker('refresh'); $('#mp_issues').selectpicker('refresh') break; case 'Customer Portal': //Portal related fields $('.phone_section').addClass('hide'); $('.browser_os_section').removeClass('hide'); $('.sender_details_section').addClass('hide'); var mp_issues_option_inline_html = '<option value="9" selected> Customer Portal Issue</option>'; $('#mp_issues').html(mp_issues_option_inline_html); //Requires double refresh. One for the dropwdown chnage and sceond for selection $('#mp_issues').selectpicker('refresh'); $('#mp_issues').selectpicker('refresh') break; case 'Update Label': //Label fields $('.browser_os_section').addClass('hide'); $('.phone_section').addClass('hide'); $('.sender_details_section').removeClass('hide'); var mp_issues_option_inline_html = '<option value="11" selected> Update Customer Label Issue</option>'; $('#mp_issues').html(mp_issues_option_inline_html); //Requires double refresh. One for the dropwdown chnage and sceond for selection $('#mp_issues').selectpicker('refresh'); $('#mp_issues').selectpicker('refresh'); break; } //Set Owner to Rianne Mansell var owner_list = ['1132504']; $('#owner').selectpicker('val', owner_list); break; } $(this).closest("ul").toggleClass('hide'); $(this).closest("ul").toggleClass('show'); }); $('#open_inv').click(function() { var invoice_id = $(this).data('inv-id'); var compid = (runtime.envType == "SANDBOX") ? '1048144_SB3' : '1048144'; var invoice_link = baseURL + '/app/accounting/transactions/custinvc.nl?id=' + invoice_id + '&compid=' + compid + '&cf=116&whence='; console.log("invoice_link", invoice_link); window.open(invoice_link, "_blank", "height=750,width=650,modal=yes,alwaysRaised=yes"); }) updateEnquiryMediumAndCount(); $('#reviewcontacts').click(function() { console.log("1234"); addEditContact(); }); $('#invoices_dropdown').change(function() { var invoice_status_filter = $(this, 'option:selected').val(); if (invoice_status_filter == 'open') { var invoice_section_header = 'OPEN INVOICES'; } else if (invoice_status_filter == 'paidInFull') { var invoice_section_header = 'PAID INVOICES'; } $('.open_invoices_header div div h4 span').text(invoice_section_header); updateInvoicesDatatable(); }); $('.add_as_recipient').click(function() { var email_address = $(this).data('email'); console.log(email_address); if (!isNullorEmpty(email_address)) { $(this).toggleClass('btn-success'); $(this).toggleClass('btn-danger'); if ($(this).attr('data-original-title') == 'Add as recipient') { $(this).attr('data-original-title', 'Remove recipient'); } else { $(this).attr('data-original-title', 'Add as recipient'); } $('[data-toggle="tooltip"]').tooltip(); // Convert "TO" text field to email adresses array console.log($('#send_to')); var send_to_values = $('#send_to').val().split(','); var send_to_array = []; send_to_values.forEach(function(email_address_in_send_to) { email_address_in_send_to = email_address_in_send_to.trim(); if (!isNullorEmpty(email_address_in_send_to)) { send_to_array.push(email_address_in_send_to); } }); // Add or remove selected email adress from array var firstname = $(this).data('firstname'); var firstname_array = $('#send_to').data('firstname'); if (!isNullorEmpty(firstname_array)) { firstname_array = JSON.parse($('#send_to').data('firstname')); } else { firstname_array = []; } var contact_id = $(this).data('contact-id'); var contact_id_array = $('#send_to').data('contact-id'); if (!isNullorEmpty(contact_id_array)) { contact_id_array = JSON.parse(contact_id_array); } else { contact_id_array = []; } var index_of_email_address = send_to_array.indexOf(email_address); if (index_of_email_address == -1 && $(this).hasClass('btn-danger') && !isNullorEmpty(email_address)) { send_to_array.push(email_address); if (!isNullorEmpty(firstname)) { firstname_array.push(firstname); } if (!isNullorEmpty(contact_id) || contact_id == 0) { contact_id_array.push(contact_id); } } else if ($(this).hasClass('btn-success')) { send_to_array.splice(index_of_email_address, 1); if (!isNullorEmpty(firstname)) { firstname_array.splice(firstname, 1); } if (!isNullorEmpty(contact_id)) { contact_id_array.splice(contact_id, 1); } } firstname_array = JSON.stringify(firstname_array); contact_id_array = JSON.stringify(contact_id_array); // Convert array to text field var send_to = ''; send_to_array.forEach(function(email_address) { send_to += email_address + ', '; }); send_to = send_to.slice(0, -2); console.log('send_to : ', send_to); $('#send_to').val(send_to); $('#send_to').data('firstname', firstname_array); $('#send_to').data('contact-id', contact_id_array); } }); $('#credit_memo tbody td[headers="credit_memo_action"] button, #usage_report tbody td[headers="usage_report_action"] button, button#add_inv').on('click', function() { attachFileButton.call(this) }); $('#acc_manager_button').click(function() { var account_manager_email = $('#acc_manager').data('email'); var send_cc_field = $('#send_cc').val(); if (isNullorEmpty(send_cc_field)) { $('#send_cc').val(account_manager_email); } else { $('#send_cc').val(send_cc_field + ', ' + account_manager_email); } }); $('#template').change(function() { loadTemplate() }); $('#send_email').click(function() { sendEmail() }); $('#toll_issues, #invoice_issues').on('change', function() { hideCloseTicketButton() }); $('#mp_issues').change(function() { selectOwner(); hideCloseTicketButton(); }); $('#cancelbutton').click(function() { onCancel() }); $('#closeticketbutton').click(function() { closeTicket(selector_type, '') }); $('#closenewticketbutton').click(function() { console.log("in close new"); closeNewTicket() }); $('#closelostbutton').click(function() { closeTicketLost() }); $('#closeunallocatedbutton').click(function() { closeUnallocatedTicket() }); $('#reopenticketbutton').click(function() { reopenTicket() }); $('#updateticketbutton').click(function() { updateAndNew(); }); $('#updatecloseticketbutton').click(function() { console.log("btn clicked"); if (confirm("Are you sure you want to update and close this ticket?\n\nThis action cannot be undone.")) { console.log('Update & Closed Started'); updateSaveRecord(); updateCloseTicket(); console.log("Update finished"); //updateCloseTicket(); } }); $('#openticketbutton').click(function() { console.log("hi"); //saveRecord(); $('#submitter').trigger('click'); }); $('#opennewticketbutton').click(function() { openAndNew(); }); $('#escalatebutton').click(function() { escalateTicket(ticket_id, selector_number, selector_type); }); $('#escalaterianne').click(function() { console.log("Escalating to rianne"); var ticketRecord = record.load({ type: 'customrecord_mp_ticket', id: parseInt(ticket_id), }); var comments = $('#comment').val(); console.log('comments', comments); if (isNullorEmpty(comments)) { console.log('Enter comment before Escalation', comments); showAlert('Please enter a Comment before escalating to IT'); return false; } if (isNullorEmpty(ticketRecord.getValue({fieldId: 'custrecord_date_escalated_it'}))) { ticketRecord.setValue({fieldId: 'custrecord_date_escalated_it', value: new Date()}); var owner_list = ['1132504']; $('#owner').selectpicker('val', owner_list); ticketRecord.setValue({fieldId: 'custrecord_owner', value: owner_list}); ticketRecord.save({ enableSourcing: true, ignoreMandatoryFields: true }); sendCustomerTicketEmail('', parseInt(ticket_id), customer_number, selector_type, selector_number, $("#browser_value option:selected").text(), $('#os_value option:selected').text(), $('#login_email_text').val(), '', '', ["envkt@example.com"]); var output = url.resolveScript({ deploymentId: 'customdeploy_sl_edit_ticket_2', scriptId: 'customscript_sl_edit_ticket_2', }); var upload_url = baseURL + output; window.open(upload_url, "_self", "height=750,width=650,modal=yes,alwaysRaised=yes"); } else { console.log('didnt work for some reason'); } }); $('#escalateankith').click(function() { var ticketRecord = record.load({ type: 'customrecord_mp_ticket', id: parseInt(ticket_id), }); var interaction_count_by_phone = $('#interaction_count_by_phone').val(); var interaction_count_by_email = $('#interaction_count_by_email').val(); var customer_number = $('#customer_number_value').val().trim(); var creator_id = ticketRecord.getValue({fieldId: 'custrecord_creator'}); var escalated_to_it = ticketRecord.getValue({ fieldId: 'custrecord_date_escalated_it' }); var first_interaction = ticketRecord.getValue({ fieldId: 'custrecord_first_interaction_date' }); if (isNullorEmpty(customer_number) && creator_id == 112209 && !isNullorEmpty(escalated_to_it) && selector_type == "customer_issue" && !isNullorEmpty(ticket_id)) { console.log('Enter customer number before Escalation'); showAlert('Please enter a Customer Number'); return false; } else if (isNullorEmpty(first_interaction) && interaction_count_by_phone == 0 && interaction_count_by_email == 0) { console.log('Incrememnt interaction count before Escalation'); showAlert('Please Interact with Customer before Escalation'); return false; } ticketRecord.setValue({fieldId: 'custrecord_ticket_status', value: 10}); var owner_list = ['409635']; $('#owner').selectpicker('val', owner_list); ticketRecord.setValue({fieldId: 'custrecord_owner', value: owner_list}); ticketRecord.save({ enableSourcing: true, ignoreMandatoryFields: true }); var subject = 'MPSD' + ticket_id + ' - Customer Issue Ticket Escalated'; var customer_id = ticketRecord.getValue({fieldId: 'custrecord_customer1'}); var login_email = ticketRecord.getText({fieldId: 'custrecord_login_email'}); sendCustomerTicketEmail(subject, parseInt(ticket_id), customer_number, selector_type, selector_number, $("#browser_value option:selected").text(), $('#os_value option:selected').text(), $('#login_email_text').val(), '', '', ["nnheo@example.com"]); if (!isNullorEmpty(login_email)) { sendCustomerEscalateEmail('MailPlus [MPSD' + parseInt(ticket_id) + '] - Your IT ticket has been escalated - Customer Portal', [login_email], 120, customer_id); } var output = url.resolveScript({ deploymentId: 'customdeploy_sl_edit_ticket_2', scriptId: 'customscript_sl_edit_ticket_2', }); var upload_url = baseURL + output; window.open(upload_url, "_self", "height=750,width=650,modal=yes,alwaysRaised=yes"); }); $('#escalateunderdev').click(function() { saveRecord(); var ticketRecord = record.load({ type: 'customrecord_mp_ticket', id: parseInt(ticket_id), }); ticketRecord.setValue({fieldId: 'custrecord_ticket_status', value: 17}); ticketRecord.save({ enableSourcing: true, ignoreMandatoryFields: true }); location.reload(); }); $('#escalateremoveunderdev').click(function() { saveRecord(); var ticketRecord = record.load({ type: 'customrecord_mp_ticket', id: parseInt(ticket_id), }); ticketRecord.setValue({fieldId: 'custrecord_ticket_status', value: 10}); ticketRecord.save({ enableSourcing: true, ignoreMandatoryFields: true }); location.reload(); }); $('#closeresolvedbutton').click(function() { closeTicket(selector_type, 15); }); $('#closeunresolvedbutton').click(function() { closeTicket(selector_type, 16); }); // Prevent the ticket to be submitted on enter. $('input, textarea').keydown(function(e) { if (e.keyCode == 13) { e.preventDefault(); return false; } }); // Add a newline at the end of the comment textarea when enter is pressed // This will not create the newline where the cursor is in the text $('textarea#comment').keydown(function(e) { if (e.keyCode == 13) { var comment = $(this).val(); comment += '\n'; $(this).val(comment); return false; } }); //Event listener for customer number input and selector value input $('#customer_number_value, #selector_value').change(function() { checkMandatoryFields(); }); } function escalateTicket(ticket_id, selector_number, selector_type) { var answer = window.confirm("Are you sure you want to escalate this ticket?"); if (answer) { //SET FIELDS IN RECORD //some code // REDIRECT TO URL console.log("IN HERE"); var params = { ticket_id: parseInt(ticket_id), selector_number: selector_number, selector_type: selector_type }; params = JSON.stringify(params); var output = url.resolveScript({ deploymentId: 'customdeploy_sl_ticketing_escalate', scriptId: 'customscript_sl_ticketing_escalate', }); var upload_url = baseURL + output + '&custparam_params=' + params; var ticketRecord = record.load({ type: 'customrecord_mp_ticket', id: Math.floor(ticket_id), }); var customerstatus = ticketRecord.getValue({fieldId: 'custrecord_mp_ticket_customer_status'}); var ticketstatus = ticketRecord.getValue({fieldId: 'custrecord_ticket_status'}); var customer_id = ticketRecord.getValue({fieldId: 'custrecord_customer1'}); var customer_barcode_number = ticketRecord.getValue({ fieldId : 'custrecord_barcode_number'}); var ticket_name = ticketRecord.getText({fieldId: 'name'}); console.log('customerstatus', customerstatus); if (parseInt(customerstatus) < 4 ) { console.log(customerstatus); ticketRecord.setValue({fieldId: 'custrecord_mp_ticket_customer_status', value: parseInt(customerstatus) + 1}); } if (parseInt(ticketstatus) < 11 ) { console.log(ticketstatus); ticketRecord.setValue({fieldId: 'custrecord_ticket_status', value: 11}); } else if (parseInt(ticketstatus) < 14) { console.log(ticketstatus); ticketRecord.setValue({fieldId: 'custrecord_ticket_status', value: parseInt(ticketstatus) + 1}); } ticketRecord.save({ enableSourcing: true, }) //Send email to Receiver var barcodeRecord = record.load({ type: 'customrecord_customer_product_stock', id: customer_barcode_number, }); var receiveremail = barcodeRecord.getValue({fieldId: 'custrecord_receiver_email'}); var barcodeName = barcodeRecord.getValue({fieldId: 'name'}); var ticketRecord = record.load({ type: 'customrecord_mp_ticket', id: Math.floor(ticket_id), }) var ticketstatus = ticketRecord.getValue({fieldId: 'custrecord_ticket_status'}); if (!isNullorEmpty(receiveremail)) { if (ticketstatus == 11) { sendCustomerEscalateEmail('MailPlus [' + ticket_name + '] - Support enquiry | Stage 1 - ' + barcodeName, [receiveremail], 109, customer_id); } else if (ticketstatus == 12) { sendCustomerEscalateEmail('MailPlus [' + ticket_name + '] - Support enquiry | Stage 2 - ' + barcodeName, [receiveremail], 110, customer_id); } else if (ticketstatus == 13) { sendCustomerEscalateEmail('MailPlus [' + ticket_name + '] - Support enquiry | Stage 3 - ' + barcodeName, [receiveremail], 111, customer_id); } } //Send email to TOLL var toll_issues = ticketRecord.getText({ fieldId: 'custrecord_toll_issues' }); var mp_issues = ticketRecord.getText({ fieldId: 'custrecord_mp_ticket_issue' }); var body = 'MP Ticket ID: ' + ticket_name + '\n Barcode: ' + barcodeName + '\nToll Issues: ' + toll_issues + '\nMP Issues: ' + mp_issues; // if (ticketstatus == 11) { // email.send({ // author: 112209, // body: body, // recipients: ['kenaa@example.com'], // subject: 'Ticket Escalated: Escalation 1- ' + ticket_name, // relatedRecords: {record: ticket_id, recordtype: 1042} // }); // } else if (ticketstatus == 12) { // email.send({ // author: 112209, // body: body, // recipients: ['kenaa@example.com'], // subject: 'Ticket Escalated: Escalation 2- ' + ticket_name, // relatedRecords: {record: ticket_id, recordtype: 1042}, // }); // } else if (ticketstatus == 13) { // email.send({ // author: 112209, // body: body, // recipients: ['kenaa@example.com'], // subject: 'Ticket Escalated: Escalation 3- ' + ticket_name, // relatedRecords: {record: ticket_id, recordtype: 1042}, // }); // } console.log("upload", upload_url) window.open(upload_url, '_self'); } else { //some code } } /** * Function to sent emails when a customer associated ticket is escalated */ function sendCustomerEscalateEmail(subject, recipients, template, customer_id) { var sales_rep = encodeURIComponent(runtime.getCurrentUser().name); var userid = encodeURIComponent(runtime.getCurrentUser().id); var suiteletUrl = url.resolveScript({ scriptId: 'customscript_merge_email', deploymentId: 'customdeploy_merge_email', returnExternalUrl: true }); suiteletUrl += '&rectype=customer&template='; suiteletUrl += template + '&recid=' + customer_id + '&salesrep=' + sales_rep + '&dear=' + '' + '&contactid=' + null + '&userid=' + userid; console.log(suiteletUrl); var response = https.get({ url: suiteletUrl }); var emailHtml = response.body; if (!isNullorEmpty(customer_id)) { email.send({ author: 112209, body: emailHtml, recipients: recipients, subject: subject, relatedRecords: { entityId: customer_id} }); } else { email.send({ author: 112209, body: emailHtml, recipients: recipients, subject: subject, }); } } function commentsDate() { var today = new Date(); var dd = today.getDate(); var mm = today.getMonth()+1; var yyyy = today.getFullYear(); if(dd<10) { dd='0'+dd; } if(mm<10) { mm='0'+mm; } today = mm+'/'+dd+'/'+yyyy; return today; } function saveRecord(context) { var currRec = currentRecord.get(); var status_value = currRec.getValue({ fieldId: 'custpage_ticket_status_value' }); var selector_issue = currRec.getValue({ fieldId: 'custpage_selector_issue' }); //set to T onEscalate var selector_type = currRec.getValue({ fieldId: 'custpage_selector_type' }); var customer_number = currRec.getValue({ fieldId: 'custpage_customer_number' }); var selector_number = $('#selector_value').val(); console.log('status_value' + status_value) console.log('selector_issue ' + selector_issue) console.log('selector_type ' + selector_type) console.log('selector_number ' + selector_number) if (selector_type == 'customer_issue') { if (isNullorEmpty(customer_number)) { showAlert('Please enter a customer number'); return false; } } if (isTicketNotClosed(status_value) && !isNullorEmpty(selector_type)) { // Barcode/Inv associated tickets - check that a TOLL Issue or an Invoice Issue has been selected. // Customer number associated ticket - check that a customer number has been entered switch (selector_type) { case 'barcode_number': var toll_issues_length = $('#toll_issues option:selected').length; if (toll_issues_length == 0) { showAlert('Please select a TOLL Issue<br>'); return false; } break; case 'invoice_number': var invoice_issues_length = $('#invoice_issues option:selected').length; if (invoice_issues_length == 0) { showAlert('Please select an Invoice Issue<br>'); return false; } break; case 'customer_issue': var login_email_used = $('#login_email_text').val(); if (!isNullorEmpty(login_email_used) && !validateEmail(login_email_used)) { showAlert('User login email format is invalid. Please enter email again <br>'); return false; } break; } } if (role == 1005) { var owner_length = $('#owner option:selected').length; if (owner_length == 0) { showAlert('Please select an Owner<br>'); return false; } } else { var owner_length = $('#owner option:selected').length; var checkTicketOwner = currRec.getValue({ fieldId: 'custpage_ticket_id' }); if (!isNullorEmpty(checkTicketOwner)) { var checkTicketOwnerRec = record.load({ type: 'customrecord_mp_ticket', id: parseInt(checkTicketOwner) }); var owners = checkTicketOwnerRec.getValue({ fieldId: 'custrecord_owner'}); if (isNullorEmpty(owners) && owner_length == 0) { showAlert('Please select an Owner<br>'); return false; } } else { if (owner_length == 0) { showAlert('Please select an Owner<br>'); return false; } } } if (selector_issue == 'T') { var to = $('#owner option:selected').map(function() { return $(this).data('email') }); to = $.makeArray(to); var email_sent = sendInformationEmailTo(selector_type, to, true) if (!email_sent) { return false; } } var ticket_id = currRec.getValue({ fieldId: 'custpage_ticket_id' }); console.log("Ticket id = " + ticket_id); if (isNullorEmpty(ticket_id)) { var ticketRecord = record.create({ type: 'customrecord_mp_ticket', }); currRec.setValue({ fieldId: 'custpage_created_ticket', value: 'T' }); ticketRecord.setValue({ fieldId: 'custrecord_email_sent', value: false }); } else { ticket_id = parseInt(ticket_id); try { var ticketRecord = record.load({ type: 'customrecord_mp_ticket', id: ticket_id }); } catch (e) { if (e instanceof error.SuiteScriptError) { if (e.name == "SSS_MISSING_REQD_ARGUMENT") { console.log('Error to load the ticket record with ticket_id : ' + ticket_id); } } } } currRec.setValue({ fieldId: 'custpage_selector_number', value: selector_number }); var selector_id = currRec.getValue({ fieldId: 'custpage_selector_id' }); // Save customer number var customer_number = $('#customer_number_value').val(); console.log('Saving customer number = ' + customer_number); ticketRecord.setValue({ fieldId: 'custrecord_cust_number', value: customer_number }); // Save Enquiry status var enquiry_status_val = $('#enquiry_status option:selected').val(); if (!isNullorEmpty(enquiry_status_val)) { ticketRecord.setValue({ fieldId: 'custrecord_enquiry_status', value: enquiry_status_val }); } var attachments_hyperlink = $('#attachments').val(); if (!isNullorEmpty(attachments_hyperlink)) { ticketRecord.setValue({ fieldId: 'custrecord_mp_ticket_attachments', value: attachments_hyperlink }); } // Save Ticket Label var label = $('#label_status option:selected').val(); if (!isNullorEmpty(label)) { ticketRecord.setValue({ fieldId: 'custrecord_ticket_label', value: label }); } //Save Enquiry medium var enquiry_medium = $('#enquiry_status option:selected').val(); if (!isNullorEmpty(enquiry_medium)) { ticketRecord.setValue({ fieldId: 'custrecord_enquiry_medium', value: enquiry_medium }); } var total_enquiry_count = 0; if (!isNullorEmpty($('#enquiry_count_by_chat').val())) { total_enquiry_count += parseInt($('#enquiry_count_by_chat').val()); } if (!isNullorEmpty($('#enquiry_count_by_phone').val())) { total_enquiry_count += parseInt($('#enquiry_count_by_phone').val()); } if (!isNullorEmpty($('#enquiry_count_by_email').val())) { total_enquiry_count += parseInt($('#enquiry_count_by_email').val()); } ticketRecord.setValue({ fieldId: 'custrecord_enquiry_count', value: total_enquiry_count }); var enquiry_count_by_chat = $('#enquiry_count_by_chat').val(); if (!isNullorEmpty(enquiry_count_by_chat)) { ticketRecord.setValue({ fieldId: 'custrecord_chat_enquiry_count', value: enquiry_count_by_chat }); } var enquiry_count_by_phone = $('#enquiry_count_by_phone').val(); if (!isNullorEmpty(enquiry_count_by_phone)) { ticketRecord.setValue({ fieldId: 'custrecord_phone_enquiry_count', value: enquiry_count_by_phone }); } var enquiry_count_by_email = $('#enquiry_count_by_email').val(); if (!isNullorEmpty(enquiry_count_by_email)) { ticketRecord.setValue({ fieldId: 'custrecord_email_enquiry_count', value: enquiry_count_by_email }); } var interaction_count_by_phone = $('#interaction_count_by_phone').val(); var interaction_count_by_email = $('#interaction_count_by_email').val(); if (isNullorEmpty(ticketRecord.getValue({ fieldId: 'custrecord_first_interaction_date'}))) { if (!isNullorEmpty(interaction_count_by_email) || !isNullorEmpty(interaction_count_by_phone)) { ticketRecord.setValue({ fieldId: 'custrecord_first_interaction_date', value: new Date()}); } } if (!isNullorEmpty(interaction_count_by_phone)) { ticketRecord.setValue({ fieldId: 'custrecord_phone_interaction_count', value: interaction_count_by_phone }); } if (!isNullorEmpty(interaction_count_by_email)) { ticketRecord.setValue({ fieldId: 'custrecord_email_interaction_count', value: interaction_count_by_email }); } //Check Enquiry is Selected if (isNullorEmpty(enquiry_count_by_chat) && isNullorEmpty(enquiry_count_by_phone) && isNullorEmpty(enquiry_count_by_email)) { showAlert('Please select an Enquiry Type<br>'); return false; } else if(total_enquiry_count == 0) { showAlert('Please select an Enquiry Type<br>'); return false; } //Save Medium list saveMediumList(enquiry_count_by_chat, enquiry_count_by_phone, enquiry_count_by_email, ticketRecord); ticketRecord = setTicketStatus(ticketRecord); ticketRecord = setCreator(ticketRecord); ticketRecord.setValue({ fieldId: 'altname', value: selector_number }); var owner_email_list = $('#owner option:selected').map(function() { return $(this).data('email') }); owner_email_list = $.makeArray(owner_email_list); var zee_id = currRec.getValue({ fieldId: 'custpage_zee_id' }); ticketRecord.setValue({ fieldId: 'custrecord_zee', value: zee_id }); console.log("sending email..." + selector_type); if (!isNullorEmpty(selector_type)) { switch (selector_type) { case 'barcode_number': ticketRecord.setValue({ fieldId: 'custrecord_barcode_number', value: selector_id }); // Save Reminder date var reminder_date = $('#reminder').val(); if (!isNullorEmpty(reminder_date)) { reminder_date = new Date(reminder_date); reminder_date = format.parse({ value: reminder_date, type: format.Type.DATE }); ticketRecord.setValue({ fieldId: 'custrecord_reminder', value: reminder_date }); } break; case 'invoice_number': ticketRecord.setValue({ fieldId: 'custrecord_invoice_number', value: selector_id }); var customer_id = currRec.getValue({ fieldId: 'custpage_customer_id' }); ticketRecord.setValue({ fieldId: 'custrecord_customer1', value: customer_id }); if (isFinanceRole(userRole)) { var daytodayemail = $('#daytodayemail').val(); var daytodayphone = $('#daytodayphone').val(); var accountsemail = $('#accountsemail').val(); var accountsphone = $('#accountsphone').val(); var selected_invoice_method_id = $('#invoice_method option:selected').val(); var accounts_cc_email = $('#accounts_cc_email').val(); var mpex_po_number = $('#mpex_po_number').val(); var customer_po_number = $('#customer_po_number').val(); var customer_terms = $('#customers_terms').val(); var selected_invoice_cycle_id = $('#mpex_invoicing_cycle option:selected').val(); var customerRecord = record.load({ type: 'customer', id: customer_id }); customerRecord.setValue({ fieldId: 'custentity_email_service', value: daytodayemail }); customerRecord.setValue({ fieldId: 'phone', value: daytodayphone }); customerRecord.setValue({ fieldId: 'email', value: accountsemail }); customerRecord.setValue({ fieldId: 'altphone', value: accountsphone }); customerRecord.setValue({ fieldId: 'custentity_invoice_method', value: selected_invoice_method_id }); customerRecord.setValue({ fieldId: 'custentity_accounts_cc_email', value: accounts_cc_email }); customerRecord.setValue({ fieldId: 'custentity_mpex_po', value: mpex_po_number }); customerRecord.setValue({ fieldId: 'custentity11', value: customer_po_number }); customerRecord.setValue({ fieldId: 'custentity_finance_terms', value: customer_terms }); customerRecord.setValue({ fieldId: 'custentity_mpex_invoicing_cycle', value: selected_invoice_cycle_id }); customerRecord.save({}) // Save Reminder date var reminder_date = $('#reminder').val(); if (!isNullorEmpty(reminder_date)) { reminder_date = new Date(reminder_date); reminder_date = format.parse({ value: reminder_date, type: format.Type.DATE }); ticketRecord.setValue({ fieldId: 'custrecord_reminder', value: reminder_date}); } } break; case 'customer_issue': var screenshot_image = currRec.getValue({ fieldId: 'custpage_ss_image' }); if (!isNullorEmpty(screenshot_image)) { ticketRecord.setValue({ fieldId: 'custrecord_screenshot', value: screenshot_image}); } var customer_id = currRec.getValue({ fieldId: 'custpage_customer_id' }); if (!isNullorEmpty(customer_id)) { ticketRecord.setValue({ fieldId: 'custrecord_customer1', value: customer_id}); } var customer_issue_type = $('#selector_value').val(); if (!isNullorEmpty(customer_issue_type)) { ticketRecord.setValue({ fieldId: 'custrecord_customer_issue', value: customer_issue_type}); } var login_email_used = $('#login_email_text').val(); if (!isNullorEmpty(login_email_used)) { ticketRecord.setValue({ fieldId: 'custrecord_login_email', value: login_email_used}); } var is_customer_number_email_sent = currRec.getValue({ fieldId: 'custpage_customer_number_email_sent' }); console.log("cust iss typ", customer_issue_type); switch (customer_issue_type) { case 'Customer App': console.log("in cust app"); var phone_used = $('#phone_used').val(); if (!isNullorEmpty(phone_used)) { ticketRecord.setValue({ fieldId: 'custrecord_phone_used', value: phone_used}); } if (is_customer_number_email_sent == 'F' && !isNullorEmpty(ticket_id)) { sendCustomerTicketEmail('',ticket_id, customer_number, selector_type, selector_number, '', '', login_email_used, '', '', owner_email_list); ticketRecord.setValue({ fieldId: 'custrecord_customer_number_email_sent', value: true }); } break; case 'Customer Portal': var browser = $("#browser_value option:selected").val(); if (!isNullorEmpty(browser)) { ticketRecord.setValue({ fieldId: 'custrecord_browser', value: browser}); } var os_used = $('#os_value option:selected').val(); if (!isNullorEmpty(os_used)) { ticketRecord.setValue({ fieldId: 'custrecord_operating_system', value: os_used}); } if (is_customer_number_email_sent == 'F' && !isNullorEmpty(ticket_id)) { sendCustomerTicketEmail('',ticket_id, customer_number, selector_type, selector_number, $("#browser_value option:selected").text(), $('#os_value option:selected').text(), login_email_used, '', '', owner_email_list); ticketRecord.setValue({ fieldId: 'custrecord_customer_number_email_sent', value: true }); } break; case 'Update Label': var sender_name = $('#sender_name_text').val(); if (!isNullorEmpty(sender_name)) { ticketRecord.setValue({ fieldId: 'custrecord_sender_name', value: sender_name}); } var sender_phone = $('#sender_phone_text').val(); if (!isNullorEmpty(sender_phone)) { ticketRecord.setValue({ fieldId: 'custrecord_sender_phone', value: sender_phone}); } if (is_customer_number_email_sent == 'F' && !isNullorEmpty(ticket_id)) { sendCustomerTicketEmail('',ticket_id, customer_number, selector_type, selector_number, '', '', login_email_used, sender_name, sender_phone, owner_email_list); ticketRecord.setValue({ fieldId: 'custrecord_customer_number_email_sent', value: true }); } break; } break; } } ticketRecord = updateIssues(ticketRecord); //Owner var owner_list = new Array; $('#owner option:selected').each(function() { owner_list.push($(this).val()); }); if (!isNullorEmpty(ticket_id)) { // Send email to new owners. var old_owner_list = ticketRecord.getValue({ fieldId: 'custrecord_owner' }); if (!isNullorEmpty(old_owner_list)) { var only_new_owner_ids = []; var only_new_owner_email_address = []; owner_list.forEach(function(new_owner_id) { if (old_owner_list.indexOf(new_owner_id) == -1) { only_new_owner_ids.push(new_owner_id); only_new_owner_email_address.push($('#owner [value="' + new_owner_id + '"]').data('email')); } }) } else { var only_new_owner_ids = owner_list; var only_new_owner_email_address = []; owner_list.forEach(function(owner_id) { only_new_owner_email_address.push($('#owner [value="' + owner_id + '"]').data('email')); }) } console.log('selector_issue ' + selector_issue); console.log('only_new_owner_email_address ' + only_new_owner_email_address); console.log('selector_type ' + selector_type); // If there is an issue, all the owners have already received an email. if (selector_issue == 'F' && (!isNullorEmpty(only_new_owner_email_address))) { console.log('ISSUE'); var email_sent = sendInformationEmailTo(selector_type, only_new_owner_email_address, false); if (!email_sent) { return false; } } else if (selector_type == 'customer_issue') { var login_email_used = $('#login_email_text').val(); var customer_issue_type = $('#selector_value').val(); switch (customer_issue_type) { case 'Customer App': var phone_used = $('#phone_used').val(); var os_used = $('#os_value option:selected').val(); var browser = $("#browser_value option:selected").val() sendCustomerTicketEmail('',ticket_id, customer_number, selector_type, selector_number, $("#browser_value option:selected").text(), $('#os_value option:selected').text(), login_email_used, '', '', only_new_owner_email_address); break; case 'Customer Portal': var browser = $('#browser_value').val(); sendCustomerTicketEmail('',ticket_id, customer_number, selector_type, selector_number, $("#browser_value option:selected").text(), '', login_email_used, '', '', only_new_owner_email_address); break; case 'Update Label': var sender_phone = $('#sender_phone_text').val(); var sender_name = $('#sender_name_text').val(); sendCustomerTicketEmail('',ticket_id, customer_number, selector_type, selector_number, '', '', login_email_used, sender_name, sender_phone, only_new_owner_email_address); break; } } } // Save Owner list console.log(owner_list); ticketRecord.setValue({ fieldId: 'custrecord_owner', value: owner_list }); console.log("oList", ticketRecord.getValue({ fieldId: 'custrecord_owner'})); //cxcxc // Save Comment switch (selector_type) { case 'barcode_number': var comment = $('#comment').val(); break; case 'invoice_number': var comment = ticketRecord.getValue({ fieldId: 'custrecord_comment' }); if (isNullorEmpty(comment)) { comment = '' }; var selected_title = $('#user_note_title option:selected').text(); var usernote_textarea = $('#user_note_textarea').val(); var date = new Date; var date_time_now = format.parse({ value: date, type: format.Type.DATETIMETZ}); var date_now = format.parse({ value: date, type: format.Type.DATE}); var time_now = format.parse({ value: date, type: format.Type.TIMEOFDAY}); if (!isNullorEmpty(usernote_textarea)) { if (!isNullorEmpty(comment)) { comment += '\n'; } var usernote = '[' + selected_title + '] - [' + userName + '] - [' + date_time_now + '] - ' + usernote_textarea; // Save usernote on Customer record var userNote = record.create({ type: 'note', }); userNote.setValue({ fieldId: 'title', value: selected_title}); userNote.setValue({ fieldId: 'notedate', value: date_now}); userNote.setValue({ fieldId: 'time', value: time_now}); userNote.setValue({ fieldId: 'note', value: usernote_textarea}); userNote.setValue({ fieldId: 'entity', value: customer_id}); if (!isNullorEmpty(customer_id)) { userNote.save({}) } comment += usernote; } break; case 'customer_issue': var comment = $('#comment').val(); break; } if (!isNullorEmpty(comment)) { var original_comment = ticketRecord.getValue({ fieldId: 'custrecord_comment'} ); var total_comment = $('#comment').val(); var new_comment = total_comment.split(original_comment).join(''); var new_comment = total_comment.split(original_comment).join(''); var new_comment2 = new_comment.split("\n").join(''); var date_netsuite = format.format({ value: new Date(), type: format.Type.DATETIME }); console.log("new_comment", new_comment); console.log("new_comment2", new_comment2); var comment_with_date = total_comment; if (!isNullorEmpty(new_comment2)) { comment_with_date = "\n" + original_comment + "\n" + date_netsuite + " - " + new_comment2 + "\n"; } console.log('comment_with_date', comment_with_date); ticketRecord.setValue({ fieldId: 'custrecord_comment', value: comment_with_date} ); } var ticket_id = ticketRecord.save({ enableSourcing: true, }); currRec.setValue({ fieldId: 'custpage_ticket_id', value: ticket_id} ); if (!isNullorEmpty(selector_id) && (selector_type == 'barcode_number')) { try { var list_toll_issues = new Array; $('#toll_issues option:selected').each(function() { list_toll_issues.push($(this).val()); }); var barcodeRecord = record.load({ type: 'customrecord_customer_product_stock', id: selector_id }); console.log("ticket_id", ticket_id); console.log("list_toll_issues", list_toll_issues); barcodeRecord.setValue({ fieldId: 'custrecord_mp_ticket', value: ticket_id} ); barcodeRecord.setValue({ fieldId: 'custrecord_cust_prod_stock_toll_issues ', value: list_toll_issues }); var rec_email = $('#receiveremail').val(); var rec_name = $('#receivername').val(); var rec_state = $('#receiverstate').val(); var rec_zip = $('#receiverzip').val(); var rec_addr1 = $('#receiveraddr1').val(); var rec_addr2 = $('#receiveraddr2').val(); var rec_city = $('#receiversuburb').val(); var rec_phone = $('#receiverphone').val(); //Check if Rec details are to be updated if (!$("#receiveremail").is(":disabled")) { if (!isNullorEmpty(rec_email)) { barcodeRecord.setValue({ fieldId: 'custrecord_receiver_email', value: rec_email }); } if (!isNullorEmpty(rec_name)) { barcodeRecord.setValue({ fieldId: 'custrecord_receiver_name', value: rec_name }); } if (!isNullorEmpty(rec_state)) { barcodeRecord.setValue({ fieldId: 'custrecord_receiver_state', value: rec_state }); } if (!isNullorEmpty(rec_zip)) { barcodeRecord.setValue({ fieldId: 'custrecord_receiver_postcode', value: rec_zip }); } if (!isNullorEmpty(rec_addr1)) { barcodeRecord.setValue({ fieldId: 'custrecord_receiver_addr1', value: rec_addr1 }); } if (!isNullorEmpty(rec_addr2)) { barcodeRecord.setValue({ fieldId: 'custrecord_receiver_addr2', value: rec_addr2 }); } if (!isNullorEmpty(rec_city)) { barcodeRecord.setValue({ fieldId: 'custrecord_receiver_suburb', value: rec_city }); } if (!isNullorEmpty(rec_phone)) { barcodeRecord.setValue({ fieldId: 'custrecord_receiver_phone', value: rec_phone }); } } barcodeRecord.save({ enableSourcing: true, }); } catch (e) { console.log('Error to load the barcode record with barcode_id : ' + selector_id); } } return true; } /** * Takes action depending on which of the two fields (Customer number or Barcode/Inv number) is filled */ function checkMandatoryFields() { var currRec = currentRecord.get(); console.log("checkMandatoryField"); var selector_number = $('#selector_value').val().trim().toUpperCase(); var customer_number = $('#customer_number_value').val().trim(); var selector_type = $('#selector_text').text().toLowerCase().split(' ').join('_'); var ticket_records = null; if (!isNullorEmpty(customer_number) && isCustomerNumberValid(customer_number)) { currRec.setValue({ fieldId: 'custpage_customer_number', value: customer_number }); var customer_id = getCustomerID(customer_number); console.log("cid", customer_id); currRec.setValue({ fieldId: 'custpage_customer_id', value: customer_id }); if (!isNullorEmpty(selector_number)) { switch (selector_type) { case "barcode_number": case "invoice_number": displayCustomerInfo(); break; case "customer_issue": } } ticket_records = searchTicketRecords(customer_number); console.log('Current tickets on customer number ' + customer_number + ': ' + ticket_records); var customer_record = customerLinkedToCustomerNum(customer_number); if (!isNullorEmpty(customer_record)) { //Display franchisee details displayFranchiseeInfo(customer_record); } if (!isNullorEmpty(ticket_records)) { //If tickets exist with this customer number, display customer number tickets datatable updateCustomerNumTicketsTable(ticket_records); } else { console.log('Removing table'); //Remove tickets datatable $('#customer_number_tickets_preview_wrapper').hide(); //Show no ticket exists info box $('#info').text('No ticket exists for the customer '); $('#info').parent().show(); } } if (!isNullorEmpty(selector_number) && isNullorEmpty(customer_number)) { switch (selector_type) { case "barcode_number": if (validateSelectorInput()) { displayCustomerInfo(); } break; case "invoice_number": if (validateSelectorInput()) { displayCustomerInfo(); } break; case "customer_issue": break; } } if (isNullorEmpty(customer_number) && isNullorEmpty(selector_number)) { showAlert('Please enter a customer number or a barcode/invoice number'); //Remove tickets datatable $('#customer_number_tickets_preview_wrapper').hide(); //Reload page var output = url.resolveScript({ deploymentId: 'customdeploy_sl_open_ticket_2', scriptId: 'customscript_sl_open_ticket_2', }) var upload_url = baseURL + output; window.open(upload_url, "_self", "height=750,width=650,modal=yes,alwaysRaised=yes"); } } function updateCustomerNumTicketsTable(ticket_records_dataset) { console.log('Inside update customer tickets table'); $('#customer_number_tickets_preview_wrapper').show(); $('#customer_number_tickets_preview').show(); if (!($.fn.dataTable.isDataTable('#customer_number_tickets_preview'))) { //Initialise new datatable $('#customer_number_tickets_preview').DataTable({ data: ticket_records_dataset, select: { style: 'single' }, columns: [{ title: "ID" }, { title: "Customer Number" }, { title: "Name" }, { title: "Barcode Number" }, { title: "Invoice Number" }, { title: "Customer Issue" }, { title: "Owner" }, { title: "Date created" }] }); //Row selection $('#customer_number_tickets_preview tbody').on('click', 'tr', function() { if ($(this).hasClass('selected')) { $(this).removeClass('selected'); } else { $('#customer_number_tickets_preview tr.selected').removeClass('selected'); $(this).addClass('selected'); var selected_row = $('#customer_number_tickets_preview > tbody > tr.selected'); updateFields(selected_row); } }); } else { //Update datatable rows var datatable = $('#customer_number_tickets_preview').DataTable().clear(); datatable.rows.add(ticket_records_dataset); datatable.draw(); } } function updateFields(selected_row) { //All tickets in here always exist so we can directly redirect to the Edit ticket page console.log('Inside update fields'); var barcode_number = selected_row.children()[3].textContent.trim(); var invoice_number = selected_row.children()[4].textContent.trim(); var customer_issue_type = selected_row.children()[5].textContent.trim(); var ticket_id = selected_row.children()[0].textContent.trim(); if (!isNullorEmpty(barcode_number) || !isNullorEmpty(invoice_number)) { var selector_type = isNullorEmpty(barcode_number) ? "invoice_number" : "barcode_number"; currRec.setValue({ fieldId: 'custpage_selector_type', value: selector_type }); //Set selector value var selector_number = isNullorEmpty(barcode_number) ? invoice_number : barcode_number; $('#selector_value').val(selector_number); // If a ticket already exists for the barcode number, the user is redirected to the "Edit Ticket" page. if (ticketLinkedToSelector(selector_number)) { console.log('ticket linked to barcode') var ticket_id = currRec.getValue({ fieldId: 'custpage_ticket_id' }); var params = { ticket_id: parseInt(ticket_id), selector_number: selector_number, selector_type: selector_type }; params = JSON.stringify(params); var output = url.resolveScript({ deploymentId: 'customdeploy_sl_open_ticket_2', scriptId: 'customscript_sl_open_ticket_2', }); var upload_url = baseURL + output + '&custparam_params=' + params; window.open(upload_url, "_self", "height=750,width=650,modal=yes,alwaysRaised=yes"); } displayCustomerInfo(); } else { var selector_type = "customer_issue"; currRec.setValue({ fieldId: 'custpage_selector_type', value: selector_type }); currRec.setValue({ fieldId: 'custpage_selector_number', value: customer_issue_type }); console.log('In displayCustomerIssueInfo - ' + customer_issue_type); var params = { ticket_id: parseInt(ticket_id.slice(4, 8)), selector_number: customer_issue_type, selector_type: selector_type }; params = JSON.stringify(params); var output = url.resolveScript({ deploymentId: 'customdeploy_sl_open_ticket_2', scriptId: 'customscript_sl_open_ticket_2', }); var upload_url = baseURL + output + '&custparam_params=' + params; window.open(upload_url, "_self", "height=750,width=650,modal=yes,alwaysRaised=yes"); } } /** * Updates the enquiry medium multi-select field and the enquiry count by chat, phone and email fields in the client side */ function updateEnquiryMediumAndCount() { $('.increment_enquiry_count_by_chat, .increment_enquiry_count_by_phone, .increment_enquiry_count_by_email').click(function() { console.log("Clicked increment"); //Get total enquiry count and increment by 1 var total_enquiry_count = $('#total_enquiry_count').val(); $('#total_enquiry_count').val(++total_enquiry_count); if (this.className.indexOf('increment_enquiry_count_by_chat') !== -1) { console.log("In chat click"); //Get chat enquiry count and increment by 1 var enquiry_count_by_chat = $('#enquiry_count_by_chat').val(); $('#enquiry_count_by_chat').val(++enquiry_count_by_chat); //Select the chat option in medium list $('#enquiry_medium_status option[value="3"]').prop('selected', true); } if (this.className.indexOf('increment_enquiry_count_by_phone') !== -1) { //Get phone enquiry count and increment by 1 var enquiry_count_by_phone = $('#enquiry_count_by_phone').val(); $('#enquiry_count_by_phone').val(++enquiry_count_by_phone); //Select the phone option in medium list $('#enquiry_medium_status option[value="1"]').prop('selected', true); } if (this.className.indexOf('increment_enquiry_count_by_email') !== -1) { //Get email enquiry count and increment by 1 var enquiry_count_by_email = $('#enquiry_count_by_email').val(); $('#enquiry_count_by_email').val(++enquiry_count_by_email); //Select the email option in medium list $('#enquiry_medium_status option[value="2"]').prop('selected', true); } //Get medium list and update it var medium_list = $('#enquiry_medium_status option:selected').map(function() { return $(this).val() }); medium_list = $.makeArray(medium_list); $('#enquiry_medium_status').val(medium_list).trigger('change'); }); $('.decrement_enquiry_count_by_chat, .decrement_enquiry_count_by_phone, .decrement_enquiry_count_by_email').click(function() { var total_enquiry_count = $('#total_enquiry_count').val(); if (this.className.indexOf('decrement_enquiry_count_by_chat') !== -1) { var enquiry_count_by_chat = $('#enquiry_count_by_chat').val(); if (enquiry_count_by_chat > 0) { $('#enquiry_count_by_chat').val(--enquiry_count_by_chat); $('#total_enquiry_count').val(--total_enquiry_count); } if (enquiry_count_by_chat === 0) { //Unselect medium list option $('#enquiry_medium_status option[value="3"]').prop('selected', false); } } if (this.className.indexOf('decrement_enquiry_count_by_phone') !== -1) { var enquiry_count_by_phone = $('#enquiry_count_by_phone').val(); if (enquiry_count_by_phone > 0) { $('#enquiry_count_by_phone').val(--enquiry_count_by_phone); $('#total_enquiry_count').val(--total_enquiry_count); } if (enquiry_count_by_phone === 0) { $('#enquiry_medium_status option[value="1"]').prop('selected', false); } } if (this.className.indexOf('decrement_enquiry_count_by_email') !== -1) { var enquiry_count_by_email = $('#enquiry_count_by_email').val(); if (enquiry_count_by_email > 0) { $('#enquiry_count_by_email').val(--enquiry_count_by_email); $('#total_enquiry_count').val(--total_enquiry_count); } if (enquiry_count_by_email === 0) { $('#enquiry_medium_status option[value="2"]').prop('selected', false); } } //Get medium list and update it var medium_list = $('#enquiry_medium_status option:selected').map(function() { return $(this).val() }); medium_list = $.makeArray(medium_list); $('#enquiry_medium_status').val(medium_list).trigger('change'); }); $('.increment_interaction_count_by_chat, .increment_interaction_count_by_phone, .increment_interaction_count_by_email').click(function() { console.log("Clicked increment"); //Get total interaction count and increment by 1 var total_interaction_count = $('#total_interaction_count').val(); $('#total_interaction_count').val(++total_interaction_count); if (this.className.indexOf('increment_interaction_count_by_chat') !== -1) { console.log("In chat click"); //Get chat interaction count and increment by 1 var interaction_count_by_chat = $('#interaction_count_by_chat').val(); $('#interaction_count_by_chat').val(++interaction_count_by_chat); } if (this.className.indexOf('increment_interaction_count_by_phone') !== -1) { //Get phone interaction count and increment by 1 var interaction_count_by_phone = $('#interaction_count_by_phone').val(); $('#interaction_count_by_phone').val(++interaction_count_by_phone); } if (this.className.indexOf('increment_interaction_count_by_email') !== -1) { //Get email interaction count and increment by 1 var interaction_count_by_email = $('#interaction_count_by_email').val(); $('#interaction_count_by_email').val(++interaction_count_by_email); //Select the email option in medium list } }); $('.decrement_interaction_count_by_chat, .decrement_interaction_count_by_phone, .decrement_interaction_count_by_email').click(function() { var total_interaction_count = $('#total_interaction_count').val(); if (this.className.indexOf('decrement_interaction_count_by_chat') !== -1) { var interaction_count_by_chat = $('#interaction_count_by_chat').val(); if (interaction_count_by_chat > 0) { $('#interaction_count_by_chat').val(--interaction_count_by_chat); $('#total_interaction_count').val(--total_interaction_count); } } if (this.className.indexOf('decrement_interaction_count_by_phone') !== -1) { var interaction_count_by_phone = $('#interaction_count_by_phone').val(); if (interaction_count_by_phone > 0) { $('#interaction_count_by_phone').val(--interaction_count_by_phone); $('#total_interaction_count').val(--total_interaction_count); } if (interaction_count_by_phone === 0) { $('#interaction_medium_status option[value="1"]').prop('selected', false); } } if (this.className.indexOf('decrement_interaction_count_by_email') !== -1) { var interaction_count_by_email = $('#interaction_count_by_email').val(); if (interaction_count_by_email > 0) { $('#interaction_count_by_email').val(--interaction_count_by_email); $('#total_interaction_count').val(--total_interaction_count); } if (interaction_count_by_email === 0) { $('#interaction_medium_status option[value="2"]').prop('selected', false); } } //Get medium list and update it var medium_list = $('#interaction_medium_status option:selected').map(function() { return $(this).val() }); medium_list = $.makeArray(medium_list); $('#interaction_medium_status').val(medium_list).trigger('change'); }); } function openAndNew() { var currRec = currentRecord.get(); currRec.setValue({ fieldId: 'custpage_open_new_ticket', value: 'T' }); // Trigger the submit function. $('#submitter').trigger('click'); } function updateAndNew() { var currRec = currentRecord.get(); currRec.setValue({ fieldId: 'custpage_open_new_ticket', value: 'T' }); // Trigger the submit function. $('#submitter').trigger('click'); } /** * Function to save the medium list depending on chat, phone and email enquiry values */ function saveMediumList(enquiry_count_by_chat, enquiry_count_by_phone, enquiry_count_by_email, ticketRecord) { var medium_list = $('#enquiry_medium_status option:selected').map(function() { return $(this).val() }); medium_list = $.makeArray(medium_list); if (enquiry_count_by_phone >= 1 && medium_list.indexOf("1") === -1) { medium_list.push("1"); } if (enquiry_count_by_email >= 1 && medium_list.indexOf("2") === -1) { medium_list.push("2"); } if (enquiry_count_by_chat >= 1 && medium_list.indexOf("3") === -1) { medium_list.push("3"); } if (enquiry_count_by_phone === "0") { var index = medium_list.indexOf("1"); if (index > -1) { medium_list.splice(index, 1); } } if (enquiry_count_by_email === "0") { var index = medium_list.indexOf("2"); if (index > -1) { medium_list.splice(index, 1); } } if (enquiry_count_by_chat === "0") { var index = medium_list.indexOf("3"); if (index > -1) { medium_list.splice(index, 1); } } ticketRecord.setValue({ fieldId: 'custrecord_enquiry_medium', value: medium_list }); } /** * Triggered when a customer calls for an issue with a barcode that is not his. * Reorganize the shown sections. */ function onEscalate() { console.log("onesc"); var currRec = currentRecord.get(); currRec.setValue({ fieldId: 'custpage_selector_issue', value: 'T' }); //Set status to Escalated // currRec.setValue({ fieldId: 'custpage_ticket_status_value', value: 10) }; $('#submitter').val('Escalate to Owner'); $('#submit_ticket').val('ESCALATE TO OWNER'); // Hide the "Escalate" button $('#tbl_custpage_escalate').closest('td').hide(); $('#tbl_custpage_escalate').closest('td').prev().hide(); $('.open_and_new_ticket_btn').addClass('hide'); $('.escalate').addClass('hide'); updateButtonsWidth(); // Hide the contacts fields and contact details sections $('.daytodaycontact_section').addClass('hide'); $('.zee_main_contact_section').addClass('hide'); $('.mpex_stock_used_section').addClass('hide'); $('.final_delivery_section').addClass('hide'); $('.mpex_contact_section').addClass('hide'); $('.contacts_section').addClass('hide'); $('.reviewcontacts_section').addClass('hide'); // Hide the send email section $('#send_email_container').addClass('hide'); // Show that the Issue Customer Name, the MP Issue and the Comment are mandatory $('.mandatory').removeClass('hide'); // Show the "MP Issues" field and the "Owner" text area $('.mp_issues_section').removeClass('hide'); selectOwner(); // Hide the tickets datatable $('.tickets_datatable_section').addClass('hide'); $('#tickets-preview_wrapper').addClass('hide'); //Hide tickets enquiry section $('.ticket_enquiry_header_section').addClass('hide'); $('.enquiry_medium_section').addClass('hide'); $('.enquiry_count_breakdown_section').addClass('hide'); $('.interaction_count_breakdown_section').addClass('hide'); $('.ticket_enquiry_header_section').addClass('hide'); $('.label_section').addClass('hide'); //Hide previous emails section $('.previous_emails_header').addClass('hide'); $('.previous_emails_section').addClass('hide'); //Hide customer ticket related issues $('.ss_section').addClass('hide'); $('.browser_os_section').addClass('hide'); $('.phone_section').addClass('hide'); $('.login_email_used_section').addClass('hide'); var selector_type = currRec.getValue({ fieldId: 'custpage_selector_type' }); if (selector_type == "customer_issue") { var selector_number = currRec.getValue({ fieldId: 'custpage_selector_number' }); if (selector_number == "Customer App") { //Set current chosen option to Customer App var mp_issues_option_inline_html = '<option value="10" selected> Customer App Issue</option>'; } else if (selector_number == "Customer Portal") { //Set current chosen option to Customer Portal var mp_issues_option_inline_html = '<option value="9" selected> Customer App Issue</option>'; } else if (selector_number == "Update Label") { //Set current chosen option to Update Label var mp_issues_option_inline_html = '<option value="11" selected> Customer App Issue</option>'; } $('#mp_issues').html(mp_issues_option_inline_html); //Requires double refresh. One for the dropwdown chnage and sceond for selection $('#mp_issues').selectpicker('refresh'); $('#mp_issues').selectpicker('refresh') } } /** * If the barcode number validation raises an error, the fields are cleared. * The informations linked to the previous barcode are deleted. */ function clearFields() { $('#customer_name').val(''); // Unselect all TOLL Issues fields $('#toll_issues option:selected').each(function() { $(this).attr('selected', false); }); $('#comment').val(''); } /** * Called when "Escalate to Owner" is clicked. * Check that in case of an issue with a barcode, the mandatory fields are filled. * @param {String} selector_type * @returns {Boolean} */ function validateIssueFields(selector_type) { var alertMessage = ''; var return_value = true; var toll_issues_length = $('#toll_issues option:selected').length; var mp_issues_length = $('#mp_issues option:selected').length; var invoice_issues_length = $('#invoice_issues option:selected').length; var comment = $('#comment').val(); var usernote = $('#user_note_textarea').val(); switch (selector_type) { case 'barcode_number': if (toll_issues_length == 0) { alertMessage += 'Please select a TOLL Issue<br>'; return_value = false; } if (isNullorEmpty(comment)) { alertMessage += 'Please type a comment<br>'; return_value = false; } break; case 'invoice_number': if (invoice_issues_length == 0) { alertMessage += 'Please select an Invoice Issue<br>'; return_value = false; } if (isNullorEmpty(usernote)) { alertMessage += 'Please type a User Note<br>'; return_value = false; } break; } if (return_value == true && mp_issues_length == 0) { alertMessage += 'Please select an MP Issue<br>'; return_value = false; } if (return_value == false) { showAlert(alertMessage); } else { $('#alert').parent().hide(); } return return_value; } /** * Send the email with the information regarding the ticket to the email adresses in the array 'to'. * @param {String} selector_type * @param {Array} to * @param {Boolean} is_issue * @returns {Boolean} Whether the email was sent or not. */ function sendInformationEmailTo(selector_type, to, is_issue) { console.log("sek type", selector_type); console.log("to", to); console.log("is_issue", is_issue); // There is an issue with the barcode // The owner should be contacted. if (is_issue) { var validate_issue_fields = validateIssueFields(selector_type); if (!validate_issue_fields) { return false; } } var selector_number = $('#selector_value').val(); var customer_name = $('#customer_name').val(); var comment = $('#comment').val(); var selected_title = $('#user_note_title option:selected').text(); var usernote_textarea = $('#user_note_textarea').val(); var date = new Date(); var email_subject = 'MP Ticket issue - ' + selector_number; var email_body = ''; email_body += 'Environment : ' + runtime.envType + '\n'; email_body += 'Date & Time : ' + formatDate(date) + '\n'; switch (selector_type) { case 'barcode_number': email_body += 'Barcode Number : ' + selector_number + '\n'; break; case 'invoice_number': email_body += 'Invoice Number : ' + selector_number + '\n'; break; case 'customer_issue': email_body += 'Customer associated ticket : ' + selector_number + '\n'; break; } email_body += 'Customer Name : ' + customer_name + '\n'; switch (selector_type) { case 'barcode_number': email_body += 'TOLL Issues : '; $('#toll_issues option:selected').each(function() { email_body += $(this).text() + '\n'; }); break; case 'invoice_number': email_body += 'Invoice Issues : '; $('#invoice_issues option:selected').each(function() { email_body += $(this).text() + '\n'; }); break; } email_body += 'MP Issues : '; $('#mp_issues option:selected').each(function() { email_body += $(this).text() + '\n'; }); if (selector_type == 'invoice_number') { if (!isNullorEmpty(comment.trim())) { comment += '\n'; } var date = new Date(); var dnow = format.parse({ value: date, type: format.Type.DATETIMETZ }); var usernote = '[' + selected_title + '] - [' + userName + '] - [' + dnow + '] - ' + usernote_textarea; comment += usernote; } email_body += 'Comment : ' + comment; var cc = [] //CC email addresses // Now the escalation and information emails are sent from the user addresses. console.log("emailsend"); email.send({ author: 112209, body: email_body, recipients: to, subject: email_subject, cc: cc, }); // 112209 is from MailPlus Team return true; } /** * Redirect to the "View MP Tickets" page without saving any changes. */ function onCancel() { console.log("cancel"); var status_value = currRec.getValue({ fieldId: 'custpage_ticket_status_value' }); if (isTicketNotClosed(status_value)) { var output = url.resolveScript({ deploymentId: 'customdeploy_sl_edit_ticket_2', scriptId: 'customscript_sl_edit_ticket_2', }); var upload_url = baseURL + output; } else { var output = url.resolveScript({ deploymentId: 'customdeploy_sl_edit_closed_ticket_2', scriptId: 'customscript_sl_edit_closed_ticket_2', }); var upload_url = baseURL + output; } window.open(upload_url, "_self", "height=750,width=650,modal=yes,alwaysRaised=yes"); } /** * Function to return the customer id given a customer number * @param {*} customer_number */ function getCustomerID(customer_number) { var customer_search = search.load({ type: 'customer', id: 'customsearch_customer_name_2' }); customer_search.filters.push(search.createFilter({ name: 'entityid', operator: 'haskeywords', values: customer_number, })); var result_set = customer_search.run().getRange({ start: 0, end: 1000 }); result_set.forEach(function(search_value) { console.log("search va", search_value); }); var customerId = result_set[0].id; console.log(customerId, "custid"); return customerId; } /** * Checks that the given customer number is valid * Returns the customer record if found, else returns null */ function isCustomerNumberValid(customer_number) { if (!isNullorEmpty(customer_number)) { var customer_search = search.load({ type: 'customer', id: 'customsearch_customer_name_2' }); var new_filter = search.createFilter({ name: 'entityid', operator: 'is', values: customer_number, }) customer_search.filters.push(new_filter); try { var result_set = customer_search.run(); if (result_set.getRange({ start: 0, end: 1000 }) != null && result_set.getRange({ start: 0, end: 1000 }).length > 0) { // Customer found. return true; } else { //Customer does not exist in record showAlert('Enter a valid customer number. Customer ' + customer_number + ' does not exist'); return false; } } catch (error) { //Undefined ID error return false; } } else { showAlert('Enter a customer number'); return false; } } /** * - If the barcode record exists but there is an MP Ticket issue with the record, * the onEscalate function is called. * @return {Boolean} Whether or not all the input has been filled. */ function validateSelectorInput() { console.log('In validateSelectorInput()'); var selector_number = $('#selector_value').val().trim().toUpperCase(); $('#selector_value').val(selector_number); var selector_type = $('#selector_text').text().toLowerCase().split(' ').join('_'); console.log(selector_number); console.log(selector_type); var alertMessage = ''; var return_value = true; var keep_selector_number = false; if (isNullorEmpty(selector_number)) { switch (selector_type) { case 'invoice_number': alertMessage += 'Please enter the Invoice Number<br>'; break; case 'barcode_number': alertMessage += 'Please enter the Barcode Number<br>'; break; default: alertMessage += 'Please enter a selector number or a customer issue <br>'; } return_value = false; } if ((return_value == true) && (!checkSelectorFormat(selector_number, selector_type))) { switch (selector_type) { case 'invoice_number': alertMessage += 'The Invoice Number format is incorrect<br>'; break; case 'barcode_number': alertMessage += 'The Barcode Number format is incorrect<br>'; break; } return_value = false; } // If a ticket already exists for the barcode number, the user is redirected to the "Edit Ticket" page. if (return_value && ticketLinkedToSelector(selector_number)) { console.log('tic ket linked to barcode') var ticket_id = currRec.getValue({ fieldId: 'custpage_ticket_id' }); var params = { ticket_id: parseInt(ticket_id), selector_number: selector_number, selector_type: selector_type }; params = JSON.stringify(params); var output = url.resolveScript({ deploymentId: 'customdeploy_sl_open_ticket_2', scriptId: 'customscript_sl_open_ticket_2', }); var upload_url = baseURL + output + '&custparam_params=' + params; window.open(upload_url, "_self", "height=750,width=650,modal=yes,alwaysRaised=yes"); } if (return_value) { console.log('Escalate to owner cases'); switch (selector_type) { //Escalate to owner cases case 'invoice_number': var activeInvoiceResults = getSelectorRecords(selector_number, selector_type); if ((isNullorEmpty(activeInvoiceResults))) { alertMessage += 'No invoice record exists for the invoice number ' + selector_number + '<br>'; keep_selector_number = true; $('.customer_section').addClass('hide'); clearFields(); currRec.setValue({ fieldId: 'custpage_selector_id', value: '' }); return_value = false; } break; case 'barcode_number': var activeBarcodeResults = getSelectorRecords(selector_number, selector_type); console.log("absdhskhd"); if ((isNullorEmpty(activeBarcodeResults))) { console.log("aasnj"); alertMessage += 'No active barcode record exists for the barcode number ' + selector_number + '<br>'; // $('#mp_issues option[value="1"]').prop('selected', true); // $('#mp_issues option[value="2"]').prop('selected', true); // $('#mp_issues option[value="3"]').prop('selected', true); var mp_issues_list = [1, 2, 3]; $('#mp_issues').selectpicker('val', mp_issues_list); keep_selector_number = true; $('.customer_section').addClass('hide'); clearFields(); currRec.setValue({ fieldId: 'custpage_selector_id', value: '' }); onEscalate(); return_value = false; } console.log("baasnj"); if ((!zeeLinkedToBarcode(activeBarcodeResults))) { alertMessage += 'No franchisee is associated to the barcode ' + selector_number + '<br>'; console.log("casnj"); // $('#mp_issues option[value="1"]').prop('selected', true); // $('#mp_issues option[value="3"]').prop('selected', true); var mp_issues_list = [1, 3]; $('#mp_issues').selectpicker('val', mp_issues_list); keep_selector_number = true; $('.customer_section').addClass('hide'); clearFields(); onEscalate(); return_value = false; } console.log("adasnj"); if ((!customerLinkedToBarcode(activeBarcodeResults))) { alertMessage += 'No customer is associated to the barcode ' + selector_number + '<br>'; console.log("easnj"); //$('#mp_issues option[value="1"]').prop('selected', true); var mp_issues_list = [1]; $('#mp_issues').selectpicker('val', mp_issues_list); keep_selector_number = true; $('.customer_section').addClass('hide'); clearFields(); onEscalate(); return_value = false; } break; } } // if (return_value == false) { // if (!keep_selector_number) { // var last_correct_selector_number = currRec.getValue({ fieldId: 'custpage_selector_number' }); // $('#selector_value').val(last_correct_selector_number); // } // showAlert(alertMessage); // } else { // $('#alert').parent().hide(); // } if (return_value == false) { console.log('Lastcase'); showAlert(alertMessage); } else { $('#alert').parent().hide(); } return return_value; } /** * Displays error messages in the alert box on top of the page. * @param {String} message The message to be displayed. */ function showAlert(message) { $('#danger-alert').html('<button type="button" class="close" id="close-alert" data-dismiss="alert" aria-label="Close"><span aria-hidden="true">&times;</span></button>' + message); $('#danger-alert').parent().show(); $("#danger-alert").fadeTo(3000, 500).slideUp(500, function() { $("#danger-alert").slideUp(500); }); $('html, body').animate({ scrollTop: 0 }, 800) } /** * Check that if the selector is a barcode number, it starts with 'MPE', * followed by either 'B', 'C', 'D', 'F', 'N' or 'T', * and then finishes by 6 digits. * * If it's an invoice, it should start with 'INV' and then finishes by 6 digits. * @param {String} selector_number * @param {String} selector_type * @returns {Boolean} */ function checkSelectorFormat(selector_number, selector_type) { switch (selector_type) { case 'barcode_number': var barcodeFormat = /^MPE[BCDFNTG]\d{6}$/; var connoteFormat = /^MPXL\d{6}$/; var onlyNumbers = /^\d{20}$/; if (barcodeFormat.test(selector_number) || connoteFormat.test(selector_number) || onlyNumbers.test(selector_number)) { return true; } return false; case 'invoice_number': var invoiceFormat = /^INV\d{6}$/; return invoiceFormat.test(selector_number); } } /** * Searches for an opened ticket linked to this selector number. * The barcode record might not exist, but the ticket associated to the selector number can. * @param {String} selector_number * @returns {Boolean} */ function ticketLinkedToSelector(selector_number) { console.log("selector number", selector_number); var activeTicketFilterExpression = [ [["custrecord_barcode_number", "is", selector_number], "OR", ["altname", "is", selector_number]], 'AND', ["custrecord_ticket_status", "noneof", '3'] ]; var activeTicketsResults = search.create({ type: 'customrecord_mp_ticket', filterExpression: activeTicketFilterExpression }); activeTicketsResults.filters.push(search.createFilter({ name: 'custrecord_ticket_status', operator: search.Operator.NONEOF, values: 3 })); activeTicketsResults.filters.push(search.createFilter({ name: 'formulatext', operator: search.Operator.IS, values: selector_number, formula: '{altname}' })); if (activeTicketsResults.runPaged().count < 1) { console.log("change filters1"); activeTicketsResults.filters.pop(); activeTicketsResults.filters.push(search.createFilter({ name: 'formulatext', operator: search.Operator.IS, values: selector_number, formula: '{custrecord_barcode_number.custrecord_connote_number}' })); } if (activeTicketsResults.runPaged().count < 1) { console.log("change filters2"); activeTicketsResults.filters.pop(); activeTicketsResults.filters.push(search.createFilter({ name: 'formulatext', operator: search.Operator.IS, values: selector_number, formula: '{custrecord_barcode_number.name}' })); } var searchResultCount = activeTicketsResults.runPaged().count; console.log("CNTTTT", searchResultCount); if (isNullorEmpty(activeTicketsResults) || searchResultCount < 1) { console.log("ISNULL") return false; } else { // If an active ticket exists for the barcode number, the ticket_id is saved. // The validate function then redirects the user to its "Edit Ticket" page. var ticket_id = ''; activeTicketsResults.run().each(function(value) { console.log(value); console.log("id", value.id); ticket_id = value.id; return true; }); //console.log("AR2", activeTicketsRes); console.log("matching ticket_id", ticket_id); currRec.setValue({ fieldId: 'custpage_ticket_id', value: ticket_id }); return true; } } /** * Searches for the active barcodes records with the name `barcode_number`, * or for the active invoice records with the name `invoice_number`, * There is normally only one such record. * @param {String} selector_number * @param {String} selector_type * @returns {nlobjSearchResult[]} An array of nlobjSearchResult objects corresponding to the searched records. */ function getSelectorRecords(selector_number, selector_type) { switch (selector_type) { case 'barcode_number': var filterExpression = [ [["name", "is", selector_number], "OR", ["custrecord_connote_number", "is", selector_number]], 'AND', ["isinactive", "is", 'F'] ]; var activeBarcodeColumns = new Array(); activeBarcodeColumns[0] = search.createColumn({ name: 'custrecord_cust_prod_stock_customer', join: null, summary: null }); activeBarcodeColumns[1] = search.createColumn({ name: 'custrecord_cust_prod_stock_zee', join: null, summary: null }); activeBarcodeColumns[2] = search.createColumn({ name: 'custrecord_cust_prod_stock_toll_issues', join: null, summary: null }); activeBarcodeColumns[3] = search.createColumn({ name: 'custrecord_mp_ticket', join: null, summary: null }); activeBarcodeColumns[4] = search.createColumn({ name: 'custrecord_cust_date_stock_used', join: null, summary: null }); activeBarcodeColumns[5] = search.createColumn({ name: 'custrecord_cust_time_stock_used', join: null, summary: null }); activeBarcodeColumns[6] = search.createColumn({ name: 'custrecord_cust_prod_stock_final_del', join: null, summary: null }); activeBarcodeColumns[7] = search.createColumn({ name: 'name', join: null, summary: null }); var activeSelectorResults = search.create({ type: 'customrecord_customer_product_stock', filterExpression: filterExpression, columns: activeBarcodeColumns }); var connoteFormat = /^MPXL\d{6}$/; if (connoteFormat.test(selector_number)) { console.log('connote'); activeSelectorResults.filters.push(search.createFilter({ name: 'custrecord_connote_number', operator: search.Operator.IS, values: selector_number, })); } else { console.log('else'); activeSelectorResults.filters.push(search.createFilter({ name: 'name', operator: search.Operator.IS, values: selector_number, })); } activeSelectorResults.filters.push(search.createFilter({ name: 'isinactive', operator: search.Operator.IS, values: false, })); break; case 'invoice_number': var filterExpression = [ ["tranid", "is", selector_number] ]; var invoiceColumns = new Array(); invoiceColumns[0] = search.createColumn({ name: 'entity', join: null, summary: null }); invoiceColumns[1] = search.createColumn({ name: 'partner', join: null, summary: null }); var activeSelectorResults = search.create({ type: 'invoice', join: null, filterExpression: filterExpression, columns: invoiceColumns }); break; } console.log("abc"); console.log(activeSelectorResults); if (!isNullorEmpty(activeSelectorResults)) { var selector_id = ''; activeSelectorResults.run().each(function(search_res) { console.log("ID", search_res.id); selector_id = search_res.id; return true; }); console.log('selector_id val', selector_id); currRec.setValue({ fieldId: 'custpage_selector_id', value: selector_id }); } return activeSelectorResults; } /** * Verifies that the barcode record is associated to a customer * @param {nlobjSearchResult[]} activeBarcodeResults Result of getSelectorRecords(selector_number, selector_type) * @returns {Boolean} */ function customerLinkedToBarcode(activeBarcodeResults) { // var activeBarcodeResult = activeBarcodeResults[0]; // var customer_id = activeBarcodeResult.getValue('custrecord_cust_prod_stock_customer'); // if (isNullorEmpty(customer_id)) { // return false; // } else { // return true; // } var customer_id; activeBarcodeResults.run().each(function(search_val) { customer_id = search_val.getValue({ name: 'custrecord_cust_prod_stock_customer' }); if (isNullorEmpty(customer_id)) { return true; } else { return false; } }); if (isNullorEmpty(customer_id)) { return false; } else { return true; } } /** * Verifies that the barcode record is associated to a franchisee * @param {nlobjSearchResult[]} activeBarcodeResults Result of getSelectorRecords(selector_number, selector_type) * @returns {Boolean} */ function zeeLinkedToBarcode(activeBarcodeResults) { //var activeBarcodeResult = activeBarcodeResults[0]; var zee_id; activeBarcodeResults.run().each(function(search_val) { zee_id = search_val.getValue({name: 'custrecord_cust_prod_stock_zee' }); console.log("zee", zee_id); if (isNullorEmpty(zee_id)) { return true; } else { return false; } }); if (isNullorEmpty(zee_id)) { return false; } else { return true; } } /** * Returns the customer record for a given customer number * If record does not exist, returns null * @param {*} customer_number */ function customerLinkedToCustomerNum(customer_number) { if (!isNullorEmpty(customer_number)) { var customer_search = search.load({ type: 'customer', id: 'customsearch_customer_name_2' }); var new_filter = search.createFilter({ name: 'entityid', operator: 'haskeywords', values: customer_number, }); customer_search.filters.push(new_filter); try { var result_set = customer_search.run(); if (result_set.getRange({ start: 0, end: 1000 }) != null && result_set.getRange({ start: 0, end: 1000 }).length >= 1) { // Customer found. return result_set.getRange({ start: 0, end: 1000 })[0]; } else { // Customer does not exist in record return null; } } catch (error) { //Undefined ID error return showAlert(error); } } } /** * Displays the informations linked to a selector record. * @returns {Boolean} Whether the function worked well or not. */ function displayCustomerInfo() { console.log('In displayCustomerInfo()'); var selector_number = $('#selector_value').val().trim().toUpperCase(); currRec.setValue({ fieldId: 'custpage_selector_number', value: selector_number }); var selector_type = currRec.getValue({ fieldId: 'custpage_selector_type' }); var activeSelectorResults = getSelectorRecords(selector_number, selector_type); var activeSelectorResult; var selector_id = ''; activeSelectorResults.run().each(function(search_val) { selector_id = search_val.id; activeSelectorResult = search_val; console.log("selector_id", selector_id); }); console.log("asr", activeSelectorResult); //var selector_id = activeSelectorResult.getId(); console.log('selector_id : ', selector_id); console.log('activeSelectorResult : ', activeSelectorResult); currRec.setValue({ fieldId: 'custpage_selector_id', value: selector_id }); switch (selector_type) { case 'barcode_number': var customer_name = activeSelectorResult.getText('custrecord_cust_prod_stock_customer'); var customer_id = activeSelectorResult.getValue('custrecord_cust_prod_stock_customer'); currRec.setValue({ fieldId: 'custpage_customer_id', value: customer_id }); var zee_name = activeSelectorResult.getText('custrecord_cust_prshowAlod_stock_zee'); var zee_id = activeSelectorResult.getValue('custrecord_cust_prod_stock_zee'); var date_stock_used = activeSelectorResult.getValue('custrecord_cust_date_stock_used'); var time_stock_used = activeSelectorResult.getValue('custrecord_cust_time_stock_used'); var final_delivery_val = activeSelectorResult.getValue('custrecord_cust_prod_stock_final_del'); var final_delivery = activeSelectorResult.getText('custrecord_cust_prod_stock_final_del'); //Show the required fields $('.mpex_stock_used_section').show(); $('.final_delivery_enquiry_status_section').show(); //Update values $('#date_stock_used').val(date_stock_used); $('#time_stock_used').val(time_stock_used); $('#final_delivery').attr('data-val', final_delivery_val); $('#final_delivery').val(final_delivery); break; case 'invoice_number': var customer_name = activeSelectorResult.getText('entity'); var customer_id = activeSelectorResult.getValue('entity'); currRec.setValue({ fieldId: 'custpage_customer_id', value: customer_id }); var zee_name = activeSelectorResult.getText('partner'); var zee_id = activeSelectorResult.getValue('partner'); break; } $('#customer_name').val(customer_name); // Load customer record try { var customerRecord = record.load({ type: 'customer', id: customer_id }); var zee_id = customerRecord.getValue({ fieldId: 'partner' }); var daytodayphone = customerRecord.getValue({ fieldId: 'phone' }); var daytodayemail = customerRecord.getValue({ fieldId: 'custentity_email_service' }); var entityid = customerRecord.getValue({ fieldId: 'entityid' }); // Set new customer number value $('#customer_number_value').val(entityid); currRec.setValue({ fieldId: 'custpage_customer_number', value: entityid }); if (selector_type == 'invoice_number') { var accountsphone = customerRecord.getValue({ fieldId: 'altphone' }); var accountsemail = customerRecord.getValue({ fieldId: 'email' }); var maap_bank_account_number = customerRecord.getValue({ fieldId: 'custentity_maap_bankacctno' }); var maap_parent_bank_account_number = customerRecord.getValue({ fieldId: 'custentity_maap_bankacctno_parent' }); var selected_invoice_method_id = customerRecord.getValue({ fieldId: 'custentity_invoice_method' }); var accounts_cc_email = customerRecord.getValue({ fieldId: 'custentity_accounts_cc_email' }); var mpex_po_number = customerRecord.getValue({ fieldId: 'custentity_mpex_po' }); var customer_po_number = customerRecord.getValue({ fieldId: 'custentity11' }); var mpex_invoicing_cycle = customerRecord.getValue({ fieldId: 'custentity_mpex_invoicing_cycle' }); } // Load Franchisee record var zeeRecord = record.load({ type: 'partner', id: zee_id }); var zee_name = zeeRecord.getValue({ fieldId: 'companyname' }); var zee_main_contact_name = zeeRecord.getValue({ fieldId: 'custentity3' }); var zee_email = zeeRecord.getValue({ fieldId: 'email' }); var zee_main_contact_phone = zeeRecord.getValue({ fieldId: 'custentity2' }); $('#daytodayphone').val(daytodayphone); $('#daytodayemail').val(daytodayemail); if (selector_type == 'invoice_number') { $('#accountsphone').val(accountsphone); $('#accountsemail').val(accountsemail); $('#account_number').val(maap_bank_account_number); $('#parent_account_number').val(maap_parent_bank_account_number); // Unselect Invoice all method options fields $('#invoice_method option:selected').each(function() { $(this).attr('selected', false); }); // Select the right invoice method option $('#invoice_method option[value=' + selected_invoice_method_id + ']').prop('selected', true); $('#accounts_cc_email').val(accounts_cc_email); $('#mpex_po_number').val(mpex_po_number); $('#customer_po_number').val(customer_po_number); $('#mpex_invoicing_cycle').val(mpex_invoicing_cycle); } $('#zee_main_contact_name').val(zee_main_contact_name); $('#zee_email').val(zee_email); $('#zee_main_contact_phone').val(zee_main_contact_phone); } catch (e) { if (e instanceof error.SuiteScriptError) { if (error.name == "SSS_MISSING_REQD_ARGUMENT") { console.log('Error to load the customer record with customer_id : ' + customer_id); } } } currRec.setValue({ fieldId: 'custpage_zee_id', value: zee_id }); $('#franchisee_name').val(zee_name); // Contacts details createContactsRows(); switch (selector_type) { case 'barcode_number': // TOLL Issues // Unselect all TOLL Issues fields $('#toll_issues option:selected').each(function() { $(this).attr('selected', false); }); // Select the corresponding TOLL issues var toll_issues = activeSelectorResult.getValue({name: 'custrecord_cust_prod_stock_toll_issues' }); if (!isNullorEmpty(toll_issues)) { toll_issues = toll_issues.split(','); toll_issues.forEach(function(toll_value) { $('#toll_issues option[value=' + toll_value + ']').prop('selected', true); }); } break; case 'invoice_number': // Invoice Issues // If the ticket is not opened yet, there are no Invoice Issues yet. updateInvoicesDatatable(); break; } // Display the tickets linked to the customer in the datatable updateTicketsDatatable(); setReminderDate(); return true; } function searchTicketRecords(customer_number) { var all_ticket_search = search.load({ type: 'customrecord_mp_ticket', id: 'customsearch_ticket_by_custnum' }); var new_filter = search.createFilter({ name: 'custrecord_cust_number', operator: 'contains', values: customer_number, }) all_ticket_search.filters.push(new_filter); var tickets_result_set = all_ticket_search.run().getRange({ start: 0, end: 1000 }); var ticket_records = []; if (!isNullorEmpty(tickets_result_set)) { for (var i = 0; i < tickets_result_set.length; i++) { var ticket_id = tickets_result_set[i].getValue('name'); var cust_number = tickets_result_set[i].getValue('custrecord_cust_number'); var cust_name = tickets_result_set[i].getText('custrecord_customer1'); var barcode_num = tickets_result_set[i].getText('custrecord_barcode_number'); var invoice_num = tickets_result_set[i].getText('custrecord_invoice_number'); var customer_issue = tickets_result_set[i].getValue('custrecord_customer_issue'); var owner = tickets_result_set[i].getText('owner'); var date_created = tickets_result_set[i].getValue('created'); ticket_records.push([ticket_id, cust_number, cust_name, barcode_num, invoice_num, customer_issue, owner, date_created]); } } return ticket_records; } /** * Displays the invoices linked to the customer into a datatable. * @returns {Boolean} Whether the function worked well or not. */ function updateInvoicesDatatable() { var compid = (runtime.envType == "SANDBOX") ? '1048144_SB3' : '1048144'; var customer_id = currRec.getValue({ fieldId: 'custpage_customer_id' }); var invoice_status_filter = $('#invoices_dropdown option:selected').val(); console.log("inv filter", invoice_status_filter); var invoicesSearchResults = loadInvoicesSearch(customer_id, invoice_status_filter); $('#result_invoices').empty(); var invoicesDataSet = []; if (isNullorEmpty(invoicesSearchResults)) { if (isNullorEmpty(customer_id)) { $('#info').text('No customer is associated to this invoice.'); $('#info').parent().show(); return true; } else { try { var customerRecord = record.load({ type: record.Type.CUSTOMER, id: customer_id, isDynamic: true }); var customer_name = customerRecord.getValue({ fieldId: 'altname' }); console.log(customer_name); return true; } catch (error) { if (error instanceof error.SuiteScriptError) { if (error.name == "SSS_MISSING_REQD_ARGUMENT") { console.log('Error to load the customer record with customer_id : ' + customer_id); } } } } } var today = new Date; invoicesSearchResults.each(function(invoiceResult) { var status = invoiceResult.getValue('statusref'); if (status == invoice_status_filter) { var invoice_date = invoiceResult.getValue('trandate'); invoice_date = invoice_date.split(' ')[0]; invoice_date = dateCreated2DateSelectedFormat(invoice_date); var re = /Invoice #([\w]+)/; var invoice_number = invoiceResult.getValue('invoicenum'); invoice_number = invoice_number.replace(re, '$1'); var invoice_id = invoiceResult.id; var invoice_link = baseURL + '/app/accounting/transactions/custinvc.nl?id=' + invoice_id + '&compid=' + compid + '&cf=116&whence='; invoice_number = '<a href="' + invoice_link + '">' + invoice_number + '</a>'; var status_text = invoiceResult.getText('statusref'); var invoice_type = invoiceResult.getText('custbody_inv_type'); var amount_due = invoiceResult.getValue('amountremaining'); var total_amount = invoiceResult.getValue('total'); var due_date_string = invoiceResult.getValue('duedate'); var overdue = ''; if (!isNullorEmpty(due_date_string)) { due_date = stringToDate(due_date_string); var days_overdue = Math.ceil((today - due_date) / 86400000); if (days_overdue > 0) { overdue = days_overdue + ' days (' + due_date_string + ')'; } else { overdue = 'Due date : ' + due_date_string; } } amount_due = financial(amount_due); total_amount = financial(total_amount); invoicesDataSet.push([invoice_date, invoice_number, status_text, invoice_type, amount_due, total_amount, overdue, invoice_id]); } return true; }); // Update datatable rows. var datatable = $('#invoices-preview').DataTable(); datatable.clear(); datatable.rows.add(invoicesDataSet); datatable.draw(); $('[data-toggle="tooltip"]').tooltip(); return true; } /** * Update the headers of the tickets preview datatable, depending on the selector_type. * @param {String} selector_type */ function updateTicketsDatatableHeaders(selector_type) { var table = $('#tickets-preview').DataTable(); var header_cells = table.columns([3, 5, 6]).header().to$(); switch (selector_type) { case 'barcode_number': $.each(header_cells, function(index) { switch (index) { case 0: $(this).text('Barcode Number'); break; case 1: $(this).text('TOLL Issues'); break; case 2: $(this).text('Resolved TOLL Issues'); break; default: break; } }); break; case 'invoice_number': $.each(header_cells, function(index) { switch (index) { case 0: $(this).text('Invoice Number'); break; case 1: $(this).text('Invoice Issues'); break; case 2: $(this).text('Resolved Invoice Issues'); break; default: break; } }); break; } } /** * Displays the tickets linked to the customer into a datatable. * @returns {Boolean} Whether the function worked well or not. */ function updateTicketsDatatable() { var customer_id = currRec.getValue({ fieldId: 'custpage_customer_id' }); var selector_type = currRec.getValue({ fieldId: 'custpage_selector_type' }); var ticketSearchResults = loadTicketsSearch(customer_id); if (!isNullorEmpty(ticketSearchResults)) { ticketSearchResults.filters.push( search.createFilter({ name: 'custrecord_customer1', operator: search.Operator.IS, values: customer_id, }) ); } //console.log("cnt", searchResultCount); console.log('update tickets datatable'); updateTicketsDatatableHeaders(selector_type); $('#result_tickets').empty(); var ticketsDataSet = []; if (isNullorEmpty(ticketSearchResults)) { if (isNullorEmpty(customer_id)) { $('#info').text('No customer is associated to this ticket.'); $('#info').parent().show(); return true; } else { try { var customerRecord = record.load({ type: 'customer', id: customer_id }); var customer_name = customerRecord.getValue({ fieldId: 'altname' }); $('#info').text('No ticket exists for the customer ' + customer_name); $('#info').parent().show(); return true; } catch (e) { if (e instanceof error.SuiteScriptError) { if (e.name == "SSS_MISSING_REQD_ARGUMENT") { console.log('Error to load the customer record with customer_id : ' + customer_id); } } } } } ticketSearchResults.run().each(function(ticketResult) { switch (selector_type) { case 'barcode_number': var ticket_id = ticketResult.getValue('name'); var date_created = ticketResult.getValue('created'); var date_closed = ticketResult.getValue('custrecord_date_closed'); var barcode_number = ticketResult.getText('custrecord_barcode_number'); var status = ticketResult.getText('custrecord_ticket_status'); var toll_issues = ticketResult.getText('custrecord_toll_issues'); toll_issues = toll_issues.split(',').join('<br>'); var resolved_toll_issues = ticketResult.getText('custrecord_resolved_toll_issues'); resolved_toll_issues = resolved_toll_issues.split(',').join('<br>'); var comment = ticketResult.getValue('custrecord_comment'); ticketsDataSet.push([ticket_id, date_created, date_closed, barcode_number, status, toll_issues, resolved_toll_issues, comment]); break; case 'invoice_number': var ticket_id = ticketResult.getValue('name'); var date_created = ticketResult.getValue('created'); var date_closed = ticketResult.getValue('custrecord_date_closed'); var re = /Invoice #([\w]+)/; var invoice_number = ticketResult.getText('custrecord_invoice_number'); invoice_number = invoice_number.replace(re, '$1'); var status = ticketResult.getText('custrecord_ticket_status'); var invoice_issues = ticketResult.getText('custrecord_invoice_issues'); invoice_issues = invoice_issues.split(',').join('<br>'); var resolved_invoice_issues = ticketResult.getText('custrecord_resolved_invoice_issues'); resolved_invoice_issues = resolved_invoice_issues.split(',').join('<br>'); var comment = ticketResult.getValue('custrecord_comment'); comment = comment.split('\n').join('<br>'); ticketsDataSet.push([ticket_id, date_created, date_closed, invoice_number, status, invoice_issues, resolved_invoice_issues, comment]); break; } return true; }); // Update datatable rows. var datatable = $('#tickets-preview').dataTable().api(); datatable.clear(); datatable.rows.add(ticketsDataSet); datatable.draw(); return true; } /** * Load the result set of the invoices records linked to the customer. * @param {String} customer_id * @param {String} invoice_status * @return {nlobjSearchResultSet} invoicesResultSet */ // function loadInvoicesSearch(customer_id, invoice_status) { // if (!isNullorEmpty(customer_id)) { // var invoicesSearch = search.load({ type: 'invoice', id: 'customsearch_mp_ticket_invoices_datatabl' }); // var invoicesFilterExpression = invoicesSearch.filterExpression; // invoicesFilterExpression.push('AND', ['entity', 'is', customer_id]); // if (invoice_status == 'open') { // invoicesFilterExpression.push('AND', ["status", "anyof", "CustInvc:A"]); // Open Invoices // } else if (invoice_status == 'paidInFull') { // invoicesFilterExpression.push('AND', ["status", "anyof", "CustInvc:B"]); // Paid in Full // var today_date = new Date(); // var today_day = today_date.getDate(); // var today_month = today_date.getMonth(); // var today_year = today_date.getFullYear(); // var date_3_months_ago = new Date(Date.UTC(today_year, today_month - 3, today_day)); // var date_3_months_ago_string = format.parse({ value: date_3_months_ago, type: format.Type.DATE }); // invoicesFilterExpression.push('AND', ["trandate", "after", date_3_months_ago_string]); // } // console.log('invoicesFilterExpression : ', invoicesFilterExpression); // invoicesSearch.filterExpression = invoicesFilterExpression; // invoicesResultSet = invoicesSearch.run(); // } // console.log("inv res set", invoicesResultSet) // return invoicesResultSet; // } /** * Load the result set of the invoices records linked to the customer. * @param {String} customer_id * @param {String} invoice_status * @return {nlobjSearchResultSet} invoicesResultSet */ function loadInvoicesSearch(customer_id, invoice_status) { var invoicesResultSet; if (!isNullorEmpty(customer_id)) { var invoicesSearch = search.load({ id: 'customsearch_mp_ticket_invoices_datatabl', type: search.Type.INVOICE }); var invoicesFilterExpression = invoicesSearch.filterExpression; invoicesFilterExpression.push('AND'); invoicesFilterExpression.push(['entity', search.Operator.IS, customer_id]); console.log("inv status", invoice_status); // Open Invoices if (invoice_status == 'open' || isNullorEmpty(invoice_status)) { invoicesFilterExpression.push('AND', ["status", search.Operator.ANYOF, "CustInvc:A"]); // Open Invoices } else if (invoice_status == 'paidInFull') { invoicesFilterExpression.push('AND', ["status", search.Operator.ANYOF, "CustInvc:B"]); // Paid in Full var today_date = new Date(); var today_day = today_date.getDate(); var today_month = today_date.getMonth(); var today_year = today_date.getFullYear(); var date_3_months_ago = new Date(Date.UTC(today_year, today_month - 3, today_day)); var date_3_months_ago_string = formatDate(date_3_months_ago); invoicesFilterExpression.push('AND', ["trandate", search.Operator.AFTER, date_3_months_ago_string]); } invoicesSearch.filterExpression = invoicesFilterExpression; invoicesResultSet = invoicesSearch.run(); var searchResultCount = invoicesSearch.runPaged().count; console.log("cnt", searchResultCount); } return invoicesResultSet; } /** * Load the result set of the tickets records linked to the customer. * WARNING : This method returns only 1000 results. If we want more results, we need to use a saved search * @param {String} customer_id * @return {Array} An array of nlobjSearchResult objects, containing the different ticket records. */ function loadTicketsSearch(customer_id) { var ticketSearchResults = new Array; console.log("custid", customer_id); // If a ticket is opened for a barcode that is not allocated to a customer, // there will be no customer_id. if (!isNullorEmpty(customer_id)) { var filterExpression = search.createFilter({ name: 'custrecord_customer1', operator: 'is', values: customer_id, }); var ticketsColumns = new Array(); ticketsColumns[0] = search.createColumn({ name: 'name' }); ticketsColumns[1] = search.createColumn({ name: 'created' }); ticketsColumns[2] = search.createColumn({ name: 'custrecord_date_closed' }); ticketsColumns[3] = search.createColumn({ name: 'custrecord_barcode_number' }); ticketsColumns[4] = search.createColumn({ name: 'custrecord_invoice_number' }); ticketsColumns[5] = search.createColumn({ name: 'custrecord_ticket_status' }); ticketsColumns[6] = search.createColumn({ name: 'custrecord_toll_issues' }); ticketsColumns[7] = search.createColumn({ name: 'custrecord_resolved_toll_issues' }); ticketsColumns[8] = search.createColumn({ name: 'custrecord_invoice_issues' }); ticketsColumns[9] = search.createColumn({ name: 'custrecord_resolved_invoice_issues' }); ticketsColumns[10] = search.createColumn({ name: 'custrecord_comment' }); ticketSearchResults = search.create({ type: 'customrecord_mp_ticket', filter: filterExpression, columns: ticketsColumns }); } return ticketSearchResults; } /** * Triggered by a click on the button 'ADD/EDIT CONTACTS' ('#reviewcontacts') * Open the 'ticket_contact' page with the parameters : * - Customer ID * - Barcode Number * - Script ID : 'customscript_sl_open_ticket' * - Deployment ID : 'customdeploy_sl_open_ticket' */ function addEditContact() { var customer_id = currRec.getValue({ fieldId: 'custpage_customer_id' }); if (!isNullorEmpty(customer_id)) { var selector_number = currRec.getValue({ fieldId: 'custpage_selector_number' }); var selector_type = currRec.getValue({ fieldId: 'custpage_selector_type' }); var params = { custid: parseInt(customer_id), selector_number: selector_number, selector_type: selector_type, id: 'customscript_sl_open_ticket_2', deploy: 'customdeploy_sl_open_ticket_2' }; params = JSON.stringify(params); var output = url.resolveScript({ deploymentId: 'customdeploy_sl_ticket_contact', scriptId: 'customscript_sl_ticket_contact', }) var upload_url = baseURL + output + '&params=' + params; window.open(upload_url, "_self", "height=750,width=650,modal=yes,alwaysRaised=yes"); } else { $('#info').parent().hide(); showAlert('No customer is associated to this ticket.'); } } /** * Loads the result set of all the contacts linked to a Customer. * @returns {nlobjSearchResultSet} contactsResultSet */ function loadContactsList() { var currRec = currentRecord.get(); var customer_id = currRec.getValue({ fieldId: 'custpage_customer_id' }); var contactsResultSet = []; // If a ticket is opened for a barcode that is not allocated to a customer, // there will be no customer_id. if (!isNullorEmpty(customer_id)) { var contactsSearch = search.load({ type: 'contact', id: 'customsearch_salesp_contacts' }); var contactsFilterExpression = [ ['company', 'is', customer_id], 'AND', ['isinactive', 'is', 'F'] ]; contactsSearch.filterExpression = contactsFilterExpression; contactsResultSet = contactsSearch.run(); } return contactsResultSet; } /** * Dispalys fields related to customer and frnachisee and hides the remaining. */ function displayFranchiseeInfo(customer_record) { var customer_name = customer_record.getValue('companyname'); var daytodayemail = customer_record.getValue('email'); var daytodayphone = customer_record.getValue('phone'); var zee_name = customer_record.getText('partner'); var zee_email = customer_record.getValue({ name: 'email', join: 'partner', summary: null }); var zee_contact_name = customer_record.getValue({ name: 'custentity3', join: 'partner', summary: null }); var zee_abn = customer_record.getValue({ name: 'custentity_abn_franchiserecord', join: 'partner', summary: null }); var zee_phone = customer_record.getValue({ name: 'custentity2', join: 'partner', summary: null }); //Ticket details section $('.customer_name').val(customer_name); $('#daytodayemail').val(daytodayemail); $('#daytodayphone').val(daytodayphone); $('#franchisee_name').val(zee_name); $('#zee_email').val(zee_email); $('#zee_main_contact_name').val(zee_contact_name); $('#zee_main_contact_phone').val(zee_phone); $('#zee_abn').val(zee_abn); createContactsRows(); } /** * - Populates the Contacts table by adding contacts details at each row. * - If there is a ticket_id (which means we are in edit mode), * adds the contact to the "To" field of the "Send Email" section. */ function createContactsRows() { var contactsResultSet = loadContactsList(); console.log(contactsResultSet); // Used for the Contacts Table. var inline_contacts_table_html = ''; // If a ticket is opened for a barcode that is not allocated to a customer, // there will be no contacts. if (!isNullorEmpty(contactsResultSet)) { contactsResultSet.each(function(contactResult) { var contact_id = contactResult.getValue('internalid'); var salutation = contactResult.getValue('salutation'); var first_name = contactResult.getValue('firstname'); var last_name = contactResult.getValue('lastname'); var contact_name = salutation + ' ' + first_name + ' ' + last_name; var contact_email = contactResult.getValue('email'); var contact_phone = contactResult.getValue('phone'); var contact_role_value = contactResult.getValue('contactrole'); var contact_role_text = contactResult.getText('contactrole'); var add_as_recipient_btn = '<button style="background-color: #379E8F; border-color: #379E8F" class="btn btn-success add_as_recipient glyphicon glyphicon-envelope" type="button" data-email="' + contact_email + '" data-firstname="' + first_name + '" data-contact-id="' + contact_id + '" data-toggle="tooltip" data-placement="right" title="Add as recipient"></button>'; inline_contacts_table_html += '<tr class="text-center">'; inline_contacts_table_html += '<td headers="col_name">' + contact_name + '</td>'; inline_contacts_table_html += '<td headers="col_phone">' + contact_phone + '</td>'; inline_contacts_table_html += '<td headers="col_email">' + contact_email + '</td>'; inline_contacts_table_html += '<td headers="col_role">'; inline_contacts_table_html += '<span class="role_value" hidden>' + contact_role_value + '</span>'; inline_contacts_table_html += '<span class="role_text">' + contact_role_text + '</span>'; inline_contacts_table_html += '</td>'; inline_contacts_table_html += '<td headers="col_add_as_recipient">' + add_as_recipient_btn + '</td>'; inline_contacts_table_html += '</tr>'; return true; }); } $('#contacts tbody').html(inline_contacts_table_html); } /** * Populates the Usernote table by adding the usernotes at each row. */ function createUsernoteRows(ticket_id) { // Used for the UserNote Table. var inline_usernote_table_html = ''; ticket_id = parseInt(ticket_id); var ticketRecord = record.load({ type: 'customrecord_mp_ticket', id: ticket_id }); var comment = ticketRecord.getValue({ fieldId: 'custrecord_comment' }); if (!isNullorEmpty(comment)) { var comments = comment.split('\n'); // This regExp matches any content inside brackets, that is not brackets. var re = /\[([^\[\]]+)\]/g; comments.forEach(function(value, index, comments_array) { // Iterate the array from the last element to the first, in order to display the most recent usernote on top. var nb_usernotes = comments_array.length; var usernote = comments_array[nb_usernotes - index - 1]; var usernote_array = usernote.split(' - '); var match_brackets_content_iterator = re[Symbol.matchAll](usernote); // match_brackets_content_array is an array of arrays. // Each of its element contains the matched string (with the brackets), // and the string inside the brackets (which is used for `usernote_title`, `usernote_name` and `usernote_date`. var match_brackets_content_array = Array.from(match_brackets_content_iterator, function(x) { return (x[1]) }); var usernote_title = match_brackets_content_array[0]; var usernote_name = match_brackets_content_array[1]; var usernote_date = match_brackets_content_array[2]; var usernote_text = usernote_array[usernote_array.length - 1]; inline_usernote_table_html += '<tr class="text-center">'; inline_usernote_table_html += '<td headers="col_usernote_title">' + usernote_title + '</td>'; inline_usernote_table_html += '<td headers="col_usernote_name">' + usernote_name + '</td>'; inline_usernote_table_html += '<td headers="col_usernote_date">' + usernote_date + '</td>'; inline_usernote_table_html += '<td headers="col_usernote_comment">' + usernote_text + '</td>'; inline_usernote_table_html += '</tr>'; }); } $('#user_note tbody').html(inline_usernote_table_html); } /** * Function to select TOLL emails */ function selectTollEmails() { var toll_emails = $('#send_toll option:selected').map(function() { return $(this).val() }); toll_emails = $.makeArray(toll_emails); $('toll_emails').selectpicker('val', toll_emails); } /** * Function to select the enquiry medium */ function selectEnquiryMedium() { var medium_list = $('#enquiry_medium_status option:selected').map(function() { return $(this).val() }); medium_list = $.makeArray(medium_list); $('enquiry_medium_status').selectpicker('val', medium_list); } /** * For barcode tickets currently * Based on the selected MP Issue, an Owner is allocated to the ticket. * IT issues have priority over the other issues. */ function selectOwner() { var owner_list = $('#owner option:selected').map(function() { return $(this).val() }); console.log("owner_list", owner_list) owner_list = $.makeArray(owner_list); var list_mp_ticket_issues = $('#mp_issues option:selected').map(function() { return $(this).val() }); list_mp_ticket_issues = $.makeArray(list_mp_ticket_issues); console.log(list_mp_ticket_issues); if (list_mp_ticket_issues.length != 0) { var it_issue = false; var other_issue = '0'; list_mp_ticket_issues.forEach(function(mp_ticket_issue_value) { if (mp_ticket_issue_value < 5) { it_issue = true; } else { other_issue = mp_ticket_issue_value; } }); if (it_issue) { // IT Issue owner_list = owner_list.concat([409635, 696992]); // Select Ankith Ravindran and Raine Giderson. } else if (other_issue != '0') { switch (other_issue) { case '5': // Operational Issue owner_list.push(25537); // Select Michael McDaid. break; case '6': // Finance Issue owner_list.push(280700); // Select Vira Nathania. break; case '7': // Customer Service Issue owner_list.push(386344); // Select Jessica Roberts. break; case '10': // Customer App Issue owner_list = [1132504]; // Select Rianne Mansell break; case '9': // Customer App Issue owner_list = [1132504]; // Select Rianne Mansell break; case '11': // Customer App Issue owner_list = [1132504]; // Select Rianne Mansell break; } } } $('#owner').selectpicker('val', owner_list); } /** * Function triggered when the '#template' input field is blurred. * Load the subject of the email and the body of the template. */ function loadTemplate() { var currRec = currentRecord.get(); var template_id = $('#template option:selected').val(); console.log('template_id : ', template_id); try { var templateRecord = record.load({ type: 'customrecord_camp_comm_template', id: template_id, isDynamic: true }); var template_subject = templateRecord.getValue({ fieldId: 'custrecord_camp_comm_subject' }); console.log("templateRecord", templateRecord); console.log("tempsubj", template_subject); } catch (e) { //if (e instanceof error.SuiteScriptError) { if (e.name == "SSS_MISSING_REQD_ARGUMENT") { console.log('Error to load the template with template_id : ' + template_id); } //} } var customer_id = currRec.getValue({ fieldId: 'custpage_customer_id' }); var sales_rep = encodeURIComponent(runtime.getCurrentUser().name); console.log($('#send_to')) var first_name = $('#send_to').data("firstname"); console.log(first_name) var dear = encodeURIComponent(first_name); var contact_id = ''; var contact_id_array = $('#send_to').data('contact-id'); if (!isNullorEmpty(contact_id_array)) { contact_id_array = JSON.parse(contact_id_array); if (!isNullorEmpty(contact_id_array)) { contact_id = contact_id_array[0].toString(); if (contact_id == '0' && !isNullorEmpty(contact_id[1])) { contact_id = ''; } } } console.log('contact_id : ', contact_id); var userid = encodeURIComponent(runtime.getCurrentUser().id); // var url = 'https://1048144.extforms.netsuite.com/app/site/hosting/scriptlet.nl?script=395&deploy=1&compid=1048144&h=6d4293eecb3cb3f4353e&rectype=customer&template='; // if (runtime.envType == "SANDBOX") { // var url = 'https://1048144-sb3.extforms.netsuite.com/app/site/hosting/scriptlet.nl?script=395&deploy=1&compid=1048144_SB3&h=9c35dc467fbdfafcfeaa&rectype=customer&template='; // } // url += template_id + '&recid=' + customer_id + '&salesrep=' + sales_rep + '&dear=' + dear + '&contactid=' + contact_id + '&userid=' + userid; var suiteletUrl = url.resolveScript({ scriptId: 'customscript_merge_email', deploymentId: 'customdeploy_merge_email', returnExternalUrl: true }); console.log('suiteletUrl', suiteletUrl); suiteletUrl += '&rectype=customer&template='; //var template_id = 94; // var newLeadEmailTemplateRecord = record.load({ // type: 'customrecord_camp_comm_template', // id: template_id, // isDynamic: true // }); //var templateSubject = template_subject; var emailAttach = new Object(); emailAttach['entity'] = customer_id; //https://1048144-sb3.extforms.netsuite.com/app/site/hosting/scriptlet.nl?script=395&deploy=1&compid=1048144_SB3&h=9c35dc467fbdfafcfeaa&rectype=customer&template=91&recid=780069&salesrep=Sruti%20Desai&dear=&contactid=&userid=1115209 suiteletUrl += template_id + '&recid=' + customer_id + '&salesrep=' + sales_rep + '&dear=' + dear + '&contactid=' + null + '&userid=' + userid; // var headerObj = { // name: 'Accept-Language', // value: 'en-us' // }; console.log('suiteletUrl', suiteletUrl); // var response = https.get({ // url: suiteletUrl, // }); // var emailHtml = response.body; var response = https.get({ url: suiteletUrl }); console.log("response", response); // console.log("URL", url); // suiteletUrl = http.request({ // method: http.Method.GET, // url: url, // }) // // urlCall = http.get({ // // url: url, // // }); // console.log(urlCall); var emailHtml = response.body; $('#email_body').summernote('code', emailHtml); var ticket_id = currRec.getValue({ fieldId: 'custpage_ticket_id' }); ticket_id = parseInt(ticket_id); var selector_number = currRec.getValue({ fieldId: 'custpage_selector_number' }); var subject = 'MailPlus [MPSD' + ticket_id + '] - ' + template_subject + ' - ' + selector_number; $('#subject').val(subject); } /** * Check that the fields "To", "Template" and "Subject" are non-empty. * @returns {Boolean} */ function validateEmailFields() { var alertMessage = ''; var return_value = true; var send_to_val = $('#send_to').val(); var send_toll_val = $('#send_toll').val(); if (isNullorEmpty(send_to_val) && isNullorEmpty(send_toll_val)) { return_value = false; alertMessage += 'Please select a recipient.<br>'; } var template_val = $('#template option:selected').val(); if (isNullorEmpty(template_val)) { return_value = false; alertMessage += 'Please select a template.<br>'; } else { var subject_val = $('#subject').val(); if (isNullorEmpty(subject_val)) { return_value = false; alertMessage += 'Please enter a subject.<br>'; } } if (return_value == false) { showAlert(alertMessage); } else { $('#alert').parent().hide(); } return return_value; } /** * Function to sent emails when a customer associated ticket is opened */ function sendCustomerTicketEmail(subject, ticket_id, customer_number, selector_type, selector_number, browser, os, login_email_used, sender_name, sender_phone, send_to) { console.log("in email fn ", send_to); if (isNullorEmpty(browser)) { browser = " - " }; if (isNullorEmpty(os)) { os = " - " }; if (isNullorEmpty(login_email_used)) { login_email_used = " - " }; if (isNullorEmpty(sender_name)) { sender_name = " - " }; if (isNullorEmpty(sender_phone)) { sender_phone = " - " }; var url = "https://1048144.app.netsuite.com/app/site/hosting/scriptlet.nl?script=1243&deploy=1&compid=1048144&"; if (runtime.envType == "SANDBOX") { var url = "https://1048144-sb3.app.netsuite.com/app/site/hosting/scriptlet.nl?script=1243&deploy=1&compid=1048144_SB3"; } var contactEmail = ["nnheo@example.com"]; var custparam_params = new Object(); custparam_params['ticket_id'] = parseInt(ticket_id); custparam_params['selector_number'] = selector_number; custparam_params['selector_type'] = selector_type; var ticket_url = url + "&custparam_params=" + encodeURIComponent(JSON.stringify(custparam_params)); if (isNullorEmpty(subject)){ subject = 'MPSD' + ticket_id + ' - New Customer Ticket Opened'; } var body = '' + selector_number + ' Ticket Details <br>'; body += 'Customer number : ' + customer_number + ' <br>'; body += 'Login email used : ' + login_email_used + ' <br>'; switch (selector_number) { case 'Customer App': body += 'Browser : ' + browser + ' <br>'; body += 'Operating system : ' + os + ' <br>'; break; case 'Customer Portal': body += 'Browser : ' + browser + ' <br>'; break; case 'Update Label': body += 'Sender name : ' + sender_name + ' <br>'; body += 'Sender phone : ' + sender_phone + ' <br>'; break; } body += '<a href="' + ticket_url + '"> Open ticket page </a><br>'; body += 'Next reminder time: ' + getNextReminderTime() + ' <br>'; var file = $('#screenshot_image')[0]; if (file && (typeof file.files[0] != 'undefined')) { file = file.files[0]; if ((file.type == "image/jpeg" || file.type == "image/png") && (file.name)) { var fr = new FileReader(); fr.onload = function(e) { body += '<img src=" ' + e.target.result + '">'; console.log("email send", send_to); if (!isNullorEmpty(send_to)) { email.send({ author: userId, body: body, recipients: send_to, subject: subject, cc: contactEmail, }); } } fr.readAsDataURL(file); } } else { if (!isNullorEmpty(send_to)) { console.log("email send", send_to); email.send({ author: userId, body: body, recipients: send_to, subject: subject, cc: contactEmail, }) } } console.log("EMAIL WORKED"); } /** * Triggered by a click on the button 'SEND EMAIL' ('#send_email') * Send the selected email to the selected contact, and reloads the page. */ function sendEmail() { if (validateEmailFields()) { // Send Email // Convert "TO" text field to email adresses array var send_to_values = $('#send_to').val().split(','); var send_to = []; if (!isNullorEmpty(send_to_values)) { send_to_values.forEach(function(email_address) { email_address = email_address.trim(); if (!isNullorEmpty(email_address)) { send_to.push(email_address); } }); } console.log("send_to", send_to); var send_toll_values = $('#send_toll').val(); var send_toll_to = []; if (!isNullorEmpty(send_toll_values)) { for (var i = 0; i < send_toll_values.length; i++) { send_toll_to.push($('#send_toll option:selected').val(send_toll_values)[i].text); } } // CC Field var cc_values = $('#send_cc').val().split(','); var cc = []; cc_values.forEach(function(email_address) { cc.push(email_address.trim()); return true; }); if (isNullorEmpty(cc)) { cc = null; } console.log("cc", cc); // BCC Field var bcc_values = $('#send_bcc').val().split(','); var bcc = []; bcc_values.forEach(function(email_address) { bcc.push(email_address.trim()); return true; }); if (isNullorEmpty(bcc)) { bcc = null; } console.log("bcc", bcc); var email_subject = $('#subject').val(); var email_body = $('#email_body').summernote('code'); var customer_id = currRec.getValue({ fieldId: 'custpage_customer_id' }); var ticket_id = currRec.getValue({ fieldId: 'custpage_ticket_id' }); ticket_id = parseInt(ticket_id); var params_email = currRec.getValue({ fieldId: 'custpage_param_email' }); params_email = JSON.parse(params_email); params_email.recipient = send_to; params_email.subject = email_subject; params_email.body = encodeURIComponent(email_body); params_email.cc = cc; params_email.bcc = bcc; params_email.records = {entityId: customer_id}; var attachments_credit_memo_ids = params_email.attachments_credit_memo_ids; var attachments_usage_report_ids = params_email.attachments_usage_report_ids; var attachments_invoice_ids = params_email.attachments_invoice_ids; params_email = JSON.stringify(params_email); if (!isNullorEmpty(attachments_credit_memo_ids) || !isNullorEmpty(attachments_usage_report_ids) || !isNullorEmpty(attachments_invoice_ids)) { // Send email using the response part of this suitelet script. currRec.setValue({ fieldId: 'custpage_param_email', value: params_email }); setRecordStatusToInProgress(ticket_id); // Trigger the submit function. $('#submitter').trigger('click'); } else { send_to = send_to.concat(send_toll_to); console.log("Final send " + send_to); // If there are no attachments, it's faster to directly use nlapiSendEmail() from the client script. // console.log("email send", recipients); if (!isNullorEmpty(customer_id) && !isNullorEmpty(send_to)) { email.send({ author: userId, body: email_body, recipients: send_to, subject: email_subject, relatedRecords: { entityId: customer_id}, bcc: bcc, cc: cc, }) } else { email.send({ author: userId, body: email_body, recipients: send_to, subject: email_subject, bcc: bcc, cc: cc, }) } // 112209 is from MailPlus Team var selector_number = currRec.getValue({ fieldId: 'custpage_selector_number' }); var selector_type = currRec.getValue({ fieldId: 'custpage_selector_type' }); setRecordStatusToInProgress(ticket_id); // Reload the page var params = { ticket_id: parseInt(ticket_id), selector_number: selector_number, selector_type: selector_type, }; params = JSON.stringify(params); var output = url.resolveScript({ deploymentId: 'customdeploy_sl_open_ticket_2', scriptId: 'customscript_sl_open_ticket_2', }) var upload_url = baseURL + output + '&custparam_params=' + params; window.open(upload_url, "_self", "height=750,width=650,modal=yes,alwaysRaised=yes"); } } else { return false; } } /** * Set record status to 'In Progress'. * @param {Number} ticket_id */ function setRecordStatusToInProgress(ticket_id) { try { var ticketRecord = record.load({ type: 'customrecord_mp_ticket', id: ticket_id }); var status_value = ticketRecord.getValue({ fieldId: 'custrecord_ticket_status' }); var invoice_id = ticketRecord.getValue({ fieldId: 'custrecord_invoice_number' }); if (isNullorEmpty(status_value) || status_value == 1) { //Ticket is open var selector_number = currRec.getValue({ fieldId: 'custpage_selector_number' }); if (isFinanceRoleOnly(userRole) && !isNullorEmpty(invoice_id)) { ticketRecord.setValue({ fieldId: 'custrecord_ticket_status', value: 6 }); } else if (!isNullorEmpty(selector_number) && selector_number == "Customer App") { console.log('Setting ticket status to In progress - IT'); ticketRecord.setValue({ fieldId: 'custrecord_ticket_status', value: 4 }); //In progress - Developers } else { ticketRecord.setValue({ fieldId: 'custrecord_ticket_status', value: 2 }); } ticketRecord.setValue({ fieldId: 'custrecord_email_sent', value: true }); ticketRecord.save({ enableSourcing: true, }) } } catch (e) { console.log("e", e); //if (e instanceof error.SuiteScriptError) { if (e.name == "SSS_MISSING_REQD_ARGUMENT") { console.log('Error to Set record status to In Progress with ticket_id : ' + ticket_id); } //} } } /** * - Triggered by any changes on the TOLL Issues, Invoice Issues or MP Ticket Issues fields. * - Display the button 'CLOSE TICKET' only when there are no selected issues. * - Display the button 'CLOSE UNALLOCATED TICKET' only if the user is Ankith Ravindran or Raine Giderson * and if the issues 'No allocated customer' or 'No allocated franchisee' are selected. */ function hideCloseTicketButton() { // Check that there are no selected issues. var selector_type = currRec.getValue({ fieldId: 'custpage_selector_type' }); var toll_issues_length = $('#toll_issues option:selected').length; var invoice_issues_length = $('#invoice_issues option:selected').length; var mp_issues_length = $('#mp_issues option:selected').length; // Show the 'Close Ticket' Button switch (selector_type) { case 'barcode_number': if ((toll_issues_length == 0) && (mp_issues_length == 0)) { $('.close_ticket').removeClass('hide'); $('.close_ticket_lost').removeClass('hide'); } else { $('.close_ticket').addClass('hide'); $('.close_ticket_lost').addClass('hide'); } break; case 'invoice_number': if ((invoice_issues_length == 0) && (mp_issues_length == 0)) { $('.close_ticket').removeClass('hide'); $('.close_ticket_lost').removeClass('hide'); } else { $('.close_ticket').addClass('hide'); $('.close_ticket_lost').addClass('hide'); } break; } // Show the 'Close Unallocated' button. var mp_issues_selected = $('#mp_issues option:selected').map(function() { return $(this).val() }); mp_issues_selected = $.makeArray(mp_issues_selected); // '1' is the MP Issue 'No Allocated Customer' // '3' is the MP Issue 'No Allocated Franchisee' var is_no_allocated_mp_issue = (mp_issues_selected.indexOf('1') != -1 || mp_issues_selected.indexOf('3') != -1); // '409635' is the user ID of Ankith Ravindran // '696992' is the user ID of Raine Giderson // '766498' is the user ID of RaphaΓ«l Chalicarne var is_user_ankith_or_raine = (userId == '409635' || userId == '696992' || userId == '766498'); var can_show_close_unallocated_button = (is_no_allocated_mp_issue && is_user_ankith_or_raine); if (can_show_close_unallocated_button) { $('.close_unallocated_ticket').removeClass('hide'); } else { $('.close_unallocated_ticket').addClass('hide'); } updateButtonsWidth(); } function updateSaveRecord() { var currRec = currentRecord.get(); var status_value = currRec.getValue({ fieldId: 'custpage_ticket_status_value' }); var selector_issue = currRec.getValue({ fieldId: 'custpage_selector_issue' }); //set to T onEscalate var selector_type = currRec.getValue({ fieldId: 'custpage_selector_type' }); var customer_number = currRec.getValue({ fieldId: 'custpage_customer_number' }); var selector_number = $('#selector_value').val(); console.log('status_value' + status_value) console.log('selector_issue ' + selector_issue) console.log('selector_type ' + selector_type) console.log('selector_number ' + selector_number) if (selector_type == 'customer_issue') { if (isNullorEmpty(customer_number)) { showAlert('Please enter a customer number'); return false; } } // if (isTicketNotClosed(status_value) && !isNullorEmpty(selector_type)) { // // Barcode/Inv associated tickets - check that a TOLL Issue or an Invoice Issue has been selected. // // Customer number associated ticket - check that a customer number has been entered // switch (selector_type) { // case 'barcode_number': // var toll_issues_length = $('#toll_issues option:selected').length; // if (toll_issues_length == 0) { // showAlert('Please select a TOLL Issue<br>'); // return false; // } // break; // case 'invoice_number': // var invoice_issues_length = $('#invoice_issues option:selected').length; // if (invoice_issues_length == 0) { // showAlert('Please select an Invoice Issue<br>'); // return false; // } // break; // case 'customer_issue': // var login_email_used = $('#login_email_text').val(); // if (!isNullorEmpty(login_email_used) && !validateEmail(login_email_used)) { // showAlert('User login email format is invalid. Please enter email again <br>'); // return false; // } // break; // } // } if (role == 1005) { var owner_length = $('#owner option:selected').length; if (owner_length == 0) { showAlert('Please select an Owner<br>'); return false; } } else { var owner_length = $('#owner option:selected').length; var checkTicketOwner = currRec.getValue({ fieldId: 'custpage_ticket_id' }); if (!isNullorEmpty(checkTicketOwner)) { var checkTicketOwnerRec = record.load({ type: 'customrecord_mp_ticket', id: parseInt(checkTicketOwner) }); var owners = checkTicketOwnerRec.getValue({ fieldId: 'custrecord_owner'}); if (isNullorEmpty(owners) && owner_length == 0) { showAlert('Please select an Owner<br>'); return false; } } else { if (owner_length == 0) { showAlert('Please select an Owner<br>'); return false; } } } if (selector_issue == 'T') { var to = $('#owner option:selected').map(function() { return $(this).data('email') }); to = $.makeArray(to); var email_sent = sendInformationEmailTo(selector_type, to, true) if (!email_sent) { return false; } } var ticket_id = currRec.getValue({ fieldId: 'custpage_ticket_id' }); console.log("Ticket id = " + ticket_id); if (isNullorEmpty(ticket_id)) { var ticketRecord = record.create({ type: 'customrecord_mp_ticket', }); currRec.setValue({ fieldId: 'custpage_created_ticket', value: 'T' }); ticketRecord.setValue({ fieldId: 'custrecord_email_sent', value: false }); console.log("DOES FALSE WORK", ticketRecord.getValue({ fieldId: 'custrecord_email_sent' })) } else { ticket_id = parseInt(ticket_id); try { var ticketRecord = record.load({ type: 'customrecord_mp_ticket', id: ticket_id }); } catch (e) { if (e instanceof error.SuiteScriptError) { if (e.name == "SSS_MISSING_REQD_ARGUMENT") { console.log('Error to load the ticket record with ticket_id : ' + ticket_id); } } } } currRec.setValue({ fieldId: 'custpage_selector_number', value: selector_number }); var selector_id = currRec.getValue({ fieldId: 'custpage_selector_id' }); // Save customer number var customer_number = $('#customer_number_value').val(); console.log('Saving customer number = ' + customer_number); ticketRecord.setValue({ fieldId: 'custrecord_cust_number', value: customer_number }); // Save Enquiry status var enquiry_status_val = $('#enquiry_status option:selected').val(); if (!isNullorEmpty(enquiry_status_val)) { ticketRecord.setValue({ fieldId: 'custrecord_enquiry_status', value: enquiry_status_val }); } var attachments_hyperlink = $('#attachments').val(); if (!isNullorEmpty(attachments_hyperlink)) { ticketRecord.setValue({ fieldId: 'custrecord_mp_ticket_attachments', value: attachments_hyperlink }); } // Save Ticket Label var label = $('#label_status option:selected').val(); if (!isNullorEmpty(label)) { ticketRecord.setValue({ fieldId: 'custrecord_ticket_label', value: label }); } //Save Enquiry medium var enquiry_medium = $('#enquiry_status option:selected').val(); if (!isNullorEmpty(enquiry_medium)) { ticketRecord.setValue({ fieldId: 'custrecord_enquiry_medium', value: enquiry_medium }); } var total_enquiry_count = 0; if (!isNullorEmpty($('#enquiry_count_by_chat').val())) { total_enquiry_count += parseInt($('#enquiry_count_by_chat').val()); } if (!isNullorEmpty($('#enquiry_count_by_phone').val())) { total_enquiry_count += parseInt($('#enquiry_count_by_phone').val()); } if (!isNullorEmpty($('#enquiry_count_by_email').val())) { total_enquiry_count += parseInt($('#enquiry_count_by_email').val()); } ticketRecord.setValue({ fieldId: 'custrecord_enquiry_count', value: total_enquiry_count }); var enquiry_count_by_chat = $('#enquiry_count_by_chat').val(); if (!isNullorEmpty(enquiry_count_by_chat)) { ticketRecord.setValue({ fieldId: 'custrecord_chat_enquiry_count', value: enquiry_count_by_chat }); } var enquiry_count_by_phone = $('#enquiry_count_by_phone').val(); if (!isNullorEmpty(enquiry_count_by_phone)) { ticketRecord.setValue({ fieldId: 'custrecord_phone_enquiry_count', value: enquiry_count_by_phone }); } var enquiry_count_by_email = $('#enquiry_count_by_email').val(); if (!isNullorEmpty(enquiry_count_by_email)) { ticketRecord.setValue({ fieldId: 'custrecord_email_enquiry_count', value: enquiry_count_by_email }); } var interaction_count_by_phone = $('#interaction_count_by_phone').val(); var interaction_count_by_email = $('#interaction_count_by_email').val(); if (isNullorEmpty(ticketRecord.getValue({ fieldId: 'custrecord_first_interaction_date'}))) { if (!isNullorEmpty(interaction_count_by_email) || !isNullorEmpty(interaction_count_by_phone)) { ticketRecord.setValue({ fieldId: 'custrecord_first_interaction_date', value: new Date()}); } } if (!isNullorEmpty(interaction_count_by_phone)) { ticketRecord.setValue({ fieldId: 'custrecord_phone_interaction_count', value: interaction_count_by_phone }); } if (!isNullorEmpty(interaction_count_by_email)) { ticketRecord.setValue({ fieldId: 'custrecord_email_interaction_count', value: interaction_count_by_email }); } //Check Enquiry is Selected if (isNullorEmpty(enquiry_count_by_chat) && isNullorEmpty(enquiry_count_by_phone) && isNullorEmpty(enquiry_count_by_email)) { showAlert('Please select an Enquiry Type<br>'); return false; } else if(total_enquiry_count == 0) { showAlert('Please select an Enquiry Type<br>'); return false; } //Save Medium list saveMediumList(enquiry_count_by_chat, enquiry_count_by_phone, enquiry_count_by_email, ticketRecord); ticketRecord = setTicketStatus(ticketRecord); ticketRecord = setCreator(ticketRecord); ticketRecord.setValue({ fieldId: 'altname', value: selector_number }); var owner_email_list = $('#owner option:selected').map(function() { return $(this).data('email') }); owner_email_list = $.makeArray(owner_email_list); var zee_id = currRec.getValue({ fieldId: 'custpage_zee_id' }); ticketRecord.setValue({ fieldId: 'custrecord_zee', value: zee_id }); if (!isNullorEmpty(selector_type)) { switch (selector_type) { case 'barcode_number': ticketRecord.setValue({ fieldId: 'custrecord_barcode_number', value: selector_id }); // Save Reminder date var reminder_date = $('#reminder').val(); if (!isNullorEmpty(reminder_date)) { reminder_date = new Date(reminder_date); console.log(reminder_date); reminder_date = format.parse({ value: reminder_date, type: format.Type.DATE }); console.log("rem date", reminder_date); ticketRecord.setValue({ fieldId: 'custrecord_reminder', value: reminder_date }); } break; case 'invoice_number': ticketRecord.setValue({ fieldId: 'custrecord_invoice_number', value: selector_id }); var customer_id = currRec.getValue({ fieldId: 'custpage_customer_id' }); ticketRecord.setValue({ fieldId: 'custrecord_customer1', value: customer_id }); if (isFinanceRole(userRole)) { var daytodayemail = $('#daytodayemail').val(); var daytodayphone = $('#daytodayphone').val(); var accountsemail = $('#accountsemail').val(); var accountsphone = $('#accountsphone').val(); var selected_invoice_method_id = $('#invoice_method option:selected').val(); var accounts_cc_email = $('#accounts_cc_email').val(); var mpex_po_number = $('#mpex_po_number').val(); var customer_po_number = $('#customer_po_number').val(); var customer_terms = $('#customers_terms').val(); var selected_invoice_cycle_id = $('#mpex_invoicing_cycle option:selected').val(); var customerRecord = record.load({ type: 'customer', id: customer_id }); customerRecord.setValue({ fieldId: 'custentity_email_service', value: daytodayemail }); customerRecord.setValue({ fieldId: 'phone', value: daytodayphone }); customerRecord.setValue({ fieldId: 'email', value: accountsemail }); customerRecord.setValue({ fieldId: 'altphone', value: accountsphone }); customerRecord.setValue({ fieldId: 'custentity_invoice_method', value: selected_invoice_method_id }); customerRecord.setValue({ fieldId: 'custentity_accounts_cc_email', value: accounts_cc_email }); customerRecord.setValue({ fieldId: 'custentity_mpex_po', value: mpex_po_number }); customerRecord.setValue({ fieldId: 'custentity11', value: customer_po_number }); customerRecord.setValue({ fieldId: 'custentity_finance_terms', value: customer_terms }); customerRecord.setValue({ fieldId: 'custentity_mpex_invoicing_cycle', value: selected_invoice_cycle_id }); customerRecord.save({}) // Save Reminder date var reminder_date = $('#reminder').val(); if (!isNullorEmpty(reminder_date)) { reminder_date = new Date(reminder_date); reminder_date = format.parse({ value: reminder_date, type: format.Type.DATE }); ticketRecord.setValue({ fieldId: 'custrecord_reminder', value: reminder_date}); } } break; case 'customer_issue': var screenshot_image = currRec.getValue({ fieldId: 'custpage_ss_image' }); if (!isNullorEmpty(screenshot_image)) { ticketRecord.setValue({ fieldId: 'custrecord_screenshot', value: screenshot_image}); } var customer_id = currRec.getValue({ fieldId: 'custpage_customer_id' }); if (!isNullorEmpty(customer_id)) { ticketRecord.setValue({ fieldId: 'custrecord_customer1', value: customer_id}); } var customer_issue_type = $('#selector_value').val(); if (!isNullorEmpty(customer_issue_type)) { ticketRecord.setValue({ fieldId: 'custrecord_customer_issue', value: customer_issue_type}); } var login_email_used = $('#login_email_text').val(); if (!isNullorEmpty(login_email_used)) { ticketRecord.setValue({ fieldId: 'custrecord_login_email', value: login_email_used}); } var is_customer_number_email_sent = currRec.getValue({ fieldId: 'custpage_customer_number_email_sent' }); switch (customer_issue_type) { case 'Customer App': var phone_used = $('#phone_used').val(); if (!isNullorEmpty(phone_used)) { ticketRecord.setValue({ fieldId: 'custrecord_phone_used', value: phone_used}); } if (is_customer_number_email_sent == 'F' && !isNullorEmpty(ticket_id)) { sendCustomerTicketEmail('',ticket_id, customer_number, selector_type, selector_number, '', '', login_email_used, '', '', owner_email_list); ticketRecord.setValue({ fieldId: 'custrecord_customer_number_email_sent', value: true }); } break; case 'Customer Portal': var browser = $("#browser_value option:selected").val(); if (!isNullorEmpty(browser)) { ticketRecord.setValue({ fieldId: 'custrecord_browser', value: browser}); } var os_used = $('#os_value option:selected').val(); if (!isNullorEmpty(os_used)) { ticketRecord.setValue({ fieldId: 'custrecord_operating_system', value: os_used}); } if (is_customer_number_email_sent == 'F' && !isNullorEmpty(ticket_id)) { sendCustomerTicketEmail('',ticket_id, customer_number, selector_type, selector_number, $("#browser_value option:selected").text(), $('#os_value option:selected').text(), login_email_used, '', '', owner_email_list); ticketRecord.setValue({ fieldId: 'custrecord_customer_number_email_sent', value: true }); } break; case 'Update Label': var sender_name = $('#sender_name_text').val(); if (!isNullorEmpty(sender_name)) { ticketRecord.setValue({ fieldId: 'custrecord_sender_name', value: sender_name}); } var sender_phone = $('#sender_phone_text').val(); if (!isNullorEmpty(sender_phone)) { ticketRecord.setValue({ fieldId: 'custrecord_sender_phone', value: sender_phone}); } if (is_customer_number_email_sent == 'F' && !isNullorEmpty(ticket_id)) { sendCustomerTicketEmail('',ticket_id, customer_number, selector_type, selector_number, '', '', login_email_used, sender_name, sender_phone, owner_email_list); ticketRecord.setValue({ fieldId: 'custrecord_customer_number_email_sent', value: true }); } break; } break; } } ticketRecord = updateIssues(ticketRecord); //Owner var owner_list = new Array; $('#owner option:selected').each(function() { owner_list.push($(this).val()); }); if (!isNullorEmpty(ticket_id)) { // Send email to new owners. var old_owner_list = ticketRecord.getValue({ fieldId: 'custrecord_owner' }); if (!isNullorEmpty(old_owner_list)) { var only_new_owner_ids = []; var only_new_owner_email_address = []; owner_list.forEach(function(new_owner_id) { if (old_owner_list.indexOf(new_owner_id) == -1) { only_new_owner_ids.push(new_owner_id); only_new_owner_email_address.push($('#owner [value="' + new_owner_id + '"]').data('email')); } }) } else { var only_new_owner_ids = owner_list; var only_new_owner_email_address = []; owner_list.forEach(function(owner_id) { only_new_owner_email_address.push($('#owner [value="' + owner_id + '"]').data('email')); }) } // If there is an issue, all the owners have already received an email. if (selector_issue == 'F' && (!isNullorEmpty(only_new_owner_email_address))) { var email_sent = sendInformationEmailTo(selector_type, only_new_owner_email_address, false); if (!email_sent) { return false; } } else if (selector_type == 'customer_issue') { var login_email_used = $('#login_email_text').val(); var customer_issue_type = $('#selector_value').val(); switch (customer_issue_type) { case 'Customer App': var phone_used = $('#phone_used').val(); var os_used = $('#os_value option:selected').val(); var browser = $("#browser_value option:selected").val() sendCustomerTicketEmail('',ticket_id, customer_number, selector_type, selector_number, $("#browser_value option:selected").text(), $('#os_value option:selected').text(), login_email_used, '', '', only_new_owner_email_address); break; case 'Customer Portal': var browser = $('#browser_value').val(); sendCustomerTicketEmail('',ticket_id, customer_number, selector_type, selector_number, $("#browser_value option:selected").text(), '', login_email_used, '', '', only_new_owner_email_address); break; case 'Update Label': var sender_phone = $('#sender_phone_text').val(); var sender_name = $('#sender_name_text').val(); sendCustomerTicketEmail('',ticket_id, customer_number, selector_type, selector_number, '', '', login_email_used, sender_name, sender_phone, only_new_owner_email_address); break; } } } // Save Owner list console.log(owner_list); ticketRecord.setValue({ fieldId: 'custrecord_owner', value: owner_list }); console.log("oList", ticketRecord.getValue({ fieldId: 'custrecord_owner'})); //cxcxc // Save Comment switch (selector_type) { case 'barcode_number': var comment = $('#comment').val(); break; case 'invoice_number': var comment = ticketRecord.getValue({ fieldId: 'custrecord_comment' }); if (isNullorEmpty(comment)) { comment = '' }; var selected_title = $('#user_note_title option:selected').text(); var usernote_textarea = $('#user_note_textarea').val(); var date = new Date; var date_time_now = format.parse({ value: date, type: format.Type.DATETIMETZ}); var date_now = format.parse({ value: date, type: format.Type.DATE}); var time_now = format.parse({ value: date, type: format.Type.TIMEOFDAY}); if (!isNullorEmpty(usernote_textarea)) { if (!isNullorEmpty(comment)) { comment += '\n'; } var usernote = '[' + selected_title + '] - [' + userName + '] - [' + date_time_now + '] - ' + usernote_textarea; // Save usernote on Customer record var userNote = record.create({ type: 'note', }); userNote.setValue({ fieldId: 'title', value: selected_title}); userNote.setValue({ fieldId: 'notedate', value: date_now}); userNote.setValue({ fieldId: 'time', value: time_now}); userNote.setValue({ fieldId: 'note', value: usernote_textarea}); userNote.setValue({ fieldId: 'entity', value: customer_id}); if (!isNullorEmpty(customer_id)) { userNote.save({}) } comment += usernote; } break; case 'customer_issue': var comment = $('#comment').val(); break; } if (!isNullorEmpty(comment)) { var original_comment = ticketRecord.getValue({ fieldId: 'custrecord_comment'} ); var total_comment = $('#comment').val(); var new_comment = total_comment.split(original_comment).join(''); var new_comment = total_comment.split(original_comment).join(''); var new_comment2 = new_comment.split("\n").join(''); //"good_luck_buddy".replace(/\n/,'&').split('&') //["good","luck_buddy"] var date_netsuite = format.format({ value: new Date(), type: format.Type.DATETIME }); console.log("new_comment", new_comment); console.log("new_comment2", new_comment2); var comment_with_date = total_comment; if (!isNullorEmpty(new_comment2)) { comment_with_date = "\n" + original_comment + "\n" + date_netsuite + " - " + new_comment2 + "\n"; } console.log('comment_with_date', comment_with_date); ticketRecord.setValue({ fieldId: 'custrecord_comment', value: comment_with_date} ); } var ticket_id = ticketRecord.save({ enableSourcing: true, }); currRec.setValue({ fieldId: 'custpage_ticket_id', value: ticket_id} ); if (!isNullorEmpty(selector_id) && (selector_type == 'barcode_number')) { try { var list_toll_issues = new Array; $('#toll_issues option:selected').each(function() { list_toll_issues.push($(this).val()); }); var barcodeRecord = record.load({ type: 'customrecord_customer_product_stock', id: selector_id }); console.log("ticket_id", ticket_id); console.log("list_toll_issues", list_toll_issues); barcodeRecord.setValue({ fieldId: 'custrecord_mp_ticket', value: ticket_id} ); barcodeRecord.setValue({ fieldId: 'custrecord_cust_prod_stock_toll_issues ', value: list_toll_issues }); var rec_email = $('#receiveremail').val(); var rec_name = $('#receivername').val(); var rec_state = $('#receiverstate').val(); var rec_zip = $('#receiverzip').val(); var rec_addr1 = $('#receiveraddr1').val(); var rec_addr2 = $('#receiveraddr2').val(); var rec_city = $('#receiversuburb').val(); var rec_phone = $('#receiverphone').val(); //Check if Rec details are to be updated if (!$("#receiveremail").is(":disabled")) { if (!isNullorEmpty(rec_email)) { barcodeRecord.setValue({ fieldId: 'custrecord_receiver_email', value: rec_email }); } if (!isNullorEmpty(rec_name)) { barcodeRecord.setValue({ fieldId: 'custrecord_receiver_name', value: rec_name }); } if (!isNullorEmpty(rec_state)) { barcodeRecord.setValue({ fieldId: 'custrecord_receiver_state', value: rec_state }); } if (!isNullorEmpty(rec_zip)) { barcodeRecord.setValue({ fieldId: 'custrecord_receiver_postcode', value: rec_zip }); } if (!isNullorEmpty(rec_addr1)) { barcodeRecord.setValue({ fieldId: 'custrecord_receiver_addr1', value: rec_addr1 }); } if (!isNullorEmpty(rec_addr2)) { barcodeRecord.setValue({ fieldId: 'custrecord_receiver_addr2', value: rec_addr2 }); } if (!isNullorEmpty(rec_city)) { barcodeRecord.setValue({ fieldId: 'custrecord_receiver_suburb', value: rec_city }); } if (!isNullorEmpty(rec_phone)) { barcodeRecord.setValue({ fieldId: 'custrecord_receiver_phone', value: rec_phone }); } } barcodeRecord.save({ enableSourcing: true, }); } catch (e) { //if (e instanceof error.SuiteScriptError) { // if (e.name == "SSS_MISSING_REQD_ARGUMENT") { console.log('Error to load the barcode record with barcode_id : ' + selector_id); // } //} } } return true; } /** * Triggered by a click on the button 'UPDATE CLOSE TICKET' ('#close_ticket') * Set the date of closure, and the status as "Closed". */ function updateCloseTicket() { console.log('In update&close function'); var date = new Date; var dnow = format.parse({ value: date, type: format.Type.DATETIMETZ }); var ticket_id = currRec.getValue({ fieldId: 'custpage_ticket_id' }); ticket_id = parseInt(ticket_id); var ticketRecord = record.load({ type: 'customrecord_mp_ticket', id: ticket_id }); ticketRecord.setValue({ fieldId: 'custrecord_date_closed', value: dnow }); ticketRecord.setValue({ fieldId: 'custrecord_ticket_status', value: 3 }); ticketRecord.setValue({ fieldId: 'custrecord_mp_ticket_customer_status', value: 5 }); ticketRecord.setValue({ fieldId: 'custrecord_reminder', value: null }); console.log('All values have been set part1'); // Save issues and resolved issues ticketRecord = updateIssues(ticketRecord); var ticket_name = ticketRecord.getText({fieldId: 'name'}); var customer_barcode_number = ticketRecord.getValue({ fieldId : 'custrecord_barcode_number'}); var customer_id = ticketRecord.getValue({fieldId: 'custrecord_customer1'}); try { var barcodeRecord = record.load({ type: 'customrecord_customer_product_stock', id: customer_barcode_number, }); var receiveremail = barcodeRecord.getValue({fieldId: 'custrecord_receiver_email'}); var barcodeName = barcodeRecord.getValue({fieldId: 'name'}); console.log('All values have been set part2'); //Send Email To Customer if (!isNullorEmpty(receiveremail)) { sendCustomerEscalateEmail('MailPlus [' + ticket_name + '] - Ticket Closed - ' + barcodeName, [receiveremail], 114, customer_id); } } catch(e) { console.log("Failed to load barcode because no customer linked"); } console.log('Email sent'); ticketRecord.save({ enableSourcing: true, }) console.log('Redirecting to edit tickets page'); // Redirect to the "View MP Tickets" page var output = url.resolveScript({ deploymentId: 'customdeploy_sl_edit_ticket_2', scriptId: 'customscript_sl_edit_ticket_2', }) var upload_url = baseURL + output; window.open(upload_url, "_self", "height=750,width=650,modal=yes,alwaysRaised=yes"); } function closeTicket(selector_type, status_num) { if (selector_type == "customer_issue") { closeCustIssueTicket(selector_type, status_num); } else { closeBarcodeTicket() } } /** * Triggered by a click on the button 'CLOSE TICKET' ('#close_ticket') * Set the date of closure, and the status as "Closed". */ function closeBarcodeTicket() { if (confirm("Are you sure you want to close this ticket?\n\nThis action cannot be undone.")) { var date = new Date; var dnow = format.parse({ value: date, type: format.Type.DATETIMETZ }); updateSaveRecord(); var ticket_id = currRec.getValue({ fieldId: 'custpage_ticket_id' }); ticket_id = parseInt(ticket_id); var ticketRecord = record.load({ type: 'customrecord_mp_ticket', id: ticket_id }); var customer_id = ticketRecord.getValue({fieldId: 'custrecord_customer1'}); ticketRecord.setValue({ fieldId: 'custrecord_ticket_status', value: 3 }); ticketRecord.setValue({ fieldId: 'custrecord_date_closed', value: dnow }); ticketRecord.setValue({ fieldId: 'custrecord_mp_ticket_customer_status', value: 5 }); ticketRecord.setValue({ fieldId: 'custrecord_reminder', value: null }); // Save issues and resolved issues ticketRecord = updateIssues(ticketRecord); var ticket_name = ticketRecord.getText({fieldId: 'name'}); var customer_barcode_number = ticketRecord.getValue({ fieldId : 'custrecord_barcode_number'}); var customer_id = ticketRecord.getValue({fieldId: 'custrecord_customer1'}); try { var barcodeRecord = record.load({ type: 'customrecord_customer_product_stock', id: customer_barcode_number, }); var receiveremail = barcodeRecord.getValue({fieldId: 'custrecord_receiver_email'}); var barcodeName = barcodeRecord.getValue({fieldId: 'name'}); //Send Email To Customer if (!isNullorEmpty(receiveremail)) { sendCustomerEscalateEmail('MailPlus [' + ticket_name + '] - Ticket Closed - ' + barcodeName, [receiveremail], 114, customer_id); } } catch(e) { console.log("Failed to load barcode because no customer linked"); } ticketRecord.save({ enableSourcing: true, }) // Redirect to the "View MP Tickets" page var output = url.resolveScript({ deploymentId: 'customdeploy_sl_edit_ticket_2', scriptId: 'customscript_sl_edit_ticket_2', }) var upload_url = baseURL + output; window.open(upload_url, "_self", "height=750,width=650,modal=yes,alwaysRaised=yes"); } } function closeCustIssueTicket(selector_type, status_num) { if (confirm("Are you sure you want to close this ticket?\n\nThis action cannot be undone.")) { var ticket_id = parseInt(currRec.getValue({ fieldId: 'custpage_ticket_id' })); var ticketRecord = record.load({ type: 'customrecord_mp_ticket', id: ticket_id }); var customer_id = ticketRecord.getValue({fieldId: 'custrecord_customer1'}); var login_email = $('#login_email_text').val(); var customer_number = $('#customer_number_value').val().trim(); var creator_id = ticketRecord.getValue({fieldId: 'custrecord_creator'}); var escalated_to_it = ticketRecord.getValue({ fieldId: 'custrecord_date_escalated_it' }); if (isNullorEmpty(login_email)) { console.log('No LOGIN EMAIL'); showAlert('Please enter a valid Login Email'); return false; } if (isNullorEmpty(customer_number) && creator_id == 112209 && !isNullorEmpty(escalated_to_it) && selector_type == "customer_issue" && !isNullorEmpty(ticket_id)) { console.log('CUSTOMER NUMBER MISSING'); showAlert('Please enter a Customer Number'); return false; } updateSaveRecord(); var ticketRecord = record.load({ type: 'customrecord_mp_ticket', id: ticket_id }); var date = new Date; var dnow = format.parse({ value: date, type: format.Type.DATETIMETZ }); ticketRecord.setValue({ fieldId: 'custrecord_date_closed', value: dnow }); if (isNullorEmpty(status_num)) { ticketRecord.setValue({ fieldId: 'custrecord_ticket_status', value: 15 }); sendCustomerEscalateEmail('MailPlus [MPSD' + ticket_id + '] - Your IT ticket has been resolved - Customer Portal', [login_email], 121, customer_id); } else { if (status_num == 15) { sendCustomerEscalateEmail('MailPlus [MPSD' + ticket_id + '] - Your IT ticket has been resolved - Customer Portal', [login_email], 121, customer_id); } ticketRecord.setValue({ fieldId: 'custrecord_ticket_status', value: status_num }); } ticketRecord.setValue({ fieldId: 'custrecord_mp_ticket_customer_status', value: 5 }); ticketRecord.setValue({ fieldId: 'custrecord_reminder', value: null }); // Save issues and resolved issues ticketRecord = updateIssues(ticketRecord); var customer_id = ticketRecord.getValue({fieldId: 'custrecord_customer1'}); ticketRecord.save({ enableSourcing: true, }); // Redirect to the "View MP Tickets" page var output = url.resolveScript({ deploymentId: 'customdeploy_sl_edit_ticket_2', scriptId: 'customscript_sl_edit_ticket_2', }) var upload_url = baseURL + output; window.open(upload_url, "_self", "height=750,width=650,modal=yes,alwaysRaised=yes"); } } /** * Triggered by a click on the button 'CLOSE TICKET' ('#close_ticket') * Set the date of closure, and the status as "Closed". */ function closeNewTicket() { if (confirm("Are you sure you want to close this ticket and open a new ticket?\n\nThis action cannot be undone.")) { updateSaveRecord(); var date = new Date; var dnow = format.parse({ value: date, type: format.Type.DATETIMETZ }); var ticket_id = currRec.getValue({ fieldId: 'custpage_ticket_id' }); ticket_id = parseInt(ticket_id); var ticketRecord = record.load({ type: 'customrecord_mp_ticket', id: ticket_id }); ticketRecord.setValue({ fieldId: 'custrecord_date_closed', value: dnow }); ticketRecord.setValue({ fieldId: 'custrecord_ticket_status', value: 3 }); ticketRecord.setValue({ fieldId: 'custrecord_mp_ticket_customer_status', value: 5 }); ticketRecord.setValue({ fieldId: 'custrecord_reminder', value: null }); // Save issues and resolved issues ticketRecord = updateIssues(ticketRecord); var ticket_name = ticketRecord.getText({fieldId: 'name'}); var customer_barcode_number = ticketRecord.getValue({ fieldId : 'custrecord_barcode_number'}); var customer_id = ticketRecord.getValue({fieldId: 'custrecord_customer1'}); try { var barcodeRecord = record.load({ type: 'customrecord_customer_product_stock', id: customer_barcode_number, }); var receiveremail = barcodeRecord.getValue({fieldId: 'custrecord_receiver_email'}); var barcodeName = barcodeRecord.getValue({fieldId: 'name'}); //Send Email To Customer if (!isNullorEmpty(receiveremail)) { sendCustomerEscalateEmail('MailPlus [' + ticket_name + '] - Ticket Closed - ' + barcodeName, [receiveremail], 114, customer_id); } } catch(e) { console.log("Failed to load barcode because no customer linked"); } ticketRecord.save({ enableSourcing: true, }) // Redirect to the Open New Ticket" page // var output = url.resolveScript({ // deploymentId: 'customdeploy_sl_edit_ticket_2', // scriptId: 'customscript_sl_edit_ticket_2', // }) var output = url.resolveScript({ deploymentId: 'customdeploy_sl_open_ticket_2', scriptId: 'customscript_sl_open_ticket_2', }); var upload_url = baseURL + output; window.open(upload_url, "_self", "height=750,width=650,modal=yes,alwaysRaised=yes"); } } /** * Triggered by a click on the button 'CLOSE TICKET - LOST ITEM' ('#close_ticket_lost') * Set the date of closure, and the status as "Closed - Lost Item". */ function closeTicketLost() { if (confirm("Are you sure you want to close this ticket and set it as Closed-Lost?\n\nThis action cannot be undone.")) { updateSaveRecord(); var date = new Date; var dnow = format.parse({ value: date, type: format.Type.DATETIMETZ }); var ticket_id = currRec.getValue({ fieldId: 'custpage_ticket_id' }); ticket_id = parseInt(ticket_id); var ticketRecord = record.load({ type: 'customrecord_mp_ticket', id: ticket_id }); ticketRecord.setValue({ fieldId: 'custrecord_date_closed', value: dnow }); ticketRecord.setValue({ fieldId: 'custrecord_ticket_status', value: 9 }); ticketRecord.setValue({ fieldId: 'custrecord_mp_ticket_customer_status', value: 5 }); ticketRecord.setValue({ fieldId: 'custrecord_reminder', value: null }); // Save issues and resolved issues ticketRecord = updateIssues(ticketRecord); ticketRecord.save({ enableSourcing: true, }); var ticket_name = ticketRecord.getText({fieldId: 'name'}); var customer_barcode_number = ticketRecord.getValue({ fieldId : 'custrecord_barcode_number'}); var customer_id = ticketRecord.getValue({fieldId: 'custrecord_customer1'}); var barcodeRecord = record.load({ type: 'customrecord_customer_product_stock', id: customer_barcode_number, }); var receiveremail = barcodeRecord.getValue({fieldId: 'custrecord_receiver_email'}); var barcodeName = barcodeRecord.getValue({fieldId: 'name'}); //Send Email To Customer if (!isNullorEmpty(receiveremail)) { sendCustomerEscalateEmail('MailPlus [' + ticket_name + '] - Lost In Transit - ' + barcodeName, [receiveremail], 113, customer_id); } var product_order = barcodeRecord.getValue({fieldId: 'custrecord_prod_stock_prod_order'}); var invoice = barcodeRecord.getValue({fieldId: 'custrecord_prod_stock_invoice'}); var userNoteId = barcodeRecord.getValue({fieldId: 'recordid'}); console.log("Invoice", invoice); console.log("product order", product_order); var params = { ticket_id: parseInt(ticket_id), selector_number: barcodeName, selector_type: 'barcode_number' }; params = JSON.stringify(params); var output = url.resolveScript({ deploymentId: 'customdeploy_sl_open_ticket_2', scriptId: 'customscript_sl_open_ticket_2', }); var ticket_url = baseURL + output + '&custparam_params=' + params; //CREDIT MEMO SECTION if (!isNullorEmpty(invoice) && isNullorEmpty(product_order)) { //Error- Send Email to Ankith body = "There's an error with the barcode as only the Invoice field is filled and the Product Order field is not (within the barcode record). Please see below barcode details\n\nMP Ticket: " + ticket_name + '\nBarcode: ' + barcodeName + '\nProduct Order: ' + product_order + '\nTicket URL: ' + ticket_url; email.send({ author: 112209, body: body, recipients: ['kenaa@example.com', 'nnheo@example.com'], subject: "Test Error MPEX Barcode Credit- LIT " + barcodeName, relatedRecords: {entityId: customer_id}, }); } else if (!isNullorEmpty(invoice) && !isNullorEmpty(product_order)) { //SEND EMAIL TO FIONA + POPIE --> change to raine after mat leave body = 'MP Ticket: ' + ticket_name + '\nBarcode: ' + barcodeName + '\nProduct Order: ' + product_order + '\nInvoice: ' + invoice + '\nTicket URL: ' + ticket_url; email.send({ author: 112209, body: body, recipients: ['kenaa@example.com', 'anpch@example.com', 'anpch@example.com'], subject: "MPEX Barcode Credit- LIT " + barcodeName, relatedRecords: {entityId: customer_id} }) } else { //SEND EMAIL TO FIONA console.log("in here"); body = 'MP Ticket: ' + ticket_name + '\nBarcode: ' + barcodeName + '\nProduct Order: ' + product_order + '\nTicket URL: ' + ticket_url; email.send({ author: 112209, body: body, recipients: ['kenaa@example.com', 'anpch@example.com'], subject: "MPEX Barcode Credit- LIT " + barcodeName, relatedRecords: {entityId: customer_id} }) } // Create User Note under Barcode Record var userNote = record.create({ type: record.Type.NOTE, isDynamic: true, }); // Record Type i.e Cust Product Stock userNote.setValue({fieldId: 'recordtype', value: 1014}); // Record ID userNote.setValue({fieldId: 'record', value: parseInt(userNoteId) }); //Title userNote.setValue({fieldId: 'title', value: 'Barcode Status- LIT'}); //Memo userNote.setValue({fieldId: 'note', value: 'Barcode ' + barcodeName + ' has been set to status Lost in Transit'}); userNote.save({ enableSourcing: true, ignoreMandatoryFields: true }); // Redirect to the "View MP Tickets" page var output = url.resolveScript({ deploymentId: 'customdeploy_sl_edit_ticket_2', scriptId: 'customscript_sl_edit_ticket_2', }) var upload_url = baseURL + output; window.open(upload_url, "_self", "height=750,width=650,modal=yes,alwaysRaised=yes"); } } /** * Triggered by a click on the button 'CLOSE UNALLOCATED TICKET' ('#close_unallocated_ticket') * Set the date of closure, and the status as "Closed - Unallocated". */ function closeUnallocatedTicket() { if (confirm("Are you sure you want to close this ticket?\n\nThis action cannot be undone.")) { updateSaveRecord(); var date = new Date; var dnow = format.parse({ value: date, type: format.Type.DATETIMETZ }); var ticket_id = currRec.getValue({ fieldId: 'custpage_ticket_id' }); ticket_id = parseInt(ticket_id); var ticketRecord = record.load({ type: 'customrecord_mp_ticket', id: ticket_id }); ticketRecord.setValue({ fieldId: 'custrecord_date_closed', value: dnow }); ticketRecord.setValue({ fieldId: 'custrecord_ticket_status', value: 8 }); ticketRecord.setValue({ fieldId: 'custrecord_mp_ticket_customer_status', value: 5 }); ticketRecord.setValue({ fieldId: 'custrecord_reminder', value: null }); // Save issues and resolved issues ticketRecord = updateIssues(ticketRecord); ticketRecord.save({ enableSourcing: true, }); // Redirect to the "View MP Tickets" page var output = url.resolveScript({ deploymentId: 'customdeploy_sl_edit_ticket_2', scriptId: 'customscript_sl_edit_ticket_2', }) var upload_url = baseURL + output; window.open(upload_url, "_self", "height=750,width=650,modal=yes,alwaysRaised=yes"); } } /** * Set the status of the ticket based on the MP ticket Values. * @param {nlobjRecord} ticketRecord * @returns {nlobjRecord} ticketRecord */ function setTicketStatus(ticketRecord) { var current_status = ticketRecord.getValue({ fieldId: 'custrecord_ticket_status' }); var list_mp_ticket_issues = new Array; $('#mp_issues option:selected').each(function() { list_mp_ticket_issues.push($(this).val()); }); ticketRecord.setValue({ fieldId: 'custrecord_mp_ticket_customer_status', value: 1 }); if (currRec.getValue({ fieldId: 'custpage_selector_issue'}) == 'T') { //Set status to escalated //console.log("Changing status to escalated"); //ticketRecord.setValue({ fieldId: 'custrecord_ticket_status', value: 10 }); } else if (isNullorEmpty(current_status)) { ticketRecord.setValue({ fieldId: 'custrecord_ticket_status', value: 1 }); } else if (list_mp_ticket_issues.length != 0) { var it_issue = false; var other_issue = '0'; list_mp_ticket_issues.forEach(function(mp_ticket_issue_value) { if (mp_ticket_issue_value < 5) { it_issue = true; } else { other_issue = mp_ticket_issue_value; } }); if (it_issue) { ticketRecord.setValue({ fieldId: 'custrecord_ticket_status', value: 4 }); } else if (other_issue != '0') { switch (other_issue) { case '5': // Operational Issue ticketRecord.setValue({ fieldId: 'custrecord_ticket_status', value: 5 }); break; case '6': // Finance Issue ticketRecord.setValue({ fieldId: 'custrecord_ticket_status', value: 6 }); break; case '7': // Customer Service Issue ticketRecord.setValue({ fieldId: 'custrecord_ticket_status', value: 2 }); break; } } } else { // If there are no more MP Ticket issues, if (current_status >= 4) { var email_sent = ticketRecord.getValue({ fieldId: 'custrecord_email_sent' }); console.log(email_sent); if (email_sent) { //If an email has ever been sent to the customer, the status is updated to 'In progress - Customer service' ticketRecord.setValue({ fieldId: 'custrecord_ticket_status', value: 2 }); } else { // If no email has ever been sent to the customer, the status is updated to 'Open' ticketRecord.setValue({ fieldId: 'custrecord_ticket_status', value: 1 }); } } } return ticketRecord; } /** * Set the creator of the ticket if there is none. * @param {nlobjRecord} ticketRecord * @returns {nlobjRecord} ticketRecord */ function setCreator(ticketRecord) { var creator_id = ticketRecord.getValue({ fieldId: 'custrecord_creator' }); if (isNullorEmpty(creator_id)) { var user_id = parseInt(runtime.getCurrentUser().id); ticketRecord.setValue({ fieldId: 'custrecord_creator', value: user_id }); } return ticketRecord; } /** * If we work with a barcode ticket, the TOLL Issues and MP Ticket Issues are added to the record. * If we work with an invoice ticket, the Invoice Issues are added to the record. * If issues have been deleted from any of these fields, they are saved in the resolved fields. * @param {nlobjRecord} ticketRecord * @returns {nlobjRecord} ticketRecord */ function updateIssues(ticketRecord) { var ticket_id = currRec.getValue({ fieldId: 'custpage_ticket_id' }); var selector_type = currRec.getValue({ fieldId: 'custpage_selector_type' }); switch (selector_type) { case 'barcode_number': // Save TOLL Issues var list_toll_issues = new Array; $('#toll_issues option:selected').each(function() { list_toll_issues.push($(this).val()); }); // Save resolved TOLL Issues if (!isNullorEmpty(ticket_id)) { var old_list_toll_issues = ticketRecord.getValue({ fieldId: 'custrecord_toll_issues' }); if (!isNullorEmpty(old_list_toll_issues)) { if (typeof(old_list_toll_issues) == "string") { old_list_toll_issues = [old_list_toll_issues]; } var list_resolved_toll_issues = ticketRecord.getValue({fieldId: 'custrecord_resolved_toll_issues' }); if (isNullorEmpty(list_resolved_toll_issues)) { list_resolved_toll_issues = new Array; } else if (typeof(list_resolved_toll_issues) == "string") { list_resolved_toll_issues = [list_resolved_toll_issues]; } old_list_toll_issues.forEach(function(old_toll_issue) { // If a TOLL issue of the old list is not in the new list, // it means that the issue was resolved. if (list_toll_issues.indexOf(old_toll_issue) == -1) { list_resolved_toll_issues.push(old_toll_issue); } }); ticketRecord.setValue({ fieldId: 'custrecord_resolved_toll_issues', value: list_resolved_toll_issues }); } } console.log("list_toll_issues", list_toll_issues); ticketRecord.setValue({ fieldId: 'custrecord_toll_issues', value: list_toll_issues }); break; case 'invoice_number': // Save Invoice Issues var list_invoice_issues = new Array; $('#invoice_issues option:selected').each(function() { list_invoice_issues.push($(this).val()); }); // Save resolved INVOICE Issues if (!isNullorEmpty(ticket_id)) { var old_list_invoice_issues = ticketRecord.getValue({ fieldId: 'custrecord_invoice_issues' }); if (!isNullorEmpty(old_list_invoice_issues)) { if (typeof(old_list_invoice_issues) == "string") { old_list_invoice_issues = [old_list_invoice_issues]; } var list_resolved_invoice_issues = ticketRecord.getValue({ fieldId: 'custrecord_resolved_invoice_issues' }); if (isNullorEmpty(list_resolved_invoice_issues)) { list_resolved_invoice_issues = new Array; } else if (typeof(list_resolved_invoice_issues) == "string") { list_resolved_invoice_issues = [list_resolved_invoice_issues]; } old_list_invoice_issues.forEach(function(old_invoice_issue) { // If an invoice issue of the old list is not in the new list, // it means that the issue was resolved. if (list_invoice_issues.indexOf(old_invoice_issue) == -1) { list_resolved_invoice_issues.push(old_invoice_issue); } }); ticketRecord.setValue({ fieldId: 'custrecord_resolved_invoice_issues', value: list_resolved_invoice_issues }); } } ticketRecord.setValue({ fieldId: 'custrecord_invoice_issues', value: list_invoice_issues }); break; } // Save MP Ticket Issues var list_mp_ticket_issues = new Array; $('#mp_issues option:selected').each(function() { list_mp_ticket_issues.push($(this).val()); }); // Save resolved MP Ticket Issues if (!isNullorEmpty(ticket_id) && selector_type != "customer_issue") { var old_list_mp_ticket_issues = ticketRecord.getValue({ fieldId: 'custrecord_mp_ticket_issue' }); if (!isNullorEmpty(old_list_mp_ticket_issues)) { old_list_mp_ticket_issues = Array.from(old_list_mp_ticket_issues); var list_resolved_mp_ticket_issues = ticketRecord.getValue({ fieldId: 'custrecord_resolved_mp_ticket_issue' }); if (isNullorEmpty(list_resolved_mp_ticket_issues)) { list_resolved_mp_ticket_issues = new Array; } else { list_resolved_mp_ticket_issues = Array.from(list_resolved_mp_ticket_issues); } old_list_mp_ticket_issues.forEach(function(old_mp_ticket_issue) { // If a MP Ticket issue of the old list is not in the new list, // it means that the issue was resolved. if (list_mp_ticket_issues.indexOf(old_mp_ticket_issue) == -1) { list_resolved_mp_ticket_issues.push(old_mp_ticket_issue); } }); ticketRecord.setValue({ fieldId: 'custrecord_resolved_mp_ticket_issue', value: list_resolved_mp_ticket_issues }); } } ticketRecord.setValue({ fieldId: 'custrecord_mp_ticket_issue', value: list_mp_ticket_issues }); return ticketRecord; } /** * Triggered by a click on the button 'REOPEN TICKET' ('#reopen_ticket') * Set the ticket record as active. * Deletes the date of closure, * Set the status as "Open". */ function reopenTicket() { console.log("in reopen"); console.log("customer number"); var ticket_id = currRec.getValue({ fieldId: 'custpage_ticket_id' }); ticket_id = parseInt(ticket_id); var selector_number = currRec.getValue({ fieldId: 'custpage_selector_number' }); var selector_type = currRec.getValue({ fieldId: 'custpage_selector_type' }); var customer_number = currRec.getValue({ fieldId: 'custpage_customer_number' }); var ticketRecord = record.load({ type: 'customrecord_mp_ticket', id: ticket_id }); ticketRecord.setValue({ fieldId: 'custrecord_date_closed', value: null }); ticketRecord.setValue({ fieldId: 'custrecord_ticket_status', value: 1 }); ticketRecord.setValue({ fieldId: 'custrecord_mp_ticket_customer_status', value: 1 }); // Save Reminder date setReminderDate(); var reminder_date = $('#reminder').val(); console.log("rem3", reminder_date); if (!isNullorEmpty(reminder_date)) { reminder_date = new Date(reminder_date); reminder_date = format.parse({ value: reminder_date, type: format.Type.DATE}); ticketRecord.setValue({ fieldId: 'custrecord_reminder', value: reminder_date }); } // Set new Creator and new Owner ticketRecord.setValue({ fieldId: 'custrecord_creator', value: userId }); ticketRecord.setValue({ fieldId: 'custrecord_owner', value: [userId] }); ticketRecord.save({ enableSourcing: true, }); // Reload the page var params = { ticket_id: parseInt(ticket_id), selector_number: selector_number, selector_type: selector_type, customer_number: customer_number, }; params = JSON.stringify(params); var output = url.resolveScript({ deploymentId: 'customdeploy_sl_open_ticket_2', scriptId: 'customscript_sl_open_ticket_2', }); var upload_url = baseURL + output + '&custparam_params=' + params; window.open(upload_url, "_self", "height=750,width=650,modal=yes,alwaysRaised=yes"); console.log("in reopen"); } /** * Lookup for the Credit Memo associated to an invoice. * @returns {nlobjSearchResult[]} creditMemoResults */ function searchCreditMemo() { var selector_type = currRec.getValue({ fieldId: 'custpage_selector_type' }); if (selector_type == 'invoice_number') { var selector_id = currRec.getValue({ fieldId: 'custpage_selector_id' }); var creditMemoResults = search.create({ type: 'creditmemo', filter: [ search.createFilter({ name: 'mainline', operator: 'is', values: 'T', }), search.createFilter({ name: 'createdfrom', operator: 'is', values: selector_id, }) ], columns: [ search.createColumn({ name: 'tranid', summary: 'group' }), search.createColumn({ name: 'trandate', summary: 'group' }), search.createColumn({ name: 'entity', summary: 'group' }), search.createColumn({ name: 'createdfrom', summary: 'group' }), search.createColumn({ name: 'internalid', summary: 'group' }) ] }); return creditMemoResults.run(); } else { return null; } } /** * searchCreditMemo() searches for Credit Memos linked to the current invoice. * If there are results, they are displayed in the table '#credit_memo'. * Otherwise, the section containing the table is hidden. * @param {Number} status_value */ function createCreditMemoRows(status_value) { var inline_credit_memo_table_html = ''; var compid = (runtime.envType == "SANDBOX") ? '1048144_SB3' : '1048144'; console.log("sv", status_value); var creditMemoResults = searchCreditMemo(); if (!isNullorEmpty(creditMemoResults)) { $('.credit_memo').removeClass('hide'); creditMemoResults.each(function(creditMemoResult) { console.log("CMR", creditMemoResult); var credit_memo_number = creditMemoResult.getValue({ name:'tranid', join: null, summary: 'group' }); var credit_memo_date = creditMemoResult.getValue({ name:'trandate', join: null, summary: 'group' }); var credit_memo_customer_name = creditMemoResult.getText({ name: 'entity', join: null, summary: 'group' }); var credit_memo_customer_id = creditMemoResult.getValue({ name:'entity', join: null, summary: 'group' }); var credit_memo_customer_link = baseURL + '/app/common/entity/custjob.nl?id=' + credit_memo_customer_id; var credit_memo_created_from_id = creditMemoResult.getValue({ name:'createdfrom', join: null, summary: 'group' }); var credit_memo_created_from = creditMemoResult.getText({ name: 'createdfrom', join: null, summary: 'group' }); var invoice_link = baseURL + '/app/accounting/transactions/custinvc.nl?id=' + credit_memo_created_from_id + '&compid=' + compid + '&cf=116&whence='; var credit_memo_id = creditMemoResult.getText({ name: 'internalid', join: null, summary: 'group' }); var credit_memo_link = baseURL + '/app/accounting/transactions/custcred.nl?id=' + credit_memo_id + '&whence='; var credit_memo_url = baseURL + '/app/accounting/print/hotprint.nl?regular=T&sethotprinter=T&formnumber=106&trantype=custcred&id=' + credit_memo_id + '&label=Credit+Memo&printtype=transaction'; var credit_memo_action_button = '<button class="btn btn-success add_cm glyphicon glyphicon-plus" type="button" data-toggle="tooltip" data-placement="right" data-cm-id="' + credit_memo_id + '" data-cm-url="' + credit_memo_url + '" title="Attach to email"></button>'; inline_credit_memo_table_html += '<tr class="text-center">'; inline_credit_memo_table_html += '<td headers="credit_memo_number"><a href="' + credit_memo_link + '">' + credit_memo_number + '</a></td>'; inline_credit_memo_table_html += '<td headers="credit_memo_date">' + credit_memo_date + '</td>'; inline_credit_memo_table_html += '<td headers="credit_memo_customer"><a href="' + credit_memo_customer_link + '">' + credit_memo_customer_name + '</td>'; inline_credit_memo_table_html += '<td headers="credit_memo_invoice_number"><a href="' + invoice_link + '">' + credit_memo_created_from + '</td>'; if (isTicketNotClosed(status_value)) { inline_credit_memo_table_html += '<td headers="credit_memo_action">' + credit_memo_action_button + '</td>'; } inline_credit_memo_table_html += '</tr>'; }); } else { $('.credit_memo').addClass('hide'); } $('#credit_memo tbody').html(inline_credit_memo_table_html); // Each time the table is redrawn, we trigger tooltip for the new cells. $('[data-toggle="tooltip"]').tooltip(); } /** * In the suitelet script, if the ticket record concerns an invoice, * the associated usage reports id are saved. * The files are loaded and their filenames and url are saved into the array of objects 'usage_report_array'. * This array is parsed and if the ids are not null, a row is added to the '#usage_report' table. * Otherwise, the section containing the table is hidden. * @param {Number} status_value */ function createUsageReportRows(status_value) { var inline_usage_report_table_html = ''; var usage_report_array = currRec.getValue({ fieldId: 'custpage_usage_report_array' }); usage_report_array = JSON.parse(usage_report_array); console.log('usage_report_array : ', usage_report_array); if (!isNullorEmpty(usage_report_array)) { usage_report_array.forEach(function(usage_report_obj) { var usage_report_id = usage_report_obj.id; if (!isNullorEmpty(usage_report_id)) { var usage_report_filename = usage_report_obj.name; var usage_report_link = usage_report_obj.url; var usage_report_action_button = '<button class="btn btn-success add_ur glyphicon glyphicon-plus" type="button" data-toggle="tooltip" data-placement="right" data-ur-id="' + usage_report_id + '" title="Attach to email"></button>'; inline_usage_report_table_html += '<tr class="text-center">'; inline_usage_report_table_html += '<td headers="usage_report_filename"><a href="' + usage_report_link + '">' + usage_report_filename + '</a></td>'; if (isTicketNotClosed(status_value)) { inline_usage_report_table_html += '<td headers="usage_report_action">' + usage_report_action_button + '</td>'; } inline_usage_report_table_html += '</tr>'; } }); } else { $('.usage_report').addClass('hide'); } $('#usage_report tbody').html(inline_usage_report_table_html); // Each time the table is redrawn, we trigger tooltip for the new cells. $('[data-toggle="tooltip"]').tooltip(); } /** * Depending on the number of buttons at the end of the page, their width and offset should change. * If there are 2 buttons, they have a width of 4 cols and an offset of 2 cols. * If there are 3 buttons, they have a width of 4 cols. * If there are 4 buttons, they have a width of 3 cols. */ function updateButtonsWidth() { var nb_buttons = $('.close_reopen_submit_ticket_section .row div:not(.hide)').length; $('.close_reopen_submit_ticket_section .row div').removeClass('col-xs-offset-2'); switch (nb_buttons) { case 2: $('.close_reopen_submit_ticket_section .row div').addClass('col-xs-4'); $('.close_reopen_submit_ticket_section .row div').removeClass('col-xs-3'); $('.close_reopen_submit_ticket_section .row div:not(.hide)').eq(0).addClass('col-xs-offset-2'); break; case 3: $('.close_reopen_submit_ticket_section .row div').addClass('col-xs-4'); $('.close_reopen_submit_ticket_section .row div').removeClass('col-xs-3'); break; case 4: $('.close_reopen_submit_ticket_section .row div').removeClass('col-xs-4'); $('.close_reopen_submit_ticket_section .row div').addClass('col-xs-3'); break; } } /** * Converts the selector field into either "Invoice number"/"Barcode number"/ "Customer App" * @param {String} selector_name */ function setupSelectorInput(selector_name) { $('#selector_text').text(selector_name); switch (selector_name) { case 'INVOICE NUMBER': $('#selector_value').attr('placeholder', 'INV123456'); $('#selector_value').removeAttr('value'); $('#selector_value').removeAttr('disabled'); break; case 'BARCODE NUMBER': $('#selector_value').attr('placeholder', 'MPEN123456'); $('#selector_value').removeAttr('value'); $('#selector_value').removeAttr('disabled'); break; case 'CUSTOMER APP': $('#selector_text').text("CUSTOMER ISSUE"); $('#selector_value').attr('value', 'Customer App'); $('#selector_value').attr('disabled', 'disabled'); break; case 'CUSTOMER PORTAL': $('#selector_text').text("CUSTOMER ISSUE"); $('#selector_value').attr('value', 'Customer Portal'); $('#selector_value').attr('disabled', 'disabled'); break; case 'UPDATE LABEL': $('#selector_text').text("CUSTOMER ISSUE"); $('#selector_value').attr('value', 'Update Label'); $('#selector_value').attr('disabled', 'disabled'); break; // case 'UPDATE CUSTOMER DETAILS': // $('#selector_text').text("CUSTOMER ISSUE"); // $('#selector_value').attr('value', 'Update Customer Details'); // $('#selector_value').attr('disabled', 'disabled'); // break; } } /** * Format a date object to the string 'dd/mm/yyyy hh:mm [am/pm]' * @param {Date} date * @returns {String} date_string */ function formatDate(testDate){ console.log('testDate: '+testDate); var responseDate=format.format({value:testDate,type:format.Type.DATE}); console.log('responseDate: '+responseDate); return responseDate; } /** * Converts the date string in the "invoice_date" table to the format of "date_selected". * @param {String} invoice_date ex: '4/6/2020' * @returns {String} date ex: '2020-06-04' */ function dateCreated2DateSelectedFormat(invoice_date) { // date_created = '4/6/2020' var date_array = invoice_date.split('/'); // date_array = ["4", "6", "2020"] var year = date_array[2]; var month = date_array[1]; if (month < 10) { month = '0' + month; } var day = date_array[0]; if (day < 10) { day = '0' + day; } return year + '-' + month + '-' + day; } /** * Calculates the reminder date based on the current date and the selector_type. */ function setReminderDate() { var ticket_id = currRec.getValue({ fieldId: 'custpage_ticket_id' }); var status_value = currRec.getValue({ fieldId: 'custpage_ticket_status_value' }); if (isNullorEmpty(ticket_id) || !isTicketNotClosed(status_value)) { var selector_type = currRec.getValue({ fieldId: 'custpage_selector_type' }); var today = new Date(); var today_day_in_month = today.getDate(); var today_day_in_week = today.getDay(); var today_month = today.getMonth(); var today_year = today.getFullYear(); switch (selector_type) { case 'barcode_number': var addNbDays = 1; if (today_day_in_week == 5) { addNbDays += 2; } break; case 'invoice_number': var addNbDays = 3; if (today_day_in_week == 3 || today_day_in_week == 4 || today_day_in_week == 5) { addNbDays += 2; } break; } var reminder_date = new Date(Date.UTC(today_year, today_month, today_day_in_month + addNbDays)); reminder_date = reminder_date.toISOString().split('T')[0]; } else { ticket_id = parseInt(ticket_id); var ticketRecord = record.load({ type: 'customrecord_mp_ticket', id: ticket_id }); var ticket_reminder_date = ticketRecord.getValue({ fieldId: 'custrecord_reminder' }); var reminder_date = ''; if (!isNullorEmpty(ticket_reminder_date)) { ticket_reminder_date = format.parse({ value: ticket_reminder_date, type: format.Type.DATE }); var reminder_date_day_in_month = ticket_reminder_date.getDate(); var reminder_date_month = ticket_reminder_date.getMonth(); var reminder_date_year = ticket_reminder_date.getFullYear(); reminder_date = new Date(Date.UTC(reminder_date_year, reminder_date_month, reminder_date_day_in_month)); reminder_date = reminder_date.toISOString().split('T')[0]; } } $('#reminder').val(reminder_date); } /** * Creates the inline HTML of the Credit Memo table, * with a button for the attachments if the ticket is not closed. * @param {Number} status_value * @returns {String} inline_html_credit_memo_table */ function htmlCreditMemoTable(status_value) { var inline_html_credit_memo_table = '<table cellpadding="15" id="credit_memo" class="table table-responsive table-striped contacts tablesorter" cellspacing="0" style="width: 100%;border: 0">'; inline_html_credit_memo_table += '<thead style="color: white;background-color: #379E8F;">'; inline_html_credit_memo_table += '<tr>'; inline_html_credit_memo_table += '<th style="vertical-align: middle;text-align: center;" id="credit_memo_number">'; inline_html_credit_memo_table += '<b>CREDIT #</b>'; inline_html_credit_memo_table += '</th>'; inline_html_credit_memo_table += '<th style="vertical-align: middle;text-align: center;" id="credit_memo_date">'; inline_html_credit_memo_table += '<b>DATE</b>'; inline_html_credit_memo_table += '</th>'; inline_html_credit_memo_table += '<th style="vertical-align: middle;text-align: center;" id="credit_memo_customer">'; inline_html_credit_memo_table += '<b>CUSTOMER</b>'; inline_html_credit_memo_table += '</th>'; inline_html_credit_memo_table += '<th style="vertical-align: middle;text-align: center;" id="credit_memo_invoice_number">'; inline_html_credit_memo_table += '<b>CREATED FROM</b>'; inline_html_credit_memo_table += '</th>'; if (isTicketNotClosed(status_value)) { inline_html_credit_memo_table += '<th style="vertical-align: middle;text-align: center;" id="credit_memo_action">'; inline_html_credit_memo_table += '<b>ATTACH TO EMAIL</b>'; inline_html_credit_memo_table += '</th>'; } inline_html_credit_memo_table += '</tr>'; inline_html_credit_memo_table += '</thead>'; inline_html_credit_memo_table += '<tbody></tbody>'; inline_html_credit_memo_table += '</table>'; return inline_html_credit_memo_table; } function htmlUsageReportTable(status_value) { var inline_html_usage_report_table = '<table cellpadding="15" id="usage_report" class="table table-responsive table-striped contacts tablesorter" cellspacing="0" style="width: 100%;border: 0"><thead style="color: white;background-color: #379E8F;">'; inline_html_usage_report_table += '<tr>'; inline_html_usage_report_table += '<th style="vertical-align: middle;text-align: center;" id="usage_report_filename">'; inline_html_usage_report_table += '<b>FILE NAME</b>'; inline_html_usage_report_table += '</th>'; if (isTicketNotClosed(status_value)) { inline_html_usage_report_table += '<th style="vertical-align: middle;text-align: center;" id="usage_report_action">'; inline_html_usage_report_table += '<b>ATTACH TO EMAIL</b>'; inline_html_usage_report_table += '</th>'; } inline_html_usage_report_table += '</tr>'; inline_html_usage_report_table += '</thead>'; inline_html_usage_report_table += '<tbody></tbody>'; inline_html_usage_report_table += '</table>'; return inline_html_usage_report_table; } /** * This function is triggered when a button is clicked to attach a file. * It stores the file id in the right array of the object 'params_email'. */ function attachFileButton() { $(this).toggleClass('btn-success'); $(this).toggleClass('btn-danger'); if ($(this).attr('id') == 'add_inv') { $(this).find('span.glyphicon').toggleClass('glyphicon-minus'); $(this).find('span.glyphicon').toggleClass('glyphicon-plus'); } else { $(this).toggleClass('glyphicon-minus'); $(this).toggleClass('glyphicon-plus'); } // Tooltip seems to set the 'title' attribute to 'data-original-title'. // The only way to have tooltip take into account the change of title is to modifiy the attribute 'data-original-title'. // Using the jQuery method 'data()' doesn't work. if ($(this).attr('data-original-title') == 'Attach to email') { $(this).attr('data-original-title', 'Remove from email'); } else { $(this).attr('data-original-title', 'Attach to email'); } $('[data-toggle="tooltip"]').tooltip(); var attachment_id = ''; var attachment_ids_array_name = ''; if ($(this).hasClass('add_ur')) { attachment_id = $(this).data('ur-id'); attachment_ids_array_name = 'attachments_usage_report_ids'; } else if ($(this).hasClass('add_cm')) { attachment_id = $(this).data('cm-id'); attachment_ids_array_name = 'attachments_credit_memo_ids'; } else if ($(this).hasClass('add_inv')) { attachment_id = $(this).data('inv-id'); attachment_ids_array_name = 'attachments_invoice_ids'; } addIdToAttachmentList(attachment_ids_array_name, attachment_id); } /** * Adds or remove the id of a record to be attached (or removed) to the email that will be sent in the function sendEmail(); * @param {String} attachment_ids_array_name * @param {Number} id */ function addIdToAttachmentList(attachment_ids_array_name, id) { var params_email = currRec.getValue({ fieldId: 'custpage_param_email' }); params_email = JSON.parse(params_email); var attachment_ids_array = params_email[attachment_ids_array_name]; var index_of_id_elem = attachment_ids_array.indexOf(id); if (index_of_id_elem == -1) { attachment_ids_array.push(id); } else { attachment_ids_array.splice(index_of_id_elem, 1); } params_email[attachment_ids_array_name] = attachment_ids_array; params_email = JSON.stringify(params_email); currRec.setValue({ fieldId: 'custpage_param_email', value: params_email }); } /** * @param {Number} x * @returns {String} The same number, formatted in Australian dollars. */ function financial(x) { if (typeof(x) === 'string') { x = parseFloat(x); } if (isNullorEmpty(x)) { return "$0.00"; } else { return x.toLocaleString('en-AU', { style: 'currency', currency: 'AUD' }); } } /** * Returns whether a ticket is closed or not based on its status value. * @param {Number} status_value * @returns {Boolean} is_ticket_closed */ function isTicketNotClosed(status_value) { var is_ticket_not_closed = ((status_value != 3) && (status_value != 8)) ? true : false; return is_ticket_not_closed; } /** * Whether the user is from the finance team, * or a Data Systems Co-ordinator, MailPlus Administration or Administrator user. * @param {Number} userRole * @returns {Boolean} */ function isFinanceRole(userRole) { // 1001, 1031 and 1023 are finance roles // 1032 is the Data Systems Co-ordinator role (to be deleted in prod) // 1006 is the Mail Plus Administration role. // 3 is the Administrator role. return ((userRole == 1001 || userRole == 1031 || userRole == 1023) || ((userRole == 1032) || (userRole == 1006) || (userRole == 3))); } /** * Whether the user is from the finance team. * @param {Number} userRole * @returns {Boolean} */ function isFinanceRoleOnly(userRole) { // 1001, 1031 and 1023 are finance roles return (userRole == 1001 || userRole == 1031 || userRole == 1023); } function validateEmail(email) { var re = /^(([^<>()[\]\\.,;:\s@"]+(\.[^<>()[\]\\.,;:\s@"]+)*)|(".+"))@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/; return re.test(String(email).toLowerCase()); } function getBase64(file) { return new Promise(function(resolve) { var reader = new FileReader(); reader.onloadend = function() { resolve(reader.result) } reader.readAsDataURL(file); }); } /** * Function to get the next email reminder time. * Adds +2 hours to the current date. */ function getNextReminderTime() { var today = new Date(); //Adding 19 hours to PST will give Australia/ Sydney timezone today.setHours(today.getHours() + 19); var currentHours = today.getHours(); log.debug({ title: 'currentHours + 2', details: currentHours + 2 }); if (currentHours + 2 > 16) { //Current hours + 2 hours is past 5. next reminder will be sent the next day at 9 am today.setDate(today.getDate() + 1); today.setHours(9); today.setMinutes(0); today.setSeconds(0); } else if (currentHours + 2 < 9) { //Current hours + 2 hours is before 9 am. Edge case but this is unlikely to happen since script does not run outside 9-5 today.setHours(9); today.setMinutes(0); today.setSeconds(0); } else { // Set next reminder time to today + 2 hours today.setHours(today.getHours() + 2); } return today; } function stringToDate(val) { return format.parse({value:val, type: format.Type.DATE}) } function isNullorEmpty(strVal) { return (strVal == null || strVal == '' || strVal == 'null' || strVal == undefined || strVal == 'undefined' || strVal == '- None -'); } return { pageInit: pageInit, saveRecord: saveRecord, closeTicket: closeTicket, closeTicketLost: closeTicketLost, closeUnallocatedTicket: closeUnallocatedTicket, onEscalate: onEscalate, onCancel: onCancel }; } );
true
/** * * @NApiVersion 2.0 * @NScriptType ClientScript * * Description: A ticketing system for the Customer Service. * @Last Modified by: Sruti Desai * */ define(['N/error', 'N/runtime', 'N/search', 'N/url', 'N/record', 'N/format', 'N/email', 'N/currentRecord', 'N/https'], function(error, runtime, search, url, record, format, email, currentRecord, https) { var baseURL = 'https://1048144.app.netsuite.com'; if (runtime.envType == "SANDBOX") { baseURL = 'https://1048144-sb3.app.netsuite.com'; } var role = runtime.getCurrentUser().role; var userRole = runtime.getCurrentUser().role; var userId = runtime.getCurrentUser().id; /** * On page initialisation */ var currRec = currentRecord.get(); function pageInit() { var currRec = currentRecord.get(); //Remove Chrome's incessant "Leave Site" warning window.onbeforeunload = null; //background-colors $("#NS_MENU_ID0-item0").css("background-color", "#CFE0CE"); $("#NS_MENU_ID0-item0 a").css("background-color", "#CFE0CE"); $("#body").css("background-color", "#CFE0CE"); $("#tr_submitter").css("margin-left", "10px"); var ticketsDataSet = []; var invoicesDataSet = []; $(document).ready(function() { console.log('doc ready'); $('#email_body').summernote(); $('#owner, #toll_issues, #mp_issues, #invoice_issues, #enquiry_medium_status, #send_toll').selectpicker(); $('#tickets-preview').DataTable({ data: ticketsDataSet, columns: [{ title: "ID" }, { title: "Date created" }, { title: "Date closed" }, { title: "Barcode Number" }, { title: "Status" }, { title: "TOLL Issues" }, { title: "Resolved TOLL Issues" }, { title: "Comment" }] }); $('#emails-preview').DataTable(); var invoice_table = $('#invoices-preview').DataTable({ data: invoicesDataSet, columns: [{ title: "Invoice Date", type: "date" }, { title: "Invoice #" }, { title: "Status" }, { title: "Invoice Type" }, { title: "Amount Due", type: "num-fmt" }, { title: "Total Amount", type: "num-fmt" }, { title: "Overdue" }, { title: "Invoice ID" }, { title: "Action" }], columnDefs: [{ visible: false, targets: -2, }, { targets: -1, data: null, render: function(data, type, row, meta) { var selector_id = currRec.getValue({ fieldId: 'custpage_selector_id' }); var disabled = (data[7] == selector_id) ? 'disabled' : ''; return '<button class="btn btn-success add_inv glyphicon glyphicon-plus" type="button" data-inv-id="' + data[7] + '" data-toggle="tooltip" data-placement="right" title="Attach to email" ' + disabled + '></button>'; } }] }); $('#invoices-preview thead tr').addClass('text-center'); // Adapted from https://datatables.net/extensions/fixedheader/examples/options/columnFiltering.html // Adds a row to the table head row, and adds search filters to each column. $('#invoices-preview thead tr').clone(true).appendTo('#invoices-preview thead'); $('#invoices-preview thead tr:eq(3) th').each(function(i) { var title = $(this).text(); $(this).html('<input style="width: 80%" type="text" placeholder="Search ' + title + '" />'); $('input', this).on('keyup change', function() { if (invoice_table.column(i).search() !== this.value) { invoice_table .column(i) .search(this.value) .draw(); } }); }); //var invoice_table = $('#invoices-preview').DataTable(); invoice_table.on('click', 'button.add_inv', function() { attachFileButton.call(this) }); }); console.log('Page init'); if (window.location.search.substr(1) == "script=1243&deploy=1" || window.location.search.substr(1) == "script=976&deploy=1&compid=1048144_SB3" || window.location.search.substr(1) == "script=1243&deploy=1&compid=1048144_SB3&whence=") { currRec.setValue({ fieldId: 'custpage_selector_number', value: '' }); currRec.setValue({ fieldId: 'custpage_selector_type', value: "barcode_number"}); } var selector_number = currRec.getValue({ fieldId: 'custpage_selector_number' }); var selector_type = currRec.getValue({ fieldId: 'custpage_selector_type' }); var ticket_id = currRec.getValue({ fieldId: 'custpage_ticket_id' }); var status_value = currRec.getValue({ fieldId: 'custpage_ticket_status_value' }); var customer_number = currRec.getValue({ fieldId: 'custpage_customer_number' }); //Toggling show/hide for the tickets associated to customer number if (!isNullorEmpty(customer_number) && isNullorEmpty(selector_number)) { $('#customer_number_tickets_preview').show(); } else { $('#customer_number_tickets_preview').hide(); } // The inline html of the <table> tag is not correctly displayed inside div.col-xs-12.contacts_div when added with Suitelet. // Hence, the html code is added using jQuery when the page loads. var inline_html_contact_table = '<table cellpadding="15" id="contacts" class="table table-responsive table-striped contacts tablesorter" cellspacing="0" style="width: 100%;border: 0"><thead style="color: white;background-color: #379E8F;"><tr><th style="vertical-align: middle;text-align: center;" id="col_name"><b>NAME</b></th><th style="vertical-align: middle;text-align: center;" id="col_phone"><b>PHONE</b></th><th style="vertical-align: middle;text-align: center;" id="col_email"><b>EMAIL</b></th><th style="vertical-align: middle;text-align: center;" id="col_role"><b>ROLE</b></th><th style="vertical-align: middle;text-align: center;" id="col_add_as_recipient"><b>ADD AS RECIPIENT</b></th></tr></thead><tbody></tbody></table>'; $('div.col-xs-12.contacts_div').html(inline_html_contact_table); // Like the contacts table, the html code of the usernote table is added using jQuery when the page loads. var inline_html_usernote_table = '<table cellpadding="15" id="user_note" class="table table-responsive table-striped contacts tablesorter" cellspacing="0" style="width: 100%;border: 0"><thead style="color: white;background-color: #379E8F;"><tr><th style="vertical-align: middle;text-align: center;" id="usernote_title"><b>TITLE</b></th><th style="vertical-align: middle;text-align: center;" id="usernote_name"><b>NAME</b></th><th style="vertical-align: middle;text-align: center;" id="usernote_date"><b>DATE</b></th><th style="vertical-align: middle;text-align: center;" id="usernote_comment"><b>USER NOTE</b></th></tr></thead><tbody></tbody></table>'; $('div.col-xs-12.user_note_div').html(inline_html_usernote_table); //Credit memo display displayed conditionally if (selector_type == 'invoice_number' && !isNullorEmpty(ticket_id)) { var inline_html_credit_memo_table = htmlCreditMemoTable(status_value); $('div.col-xs-12.credit_memo_div').html(inline_html_credit_memo_table); var inline_html_usage_report_table = htmlUsageReportTable(status_value); $('div.col-xs-12.usage_report_div').html(inline_html_usage_report_table); } // The value of the submitter button at the bottom of the page is directly linked to the value of the button at the top. // var submit_btn_val = $('#submitter').val().toUpperCase(); // $('#submit_ticket').val(submit_btn_val); if (!isNullorEmpty(selector_number)) { console.log('!isNullorEmpty(selector_number) : ', !isNullorEmpty(selector_number)); // If we updated the contacts, we have the parameter 'custpage_selector_number' and no parameter for 'custpage_ticket_id'. if (isNullorEmpty(ticket_id)) { console.log('isNullorEmpty(ticket_id) : ', isNullorEmpty(ticket_id)); $('#selector_value').val(selector_number); if (validateSelectorInput()) { displayCustomerInfo(); } // If we come from the edit_ticket page, we have the parameters 'custpage_selector_number' and' custpage_ticket_id'. } else { console.log('isNullorEmpty(ticket_id) : ', isNullorEmpty(ticket_id)); createContactsRows(); // If the ticket status is "Open, the acknoledgement template shall be selected. if (status_value != 3) { $('#template option:selected').attr('selected', false); $('#template option[value="66"]').attr('selected', true); // Select the acknoledgement template loadTemplate(); } if (selector_type == 'invoice_number') { updateInvoicesDatatable(); createCreditMemoRows(status_value); createUsageReportRows(status_value); createUsernoteRows(ticket_id); } else if (selector_type == 'barcode_number') { selectEnquiryMedium(); selectTollEmails(); selectOwner(); setReminderDate(); hideCloseTicketButton(); updateTicketsDatatable(); } else { //selector_type == 'customer_issue' selectEnquiryMedium(); } } } $('[data-toggle="tooltip"]').tooltip(); updateButtonsWidth(); $('.input-group-btn button').click(function(e) { $(e.currentTarget).next('ul').toggleClass('hide'); $(e.currentTarget).next('ul').toggleClass('show'); }); $('#screenshot_image').on('change', function() { var file = $('#screenshot_image')[0].files[0]; if (file && (file.type == "image/jpeg" || file.type == "image/png")) { //continue } else { showAlert('Please enter a screenshot image of type .png or .jpeg'); } }); //Change display depending on which selector is chosen $('.dropdown-menu li a').click(function(e) { console.log("in selector dropdown li a"); e.preventDefault(); setupSelectorInput($(this).text()); var selector_type = $('#selector_text').text().toLowerCase().split(' ').join('_'); currRec.setValue({ fieldId: 'custpage_selector_type', value: selector_type}); updateTicketsDatatableHeaders(selector_type); switch (selector_type) { case 'barcode_number': $('#daytodayemail').attr('disabled', true); $('#daytodayphone').attr('disabled', true); $('#accountsemail').attr('disabled', true); $('#accountsphone').attr('disabled', true); $('.accountscontact_section').addClass('hide'); $('.accountscontact_section').addClass('hide'); $('.accounts_number_section').addClass('hide'); $('.mpex_stock_used_section').removeClass('hide'); $('.final_delivery').removeClass('hide'); $('.enquiry_status_div').removeClass('col-xs-12'); $('.enquiry_status_div').addClass('col-xs-6'); $('.label_section').removeClass('hide'); $('.enquiry_medium_section').removeClass('hide'); $('.ticket_enquiry_header_section').removeClass('hide'); $('.enquiry_status_div').removeClass('hide'); $('.enquiry_count_section').removeClass('hide'); $('.enquiry_count_breakdown_section').removeClass('hide'); $('.interaction_count_breakdown_section').removeClass('hide'); $('.invoice_method_accounts_cc_email_section').addClass('hide'); $('.mpex_customer_po_number_section').addClass('hide'); $('.terms_section').addClass('hide'); $('.mpex_invoicing_cycle_section').addClass('hide'); $('.ss_section').addClass('hide'); $('.browser_os_section').addClass('hide'); $('.phone_section').addClass('hide'); $('.login_email_section').addClass('hide'); $('.sender_details_section').addClass('hide'); $('.login_email_used_section').addClass('hide'); // Add MP Issues options var mp_ticket_issues_columns = new Array(); mp_ticket_issues_columns[0] = search.createColumn({ name: 'name' }); mp_ticket_issues_columns[1] = search.createColumn({ name: 'internalId' }); var mpTicketIssuesResultSet = search.create({ type: 'customlist_mp_ticket_issues', columns: mp_ticket_issues_columns }); var mp_issues_option_inline_html = ''; mpTicketIssuesResultSet.each(function(mpTicketIssueResult) { var mp_issue_name = mpTicketIssueResult.getValue('name'); var mp_issue_id = mpTicketIssueResult.getValue('internalId'); mp_issues_option_inline_html += '<option value="' + mp_issue_id + '">' + mp_issue_name + '</option >'; return true; }); $('#mp_issues').html(mp_issues_option_inline_html); $('#mp_issues').selectpicker('refresh'); $('.toll_issues_section').removeClass('hide'); $('.resolved_toll_issues_section').removeClass('hide'); $('.open_invoices').addClass('hide'); $('.invoice_issues_section').addClass('hide'); $('.resolved_invoice_issues_section').addClass('hide'); $('.user_note').addClass('hide'); $('.comment_section').removeClass('hide'); $('.reminder_section').removeClass('hide'); $('.login_email_used_section').addClass('hide'); var owner_list = [userId]; console.log(owner_list); $('#owner').selectpicker('val', owner_list); break; case 'invoice_number': if (isFinanceRole(userRole)) { $('#daytodayemail').attr('disabled', false); $('#daytodayphone').attr('disabled', false); $('#accountsemail').attr('disabled', false); $('#accountsphone').attr('disabled', false); $('#invoice_method').attr('disabled', false); $('#accounts_cc_email').attr('disabled', false); $('#mpex_po_number').attr('disabled', false); $('#customer_po_number').attr('disabled', false); $('#mpex_invoicing_cycle').attr('disabled', false); } $('.accountscontact_section').removeClass('hide'); $('.accounts_number_section').removeClass('hide'); $('.mpex_stock_used_section').addClass('hide'); $('.final_delivery').addClass('hide'); $('.enquiry_status_div').addClass('col-xs-12'); $('.enquiry_status_div').removeClass('col-xs-6'); $('.label_section').addClass('hide'); $('.enquiry_medium_section').addClass('hide'); $('.ticket_enquiry_header_section').addClass('hide'); $('.enquiry_status_div').addClass('hide'); $('.enquiry_count_section').addClass('hide'); $('.enquiry_count_breakdown_section').addClass('hide'); $('.interaction_count_breakdown_section').addClass('hide'); $('.ss_section').addClass('hide'); $('.browser_os_section').addClass('hide'); $('.phone_section').addClass('hide'); $('.login_email_section').addClass('hide'); $('.sender_details_section').addClass('hide'); $('.invoice_method_accounts_cc_email_section').removeClass('hide'); $('.mpex_customer_po_number_section').removeClass('hide'); $('.terms_section').removeClass('hide'); $('.mpex_invoicing_cycle_section').removeClass('hide'); $('.open_invoices').removeClass('hide'); // Remove MP Issues options $('#mp_issues option').each(function() { if ($(this).val() != 4) { $(this).remove(); } }); $('#mp_issues').selectpicker('refresh'); $('.toll_issues_section').addClass('hide'); $('.resolved_toll_issues_section').addClass('hide'); $('.invoice_issues_section').removeClass('hide'); $('.resolved_invoice_issues_section').removeClass('hide'); $('.user_note').removeClass('hide'); $('.comment_section').addClass('hide'); $('.reminder_section').removeClass('hide'); //Set Owner to current user var owner_list = [userId]; $('#owner').selectpicker('val', owner_list); break; case 'customer_issue': $('#daytodayemail').attr('disabled', true); $('#daytodayphone').attr('disabled', true); $('#accountsemail').attr('disabled', true); $('#accountsphone').attr('disabled', true); $('.invoice_issues_section').addClass('hide'); $('.user_note_title_section').addClass('hide'); $('.user_note_textarea_section').addClass('hide'); $('.user_note_section').addClass('hide'); $('.accountscontact_section').addClass('hide'); $('.accountscontact_section').addClass('hide'); $('.accounts_number_section').addClass('hide'); $('.mpex_stock_used_section').removeClass('hide'); $('.final_delivery').removeClass('hide'); $('.enquiry_status_div').removeClass('col-xs-12'); $('.enquiry_status_div').addClass('col-xs-6'); $('.label_section').removeClass('hide'); $('.enquiry_medium_section').removeClass('hide'); $('.ticket_enquiry_header_section').removeClass('hide'); $('.enquiry_status_div').removeClass('hide'); $('.enquiry_count_section').removeClass('hide'); $('.enquiry_count_breakdown_section').removeClass('hide'); $('.interaction_count_breakdown_section').removeClass('hide'); $('.reminder_section').addClass('hide'); $('.toll_issues_section').addClass('hide'); $('.login_email_used_section').removeClass('hide'); var current_customer_issue = $('#selector_value').val(); switch (current_customer_issue) { case 'Customer App': //App related fields $('.browser_os_section').addClass('hide'); $('.sender_details_section').addClass('hide'); $('.phone_section').removeClass('hide'); //Set current chosen option to Customer App var mp_issues_option_inline_html = '<option value="10" selected> Customer App Issue</option>'; $('#mp_issues').html(mp_issues_option_inline_html); //Requires double refresh. One for the dropwdown chnage and sceond for selection $('#mp_issues').selectpicker('refresh'); $('#mp_issues').selectpicker('refresh') break; case 'Customer Portal': //Portal related fields $('.phone_section').addClass('hide'); $('.browser_os_section').removeClass('hide'); $('.sender_details_section').addClass('hide'); var mp_issues_option_inline_html = '<option value="9" selected> Customer Portal Issue</option>'; $('#mp_issues').html(mp_issues_option_inline_html); //Requires double refresh. One for the dropwdown chnage and sceond for selection $('#mp_issues').selectpicker('refresh'); $('#mp_issues').selectpicker('refresh') break; case 'Update Label': //Label fields $('.browser_os_section').addClass('hide'); $('.phone_section').addClass('hide'); $('.sender_details_section').removeClass('hide'); var mp_issues_option_inline_html = '<option value="11" selected> Update Customer Label Issue</option>'; $('#mp_issues').html(mp_issues_option_inline_html); //Requires double refresh. One for the dropwdown chnage and sceond for selection $('#mp_issues').selectpicker('refresh'); $('#mp_issues').selectpicker('refresh'); break; } //Set Owner to Rianne Mansell var owner_list = ['1132504']; $('#owner').selectpicker('val', owner_list); break; } $(this).closest("ul").toggleClass('hide'); $(this).closest("ul").toggleClass('show'); }); $('#open_inv').click(function() { var invoice_id = $(this).data('inv-id'); var compid = (runtime.envType == "SANDBOX") ? '1048144_SB3' : '1048144'; var invoice_link = baseURL + '/app/accounting/transactions/custinvc.nl?id=' + invoice_id + '&compid=' + compid + '&cf=116&whence='; console.log("invoice_link", invoice_link); window.open(invoice_link, "_blank", "height=750,width=650,modal=yes,alwaysRaised=yes"); }) updateEnquiryMediumAndCount(); $('#reviewcontacts').click(function() { console.log("1234"); addEditContact(); }); $('#invoices_dropdown').change(function() { var invoice_status_filter = $(this, 'option:selected').val(); if (invoice_status_filter == 'open') { var invoice_section_header = 'OPEN INVOICES'; } else if (invoice_status_filter == 'paidInFull') { var invoice_section_header = 'PAID INVOICES'; } $('.open_invoices_header div div h4 span').text(invoice_section_header); updateInvoicesDatatable(); }); $('.add_as_recipient').click(function() { var email_address = $(this).data('email'); console.log(email_address); if (!isNullorEmpty(email_address)) { $(this).toggleClass('btn-success'); $(this).toggleClass('btn-danger'); if ($(this).attr('data-original-title') == 'Add as recipient') { $(this).attr('data-original-title', 'Remove recipient'); } else { $(this).attr('data-original-title', 'Add as recipient'); } $('[data-toggle="tooltip"]').tooltip(); // Convert "TO" text field to email adresses array console.log($('#send_to')); var send_to_values = $('#send_to').val().split(','); var send_to_array = []; send_to_values.forEach(function(email_address_in_send_to) { email_address_in_send_to = email_address_in_send_to.trim(); if (!isNullorEmpty(email_address_in_send_to)) { send_to_array.push(email_address_in_send_to); } }); // Add or remove selected email adress from array var firstname = $(this).data('firstname'); var firstname_array = $('#send_to').data('firstname'); if (!isNullorEmpty(firstname_array)) { firstname_array = JSON.parse($('#send_to').data('firstname')); } else { firstname_array = []; } var contact_id = $(this).data('contact-id'); var contact_id_array = $('#send_to').data('contact-id'); if (!isNullorEmpty(contact_id_array)) { contact_id_array = JSON.parse(contact_id_array); } else { contact_id_array = []; } var index_of_email_address = send_to_array.indexOf(email_address); if (index_of_email_address == -1 && $(this).hasClass('btn-danger') && !isNullorEmpty(email_address)) { send_to_array.push(email_address); if (!isNullorEmpty(firstname)) { firstname_array.push(firstname); } if (!isNullorEmpty(contact_id) || contact_id == 0) { contact_id_array.push(contact_id); } } else if ($(this).hasClass('btn-success')) { send_to_array.splice(index_of_email_address, 1); if (!isNullorEmpty(firstname)) { firstname_array.splice(firstname, 1); } if (!isNullorEmpty(contact_id)) { contact_id_array.splice(contact_id, 1); } } firstname_array = JSON.stringify(firstname_array); contact_id_array = JSON.stringify(contact_id_array); // Convert array to text field var send_to = ''; send_to_array.forEach(function(email_address) { send_to += email_address + ', '; }); send_to = send_to.slice(0, -2); console.log('send_to : ', send_to); $('#send_to').val(send_to); $('#send_to').data('firstname', firstname_array); $('#send_to').data('contact-id', contact_id_array); } }); $('#credit_memo tbody td[headers="credit_memo_action"] button, #usage_report tbody td[headers="usage_report_action"] button, button#add_inv').on('click', function() { attachFileButton.call(this) }); $('#acc_manager_button').click(function() { var account_manager_email = $('#acc_manager').data('email'); var send_cc_field = $('#send_cc').val(); if (isNullorEmpty(send_cc_field)) { $('#send_cc').val(account_manager_email); } else { $('#send_cc').val(send_cc_field + ', ' + account_manager_email); } }); $('#template').change(function() { loadTemplate() }); $('#send_email').click(function() { sendEmail() }); $('#toll_issues, #invoice_issues').on('change', function() { hideCloseTicketButton() }); $('#mp_issues').change(function() { selectOwner(); hideCloseTicketButton(); }); $('#cancelbutton').click(function() { onCancel() }); $('#closeticketbutton').click(function() { closeTicket(selector_type, '') }); $('#closenewticketbutton').click(function() { console.log("in close new"); closeNewTicket() }); $('#closelostbutton').click(function() { closeTicketLost() }); $('#closeunallocatedbutton').click(function() { closeUnallocatedTicket() }); $('#reopenticketbutton').click(function() { reopenTicket() }); $('#updateticketbutton').click(function() { updateAndNew(); }); $('#updatecloseticketbutton').click(function() { console.log("btn clicked"); if (confirm("Are you sure you want to update and close this ticket?\n\nThis action cannot be undone.")) { console.log('Update & Closed Started'); updateSaveRecord(); updateCloseTicket(); console.log("Update finished"); //updateCloseTicket(); } }); $('#openticketbutton').click(function() { console.log("hi"); //saveRecord(); $('#submitter').trigger('click'); }); $('#opennewticketbutton').click(function() { openAndNew(); }); $('#escalatebutton').click(function() { escalateTicket(ticket_id, selector_number, selector_type); }); $('#escalaterianne').click(function() { console.log("Escalating to rianne"); var ticketRecord = record.load({ type: 'customrecord_mp_ticket', id: parseInt(ticket_id), }); var comments = $('#comment').val(); console.log('comments', comments); if (isNullorEmpty(comments)) { console.log('Enter comment before Escalation', comments); showAlert('Please enter a Comment before escalating to IT'); return false; } if (isNullorEmpty(ticketRecord.getValue({fieldId: 'custrecord_date_escalated_it'}))) { ticketRecord.setValue({fieldId: 'custrecord_date_escalated_it', value: new Date()}); var owner_list = ['1132504']; $('#owner').selectpicker('val', owner_list); ticketRecord.setValue({fieldId: 'custrecord_owner', value: owner_list}); ticketRecord.save({ enableSourcing: true, ignoreMandatoryFields: true }); sendCustomerTicketEmail('', parseInt(ticket_id), customer_number, selector_type, selector_number, $("#browser_value option:selected").text(), $('#os_value option:selected').text(), $('#login_email_text').val(), '', '', ["PI:EMAIL:envkt@example.comEND_PI"]); var output = url.resolveScript({ deploymentId: 'customdeploy_sl_edit_ticket_2', scriptId: 'customscript_sl_edit_ticket_2', }); var upload_url = baseURL + output; window.open(upload_url, "_self", "height=750,width=650,modal=yes,alwaysRaised=yes"); } else { console.log('didnt work for some reason'); } }); $('#escalateankith').click(function() { var ticketRecord = record.load({ type: 'customrecord_mp_ticket', id: parseInt(ticket_id), }); var interaction_count_by_phone = $('#interaction_count_by_phone').val(); var interaction_count_by_email = $('#interaction_count_by_email').val(); var customer_number = $('#customer_number_value').val().trim(); var creator_id = ticketRecord.getValue({fieldId: 'custrecord_creator'}); var escalated_to_it = ticketRecord.getValue({ fieldId: 'custrecord_date_escalated_it' }); var first_interaction = ticketRecord.getValue({ fieldId: 'custrecord_first_interaction_date' }); if (isNullorEmpty(customer_number) && creator_id == 112209 && !isNullorEmpty(escalated_to_it) && selector_type == "customer_issue" && !isNullorEmpty(ticket_id)) { console.log('Enter customer number before Escalation'); showAlert('Please enter a Customer Number'); return false; } else if (isNullorEmpty(first_interaction) && interaction_count_by_phone == 0 && interaction_count_by_email == 0) { console.log('Incrememnt interaction count before Escalation'); showAlert('Please Interact with Customer before Escalation'); return false; } ticketRecord.setValue({fieldId: 'custrecord_ticket_status', value: 10}); var owner_list = ['409635']; $('#owner').selectpicker('val', owner_list); ticketRecord.setValue({fieldId: 'custrecord_owner', value: owner_list}); ticketRecord.save({ enableSourcing: true, ignoreMandatoryFields: true }); var subject = 'MPSD' + ticket_id + ' - Customer Issue Ticket Escalated'; var customer_id = ticketRecord.getValue({fieldId: 'custrecord_customer1'}); var login_email = ticketRecord.getText({fieldId: 'custrecord_login_email'}); sendCustomerTicketEmail(subject, parseInt(ticket_id), customer_number, selector_type, selector_number, $("#browser_value option:selected").text(), $('#os_value option:selected').text(), $('#login_email_text').val(), '', '', ["PI:EMAIL:nnheo@example.comEND_PI"]); if (!isNullorEmpty(login_email)) { sendCustomerEscalateEmail('MailPlus [MPSD' + parseInt(ticket_id) + '] - Your IT ticket has been escalated - Customer Portal', [login_email], 120, customer_id); } var output = url.resolveScript({ deploymentId: 'customdeploy_sl_edit_ticket_2', scriptId: 'customscript_sl_edit_ticket_2', }); var upload_url = baseURL + output; window.open(upload_url, "_self", "height=750,width=650,modal=yes,alwaysRaised=yes"); }); $('#escalateunderdev').click(function() { saveRecord(); var ticketRecord = record.load({ type: 'customrecord_mp_ticket', id: parseInt(ticket_id), }); ticketRecord.setValue({fieldId: 'custrecord_ticket_status', value: 17}); ticketRecord.save({ enableSourcing: true, ignoreMandatoryFields: true }); location.reload(); }); $('#escalateremoveunderdev').click(function() { saveRecord(); var ticketRecord = record.load({ type: 'customrecord_mp_ticket', id: parseInt(ticket_id), }); ticketRecord.setValue({fieldId: 'custrecord_ticket_status', value: 10}); ticketRecord.save({ enableSourcing: true, ignoreMandatoryFields: true }); location.reload(); }); $('#closeresolvedbutton').click(function() { closeTicket(selector_type, 15); }); $('#closeunresolvedbutton').click(function() { closeTicket(selector_type, 16); }); // Prevent the ticket to be submitted on enter. $('input, textarea').keydown(function(e) { if (e.keyCode == 13) { e.preventDefault(); return false; } }); // Add a newline at the end of the comment textarea when enter is pressed // This will not create the newline where the cursor is in the text $('textarea#comment').keydown(function(e) { if (e.keyCode == 13) { var comment = $(this).val(); comment += '\n'; $(this).val(comment); return false; } }); //Event listener for customer number input and selector value input $('#customer_number_value, #selector_value').change(function() { checkMandatoryFields(); }); } function escalateTicket(ticket_id, selector_number, selector_type) { var answer = window.confirm("Are you sure you want to escalate this ticket?"); if (answer) { //SET FIELDS IN RECORD //some code // REDIRECT TO URL console.log("IN HERE"); var params = { ticket_id: parseInt(ticket_id), selector_number: selector_number, selector_type: selector_type }; params = JSON.stringify(params); var output = url.resolveScript({ deploymentId: 'customdeploy_sl_ticketing_escalate', scriptId: 'customscript_sl_ticketing_escalate', }); var upload_url = baseURL + output + '&custparam_params=' + params; var ticketRecord = record.load({ type: 'customrecord_mp_ticket', id: Math.floor(ticket_id), }); var customerstatus = ticketRecord.getValue({fieldId: 'custrecord_mp_ticket_customer_status'}); var ticketstatus = ticketRecord.getValue({fieldId: 'custrecord_ticket_status'}); var customer_id = ticketRecord.getValue({fieldId: 'custrecord_customer1'}); var customer_barcode_number = ticketRecord.getValue({ fieldId : 'custrecord_barcode_number'}); var ticket_name = ticketRecord.getText({fieldId: 'name'}); console.log('customerstatus', customerstatus); if (parseInt(customerstatus) < 4 ) { console.log(customerstatus); ticketRecord.setValue({fieldId: 'custrecord_mp_ticket_customer_status', value: parseInt(customerstatus) + 1}); } if (parseInt(ticketstatus) < 11 ) { console.log(ticketstatus); ticketRecord.setValue({fieldId: 'custrecord_ticket_status', value: 11}); } else if (parseInt(ticketstatus) < 14) { console.log(ticketstatus); ticketRecord.setValue({fieldId: 'custrecord_ticket_status', value: parseInt(ticketstatus) + 1}); } ticketRecord.save({ enableSourcing: true, }) //Send email to Receiver var barcodeRecord = record.load({ type: 'customrecord_customer_product_stock', id: customer_barcode_number, }); var receiveremail = barcodeRecord.getValue({fieldId: 'custrecord_receiver_email'}); var barcodeName = barcodeRecord.getValue({fieldId: 'name'}); var ticketRecord = record.load({ type: 'customrecord_mp_ticket', id: Math.floor(ticket_id), }) var ticketstatus = ticketRecord.getValue({fieldId: 'custrecord_ticket_status'}); if (!isNullorEmpty(receiveremail)) { if (ticketstatus == 11) { sendCustomerEscalateEmail('MailPlus [' + ticket_name + '] - Support enquiry | Stage 1 - ' + barcodeName, [receiveremail], 109, customer_id); } else if (ticketstatus == 12) { sendCustomerEscalateEmail('MailPlus [' + ticket_name + '] - Support enquiry | Stage 2 - ' + barcodeName, [receiveremail], 110, customer_id); } else if (ticketstatus == 13) { sendCustomerEscalateEmail('MailPlus [' + ticket_name + '] - Support enquiry | Stage 3 - ' + barcodeName, [receiveremail], 111, customer_id); } } //Send email to TOLL var toll_issues = ticketRecord.getText({ fieldId: 'custrecord_toll_issues' }); var mp_issues = ticketRecord.getText({ fieldId: 'custrecord_mp_ticket_issue' }); var body = 'MP Ticket ID: ' + ticket_name + '\n Barcode: ' + barcodeName + '\nToll Issues: ' + toll_issues + '\nMP Issues: ' + mp_issues; // if (ticketstatus == 11) { // email.send({ // author: 112209, // body: body, // recipients: ['PI:EMAIL:kenaa@example.comEND_PI'], // subject: 'Ticket Escalated: Escalation 1- ' + ticket_name, // relatedRecords: {record: ticket_id, recordtype: 1042} // }); // } else if (ticketstatus == 12) { // email.send({ // author: 112209, // body: body, // recipients: ['PI:EMAIL:kenaa@example.comEND_PI'], // subject: 'Ticket Escalated: Escalation 2- ' + ticket_name, // relatedRecords: {record: ticket_id, recordtype: 1042}, // }); // } else if (ticketstatus == 13) { // email.send({ // author: 112209, // body: body, // recipients: ['PI:EMAIL:kenaa@example.comEND_PI'], // subject: 'Ticket Escalated: Escalation 3- ' + ticket_name, // relatedRecords: {record: ticket_id, recordtype: 1042}, // }); // } console.log("upload", upload_url) window.open(upload_url, '_self'); } else { //some code } } /** * Function to sent emails when a customer associated ticket is escalated */ function sendCustomerEscalateEmail(subject, recipients, template, customer_id) { var sales_rep = encodeURIComponent(runtime.getCurrentUser().name); var userid = encodeURIComponent(runtime.getCurrentUser().id); var suiteletUrl = url.resolveScript({ scriptId: 'customscript_merge_email', deploymentId: 'customdeploy_merge_email', returnExternalUrl: true }); suiteletUrl += '&rectype=customer&template='; suiteletUrl += template + '&recid=' + customer_id + '&salesrep=' + sales_rep + '&dear=' + '' + '&contactid=' + null + '&userid=' + userid; console.log(suiteletUrl); var response = https.get({ url: suiteletUrl }); var emailHtml = response.body; if (!isNullorEmpty(customer_id)) { email.send({ author: 112209, body: emailHtml, recipients: recipients, subject: subject, relatedRecords: { entityId: customer_id} }); } else { email.send({ author: 112209, body: emailHtml, recipients: recipients, subject: subject, }); } } function commentsDate() { var today = new Date(); var dd = today.getDate(); var mm = today.getMonth()+1; var yyyy = today.getFullYear(); if(dd<10) { dd='0'+dd; } if(mm<10) { mm='0'+mm; } today = mm+'/'+dd+'/'+yyyy; return today; } function saveRecord(context) { var currRec = currentRecord.get(); var status_value = currRec.getValue({ fieldId: 'custpage_ticket_status_value' }); var selector_issue = currRec.getValue({ fieldId: 'custpage_selector_issue' }); //set to T onEscalate var selector_type = currRec.getValue({ fieldId: 'custpage_selector_type' }); var customer_number = currRec.getValue({ fieldId: 'custpage_customer_number' }); var selector_number = $('#selector_value').val(); console.log('status_value' + status_value) console.log('selector_issue ' + selector_issue) console.log('selector_type ' + selector_type) console.log('selector_number ' + selector_number) if (selector_type == 'customer_issue') { if (isNullorEmpty(customer_number)) { showAlert('Please enter a customer number'); return false; } } if (isTicketNotClosed(status_value) && !isNullorEmpty(selector_type)) { // Barcode/Inv associated tickets - check that a TOLL Issue or an Invoice Issue has been selected. // Customer number associated ticket - check that a customer number has been entered switch (selector_type) { case 'barcode_number': var toll_issues_length = $('#toll_issues option:selected').length; if (toll_issues_length == 0) { showAlert('Please select a TOLL Issue<br>'); return false; } break; case 'invoice_number': var invoice_issues_length = $('#invoice_issues option:selected').length; if (invoice_issues_length == 0) { showAlert('Please select an Invoice Issue<br>'); return false; } break; case 'customer_issue': var login_email_used = $('#login_email_text').val(); if (!isNullorEmpty(login_email_used) && !validateEmail(login_email_used)) { showAlert('User login email format is invalid. Please enter email again <br>'); return false; } break; } } if (role == 1005) { var owner_length = $('#owner option:selected').length; if (owner_length == 0) { showAlert('Please select an Owner<br>'); return false; } } else { var owner_length = $('#owner option:selected').length; var checkTicketOwner = currRec.getValue({ fieldId: 'custpage_ticket_id' }); if (!isNullorEmpty(checkTicketOwner)) { var checkTicketOwnerRec = record.load({ type: 'customrecord_mp_ticket', id: parseInt(checkTicketOwner) }); var owners = checkTicketOwnerRec.getValue({ fieldId: 'custrecord_owner'}); if (isNullorEmpty(owners) && owner_length == 0) { showAlert('Please select an Owner<br>'); return false; } } else { if (owner_length == 0) { showAlert('Please select an Owner<br>'); return false; } } } if (selector_issue == 'T') { var to = $('#owner option:selected').map(function() { return $(this).data('email') }); to = $.makeArray(to); var email_sent = sendInformationEmailTo(selector_type, to, true) if (!email_sent) { return false; } } var ticket_id = currRec.getValue({ fieldId: 'custpage_ticket_id' }); console.log("Ticket id = " + ticket_id); if (isNullorEmpty(ticket_id)) { var ticketRecord = record.create({ type: 'customrecord_mp_ticket', }); currRec.setValue({ fieldId: 'custpage_created_ticket', value: 'T' }); ticketRecord.setValue({ fieldId: 'custrecord_email_sent', value: false }); } else { ticket_id = parseInt(ticket_id); try { var ticketRecord = record.load({ type: 'customrecord_mp_ticket', id: ticket_id }); } catch (e) { if (e instanceof error.SuiteScriptError) { if (e.name == "SSS_MISSING_REQD_ARGUMENT") { console.log('Error to load the ticket record with ticket_id : ' + ticket_id); } } } } currRec.setValue({ fieldId: 'custpage_selector_number', value: selector_number }); var selector_id = currRec.getValue({ fieldId: 'custpage_selector_id' }); // Save customer number var customer_number = $('#customer_number_value').val(); console.log('Saving customer number = ' + customer_number); ticketRecord.setValue({ fieldId: 'custrecord_cust_number', value: customer_number }); // Save Enquiry status var enquiry_status_val = $('#enquiry_status option:selected').val(); if (!isNullorEmpty(enquiry_status_val)) { ticketRecord.setValue({ fieldId: 'custrecord_enquiry_status', value: enquiry_status_val }); } var attachments_hyperlink = $('#attachments').val(); if (!isNullorEmpty(attachments_hyperlink)) { ticketRecord.setValue({ fieldId: 'custrecord_mp_ticket_attachments', value: attachments_hyperlink }); } // Save Ticket Label var label = $('#label_status option:selected').val(); if (!isNullorEmpty(label)) { ticketRecord.setValue({ fieldId: 'custrecord_ticket_label', value: label }); } //Save Enquiry medium var enquiry_medium = $('#enquiry_status option:selected').val(); if (!isNullorEmpty(enquiry_medium)) { ticketRecord.setValue({ fieldId: 'custrecord_enquiry_medium', value: enquiry_medium }); } var total_enquiry_count = 0; if (!isNullorEmpty($('#enquiry_count_by_chat').val())) { total_enquiry_count += parseInt($('#enquiry_count_by_chat').val()); } if (!isNullorEmpty($('#enquiry_count_by_phone').val())) { total_enquiry_count += parseInt($('#enquiry_count_by_phone').val()); } if (!isNullorEmpty($('#enquiry_count_by_email').val())) { total_enquiry_count += parseInt($('#enquiry_count_by_email').val()); } ticketRecord.setValue({ fieldId: 'custrecord_enquiry_count', value: total_enquiry_count }); var enquiry_count_by_chat = $('#enquiry_count_by_chat').val(); if (!isNullorEmpty(enquiry_count_by_chat)) { ticketRecord.setValue({ fieldId: 'custrecord_chat_enquiry_count', value: enquiry_count_by_chat }); } var enquiry_count_by_phone = $('#enquiry_count_by_phone').val(); if (!isNullorEmpty(enquiry_count_by_phone)) { ticketRecord.setValue({ fieldId: 'custrecord_phone_enquiry_count', value: enquiry_count_by_phone }); } var enquiry_count_by_email = $('#enquiry_count_by_email').val(); if (!isNullorEmpty(enquiry_count_by_email)) { ticketRecord.setValue({ fieldId: 'custrecord_email_enquiry_count', value: enquiry_count_by_email }); } var interaction_count_by_phone = $('#interaction_count_by_phone').val(); var interaction_count_by_email = $('#interaction_count_by_email').val(); if (isNullorEmpty(ticketRecord.getValue({ fieldId: 'custrecord_first_interaction_date'}))) { if (!isNullorEmpty(interaction_count_by_email) || !isNullorEmpty(interaction_count_by_phone)) { ticketRecord.setValue({ fieldId: 'custrecord_first_interaction_date', value: new Date()}); } } if (!isNullorEmpty(interaction_count_by_phone)) { ticketRecord.setValue({ fieldId: 'custrecord_phone_interaction_count', value: interaction_count_by_phone }); } if (!isNullorEmpty(interaction_count_by_email)) { ticketRecord.setValue({ fieldId: 'custrecord_email_interaction_count', value: interaction_count_by_email }); } //Check Enquiry is Selected if (isNullorEmpty(enquiry_count_by_chat) && isNullorEmpty(enquiry_count_by_phone) && isNullorEmpty(enquiry_count_by_email)) { showAlert('Please select an Enquiry Type<br>'); return false; } else if(total_enquiry_count == 0) { showAlert('Please select an Enquiry Type<br>'); return false; } //Save Medium list saveMediumList(enquiry_count_by_chat, enquiry_count_by_phone, enquiry_count_by_email, ticketRecord); ticketRecord = setTicketStatus(ticketRecord); ticketRecord = setCreator(ticketRecord); ticketRecord.setValue({ fieldId: 'altname', value: selector_number }); var owner_email_list = $('#owner option:selected').map(function() { return $(this).data('email') }); owner_email_list = $.makeArray(owner_email_list); var zee_id = currRec.getValue({ fieldId: 'custpage_zee_id' }); ticketRecord.setValue({ fieldId: 'custrecord_zee', value: zee_id }); console.log("sending email..." + selector_type); if (!isNullorEmpty(selector_type)) { switch (selector_type) { case 'barcode_number': ticketRecord.setValue({ fieldId: 'custrecord_barcode_number', value: selector_id }); // Save Reminder date var reminder_date = $('#reminder').val(); if (!isNullorEmpty(reminder_date)) { reminder_date = new Date(reminder_date); reminder_date = format.parse({ value: reminder_date, type: format.Type.DATE }); ticketRecord.setValue({ fieldId: 'custrecord_reminder', value: reminder_date }); } break; case 'invoice_number': ticketRecord.setValue({ fieldId: 'custrecord_invoice_number', value: selector_id }); var customer_id = currRec.getValue({ fieldId: 'custpage_customer_id' }); ticketRecord.setValue({ fieldId: 'custrecord_customer1', value: customer_id }); if (isFinanceRole(userRole)) { var daytodayemail = $('#daytodayemail').val(); var daytodayphone = $('#daytodayphone').val(); var accountsemail = $('#accountsemail').val(); var accountsphone = $('#accountsphone').val(); var selected_invoice_method_id = $('#invoice_method option:selected').val(); var accounts_cc_email = $('#accounts_cc_email').val(); var mpex_po_number = $('#mpex_po_number').val(); var customer_po_number = $('#customer_po_number').val(); var customer_terms = $('#customers_terms').val(); var selected_invoice_cycle_id = $('#mpex_invoicing_cycle option:selected').val(); var customerRecord = record.load({ type: 'customer', id: customer_id }); customerRecord.setValue({ fieldId: 'custentity_email_service', value: daytodayemail }); customerRecord.setValue({ fieldId: 'phone', value: daytodayphone }); customerRecord.setValue({ fieldId: 'email', value: accountsemail }); customerRecord.setValue({ fieldId: 'altphone', value: accountsphone }); customerRecord.setValue({ fieldId: 'custentity_invoice_method', value: selected_invoice_method_id }); customerRecord.setValue({ fieldId: 'custentity_accounts_cc_email', value: accounts_cc_email }); customerRecord.setValue({ fieldId: 'custentity_mpex_po', value: mpex_po_number }); customerRecord.setValue({ fieldId: 'custentity11', value: customer_po_number }); customerRecord.setValue({ fieldId: 'custentity_finance_terms', value: customer_terms }); customerRecord.setValue({ fieldId: 'custentity_mpex_invoicing_cycle', value: selected_invoice_cycle_id }); customerRecord.save({}) // Save Reminder date var reminder_date = $('#reminder').val(); if (!isNullorEmpty(reminder_date)) { reminder_date = new Date(reminder_date); reminder_date = format.parse({ value: reminder_date, type: format.Type.DATE }); ticketRecord.setValue({ fieldId: 'custrecord_reminder', value: reminder_date}); } } break; case 'customer_issue': var screenshot_image = currRec.getValue({ fieldId: 'custpage_ss_image' }); if (!isNullorEmpty(screenshot_image)) { ticketRecord.setValue({ fieldId: 'custrecord_screenshot', value: screenshot_image}); } var customer_id = currRec.getValue({ fieldId: 'custpage_customer_id' }); if (!isNullorEmpty(customer_id)) { ticketRecord.setValue({ fieldId: 'custrecord_customer1', value: customer_id}); } var customer_issue_type = $('#selector_value').val(); if (!isNullorEmpty(customer_issue_type)) { ticketRecord.setValue({ fieldId: 'custrecord_customer_issue', value: customer_issue_type}); } var login_email_used = $('#login_email_text').val(); if (!isNullorEmpty(login_email_used)) { ticketRecord.setValue({ fieldId: 'custrecord_login_email', value: login_email_used}); } var is_customer_number_email_sent = currRec.getValue({ fieldId: 'custpage_customer_number_email_sent' }); console.log("cust iss typ", customer_issue_type); switch (customer_issue_type) { case 'Customer App': console.log("in cust app"); var phone_used = $('#phone_used').val(); if (!isNullorEmpty(phone_used)) { ticketRecord.setValue({ fieldId: 'custrecord_phone_used', value: phone_used}); } if (is_customer_number_email_sent == 'F' && !isNullorEmpty(ticket_id)) { sendCustomerTicketEmail('',ticket_id, customer_number, selector_type, selector_number, '', '', login_email_used, '', '', owner_email_list); ticketRecord.setValue({ fieldId: 'custrecord_customer_number_email_sent', value: true }); } break; case 'Customer Portal': var browser = $("#browser_value option:selected").val(); if (!isNullorEmpty(browser)) { ticketRecord.setValue({ fieldId: 'custrecord_browser', value: browser}); } var os_used = $('#os_value option:selected').val(); if (!isNullorEmpty(os_used)) { ticketRecord.setValue({ fieldId: 'custrecord_operating_system', value: os_used}); } if (is_customer_number_email_sent == 'F' && !isNullorEmpty(ticket_id)) { sendCustomerTicketEmail('',ticket_id, customer_number, selector_type, selector_number, $("#browser_value option:selected").text(), $('#os_value option:selected').text(), login_email_used, '', '', owner_email_list); ticketRecord.setValue({ fieldId: 'custrecord_customer_number_email_sent', value: true }); } break; case 'Update Label': var sender_name = $('#sender_name_text').val(); if (!isNullorEmpty(sender_name)) { ticketRecord.setValue({ fieldId: 'custrecord_sender_name', value: sender_name}); } var sender_phone = $('#sender_phone_text').val(); if (!isNullorEmpty(sender_phone)) { ticketRecord.setValue({ fieldId: 'custrecord_sender_phone', value: sender_phone}); } if (is_customer_number_email_sent == 'F' && !isNullorEmpty(ticket_id)) { sendCustomerTicketEmail('',ticket_id, customer_number, selector_type, selector_number, '', '', login_email_used, sender_name, sender_phone, owner_email_list); ticketRecord.setValue({ fieldId: 'custrecord_customer_number_email_sent', value: true }); } break; } break; } } ticketRecord = updateIssues(ticketRecord); //Owner var owner_list = new Array; $('#owner option:selected').each(function() { owner_list.push($(this).val()); }); if (!isNullorEmpty(ticket_id)) { // Send email to new owners. var old_owner_list = ticketRecord.getValue({ fieldId: 'custrecord_owner' }); if (!isNullorEmpty(old_owner_list)) { var only_new_owner_ids = []; var only_new_owner_email_address = []; owner_list.forEach(function(new_owner_id) { if (old_owner_list.indexOf(new_owner_id) == -1) { only_new_owner_ids.push(new_owner_id); only_new_owner_email_address.push($('#owner [value="' + new_owner_id + '"]').data('email')); } }) } else { var only_new_owner_ids = owner_list; var only_new_owner_email_address = []; owner_list.forEach(function(owner_id) { only_new_owner_email_address.push($('#owner [value="' + owner_id + '"]').data('email')); }) } console.log('selector_issue ' + selector_issue); console.log('only_new_owner_email_address ' + only_new_owner_email_address); console.log('selector_type ' + selector_type); // If there is an issue, all the owners have already received an email. if (selector_issue == 'F' && (!isNullorEmpty(only_new_owner_email_address))) { console.log('ISSUE'); var email_sent = sendInformationEmailTo(selector_type, only_new_owner_email_address, false); if (!email_sent) { return false; } } else if (selector_type == 'customer_issue') { var login_email_used = $('#login_email_text').val(); var customer_issue_type = $('#selector_value').val(); switch (customer_issue_type) { case 'Customer App': var phone_used = $('#phone_used').val(); var os_used = $('#os_value option:selected').val(); var browser = $("#browser_value option:selected").val() sendCustomerTicketEmail('',ticket_id, customer_number, selector_type, selector_number, $("#browser_value option:selected").text(), $('#os_value option:selected').text(), login_email_used, '', '', only_new_owner_email_address); break; case 'Customer Portal': var browser = $('#browser_value').val(); sendCustomerTicketEmail('',ticket_id, customer_number, selector_type, selector_number, $("#browser_value option:selected").text(), '', login_email_used, '', '', only_new_owner_email_address); break; case 'Update Label': var sender_phone = $('#sender_phone_text').val(); var sender_name = $('#sender_name_text').val(); sendCustomerTicketEmail('',ticket_id, customer_number, selector_type, selector_number, '', '', login_email_used, sender_name, sender_phone, only_new_owner_email_address); break; } } } // Save Owner list console.log(owner_list); ticketRecord.setValue({ fieldId: 'custrecord_owner', value: owner_list }); console.log("oList", ticketRecord.getValue({ fieldId: 'custrecord_owner'})); //cxcxc // Save Comment switch (selector_type) { case 'barcode_number': var comment = $('#comment').val(); break; case 'invoice_number': var comment = ticketRecord.getValue({ fieldId: 'custrecord_comment' }); if (isNullorEmpty(comment)) { comment = '' }; var selected_title = $('#user_note_title option:selected').text(); var usernote_textarea = $('#user_note_textarea').val(); var date = new Date; var date_time_now = format.parse({ value: date, type: format.Type.DATETIMETZ}); var date_now = format.parse({ value: date, type: format.Type.DATE}); var time_now = format.parse({ value: date, type: format.Type.TIMEOFDAY}); if (!isNullorEmpty(usernote_textarea)) { if (!isNullorEmpty(comment)) { comment += '\n'; } var usernote = '[' + selected_title + '] - [' + userName + '] - [' + date_time_now + '] - ' + usernote_textarea; // Save usernote on Customer record var userNote = record.create({ type: 'note', }); userNote.setValue({ fieldId: 'title', value: selected_title}); userNote.setValue({ fieldId: 'notedate', value: date_now}); userNote.setValue({ fieldId: 'time', value: time_now}); userNote.setValue({ fieldId: 'note', value: usernote_textarea}); userNote.setValue({ fieldId: 'entity', value: customer_id}); if (!isNullorEmpty(customer_id)) { userNote.save({}) } comment += usernote; } break; case 'customer_issue': var comment = $('#comment').val(); break; } if (!isNullorEmpty(comment)) { var original_comment = ticketRecord.getValue({ fieldId: 'custrecord_comment'} ); var total_comment = $('#comment').val(); var new_comment = total_comment.split(original_comment).join(''); var new_comment = total_comment.split(original_comment).join(''); var new_comment2 = new_comment.split("\n").join(''); var date_netsuite = format.format({ value: new Date(), type: format.Type.DATETIME }); console.log("new_comment", new_comment); console.log("new_comment2", new_comment2); var comment_with_date = total_comment; if (!isNullorEmpty(new_comment2)) { comment_with_date = "\n" + original_comment + "\n" + date_netsuite + " - " + new_comment2 + "\n"; } console.log('comment_with_date', comment_with_date); ticketRecord.setValue({ fieldId: 'custrecord_comment', value: comment_with_date} ); } var ticket_id = ticketRecord.save({ enableSourcing: true, }); currRec.setValue({ fieldId: 'custpage_ticket_id', value: ticket_id} ); if (!isNullorEmpty(selector_id) && (selector_type == 'barcode_number')) { try { var list_toll_issues = new Array; $('#toll_issues option:selected').each(function() { list_toll_issues.push($(this).val()); }); var barcodeRecord = record.load({ type: 'customrecord_customer_product_stock', id: selector_id }); console.log("ticket_id", ticket_id); console.log("list_toll_issues", list_toll_issues); barcodeRecord.setValue({ fieldId: 'custrecord_mp_ticket', value: ticket_id} ); barcodeRecord.setValue({ fieldId: 'custrecord_cust_prod_stock_toll_issues ', value: list_toll_issues }); var rec_email = $('#receiveremail').val(); var rec_name = $('#receivername').val(); var rec_state = $('#receiverstate').val(); var rec_zip = $('#receiverzip').val(); var rec_addr1 = $('#receiveraddr1').val(); var rec_addr2 = $('#receiveraddr2').val(); var rec_city = $('#receiversuburb').val(); var rec_phone = $('#receiverphone').val(); //Check if Rec details are to be updated if (!$("#receiveremail").is(":disabled")) { if (!isNullorEmpty(rec_email)) { barcodeRecord.setValue({ fieldId: 'custrecord_receiver_email', value: rec_email }); } if (!isNullorEmpty(rec_name)) { barcodeRecord.setValue({ fieldId: 'custrecord_receiver_name', value: rec_name }); } if (!isNullorEmpty(rec_state)) { barcodeRecord.setValue({ fieldId: 'custrecord_receiver_state', value: rec_state }); } if (!isNullorEmpty(rec_zip)) { barcodeRecord.setValue({ fieldId: 'custrecord_receiver_postcode', value: rec_zip }); } if (!isNullorEmpty(rec_addr1)) { barcodeRecord.setValue({ fieldId: 'custrecord_receiver_addr1', value: rec_addr1 }); } if (!isNullorEmpty(rec_addr2)) { barcodeRecord.setValue({ fieldId: 'custrecord_receiver_addr2', value: rec_addr2 }); } if (!isNullorEmpty(rec_city)) { barcodeRecord.setValue({ fieldId: 'custrecord_receiver_suburb', value: rec_city }); } if (!isNullorEmpty(rec_phone)) { barcodeRecord.setValue({ fieldId: 'custrecord_receiver_phone', value: rec_phone }); } } barcodeRecord.save({ enableSourcing: true, }); } catch (e) { console.log('Error to load the barcode record with barcode_id : ' + selector_id); } } return true; } /** * Takes action depending on which of the two fields (Customer number or Barcode/Inv number) is filled */ function checkMandatoryFields() { var currRec = currentRecord.get(); console.log("checkMandatoryField"); var selector_number = $('#selector_value').val().trim().toUpperCase(); var customer_number = $('#customer_number_value').val().trim(); var selector_type = $('#selector_text').text().toLowerCase().split(' ').join('_'); var ticket_records = null; if (!isNullorEmpty(customer_number) && isCustomerNumberValid(customer_number)) { currRec.setValue({ fieldId: 'custpage_customer_number', value: customer_number }); var customer_id = getCustomerID(customer_number); console.log("cid", customer_id); currRec.setValue({ fieldId: 'custpage_customer_id', value: customer_id }); if (!isNullorEmpty(selector_number)) { switch (selector_type) { case "barcode_number": case "invoice_number": displayCustomerInfo(); break; case "customer_issue": } } ticket_records = searchTicketRecords(customer_number); console.log('Current tickets on customer number ' + customer_number + ': ' + ticket_records); var customer_record = customerLinkedToCustomerNum(customer_number); if (!isNullorEmpty(customer_record)) { //Display franchisee details displayFranchiseeInfo(customer_record); } if (!isNullorEmpty(ticket_records)) { //If tickets exist with this customer number, display customer number tickets datatable updateCustomerNumTicketsTable(ticket_records); } else { console.log('Removing table'); //Remove tickets datatable $('#customer_number_tickets_preview_wrapper').hide(); //Show no ticket exists info box $('#info').text('No ticket exists for the customer '); $('#info').parent().show(); } } if (!isNullorEmpty(selector_number) && isNullorEmpty(customer_number)) { switch (selector_type) { case "barcode_number": if (validateSelectorInput()) { displayCustomerInfo(); } break; case "invoice_number": if (validateSelectorInput()) { displayCustomerInfo(); } break; case "customer_issue": break; } } if (isNullorEmpty(customer_number) && isNullorEmpty(selector_number)) { showAlert('Please enter a customer number or a barcode/invoice number'); //Remove tickets datatable $('#customer_number_tickets_preview_wrapper').hide(); //Reload page var output = url.resolveScript({ deploymentId: 'customdeploy_sl_open_ticket_2', scriptId: 'customscript_sl_open_ticket_2', }) var upload_url = baseURL + output; window.open(upload_url, "_self", "height=750,width=650,modal=yes,alwaysRaised=yes"); } } function updateCustomerNumTicketsTable(ticket_records_dataset) { console.log('Inside update customer tickets table'); $('#customer_number_tickets_preview_wrapper').show(); $('#customer_number_tickets_preview').show(); if (!($.fn.dataTable.isDataTable('#customer_number_tickets_preview'))) { //Initialise new datatable $('#customer_number_tickets_preview').DataTable({ data: ticket_records_dataset, select: { style: 'single' }, columns: [{ title: "ID" }, { title: "Customer Number" }, { title: "Name" }, { title: "Barcode Number" }, { title: "Invoice Number" }, { title: "Customer Issue" }, { title: "Owner" }, { title: "Date created" }] }); //Row selection $('#customer_number_tickets_preview tbody').on('click', 'tr', function() { if ($(this).hasClass('selected')) { $(this).removeClass('selected'); } else { $('#customer_number_tickets_preview tr.selected').removeClass('selected'); $(this).addClass('selected'); var selected_row = $('#customer_number_tickets_preview > tbody > tr.selected'); updateFields(selected_row); } }); } else { //Update datatable rows var datatable = $('#customer_number_tickets_preview').DataTable().clear(); datatable.rows.add(ticket_records_dataset); datatable.draw(); } } function updateFields(selected_row) { //All tickets in here always exist so we can directly redirect to the Edit ticket page console.log('Inside update fields'); var barcode_number = selected_row.children()[3].textContent.trim(); var invoice_number = selected_row.children()[4].textContent.trim(); var customer_issue_type = selected_row.children()[5].textContent.trim(); var ticket_id = selected_row.children()[0].textContent.trim(); if (!isNullorEmpty(barcode_number) || !isNullorEmpty(invoice_number)) { var selector_type = isNullorEmpty(barcode_number) ? "invoice_number" : "barcode_number"; currRec.setValue({ fieldId: 'custpage_selector_type', value: selector_type }); //Set selector value var selector_number = isNullorEmpty(barcode_number) ? invoice_number : barcode_number; $('#selector_value').val(selector_number); // If a ticket already exists for the barcode number, the user is redirected to the "Edit Ticket" page. if (ticketLinkedToSelector(selector_number)) { console.log('ticket linked to barcode') var ticket_id = currRec.getValue({ fieldId: 'custpage_ticket_id' }); var params = { ticket_id: parseInt(ticket_id), selector_number: selector_number, selector_type: selector_type }; params = JSON.stringify(params); var output = url.resolveScript({ deploymentId: 'customdeploy_sl_open_ticket_2', scriptId: 'customscript_sl_open_ticket_2', }); var upload_url = baseURL + output + '&custparam_params=' + params; window.open(upload_url, "_self", "height=750,width=650,modal=yes,alwaysRaised=yes"); } displayCustomerInfo(); } else { var selector_type = "customer_issue"; currRec.setValue({ fieldId: 'custpage_selector_type', value: selector_type }); currRec.setValue({ fieldId: 'custpage_selector_number', value: customer_issue_type }); console.log('In displayCustomerIssueInfo - ' + customer_issue_type); var params = { ticket_id: parseInt(ticket_id.slice(4, 8)), selector_number: customer_issue_type, selector_type: selector_type }; params = JSON.stringify(params); var output = url.resolveScript({ deploymentId: 'customdeploy_sl_open_ticket_2', scriptId: 'customscript_sl_open_ticket_2', }); var upload_url = baseURL + output + '&custparam_params=' + params; window.open(upload_url, "_self", "height=750,width=650,modal=yes,alwaysRaised=yes"); } } /** * Updates the enquiry medium multi-select field and the enquiry count by chat, phone and email fields in the client side */ function updateEnquiryMediumAndCount() { $('.increment_enquiry_count_by_chat, .increment_enquiry_count_by_phone, .increment_enquiry_count_by_email').click(function() { console.log("Clicked increment"); //Get total enquiry count and increment by 1 var total_enquiry_count = $('#total_enquiry_count').val(); $('#total_enquiry_count').val(++total_enquiry_count); if (this.className.indexOf('increment_enquiry_count_by_chat') !== -1) { console.log("In chat click"); //Get chat enquiry count and increment by 1 var enquiry_count_by_chat = $('#enquiry_count_by_chat').val(); $('#enquiry_count_by_chat').val(++enquiry_count_by_chat); //Select the chat option in medium list $('#enquiry_medium_status option[value="3"]').prop('selected', true); } if (this.className.indexOf('increment_enquiry_count_by_phone') !== -1) { //Get phone enquiry count and increment by 1 var enquiry_count_by_phone = $('#enquiry_count_by_phone').val(); $('#enquiry_count_by_phone').val(++enquiry_count_by_phone); //Select the phone option in medium list $('#enquiry_medium_status option[value="1"]').prop('selected', true); } if (this.className.indexOf('increment_enquiry_count_by_email') !== -1) { //Get email enquiry count and increment by 1 var enquiry_count_by_email = $('#enquiry_count_by_email').val(); $('#enquiry_count_by_email').val(++enquiry_count_by_email); //Select the email option in medium list $('#enquiry_medium_status option[value="2"]').prop('selected', true); } //Get medium list and update it var medium_list = $('#enquiry_medium_status option:selected').map(function() { return $(this).val() }); medium_list = $.makeArray(medium_list); $('#enquiry_medium_status').val(medium_list).trigger('change'); }); $('.decrement_enquiry_count_by_chat, .decrement_enquiry_count_by_phone, .decrement_enquiry_count_by_email').click(function() { var total_enquiry_count = $('#total_enquiry_count').val(); if (this.className.indexOf('decrement_enquiry_count_by_chat') !== -1) { var enquiry_count_by_chat = $('#enquiry_count_by_chat').val(); if (enquiry_count_by_chat > 0) { $('#enquiry_count_by_chat').val(--enquiry_count_by_chat); $('#total_enquiry_count').val(--total_enquiry_count); } if (enquiry_count_by_chat === 0) { //Unselect medium list option $('#enquiry_medium_status option[value="3"]').prop('selected', false); } } if (this.className.indexOf('decrement_enquiry_count_by_phone') !== -1) { var enquiry_count_by_phone = $('#enquiry_count_by_phone').val(); if (enquiry_count_by_phone > 0) { $('#enquiry_count_by_phone').val(--enquiry_count_by_phone); $('#total_enquiry_count').val(--total_enquiry_count); } if (enquiry_count_by_phone === 0) { $('#enquiry_medium_status option[value="1"]').prop('selected', false); } } if (this.className.indexOf('decrement_enquiry_count_by_email') !== -1) { var enquiry_count_by_email = $('#enquiry_count_by_email').val(); if (enquiry_count_by_email > 0) { $('#enquiry_count_by_email').val(--enquiry_count_by_email); $('#total_enquiry_count').val(--total_enquiry_count); } if (enquiry_count_by_email === 0) { $('#enquiry_medium_status option[value="2"]').prop('selected', false); } } //Get medium list and update it var medium_list = $('#enquiry_medium_status option:selected').map(function() { return $(this).val() }); medium_list = $.makeArray(medium_list); $('#enquiry_medium_status').val(medium_list).trigger('change'); }); $('.increment_interaction_count_by_chat, .increment_interaction_count_by_phone, .increment_interaction_count_by_email').click(function() { console.log("Clicked increment"); //Get total interaction count and increment by 1 var total_interaction_count = $('#total_interaction_count').val(); $('#total_interaction_count').val(++total_interaction_count); if (this.className.indexOf('increment_interaction_count_by_chat') !== -1) { console.log("In chat click"); //Get chat interaction count and increment by 1 var interaction_count_by_chat = $('#interaction_count_by_chat').val(); $('#interaction_count_by_chat').val(++interaction_count_by_chat); } if (this.className.indexOf('increment_interaction_count_by_phone') !== -1) { //Get phone interaction count and increment by 1 var interaction_count_by_phone = $('#interaction_count_by_phone').val(); $('#interaction_count_by_phone').val(++interaction_count_by_phone); } if (this.className.indexOf('increment_interaction_count_by_email') !== -1) { //Get email interaction count and increment by 1 var interaction_count_by_email = $('#interaction_count_by_email').val(); $('#interaction_count_by_email').val(++interaction_count_by_email); //Select the email option in medium list } }); $('.decrement_interaction_count_by_chat, .decrement_interaction_count_by_phone, .decrement_interaction_count_by_email').click(function() { var total_interaction_count = $('#total_interaction_count').val(); if (this.className.indexOf('decrement_interaction_count_by_chat') !== -1) { var interaction_count_by_chat = $('#interaction_count_by_chat').val(); if (interaction_count_by_chat > 0) { $('#interaction_count_by_chat').val(--interaction_count_by_chat); $('#total_interaction_count').val(--total_interaction_count); } } if (this.className.indexOf('decrement_interaction_count_by_phone') !== -1) { var interaction_count_by_phone = $('#interaction_count_by_phone').val(); if (interaction_count_by_phone > 0) { $('#interaction_count_by_phone').val(--interaction_count_by_phone); $('#total_interaction_count').val(--total_interaction_count); } if (interaction_count_by_phone === 0) { $('#interaction_medium_status option[value="1"]').prop('selected', false); } } if (this.className.indexOf('decrement_interaction_count_by_email') !== -1) { var interaction_count_by_email = $('#interaction_count_by_email').val(); if (interaction_count_by_email > 0) { $('#interaction_count_by_email').val(--interaction_count_by_email); $('#total_interaction_count').val(--total_interaction_count); } if (interaction_count_by_email === 0) { $('#interaction_medium_status option[value="2"]').prop('selected', false); } } //Get medium list and update it var medium_list = $('#interaction_medium_status option:selected').map(function() { return $(this).val() }); medium_list = $.makeArray(medium_list); $('#interaction_medium_status').val(medium_list).trigger('change'); }); } function openAndNew() { var currRec = currentRecord.get(); currRec.setValue({ fieldId: 'custpage_open_new_ticket', value: 'T' }); // Trigger the submit function. $('#submitter').trigger('click'); } function updateAndNew() { var currRec = currentRecord.get(); currRec.setValue({ fieldId: 'custpage_open_new_ticket', value: 'T' }); // Trigger the submit function. $('#submitter').trigger('click'); } /** * Function to save the medium list depending on chat, phone and email enquiry values */ function saveMediumList(enquiry_count_by_chat, enquiry_count_by_phone, enquiry_count_by_email, ticketRecord) { var medium_list = $('#enquiry_medium_status option:selected').map(function() { return $(this).val() }); medium_list = $.makeArray(medium_list); if (enquiry_count_by_phone >= 1 && medium_list.indexOf("1") === -1) { medium_list.push("1"); } if (enquiry_count_by_email >= 1 && medium_list.indexOf("2") === -1) { medium_list.push("2"); } if (enquiry_count_by_chat >= 1 && medium_list.indexOf("3") === -1) { medium_list.push("3"); } if (enquiry_count_by_phone === "0") { var index = medium_list.indexOf("1"); if (index > -1) { medium_list.splice(index, 1); } } if (enquiry_count_by_email === "0") { var index = medium_list.indexOf("2"); if (index > -1) { medium_list.splice(index, 1); } } if (enquiry_count_by_chat === "0") { var index = medium_list.indexOf("3"); if (index > -1) { medium_list.splice(index, 1); } } ticketRecord.setValue({ fieldId: 'custrecord_enquiry_medium', value: medium_list }); } /** * Triggered when a customer calls for an issue with a barcode that is not his. * Reorganize the shown sections. */ function onEscalate() { console.log("onesc"); var currRec = currentRecord.get(); currRec.setValue({ fieldId: 'custpage_selector_issue', value: 'T' }); //Set status to Escalated // currRec.setValue({ fieldId: 'custpage_ticket_status_value', value: 10) }; $('#submitter').val('Escalate to Owner'); $('#submit_ticket').val('ESCALATE TO OWNER'); // Hide the "Escalate" button $('#tbl_custpage_escalate').closest('td').hide(); $('#tbl_custpage_escalate').closest('td').prev().hide(); $('.open_and_new_ticket_btn').addClass('hide'); $('.escalate').addClass('hide'); updateButtonsWidth(); // Hide the contacts fields and contact details sections $('.daytodaycontact_section').addClass('hide'); $('.zee_main_contact_section').addClass('hide'); $('.mpex_stock_used_section').addClass('hide'); $('.final_delivery_section').addClass('hide'); $('.mpex_contact_section').addClass('hide'); $('.contacts_section').addClass('hide'); $('.reviewcontacts_section').addClass('hide'); // Hide the send email section $('#send_email_container').addClass('hide'); // Show that the Issue Customer Name, the MP Issue and the Comment are mandatory $('.mandatory').removeClass('hide'); // Show the "MP Issues" field and the "Owner" text area $('.mp_issues_section').removeClass('hide'); selectOwner(); // Hide the tickets datatable $('.tickets_datatable_section').addClass('hide'); $('#tickets-preview_wrapper').addClass('hide'); //Hide tickets enquiry section $('.ticket_enquiry_header_section').addClass('hide'); $('.enquiry_medium_section').addClass('hide'); $('.enquiry_count_breakdown_section').addClass('hide'); $('.interaction_count_breakdown_section').addClass('hide'); $('.ticket_enquiry_header_section').addClass('hide'); $('.label_section').addClass('hide'); //Hide previous emails section $('.previous_emails_header').addClass('hide'); $('.previous_emails_section').addClass('hide'); //Hide customer ticket related issues $('.ss_section').addClass('hide'); $('.browser_os_section').addClass('hide'); $('.phone_section').addClass('hide'); $('.login_email_used_section').addClass('hide'); var selector_type = currRec.getValue({ fieldId: 'custpage_selector_type' }); if (selector_type == "customer_issue") { var selector_number = currRec.getValue({ fieldId: 'custpage_selector_number' }); if (selector_number == "Customer App") { //Set current chosen option to Customer App var mp_issues_option_inline_html = '<option value="10" selected> Customer App Issue</option>'; } else if (selector_number == "Customer Portal") { //Set current chosen option to Customer Portal var mp_issues_option_inline_html = '<option value="9" selected> Customer App Issue</option>'; } else if (selector_number == "Update Label") { //Set current chosen option to Update Label var mp_issues_option_inline_html = '<option value="11" selected> Customer App Issue</option>'; } $('#mp_issues').html(mp_issues_option_inline_html); //Requires double refresh. One for the dropwdown chnage and sceond for selection $('#mp_issues').selectpicker('refresh'); $('#mp_issues').selectpicker('refresh') } } /** * If the barcode number validation raises an error, the fields are cleared. * The informations linked to the previous barcode are deleted. */ function clearFields() { $('#customer_name').val(''); // Unselect all TOLL Issues fields $('#toll_issues option:selected').each(function() { $(this).attr('selected', false); }); $('#comment').val(''); } /** * Called when "Escalate to Owner" is clicked. * Check that in case of an issue with a barcode, the mandatory fields are filled. * @param {String} selector_type * @returns {Boolean} */ function validateIssueFields(selector_type) { var alertMessage = ''; var return_value = true; var toll_issues_length = $('#toll_issues option:selected').length; var mp_issues_length = $('#mp_issues option:selected').length; var invoice_issues_length = $('#invoice_issues option:selected').length; var comment = $('#comment').val(); var usernote = $('#user_note_textarea').val(); switch (selector_type) { case 'barcode_number': if (toll_issues_length == 0) { alertMessage += 'Please select a TOLL Issue<br>'; return_value = false; } if (isNullorEmpty(comment)) { alertMessage += 'Please type a comment<br>'; return_value = false; } break; case 'invoice_number': if (invoice_issues_length == 0) { alertMessage += 'Please select an Invoice Issue<br>'; return_value = false; } if (isNullorEmpty(usernote)) { alertMessage += 'Please type a User Note<br>'; return_value = false; } break; } if (return_value == true && mp_issues_length == 0) { alertMessage += 'Please select an MP Issue<br>'; return_value = false; } if (return_value == false) { showAlert(alertMessage); } else { $('#alert').parent().hide(); } return return_value; } /** * Send the email with the information regarding the ticket to the email adresses in the array 'to'. * @param {String} selector_type * @param {Array} to * @param {Boolean} is_issue * @returns {Boolean} Whether the email was sent or not. */ function sendInformationEmailTo(selector_type, to, is_issue) { console.log("sek type", selector_type); console.log("to", to); console.log("is_issue", is_issue); // There is an issue with the barcode // The owner should be contacted. if (is_issue) { var validate_issue_fields = validateIssueFields(selector_type); if (!validate_issue_fields) { return false; } } var selector_number = $('#selector_value').val(); var customer_name = $('#customer_name').val(); var comment = $('#comment').val(); var selected_title = $('#user_note_title option:selected').text(); var usernote_textarea = $('#user_note_textarea').val(); var date = new Date(); var email_subject = 'MP Ticket issue - ' + selector_number; var email_body = ''; email_body += 'Environment : ' + runtime.envType + '\n'; email_body += 'Date & Time : ' + formatDate(date) + '\n'; switch (selector_type) { case 'barcode_number': email_body += 'Barcode Number : ' + selector_number + '\n'; break; case 'invoice_number': email_body += 'Invoice Number : ' + selector_number + '\n'; break; case 'customer_issue': email_body += 'Customer associated ticket : ' + selector_number + '\n'; break; } email_body += 'Customer Name : ' + customer_name + '\n'; switch (selector_type) { case 'barcode_number': email_body += 'TOLL Issues : '; $('#toll_issues option:selected').each(function() { email_body += $(this).text() + '\n'; }); break; case 'invoice_number': email_body += 'Invoice Issues : '; $('#invoice_issues option:selected').each(function() { email_body += $(this).text() + '\n'; }); break; } email_body += 'MP Issues : '; $('#mp_issues option:selected').each(function() { email_body += $(this).text() + '\n'; }); if (selector_type == 'invoice_number') { if (!isNullorEmpty(comment.trim())) { comment += '\n'; } var date = new Date(); var dnow = format.parse({ value: date, type: format.Type.DATETIMETZ }); var usernote = '[' + selected_title + '] - [' + userName + '] - [' + dnow + '] - ' + usernote_textarea; comment += usernote; } email_body += 'Comment : ' + comment; var cc = [] //CC email addresses // Now the escalation and information emails are sent from the user addresses. console.log("emailsend"); email.send({ author: 112209, body: email_body, recipients: to, subject: email_subject, cc: cc, }); // 112209 is from MailPlus Team return true; } /** * Redirect to the "View MP Tickets" page without saving any changes. */ function onCancel() { console.log("cancel"); var status_value = currRec.getValue({ fieldId: 'custpage_ticket_status_value' }); if (isTicketNotClosed(status_value)) { var output = url.resolveScript({ deploymentId: 'customdeploy_sl_edit_ticket_2', scriptId: 'customscript_sl_edit_ticket_2', }); var upload_url = baseURL + output; } else { var output = url.resolveScript({ deploymentId: 'customdeploy_sl_edit_closed_ticket_2', scriptId: 'customscript_sl_edit_closed_ticket_2', }); var upload_url = baseURL + output; } window.open(upload_url, "_self", "height=750,width=650,modal=yes,alwaysRaised=yes"); } /** * Function to return the customer id given a customer number * @param {*} customer_number */ function getCustomerID(customer_number) { var customer_search = search.load({ type: 'customer', id: 'customsearch_customer_name_2' }); customer_search.filters.push(search.createFilter({ name: 'entityid', operator: 'haskeywords', values: customer_number, })); var result_set = customer_search.run().getRange({ start: 0, end: 1000 }); result_set.forEach(function(search_value) { console.log("search va", search_value); }); var customerId = result_set[0].id; console.log(customerId, "custid"); return customerId; } /** * Checks that the given customer number is valid * Returns the customer record if found, else returns null */ function isCustomerNumberValid(customer_number) { if (!isNullorEmpty(customer_number)) { var customer_search = search.load({ type: 'customer', id: 'customsearch_customer_name_2' }); var new_filter = search.createFilter({ name: 'entityid', operator: 'is', values: customer_number, }) customer_search.filters.push(new_filter); try { var result_set = customer_search.run(); if (result_set.getRange({ start: 0, end: 1000 }) != null && result_set.getRange({ start: 0, end: 1000 }).length > 0) { // Customer found. return true; } else { //Customer does not exist in record showAlert('Enter a valid customer number. Customer ' + customer_number + ' does not exist'); return false; } } catch (error) { //Undefined ID error return false; } } else { showAlert('Enter a customer number'); return false; } } /** * - If the barcode record exists but there is an MP Ticket issue with the record, * the onEscalate function is called. * @return {Boolean} Whether or not all the input has been filled. */ function validateSelectorInput() { console.log('In validateSelectorInput()'); var selector_number = $('#selector_value').val().trim().toUpperCase(); $('#selector_value').val(selector_number); var selector_type = $('#selector_text').text().toLowerCase().split(' ').join('_'); console.log(selector_number); console.log(selector_type); var alertMessage = ''; var return_value = true; var keep_selector_number = false; if (isNullorEmpty(selector_number)) { switch (selector_type) { case 'invoice_number': alertMessage += 'Please enter the Invoice Number<br>'; break; case 'barcode_number': alertMessage += 'Please enter the Barcode Number<br>'; break; default: alertMessage += 'Please enter a selector number or a customer issue <br>'; } return_value = false; } if ((return_value == true) && (!checkSelectorFormat(selector_number, selector_type))) { switch (selector_type) { case 'invoice_number': alertMessage += 'The Invoice Number format is incorrect<br>'; break; case 'barcode_number': alertMessage += 'The Barcode Number format is incorrect<br>'; break; } return_value = false; } // If a ticket already exists for the barcode number, the user is redirected to the "Edit Ticket" page. if (return_value && ticketLinkedToSelector(selector_number)) { console.log('tic ket linked to barcode') var ticket_id = currRec.getValue({ fieldId: 'custpage_ticket_id' }); var params = { ticket_id: parseInt(ticket_id), selector_number: selector_number, selector_type: selector_type }; params = JSON.stringify(params); var output = url.resolveScript({ deploymentId: 'customdeploy_sl_open_ticket_2', scriptId: 'customscript_sl_open_ticket_2', }); var upload_url = baseURL + output + '&custparam_params=' + params; window.open(upload_url, "_self", "height=750,width=650,modal=yes,alwaysRaised=yes"); } if (return_value) { console.log('Escalate to owner cases'); switch (selector_type) { //Escalate to owner cases case 'invoice_number': var activeInvoiceResults = getSelectorRecords(selector_number, selector_type); if ((isNullorEmpty(activeInvoiceResults))) { alertMessage += 'No invoice record exists for the invoice number ' + selector_number + '<br>'; keep_selector_number = true; $('.customer_section').addClass('hide'); clearFields(); currRec.setValue({ fieldId: 'custpage_selector_id', value: '' }); return_value = false; } break; case 'barcode_number': var activeBarcodeResults = getSelectorRecords(selector_number, selector_type); console.log("absdhskhd"); if ((isNullorEmpty(activeBarcodeResults))) { console.log("aasnj"); alertMessage += 'No active barcode record exists for the barcode number ' + selector_number + '<br>'; // $('#mp_issues option[value="1"]').prop('selected', true); // $('#mp_issues option[value="2"]').prop('selected', true); // $('#mp_issues option[value="3"]').prop('selected', true); var mp_issues_list = [1, 2, 3]; $('#mp_issues').selectpicker('val', mp_issues_list); keep_selector_number = true; $('.customer_section').addClass('hide'); clearFields(); currRec.setValue({ fieldId: 'custpage_selector_id', value: '' }); onEscalate(); return_value = false; } console.log("baasnj"); if ((!zeeLinkedToBarcode(activeBarcodeResults))) { alertMessage += 'No franchisee is associated to the barcode ' + selector_number + '<br>'; console.log("casnj"); // $('#mp_issues option[value="1"]').prop('selected', true); // $('#mp_issues option[value="3"]').prop('selected', true); var mp_issues_list = [1, 3]; $('#mp_issues').selectpicker('val', mp_issues_list); keep_selector_number = true; $('.customer_section').addClass('hide'); clearFields(); onEscalate(); return_value = false; } console.log("adasnj"); if ((!customerLinkedToBarcode(activeBarcodeResults))) { alertMessage += 'No customer is associated to the barcode ' + selector_number + '<br>'; console.log("easnj"); //$('#mp_issues option[value="1"]').prop('selected', true); var mp_issues_list = [1]; $('#mp_issues').selectpicker('val', mp_issues_list); keep_selector_number = true; $('.customer_section').addClass('hide'); clearFields(); onEscalate(); return_value = false; } break; } } // if (return_value == false) { // if (!keep_selector_number) { // var last_correct_selector_number = currRec.getValue({ fieldId: 'custpage_selector_number' }); // $('#selector_value').val(last_correct_selector_number); // } // showAlert(alertMessage); // } else { // $('#alert').parent().hide(); // } if (return_value == false) { console.log('Lastcase'); showAlert(alertMessage); } else { $('#alert').parent().hide(); } return return_value; } /** * Displays error messages in the alert box on top of the page. * @param {String} message The message to be displayed. */ function showAlert(message) { $('#danger-alert').html('<button type="button" class="close" id="close-alert" data-dismiss="alert" aria-label="Close"><span aria-hidden="true">&times;</span></button>' + message); $('#danger-alert').parent().show(); $("#danger-alert").fadeTo(3000, 500).slideUp(500, function() { $("#danger-alert").slideUp(500); }); $('html, body').animate({ scrollTop: 0 }, 800) } /** * Check that if the selector is a barcode number, it starts with 'MPE', * followed by either 'B', 'C', 'D', 'F', 'N' or 'T', * and then finishes by 6 digits. * * If it's an invoice, it should start with 'INV' and then finishes by 6 digits. * @param {String} selector_number * @param {String} selector_type * @returns {Boolean} */ function checkSelectorFormat(selector_number, selector_type) { switch (selector_type) { case 'barcode_number': var barcodeFormat = /^MPE[BCDFNTG]\d{6}$/; var connoteFormat = /^MPXL\d{6}$/; var onlyNumbers = /^\d{20}$/; if (barcodeFormat.test(selector_number) || connoteFormat.test(selector_number) || onlyNumbers.test(selector_number)) { return true; } return false; case 'invoice_number': var invoiceFormat = /^INV\d{6}$/; return invoiceFormat.test(selector_number); } } /** * Searches for an opened ticket linked to this selector number. * The barcode record might not exist, but the ticket associated to the selector number can. * @param {String} selector_number * @returns {Boolean} */ function ticketLinkedToSelector(selector_number) { console.log("selector number", selector_number); var activeTicketFilterExpression = [ [["custrecord_barcode_number", "is", selector_number], "OR", ["altname", "is", selector_number]], 'AND', ["custrecord_ticket_status", "noneof", '3'] ]; var activeTicketsResults = search.create({ type: 'customrecord_mp_ticket', filterExpression: activeTicketFilterExpression }); activeTicketsResults.filters.push(search.createFilter({ name: 'custrecord_ticket_status', operator: search.Operator.NONEOF, values: 3 })); activeTicketsResults.filters.push(search.createFilter({ name: 'formulatext', operator: search.Operator.IS, values: selector_number, formula: '{altname}' })); if (activeTicketsResults.runPaged().count < 1) { console.log("change filters1"); activeTicketsResults.filters.pop(); activeTicketsResults.filters.push(search.createFilter({ name: 'formulatext', operator: search.Operator.IS, values: selector_number, formula: '{custrecord_barcode_number.custrecord_connote_number}' })); } if (activeTicketsResults.runPaged().count < 1) { console.log("change filters2"); activeTicketsResults.filters.pop(); activeTicketsResults.filters.push(search.createFilter({ name: 'formulatext', operator: search.Operator.IS, values: selector_number, formula: '{custrecord_barcode_number.name}' })); } var searchResultCount = activeTicketsResults.runPaged().count; console.log("CNTTTT", searchResultCount); if (isNullorEmpty(activeTicketsResults) || searchResultCount < 1) { console.log("ISNULL") return false; } else { // If an active ticket exists for the barcode number, the ticket_id is saved. // The validate function then redirects the user to its "Edit Ticket" page. var ticket_id = ''; activeTicketsResults.run().each(function(value) { console.log(value); console.log("id", value.id); ticket_id = value.id; return true; }); //console.log("AR2", activeTicketsRes); console.log("matching ticket_id", ticket_id); currRec.setValue({ fieldId: 'custpage_ticket_id', value: ticket_id }); return true; } } /** * Searches for the active barcodes records with the name `barcode_number`, * or for the active invoice records with the name `invoice_number`, * There is normally only one such record. * @param {String} selector_number * @param {String} selector_type * @returns {nlobjSearchResult[]} An array of nlobjSearchResult objects corresponding to the searched records. */ function getSelectorRecords(selector_number, selector_type) { switch (selector_type) { case 'barcode_number': var filterExpression = [ [["name", "is", selector_number], "OR", ["custrecord_connote_number", "is", selector_number]], 'AND', ["isinactive", "is", 'F'] ]; var activeBarcodeColumns = new Array(); activeBarcodeColumns[0] = search.createColumn({ name: 'custrecord_cust_prod_stock_customer', join: null, summary: null }); activeBarcodeColumns[1] = search.createColumn({ name: 'custrecord_cust_prod_stock_zee', join: null, summary: null }); activeBarcodeColumns[2] = search.createColumn({ name: 'custrecord_cust_prod_stock_toll_issues', join: null, summary: null }); activeBarcodeColumns[3] = search.createColumn({ name: 'custrecord_mp_ticket', join: null, summary: null }); activeBarcodeColumns[4] = search.createColumn({ name: 'custrecord_cust_date_stock_used', join: null, summary: null }); activeBarcodeColumns[5] = search.createColumn({ name: 'custrecord_cust_time_stock_used', join: null, summary: null }); activeBarcodeColumns[6] = search.createColumn({ name: 'custrecord_cust_prod_stock_final_del', join: null, summary: null }); activeBarcodeColumns[7] = search.createColumn({ name: 'name', join: null, summary: null }); var activeSelectorResults = search.create({ type: 'customrecord_customer_product_stock', filterExpression: filterExpression, columns: activeBarcodeColumns }); var connoteFormat = /^MPXL\d{6}$/; if (connoteFormat.test(selector_number)) { console.log('connote'); activeSelectorResults.filters.push(search.createFilter({ name: 'custrecord_connote_number', operator: search.Operator.IS, values: selector_number, })); } else { console.log('else'); activeSelectorResults.filters.push(search.createFilter({ name: 'name', operator: search.Operator.IS, values: selector_number, })); } activeSelectorResults.filters.push(search.createFilter({ name: 'isinactive', operator: search.Operator.IS, values: false, })); break; case 'invoice_number': var filterExpression = [ ["tranid", "is", selector_number] ]; var invoiceColumns = new Array(); invoiceColumns[0] = search.createColumn({ name: 'entity', join: null, summary: null }); invoiceColumns[1] = search.createColumn({ name: 'partner', join: null, summary: null }); var activeSelectorResults = search.create({ type: 'invoice', join: null, filterExpression: filterExpression, columns: invoiceColumns }); break; } console.log("abc"); console.log(activeSelectorResults); if (!isNullorEmpty(activeSelectorResults)) { var selector_id = ''; activeSelectorResults.run().each(function(search_res) { console.log("ID", search_res.id); selector_id = search_res.id; return true; }); console.log('selector_id val', selector_id); currRec.setValue({ fieldId: 'custpage_selector_id', value: selector_id }); } return activeSelectorResults; } /** * Verifies that the barcode record is associated to a customer * @param {nlobjSearchResult[]} activeBarcodeResults Result of getSelectorRecords(selector_number, selector_type) * @returns {Boolean} */ function customerLinkedToBarcode(activeBarcodeResults) { // var activeBarcodeResult = activeBarcodeResults[0]; // var customer_id = activeBarcodeResult.getValue('custrecord_cust_prod_stock_customer'); // if (isNullorEmpty(customer_id)) { // return false; // } else { // return true; // } var customer_id; activeBarcodeResults.run().each(function(search_val) { customer_id = search_val.getValue({ name: 'custrecord_cust_prod_stock_customer' }); if (isNullorEmpty(customer_id)) { return true; } else { return false; } }); if (isNullorEmpty(customer_id)) { return false; } else { return true; } } /** * Verifies that the barcode record is associated to a franchisee * @param {nlobjSearchResult[]} activeBarcodeResults Result of getSelectorRecords(selector_number, selector_type) * @returns {Boolean} */ function zeeLinkedToBarcode(activeBarcodeResults) { //var activeBarcodeResult = activeBarcodeResults[0]; var zee_id; activeBarcodeResults.run().each(function(search_val) { zee_id = search_val.getValue({name: 'custrecord_cust_prod_stock_zee' }); console.log("zee", zee_id); if (isNullorEmpty(zee_id)) { return true; } else { return false; } }); if (isNullorEmpty(zee_id)) { return false; } else { return true; } } /** * Returns the customer record for a given customer number * If record does not exist, returns null * @param {*} customer_number */ function customerLinkedToCustomerNum(customer_number) { if (!isNullorEmpty(customer_number)) { var customer_search = search.load({ type: 'customer', id: 'customsearch_customer_name_2' }); var new_filter = search.createFilter({ name: 'entityid', operator: 'haskeywords', values: customer_number, }); customer_search.filters.push(new_filter); try { var result_set = customer_search.run(); if (result_set.getRange({ start: 0, end: 1000 }) != null && result_set.getRange({ start: 0, end: 1000 }).length >= 1) { // Customer found. return result_set.getRange({ start: 0, end: 1000 })[0]; } else { // Customer does not exist in record return null; } } catch (error) { //Undefined ID error return showAlert(error); } } } /** * Displays the informations linked to a selector record. * @returns {Boolean} Whether the function worked well or not. */ function displayCustomerInfo() { console.log('In displayCustomerInfo()'); var selector_number = $('#selector_value').val().trim().toUpperCase(); currRec.setValue({ fieldId: 'custpage_selector_number', value: selector_number }); var selector_type = currRec.getValue({ fieldId: 'custpage_selector_type' }); var activeSelectorResults = getSelectorRecords(selector_number, selector_type); var activeSelectorResult; var selector_id = ''; activeSelectorResults.run().each(function(search_val) { selector_id = search_val.id; activeSelectorResult = search_val; console.log("selector_id", selector_id); }); console.log("asr", activeSelectorResult); //var selector_id = activeSelectorResult.getId(); console.log('selector_id : ', selector_id); console.log('activeSelectorResult : ', activeSelectorResult); currRec.setValue({ fieldId: 'custpage_selector_id', value: selector_id }); switch (selector_type) { case 'barcode_number': var customer_name = activeSelectorResult.getText('custrecord_cust_prod_stock_customer'); var customer_id = activeSelectorResult.getValue('custrecord_cust_prod_stock_customer'); currRec.setValue({ fieldId: 'custpage_customer_id', value: customer_id }); var zee_name = activeSelectorResult.getText('custrecord_cust_prshowAlod_stock_zee'); var zee_id = activeSelectorResult.getValue('custrecord_cust_prod_stock_zee'); var date_stock_used = activeSelectorResult.getValue('custrecord_cust_date_stock_used'); var time_stock_used = activeSelectorResult.getValue('custrecord_cust_time_stock_used'); var final_delivery_val = activeSelectorResult.getValue('custrecord_cust_prod_stock_final_del'); var final_delivery = activeSelectorResult.getText('custrecord_cust_prod_stock_final_del'); //Show the required fields $('.mpex_stock_used_section').show(); $('.final_delivery_enquiry_status_section').show(); //Update values $('#date_stock_used').val(date_stock_used); $('#time_stock_used').val(time_stock_used); $('#final_delivery').attr('data-val', final_delivery_val); $('#final_delivery').val(final_delivery); break; case 'invoice_number': var customer_name = activeSelectorResult.getText('entity'); var customer_id = activeSelectorResult.getValue('entity'); currRec.setValue({ fieldId: 'custpage_customer_id', value: customer_id }); var zee_name = activeSelectorResult.getText('partner'); var zee_id = activeSelectorResult.getValue('partner'); break; } $('#customer_name').val(customer_name); // Load customer record try { var customerRecord = record.load({ type: 'customer', id: customer_id }); var zee_id = customerRecord.getValue({ fieldId: 'partner' }); var daytodayphone = customerRecord.getValue({ fieldId: 'phone' }); var daytodayemail = customerRecord.getValue({ fieldId: 'custentity_email_service' }); var entityid = customerRecord.getValue({ fieldId: 'entityid' }); // Set new customer number value $('#customer_number_value').val(entityid); currRec.setValue({ fieldId: 'custpage_customer_number', value: entityid }); if (selector_type == 'invoice_number') { var accountsphone = customerRecord.getValue({ fieldId: 'altphone' }); var accountsemail = customerRecord.getValue({ fieldId: 'email' }); var maap_bank_account_number = customerRecord.getValue({ fieldId: 'custentity_maap_bankacctno' }); var maap_parent_bank_account_number = customerRecord.getValue({ fieldId: 'custentity_maap_bankacctno_parent' }); var selected_invoice_method_id = customerRecord.getValue({ fieldId: 'custentity_invoice_method' }); var accounts_cc_email = customerRecord.getValue({ fieldId: 'custentity_accounts_cc_email' }); var mpex_po_number = customerRecord.getValue({ fieldId: 'custentity_mpex_po' }); var customer_po_number = customerRecord.getValue({ fieldId: 'custentity11' }); var mpex_invoicing_cycle = customerRecord.getValue({ fieldId: 'custentity_mpex_invoicing_cycle' }); } // Load Franchisee record var zeeRecord = record.load({ type: 'partner', id: zee_id }); var zee_name = zeeRecord.getValue({ fieldId: 'companyname' }); var zee_main_contact_name = zeeRecord.getValue({ fieldId: 'custentity3' }); var zee_email = zeeRecord.getValue({ fieldId: 'email' }); var zee_main_contact_phone = zeeRecord.getValue({ fieldId: 'custentity2' }); $('#daytodayphone').val(daytodayphone); $('#daytodayemail').val(daytodayemail); if (selector_type == 'invoice_number') { $('#accountsphone').val(accountsphone); $('#accountsemail').val(accountsemail); $('#account_number').val(maap_bank_account_number); $('#parent_account_number').val(maap_parent_bank_account_number); // Unselect Invoice all method options fields $('#invoice_method option:selected').each(function() { $(this).attr('selected', false); }); // Select the right invoice method option $('#invoice_method option[value=' + selected_invoice_method_id + ']').prop('selected', true); $('#accounts_cc_email').val(accounts_cc_email); $('#mpex_po_number').val(mpex_po_number); $('#customer_po_number').val(customer_po_number); $('#mpex_invoicing_cycle').val(mpex_invoicing_cycle); } $('#zee_main_contact_name').val(zee_main_contact_name); $('#zee_email').val(zee_email); $('#zee_main_contact_phone').val(zee_main_contact_phone); } catch (e) { if (e instanceof error.SuiteScriptError) { if (error.name == "SSS_MISSING_REQD_ARGUMENT") { console.log('Error to load the customer record with customer_id : ' + customer_id); } } } currRec.setValue({ fieldId: 'custpage_zee_id', value: zee_id }); $('#franchisee_name').val(zee_name); // Contacts details createContactsRows(); switch (selector_type) { case 'barcode_number': // TOLL Issues // Unselect all TOLL Issues fields $('#toll_issues option:selected').each(function() { $(this).attr('selected', false); }); // Select the corresponding TOLL issues var toll_issues = activeSelectorResult.getValue({name: 'custrecord_cust_prod_stock_toll_issues' }); if (!isNullorEmpty(toll_issues)) { toll_issues = toll_issues.split(','); toll_issues.forEach(function(toll_value) { $('#toll_issues option[value=' + toll_value + ']').prop('selected', true); }); } break; case 'invoice_number': // Invoice Issues // If the ticket is not opened yet, there are no Invoice Issues yet. updateInvoicesDatatable(); break; } // Display the tickets linked to the customer in the datatable updateTicketsDatatable(); setReminderDate(); return true; } function searchTicketRecords(customer_number) { var all_ticket_search = search.load({ type: 'customrecord_mp_ticket', id: 'customsearch_ticket_by_custnum' }); var new_filter = search.createFilter({ name: 'custrecord_cust_number', operator: 'contains', values: customer_number, }) all_ticket_search.filters.push(new_filter); var tickets_result_set = all_ticket_search.run().getRange({ start: 0, end: 1000 }); var ticket_records = []; if (!isNullorEmpty(tickets_result_set)) { for (var i = 0; i < tickets_result_set.length; i++) { var ticket_id = tickets_result_set[i].getValue('name'); var cust_number = tickets_result_set[i].getValue('custrecord_cust_number'); var cust_name = tickets_result_set[i].getText('custrecord_customer1'); var barcode_num = tickets_result_set[i].getText('custrecord_barcode_number'); var invoice_num = tickets_result_set[i].getText('custrecord_invoice_number'); var customer_issue = tickets_result_set[i].getValue('custrecord_customer_issue'); var owner = tickets_result_set[i].getText('owner'); var date_created = tickets_result_set[i].getValue('created'); ticket_records.push([ticket_id, cust_number, cust_name, barcode_num, invoice_num, customer_issue, owner, date_created]); } } return ticket_records; } /** * Displays the invoices linked to the customer into a datatable. * @returns {Boolean} Whether the function worked well or not. */ function updateInvoicesDatatable() { var compid = (runtime.envType == "SANDBOX") ? '1048144_SB3' : '1048144'; var customer_id = currRec.getValue({ fieldId: 'custpage_customer_id' }); var invoice_status_filter = $('#invoices_dropdown option:selected').val(); console.log("inv filter", invoice_status_filter); var invoicesSearchResults = loadInvoicesSearch(customer_id, invoice_status_filter); $('#result_invoices').empty(); var invoicesDataSet = []; if (isNullorEmpty(invoicesSearchResults)) { if (isNullorEmpty(customer_id)) { $('#info').text('No customer is associated to this invoice.'); $('#info').parent().show(); return true; } else { try { var customerRecord = record.load({ type: record.Type.CUSTOMER, id: customer_id, isDynamic: true }); var customer_name = customerRecord.getValue({ fieldId: 'altname' }); console.log(customer_name); return true; } catch (error) { if (error instanceof error.SuiteScriptError) { if (error.name == "SSS_MISSING_REQD_ARGUMENT") { console.log('Error to load the customer record with customer_id : ' + customer_id); } } } } } var today = new Date; invoicesSearchResults.each(function(invoiceResult) { var status = invoiceResult.getValue('statusref'); if (status == invoice_status_filter) { var invoice_date = invoiceResult.getValue('trandate'); invoice_date = invoice_date.split(' ')[0]; invoice_date = dateCreated2DateSelectedFormat(invoice_date); var re = /Invoice #([\w]+)/; var invoice_number = invoiceResult.getValue('invoicenum'); invoice_number = invoice_number.replace(re, '$1'); var invoice_id = invoiceResult.id; var invoice_link = baseURL + '/app/accounting/transactions/custinvc.nl?id=' + invoice_id + '&compid=' + compid + '&cf=116&whence='; invoice_number = '<a href="' + invoice_link + '">' + invoice_number + '</a>'; var status_text = invoiceResult.getText('statusref'); var invoice_type = invoiceResult.getText('custbody_inv_type'); var amount_due = invoiceResult.getValue('amountremaining'); var total_amount = invoiceResult.getValue('total'); var due_date_string = invoiceResult.getValue('duedate'); var overdue = ''; if (!isNullorEmpty(due_date_string)) { due_date = stringToDate(due_date_string); var days_overdue = Math.ceil((today - due_date) / 86400000); if (days_overdue > 0) { overdue = days_overdue + ' days (' + due_date_string + ')'; } else { overdue = 'Due date : ' + due_date_string; } } amount_due = financial(amount_due); total_amount = financial(total_amount); invoicesDataSet.push([invoice_date, invoice_number, status_text, invoice_type, amount_due, total_amount, overdue, invoice_id]); } return true; }); // Update datatable rows. var datatable = $('#invoices-preview').DataTable(); datatable.clear(); datatable.rows.add(invoicesDataSet); datatable.draw(); $('[data-toggle="tooltip"]').tooltip(); return true; } /** * Update the headers of the tickets preview datatable, depending on the selector_type. * @param {String} selector_type */ function updateTicketsDatatableHeaders(selector_type) { var table = $('#tickets-preview').DataTable(); var header_cells = table.columns([3, 5, 6]).header().to$(); switch (selector_type) { case 'barcode_number': $.each(header_cells, function(index) { switch (index) { case 0: $(this).text('Barcode Number'); break; case 1: $(this).text('TOLL Issues'); break; case 2: $(this).text('Resolved TOLL Issues'); break; default: break; } }); break; case 'invoice_number': $.each(header_cells, function(index) { switch (index) { case 0: $(this).text('Invoice Number'); break; case 1: $(this).text('Invoice Issues'); break; case 2: $(this).text('Resolved Invoice Issues'); break; default: break; } }); break; } } /** * Displays the tickets linked to the customer into a datatable. * @returns {Boolean} Whether the function worked well or not. */ function updateTicketsDatatable() { var customer_id = currRec.getValue({ fieldId: 'custpage_customer_id' }); var selector_type = currRec.getValue({ fieldId: 'custpage_selector_type' }); var ticketSearchResults = loadTicketsSearch(customer_id); if (!isNullorEmpty(ticketSearchResults)) { ticketSearchResults.filters.push( search.createFilter({ name: 'custrecord_customer1', operator: search.Operator.IS, values: customer_id, }) ); } //console.log("cnt", searchResultCount); console.log('update tickets datatable'); updateTicketsDatatableHeaders(selector_type); $('#result_tickets').empty(); var ticketsDataSet = []; if (isNullorEmpty(ticketSearchResults)) { if (isNullorEmpty(customer_id)) { $('#info').text('No customer is associated to this ticket.'); $('#info').parent().show(); return true; } else { try { var customerRecord = record.load({ type: 'customer', id: customer_id }); var customer_name = customerRecord.getValue({ fieldId: 'altname' }); $('#info').text('No ticket exists for the customer ' + customer_name); $('#info').parent().show(); return true; } catch (e) { if (e instanceof error.SuiteScriptError) { if (e.name == "SSS_MISSING_REQD_ARGUMENT") { console.log('Error to load the customer record with customer_id : ' + customer_id); } } } } } ticketSearchResults.run().each(function(ticketResult) { switch (selector_type) { case 'barcode_number': var ticket_id = ticketResult.getValue('name'); var date_created = ticketResult.getValue('created'); var date_closed = ticketResult.getValue('custrecord_date_closed'); var barcode_number = ticketResult.getText('custrecord_barcode_number'); var status = ticketResult.getText('custrecord_ticket_status'); var toll_issues = ticketResult.getText('custrecord_toll_issues'); toll_issues = toll_issues.split(',').join('<br>'); var resolved_toll_issues = ticketResult.getText('custrecord_resolved_toll_issues'); resolved_toll_issues = resolved_toll_issues.split(',').join('<br>'); var comment = ticketResult.getValue('custrecord_comment'); ticketsDataSet.push([ticket_id, date_created, date_closed, barcode_number, status, toll_issues, resolved_toll_issues, comment]); break; case 'invoice_number': var ticket_id = ticketResult.getValue('name'); var date_created = ticketResult.getValue('created'); var date_closed = ticketResult.getValue('custrecord_date_closed'); var re = /Invoice #([\w]+)/; var invoice_number = ticketResult.getText('custrecord_invoice_number'); invoice_number = invoice_number.replace(re, '$1'); var status = ticketResult.getText('custrecord_ticket_status'); var invoice_issues = ticketResult.getText('custrecord_invoice_issues'); invoice_issues = invoice_issues.split(',').join('<br>'); var resolved_invoice_issues = ticketResult.getText('custrecord_resolved_invoice_issues'); resolved_invoice_issues = resolved_invoice_issues.split(',').join('<br>'); var comment = ticketResult.getValue('custrecord_comment'); comment = comment.split('\n').join('<br>'); ticketsDataSet.push([ticket_id, date_created, date_closed, invoice_number, status, invoice_issues, resolved_invoice_issues, comment]); break; } return true; }); // Update datatable rows. var datatable = $('#tickets-preview').dataTable().api(); datatable.clear(); datatable.rows.add(ticketsDataSet); datatable.draw(); return true; } /** * Load the result set of the invoices records linked to the customer. * @param {String} customer_id * @param {String} invoice_status * @return {nlobjSearchResultSet} invoicesResultSet */ // function loadInvoicesSearch(customer_id, invoice_status) { // if (!isNullorEmpty(customer_id)) { // var invoicesSearch = search.load({ type: 'invoice', id: 'customsearch_mp_ticket_invoices_datatabl' }); // var invoicesFilterExpression = invoicesSearch.filterExpression; // invoicesFilterExpression.push('AND', ['entity', 'is', customer_id]); // if (invoice_status == 'open') { // invoicesFilterExpression.push('AND', ["status", "anyof", "CustInvc:A"]); // Open Invoices // } else if (invoice_status == 'paidInFull') { // invoicesFilterExpression.push('AND', ["status", "anyof", "CustInvc:B"]); // Paid in Full // var today_date = new Date(); // var today_day = today_date.getDate(); // var today_month = today_date.getMonth(); // var today_year = today_date.getFullYear(); // var date_3_months_ago = new Date(Date.UTC(today_year, today_month - 3, today_day)); // var date_3_months_ago_string = format.parse({ value: date_3_months_ago, type: format.Type.DATE }); // invoicesFilterExpression.push('AND', ["trandate", "after", date_3_months_ago_string]); // } // console.log('invoicesFilterExpression : ', invoicesFilterExpression); // invoicesSearch.filterExpression = invoicesFilterExpression; // invoicesResultSet = invoicesSearch.run(); // } // console.log("inv res set", invoicesResultSet) // return invoicesResultSet; // } /** * Load the result set of the invoices records linked to the customer. * @param {String} customer_id * @param {String} invoice_status * @return {nlobjSearchResultSet} invoicesResultSet */ function loadInvoicesSearch(customer_id, invoice_status) { var invoicesResultSet; if (!isNullorEmpty(customer_id)) { var invoicesSearch = search.load({ id: 'customsearch_mp_ticket_invoices_datatabl', type: search.Type.INVOICE }); var invoicesFilterExpression = invoicesSearch.filterExpression; invoicesFilterExpression.push('AND'); invoicesFilterExpression.push(['entity', search.Operator.IS, customer_id]); console.log("inv status", invoice_status); // Open Invoices if (invoice_status == 'open' || isNullorEmpty(invoice_status)) { invoicesFilterExpression.push('AND', ["status", search.Operator.ANYOF, "CustInvc:A"]); // Open Invoices } else if (invoice_status == 'paidInFull') { invoicesFilterExpression.push('AND', ["status", search.Operator.ANYOF, "CustInvc:B"]); // Paid in Full var today_date = new Date(); var today_day = today_date.getDate(); var today_month = today_date.getMonth(); var today_year = today_date.getFullYear(); var date_3_months_ago = new Date(Date.UTC(today_year, today_month - 3, today_day)); var date_3_months_ago_string = formatDate(date_3_months_ago); invoicesFilterExpression.push('AND', ["trandate", search.Operator.AFTER, date_3_months_ago_string]); } invoicesSearch.filterExpression = invoicesFilterExpression; invoicesResultSet = invoicesSearch.run(); var searchResultCount = invoicesSearch.runPaged().count; console.log("cnt", searchResultCount); } return invoicesResultSet; } /** * Load the result set of the tickets records linked to the customer. * WARNING : This method returns only 1000 results. If we want more results, we need to use a saved search * @param {String} customer_id * @return {Array} An array of nlobjSearchResult objects, containing the different ticket records. */ function loadTicketsSearch(customer_id) { var ticketSearchResults = new Array; console.log("custid", customer_id); // If a ticket is opened for a barcode that is not allocated to a customer, // there will be no customer_id. if (!isNullorEmpty(customer_id)) { var filterExpression = search.createFilter({ name: 'custrecord_customer1', operator: 'is', values: customer_id, }); var ticketsColumns = new Array(); ticketsColumns[0] = search.createColumn({ name: 'name' }); ticketsColumns[1] = search.createColumn({ name: 'created' }); ticketsColumns[2] = search.createColumn({ name: 'custrecord_date_closed' }); ticketsColumns[3] = search.createColumn({ name: 'custrecord_barcode_number' }); ticketsColumns[4] = search.createColumn({ name: 'custrecord_invoice_number' }); ticketsColumns[5] = search.createColumn({ name: 'custrecord_ticket_status' }); ticketsColumns[6] = search.createColumn({ name: 'custrecord_toll_issues' }); ticketsColumns[7] = search.createColumn({ name: 'custrecord_resolved_toll_issues' }); ticketsColumns[8] = search.createColumn({ name: 'custrecord_invoice_issues' }); ticketsColumns[9] = search.createColumn({ name: 'custrecord_resolved_invoice_issues' }); ticketsColumns[10] = search.createColumn({ name: 'custrecord_comment' }); ticketSearchResults = search.create({ type: 'customrecord_mp_ticket', filter: filterExpression, columns: ticketsColumns }); } return ticketSearchResults; } /** * Triggered by a click on the button 'ADD/EDIT CONTACTS' ('#reviewcontacts') * Open the 'ticket_contact' page with the parameters : * - Customer ID * - Barcode Number * - Script ID : 'customscript_sl_open_ticket' * - Deployment ID : 'customdeploy_sl_open_ticket' */ function addEditContact() { var customer_id = currRec.getValue({ fieldId: 'custpage_customer_id' }); if (!isNullorEmpty(customer_id)) { var selector_number = currRec.getValue({ fieldId: 'custpage_selector_number' }); var selector_type = currRec.getValue({ fieldId: 'custpage_selector_type' }); var params = { custid: parseInt(customer_id), selector_number: selector_number, selector_type: selector_type, id: 'customscript_sl_open_ticket_2', deploy: 'customdeploy_sl_open_ticket_2' }; params = JSON.stringify(params); var output = url.resolveScript({ deploymentId: 'customdeploy_sl_ticket_contact', scriptId: 'customscript_sl_ticket_contact', }) var upload_url = baseURL + output + '&params=' + params; window.open(upload_url, "_self", "height=750,width=650,modal=yes,alwaysRaised=yes"); } else { $('#info').parent().hide(); showAlert('No customer is associated to this ticket.'); } } /** * Loads the result set of all the contacts linked to a Customer. * @returns {nlobjSearchResultSet} contactsResultSet */ function loadContactsList() { var currRec = currentRecord.get(); var customer_id = currRec.getValue({ fieldId: 'custpage_customer_id' }); var contactsResultSet = []; // If a ticket is opened for a barcode that is not allocated to a customer, // there will be no customer_id. if (!isNullorEmpty(customer_id)) { var contactsSearch = search.load({ type: 'contact', id: 'customsearch_salesp_contacts' }); var contactsFilterExpression = [ ['company', 'is', customer_id], 'AND', ['isinactive', 'is', 'F'] ]; contactsSearch.filterExpression = contactsFilterExpression; contactsResultSet = contactsSearch.run(); } return contactsResultSet; } /** * Dispalys fields related to customer and frnachisee and hides the remaining. */ function displayFranchiseeInfo(customer_record) { var customer_name = customer_record.getValue('companyname'); var daytodayemail = customer_record.getValue('email'); var daytodayphone = customer_record.getValue('phone'); var zee_name = customer_record.getText('partner'); var zee_email = customer_record.getValue({ name: 'email', join: 'partner', summary: null }); var zee_contact_name = customer_record.getValue({ name: 'custentity3', join: 'partner', summary: null }); var zee_abn = customer_record.getValue({ name: 'custentity_abn_franchiserecord', join: 'partner', summary: null }); var zee_phone = customer_record.getValue({ name: 'custentity2', join: 'partner', summary: null }); //Ticket details section $('.customer_name').val(customer_name); $('#daytodayemail').val(daytodayemail); $('#daytodayphone').val(daytodayphone); $('#franchisee_name').val(zee_name); $('#zee_email').val(zee_email); $('#zee_main_contact_name').val(zee_contact_name); $('#zee_main_contact_phone').val(zee_phone); $('#zee_abn').val(zee_abn); createContactsRows(); } /** * - Populates the Contacts table by adding contacts details at each row. * - If there is a ticket_id (which means we are in edit mode), * adds the contact to the "To" field of the "Send Email" section. */ function createContactsRows() { var contactsResultSet = loadContactsList(); console.log(contactsResultSet); // Used for the Contacts Table. var inline_contacts_table_html = ''; // If a ticket is opened for a barcode that is not allocated to a customer, // there will be no contacts. if (!isNullorEmpty(contactsResultSet)) { contactsResultSet.each(function(contactResult) { var contact_id = contactResult.getValue('internalid'); var salutation = contactResult.getValue('salutation'); var first_name = contactResult.getValue('firstname'); var last_name = contactResult.getValue('lastname'); var contact_name = salutation + ' ' + first_name + ' ' + last_name; var contact_email = contactResult.getValue('email'); var contact_phone = contactResult.getValue('phone'); var contact_role_value = contactResult.getValue('contactrole'); var contact_role_text = contactResult.getText('contactrole'); var add_as_recipient_btn = '<button style="background-color: #379E8F; border-color: #379E8F" class="btn btn-success add_as_recipient glyphicon glyphicon-envelope" type="button" data-email="' + contact_email + '" data-firstname="' + first_name + '" data-contact-id="' + contact_id + '" data-toggle="tooltip" data-placement="right" title="Add as recipient"></button>'; inline_contacts_table_html += '<tr class="text-center">'; inline_contacts_table_html += '<td headers="col_name">' + contact_name + '</td>'; inline_contacts_table_html += '<td headers="col_phone">' + contact_phone + '</td>'; inline_contacts_table_html += '<td headers="col_email">' + contact_email + '</td>'; inline_contacts_table_html += '<td headers="col_role">'; inline_contacts_table_html += '<span class="role_value" hidden>' + contact_role_value + '</span>'; inline_contacts_table_html += '<span class="role_text">' + contact_role_text + '</span>'; inline_contacts_table_html += '</td>'; inline_contacts_table_html += '<td headers="col_add_as_recipient">' + add_as_recipient_btn + '</td>'; inline_contacts_table_html += '</tr>'; return true; }); } $('#contacts tbody').html(inline_contacts_table_html); } /** * Populates the Usernote table by adding the usernotes at each row. */ function createUsernoteRows(ticket_id) { // Used for the UserNote Table. var inline_usernote_table_html = ''; ticket_id = parseInt(ticket_id); var ticketRecord = record.load({ type: 'customrecord_mp_ticket', id: ticket_id }); var comment = ticketRecord.getValue({ fieldId: 'custrecord_comment' }); if (!isNullorEmpty(comment)) { var comments = comment.split('\n'); // This regExp matches any content inside brackets, that is not brackets. var re = /\[([^\[\]]+)\]/g; comments.forEach(function(value, index, comments_array) { // Iterate the array from the last element to the first, in order to display the most recent usernote on top. var nb_usernotes = comments_array.length; var usernote = comments_array[nb_usernotes - index - 1]; var usernote_array = usernote.split(' - '); var match_brackets_content_iterator = re[Symbol.matchAll](usernote); // match_brackets_content_array is an array of arrays. // Each of its element contains the matched string (with the brackets), // and the string inside the brackets (which is used for `usernote_title`, `usernote_name` and `usernote_date`. var match_brackets_content_array = Array.from(match_brackets_content_iterator, function(x) { return (x[1]) }); var usernote_title = match_brackets_content_array[0]; var usernote_name = match_brackets_content_array[1]; var usernote_date = match_brackets_content_array[2]; var usernote_text = usernote_array[usernote_array.length - 1]; inline_usernote_table_html += '<tr class="text-center">'; inline_usernote_table_html += '<td headers="col_usernote_title">' + usernote_title + '</td>'; inline_usernote_table_html += '<td headers="col_usernote_name">' + usernote_name + '</td>'; inline_usernote_table_html += '<td headers="col_usernote_date">' + usernote_date + '</td>'; inline_usernote_table_html += '<td headers="col_usernote_comment">' + usernote_text + '</td>'; inline_usernote_table_html += '</tr>'; }); } $('#user_note tbody').html(inline_usernote_table_html); } /** * Function to select TOLL emails */ function selectTollEmails() { var toll_emails = $('#send_toll option:selected').map(function() { return $(this).val() }); toll_emails = $.makeArray(toll_emails); $('toll_emails').selectpicker('val', toll_emails); } /** * Function to select the enquiry medium */ function selectEnquiryMedium() { var medium_list = $('#enquiry_medium_status option:selected').map(function() { return $(this).val() }); medium_list = $.makeArray(medium_list); $('enquiry_medium_status').selectpicker('val', medium_list); } /** * For barcode tickets currently * Based on the selected MP Issue, an Owner is allocated to the ticket. * IT issues have priority over the other issues. */ function selectOwner() { var owner_list = $('#owner option:selected').map(function() { return $(this).val() }); console.log("owner_list", owner_list) owner_list = $.makeArray(owner_list); var list_mp_ticket_issues = $('#mp_issues option:selected').map(function() { return $(this).val() }); list_mp_ticket_issues = $.makeArray(list_mp_ticket_issues); console.log(list_mp_ticket_issues); if (list_mp_ticket_issues.length != 0) { var it_issue = false; var other_issue = '0'; list_mp_ticket_issues.forEach(function(mp_ticket_issue_value) { if (mp_ticket_issue_value < 5) { it_issue = true; } else { other_issue = mp_ticket_issue_value; } }); if (it_issue) { // IT Issue owner_list = owner_list.concat([409635, 696992]); // Select Ankith Ravindran and Raine Giderson. } else if (other_issue != '0') { switch (other_issue) { case '5': // Operational Issue owner_list.push(25537); // Select Michael McDaid. break; case '6': // Finance Issue owner_list.push(280700); // Select Vira Nathania. break; case '7': // Customer Service Issue owner_list.push(386344); // Select Jessica Roberts. break; case '10': // Customer App Issue owner_list = [1132504]; // Select Rianne Mansell break; case '9': // Customer App Issue owner_list = [1132504]; // Select Rianne Mansell break; case '11': // Customer App Issue owner_list = [1132504]; // Select Rianne Mansell break; } } } $('#owner').selectpicker('val', owner_list); } /** * Function triggered when the '#template' input field is blurred. * Load the subject of the email and the body of the template. */ function loadTemplate() { var currRec = currentRecord.get(); var template_id = $('#template option:selected').val(); console.log('template_id : ', template_id); try { var templateRecord = record.load({ type: 'customrecord_camp_comm_template', id: template_id, isDynamic: true }); var template_subject = templateRecord.getValue({ fieldId: 'custrecord_camp_comm_subject' }); console.log("templateRecord", templateRecord); console.log("tempsubj", template_subject); } catch (e) { //if (e instanceof error.SuiteScriptError) { if (e.name == "SSS_MISSING_REQD_ARGUMENT") { console.log('Error to load the template with template_id : ' + template_id); } //} } var customer_id = currRec.getValue({ fieldId: 'custpage_customer_id' }); var sales_rep = encodeURIComponent(runtime.getCurrentUser().name); console.log($('#send_to')) var first_name = $('#send_to').data("firstname"); console.log(first_name) var dear = encodeURIComponent(first_name); var contact_id = ''; var contact_id_array = $('#send_to').data('contact-id'); if (!isNullorEmpty(contact_id_array)) { contact_id_array = JSON.parse(contact_id_array); if (!isNullorEmpty(contact_id_array)) { contact_id = contact_id_array[0].toString(); if (contact_id == '0' && !isNullorEmpty(contact_id[1])) { contact_id = ''; } } } console.log('contact_id : ', contact_id); var userid = encodeURIComponent(runtime.getCurrentUser().id); // var url = 'https://1048144.extforms.netsuite.com/app/site/hosting/scriptlet.nl?script=395&deploy=1&compid=1048144&h=6d4293eecb3cb3f4353e&rectype=customer&template='; // if (runtime.envType == "SANDBOX") { // var url = 'https://1048144-sb3.extforms.netsuite.com/app/site/hosting/scriptlet.nl?script=395&deploy=1&compid=1048144_SB3&h=9c35dc467fbdfafcfeaa&rectype=customer&template='; // } // url += template_id + '&recid=' + customer_id + '&salesrep=' + sales_rep + '&dear=' + dear + '&contactid=' + contact_id + '&userid=' + userid; var suiteletUrl = url.resolveScript({ scriptId: 'customscript_merge_email', deploymentId: 'customdeploy_merge_email', returnExternalUrl: true }); console.log('suiteletUrl', suiteletUrl); suiteletUrl += '&rectype=customer&template='; //var template_id = 94; // var newLeadEmailTemplateRecord = record.load({ // type: 'customrecord_camp_comm_template', // id: template_id, // isDynamic: true // }); //var templateSubject = template_subject; var emailAttach = new Object(); emailAttach['entity'] = customer_id; //https://1048144-sb3.extforms.netsuite.com/app/site/hosting/scriptlet.nl?script=395&deploy=1&compid=1048144_SB3&h=9c35dc467fbdfafcfeaa&rectype=customer&template=91&recid=780069&salesrep=Sruti%20Desai&dear=&contactid=&userid=1115209 suiteletUrl += template_id + '&recid=' + customer_id + '&salesrep=' + sales_rep + '&dear=' + dear + '&contactid=' + null + '&userid=' + userid; // var headerObj = { // name: 'Accept-Language', // value: 'en-us' // }; console.log('suiteletUrl', suiteletUrl); // var response = https.get({ // url: suiteletUrl, // }); // var emailHtml = response.body; var response = https.get({ url: suiteletUrl }); console.log("response", response); // console.log("URL", url); // suiteletUrl = http.request({ // method: http.Method.GET, // url: url, // }) // // urlCall = http.get({ // // url: url, // // }); // console.log(urlCall); var emailHtml = response.body; $('#email_body').summernote('code', emailHtml); var ticket_id = currRec.getValue({ fieldId: 'custpage_ticket_id' }); ticket_id = parseInt(ticket_id); var selector_number = currRec.getValue({ fieldId: 'custpage_selector_number' }); var subject = 'MailPlus [MPSD' + ticket_id + '] - ' + template_subject + ' - ' + selector_number; $('#subject').val(subject); } /** * Check that the fields "To", "Template" and "Subject" are non-empty. * @returns {Boolean} */ function validateEmailFields() { var alertMessage = ''; var return_value = true; var send_to_val = $('#send_to').val(); var send_toll_val = $('#send_toll').val(); if (isNullorEmpty(send_to_val) && isNullorEmpty(send_toll_val)) { return_value = false; alertMessage += 'Please select a recipient.<br>'; } var template_val = $('#template option:selected').val(); if (isNullorEmpty(template_val)) { return_value = false; alertMessage += 'Please select a template.<br>'; } else { var subject_val = $('#subject').val(); if (isNullorEmpty(subject_val)) { return_value = false; alertMessage += 'Please enter a subject.<br>'; } } if (return_value == false) { showAlert(alertMessage); } else { $('#alert').parent().hide(); } return return_value; } /** * Function to sent emails when a customer associated ticket is opened */ function sendCustomerTicketEmail(subject, ticket_id, customer_number, selector_type, selector_number, browser, os, login_email_used, sender_name, sender_phone, send_to) { console.log("in email fn ", send_to); if (isNullorEmpty(browser)) { browser = " - " }; if (isNullorEmpty(os)) { os = " - " }; if (isNullorEmpty(login_email_used)) { login_email_used = " - " }; if (isNullorEmpty(sender_name)) { sender_name = " - " }; if (isNullorEmpty(sender_phone)) { sender_phone = " - " }; var url = "https://1048144.app.netsuite.com/app/site/hosting/scriptlet.nl?script=1243&deploy=1&compid=1048144&"; if (runtime.envType == "SANDBOX") { var url = "https://1048144-sb3.app.netsuite.com/app/site/hosting/scriptlet.nl?script=1243&deploy=1&compid=1048144_SB3"; } var contactEmail = ["PI:EMAIL:nnheo@example.comEND_PI"]; var custparam_params = new Object(); custparam_params['ticket_id'] = parseInt(ticket_id); custparam_params['selector_number'] = selector_number; custparam_params['selector_type'] = selector_type; var ticket_url = url + "&custparam_params=" + encodeURIComponent(JSON.stringify(custparam_params)); if (isNullorEmpty(subject)){ subject = 'MPSD' + ticket_id + ' - New Customer Ticket Opened'; } var body = '' + selector_number + ' Ticket Details <br>'; body += 'Customer number : ' + customer_number + ' <br>'; body += 'Login email used : ' + login_email_used + ' <br>'; switch (selector_number) { case 'Customer App': body += 'Browser : ' + browser + ' <br>'; body += 'Operating system : ' + os + ' <br>'; break; case 'Customer Portal': body += 'Browser : ' + browser + ' <br>'; break; case 'Update Label': body += 'Sender name : ' + sender_name + ' <br>'; body += 'Sender phone : ' + sender_phone + ' <br>'; break; } body += '<a href="' + ticket_url + '"> Open ticket page </a><br>'; body += 'Next reminder time: ' + getNextReminderTime() + ' <br>'; var file = $('#screenshot_image')[0]; if (file && (typeof file.files[0] != 'undefined')) { file = file.files[0]; if ((file.type == "image/jpeg" || file.type == "image/png") && (file.name)) { var fr = new FileReader(); fr.onload = function(e) { body += '<img src=" ' + e.target.result + '">'; console.log("email send", send_to); if (!isNullorEmpty(send_to)) { email.send({ author: userId, body: body, recipients: send_to, subject: subject, cc: contactEmail, }); } } fr.readAsDataURL(file); } } else { if (!isNullorEmpty(send_to)) { console.log("email send", send_to); email.send({ author: userId, body: body, recipients: send_to, subject: subject, cc: contactEmail, }) } } console.log("EMAIL WORKED"); } /** * Triggered by a click on the button 'SEND EMAIL' ('#send_email') * Send the selected email to the selected contact, and reloads the page. */ function sendEmail() { if (validateEmailFields()) { // Send Email // Convert "TO" text field to email adresses array var send_to_values = $('#send_to').val().split(','); var send_to = []; if (!isNullorEmpty(send_to_values)) { send_to_values.forEach(function(email_address) { email_address = email_address.trim(); if (!isNullorEmpty(email_address)) { send_to.push(email_address); } }); } console.log("send_to", send_to); var send_toll_values = $('#send_toll').val(); var send_toll_to = []; if (!isNullorEmpty(send_toll_values)) { for (var i = 0; i < send_toll_values.length; i++) { send_toll_to.push($('#send_toll option:selected').val(send_toll_values)[i].text); } } // CC Field var cc_values = $('#send_cc').val().split(','); var cc = []; cc_values.forEach(function(email_address) { cc.push(email_address.trim()); return true; }); if (isNullorEmpty(cc)) { cc = null; } console.log("cc", cc); // BCC Field var bcc_values = $('#send_bcc').val().split(','); var bcc = []; bcc_values.forEach(function(email_address) { bcc.push(email_address.trim()); return true; }); if (isNullorEmpty(bcc)) { bcc = null; } console.log("bcc", bcc); var email_subject = $('#subject').val(); var email_body = $('#email_body').summernote('code'); var customer_id = currRec.getValue({ fieldId: 'custpage_customer_id' }); var ticket_id = currRec.getValue({ fieldId: 'custpage_ticket_id' }); ticket_id = parseInt(ticket_id); var params_email = currRec.getValue({ fieldId: 'custpage_param_email' }); params_email = JSON.parse(params_email); params_email.recipient = send_to; params_email.subject = email_subject; params_email.body = encodeURIComponent(email_body); params_email.cc = cc; params_email.bcc = bcc; params_email.records = {entityId: customer_id}; var attachments_credit_memo_ids = params_email.attachments_credit_memo_ids; var attachments_usage_report_ids = params_email.attachments_usage_report_ids; var attachments_invoice_ids = params_email.attachments_invoice_ids; params_email = JSON.stringify(params_email); if (!isNullorEmpty(attachments_credit_memo_ids) || !isNullorEmpty(attachments_usage_report_ids) || !isNullorEmpty(attachments_invoice_ids)) { // Send email using the response part of this suitelet script. currRec.setValue({ fieldId: 'custpage_param_email', value: params_email }); setRecordStatusToInProgress(ticket_id); // Trigger the submit function. $('#submitter').trigger('click'); } else { send_to = send_to.concat(send_toll_to); console.log("Final send " + send_to); // If there are no attachments, it's faster to directly use nlapiSendEmail() from the client script. // console.log("email send", recipients); if (!isNullorEmpty(customer_id) && !isNullorEmpty(send_to)) { email.send({ author: userId, body: email_body, recipients: send_to, subject: email_subject, relatedRecords: { entityId: customer_id}, bcc: bcc, cc: cc, }) } else { email.send({ author: userId, body: email_body, recipients: send_to, subject: email_subject, bcc: bcc, cc: cc, }) } // 112209 is from MailPlus Team var selector_number = currRec.getValue({ fieldId: 'custpage_selector_number' }); var selector_type = currRec.getValue({ fieldId: 'custpage_selector_type' }); setRecordStatusToInProgress(ticket_id); // Reload the page var params = { ticket_id: parseInt(ticket_id), selector_number: selector_number, selector_type: selector_type, }; params = JSON.stringify(params); var output = url.resolveScript({ deploymentId: 'customdeploy_sl_open_ticket_2', scriptId: 'customscript_sl_open_ticket_2', }) var upload_url = baseURL + output + '&custparam_params=' + params; window.open(upload_url, "_self", "height=750,width=650,modal=yes,alwaysRaised=yes"); } } else { return false; } } /** * Set record status to 'In Progress'. * @param {Number} ticket_id */ function setRecordStatusToInProgress(ticket_id) { try { var ticketRecord = record.load({ type: 'customrecord_mp_ticket', id: ticket_id }); var status_value = ticketRecord.getValue({ fieldId: 'custrecord_ticket_status' }); var invoice_id = ticketRecord.getValue({ fieldId: 'custrecord_invoice_number' }); if (isNullorEmpty(status_value) || status_value == 1) { //Ticket is open var selector_number = currRec.getValue({ fieldId: 'custpage_selector_number' }); if (isFinanceRoleOnly(userRole) && !isNullorEmpty(invoice_id)) { ticketRecord.setValue({ fieldId: 'custrecord_ticket_status', value: 6 }); } else if (!isNullorEmpty(selector_number) && selector_number == "Customer App") { console.log('Setting ticket status to In progress - IT'); ticketRecord.setValue({ fieldId: 'custrecord_ticket_status', value: 4 }); //In progress - Developers } else { ticketRecord.setValue({ fieldId: 'custrecord_ticket_status', value: 2 }); } ticketRecord.setValue({ fieldId: 'custrecord_email_sent', value: true }); ticketRecord.save({ enableSourcing: true, }) } } catch (e) { console.log("e", e); //if (e instanceof error.SuiteScriptError) { if (e.name == "SSS_MISSING_REQD_ARGUMENT") { console.log('Error to Set record status to In Progress with ticket_id : ' + ticket_id); } //} } } /** * - Triggered by any changes on the TOLL Issues, Invoice Issues or MP Ticket Issues fields. * - Display the button 'CLOSE TICKET' only when there are no selected issues. * - Display the button 'CLOSE UNALLOCATED TICKET' only if the user is Ankith Ravindran or Raine Giderson * and if the issues 'No allocated customer' or 'No allocated franchisee' are selected. */ function hideCloseTicketButton() { // Check that there are no selected issues. var selector_type = currRec.getValue({ fieldId: 'custpage_selector_type' }); var toll_issues_length = $('#toll_issues option:selected').length; var invoice_issues_length = $('#invoice_issues option:selected').length; var mp_issues_length = $('#mp_issues option:selected').length; // Show the 'Close Ticket' Button switch (selector_type) { case 'barcode_number': if ((toll_issues_length == 0) && (mp_issues_length == 0)) { $('.close_ticket').removeClass('hide'); $('.close_ticket_lost').removeClass('hide'); } else { $('.close_ticket').addClass('hide'); $('.close_ticket_lost').addClass('hide'); } break; case 'invoice_number': if ((invoice_issues_length == 0) && (mp_issues_length == 0)) { $('.close_ticket').removeClass('hide'); $('.close_ticket_lost').removeClass('hide'); } else { $('.close_ticket').addClass('hide'); $('.close_ticket_lost').addClass('hide'); } break; } // Show the 'Close Unallocated' button. var mp_issues_selected = $('#mp_issues option:selected').map(function() { return $(this).val() }); mp_issues_selected = $.makeArray(mp_issues_selected); // '1' is the MP Issue 'No Allocated Customer' // '3' is the MP Issue 'No Allocated Franchisee' var is_no_allocated_mp_issue = (mp_issues_selected.indexOf('1') != -1 || mp_issues_selected.indexOf('3') != -1); // '409635' is the user ID of Ankith Ravindran // '696992' is the user ID of Raine Giderson // '766498' is the user ID of RaphaΓ«l Chalicarne var is_user_ankith_or_raine = (userId == '409635' || userId == '696992' || userId == '766498'); var can_show_close_unallocated_button = (is_no_allocated_mp_issue && is_user_ankith_or_raine); if (can_show_close_unallocated_button) { $('.close_unallocated_ticket').removeClass('hide'); } else { $('.close_unallocated_ticket').addClass('hide'); } updateButtonsWidth(); } function updateSaveRecord() { var currRec = currentRecord.get(); var status_value = currRec.getValue({ fieldId: 'custpage_ticket_status_value' }); var selector_issue = currRec.getValue({ fieldId: 'custpage_selector_issue' }); //set to T onEscalate var selector_type = currRec.getValue({ fieldId: 'custpage_selector_type' }); var customer_number = currRec.getValue({ fieldId: 'custpage_customer_number' }); var selector_number = $('#selector_value').val(); console.log('status_value' + status_value) console.log('selector_issue ' + selector_issue) console.log('selector_type ' + selector_type) console.log('selector_number ' + selector_number) if (selector_type == 'customer_issue') { if (isNullorEmpty(customer_number)) { showAlert('Please enter a customer number'); return false; } } // if (isTicketNotClosed(status_value) && !isNullorEmpty(selector_type)) { // // Barcode/Inv associated tickets - check that a TOLL Issue or an Invoice Issue has been selected. // // Customer number associated ticket - check that a customer number has been entered // switch (selector_type) { // case 'barcode_number': // var toll_issues_length = $('#toll_issues option:selected').length; // if (toll_issues_length == 0) { // showAlert('Please select a TOLL Issue<br>'); // return false; // } // break; // case 'invoice_number': // var invoice_issues_length = $('#invoice_issues option:selected').length; // if (invoice_issues_length == 0) { // showAlert('Please select an Invoice Issue<br>'); // return false; // } // break; // case 'customer_issue': // var login_email_used = $('#login_email_text').val(); // if (!isNullorEmpty(login_email_used) && !validateEmail(login_email_used)) { // showAlert('User login email format is invalid. Please enter email again <br>'); // return false; // } // break; // } // } if (role == 1005) { var owner_length = $('#owner option:selected').length; if (owner_length == 0) { showAlert('Please select an Owner<br>'); return false; } } else { var owner_length = $('#owner option:selected').length; var checkTicketOwner = currRec.getValue({ fieldId: 'custpage_ticket_id' }); if (!isNullorEmpty(checkTicketOwner)) { var checkTicketOwnerRec = record.load({ type: 'customrecord_mp_ticket', id: parseInt(checkTicketOwner) }); var owners = checkTicketOwnerRec.getValue({ fieldId: 'custrecord_owner'}); if (isNullorEmpty(owners) && owner_length == 0) { showAlert('Please select an Owner<br>'); return false; } } else { if (owner_length == 0) { showAlert('Please select an Owner<br>'); return false; } } } if (selector_issue == 'T') { var to = $('#owner option:selected').map(function() { return $(this).data('email') }); to = $.makeArray(to); var email_sent = sendInformationEmailTo(selector_type, to, true) if (!email_sent) { return false; } } var ticket_id = currRec.getValue({ fieldId: 'custpage_ticket_id' }); console.log("Ticket id = " + ticket_id); if (isNullorEmpty(ticket_id)) { var ticketRecord = record.create({ type: 'customrecord_mp_ticket', }); currRec.setValue({ fieldId: 'custpage_created_ticket', value: 'T' }); ticketRecord.setValue({ fieldId: 'custrecord_email_sent', value: false }); console.log("DOES FALSE WORK", ticketRecord.getValue({ fieldId: 'custrecord_email_sent' })) } else { ticket_id = parseInt(ticket_id); try { var ticketRecord = record.load({ type: 'customrecord_mp_ticket', id: ticket_id }); } catch (e) { if (e instanceof error.SuiteScriptError) { if (e.name == "SSS_MISSING_REQD_ARGUMENT") { console.log('Error to load the ticket record with ticket_id : ' + ticket_id); } } } } currRec.setValue({ fieldId: 'custpage_selector_number', value: selector_number }); var selector_id = currRec.getValue({ fieldId: 'custpage_selector_id' }); // Save customer number var customer_number = $('#customer_number_value').val(); console.log('Saving customer number = ' + customer_number); ticketRecord.setValue({ fieldId: 'custrecord_cust_number', value: customer_number }); // Save Enquiry status var enquiry_status_val = $('#enquiry_status option:selected').val(); if (!isNullorEmpty(enquiry_status_val)) { ticketRecord.setValue({ fieldId: 'custrecord_enquiry_status', value: enquiry_status_val }); } var attachments_hyperlink = $('#attachments').val(); if (!isNullorEmpty(attachments_hyperlink)) { ticketRecord.setValue({ fieldId: 'custrecord_mp_ticket_attachments', value: attachments_hyperlink }); } // Save Ticket Label var label = $('#label_status option:selected').val(); if (!isNullorEmpty(label)) { ticketRecord.setValue({ fieldId: 'custrecord_ticket_label', value: label }); } //Save Enquiry medium var enquiry_medium = $('#enquiry_status option:selected').val(); if (!isNullorEmpty(enquiry_medium)) { ticketRecord.setValue({ fieldId: 'custrecord_enquiry_medium', value: enquiry_medium }); } var total_enquiry_count = 0; if (!isNullorEmpty($('#enquiry_count_by_chat').val())) { total_enquiry_count += parseInt($('#enquiry_count_by_chat').val()); } if (!isNullorEmpty($('#enquiry_count_by_phone').val())) { total_enquiry_count += parseInt($('#enquiry_count_by_phone').val()); } if (!isNullorEmpty($('#enquiry_count_by_email').val())) { total_enquiry_count += parseInt($('#enquiry_count_by_email').val()); } ticketRecord.setValue({ fieldId: 'custrecord_enquiry_count', value: total_enquiry_count }); var enquiry_count_by_chat = $('#enquiry_count_by_chat').val(); if (!isNullorEmpty(enquiry_count_by_chat)) { ticketRecord.setValue({ fieldId: 'custrecord_chat_enquiry_count', value: enquiry_count_by_chat }); } var enquiry_count_by_phone = $('#enquiry_count_by_phone').val(); if (!isNullorEmpty(enquiry_count_by_phone)) { ticketRecord.setValue({ fieldId: 'custrecord_phone_enquiry_count', value: enquiry_count_by_phone }); } var enquiry_count_by_email = $('#enquiry_count_by_email').val(); if (!isNullorEmpty(enquiry_count_by_email)) { ticketRecord.setValue({ fieldId: 'custrecord_email_enquiry_count', value: enquiry_count_by_email }); } var interaction_count_by_phone = $('#interaction_count_by_phone').val(); var interaction_count_by_email = $('#interaction_count_by_email').val(); if (isNullorEmpty(ticketRecord.getValue({ fieldId: 'custrecord_first_interaction_date'}))) { if (!isNullorEmpty(interaction_count_by_email) || !isNullorEmpty(interaction_count_by_phone)) { ticketRecord.setValue({ fieldId: 'custrecord_first_interaction_date', value: new Date()}); } } if (!isNullorEmpty(interaction_count_by_phone)) { ticketRecord.setValue({ fieldId: 'custrecord_phone_interaction_count', value: interaction_count_by_phone }); } if (!isNullorEmpty(interaction_count_by_email)) { ticketRecord.setValue({ fieldId: 'custrecord_email_interaction_count', value: interaction_count_by_email }); } //Check Enquiry is Selected if (isNullorEmpty(enquiry_count_by_chat) && isNullorEmpty(enquiry_count_by_phone) && isNullorEmpty(enquiry_count_by_email)) { showAlert('Please select an Enquiry Type<br>'); return false; } else if(total_enquiry_count == 0) { showAlert('Please select an Enquiry Type<br>'); return false; } //Save Medium list saveMediumList(enquiry_count_by_chat, enquiry_count_by_phone, enquiry_count_by_email, ticketRecord); ticketRecord = setTicketStatus(ticketRecord); ticketRecord = setCreator(ticketRecord); ticketRecord.setValue({ fieldId: 'altname', value: selector_number }); var owner_email_list = $('#owner option:selected').map(function() { return $(this).data('email') }); owner_email_list = $.makeArray(owner_email_list); var zee_id = currRec.getValue({ fieldId: 'custpage_zee_id' }); ticketRecord.setValue({ fieldId: 'custrecord_zee', value: zee_id }); if (!isNullorEmpty(selector_type)) { switch (selector_type) { case 'barcode_number': ticketRecord.setValue({ fieldId: 'custrecord_barcode_number', value: selector_id }); // Save Reminder date var reminder_date = $('#reminder').val(); if (!isNullorEmpty(reminder_date)) { reminder_date = new Date(reminder_date); console.log(reminder_date); reminder_date = format.parse({ value: reminder_date, type: format.Type.DATE }); console.log("rem date", reminder_date); ticketRecord.setValue({ fieldId: 'custrecord_reminder', value: reminder_date }); } break; case 'invoice_number': ticketRecord.setValue({ fieldId: 'custrecord_invoice_number', value: selector_id }); var customer_id = currRec.getValue({ fieldId: 'custpage_customer_id' }); ticketRecord.setValue({ fieldId: 'custrecord_customer1', value: customer_id }); if (isFinanceRole(userRole)) { var daytodayemail = $('#daytodayemail').val(); var daytodayphone = $('#daytodayphone').val(); var accountsemail = $('#accountsemail').val(); var accountsphone = $('#accountsphone').val(); var selected_invoice_method_id = $('#invoice_method option:selected').val(); var accounts_cc_email = $('#accounts_cc_email').val(); var mpex_po_number = $('#mpex_po_number').val(); var customer_po_number = $('#customer_po_number').val(); var customer_terms = $('#customers_terms').val(); var selected_invoice_cycle_id = $('#mpex_invoicing_cycle option:selected').val(); var customerRecord = record.load({ type: 'customer', id: customer_id }); customerRecord.setValue({ fieldId: 'custentity_email_service', value: daytodayemail }); customerRecord.setValue({ fieldId: 'phone', value: daytodayphone }); customerRecord.setValue({ fieldId: 'email', value: accountsemail }); customerRecord.setValue({ fieldId: 'altphone', value: accountsphone }); customerRecord.setValue({ fieldId: 'custentity_invoice_method', value: selected_invoice_method_id }); customerRecord.setValue({ fieldId: 'custentity_accounts_cc_email', value: accounts_cc_email }); customerRecord.setValue({ fieldId: 'custentity_mpex_po', value: mpex_po_number }); customerRecord.setValue({ fieldId: 'custentity11', value: customer_po_number }); customerRecord.setValue({ fieldId: 'custentity_finance_terms', value: customer_terms }); customerRecord.setValue({ fieldId: 'custentity_mpex_invoicing_cycle', value: selected_invoice_cycle_id }); customerRecord.save({}) // Save Reminder date var reminder_date = $('#reminder').val(); if (!isNullorEmpty(reminder_date)) { reminder_date = new Date(reminder_date); reminder_date = format.parse({ value: reminder_date, type: format.Type.DATE }); ticketRecord.setValue({ fieldId: 'custrecord_reminder', value: reminder_date}); } } break; case 'customer_issue': var screenshot_image = currRec.getValue({ fieldId: 'custpage_ss_image' }); if (!isNullorEmpty(screenshot_image)) { ticketRecord.setValue({ fieldId: 'custrecord_screenshot', value: screenshot_image}); } var customer_id = currRec.getValue({ fieldId: 'custpage_customer_id' }); if (!isNullorEmpty(customer_id)) { ticketRecord.setValue({ fieldId: 'custrecord_customer1', value: customer_id}); } var customer_issue_type = $('#selector_value').val(); if (!isNullorEmpty(customer_issue_type)) { ticketRecord.setValue({ fieldId: 'custrecord_customer_issue', value: customer_issue_type}); } var login_email_used = $('#login_email_text').val(); if (!isNullorEmpty(login_email_used)) { ticketRecord.setValue({ fieldId: 'custrecord_login_email', value: login_email_used}); } var is_customer_number_email_sent = currRec.getValue({ fieldId: 'custpage_customer_number_email_sent' }); switch (customer_issue_type) { case 'Customer App': var phone_used = $('#phone_used').val(); if (!isNullorEmpty(phone_used)) { ticketRecord.setValue({ fieldId: 'custrecord_phone_used', value: phone_used}); } if (is_customer_number_email_sent == 'F' && !isNullorEmpty(ticket_id)) { sendCustomerTicketEmail('',ticket_id, customer_number, selector_type, selector_number, '', '', login_email_used, '', '', owner_email_list); ticketRecord.setValue({ fieldId: 'custrecord_customer_number_email_sent', value: true }); } break; case 'Customer Portal': var browser = $("#browser_value option:selected").val(); if (!isNullorEmpty(browser)) { ticketRecord.setValue({ fieldId: 'custrecord_browser', value: browser}); } var os_used = $('#os_value option:selected').val(); if (!isNullorEmpty(os_used)) { ticketRecord.setValue({ fieldId: 'custrecord_operating_system', value: os_used}); } if (is_customer_number_email_sent == 'F' && !isNullorEmpty(ticket_id)) { sendCustomerTicketEmail('',ticket_id, customer_number, selector_type, selector_number, $("#browser_value option:selected").text(), $('#os_value option:selected').text(), login_email_used, '', '', owner_email_list); ticketRecord.setValue({ fieldId: 'custrecord_customer_number_email_sent', value: true }); } break; case 'Update Label': var sender_name = $('#sender_name_text').val(); if (!isNullorEmpty(sender_name)) { ticketRecord.setValue({ fieldId: 'custrecord_sender_name', value: sender_name}); } var sender_phone = $('#sender_phone_text').val(); if (!isNullorEmpty(sender_phone)) { ticketRecord.setValue({ fieldId: 'custrecord_sender_phone', value: sender_phone}); } if (is_customer_number_email_sent == 'F' && !isNullorEmpty(ticket_id)) { sendCustomerTicketEmail('',ticket_id, customer_number, selector_type, selector_number, '', '', login_email_used, sender_name, sender_phone, owner_email_list); ticketRecord.setValue({ fieldId: 'custrecord_customer_number_email_sent', value: true }); } break; } break; } } ticketRecord = updateIssues(ticketRecord); //Owner var owner_list = new Array; $('#owner option:selected').each(function() { owner_list.push($(this).val()); }); if (!isNullorEmpty(ticket_id)) { // Send email to new owners. var old_owner_list = ticketRecord.getValue({ fieldId: 'custrecord_owner' }); if (!isNullorEmpty(old_owner_list)) { var only_new_owner_ids = []; var only_new_owner_email_address = []; owner_list.forEach(function(new_owner_id) { if (old_owner_list.indexOf(new_owner_id) == -1) { only_new_owner_ids.push(new_owner_id); only_new_owner_email_address.push($('#owner [value="' + new_owner_id + '"]').data('email')); } }) } else { var only_new_owner_ids = owner_list; var only_new_owner_email_address = []; owner_list.forEach(function(owner_id) { only_new_owner_email_address.push($('#owner [value="' + owner_id + '"]').data('email')); }) } // If there is an issue, all the owners have already received an email. if (selector_issue == 'F' && (!isNullorEmpty(only_new_owner_email_address))) { var email_sent = sendInformationEmailTo(selector_type, only_new_owner_email_address, false); if (!email_sent) { return false; } } else if (selector_type == 'customer_issue') { var login_email_used = $('#login_email_text').val(); var customer_issue_type = $('#selector_value').val(); switch (customer_issue_type) { case 'Customer App': var phone_used = $('#phone_used').val(); var os_used = $('#os_value option:selected').val(); var browser = $("#browser_value option:selected").val() sendCustomerTicketEmail('',ticket_id, customer_number, selector_type, selector_number, $("#browser_value option:selected").text(), $('#os_value option:selected').text(), login_email_used, '', '', only_new_owner_email_address); break; case 'Customer Portal': var browser = $('#browser_value').val(); sendCustomerTicketEmail('',ticket_id, customer_number, selector_type, selector_number, $("#browser_value option:selected").text(), '', login_email_used, '', '', only_new_owner_email_address); break; case 'Update Label': var sender_phone = $('#sender_phone_text').val(); var sender_name = $('#sender_name_text').val(); sendCustomerTicketEmail('',ticket_id, customer_number, selector_type, selector_number, '', '', login_email_used, sender_name, sender_phone, only_new_owner_email_address); break; } } } // Save Owner list console.log(owner_list); ticketRecord.setValue({ fieldId: 'custrecord_owner', value: owner_list }); console.log("oList", ticketRecord.getValue({ fieldId: 'custrecord_owner'})); //cxcxc // Save Comment switch (selector_type) { case 'barcode_number': var comment = $('#comment').val(); break; case 'invoice_number': var comment = ticketRecord.getValue({ fieldId: 'custrecord_comment' }); if (isNullorEmpty(comment)) { comment = '' }; var selected_title = $('#user_note_title option:selected').text(); var usernote_textarea = $('#user_note_textarea').val(); var date = new Date; var date_time_now = format.parse({ value: date, type: format.Type.DATETIMETZ}); var date_now = format.parse({ value: date, type: format.Type.DATE}); var time_now = format.parse({ value: date, type: format.Type.TIMEOFDAY}); if (!isNullorEmpty(usernote_textarea)) { if (!isNullorEmpty(comment)) { comment += '\n'; } var usernote = '[' + selected_title + '] - [' + userName + '] - [' + date_time_now + '] - ' + usernote_textarea; // Save usernote on Customer record var userNote = record.create({ type: 'note', }); userNote.setValue({ fieldId: 'title', value: selected_title}); userNote.setValue({ fieldId: 'notedate', value: date_now}); userNote.setValue({ fieldId: 'time', value: time_now}); userNote.setValue({ fieldId: 'note', value: usernote_textarea}); userNote.setValue({ fieldId: 'entity', value: customer_id}); if (!isNullorEmpty(customer_id)) { userNote.save({}) } comment += usernote; } break; case 'customer_issue': var comment = $('#comment').val(); break; } if (!isNullorEmpty(comment)) { var original_comment = ticketRecord.getValue({ fieldId: 'custrecord_comment'} ); var total_comment = $('#comment').val(); var new_comment = total_comment.split(original_comment).join(''); var new_comment = total_comment.split(original_comment).join(''); var new_comment2 = new_comment.split("\n").join(''); //"good_luck_buddy".replace(/\n/,'&').split('&') //["good","luck_buddy"] var date_netsuite = format.format({ value: new Date(), type: format.Type.DATETIME }); console.log("new_comment", new_comment); console.log("new_comment2", new_comment2); var comment_with_date = total_comment; if (!isNullorEmpty(new_comment2)) { comment_with_date = "\n" + original_comment + "\n" + date_netsuite + " - " + new_comment2 + "\n"; } console.log('comment_with_date', comment_with_date); ticketRecord.setValue({ fieldId: 'custrecord_comment', value: comment_with_date} ); } var ticket_id = ticketRecord.save({ enableSourcing: true, }); currRec.setValue({ fieldId: 'custpage_ticket_id', value: ticket_id} ); if (!isNullorEmpty(selector_id) && (selector_type == 'barcode_number')) { try { var list_toll_issues = new Array; $('#toll_issues option:selected').each(function() { list_toll_issues.push($(this).val()); }); var barcodeRecord = record.load({ type: 'customrecord_customer_product_stock', id: selector_id }); console.log("ticket_id", ticket_id); console.log("list_toll_issues", list_toll_issues); barcodeRecord.setValue({ fieldId: 'custrecord_mp_ticket', value: ticket_id} ); barcodeRecord.setValue({ fieldId: 'custrecord_cust_prod_stock_toll_issues ', value: list_toll_issues }); var rec_email = $('#receiveremail').val(); var rec_name = $('#receivername').val(); var rec_state = $('#receiverstate').val(); var rec_zip = $('#receiverzip').val(); var rec_addr1 = $('#receiveraddr1').val(); var rec_addr2 = $('#receiveraddr2').val(); var rec_city = $('#receiversuburb').val(); var rec_phone = $('#receiverphone').val(); //Check if Rec details are to be updated if (!$("#receiveremail").is(":disabled")) { if (!isNullorEmpty(rec_email)) { barcodeRecord.setValue({ fieldId: 'custrecord_receiver_email', value: rec_email }); } if (!isNullorEmpty(rec_name)) { barcodeRecord.setValue({ fieldId: 'custrecord_receiver_name', value: rec_name }); } if (!isNullorEmpty(rec_state)) { barcodeRecord.setValue({ fieldId: 'custrecord_receiver_state', value: rec_state }); } if (!isNullorEmpty(rec_zip)) { barcodeRecord.setValue({ fieldId: 'custrecord_receiver_postcode', value: rec_zip }); } if (!isNullorEmpty(rec_addr1)) { barcodeRecord.setValue({ fieldId: 'custrecord_receiver_addr1', value: rec_addr1 }); } if (!isNullorEmpty(rec_addr2)) { barcodeRecord.setValue({ fieldId: 'custrecord_receiver_addr2', value: rec_addr2 }); } if (!isNullorEmpty(rec_city)) { barcodeRecord.setValue({ fieldId: 'custrecord_receiver_suburb', value: rec_city }); } if (!isNullorEmpty(rec_phone)) { barcodeRecord.setValue({ fieldId: 'custrecord_receiver_phone', value: rec_phone }); } } barcodeRecord.save({ enableSourcing: true, }); } catch (e) { //if (e instanceof error.SuiteScriptError) { // if (e.name == "SSS_MISSING_REQD_ARGUMENT") { console.log('Error to load the barcode record with barcode_id : ' + selector_id); // } //} } } return true; } /** * Triggered by a click on the button 'UPDATE CLOSE TICKET' ('#close_ticket') * Set the date of closure, and the status as "Closed". */ function updateCloseTicket() { console.log('In update&close function'); var date = new Date; var dnow = format.parse({ value: date, type: format.Type.DATETIMETZ }); var ticket_id = currRec.getValue({ fieldId: 'custpage_ticket_id' }); ticket_id = parseInt(ticket_id); var ticketRecord = record.load({ type: 'customrecord_mp_ticket', id: ticket_id }); ticketRecord.setValue({ fieldId: 'custrecord_date_closed', value: dnow }); ticketRecord.setValue({ fieldId: 'custrecord_ticket_status', value: 3 }); ticketRecord.setValue({ fieldId: 'custrecord_mp_ticket_customer_status', value: 5 }); ticketRecord.setValue({ fieldId: 'custrecord_reminder', value: null }); console.log('All values have been set part1'); // Save issues and resolved issues ticketRecord = updateIssues(ticketRecord); var ticket_name = ticketRecord.getText({fieldId: 'name'}); var customer_barcode_number = ticketRecord.getValue({ fieldId : 'custrecord_barcode_number'}); var customer_id = ticketRecord.getValue({fieldId: 'custrecord_customer1'}); try { var barcodeRecord = record.load({ type: 'customrecord_customer_product_stock', id: customer_barcode_number, }); var receiveremail = barcodeRecord.getValue({fieldId: 'custrecord_receiver_email'}); var barcodeName = barcodeRecord.getValue({fieldId: 'name'}); console.log('All values have been set part2'); //Send Email To Customer if (!isNullorEmpty(receiveremail)) { sendCustomerEscalateEmail('MailPlus [' + ticket_name + '] - Ticket Closed - ' + barcodeName, [receiveremail], 114, customer_id); } } catch(e) { console.log("Failed to load barcode because no customer linked"); } console.log('Email sent'); ticketRecord.save({ enableSourcing: true, }) console.log('Redirecting to edit tickets page'); // Redirect to the "View MP Tickets" page var output = url.resolveScript({ deploymentId: 'customdeploy_sl_edit_ticket_2', scriptId: 'customscript_sl_edit_ticket_2', }) var upload_url = baseURL + output; window.open(upload_url, "_self", "height=750,width=650,modal=yes,alwaysRaised=yes"); } function closeTicket(selector_type, status_num) { if (selector_type == "customer_issue") { closeCustIssueTicket(selector_type, status_num); } else { closeBarcodeTicket() } } /** * Triggered by a click on the button 'CLOSE TICKET' ('#close_ticket') * Set the date of closure, and the status as "Closed". */ function closeBarcodeTicket() { if (confirm("Are you sure you want to close this ticket?\n\nThis action cannot be undone.")) { var date = new Date; var dnow = format.parse({ value: date, type: format.Type.DATETIMETZ }); updateSaveRecord(); var ticket_id = currRec.getValue({ fieldId: 'custpage_ticket_id' }); ticket_id = parseInt(ticket_id); var ticketRecord = record.load({ type: 'customrecord_mp_ticket', id: ticket_id }); var customer_id = ticketRecord.getValue({fieldId: 'custrecord_customer1'}); ticketRecord.setValue({ fieldId: 'custrecord_ticket_status', value: 3 }); ticketRecord.setValue({ fieldId: 'custrecord_date_closed', value: dnow }); ticketRecord.setValue({ fieldId: 'custrecord_mp_ticket_customer_status', value: 5 }); ticketRecord.setValue({ fieldId: 'custrecord_reminder', value: null }); // Save issues and resolved issues ticketRecord = updateIssues(ticketRecord); var ticket_name = ticketRecord.getText({fieldId: 'name'}); var customer_barcode_number = ticketRecord.getValue({ fieldId : 'custrecord_barcode_number'}); var customer_id = ticketRecord.getValue({fieldId: 'custrecord_customer1'}); try { var barcodeRecord = record.load({ type: 'customrecord_customer_product_stock', id: customer_barcode_number, }); var receiveremail = barcodeRecord.getValue({fieldId: 'custrecord_receiver_email'}); var barcodeName = barcodeRecord.getValue({fieldId: 'name'}); //Send Email To Customer if (!isNullorEmpty(receiveremail)) { sendCustomerEscalateEmail('MailPlus [' + ticket_name + '] - Ticket Closed - ' + barcodeName, [receiveremail], 114, customer_id); } } catch(e) { console.log("Failed to load barcode because no customer linked"); } ticketRecord.save({ enableSourcing: true, }) // Redirect to the "View MP Tickets" page var output = url.resolveScript({ deploymentId: 'customdeploy_sl_edit_ticket_2', scriptId: 'customscript_sl_edit_ticket_2', }) var upload_url = baseURL + output; window.open(upload_url, "_self", "height=750,width=650,modal=yes,alwaysRaised=yes"); } } function closeCustIssueTicket(selector_type, status_num) { if (confirm("Are you sure you want to close this ticket?\n\nThis action cannot be undone.")) { var ticket_id = parseInt(currRec.getValue({ fieldId: 'custpage_ticket_id' })); var ticketRecord = record.load({ type: 'customrecord_mp_ticket', id: ticket_id }); var customer_id = ticketRecord.getValue({fieldId: 'custrecord_customer1'}); var login_email = $('#login_email_text').val(); var customer_number = $('#customer_number_value').val().trim(); var creator_id = ticketRecord.getValue({fieldId: 'custrecord_creator'}); var escalated_to_it = ticketRecord.getValue({ fieldId: 'custrecord_date_escalated_it' }); if (isNullorEmpty(login_email)) { console.log('No LOGIN EMAIL'); showAlert('Please enter a valid Login Email'); return false; } if (isNullorEmpty(customer_number) && creator_id == 112209 && !isNullorEmpty(escalated_to_it) && selector_type == "customer_issue" && !isNullorEmpty(ticket_id)) { console.log('CUSTOMER NUMBER MISSING'); showAlert('Please enter a Customer Number'); return false; } updateSaveRecord(); var ticketRecord = record.load({ type: 'customrecord_mp_ticket', id: ticket_id }); var date = new Date; var dnow = format.parse({ value: date, type: format.Type.DATETIMETZ }); ticketRecord.setValue({ fieldId: 'custrecord_date_closed', value: dnow }); if (isNullorEmpty(status_num)) { ticketRecord.setValue({ fieldId: 'custrecord_ticket_status', value: 15 }); sendCustomerEscalateEmail('MailPlus [MPSD' + ticket_id + '] - Your IT ticket has been resolved - Customer Portal', [login_email], 121, customer_id); } else { if (status_num == 15) { sendCustomerEscalateEmail('MailPlus [MPSD' + ticket_id + '] - Your IT ticket has been resolved - Customer Portal', [login_email], 121, customer_id); } ticketRecord.setValue({ fieldId: 'custrecord_ticket_status', value: status_num }); } ticketRecord.setValue({ fieldId: 'custrecord_mp_ticket_customer_status', value: 5 }); ticketRecord.setValue({ fieldId: 'custrecord_reminder', value: null }); // Save issues and resolved issues ticketRecord = updateIssues(ticketRecord); var customer_id = ticketRecord.getValue({fieldId: 'custrecord_customer1'}); ticketRecord.save({ enableSourcing: true, }); // Redirect to the "View MP Tickets" page var output = url.resolveScript({ deploymentId: 'customdeploy_sl_edit_ticket_2', scriptId: 'customscript_sl_edit_ticket_2', }) var upload_url = baseURL + output; window.open(upload_url, "_self", "height=750,width=650,modal=yes,alwaysRaised=yes"); } } /** * Triggered by a click on the button 'CLOSE TICKET' ('#close_ticket') * Set the date of closure, and the status as "Closed". */ function closeNewTicket() { if (confirm("Are you sure you want to close this ticket and open a new ticket?\n\nThis action cannot be undone.")) { updateSaveRecord(); var date = new Date; var dnow = format.parse({ value: date, type: format.Type.DATETIMETZ }); var ticket_id = currRec.getValue({ fieldId: 'custpage_ticket_id' }); ticket_id = parseInt(ticket_id); var ticketRecord = record.load({ type: 'customrecord_mp_ticket', id: ticket_id }); ticketRecord.setValue({ fieldId: 'custrecord_date_closed', value: dnow }); ticketRecord.setValue({ fieldId: 'custrecord_ticket_status', value: 3 }); ticketRecord.setValue({ fieldId: 'custrecord_mp_ticket_customer_status', value: 5 }); ticketRecord.setValue({ fieldId: 'custrecord_reminder', value: null }); // Save issues and resolved issues ticketRecord = updateIssues(ticketRecord); var ticket_name = ticketRecord.getText({fieldId: 'name'}); var customer_barcode_number = ticketRecord.getValue({ fieldId : 'custrecord_barcode_number'}); var customer_id = ticketRecord.getValue({fieldId: 'custrecord_customer1'}); try { var barcodeRecord = record.load({ type: 'customrecord_customer_product_stock', id: customer_barcode_number, }); var receiveremail = barcodeRecord.getValue({fieldId: 'custrecord_receiver_email'}); var barcodeName = barcodeRecord.getValue({fieldId: 'name'}); //Send Email To Customer if (!isNullorEmpty(receiveremail)) { sendCustomerEscalateEmail('MailPlus [' + ticket_name + '] - Ticket Closed - ' + barcodeName, [receiveremail], 114, customer_id); } } catch(e) { console.log("Failed to load barcode because no customer linked"); } ticketRecord.save({ enableSourcing: true, }) // Redirect to the Open New Ticket" page // var output = url.resolveScript({ // deploymentId: 'customdeploy_sl_edit_ticket_2', // scriptId: 'customscript_sl_edit_ticket_2', // }) var output = url.resolveScript({ deploymentId: 'customdeploy_sl_open_ticket_2', scriptId: 'customscript_sl_open_ticket_2', }); var upload_url = baseURL + output; window.open(upload_url, "_self", "height=750,width=650,modal=yes,alwaysRaised=yes"); } } /** * Triggered by a click on the button 'CLOSE TICKET - LOST ITEM' ('#close_ticket_lost') * Set the date of closure, and the status as "Closed - Lost Item". */ function closeTicketLost() { if (confirm("Are you sure you want to close this ticket and set it as Closed-Lost?\n\nThis action cannot be undone.")) { updateSaveRecord(); var date = new Date; var dnow = format.parse({ value: date, type: format.Type.DATETIMETZ }); var ticket_id = currRec.getValue({ fieldId: 'custpage_ticket_id' }); ticket_id = parseInt(ticket_id); var ticketRecord = record.load({ type: 'customrecord_mp_ticket', id: ticket_id }); ticketRecord.setValue({ fieldId: 'custrecord_date_closed', value: dnow }); ticketRecord.setValue({ fieldId: 'custrecord_ticket_status', value: 9 }); ticketRecord.setValue({ fieldId: 'custrecord_mp_ticket_customer_status', value: 5 }); ticketRecord.setValue({ fieldId: 'custrecord_reminder', value: null }); // Save issues and resolved issues ticketRecord = updateIssues(ticketRecord); ticketRecord.save({ enableSourcing: true, }); var ticket_name = ticketRecord.getText({fieldId: 'name'}); var customer_barcode_number = ticketRecord.getValue({ fieldId : 'custrecord_barcode_number'}); var customer_id = ticketRecord.getValue({fieldId: 'custrecord_customer1'}); var barcodeRecord = record.load({ type: 'customrecord_customer_product_stock', id: customer_barcode_number, }); var receiveremail = barcodeRecord.getValue({fieldId: 'custrecord_receiver_email'}); var barcodeName = barcodeRecord.getValue({fieldId: 'name'}); //Send Email To Customer if (!isNullorEmpty(receiveremail)) { sendCustomerEscalateEmail('MailPlus [' + ticket_name + '] - Lost In Transit - ' + barcodeName, [receiveremail], 113, customer_id); } var product_order = barcodeRecord.getValue({fieldId: 'custrecord_prod_stock_prod_order'}); var invoice = barcodeRecord.getValue({fieldId: 'custrecord_prod_stock_invoice'}); var userNoteId = barcodeRecord.getValue({fieldId: 'recordid'}); console.log("Invoice", invoice); console.log("product order", product_order); var params = { ticket_id: parseInt(ticket_id), selector_number: barcodeName, selector_type: 'barcode_number' }; params = JSON.stringify(params); var output = url.resolveScript({ deploymentId: 'customdeploy_sl_open_ticket_2', scriptId: 'customscript_sl_open_ticket_2', }); var ticket_url = baseURL + output + '&custparam_params=' + params; //CREDIT MEMO SECTION if (!isNullorEmpty(invoice) && isNullorEmpty(product_order)) { //Error- Send Email to Ankith body = "There's an error with the barcode as only the Invoice field is filled and the Product Order field is not (within the barcode record). Please see below barcode details\n\nMP Ticket: " + ticket_name + '\nBarcode: ' + barcodeName + '\nProduct Order: ' + product_order + '\nTicket URL: ' + ticket_url; email.send({ author: 112209, body: body, recipients: ['PI:EMAIL:kenaa@example.comEND_PI', 'PI:EMAIL:nnheo@example.comEND_PI'], subject: "Test Error MPEX Barcode Credit- LIT " + barcodeName, relatedRecords: {entityId: customer_id}, }); } else if (!isNullorEmpty(invoice) && !isNullorEmpty(product_order)) { //SEND EMAIL TO FIONA + POPIE --> change to raine after mat leave body = 'MP Ticket: ' + ticket_name + '\nBarcode: ' + barcodeName + '\nProduct Order: ' + product_order + '\nInvoice: ' + invoice + '\nTicket URL: ' + ticket_url; email.send({ author: 112209, body: body, recipients: ['PI:EMAIL:kenaa@example.comEND_PI', 'PI:EMAIL:anpch@example.comEND_PI', 'PI:EMAIL:anpch@example.comEND_PI'], subject: "MPEX Barcode Credit- LIT " + barcodeName, relatedRecords: {entityId: customer_id} }) } else { //SEND EMAIL TO FIONA console.log("in here"); body = 'MP Ticket: ' + ticket_name + '\nBarcode: ' + barcodeName + '\nProduct Order: ' + product_order + '\nTicket URL: ' + ticket_url; email.send({ author: 112209, body: body, recipients: ['PI:EMAIL:kenaa@example.comEND_PI', 'PI:EMAIL:anpch@example.comEND_PI'], subject: "MPEX Barcode Credit- LIT " + barcodeName, relatedRecords: {entityId: customer_id} }) } // Create User Note under Barcode Record var userNote = record.create({ type: record.Type.NOTE, isDynamic: true, }); // Record Type i.e Cust Product Stock userNote.setValue({fieldId: 'recordtype', value: 1014}); // Record ID userNote.setValue({fieldId: 'record', value: parseInt(userNoteId) }); //Title userNote.setValue({fieldId: 'title', value: 'Barcode Status- LIT'}); //Memo userNote.setValue({fieldId: 'note', value: 'Barcode ' + barcodeName + ' has been set to status Lost in Transit'}); userNote.save({ enableSourcing: true, ignoreMandatoryFields: true }); // Redirect to the "View MP Tickets" page var output = url.resolveScript({ deploymentId: 'customdeploy_sl_edit_ticket_2', scriptId: 'customscript_sl_edit_ticket_2', }) var upload_url = baseURL + output; window.open(upload_url, "_self", "height=750,width=650,modal=yes,alwaysRaised=yes"); } } /** * Triggered by a click on the button 'CLOSE UNALLOCATED TICKET' ('#close_unallocated_ticket') * Set the date of closure, and the status as "Closed - Unallocated". */ function closeUnallocatedTicket() { if (confirm("Are you sure you want to close this ticket?\n\nThis action cannot be undone.")) { updateSaveRecord(); var date = new Date; var dnow = format.parse({ value: date, type: format.Type.DATETIMETZ }); var ticket_id = currRec.getValue({ fieldId: 'custpage_ticket_id' }); ticket_id = parseInt(ticket_id); var ticketRecord = record.load({ type: 'customrecord_mp_ticket', id: ticket_id }); ticketRecord.setValue({ fieldId: 'custrecord_date_closed', value: dnow }); ticketRecord.setValue({ fieldId: 'custrecord_ticket_status', value: 8 }); ticketRecord.setValue({ fieldId: 'custrecord_mp_ticket_customer_status', value: 5 }); ticketRecord.setValue({ fieldId: 'custrecord_reminder', value: null }); // Save issues and resolved issues ticketRecord = updateIssues(ticketRecord); ticketRecord.save({ enableSourcing: true, }); // Redirect to the "View MP Tickets" page var output = url.resolveScript({ deploymentId: 'customdeploy_sl_edit_ticket_2', scriptId: 'customscript_sl_edit_ticket_2', }) var upload_url = baseURL + output; window.open(upload_url, "_self", "height=750,width=650,modal=yes,alwaysRaised=yes"); } } /** * Set the status of the ticket based on the MP ticket Values. * @param {nlobjRecord} ticketRecord * @returns {nlobjRecord} ticketRecord */ function setTicketStatus(ticketRecord) { var current_status = ticketRecord.getValue({ fieldId: 'custrecord_ticket_status' }); var list_mp_ticket_issues = new Array; $('#mp_issues option:selected').each(function() { list_mp_ticket_issues.push($(this).val()); }); ticketRecord.setValue({ fieldId: 'custrecord_mp_ticket_customer_status', value: 1 }); if (currRec.getValue({ fieldId: 'custpage_selector_issue'}) == 'T') { //Set status to escalated //console.log("Changing status to escalated"); //ticketRecord.setValue({ fieldId: 'custrecord_ticket_status', value: 10 }); } else if (isNullorEmpty(current_status)) { ticketRecord.setValue({ fieldId: 'custrecord_ticket_status', value: 1 }); } else if (list_mp_ticket_issues.length != 0) { var it_issue = false; var other_issue = '0'; list_mp_ticket_issues.forEach(function(mp_ticket_issue_value) { if (mp_ticket_issue_value < 5) { it_issue = true; } else { other_issue = mp_ticket_issue_value; } }); if (it_issue) { ticketRecord.setValue({ fieldId: 'custrecord_ticket_status', value: 4 }); } else if (other_issue != '0') { switch (other_issue) { case '5': // Operational Issue ticketRecord.setValue({ fieldId: 'custrecord_ticket_status', value: 5 }); break; case '6': // Finance Issue ticketRecord.setValue({ fieldId: 'custrecord_ticket_status', value: 6 }); break; case '7': // Customer Service Issue ticketRecord.setValue({ fieldId: 'custrecord_ticket_status', value: 2 }); break; } } } else { // If there are no more MP Ticket issues, if (current_status >= 4) { var email_sent = ticketRecord.getValue({ fieldId: 'custrecord_email_sent' }); console.log(email_sent); if (email_sent) { //If an email has ever been sent to the customer, the status is updated to 'In progress - Customer service' ticketRecord.setValue({ fieldId: 'custrecord_ticket_status', value: 2 }); } else { // If no email has ever been sent to the customer, the status is updated to 'Open' ticketRecord.setValue({ fieldId: 'custrecord_ticket_status', value: 1 }); } } } return ticketRecord; } /** * Set the creator of the ticket if there is none. * @param {nlobjRecord} ticketRecord * @returns {nlobjRecord} ticketRecord */ function setCreator(ticketRecord) { var creator_id = ticketRecord.getValue({ fieldId: 'custrecord_creator' }); if (isNullorEmpty(creator_id)) { var user_id = parseInt(runtime.getCurrentUser().id); ticketRecord.setValue({ fieldId: 'custrecord_creator', value: user_id }); } return ticketRecord; } /** * If we work with a barcode ticket, the TOLL Issues and MP Ticket Issues are added to the record. * If we work with an invoice ticket, the Invoice Issues are added to the record. * If issues have been deleted from any of these fields, they are saved in the resolved fields. * @param {nlobjRecord} ticketRecord * @returns {nlobjRecord} ticketRecord */ function updateIssues(ticketRecord) { var ticket_id = currRec.getValue({ fieldId: 'custpage_ticket_id' }); var selector_type = currRec.getValue({ fieldId: 'custpage_selector_type' }); switch (selector_type) { case 'barcode_number': // Save TOLL Issues var list_toll_issues = new Array; $('#toll_issues option:selected').each(function() { list_toll_issues.push($(this).val()); }); // Save resolved TOLL Issues if (!isNullorEmpty(ticket_id)) { var old_list_toll_issues = ticketRecord.getValue({ fieldId: 'custrecord_toll_issues' }); if (!isNullorEmpty(old_list_toll_issues)) { if (typeof(old_list_toll_issues) == "string") { old_list_toll_issues = [old_list_toll_issues]; } var list_resolved_toll_issues = ticketRecord.getValue({fieldId: 'custrecord_resolved_toll_issues' }); if (isNullorEmpty(list_resolved_toll_issues)) { list_resolved_toll_issues = new Array; } else if (typeof(list_resolved_toll_issues) == "string") { list_resolved_toll_issues = [list_resolved_toll_issues]; } old_list_toll_issues.forEach(function(old_toll_issue) { // If a TOLL issue of the old list is not in the new list, // it means that the issue was resolved. if (list_toll_issues.indexOf(old_toll_issue) == -1) { list_resolved_toll_issues.push(old_toll_issue); } }); ticketRecord.setValue({ fieldId: 'custrecord_resolved_toll_issues', value: list_resolved_toll_issues }); } } console.log("list_toll_issues", list_toll_issues); ticketRecord.setValue({ fieldId: 'custrecord_toll_issues', value: list_toll_issues }); break; case 'invoice_number': // Save Invoice Issues var list_invoice_issues = new Array; $('#invoice_issues option:selected').each(function() { list_invoice_issues.push($(this).val()); }); // Save resolved INVOICE Issues if (!isNullorEmpty(ticket_id)) { var old_list_invoice_issues = ticketRecord.getValue({ fieldId: 'custrecord_invoice_issues' }); if (!isNullorEmpty(old_list_invoice_issues)) { if (typeof(old_list_invoice_issues) == "string") { old_list_invoice_issues = [old_list_invoice_issues]; } var list_resolved_invoice_issues = ticketRecord.getValue({ fieldId: 'custrecord_resolved_invoice_issues' }); if (isNullorEmpty(list_resolved_invoice_issues)) { list_resolved_invoice_issues = new Array; } else if (typeof(list_resolved_invoice_issues) == "string") { list_resolved_invoice_issues = [list_resolved_invoice_issues]; } old_list_invoice_issues.forEach(function(old_invoice_issue) { // If an invoice issue of the old list is not in the new list, // it means that the issue was resolved. if (list_invoice_issues.indexOf(old_invoice_issue) == -1) { list_resolved_invoice_issues.push(old_invoice_issue); } }); ticketRecord.setValue({ fieldId: 'custrecord_resolved_invoice_issues', value: list_resolved_invoice_issues }); } } ticketRecord.setValue({ fieldId: 'custrecord_invoice_issues', value: list_invoice_issues }); break; } // Save MP Ticket Issues var list_mp_ticket_issues = new Array; $('#mp_issues option:selected').each(function() { list_mp_ticket_issues.push($(this).val()); }); // Save resolved MP Ticket Issues if (!isNullorEmpty(ticket_id) && selector_type != "customer_issue") { var old_list_mp_ticket_issues = ticketRecord.getValue({ fieldId: 'custrecord_mp_ticket_issue' }); if (!isNullorEmpty(old_list_mp_ticket_issues)) { old_list_mp_ticket_issues = Array.from(old_list_mp_ticket_issues); var list_resolved_mp_ticket_issues = ticketRecord.getValue({ fieldId: 'custrecord_resolved_mp_ticket_issue' }); if (isNullorEmpty(list_resolved_mp_ticket_issues)) { list_resolved_mp_ticket_issues = new Array; } else { list_resolved_mp_ticket_issues = Array.from(list_resolved_mp_ticket_issues); } old_list_mp_ticket_issues.forEach(function(old_mp_ticket_issue) { // If a MP Ticket issue of the old list is not in the new list, // it means that the issue was resolved. if (list_mp_ticket_issues.indexOf(old_mp_ticket_issue) == -1) { list_resolved_mp_ticket_issues.push(old_mp_ticket_issue); } }); ticketRecord.setValue({ fieldId: 'custrecord_resolved_mp_ticket_issue', value: list_resolved_mp_ticket_issues }); } } ticketRecord.setValue({ fieldId: 'custrecord_mp_ticket_issue', value: list_mp_ticket_issues }); return ticketRecord; } /** * Triggered by a click on the button 'REOPEN TICKET' ('#reopen_ticket') * Set the ticket record as active. * Deletes the date of closure, * Set the status as "Open". */ function reopenTicket() { console.log("in reopen"); console.log("customer number"); var ticket_id = currRec.getValue({ fieldId: 'custpage_ticket_id' }); ticket_id = parseInt(ticket_id); var selector_number = currRec.getValue({ fieldId: 'custpage_selector_number' }); var selector_type = currRec.getValue({ fieldId: 'custpage_selector_type' }); var customer_number = currRec.getValue({ fieldId: 'custpage_customer_number' }); var ticketRecord = record.load({ type: 'customrecord_mp_ticket', id: ticket_id }); ticketRecord.setValue({ fieldId: 'custrecord_date_closed', value: null }); ticketRecord.setValue({ fieldId: 'custrecord_ticket_status', value: 1 }); ticketRecord.setValue({ fieldId: 'custrecord_mp_ticket_customer_status', value: 1 }); // Save Reminder date setReminderDate(); var reminder_date = $('#reminder').val(); console.log("rem3", reminder_date); if (!isNullorEmpty(reminder_date)) { reminder_date = new Date(reminder_date); reminder_date = format.parse({ value: reminder_date, type: format.Type.DATE}); ticketRecord.setValue({ fieldId: 'custrecord_reminder', value: reminder_date }); } // Set new Creator and new Owner ticketRecord.setValue({ fieldId: 'custrecord_creator', value: userId }); ticketRecord.setValue({ fieldId: 'custrecord_owner', value: [userId] }); ticketRecord.save({ enableSourcing: true, }); // Reload the page var params = { ticket_id: parseInt(ticket_id), selector_number: selector_number, selector_type: selector_type, customer_number: customer_number, }; params = JSON.stringify(params); var output = url.resolveScript({ deploymentId: 'customdeploy_sl_open_ticket_2', scriptId: 'customscript_sl_open_ticket_2', }); var upload_url = baseURL + output + '&custparam_params=' + params; window.open(upload_url, "_self", "height=750,width=650,modal=yes,alwaysRaised=yes"); console.log("in reopen"); } /** * Lookup for the Credit Memo associated to an invoice. * @returns {nlobjSearchResult[]} creditMemoResults */ function searchCreditMemo() { var selector_type = currRec.getValue({ fieldId: 'custpage_selector_type' }); if (selector_type == 'invoice_number') { var selector_id = currRec.getValue({ fieldId: 'custpage_selector_id' }); var creditMemoResults = search.create({ type: 'creditmemo', filter: [ search.createFilter({ name: 'mainline', operator: 'is', values: 'T', }), search.createFilter({ name: 'createdfrom', operator: 'is', values: selector_id, }) ], columns: [ search.createColumn({ name: 'tranid', summary: 'group' }), search.createColumn({ name: 'trandate', summary: 'group' }), search.createColumn({ name: 'entity', summary: 'group' }), search.createColumn({ name: 'createdfrom', summary: 'group' }), search.createColumn({ name: 'internalid', summary: 'group' }) ] }); return creditMemoResults.run(); } else { return null; } } /** * searchCreditMemo() searches for Credit Memos linked to the current invoice. * If there are results, they are displayed in the table '#credit_memo'. * Otherwise, the section containing the table is hidden. * @param {Number} status_value */ function createCreditMemoRows(status_value) { var inline_credit_memo_table_html = ''; var compid = (runtime.envType == "SANDBOX") ? '1048144_SB3' : '1048144'; console.log("sv", status_value); var creditMemoResults = searchCreditMemo(); if (!isNullorEmpty(creditMemoResults)) { $('.credit_memo').removeClass('hide'); creditMemoResults.each(function(creditMemoResult) { console.log("CMR", creditMemoResult); var credit_memo_number = creditMemoResult.getValue({ name:'tranid', join: null, summary: 'group' }); var credit_memo_date = creditMemoResult.getValue({ name:'trandate', join: null, summary: 'group' }); var credit_memo_customer_name = creditMemoResult.getText({ name: 'entity', join: null, summary: 'group' }); var credit_memo_customer_id = creditMemoResult.getValue({ name:'entity', join: null, summary: 'group' }); var credit_memo_customer_link = baseURL + '/app/common/entity/custjob.nl?id=' + credit_memo_customer_id; var credit_memo_created_from_id = creditMemoResult.getValue({ name:'createdfrom', join: null, summary: 'group' }); var credit_memo_created_from = creditMemoResult.getText({ name: 'createdfrom', join: null, summary: 'group' }); var invoice_link = baseURL + '/app/accounting/transactions/custinvc.nl?id=' + credit_memo_created_from_id + '&compid=' + compid + '&cf=116&whence='; var credit_memo_id = creditMemoResult.getText({ name: 'internalid', join: null, summary: 'group' }); var credit_memo_link = baseURL + '/app/accounting/transactions/custcred.nl?id=' + credit_memo_id + '&whence='; var credit_memo_url = baseURL + '/app/accounting/print/hotprint.nl?regular=T&sethotprinter=T&formnumber=106&trantype=custcred&id=' + credit_memo_id + '&label=Credit+Memo&printtype=transaction'; var credit_memo_action_button = '<button class="btn btn-success add_cm glyphicon glyphicon-plus" type="button" data-toggle="tooltip" data-placement="right" data-cm-id="' + credit_memo_id + '" data-cm-url="' + credit_memo_url + '" title="Attach to email"></button>'; inline_credit_memo_table_html += '<tr class="text-center">'; inline_credit_memo_table_html += '<td headers="credit_memo_number"><a href="' + credit_memo_link + '">' + credit_memo_number + '</a></td>'; inline_credit_memo_table_html += '<td headers="credit_memo_date">' + credit_memo_date + '</td>'; inline_credit_memo_table_html += '<td headers="credit_memo_customer"><a href="' + credit_memo_customer_link + '">' + credit_memo_customer_name + '</td>'; inline_credit_memo_table_html += '<td headers="credit_memo_invoice_number"><a href="' + invoice_link + '">' + credit_memo_created_from + '</td>'; if (isTicketNotClosed(status_value)) { inline_credit_memo_table_html += '<td headers="credit_memo_action">' + credit_memo_action_button + '</td>'; } inline_credit_memo_table_html += '</tr>'; }); } else { $('.credit_memo').addClass('hide'); } $('#credit_memo tbody').html(inline_credit_memo_table_html); // Each time the table is redrawn, we trigger tooltip for the new cells. $('[data-toggle="tooltip"]').tooltip(); } /** * In the suitelet script, if the ticket record concerns an invoice, * the associated usage reports id are saved. * The files are loaded and their filenames and url are saved into the array of objects 'usage_report_array'. * This array is parsed and if the ids are not null, a row is added to the '#usage_report' table. * Otherwise, the section containing the table is hidden. * @param {Number} status_value */ function createUsageReportRows(status_value) { var inline_usage_report_table_html = ''; var usage_report_array = currRec.getValue({ fieldId: 'custpage_usage_report_array' }); usage_report_array = JSON.parse(usage_report_array); console.log('usage_report_array : ', usage_report_array); if (!isNullorEmpty(usage_report_array)) { usage_report_array.forEach(function(usage_report_obj) { var usage_report_id = usage_report_obj.id; if (!isNullorEmpty(usage_report_id)) { var usage_report_filename = usage_report_obj.name; var usage_report_link = usage_report_obj.url; var usage_report_action_button = '<button class="btn btn-success add_ur glyphicon glyphicon-plus" type="button" data-toggle="tooltip" data-placement="right" data-ur-id="' + usage_report_id + '" title="Attach to email"></button>'; inline_usage_report_table_html += '<tr class="text-center">'; inline_usage_report_table_html += '<td headers="usage_report_filename"><a href="' + usage_report_link + '">' + usage_report_filename + '</a></td>'; if (isTicketNotClosed(status_value)) { inline_usage_report_table_html += '<td headers="usage_report_action">' + usage_report_action_button + '</td>'; } inline_usage_report_table_html += '</tr>'; } }); } else { $('.usage_report').addClass('hide'); } $('#usage_report tbody').html(inline_usage_report_table_html); // Each time the table is redrawn, we trigger tooltip for the new cells. $('[data-toggle="tooltip"]').tooltip(); } /** * Depending on the number of buttons at the end of the page, their width and offset should change. * If there are 2 buttons, they have a width of 4 cols and an offset of 2 cols. * If there are 3 buttons, they have a width of 4 cols. * If there are 4 buttons, they have a width of 3 cols. */ function updateButtonsWidth() { var nb_buttons = $('.close_reopen_submit_ticket_section .row div:not(.hide)').length; $('.close_reopen_submit_ticket_section .row div').removeClass('col-xs-offset-2'); switch (nb_buttons) { case 2: $('.close_reopen_submit_ticket_section .row div').addClass('col-xs-4'); $('.close_reopen_submit_ticket_section .row div').removeClass('col-xs-3'); $('.close_reopen_submit_ticket_section .row div:not(.hide)').eq(0).addClass('col-xs-offset-2'); break; case 3: $('.close_reopen_submit_ticket_section .row div').addClass('col-xs-4'); $('.close_reopen_submit_ticket_section .row div').removeClass('col-xs-3'); break; case 4: $('.close_reopen_submit_ticket_section .row div').removeClass('col-xs-4'); $('.close_reopen_submit_ticket_section .row div').addClass('col-xs-3'); break; } } /** * Converts the selector field into either "Invoice number"/"Barcode number"/ "Customer App" * @param {String} selector_name */ function setupSelectorInput(selector_name) { $('#selector_text').text(selector_name); switch (selector_name) { case 'INVOICE NUMBER': $('#selector_value').attr('placeholder', 'INV123456'); $('#selector_value').removeAttr('value'); $('#selector_value').removeAttr('disabled'); break; case 'BARCODE NUMBER': $('#selector_value').attr('placeholder', 'MPEN123456'); $('#selector_value').removeAttr('value'); $('#selector_value').removeAttr('disabled'); break; case 'CUSTOMER APP': $('#selector_text').text("CUSTOMER ISSUE"); $('#selector_value').attr('value', 'Customer App'); $('#selector_value').attr('disabled', 'disabled'); break; case 'CUSTOMER PORTAL': $('#selector_text').text("CUSTOMER ISSUE"); $('#selector_value').attr('value', 'Customer Portal'); $('#selector_value').attr('disabled', 'disabled'); break; case 'UPDATE LABEL': $('#selector_text').text("CUSTOMER ISSUE"); $('#selector_value').attr('value', 'Update Label'); $('#selector_value').attr('disabled', 'disabled'); break; // case 'UPDATE CUSTOMER DETAILS': // $('#selector_text').text("CUSTOMER ISSUE"); // $('#selector_value').attr('value', 'Update Customer Details'); // $('#selector_value').attr('disabled', 'disabled'); // break; } } /** * Format a date object to the string 'dd/mm/yyyy hh:mm [am/pm]' * @param {Date} date * @returns {String} date_string */ function formatDate(testDate){ console.log('testDate: '+testDate); var responseDate=format.format({value:testDate,type:format.Type.DATE}); console.log('responseDate: '+responseDate); return responseDate; } /** * Converts the date string in the "invoice_date" table to the format of "date_selected". * @param {String} invoice_date ex: '4/6/2020' * @returns {String} date ex: '2020-06-04' */ function dateCreated2DateSelectedFormat(invoice_date) { // date_created = '4/6/2020' var date_array = invoice_date.split('/'); // date_array = ["4", "6", "2020"] var year = date_array[2]; var month = date_array[1]; if (month < 10) { month = '0' + month; } var day = date_array[0]; if (day < 10) { day = '0' + day; } return year + '-' + month + '-' + day; } /** * Calculates the reminder date based on the current date and the selector_type. */ function setReminderDate() { var ticket_id = currRec.getValue({ fieldId: 'custpage_ticket_id' }); var status_value = currRec.getValue({ fieldId: 'custpage_ticket_status_value' }); if (isNullorEmpty(ticket_id) || !isTicketNotClosed(status_value)) { var selector_type = currRec.getValue({ fieldId: 'custpage_selector_type' }); var today = new Date(); var today_day_in_month = today.getDate(); var today_day_in_week = today.getDay(); var today_month = today.getMonth(); var today_year = today.getFullYear(); switch (selector_type) { case 'barcode_number': var addNbDays = 1; if (today_day_in_week == 5) { addNbDays += 2; } break; case 'invoice_number': var addNbDays = 3; if (today_day_in_week == 3 || today_day_in_week == 4 || today_day_in_week == 5) { addNbDays += 2; } break; } var reminder_date = new Date(Date.UTC(today_year, today_month, today_day_in_month + addNbDays)); reminder_date = reminder_date.toISOString().split('T')[0]; } else { ticket_id = parseInt(ticket_id); var ticketRecord = record.load({ type: 'customrecord_mp_ticket', id: ticket_id }); var ticket_reminder_date = ticketRecord.getValue({ fieldId: 'custrecord_reminder' }); var reminder_date = ''; if (!isNullorEmpty(ticket_reminder_date)) { ticket_reminder_date = format.parse({ value: ticket_reminder_date, type: format.Type.DATE }); var reminder_date_day_in_month = ticket_reminder_date.getDate(); var reminder_date_month = ticket_reminder_date.getMonth(); var reminder_date_year = ticket_reminder_date.getFullYear(); reminder_date = new Date(Date.UTC(reminder_date_year, reminder_date_month, reminder_date_day_in_month)); reminder_date = reminder_date.toISOString().split('T')[0]; } } $('#reminder').val(reminder_date); } /** * Creates the inline HTML of the Credit Memo table, * with a button for the attachments if the ticket is not closed. * @param {Number} status_value * @returns {String} inline_html_credit_memo_table */ function htmlCreditMemoTable(status_value) { var inline_html_credit_memo_table = '<table cellpadding="15" id="credit_memo" class="table table-responsive table-striped contacts tablesorter" cellspacing="0" style="width: 100%;border: 0">'; inline_html_credit_memo_table += '<thead style="color: white;background-color: #379E8F;">'; inline_html_credit_memo_table += '<tr>'; inline_html_credit_memo_table += '<th style="vertical-align: middle;text-align: center;" id="credit_memo_number">'; inline_html_credit_memo_table += '<b>CREDIT #</b>'; inline_html_credit_memo_table += '</th>'; inline_html_credit_memo_table += '<th style="vertical-align: middle;text-align: center;" id="credit_memo_date">'; inline_html_credit_memo_table += '<b>DATE</b>'; inline_html_credit_memo_table += '</th>'; inline_html_credit_memo_table += '<th style="vertical-align: middle;text-align: center;" id="credit_memo_customer">'; inline_html_credit_memo_table += '<b>CUSTOMER</b>'; inline_html_credit_memo_table += '</th>'; inline_html_credit_memo_table += '<th style="vertical-align: middle;text-align: center;" id="credit_memo_invoice_number">'; inline_html_credit_memo_table += '<b>CREATED FROM</b>'; inline_html_credit_memo_table += '</th>'; if (isTicketNotClosed(status_value)) { inline_html_credit_memo_table += '<th style="vertical-align: middle;text-align: center;" id="credit_memo_action">'; inline_html_credit_memo_table += '<b>ATTACH TO EMAIL</b>'; inline_html_credit_memo_table += '</th>'; } inline_html_credit_memo_table += '</tr>'; inline_html_credit_memo_table += '</thead>'; inline_html_credit_memo_table += '<tbody></tbody>'; inline_html_credit_memo_table += '</table>'; return inline_html_credit_memo_table; } function htmlUsageReportTable(status_value) { var inline_html_usage_report_table = '<table cellpadding="15" id="usage_report" class="table table-responsive table-striped contacts tablesorter" cellspacing="0" style="width: 100%;border: 0"><thead style="color: white;background-color: #379E8F;">'; inline_html_usage_report_table += '<tr>'; inline_html_usage_report_table += '<th style="vertical-align: middle;text-align: center;" id="usage_report_filename">'; inline_html_usage_report_table += '<b>FILE NAME</b>'; inline_html_usage_report_table += '</th>'; if (isTicketNotClosed(status_value)) { inline_html_usage_report_table += '<th style="vertical-align: middle;text-align: center;" id="usage_report_action">'; inline_html_usage_report_table += '<b>ATTACH TO EMAIL</b>'; inline_html_usage_report_table += '</th>'; } inline_html_usage_report_table += '</tr>'; inline_html_usage_report_table += '</thead>'; inline_html_usage_report_table += '<tbody></tbody>'; inline_html_usage_report_table += '</table>'; return inline_html_usage_report_table; } /** * This function is triggered when a button is clicked to attach a file. * It stores the file id in the right array of the object 'params_email'. */ function attachFileButton() { $(this).toggleClass('btn-success'); $(this).toggleClass('btn-danger'); if ($(this).attr('id') == 'add_inv') { $(this).find('span.glyphicon').toggleClass('glyphicon-minus'); $(this).find('span.glyphicon').toggleClass('glyphicon-plus'); } else { $(this).toggleClass('glyphicon-minus'); $(this).toggleClass('glyphicon-plus'); } // Tooltip seems to set the 'title' attribute to 'data-original-title'. // The only way to have tooltip take into account the change of title is to modifiy the attribute 'data-original-title'. // Using the jQuery method 'data()' doesn't work. if ($(this).attr('data-original-title') == 'Attach to email') { $(this).attr('data-original-title', 'Remove from email'); } else { $(this).attr('data-original-title', 'Attach to email'); } $('[data-toggle="tooltip"]').tooltip(); var attachment_id = ''; var attachment_ids_array_name = ''; if ($(this).hasClass('add_ur')) { attachment_id = $(this).data('ur-id'); attachment_ids_array_name = 'attachments_usage_report_ids'; } else if ($(this).hasClass('add_cm')) { attachment_id = $(this).data('cm-id'); attachment_ids_array_name = 'attachments_credit_memo_ids'; } else if ($(this).hasClass('add_inv')) { attachment_id = $(this).data('inv-id'); attachment_ids_array_name = 'attachments_invoice_ids'; } addIdToAttachmentList(attachment_ids_array_name, attachment_id); } /** * Adds or remove the id of a record to be attached (or removed) to the email that will be sent in the function sendEmail(); * @param {String} attachment_ids_array_name * @param {Number} id */ function addIdToAttachmentList(attachment_ids_array_name, id) { var params_email = currRec.getValue({ fieldId: 'custpage_param_email' }); params_email = JSON.parse(params_email); var attachment_ids_array = params_email[attachment_ids_array_name]; var index_of_id_elem = attachment_ids_array.indexOf(id); if (index_of_id_elem == -1) { attachment_ids_array.push(id); } else { attachment_ids_array.splice(index_of_id_elem, 1); } params_email[attachment_ids_array_name] = attachment_ids_array; params_email = JSON.stringify(params_email); currRec.setValue({ fieldId: 'custpage_param_email', value: params_email }); } /** * @param {Number} x * @returns {String} The same number, formatted in Australian dollars. */ function financial(x) { if (typeof(x) === 'string') { x = parseFloat(x); } if (isNullorEmpty(x)) { return "$0.00"; } else { return x.toLocaleString('en-AU', { style: 'currency', currency: 'AUD' }); } } /** * Returns whether a ticket is closed or not based on its status value. * @param {Number} status_value * @returns {Boolean} is_ticket_closed */ function isTicketNotClosed(status_value) { var is_ticket_not_closed = ((status_value != 3) && (status_value != 8)) ? true : false; return is_ticket_not_closed; } /** * Whether the user is from the finance team, * or a Data Systems Co-ordinator, MailPlus Administration or Administrator user. * @param {Number} userRole * @returns {Boolean} */ function isFinanceRole(userRole) { // 1001, 1031 and 1023 are finance roles // 1032 is the Data Systems Co-ordinator role (to be deleted in prod) // 1006 is the Mail Plus Administration role. // 3 is the Administrator role. return ((userRole == 1001 || userRole == 1031 || userRole == 1023) || ((userRole == 1032) || (userRole == 1006) || (userRole == 3))); } /** * Whether the user is from the finance team. * @param {Number} userRole * @returns {Boolean} */ function isFinanceRoleOnly(userRole) { // 1001, 1031 and 1023 are finance roles return (userRole == 1001 || userRole == 1031 || userRole == 1023); } function validateEmail(email) { var re = /^(([^<>()[\]\\.,;:\s@"]+(\.[^<>()[\]\\.,;:\s@"]+)*)|(".+"))@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/; return re.test(String(email).toLowerCase()); } function getBase64(file) { return new Promise(function(resolve) { var reader = new FileReader(); reader.onloadend = function() { resolve(reader.result) } reader.readAsDataURL(file); }); } /** * Function to get the next email reminder time. * Adds +2 hours to the current date. */ function getNextReminderTime() { var today = new Date(); //Adding 19 hours to PST will give Australia/ Sydney timezone today.setHours(today.getHours() + 19); var currentHours = today.getHours(); log.debug({ title: 'currentHours + 2', details: currentHours + 2 }); if (currentHours + 2 > 16) { //Current hours + 2 hours is past 5. next reminder will be sent the next day at 9 am today.setDate(today.getDate() + 1); today.setHours(9); today.setMinutes(0); today.setSeconds(0); } else if (currentHours + 2 < 9) { //Current hours + 2 hours is before 9 am. Edge case but this is unlikely to happen since script does not run outside 9-5 today.setHours(9); today.setMinutes(0); today.setSeconds(0); } else { // Set next reminder time to today + 2 hours today.setHours(today.getHours() + 2); } return today; } function stringToDate(val) { return format.parse({value:val, type: format.Type.DATE}) } function isNullorEmpty(strVal) { return (strVal == null || strVal == '' || strVal == 'null' || strVal == undefined || strVal == 'undefined' || strVal == '- None -'); } return { pageInit: pageInit, saveRecord: saveRecord, closeTicket: closeTicket, closeTicketLost: closeTicketLost, closeUnallocatedTicket: closeUnallocatedTicket, onEscalate: onEscalate, onCancel: onCancel }; } );
/** *@NApiVersion 2.x *@NScriptType Suitelet *@Author Rafael Oliveira Santos */ define(['N/record', 'N/ui/serverWidget', 'N/search', 'N/url', 'N/runtime', 'N/error'], function(record, ui, search, url, runtime, error) { function onRequest(ctx) { var paramFunc = confereFuncionario() var paramForm = criaForm() preencheLista(paramFunc, paramForm.link, paramForm.sublist) function confereFuncionario() { var usuario = runtime.getCurrentUser(); var email = usuario.email var localidadeUser; log.debug('usuΓ‘rio', usuario) /** * trocar o mΓ©todo de validação para o ID do funcionΓ‘rio. */ if(email != 'celso.filho@kovi.com.br' && email != 'filipe.reis@kovi.com.br' && email != 'paulo.baptista@kovi.com.br' && email != 'rafael.santos@runsmart.cloud') { throw "VocΓͺ nΓ£o tem permissΓ£o para fazer isso." } switch (email) { case 'celso.filho@kovi.com.br': localidadeUser = 20 // miranda break; case 'filipe.reis@kovi.com.br': localidadeUser = 24 // naçáes break; case 'paulo.baptista@kovi.com.br': localidadeUser = 27 // campus break; case 'rafael.santos@runsmart.cloud': localidadeUser = 20 break; } log.debug('localidadeUser', localidadeUser) return localidadeUser } function criaForm() { const request = ctx.request; const method = request.method; const response = ctx.response; const parameters = request.parameters; var form = ui.createForm({ title: "Fluxo de planilha de estoque" }) var aprovadobutton = form.addButton({ id: 'custpage_aprovado', label: 'Aprovar', functionName: 'aprovado' }) var rejeitadobutton = form.addButton({ id: 'custpage_rejeitado', label: 'Rejeitar', functionName: 'rejeitado' }) var sublist = form.addSublist({ id: 'custpage_sublistplanilhas', label: 'Planilhas de estoque', type: ui.SublistType.LIST }); var marcaTudo = sublist.addButton({ id: 'custpage_marcaparcela', label: 'Marcar Tudo', functionName: 'selecionar' }) var desmarcaTudo = sublist.addButton({ id: 'custpage_desmarcaparcela', label: 'Desamarcar Tudo', functionName: 'desmarcar' }) var checkBox = sublist.addField({ id: 'custpage_marcarplanilha', type: ui.FieldType.CHECKBOX, label: 'Selecionar' }); var link = sublist.addField({ id: 'custpage_planilhalink', type: ui.FieldType.URL, label: 'Link' }) var sub = sublist.addField({ id: 'custpage_planilha', type: ui.FieldType.SELECT, source: 'inventoryworksheet', label: 'Planilha' }).updateDisplayType({displayType: ui.FieldDisplayType.INLINE}) var contaAjuste = sublist.addField({ id: 'custpage_contaajuste', type: ui.FieldType.SELECT, source: 'account', label: 'CONTA DE AJUSTE' }).updateDisplayType({displayType: ui.FieldDisplayType.INLINE}) var empresa = sublist.addField({ id: 'custpage_empresa', type: ui.FieldType.TEXT, label: 'Empresa' }).updateDisplayType({displayType: ui.FieldDisplayType.INLINE}) var localidade = sublist.addField({ id: 'custpage_localidade', type: ui.FieldType.TEXT, label: 'localidade' }).updateDisplayType({displayType: ui.FieldDisplayType.INLINE}) var status = sublist.addField({ id: 'custpage_status', type: ui.FieldType.TEXT, label: 'Status' }).updateDisplayType({displayType: ui.FieldDisplayType.INLINE}) ctx.response.writePage(form) form.clientScriptModulePath = './rsc_cs_fluxoAprovacao.js' return {link: link, sublist: sublist} } function preencheLista(localidadeUser, link, sublist){ var lista = [] var busca = search.create({ type: 'inventoryworksheet', filters: [ ["custbody_status_ae", "IS", 1], "AND", ["mainline","is","T"], "AND", ["location", "IS", localidadeUser] ], columns: [ "internalId", "tranid", "account", "subsidiary", "location", "custbody_status_ae" ] }).run().each(function(result){ lista.push({ id: result.getValue('internalId'), tranid: result.getValue('tranid'), account: result.getValue('account'), subsidiary: result.getText('subsidiary') , location: result.getText('location'), status: result.getText('custbody_status_ae') }) return true }) log.debug('lista', lista) for(var i = 0; i < lista.length; i++){ link.linkText = 'Planilha' var output = url.resolveRecord({ recordType: 'inventoryworksheet', recordId: lista[i].id, isEditMode: false }); sublist.setSublistValue({ id: "custpage_planilha", line: i, value: lista[i].id }) sublist.setSublistValue({ id: "custpage_planilhalink", line: i, value: output }) sublist.setSublistValue({ id: "custpage_contaajuste", line: i, value: lista[i].account }) sublist.setSublistValue({ id: "custpage_empresa", line: i, value: lista[i].subsidiary }) sublist.setSublistValue({ id: "custpage_localidade", line: i, value: lista[i].location }) sublist.setSublistValue({ id: "custpage_status", line: i, value: lista[i].status }) } } } return { onRequest: onRequest } });
5
[{"tag": "EMAIL", "value": "celso.filho@kovi.com.br", "start": 772, "end": 795}, {"tag": "EMAIL", "value": "filipe.reis@kovi.com.br", "start": 810, "end": 833}, {"tag": "EMAIL", "value": "paulo.baptista@kovi.com.br", "start": 848, "end": 874}, {"tag": "EMAIL", "value": "rafael.santos@runsmart.cloud", "start": 889, "end": 917}, {"tag": "EMAIL", "value": "celso.filho@kovi.com.br", "start": 1061, "end": 1084}, {"tag": "EMAIL", "value": "filipe.reis@kovi.com.br", "start": 1196, "end": 1219}, {"tag": "EMAIL", "value": "paulo.baptista@kovi.com.br", "start": 1330, "end": 1356}, {"tag": "EMAIL", "value": "rafael.santos@runsmart.cloud", "start": 1467, "end": 1495}]
true
8
/** *@NApiVersion 2.x *@NScriptType Suitelet *@Author Rafael Oliveira Santos */ define(['N/record', 'N/ui/serverWidget', 'N/search', 'N/url', 'N/runtime', 'N/error'], function(record, ui, search, url, runtime, error) { function onRequest(ctx) { var paramFunc = confereFuncionario() var paramForm = criaForm() preencheLista(paramFunc, paramForm.link, paramForm.sublist) function confereFuncionario() { var usuario = runtime.getCurrentUser(); var email = usuario.email var localidadeUser; log.debug('usuΓ‘rio', usuario) /** * trocar o mΓ©todo de validação para o ID do funcionΓ‘rio. */ if(email != 'nnheo@example.com' && email != 'hzdkv@example.com' && email != 'anpch@example.com' && email != 'nnheo@example.com') { throw "VocΓͺ nΓ£o tem permissΓ£o para fazer isso." } switch (email) { case 'nnheo@example.com': localidadeUser = 20 // miranda break; case 'hzdkv@example.com': localidadeUser = 24 // naçáes break; case 'anpch@example.com': localidadeUser = 27 // campus break; case 'nnheo@example.com': localidadeUser = 20 break; } log.debug('localidadeUser', localidadeUser) return localidadeUser } function criaForm() { const request = ctx.request; const method = request.method; const response = ctx.response; const parameters = request.parameters; var form = ui.createForm({ title: "Fluxo de planilha de estoque" }) var aprovadobutton = form.addButton({ id: 'custpage_aprovado', label: 'Aprovar', functionName: 'aprovado' }) var rejeitadobutton = form.addButton({ id: 'custpage_rejeitado', label: 'Rejeitar', functionName: 'rejeitado' }) var sublist = form.addSublist({ id: 'custpage_sublistplanilhas', label: 'Planilhas de estoque', type: ui.SublistType.LIST }); var marcaTudo = sublist.addButton({ id: 'custpage_marcaparcela', label: 'Marcar Tudo', functionName: 'selecionar' }) var desmarcaTudo = sublist.addButton({ id: 'custpage_desmarcaparcela', label: 'Desamarcar Tudo', functionName: 'desmarcar' }) var checkBox = sublist.addField({ id: 'custpage_marcarplanilha', type: ui.FieldType.CHECKBOX, label: 'Selecionar' }); var link = sublist.addField({ id: 'custpage_planilhalink', type: ui.FieldType.URL, label: 'Link' }) var sub = sublist.addField({ id: 'custpage_planilha', type: ui.FieldType.SELECT, source: 'inventoryworksheet', label: 'Planilha' }).updateDisplayType({displayType: ui.FieldDisplayType.INLINE}) var contaAjuste = sublist.addField({ id: 'custpage_contaajuste', type: ui.FieldType.SELECT, source: 'account', label: 'CONTA DE AJUSTE' }).updateDisplayType({displayType: ui.FieldDisplayType.INLINE}) var empresa = sublist.addField({ id: 'custpage_empresa', type: ui.FieldType.TEXT, label: 'Empresa' }).updateDisplayType({displayType: ui.FieldDisplayType.INLINE}) var localidade = sublist.addField({ id: 'custpage_localidade', type: ui.FieldType.TEXT, label: 'localidade' }).updateDisplayType({displayType: ui.FieldDisplayType.INLINE}) var status = sublist.addField({ id: 'custpage_status', type: ui.FieldType.TEXT, label: 'Status' }).updateDisplayType({displayType: ui.FieldDisplayType.INLINE}) ctx.response.writePage(form) form.clientScriptModulePath = './rsc_cs_fluxoAprovacao.js' return {link: link, sublist: sublist} } function preencheLista(localidadeUser, link, sublist){ var lista = [] var busca = search.create({ type: 'inventoryworksheet', filters: [ ["custbody_status_ae", "IS", 1], "AND", ["mainline","is","T"], "AND", ["location", "IS", localidadeUser] ], columns: [ "internalId", "tranid", "account", "subsidiary", "location", "custbody_status_ae" ] }).run().each(function(result){ lista.push({ id: result.getValue('internalId'), tranid: result.getValue('tranid'), account: result.getValue('account'), subsidiary: result.getText('subsidiary') , location: result.getText('location'), status: result.getText('custbody_status_ae') }) return true }) log.debug('lista', lista) for(var i = 0; i < lista.length; i++){ link.linkText = 'Planilha' var output = url.resolveRecord({ recordType: 'inventoryworksheet', recordId: lista[i].id, isEditMode: false }); sublist.setSublistValue({ id: "custpage_planilha", line: i, value: lista[i].id }) sublist.setSublistValue({ id: "custpage_planilhalink", line: i, value: output }) sublist.setSublistValue({ id: "custpage_contaajuste", line: i, value: lista[i].account }) sublist.setSublistValue({ id: "custpage_empresa", line: i, value: lista[i].subsidiary }) sublist.setSublistValue({ id: "custpage_localidade", line: i, value: lista[i].location }) sublist.setSublistValue({ id: "custpage_status", line: i, value: lista[i].status }) } } } return { onRequest: onRequest } });
true
/** *@NApiVersion 2.x *@NScriptType Suitelet *@Author Rafael Oliveira Santos */ define(['N/record', 'N/ui/serverWidget', 'N/search', 'N/url', 'N/runtime', 'N/error'], function(record, ui, search, url, runtime, error) { function onRequest(ctx) { var paramFunc = confereFuncionario() var paramForm = criaForm() preencheLista(paramFunc, paramForm.link, paramForm.sublist) function confereFuncionario() { var usuario = runtime.getCurrentUser(); var email = usuario.email var localidadeUser; log.debug('usuΓ‘rio', usuario) /** * trocar o mΓ©todo de validação para o ID do funcionΓ‘rio. */ if(email != 'PI:EMAIL:nnheo@example.comEND_PI' && email != 'PI:EMAIL:hzdkv@example.comEND_PI' && email != 'PI:EMAIL:anpch@example.comEND_PI' && email != 'PI:EMAIL:nnheo@example.comEND_PI') { throw "VocΓͺ nΓ£o tem permissΓ£o para fazer isso." } switch (email) { case 'PI:EMAIL:nnheo@example.comEND_PI': localidadeUser = 20 // miranda break; case 'PI:EMAIL:hzdkv@example.comEND_PI': localidadeUser = 24 // naçáes break; case 'PI:EMAIL:anpch@example.comEND_PI': localidadeUser = 27 // campus break; case 'PI:EMAIL:nnheo@example.comEND_PI': localidadeUser = 20 break; } log.debug('localidadeUser', localidadeUser) return localidadeUser } function criaForm() { const request = ctx.request; const method = request.method; const response = ctx.response; const parameters = request.parameters; var form = ui.createForm({ title: "Fluxo de planilha de estoque" }) var aprovadobutton = form.addButton({ id: 'custpage_aprovado', label: 'Aprovar', functionName: 'aprovado' }) var rejeitadobutton = form.addButton({ id: 'custpage_rejeitado', label: 'Rejeitar', functionName: 'rejeitado' }) var sublist = form.addSublist({ id: 'custpage_sublistplanilhas', label: 'Planilhas de estoque', type: ui.SublistType.LIST }); var marcaTudo = sublist.addButton({ id: 'custpage_marcaparcela', label: 'Marcar Tudo', functionName: 'selecionar' }) var desmarcaTudo = sublist.addButton({ id: 'custpage_desmarcaparcela', label: 'Desamarcar Tudo', functionName: 'desmarcar' }) var checkBox = sublist.addField({ id: 'custpage_marcarplanilha', type: ui.FieldType.CHECKBOX, label: 'Selecionar' }); var link = sublist.addField({ id: 'custpage_planilhalink', type: ui.FieldType.URL, label: 'Link' }) var sub = sublist.addField({ id: 'custpage_planilha', type: ui.FieldType.SELECT, source: 'inventoryworksheet', label: 'Planilha' }).updateDisplayType({displayType: ui.FieldDisplayType.INLINE}) var contaAjuste = sublist.addField({ id: 'custpage_contaajuste', type: ui.FieldType.SELECT, source: 'account', label: 'CONTA DE AJUSTE' }).updateDisplayType({displayType: ui.FieldDisplayType.INLINE}) var empresa = sublist.addField({ id: 'custpage_empresa', type: ui.FieldType.TEXT, label: 'Empresa' }).updateDisplayType({displayType: ui.FieldDisplayType.INLINE}) var localidade = sublist.addField({ id: 'custpage_localidade', type: ui.FieldType.TEXT, label: 'localidade' }).updateDisplayType({displayType: ui.FieldDisplayType.INLINE}) var status = sublist.addField({ id: 'custpage_status', type: ui.FieldType.TEXT, label: 'Status' }).updateDisplayType({displayType: ui.FieldDisplayType.INLINE}) ctx.response.writePage(form) form.clientScriptModulePath = './rsc_cs_fluxoAprovacao.js' return {link: link, sublist: sublist} } function preencheLista(localidadeUser, link, sublist){ var lista = [] var busca = search.create({ type: 'inventoryworksheet', filters: [ ["custbody_status_ae", "IS", 1], "AND", ["mainline","is","T"], "AND", ["location", "IS", localidadeUser] ], columns: [ "internalId", "tranid", "account", "subsidiary", "location", "custbody_status_ae" ] }).run().each(function(result){ lista.push({ id: result.getValue('internalId'), tranid: result.getValue('tranid'), account: result.getValue('account'), subsidiary: result.getText('subsidiary') , location: result.getText('location'), status: result.getText('custbody_status_ae') }) return true }) log.debug('lista', lista) for(var i = 0; i < lista.length; i++){ link.linkText = 'Planilha' var output = url.resolveRecord({ recordType: 'inventoryworksheet', recordId: lista[i].id, isEditMode: false }); sublist.setSublistValue({ id: "custpage_planilha", line: i, value: lista[i].id }) sublist.setSublistValue({ id: "custpage_planilhalink", line: i, value: output }) sublist.setSublistValue({ id: "custpage_contaajuste", line: i, value: lista[i].account }) sublist.setSublistValue({ id: "custpage_empresa", line: i, value: lista[i].subsidiary }) sublist.setSublistValue({ id: "custpage_localidade", line: i, value: lista[i].location }) sublist.setSublistValue({ id: "custpage_status", line: i, value: lista[i].status }) } } } return { onRequest: onRequest } });
/** * hitc_mass_emailer_client.ts * by Head in the Cloud Development, Inc. * gurus@headintheclouddev.com * * @NScriptType ClientScript * @NApiVersion 2.1 */ define(["require", "exports", "N/ui/dialog", "N/ui/message", "N/record", "N/search"], function (require, exports, dialog, message, record, search) { "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.saveRecord = exports.fieldChanged = exports.pageInit = void 0; function pageInit(context) { const transactionParameter = getParameter('transaction'); // This isn't currently in use. Can be hooked up to a button on transactions. if (transactionParameter) context.currentRecord.setValue('custpage_transaction', transactionParameter); } exports.pageInit = pageInit; function fieldChanged(context) { console.log('Field Changed', context.sublistId, context.fieldId); const subject = context.currentRecord.getValue('custpage_subject'); const template = context.currentRecord.getValue('custpage_template'); const transaction = context.currentRecord.getValue('custpage_transaction'); const transText = context.currentRecord.getText('custpage_transaction'); if (context.fieldId == 'custpage_contact_contact') { // Source in company name & email const contact = context.currentRecord.getCurrentSublistValue({ sublistId: 'custpage_contacts', fieldId: 'custpage_contact_contact' }); if (contact) search.lookupFields.promise({ type: 'contact', id: contact, columns: ['company', 'email'] }).then((contactValues) => { console.log('Contact values', contactValues); const companies = contactValues['company']; const companyName = (companies && companies.length > 0) ? companies[0].text : ''; const emailAddress = contactValues.email; context.currentRecord.setCurrentSublistValue({ sublistId: 'custpage_contacts', fieldId: 'custpage_contact_company', value: companyName }); context.currentRecord.setCurrentSublistValue({ sublistId: 'custpage_contacts', fieldId: 'custpage_contact_email', value: emailAddress }); }); } else if (~['custpage_employee_employee', 'custpage_partner_partner', 'custpage_customer_customer'].indexOf(context.fieldId)) { // Source in email const entityId = context.currentRecord.getCurrentSublistValue({ sublistId: context.sublistId, fieldId: context.fieldId }); if (entityId) search.lookupFields.promise({ type: 'entity', id: entityId, columns: ['email', 'type'] }).then((entityValues) => { console.log('Entity values', entityValues); const entityTypes = entityValues['type']; // May be like: [{ value: 'CustJob', text: 'Customer' }] const fieldId = `custpage_${entityTypes[0].text.toLowerCase()}_email`; context.currentRecord.setCurrentSublistValue({ sublistId: context.sublistId, fieldId, value: entityValues.email }); }); } else if (context.fieldId == 'custpage_transaction' && !subject && transaction && !template) { context.currentRecord.setValue('custpage_subject', transText); } else if (context.fieldId == 'custpage_template') { setTemplatePreviewContent(context.currentRecord, template); } else if (['custpage_search_type', 'custpage_populate_list'].includes(context.fieldId)) { const searchId = context.currentRecord.getValue('custpage_saved_search'); const populateList = context.currentRecord.getValue('custpage_populate_list'); const searchType = context.currentRecord.getValue('custpage_search_type'); if (searchId && searchType && populateList) fillListFromSearch(searchType, searchId, context.currentRecord); } else if (context.fieldId == 'custpage_saved_search') { const searchId = context.currentRecord.getValue('custpage_saved_search'); if (searchId) { search.load.promise({ id: searchId }).then((savedSearch) => { context.currentRecord.setValue({ fieldId: 'custpage_search_type', value: savedSearch.searchType }); }); } } } exports.fieldChanged = fieldChanged; function saveRecord(context) { // Require template OR subject and body const template = context.currentRecord.getValue('custpage_template'); const subject = context.currentRecord.getValue('custpage_subject'); const body = context.currentRecord.getValue('custpage_body'); if (!template && (!subject && body)) { alert('You must either select a Template or enter an email subject and body'); return false; } // Require at least one recipient const contactCount = context.currentRecord.getLineCount({ sublistId: 'custpage_contacts' }); const employeeCount = context.currentRecord.getLineCount({ sublistId: 'custpage_employees' }); const customerCount = context.currentRecord.getLineCount({ sublistId: 'custpage_customers' }); const partnerCount = context.currentRecord.getLineCount({ sublistId: 'custpage_partners' }); const populateList = context.currentRecord.getValue('custpage_populate_list'); const savedSearch = context.currentRecord.getValue('custpage_saved_search'); if (!contactCount && !employeeCount && !partnerCount && !customerCount && (!savedSearch || populateList)) { alert('You must select at least one recipient in the tabs below!'); return false; } return true; } exports.saveRecord = saveRecord; function fillListFromSearch(searchType, searchId, rec) { // const columns = ['email', 'isinactive']; // if (searchType == 'contact') columns.push('company'); // TODO: Do we need this? search.load.promise({ id: searchId }).then((entitySearch) => { entitySearch.run().getRange.promise({ start: 0, end: 1000 }).then(async (results) => { console.log('Search', searchId, 'results', results.length); if (results.length == 1000) { // Warn them that they're not getting all the results const decision = await dialog.confirm({ title: 'Very Large Search Result Set', message: 'With the populate sublist checkbox enabled, only the first 1000 search results will be processed. Loading 1000 sublist lines may take several minutes and cause your browser to become unresponsive. Are you sure you want to populate the results in the sublist? If you click cancel then all results will be processed server-side when you click the Send button.' }); if (!decision) return rec.setValue('custpage_populate_list', false); } else if (results.length > 100) { // Warn them that this will take a minute dialog.alert({ title: 'Large Search Result Set', message: `Your search returned ${results.length} results - this may take a few minutes to populate in the sublist.` }); } const sublistId = `custpage_${searchType}s`; for (const result of results) { const emailAddress = result.getValue('email'); const inactive = result.getValue('isinactive'); if (!emailAddress || inactive) continue; rec.selectNewLine({ sublistId }); rec.setCurrentSublistValue({ sublistId, fieldId: `custpage_${searchType}_${searchType}`, value: result.id, ignoreFieldChange: true }); rec.setCurrentSublistValue({ sublistId, fieldId: `custpage_${searchType}_email`, value: emailAddress, ignoreFieldChange: true }); if (searchType == 'contact') { const companyName = result.getText('company'); rec.setCurrentSublistValue({ sublistId, fieldId: `custpage_contact_company`, value: companyName, ignoreFieldChange: true }); } rec.commitLine({ sublistId }); } }).catch((reason) => { alert(`Failed to run saved search: ${reason}`); }); }).catch((reason) => { alert(`Failed to load saved search: ${reason}`); }); } function setTemplatePreviewContent(rec, templateId) { if (templateId) { // Load the template and set the subject and body fields from the content (not a merge, just the preview) const banner = message.create({ type: message.Type.INFORMATION, title: 'Loading...', message: `Loading template preview...` }); record.load.promise({ type: 'emailtemplate', id: templateId }).then((templateRec) => { rec.setValue('custpage_subject', templateRec.getValue('subject')); rec.setValue('custpage_body', templateRec.getValue('content') || 'Email template file will be used.'); rec.getField({ fieldId: 'custpage_subject' }).isDisabled = true; rec.getField({ fieldId: 'custpage_body' }).isDisabled = true; banner.hide(); }).catch((reason) => { console.log('Failed to load email template', templateId, 're-trying as campaign template.', reason.message); alert('Failed to load the template you selected, please ensure you select an Email Template and not a Campaign Template'); rec.setValue('custpage_template', ''); }); banner.show(); } else { rec.getField({ fieldId: 'custpage_subject' }).isDisabled = false; rec.getField({ fieldId: 'custpage_body' }).isDisabled = false; rec.setValue('custpage_subject', ''); rec.setValue('custpage_body', ''); } } });
172
[{"tag": "EMAIL", "value": "gurus@headintheclouddev.com", "start": 80, "end": 107}]
true
1
/** * hitc_mass_emailer_client.ts * by Head in the Cloud Development, Inc. * ychag@example.com * * @NScriptType ClientScript * @NApiVersion 2.1 */ define(["require", "exports", "N/ui/dialog", "N/ui/message", "N/record", "N/search"], function (require, exports, dialog, message, record, search) { "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.saveRecord = exports.fieldChanged = exports.pageInit = void 0; function pageInit(context) { const transactionParameter = getParameter('transaction'); // This isn't currently in use. Can be hooked up to a button on transactions. if (transactionParameter) context.currentRecord.setValue('custpage_transaction', transactionParameter); } exports.pageInit = pageInit; function fieldChanged(context) { console.log('Field Changed', context.sublistId, context.fieldId); const subject = context.currentRecord.getValue('custpage_subject'); const template = context.currentRecord.getValue('custpage_template'); const transaction = context.currentRecord.getValue('custpage_transaction'); const transText = context.currentRecord.getText('custpage_transaction'); if (context.fieldId == 'custpage_contact_contact') { // Source in company name & email const contact = context.currentRecord.getCurrentSublistValue({ sublistId: 'custpage_contacts', fieldId: 'custpage_contact_contact' }); if (contact) search.lookupFields.promise({ type: 'contact', id: contact, columns: ['company', 'email'] }).then((contactValues) => { console.log('Contact values', contactValues); const companies = contactValues['company']; const companyName = (companies && companies.length > 0) ? companies[0].text : ''; const emailAddress = contactValues.email; context.currentRecord.setCurrentSublistValue({ sublistId: 'custpage_contacts', fieldId: 'custpage_contact_company', value: companyName }); context.currentRecord.setCurrentSublistValue({ sublistId: 'custpage_contacts', fieldId: 'custpage_contact_email', value: emailAddress }); }); } else if (~['custpage_employee_employee', 'custpage_partner_partner', 'custpage_customer_customer'].indexOf(context.fieldId)) { // Source in email const entityId = context.currentRecord.getCurrentSublistValue({ sublistId: context.sublistId, fieldId: context.fieldId }); if (entityId) search.lookupFields.promise({ type: 'entity', id: entityId, columns: ['email', 'type'] }).then((entityValues) => { console.log('Entity values', entityValues); const entityTypes = entityValues['type']; // May be like: [{ value: 'CustJob', text: 'Customer' }] const fieldId = `custpage_${entityTypes[0].text.toLowerCase()}_email`; context.currentRecord.setCurrentSublistValue({ sublistId: context.sublistId, fieldId, value: entityValues.email }); }); } else if (context.fieldId == 'custpage_transaction' && !subject && transaction && !template) { context.currentRecord.setValue('custpage_subject', transText); } else if (context.fieldId == 'custpage_template') { setTemplatePreviewContent(context.currentRecord, template); } else if (['custpage_search_type', 'custpage_populate_list'].includes(context.fieldId)) { const searchId = context.currentRecord.getValue('custpage_saved_search'); const populateList = context.currentRecord.getValue('custpage_populate_list'); const searchType = context.currentRecord.getValue('custpage_search_type'); if (searchId && searchType && populateList) fillListFromSearch(searchType, searchId, context.currentRecord); } else if (context.fieldId == 'custpage_saved_search') { const searchId = context.currentRecord.getValue('custpage_saved_search'); if (searchId) { search.load.promise({ id: searchId }).then((savedSearch) => { context.currentRecord.setValue({ fieldId: 'custpage_search_type', value: savedSearch.searchType }); }); } } } exports.fieldChanged = fieldChanged; function saveRecord(context) { // Require template OR subject and body const template = context.currentRecord.getValue('custpage_template'); const subject = context.currentRecord.getValue('custpage_subject'); const body = context.currentRecord.getValue('custpage_body'); if (!template && (!subject && body)) { alert('You must either select a Template or enter an email subject and body'); return false; } // Require at least one recipient const contactCount = context.currentRecord.getLineCount({ sublistId: 'custpage_contacts' }); const employeeCount = context.currentRecord.getLineCount({ sublistId: 'custpage_employees' }); const customerCount = context.currentRecord.getLineCount({ sublistId: 'custpage_customers' }); const partnerCount = context.currentRecord.getLineCount({ sublistId: 'custpage_partners' }); const populateList = context.currentRecord.getValue('custpage_populate_list'); const savedSearch = context.currentRecord.getValue('custpage_saved_search'); if (!contactCount && !employeeCount && !partnerCount && !customerCount && (!savedSearch || populateList)) { alert('You must select at least one recipient in the tabs below!'); return false; } return true; } exports.saveRecord = saveRecord; function fillListFromSearch(searchType, searchId, rec) { // const columns = ['email', 'isinactive']; // if (searchType == 'contact') columns.push('company'); // TODO: Do we need this? search.load.promise({ id: searchId }).then((entitySearch) => { entitySearch.run().getRange.promise({ start: 0, end: 1000 }).then(async (results) => { console.log('Search', searchId, 'results', results.length); if (results.length == 1000) { // Warn them that they're not getting all the results const decision = await dialog.confirm({ title: 'Very Large Search Result Set', message: 'With the populate sublist checkbox enabled, only the first 1000 search results will be processed. Loading 1000 sublist lines may take several minutes and cause your browser to become unresponsive. Are you sure you want to populate the results in the sublist? If you click cancel then all results will be processed server-side when you click the Send button.' }); if (!decision) return rec.setValue('custpage_populate_list', false); } else if (results.length > 100) { // Warn them that this will take a minute dialog.alert({ title: 'Large Search Result Set', message: `Your search returned ${results.length} results - this may take a few minutes to populate in the sublist.` }); } const sublistId = `custpage_${searchType}s`; for (const result of results) { const emailAddress = result.getValue('email'); const inactive = result.getValue('isinactive'); if (!emailAddress || inactive) continue; rec.selectNewLine({ sublistId }); rec.setCurrentSublistValue({ sublistId, fieldId: `custpage_${searchType}_${searchType}`, value: result.id, ignoreFieldChange: true }); rec.setCurrentSublistValue({ sublistId, fieldId: `custpage_${searchType}_email`, value: emailAddress, ignoreFieldChange: true }); if (searchType == 'contact') { const companyName = result.getText('company'); rec.setCurrentSublistValue({ sublistId, fieldId: `custpage_contact_company`, value: companyName, ignoreFieldChange: true }); } rec.commitLine({ sublistId }); } }).catch((reason) => { alert(`Failed to run saved search: ${reason}`); }); }).catch((reason) => { alert(`Failed to load saved search: ${reason}`); }); } function setTemplatePreviewContent(rec, templateId) { if (templateId) { // Load the template and set the subject and body fields from the content (not a merge, just the preview) const banner = message.create({ type: message.Type.INFORMATION, title: 'Loading...', message: `Loading template preview...` }); record.load.promise({ type: 'emailtemplate', id: templateId }).then((templateRec) => { rec.setValue('custpage_subject', templateRec.getValue('subject')); rec.setValue('custpage_body', templateRec.getValue('content') || 'Email template file will be used.'); rec.getField({ fieldId: 'custpage_subject' }).isDisabled = true; rec.getField({ fieldId: 'custpage_body' }).isDisabled = true; banner.hide(); }).catch((reason) => { console.log('Failed to load email template', templateId, 're-trying as campaign template.', reason.message); alert('Failed to load the template you selected, please ensure you select an Email Template and not a Campaign Template'); rec.setValue('custpage_template', ''); }); banner.show(); } else { rec.getField({ fieldId: 'custpage_subject' }).isDisabled = false; rec.getField({ fieldId: 'custpage_body' }).isDisabled = false; rec.setValue('custpage_subject', ''); rec.setValue('custpage_body', ''); } } });
true
/** * hitc_mass_emailer_client.ts * by Head in the Cloud Development, Inc. * PI:EMAIL:ychag@example.comEND_PI * * @NScriptType ClientScript * @NApiVersion 2.1 */ define(["require", "exports", "N/ui/dialog", "N/ui/message", "N/record", "N/search"], function (require, exports, dialog, message, record, search) { "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.saveRecord = exports.fieldChanged = exports.pageInit = void 0; function pageInit(context) { const transactionParameter = getParameter('transaction'); // This isn't currently in use. Can be hooked up to a button on transactions. if (transactionParameter) context.currentRecord.setValue('custpage_transaction', transactionParameter); } exports.pageInit = pageInit; function fieldChanged(context) { console.log('Field Changed', context.sublistId, context.fieldId); const subject = context.currentRecord.getValue('custpage_subject'); const template = context.currentRecord.getValue('custpage_template'); const transaction = context.currentRecord.getValue('custpage_transaction'); const transText = context.currentRecord.getText('custpage_transaction'); if (context.fieldId == 'custpage_contact_contact') { // Source in company name & email const contact = context.currentRecord.getCurrentSublistValue({ sublistId: 'custpage_contacts', fieldId: 'custpage_contact_contact' }); if (contact) search.lookupFields.promise({ type: 'contact', id: contact, columns: ['company', 'email'] }).then((contactValues) => { console.log('Contact values', contactValues); const companies = contactValues['company']; const companyName = (companies && companies.length > 0) ? companies[0].text : ''; const emailAddress = contactValues.email; context.currentRecord.setCurrentSublistValue({ sublistId: 'custpage_contacts', fieldId: 'custpage_contact_company', value: companyName }); context.currentRecord.setCurrentSublistValue({ sublistId: 'custpage_contacts', fieldId: 'custpage_contact_email', value: emailAddress }); }); } else if (~['custpage_employee_employee', 'custpage_partner_partner', 'custpage_customer_customer'].indexOf(context.fieldId)) { // Source in email const entityId = context.currentRecord.getCurrentSublistValue({ sublistId: context.sublistId, fieldId: context.fieldId }); if (entityId) search.lookupFields.promise({ type: 'entity', id: entityId, columns: ['email', 'type'] }).then((entityValues) => { console.log('Entity values', entityValues); const entityTypes = entityValues['type']; // May be like: [{ value: 'CustJob', text: 'Customer' }] const fieldId = `custpage_${entityTypes[0].text.toLowerCase()}_email`; context.currentRecord.setCurrentSublistValue({ sublistId: context.sublistId, fieldId, value: entityValues.email }); }); } else if (context.fieldId == 'custpage_transaction' && !subject && transaction && !template) { context.currentRecord.setValue('custpage_subject', transText); } else if (context.fieldId == 'custpage_template') { setTemplatePreviewContent(context.currentRecord, template); } else if (['custpage_search_type', 'custpage_populate_list'].includes(context.fieldId)) { const searchId = context.currentRecord.getValue('custpage_saved_search'); const populateList = context.currentRecord.getValue('custpage_populate_list'); const searchType = context.currentRecord.getValue('custpage_search_type'); if (searchId && searchType && populateList) fillListFromSearch(searchType, searchId, context.currentRecord); } else if (context.fieldId == 'custpage_saved_search') { const searchId = context.currentRecord.getValue('custpage_saved_search'); if (searchId) { search.load.promise({ id: searchId }).then((savedSearch) => { context.currentRecord.setValue({ fieldId: 'custpage_search_type', value: savedSearch.searchType }); }); } } } exports.fieldChanged = fieldChanged; function saveRecord(context) { // Require template OR subject and body const template = context.currentRecord.getValue('custpage_template'); const subject = context.currentRecord.getValue('custpage_subject'); const body = context.currentRecord.getValue('custpage_body'); if (!template && (!subject && body)) { alert('You must either select a Template or enter an email subject and body'); return false; } // Require at least one recipient const contactCount = context.currentRecord.getLineCount({ sublistId: 'custpage_contacts' }); const employeeCount = context.currentRecord.getLineCount({ sublistId: 'custpage_employees' }); const customerCount = context.currentRecord.getLineCount({ sublistId: 'custpage_customers' }); const partnerCount = context.currentRecord.getLineCount({ sublistId: 'custpage_partners' }); const populateList = context.currentRecord.getValue('custpage_populate_list'); const savedSearch = context.currentRecord.getValue('custpage_saved_search'); if (!contactCount && !employeeCount && !partnerCount && !customerCount && (!savedSearch || populateList)) { alert('You must select at least one recipient in the tabs below!'); return false; } return true; } exports.saveRecord = saveRecord; function fillListFromSearch(searchType, searchId, rec) { // const columns = ['email', 'isinactive']; // if (searchType == 'contact') columns.push('company'); // TODO: Do we need this? search.load.promise({ id: searchId }).then((entitySearch) => { entitySearch.run().getRange.promise({ start: 0, end: 1000 }).then(async (results) => { console.log('Search', searchId, 'results', results.length); if (results.length == 1000) { // Warn them that they're not getting all the results const decision = await dialog.confirm({ title: 'Very Large Search Result Set', message: 'With the populate sublist checkbox enabled, only the first 1000 search results will be processed. Loading 1000 sublist lines may take several minutes and cause your browser to become unresponsive. Are you sure you want to populate the results in the sublist? If you click cancel then all results will be processed server-side when you click the Send button.' }); if (!decision) return rec.setValue('custpage_populate_list', false); } else if (results.length > 100) { // Warn them that this will take a minute dialog.alert({ title: 'Large Search Result Set', message: `Your search returned ${results.length} results - this may take a few minutes to populate in the sublist.` }); } const sublistId = `custpage_${searchType}s`; for (const result of results) { const emailAddress = result.getValue('email'); const inactive = result.getValue('isinactive'); if (!emailAddress || inactive) continue; rec.selectNewLine({ sublistId }); rec.setCurrentSublistValue({ sublistId, fieldId: `custpage_${searchType}_${searchType}`, value: result.id, ignoreFieldChange: true }); rec.setCurrentSublistValue({ sublistId, fieldId: `custpage_${searchType}_email`, value: emailAddress, ignoreFieldChange: true }); if (searchType == 'contact') { const companyName = result.getText('company'); rec.setCurrentSublistValue({ sublistId, fieldId: `custpage_contact_company`, value: companyName, ignoreFieldChange: true }); } rec.commitLine({ sublistId }); } }).catch((reason) => { alert(`Failed to run saved search: ${reason}`); }); }).catch((reason) => { alert(`Failed to load saved search: ${reason}`); }); } function setTemplatePreviewContent(rec, templateId) { if (templateId) { // Load the template and set the subject and body fields from the content (not a merge, just the preview) const banner = message.create({ type: message.Type.INFORMATION, title: 'Loading...', message: `Loading template preview...` }); record.load.promise({ type: 'emailtemplate', id: templateId }).then((templateRec) => { rec.setValue('custpage_subject', templateRec.getValue('subject')); rec.setValue('custpage_body', templateRec.getValue('content') || 'Email template file will be used.'); rec.getField({ fieldId: 'custpage_subject' }).isDisabled = true; rec.getField({ fieldId: 'custpage_body' }).isDisabled = true; banner.hide(); }).catch((reason) => { console.log('Failed to load email template', templateId, 're-trying as campaign template.', reason.message); alert('Failed to load the template you selected, please ensure you select an Email Template and not a Campaign Template'); rec.setValue('custpage_template', ''); }); banner.show(); } else { rec.getField({ fieldId: 'custpage_subject' }).isDisabled = false; rec.getField({ fieldId: 'custpage_body' }).isDisabled = false; rec.setValue('custpage_subject', ''); rec.setValue('custpage_body', ''); } } });
/** * @NApiVersion 2.x * @NScriptType MapReduceScript * @NModuleScope SameAccount */ define(['N/https', 'N/encode', 'N/record', 'N/format', 'N/search', 'N/runtime', 'N/error', 'N/task'], /** * @param {https} https * @param {encode} encode * @param {record} record */ function(https, encode, record, format, search, runtime, error, task) { /** * Marks the beginning of the Map/Reduce process and generates input data. * * @typedef {Object} ObjectRef * @property {number} id - Internal ID of the record instance * @property {string} type - Record type id * * @return {Array|Object|Search|RecordRef} inputSummary * @since 2015.1 */ var sNextLink = ''; var sLastLink = ''; var ATLASSIANTYPE = 1; var fldValues = [ 'externalid', 'name', 'custrecord_lic_addon_key', 'custrecord_lic_addon_license_id', 'custrecord_lic_host_license_id', 'custrecord_lic_transaction_id', 'custrecord_lic_addon_name', 'custrecord_lic_company_name', 'custrecord_lic_license_id', 'custrecord_lic_country', 'custrecord_lic_region', 'custrecord_lic_hosting', 'custrecord_lic_license_type', 'custrecord_lic_status', 'custrecord_lic_tier', 'custrecord_lic_tech_contact_name', 'custrecord_lic_tech_contact_email', 'custrecord_lic_tech_contact_address1', 'custrecord_lic_tech_contact_address2', 'custrecord_lic_tech_contact_city', 'custrecord_lic_tech_contact_postcode', 'custrecord_lic_billing_contact_email', 'custrecord_lic_billing_contact_name', 'custrecord_lic_billing_contact_address1', 'custrecord_lic_billing_contact_address2', 'custrecord_lic_billing_contact_city', 'custrecord_lic_billing_contact_postcode', 'custrecord_lic_pnr_billing_contact_name', 'custrecord_lic_pnr_billing_contact_email', 'custrecord_lic_partner_name', 'custrecord_lic_partner_type', 'custrecord_lic_customer_domain', 'custrecord_lic_raw_json', 'custrecord_lic_region', 'custrecord_lic_vendor_id']; var fldDate = ['custrecord_lic_last_updated', 'custrecord_lic_maintenance_start_date', 'custrecord_lic_maintenance_end_date']; var fldTxt = []; function getInputData() { var dLastUpdate = runtime.getCurrentScript().getParameter({name: 'custscript_lichist_lastupdate'}); var objInputs = []; var sLastUpdate = dLastUpdate.getFullYear() + '-' + (parseInt(dLastUpdate.getMonth()) + 1) + '-' + dLastUpdate.getDate(); sNextLink ='https://marketplace.atlassian.com/rest/2/vendors/96/reporting/licenses?startDate=2019-8-1&endDate=2019-9-30&offset=0&limit=50&lastUpdated=' + sLastUpdate; //sNextLink ='https://marketplace.atlassian.com/rest/2/vendors/96/reporting/licenses?startDate=2021-4-14&endDate=2021-6-30&offset=0&limit=50'; log.audit({ title: 'getInputData', details: 'sNextLink: ' + sNextLink}); var sBasic = 'Basic ' + encode.convert({string: 'engliew@me.com:EhwHv6PUOthU4mh9eFIYC2A3', inputEncoding: encode.Encoding.UTF_8, outputEncoding: encode.Encoding.BASE_64}); var headerObj = {'Content-Type' : 'application/json', 'Authorization' : sBasic}; while(sNextLink !=''){ var response = https.get({url: sNextLink, headers: headerObj }); //log.audit({ title: 'getInputData', details: 'link: ' + sNextLink}); if(response.code == 200){ sNextLink = ''; var objBody = JSON.parse(response.body); var nOffset = 0; if(objBody.licenses){ var arrLicenses = objBody.licenses; var objLinks = objBody._links; arrLicenses.forEach( function(license, indx){ var objTrans = {}; //objTrans.key = (license.licenseId).replace('AT-', ''); objTrans.key = license.licenseId + '-' + license.maintenanceStartDate; objTrans.name = license.licenseId + '-' + license.maintenanceStartDate; objTrans.externalid = license.licenseId + '-' + license.addonLicenseId; objTrans.custrecord_lic_vendor_id = '96'; objTrans.custrecord_lic_addon_key = license.addonKey; objTrans.custrecord_lic_addon_license_id = license.addonLicenseId; objTrans.custrecord_lic_host_license_id = license.hostLicenseId; objTrans.custrecord_lic_transaction_id = license.transactionId; objTrans.custrecord_lic_addon_name = license.addonName; objTrans.custrecord_lic_last_updated = license.lastUpdated; objTrans.custrecord_lic_license_id = license.licenseId; objTrans.custrecord_lic_hosting = license.hosting; objTrans.custrecord_lic_license_type = license.licenseType; objTrans.custrecord_lic_maintenance_start_date = license.maintenanceStartDate; objTrans.custrecord_lic_maintenance_end_date = license.maintenanceEndDate; objTrans.custrecord_lic_status = license.status; objTrans.custrecord_lic_tier = license.tier; if(license.contactDetails){ objTrans.custrecord_lic_company_name = license.contactDetails.company; objTrans.custrecord_lic_country = license.contactDetails.country; objTrans.custrecord_lic_region = license.contactDetails.region; } if(license.contactDetails.technicalContact){ objTrans.custrecord_lic_tech_contact_email = license.contactDetails.technicalContact.email; objTrans.custrecord_lic_tech_contact_name = license.contactDetails.technicalContact.name; objTrans.custrecord_lic_tech_contact_address1 = license.contactDetails.technicalContact.address1; objTrans.custrecord_lic_tech_contact_address2 = license.contactDetails.technicalContact.address2; objTrans.custrecord_lic_tech_contact_city = license.contactDetails.technicalContact.city; objTrans.custrecord_lic_tech_contact_postcode = license.contactDetails.technicalContact.postcode; } if(license.contactDetails.billingContact){ objTrans.custrecord_lic_billing_contact_email = license.contactDetails.billingContact.email; objTrans.custrecord_lic_billing_contact_name = license.contactDetails.billingContact.name; objTrans.custrecord_lic_billing_contact_address1 = license.contactDetails.billingContact.address1; objTrans.custrecord_lic_billing_contact_address2 = license.contactDetails.billingContact.address2; objTrans.custrecord_lic_billing_contact_city = license.contactDetails.billingContact.city; objTrans.custrecord_lic_billing_contact_postcode = license.contactDetails.billingContact.postcode; } if(license.partnerDetails){ objTrans.custrecord_lic_partner_type = license.partnerDetails.partnerType; objTrans.custrecord_lic_partner_name = license.partnerDetails.partnerName; if(license.partnerDetails.billingContact){ objTrans.custrecord_lic_pnr_billing_contact_email = license.partnerDetails.billingContact.email; objTrans.custrecord_lic_pnr_billing_contact_name = license.partnerDetails.billingContact.name; } } objTrans.custrecord_lic_customer_domain = (objTrans.custrecord_lic_tech_contact_email).split('@')[1]; objTrans.custrecord_lic_raw_json = JSON.stringify(license); objInputs.push(objTrans); return true; }); //sNextLink = ''; if(objLinks.next){ var sLink = objLinks.next.href.split('offset=')[1]; var sOffset = sLink.split('&')[0]; nOffset = parseInt(sOffset) + arrLicenses.length; sNextLink = 'https://marketplace.atlassian.com' + objLinks.next.href; sLastLink = sNextLink; } else{ var dNewLastUpdate = new Date (dLastUpdate.setDate(dLastUpdate.getDate() + 1)); log.audit({ title: 'getInputData', details: 'dNewLastUpdate: ' + dNewLastUpdate}); var recDeploy = record.load({type: 'scriptdeployment', id: 15484}); recDeploy.setValue({fieldId: 'custscript_lichist_lastupdate', value: dNewLastUpdate}); //var id = recDeploy.save(); var recDeploy = record.load({type: 'scriptdeployment', id: 15630}); recDeploy.setValue({fieldId: 'custscript_lichist_lastupdate', value: dNewLastUpdate}); //var id = recDeploy.save(); var recDeploy = record.load({type: 'scriptdeployment', id: 15631}); recDeploy.setValue({fieldId: 'custscript_lichist_lastupdate', value: dNewLastUpdate}); //var id = recDeploy.save(); } } } else{ var errAtlassian = error.create({ name: 'SERVER_ERROR', message: response.code +': ' + response.body, notifyOff: false }); throw errAtlassian; } } log.audit({ title: 'getInputData', details: 'objInputs: ' + JSON.stringify(objInputs)}); log.audit({ title: 'getInputData', details: 'objInputs Count: ' + objInputs.length}); return objInputs; } /** * Executes when the map entry point is triggered and applies to each key/value pair. * * @param {MapSummary} context - Data collection containing the key/value pairs to process through the map stage * @since 2015.1 */ function map(context) { var objContext = JSON.parse(context.value); var keyMap = objContext.key; var objContent = {}; objContent.value = []; objContent.text = []; objContent.date = []; fldValues.forEach(function(field, indx) { objContent.value.push({fieldId: field, value: objContext[field]}); }); fldDate.forEach(function(field, indx) { var arrDate = objContext[field].split('-'); sDate = arrDate[1] + '/' + arrDate[2] + '/' + arrDate[0]; objContent.date.push({fieldId: field, value: sDate}); }); fldTxt.forEach(function(field, indx) { objContent.text.push({fieldId: field, text: objContext[field]}); }); context.write({ key: keyMap, value: objContent }); } /** * Executes when the reduce entry point is triggered and applies to each group. * * @param {ReduceSummary} context - Data collection containing the groups to process through the reduce stage * @since 2015.1 */ reduce = function (context) { var id = context.key; var objValue = JSON.parse(context.values[0]).value; var objText = JSON.parse(context.values[0]).text; var objDate = JSON.parse(context.values[0]).date; var rec; var src = search.create({type: 'customrecord_atl_marketplace_license', columns: ['internalid'], filters: ['externalid', 'anyof', objValue[0].value]}); var res = src.run().getRange({start: 0, end: 1}); if(res.length > 0){ rec = record.load({type: 'customrecord_atl_marketplace_license', id: res[0].id}); } else{ rec = record.create({type: 'customrecord_atl_marketplace_license'}); } rec.setValue({fieldId: 'custrecord_mp_type', value: ATLASSIANTYPE}); objValue.forEach(function(field, indx) { rec.setValue(field); }); objText.forEach(function(field, indx) { rec.setText(field); }); objDate.forEach(function(field, indx) { field.value = format.parse({ value:new Date(field.value), type: format.Type.DATE}); rec.setValue(field); }); var id = rec.save(); /////Linking Starts Here //log.audit({ title: 'reduce', details: 'Atlassian Transaction Saved: ' + id}); rec = record.load({type: 'customrecord_atl_marketplace_license', id: id}); //log.audit({ title: 'reduce', details: 'Searching Customer: ' + rec.getValue({fieldId: 'custrecord_company'}) + ':' + rec.getValue({fieldId: 'custrecord_customer_domain'})}); var src = search.create({type: 'customer', columns: ['internalid', 'isinactive']}); src.filters = []; src.filters.push(search.createFilter({name: 'companyname', operator: 'is', values: rec.getValue({fieldId: 'custrecord_lic_company_name'}).substring(0, 83)})); //src.filters.push(search.createFilter({name: 'custentity_domain', operator: 'is', values: rec.getValue({fieldId: 'custrecord_customer_domain'})})); var res = src.run().getRange({start: 0, end: 1}); //customer var idCustomer; if(res.length > 0){ //log.audit({ title: 'reduce', details: 'Customer: found'}); if( res[0].getValue({name: 'isinactive'}) == true ){ record.submitFields({ type: 'customer', id: res[0].id, values: {isinactive: false}}); } rec.setValue({fieldId: 'custrecord_lic_company', value: res[0].id}); idCustomer = res[0].id; } else{ //log.audit({ title: 'reduce', details: 'Customer: not found'}); //log.audit({ title: 'reduce', details: 'Customer: Creating New customer'}); var recCustomer = record.create({type: 'customer'}); recCustomer.setValue({fieldId: 'subsidiary', value : 1}); if(rec.getValue({fieldId: 'custrecord_lic_company_name'}).length > 83){ recCustomer.setValue({fieldId: 'companyname', value : rec.getValue({fieldId: 'custrecord_lic_company_name'}).substring(0, 83)}); recCustomer.setValue({fieldId: 'comments', value : 'Full Company Name: ' + rec.getValue({fieldId: 'custrecord_lic_company_name'})}); } else{ recCustomer.setValue({fieldId: 'companyname', value : rec.getValue({fieldId: 'custrecord_lic_company_name'})}); } recCustomer.setValue({fieldId: 'custentity_domain', value : rec.getValue({fieldId: 'custrecord_lic_customer_domain'})}); idCustomer = recCustomer.save(); //log.audit({ title: 'reduce', details: 'Customer: New customer created ' + idCustomer}); rec.setValue({fieldId: 'custrecord_lic_company', value: idCustomer}); } var id = rec.save(); rec = record.load({type: 'customrecord_atl_marketplace_license', id: id}); //tech contact if(rec.getValue({fieldId: 'custrecord_lic_tech_contact_email'}) != '' && rec.getValue({fieldId: 'custrecord_lic_tech_contact_email'}) != null){ //log.audit({ title: 'reduce', details: 'Searching: Tech Contact Email ' + rec.getValue({fieldId: 'custrecord_technical_contact_email'})}); var src = search.create({type: 'customer', columns: ['internalid']}); src.filters = []; src.filters.push(search.createFilter({name: 'email', operator: 'is', values: rec.getValue({fieldId: 'custrecord_lic_tech_contact_email'})})); var res = src.run().getRange({start: 0, end: 1}); if(res.length > 0){ //log.audit({ title: 'reduce', details: 'Searching: Tech Email Found'}); rec.setValue({fieldId: 'custrecord_lic_tech_contact', value: res[0].id}); idContact = res[0].id; } else{ //log.audit({ title: 'reduce', details: 'Searching: Tech Email Not Found'}); //log.audit({ title: 'reduce', details: 'Searching: Tech Contact Name'}); if(rec.getValue({fieldId: 'custrecord_lic_tech_contact_name'}) != '' && rec.getValue({fieldId: 'custrecord_lic_tech_contact_name'}) != null){ var src = search.create({type: 'contact', columns: ['internalid']}); src.filters = []; src.filters.push(search.createFilter({name: 'entityid', operator: 'is', values: rec.getValue({fieldId: 'custrecord_lic_tech_contact_name'})})); src.filters.push(search.createFilter({name: 'company', operator: 'anyof', values: idCustomer})); var res = src.run().getRange({start: 0, end: 1}); var idContact; if(res.length > 0){ //log.audit({ title: 'reduce', details: 'Searching: Tech Contact Name Found'}); rec.setValue({fieldId: 'custrecord_lic_tech_contact', value: res[0].id}); idContact = res[0].id; } else{ //log.audit({ title: 'reduce', details: 'Searching: Tech Contact Name Not Found'}); //log.audit({ title: 'reduce', details: 'Creating: Creating new Tech Contact'}); var recContact = record.create({type: 'contact'}); recContact.setValue({fieldId: 'subsidiary', value : 1}); recContact.setValue({fieldId: 'company', value : idCustomer}); recContact.setValue({fieldId: 'entityid', value : rec.getValue({fieldId: 'custrecord_lic_tech_contact_name'})}); recContact.setValue({fieldId: 'email', value : rec.getValue({fieldId: 'custrecord_lic_tech_contact_email'})}); idContact = recContact.save(); rec.setValue({fieldId: 'custrecord_lic_tech_contact', value: idContact}); } } else{ var src = search.create({type: 'contact', columns: ['internalid']}); src.filters = []; src.filters.push(search.createFilter({name: 'entityid', operator: 'is', values: rec.getValue({fieldId: 'custrecord_lic_company_name'}) + ' Tech Contact'})); src.filters.push(search.createFilter({name: 'company', operator: 'anyof', values: idCustomer})); var res = src.run().getRange({start: 0, end: 1}); var idContact; if(res.length > 0){ //log.audit({ title: 'reduce', details: 'Searching: Tech Contact Name Found'}); rec.setValue({fieldId: 'custrecord_lic_tech_contact', value: res[0].id}); idContact = res[0].id; } else{ //log.audit({ title: 'reduce', details: 'Creating: Creating new Tech Contact'}); var recContact = record.create({type: 'contact'}); recContact.setValue({fieldId: 'subsidiary', value : 1}); recContact.setValue({fieldId: 'company', value : idCustomer}); recContact.setValue({fieldId: 'entityid', value : rec.getValue({fieldId: 'custrecord_lic_company_name'}) + ' Tech Contact'}); recContact.setValue({fieldId: 'email', value : rec.getValue({fieldId: 'custrecord_lic_tech_contact_email'})}); idContact = recContact.save(); rec.setValue({fieldId: 'custrecord_technical_contact', value: idContact}); } } } //billing contact if the same as tech if(rec.getValue({fieldId: 'custrecord_lic_tech_contact_email'}) == rec.getValue({fieldId: 'custrecord_lic_billing_contact_email'})){ //log.audit({ title: 'reduce', details: 'Checking: Tech Contact same as Bill Contact'}); rec.setValue({fieldId: 'custrecord_lic_billing_contact', value: idContact}); } } var id = rec.save(); rec = record.load({type: 'customrecord_atl_marketplace_license', id: id}); //billing contact if not the same as tech if(rec.getValue({fieldId: 'custrecord_lic_billing_contact_email'}) && rec.getValue({fieldId: 'custrecord_lic_billing_contact_email'}) != rec.getValue({fieldId: 'custrecord_lic_tech_contact_email'})){ //log.audit({ title: 'reduce', details: 'Searching: Bill Contact Email ' + rec.getValue({fieldId: 'custrecord_billing_contact_email'})}); var src = search.create({type: 'customer', columns: ['internalid']}); src.filters = []; src.filters.push(search.createFilter({name: 'email', operator: 'is', values: rec.getValue({fieldId: 'custrecord_lic_billing_contact_email'})})); var res = src.run().getRange({start: 0, end: 1}); var idContact; if(res.length > 0){ rec.setValue({fieldId: 'custrecord_lic_billing_contact', value: res[0].id}); //log.audit({ title: 'reduce', details: 'Searching: Bill Email Found'}); idContact = res[0].id; } else{ //log.audit({ title: 'reduce', details: 'Searching: Bill Contact Name'}); if(rec.getValue({fieldId: 'custrecord_lic_billing_contact_name'}) != '' && rec.getValue({fieldId: 'custrecord_lic_billing_contact_name'}) != null){ var src = search.create({type: 'contact', columns: ['internalid']}); src.filters = []; src.filters.push(search.createFilter({name: 'entityid', operator: 'is', values: rec.getValue({fieldId: 'custrecord_lic_billing_contact_name'})})); src.filters.push(search.createFilter({name: 'company', operator: 'anyof', values: idCustomer})); var res = src.run().getRange({start: 0, end: 1}); var idContact; if(res.length > 0){ //log.audit({ title: 'reduce', details: 'Searching: Bill Contact Name Found'}); rec.setValue({fieldId: 'custrecord_lic_billing_contact', value: res[0].id}); idContact = res[0].id; } else{ //log.audit({ title: 'reduce', details: 'Creating: Creating new Bill Contact'}); var recContact = record.create({type: 'contact'}); recContact.setValue({fieldId: 'subsidiary', value : 1}); recContact.setValue({fieldId: 'company', value : idCustomer}); recContact.setValue({fieldId: 'entityid', value : rec.getValue({fieldId: 'custrecord_lic_billing_contact_name'})}); recContact.setValue({fieldId: 'email', value : rec.getValue({fieldId: 'custrecord_lic_billing_contact_email'})}); idContact = recContact.save(); rec.setValue({fieldId: 'custrecord_lic_billing_contact', value: idContact}); } } else{ var src = search.create({type: 'contact', columns: ['internalid']}); src.filters = []; src.filters.push(search.createFilter({name: 'entityid', operator: 'is', values: rec.getValue({fieldId: 'custrecord_lic_company_name'}) + ' Billing Contact'})); src.filters.push(search.createFilter({name: 'company', operator: 'anyof', values: idCustomer})); var res = src.run().getRange({start: 0, end: 1}); var idContact; if(res.length > 0){ //log.audit({ title: 'reduce', details: 'Searching: Bill Contact Name Found'}); rec.setValue({fieldId: 'custrecord_lic_billing_contact', value: res[0].id}); idContact = res[0].id; } else{ //log.audit({ title: 'reduce', details: 'Creating: Creating new Bill Contact'}); var recContact = record.create({type: 'contact'}); recContact.setValue({fieldId: 'subsidiary', value : 1}); recContact.setValue({fieldId: 'company', value : idCustomer}); recContact.setValue({fieldId: 'entityid', value : rec.getValue({fieldId: 'custrecord_lic_company_name'}) + ' Billing Contact'}); recContact.setValue({fieldId: 'email', value : rec.getValue({fieldId: 'custrecord_lic_billing_contact_email'})}); idContact = recContact.save(); rec.setValue({fieldId: 'custrecord_lic_billing_contact', value: idContact}); } } } } var id = rec.save(); rec = record.load({type: 'customrecord_atl_marketplace_license', id: id}); //log.audit({ title: 'reduce', details: 'Searching Partner: ' + rec.getValue({fieldId: 'custrecord_partner_name'})}); //partner if(rec.getValue({fieldId: 'custrecord_lic_partner_name'}) != '' && rec.getValue({fieldId: 'custrecord_lic_partner_name'}) != null){ var src = search.create({type: 'partner', columns: ['internalid']}); src.filters = []; src.filters.push(search.createFilter({name: 'entityid', operator: 'is', values: rec.getValue({fieldId: 'custrecord_lic_partner_name'})})); var res = src.run().getRange({start: 0, end: 1}); var idPartner; if(res.length > 0){ rec.setValue({fieldId: 'custrecord_lic_partner', value: res[0].id}); idPartner = res[0].id; } else{ var recPartner = record.create({type: 'partner'}); recPartner.setValue({fieldId: 'subsidiary', value : 1}); recPartner.setValue({fieldId: 'companyname', value : rec.getValue({fieldId: 'custrecord_lic_partner_name'})}); idPartner = recPartner.save(); rec.setValue({fieldId: 'custrecord_lic_partner', value: idPartner}); } if(rec.getValue({fieldId: 'custrecord_lic_pnr_billing_contact_email'})){ var src = search.create({type: 'contact', columns: ['internalid']}); src.filters = []; src.filters.push(search.createFilter({name: 'email', operator: 'is', values: rec.getValue({fieldId: 'custrecord_lic_pnr_billing_contact_email'})})); var res = src.run().getRange({start: 0, end: 1}); if(res.length > 0){ rec.setValue({fieldId: 'custrecord_lic_pnr_billing_contact', value: res[0].id});//missing idContact = res[0].id; } else{ var src = search.create({type: 'contact', columns: ['internalid']}); if(rec.getValue({fieldId: 'custrecord_lic_pnr_billing_contact_name'}) != '' && rec.getValue({fieldId: 'custrecord_lic_pnr_billing_contact_name'}) != null){ src.filters = []; src.filters.push(search.createFilter({name: 'entityid', operator: 'is', values: rec.getValue({fieldId: 'custrecord_lic_pnr_billing_contact_name'})})); src.filters.push(search.createFilter({name: 'company', operator: 'anyof', values: idPartner})); var res = src.run().getRange({start: 0, end: 1}); var idContact; if(res.length > 0){ rec.setValue({fieldId: 'custrecord_lic_pnr_billing_contact', value: res[0].id});//missing idContact = res[0].id; } else{ var recContact = record.create({type: 'contact'}); recContact.setValue({fieldId: 'subsidiary', value : 1}); recContact.setValue({fieldId: 'company', value : idPartner}); recContact.setValue({fieldId: 'entityid', value : rec.getValue({fieldId: 'custrecord_lic_pnr_billing_contact_name'})}); recContact.setValue({fieldId: 'email', value : rec.getValue({fieldId: 'custrecord_lic_pnr_billing_contact_email'})}); idContact = recContact.save(); rec.setValue({fieldId: 'custrecord_lic_pnr_billing_contact', value: idContact});//missing } } else{ src.filters = []; src.filters.push(search.createFilter({name: 'entityid', operator: 'is', values: rec.getValue({fieldId: 'custrecord_lic_partner_name'}) + ' Contact'})); src.filters.push(search.createFilter({name: 'company', operator: 'anyof', values: idPartner})); var res = src.run().getRange({start: 0, end: 1}); var idContact; if(res.length > 0){ rec.setValue({fieldId: 'custrecord_lic_pnr_billing_contact', value: res[0].id});//missing idContact = res[0].id; } else{ var recContact = record.create({type: 'contact'}); recContact.setValue({fieldId: 'subsidiary', value : 1}); recContact.setValue({fieldId: 'company', value : idPartner}); recContact.setValue({fieldId: 'entityid', value : rec.getValue({fieldId: 'custrecord_lic_partner_name'}) + ' Contact'}); recContact.setValue({fieldId: 'email', value : rec.getValue({fieldId: 'custrecord_lic_pnr_billing_contact_email'})}); idContact = recContact.save(); rec.setValue({fieldId: 'custrecord_lic_pnr_billing_contact', value: idContact});//missing } } } } } var id = rec.save(); } /** * Executes when the summarize entry point is triggered and applies to the result set. * * @param {Summary} summary - Holds statistics regarding the execution of a map/reduce script * @since 2015.1 */ summarize = function (summary) { var errorMsg = []; var inputSummary = summary.inputSummary; var mapSummary = summary.mapSummary; var reduceSummary = summary.reduceSummary; if(summary.inputSummary.error){ var msg = 'Error was: ' + summary.inputSummary.error + '\n'; errorMsg.push(msg); } //log.audit({ title: 'summarize', details: 'offset: ' + nOffset}); var nProcessed = 0; var nErrored = 0; reduceSummary.keys.iterator().each(function (key, executionCount, completionState){ if (completionState === 'COMPLETE'){ nProcessed++; } else if (completionState === 'FAILED'){ nErrored++; } return true; }); reduceSummary.errors.iterator().each(function(key, value){ var msg = 'Process id: ' + key + '. Error was: ' + JSON.parse(value).message + '\n'; errorMsg.push(msg); return true; }); var sMessage = ''; if(errorMsg.length > 0){ sMessage = 'Error on importing Atlassian Transaction. Please visit this article in TSM for details (https://rocketeers.atlassian.net/l/c/FhNAcJwj): ' + JSON.stringify(errorMsg); } else{ sMessage = 'Successful'; } var recLog = record.create({type: 'customrecord_atlassian_summary', isDynamic: true}); recLog.setValue({fieldId: 'custrecord_atlassum_message', value: sMessage}); recLog.setValue({fieldId: 'custrecord_atlassum_numprocessed', value: parseInt(nProcessed) + parseInt(nErrored)}); recLog.setValue({fieldId: 'custrecord_atlassum_error', value: nErrored}); var id = recLog.save(); var scriptTask = task.create({taskType: task.TaskType.MAP_REDUCE}); scriptTask.scriptId = 'customscript_pullatlassian_lichist_mr'; scriptTask.deploymentId = null; var id = scriptTask.submit(); } return { getInputData: getInputData, map: map, reduce: reduce, summarize: summarize }; });
1,148
[{"tag": "EMAIL", "value": "engliew@me.com", "start": 3444, "end": 3458}]
true
1
/** * @NApiVersion 2.x * @NScriptType MapReduceScript * @NModuleScope SameAccount */ define(['N/https', 'N/encode', 'N/record', 'N/format', 'N/search', 'N/runtime', 'N/error', 'N/task'], /** * @param {https} https * @param {encode} encode * @param {record} record */ function(https, encode, record, format, search, runtime, error, task) { /** * Marks the beginning of the Map/Reduce process and generates input data. * * @typedef {Object} ObjectRef * @property {number} id - Internal ID of the record instance * @property {string} type - Record type id * * @return {Array|Object|Search|RecordRef} inputSummary * @since 2015.1 */ var sNextLink = ''; var sLastLink = ''; var ATLASSIANTYPE = 1; var fldValues = [ 'externalid', 'name', 'custrecord_lic_addon_key', 'custrecord_lic_addon_license_id', 'custrecord_lic_host_license_id', 'custrecord_lic_transaction_id', 'custrecord_lic_addon_name', 'custrecord_lic_company_name', 'custrecord_lic_license_id', 'custrecord_lic_country', 'custrecord_lic_region', 'custrecord_lic_hosting', 'custrecord_lic_license_type', 'custrecord_lic_status', 'custrecord_lic_tier', 'custrecord_lic_tech_contact_name', 'custrecord_lic_tech_contact_email', 'custrecord_lic_tech_contact_address1', 'custrecord_lic_tech_contact_address2', 'custrecord_lic_tech_contact_city', 'custrecord_lic_tech_contact_postcode', 'custrecord_lic_billing_contact_email', 'custrecord_lic_billing_contact_name', 'custrecord_lic_billing_contact_address1', 'custrecord_lic_billing_contact_address2', 'custrecord_lic_billing_contact_city', 'custrecord_lic_billing_contact_postcode', 'custrecord_lic_pnr_billing_contact_name', 'custrecord_lic_pnr_billing_contact_email', 'custrecord_lic_partner_name', 'custrecord_lic_partner_type', 'custrecord_lic_customer_domain', 'custrecord_lic_raw_json', 'custrecord_lic_region', 'custrecord_lic_vendor_id']; var fldDate = ['custrecord_lic_last_updated', 'custrecord_lic_maintenance_start_date', 'custrecord_lic_maintenance_end_date']; var fldTxt = []; function getInputData() { var dLastUpdate = runtime.getCurrentScript().getParameter({name: 'custscript_lichist_lastupdate'}); var objInputs = []; var sLastUpdate = dLastUpdate.getFullYear() + '-' + (parseInt(dLastUpdate.getMonth()) + 1) + '-' + dLastUpdate.getDate(); sNextLink ='https://marketplace.atlassian.com/rest/2/vendors/96/reporting/licenses?startDate=2019-8-1&endDate=2019-9-30&offset=0&limit=50&lastUpdated=' + sLastUpdate; //sNextLink ='https://marketplace.atlassian.com/rest/2/vendors/96/reporting/licenses?startDate=2021-4-14&endDate=2021-6-30&offset=0&limit=50'; log.audit({ title: 'getInputData', details: 'sNextLink: ' + sNextLink}); var sBasic = 'Basic ' + encode.convert({string: 'kenaa@example.com:EhwHv6PUOthU4mh9eFIYC2A3', inputEncoding: encode.Encoding.UTF_8, outputEncoding: encode.Encoding.BASE_64}); var headerObj = {'Content-Type' : 'application/json', 'Authorization' : sBasic}; while(sNextLink !=''){ var response = https.get({url: sNextLink, headers: headerObj }); //log.audit({ title: 'getInputData', details: 'link: ' + sNextLink}); if(response.code == 200){ sNextLink = ''; var objBody = JSON.parse(response.body); var nOffset = 0; if(objBody.licenses){ var arrLicenses = objBody.licenses; var objLinks = objBody._links; arrLicenses.forEach( function(license, indx){ var objTrans = {}; //objTrans.key = (license.licenseId).replace('AT-', ''); objTrans.key = license.licenseId + '-' + license.maintenanceStartDate; objTrans.name = license.licenseId + '-' + license.maintenanceStartDate; objTrans.externalid = license.licenseId + '-' + license.addonLicenseId; objTrans.custrecord_lic_vendor_id = '96'; objTrans.custrecord_lic_addon_key = license.addonKey; objTrans.custrecord_lic_addon_license_id = license.addonLicenseId; objTrans.custrecord_lic_host_license_id = license.hostLicenseId; objTrans.custrecord_lic_transaction_id = license.transactionId; objTrans.custrecord_lic_addon_name = license.addonName; objTrans.custrecord_lic_last_updated = license.lastUpdated; objTrans.custrecord_lic_license_id = license.licenseId; objTrans.custrecord_lic_hosting = license.hosting; objTrans.custrecord_lic_license_type = license.licenseType; objTrans.custrecord_lic_maintenance_start_date = license.maintenanceStartDate; objTrans.custrecord_lic_maintenance_end_date = license.maintenanceEndDate; objTrans.custrecord_lic_status = license.status; objTrans.custrecord_lic_tier = license.tier; if(license.contactDetails){ objTrans.custrecord_lic_company_name = license.contactDetails.company; objTrans.custrecord_lic_country = license.contactDetails.country; objTrans.custrecord_lic_region = license.contactDetails.region; } if(license.contactDetails.technicalContact){ objTrans.custrecord_lic_tech_contact_email = license.contactDetails.technicalContact.email; objTrans.custrecord_lic_tech_contact_name = license.contactDetails.technicalContact.name; objTrans.custrecord_lic_tech_contact_address1 = license.contactDetails.technicalContact.address1; objTrans.custrecord_lic_tech_contact_address2 = license.contactDetails.technicalContact.address2; objTrans.custrecord_lic_tech_contact_city = license.contactDetails.technicalContact.city; objTrans.custrecord_lic_tech_contact_postcode = license.contactDetails.technicalContact.postcode; } if(license.contactDetails.billingContact){ objTrans.custrecord_lic_billing_contact_email = license.contactDetails.billingContact.email; objTrans.custrecord_lic_billing_contact_name = license.contactDetails.billingContact.name; objTrans.custrecord_lic_billing_contact_address1 = license.contactDetails.billingContact.address1; objTrans.custrecord_lic_billing_contact_address2 = license.contactDetails.billingContact.address2; objTrans.custrecord_lic_billing_contact_city = license.contactDetails.billingContact.city; objTrans.custrecord_lic_billing_contact_postcode = license.contactDetails.billingContact.postcode; } if(license.partnerDetails){ objTrans.custrecord_lic_partner_type = license.partnerDetails.partnerType; objTrans.custrecord_lic_partner_name = license.partnerDetails.partnerName; if(license.partnerDetails.billingContact){ objTrans.custrecord_lic_pnr_billing_contact_email = license.partnerDetails.billingContact.email; objTrans.custrecord_lic_pnr_billing_contact_name = license.partnerDetails.billingContact.name; } } objTrans.custrecord_lic_customer_domain = (objTrans.custrecord_lic_tech_contact_email).split('@')[1]; objTrans.custrecord_lic_raw_json = JSON.stringify(license); objInputs.push(objTrans); return true; }); //sNextLink = ''; if(objLinks.next){ var sLink = objLinks.next.href.split('offset=')[1]; var sOffset = sLink.split('&')[0]; nOffset = parseInt(sOffset) + arrLicenses.length; sNextLink = 'https://marketplace.atlassian.com' + objLinks.next.href; sLastLink = sNextLink; } else{ var dNewLastUpdate = new Date (dLastUpdate.setDate(dLastUpdate.getDate() + 1)); log.audit({ title: 'getInputData', details: 'dNewLastUpdate: ' + dNewLastUpdate}); var recDeploy = record.load({type: 'scriptdeployment', id: 15484}); recDeploy.setValue({fieldId: 'custscript_lichist_lastupdate', value: dNewLastUpdate}); //var id = recDeploy.save(); var recDeploy = record.load({type: 'scriptdeployment', id: 15630}); recDeploy.setValue({fieldId: 'custscript_lichist_lastupdate', value: dNewLastUpdate}); //var id = recDeploy.save(); var recDeploy = record.load({type: 'scriptdeployment', id: 15631}); recDeploy.setValue({fieldId: 'custscript_lichist_lastupdate', value: dNewLastUpdate}); //var id = recDeploy.save(); } } } else{ var errAtlassian = error.create({ name: 'SERVER_ERROR', message: response.code +': ' + response.body, notifyOff: false }); throw errAtlassian; } } log.audit({ title: 'getInputData', details: 'objInputs: ' + JSON.stringify(objInputs)}); log.audit({ title: 'getInputData', details: 'objInputs Count: ' + objInputs.length}); return objInputs; } /** * Executes when the map entry point is triggered and applies to each key/value pair. * * @param {MapSummary} context - Data collection containing the key/value pairs to process through the map stage * @since 2015.1 */ function map(context) { var objContext = JSON.parse(context.value); var keyMap = objContext.key; var objContent = {}; objContent.value = []; objContent.text = []; objContent.date = []; fldValues.forEach(function(field, indx) { objContent.value.push({fieldId: field, value: objContext[field]}); }); fldDate.forEach(function(field, indx) { var arrDate = objContext[field].split('-'); sDate = arrDate[1] + '/' + arrDate[2] + '/' + arrDate[0]; objContent.date.push({fieldId: field, value: sDate}); }); fldTxt.forEach(function(field, indx) { objContent.text.push({fieldId: field, text: objContext[field]}); }); context.write({ key: keyMap, value: objContent }); } /** * Executes when the reduce entry point is triggered and applies to each group. * * @param {ReduceSummary} context - Data collection containing the groups to process through the reduce stage * @since 2015.1 */ reduce = function (context) { var id = context.key; var objValue = JSON.parse(context.values[0]).value; var objText = JSON.parse(context.values[0]).text; var objDate = JSON.parse(context.values[0]).date; var rec; var src = search.create({type: 'customrecord_atl_marketplace_license', columns: ['internalid'], filters: ['externalid', 'anyof', objValue[0].value]}); var res = src.run().getRange({start: 0, end: 1}); if(res.length > 0){ rec = record.load({type: 'customrecord_atl_marketplace_license', id: res[0].id}); } else{ rec = record.create({type: 'customrecord_atl_marketplace_license'}); } rec.setValue({fieldId: 'custrecord_mp_type', value: ATLASSIANTYPE}); objValue.forEach(function(field, indx) { rec.setValue(field); }); objText.forEach(function(field, indx) { rec.setText(field); }); objDate.forEach(function(field, indx) { field.value = format.parse({ value:new Date(field.value), type: format.Type.DATE}); rec.setValue(field); }); var id = rec.save(); /////Linking Starts Here //log.audit({ title: 'reduce', details: 'Atlassian Transaction Saved: ' + id}); rec = record.load({type: 'customrecord_atl_marketplace_license', id: id}); //log.audit({ title: 'reduce', details: 'Searching Customer: ' + rec.getValue({fieldId: 'custrecord_company'}) + ':' + rec.getValue({fieldId: 'custrecord_customer_domain'})}); var src = search.create({type: 'customer', columns: ['internalid', 'isinactive']}); src.filters = []; src.filters.push(search.createFilter({name: 'companyname', operator: 'is', values: rec.getValue({fieldId: 'custrecord_lic_company_name'}).substring(0, 83)})); //src.filters.push(search.createFilter({name: 'custentity_domain', operator: 'is', values: rec.getValue({fieldId: 'custrecord_customer_domain'})})); var res = src.run().getRange({start: 0, end: 1}); //customer var idCustomer; if(res.length > 0){ //log.audit({ title: 'reduce', details: 'Customer: found'}); if( res[0].getValue({name: 'isinactive'}) == true ){ record.submitFields({ type: 'customer', id: res[0].id, values: {isinactive: false}}); } rec.setValue({fieldId: 'custrecord_lic_company', value: res[0].id}); idCustomer = res[0].id; } else{ //log.audit({ title: 'reduce', details: 'Customer: not found'}); //log.audit({ title: 'reduce', details: 'Customer: Creating New customer'}); var recCustomer = record.create({type: 'customer'}); recCustomer.setValue({fieldId: 'subsidiary', value : 1}); if(rec.getValue({fieldId: 'custrecord_lic_company_name'}).length > 83){ recCustomer.setValue({fieldId: 'companyname', value : rec.getValue({fieldId: 'custrecord_lic_company_name'}).substring(0, 83)}); recCustomer.setValue({fieldId: 'comments', value : 'Full Company Name: ' + rec.getValue({fieldId: 'custrecord_lic_company_name'})}); } else{ recCustomer.setValue({fieldId: 'companyname', value : rec.getValue({fieldId: 'custrecord_lic_company_name'})}); } recCustomer.setValue({fieldId: 'custentity_domain', value : rec.getValue({fieldId: 'custrecord_lic_customer_domain'})}); idCustomer = recCustomer.save(); //log.audit({ title: 'reduce', details: 'Customer: New customer created ' + idCustomer}); rec.setValue({fieldId: 'custrecord_lic_company', value: idCustomer}); } var id = rec.save(); rec = record.load({type: 'customrecord_atl_marketplace_license', id: id}); //tech contact if(rec.getValue({fieldId: 'custrecord_lic_tech_contact_email'}) != '' && rec.getValue({fieldId: 'custrecord_lic_tech_contact_email'}) != null){ //log.audit({ title: 'reduce', details: 'Searching: Tech Contact Email ' + rec.getValue({fieldId: 'custrecord_technical_contact_email'})}); var src = search.create({type: 'customer', columns: ['internalid']}); src.filters = []; src.filters.push(search.createFilter({name: 'email', operator: 'is', values: rec.getValue({fieldId: 'custrecord_lic_tech_contact_email'})})); var res = src.run().getRange({start: 0, end: 1}); if(res.length > 0){ //log.audit({ title: 'reduce', details: 'Searching: Tech Email Found'}); rec.setValue({fieldId: 'custrecord_lic_tech_contact', value: res[0].id}); idContact = res[0].id; } else{ //log.audit({ title: 'reduce', details: 'Searching: Tech Email Not Found'}); //log.audit({ title: 'reduce', details: 'Searching: Tech Contact Name'}); if(rec.getValue({fieldId: 'custrecord_lic_tech_contact_name'}) != '' && rec.getValue({fieldId: 'custrecord_lic_tech_contact_name'}) != null){ var src = search.create({type: 'contact', columns: ['internalid']}); src.filters = []; src.filters.push(search.createFilter({name: 'entityid', operator: 'is', values: rec.getValue({fieldId: 'custrecord_lic_tech_contact_name'})})); src.filters.push(search.createFilter({name: 'company', operator: 'anyof', values: idCustomer})); var res = src.run().getRange({start: 0, end: 1}); var idContact; if(res.length > 0){ //log.audit({ title: 'reduce', details: 'Searching: Tech Contact Name Found'}); rec.setValue({fieldId: 'custrecord_lic_tech_contact', value: res[0].id}); idContact = res[0].id; } else{ //log.audit({ title: 'reduce', details: 'Searching: Tech Contact Name Not Found'}); //log.audit({ title: 'reduce', details: 'Creating: Creating new Tech Contact'}); var recContact = record.create({type: 'contact'}); recContact.setValue({fieldId: 'subsidiary', value : 1}); recContact.setValue({fieldId: 'company', value : idCustomer}); recContact.setValue({fieldId: 'entityid', value : rec.getValue({fieldId: 'custrecord_lic_tech_contact_name'})}); recContact.setValue({fieldId: 'email', value : rec.getValue({fieldId: 'custrecord_lic_tech_contact_email'})}); idContact = recContact.save(); rec.setValue({fieldId: 'custrecord_lic_tech_contact', value: idContact}); } } else{ var src = search.create({type: 'contact', columns: ['internalid']}); src.filters = []; src.filters.push(search.createFilter({name: 'entityid', operator: 'is', values: rec.getValue({fieldId: 'custrecord_lic_company_name'}) + ' Tech Contact'})); src.filters.push(search.createFilter({name: 'company', operator: 'anyof', values: idCustomer})); var res = src.run().getRange({start: 0, end: 1}); var idContact; if(res.length > 0){ //log.audit({ title: 'reduce', details: 'Searching: Tech Contact Name Found'}); rec.setValue({fieldId: 'custrecord_lic_tech_contact', value: res[0].id}); idContact = res[0].id; } else{ //log.audit({ title: 'reduce', details: 'Creating: Creating new Tech Contact'}); var recContact = record.create({type: 'contact'}); recContact.setValue({fieldId: 'subsidiary', value : 1}); recContact.setValue({fieldId: 'company', value : idCustomer}); recContact.setValue({fieldId: 'entityid', value : rec.getValue({fieldId: 'custrecord_lic_company_name'}) + ' Tech Contact'}); recContact.setValue({fieldId: 'email', value : rec.getValue({fieldId: 'custrecord_lic_tech_contact_email'})}); idContact = recContact.save(); rec.setValue({fieldId: 'custrecord_technical_contact', value: idContact}); } } } //billing contact if the same as tech if(rec.getValue({fieldId: 'custrecord_lic_tech_contact_email'}) == rec.getValue({fieldId: 'custrecord_lic_billing_contact_email'})){ //log.audit({ title: 'reduce', details: 'Checking: Tech Contact same as Bill Contact'}); rec.setValue({fieldId: 'custrecord_lic_billing_contact', value: idContact}); } } var id = rec.save(); rec = record.load({type: 'customrecord_atl_marketplace_license', id: id}); //billing contact if not the same as tech if(rec.getValue({fieldId: 'custrecord_lic_billing_contact_email'}) && rec.getValue({fieldId: 'custrecord_lic_billing_contact_email'}) != rec.getValue({fieldId: 'custrecord_lic_tech_contact_email'})){ //log.audit({ title: 'reduce', details: 'Searching: Bill Contact Email ' + rec.getValue({fieldId: 'custrecord_billing_contact_email'})}); var src = search.create({type: 'customer', columns: ['internalid']}); src.filters = []; src.filters.push(search.createFilter({name: 'email', operator: 'is', values: rec.getValue({fieldId: 'custrecord_lic_billing_contact_email'})})); var res = src.run().getRange({start: 0, end: 1}); var idContact; if(res.length > 0){ rec.setValue({fieldId: 'custrecord_lic_billing_contact', value: res[0].id}); //log.audit({ title: 'reduce', details: 'Searching: Bill Email Found'}); idContact = res[0].id; } else{ //log.audit({ title: 'reduce', details: 'Searching: Bill Contact Name'}); if(rec.getValue({fieldId: 'custrecord_lic_billing_contact_name'}) != '' && rec.getValue({fieldId: 'custrecord_lic_billing_contact_name'}) != null){ var src = search.create({type: 'contact', columns: ['internalid']}); src.filters = []; src.filters.push(search.createFilter({name: 'entityid', operator: 'is', values: rec.getValue({fieldId: 'custrecord_lic_billing_contact_name'})})); src.filters.push(search.createFilter({name: 'company', operator: 'anyof', values: idCustomer})); var res = src.run().getRange({start: 0, end: 1}); var idContact; if(res.length > 0){ //log.audit({ title: 'reduce', details: 'Searching: Bill Contact Name Found'}); rec.setValue({fieldId: 'custrecord_lic_billing_contact', value: res[0].id}); idContact = res[0].id; } else{ //log.audit({ title: 'reduce', details: 'Creating: Creating new Bill Contact'}); var recContact = record.create({type: 'contact'}); recContact.setValue({fieldId: 'subsidiary', value : 1}); recContact.setValue({fieldId: 'company', value : idCustomer}); recContact.setValue({fieldId: 'entityid', value : rec.getValue({fieldId: 'custrecord_lic_billing_contact_name'})}); recContact.setValue({fieldId: 'email', value : rec.getValue({fieldId: 'custrecord_lic_billing_contact_email'})}); idContact = recContact.save(); rec.setValue({fieldId: 'custrecord_lic_billing_contact', value: idContact}); } } else{ var src = search.create({type: 'contact', columns: ['internalid']}); src.filters = []; src.filters.push(search.createFilter({name: 'entityid', operator: 'is', values: rec.getValue({fieldId: 'custrecord_lic_company_name'}) + ' Billing Contact'})); src.filters.push(search.createFilter({name: 'company', operator: 'anyof', values: idCustomer})); var res = src.run().getRange({start: 0, end: 1}); var idContact; if(res.length > 0){ //log.audit({ title: 'reduce', details: 'Searching: Bill Contact Name Found'}); rec.setValue({fieldId: 'custrecord_lic_billing_contact', value: res[0].id}); idContact = res[0].id; } else{ //log.audit({ title: 'reduce', details: 'Creating: Creating new Bill Contact'}); var recContact = record.create({type: 'contact'}); recContact.setValue({fieldId: 'subsidiary', value : 1}); recContact.setValue({fieldId: 'company', value : idCustomer}); recContact.setValue({fieldId: 'entityid', value : rec.getValue({fieldId: 'custrecord_lic_company_name'}) + ' Billing Contact'}); recContact.setValue({fieldId: 'email', value : rec.getValue({fieldId: 'custrecord_lic_billing_contact_email'})}); idContact = recContact.save(); rec.setValue({fieldId: 'custrecord_lic_billing_contact', value: idContact}); } } } } var id = rec.save(); rec = record.load({type: 'customrecord_atl_marketplace_license', id: id}); //log.audit({ title: 'reduce', details: 'Searching Partner: ' + rec.getValue({fieldId: 'custrecord_partner_name'})}); //partner if(rec.getValue({fieldId: 'custrecord_lic_partner_name'}) != '' && rec.getValue({fieldId: 'custrecord_lic_partner_name'}) != null){ var src = search.create({type: 'partner', columns: ['internalid']}); src.filters = []; src.filters.push(search.createFilter({name: 'entityid', operator: 'is', values: rec.getValue({fieldId: 'custrecord_lic_partner_name'})})); var res = src.run().getRange({start: 0, end: 1}); var idPartner; if(res.length > 0){ rec.setValue({fieldId: 'custrecord_lic_partner', value: res[0].id}); idPartner = res[0].id; } else{ var recPartner = record.create({type: 'partner'}); recPartner.setValue({fieldId: 'subsidiary', value : 1}); recPartner.setValue({fieldId: 'companyname', value : rec.getValue({fieldId: 'custrecord_lic_partner_name'})}); idPartner = recPartner.save(); rec.setValue({fieldId: 'custrecord_lic_partner', value: idPartner}); } if(rec.getValue({fieldId: 'custrecord_lic_pnr_billing_contact_email'})){ var src = search.create({type: 'contact', columns: ['internalid']}); src.filters = []; src.filters.push(search.createFilter({name: 'email', operator: 'is', values: rec.getValue({fieldId: 'custrecord_lic_pnr_billing_contact_email'})})); var res = src.run().getRange({start: 0, end: 1}); if(res.length > 0){ rec.setValue({fieldId: 'custrecord_lic_pnr_billing_contact', value: res[0].id});//missing idContact = res[0].id; } else{ var src = search.create({type: 'contact', columns: ['internalid']}); if(rec.getValue({fieldId: 'custrecord_lic_pnr_billing_contact_name'}) != '' && rec.getValue({fieldId: 'custrecord_lic_pnr_billing_contact_name'}) != null){ src.filters = []; src.filters.push(search.createFilter({name: 'entityid', operator: 'is', values: rec.getValue({fieldId: 'custrecord_lic_pnr_billing_contact_name'})})); src.filters.push(search.createFilter({name: 'company', operator: 'anyof', values: idPartner})); var res = src.run().getRange({start: 0, end: 1}); var idContact; if(res.length > 0){ rec.setValue({fieldId: 'custrecord_lic_pnr_billing_contact', value: res[0].id});//missing idContact = res[0].id; } else{ var recContact = record.create({type: 'contact'}); recContact.setValue({fieldId: 'subsidiary', value : 1}); recContact.setValue({fieldId: 'company', value : idPartner}); recContact.setValue({fieldId: 'entityid', value : rec.getValue({fieldId: 'custrecord_lic_pnr_billing_contact_name'})}); recContact.setValue({fieldId: 'email', value : rec.getValue({fieldId: 'custrecord_lic_pnr_billing_contact_email'})}); idContact = recContact.save(); rec.setValue({fieldId: 'custrecord_lic_pnr_billing_contact', value: idContact});//missing } } else{ src.filters = []; src.filters.push(search.createFilter({name: 'entityid', operator: 'is', values: rec.getValue({fieldId: 'custrecord_lic_partner_name'}) + ' Contact'})); src.filters.push(search.createFilter({name: 'company', operator: 'anyof', values: idPartner})); var res = src.run().getRange({start: 0, end: 1}); var idContact; if(res.length > 0){ rec.setValue({fieldId: 'custrecord_lic_pnr_billing_contact', value: res[0].id});//missing idContact = res[0].id; } else{ var recContact = record.create({type: 'contact'}); recContact.setValue({fieldId: 'subsidiary', value : 1}); recContact.setValue({fieldId: 'company', value : idPartner}); recContact.setValue({fieldId: 'entityid', value : rec.getValue({fieldId: 'custrecord_lic_partner_name'}) + ' Contact'}); recContact.setValue({fieldId: 'email', value : rec.getValue({fieldId: 'custrecord_lic_pnr_billing_contact_email'})}); idContact = recContact.save(); rec.setValue({fieldId: 'custrecord_lic_pnr_billing_contact', value: idContact});//missing } } } } } var id = rec.save(); } /** * Executes when the summarize entry point is triggered and applies to the result set. * * @param {Summary} summary - Holds statistics regarding the execution of a map/reduce script * @since 2015.1 */ summarize = function (summary) { var errorMsg = []; var inputSummary = summary.inputSummary; var mapSummary = summary.mapSummary; var reduceSummary = summary.reduceSummary; if(summary.inputSummary.error){ var msg = 'Error was: ' + summary.inputSummary.error + '\n'; errorMsg.push(msg); } //log.audit({ title: 'summarize', details: 'offset: ' + nOffset}); var nProcessed = 0; var nErrored = 0; reduceSummary.keys.iterator().each(function (key, executionCount, completionState){ if (completionState === 'COMPLETE'){ nProcessed++; } else if (completionState === 'FAILED'){ nErrored++; } return true; }); reduceSummary.errors.iterator().each(function(key, value){ var msg = 'Process id: ' + key + '. Error was: ' + JSON.parse(value).message + '\n'; errorMsg.push(msg); return true; }); var sMessage = ''; if(errorMsg.length > 0){ sMessage = 'Error on importing Atlassian Transaction. Please visit this article in TSM for details (https://rocketeers.atlassian.net/l/c/FhNAcJwj): ' + JSON.stringify(errorMsg); } else{ sMessage = 'Successful'; } var recLog = record.create({type: 'customrecord_atlassian_summary', isDynamic: true}); recLog.setValue({fieldId: 'custrecord_atlassum_message', value: sMessage}); recLog.setValue({fieldId: 'custrecord_atlassum_numprocessed', value: parseInt(nProcessed) + parseInt(nErrored)}); recLog.setValue({fieldId: 'custrecord_atlassum_error', value: nErrored}); var id = recLog.save(); var scriptTask = task.create({taskType: task.TaskType.MAP_REDUCE}); scriptTask.scriptId = 'customscript_pullatlassian_lichist_mr'; scriptTask.deploymentId = null; var id = scriptTask.submit(); } return { getInputData: getInputData, map: map, reduce: reduce, summarize: summarize }; });
true
/** * @NApiVersion 2.x * @NScriptType MapReduceScript * @NModuleScope SameAccount */ define(['N/https', 'N/encode', 'N/record', 'N/format', 'N/search', 'N/runtime', 'N/error', 'N/task'], /** * @param {https} https * @param {encode} encode * @param {record} record */ function(https, encode, record, format, search, runtime, error, task) { /** * Marks the beginning of the Map/Reduce process and generates input data. * * @typedef {Object} ObjectRef * @property {number} id - Internal ID of the record instance * @property {string} type - Record type id * * @return {Array|Object|Search|RecordRef} inputSummary * @since 2015.1 */ var sNextLink = ''; var sLastLink = ''; var ATLASSIANTYPE = 1; var fldValues = [ 'externalid', 'name', 'custrecord_lic_addon_key', 'custrecord_lic_addon_license_id', 'custrecord_lic_host_license_id', 'custrecord_lic_transaction_id', 'custrecord_lic_addon_name', 'custrecord_lic_company_name', 'custrecord_lic_license_id', 'custrecord_lic_country', 'custrecord_lic_region', 'custrecord_lic_hosting', 'custrecord_lic_license_type', 'custrecord_lic_status', 'custrecord_lic_tier', 'custrecord_lic_tech_contact_name', 'custrecord_lic_tech_contact_email', 'custrecord_lic_tech_contact_address1', 'custrecord_lic_tech_contact_address2', 'custrecord_lic_tech_contact_city', 'custrecord_lic_tech_contact_postcode', 'custrecord_lic_billing_contact_email', 'custrecord_lic_billing_contact_name', 'custrecord_lic_billing_contact_address1', 'custrecord_lic_billing_contact_address2', 'custrecord_lic_billing_contact_city', 'custrecord_lic_billing_contact_postcode', 'custrecord_lic_pnr_billing_contact_name', 'custrecord_lic_pnr_billing_contact_email', 'custrecord_lic_partner_name', 'custrecord_lic_partner_type', 'custrecord_lic_customer_domain', 'custrecord_lic_raw_json', 'custrecord_lic_region', 'custrecord_lic_vendor_id']; var fldDate = ['custrecord_lic_last_updated', 'custrecord_lic_maintenance_start_date', 'custrecord_lic_maintenance_end_date']; var fldTxt = []; function getInputData() { var dLastUpdate = runtime.getCurrentScript().getParameter({name: 'custscript_lichist_lastupdate'}); var objInputs = []; var sLastUpdate = dLastUpdate.getFullYear() + '-' + (parseInt(dLastUpdate.getMonth()) + 1) + '-' + dLastUpdate.getDate(); sNextLink ='https://marketplace.atlassian.com/rest/2/vendors/96/reporting/licenses?startDate=2019-8-1&endDate=2019-9-30&offset=0&limit=50&lastUpdated=' + sLastUpdate; //sNextLink ='https://marketplace.atlassian.com/rest/2/vendors/96/reporting/licenses?startDate=2021-4-14&endDate=2021-6-30&offset=0&limit=50'; log.audit({ title: 'getInputData', details: 'sNextLink: ' + sNextLink}); var sBasic = 'Basic ' + encode.convert({string: 'PI:EMAIL:kenaa@example.comEND_PI:EhwHv6PUOthU4mh9eFIYC2A3', inputEncoding: encode.Encoding.UTF_8, outputEncoding: encode.Encoding.BASE_64}); var headerObj = {'Content-Type' : 'application/json', 'Authorization' : sBasic}; while(sNextLink !=''){ var response = https.get({url: sNextLink, headers: headerObj }); //log.audit({ title: 'getInputData', details: 'link: ' + sNextLink}); if(response.code == 200){ sNextLink = ''; var objBody = JSON.parse(response.body); var nOffset = 0; if(objBody.licenses){ var arrLicenses = objBody.licenses; var objLinks = objBody._links; arrLicenses.forEach( function(license, indx){ var objTrans = {}; //objTrans.key = (license.licenseId).replace('AT-', ''); objTrans.key = license.licenseId + '-' + license.maintenanceStartDate; objTrans.name = license.licenseId + '-' + license.maintenanceStartDate; objTrans.externalid = license.licenseId + '-' + license.addonLicenseId; objTrans.custrecord_lic_vendor_id = '96'; objTrans.custrecord_lic_addon_key = license.addonKey; objTrans.custrecord_lic_addon_license_id = license.addonLicenseId; objTrans.custrecord_lic_host_license_id = license.hostLicenseId; objTrans.custrecord_lic_transaction_id = license.transactionId; objTrans.custrecord_lic_addon_name = license.addonName; objTrans.custrecord_lic_last_updated = license.lastUpdated; objTrans.custrecord_lic_license_id = license.licenseId; objTrans.custrecord_lic_hosting = license.hosting; objTrans.custrecord_lic_license_type = license.licenseType; objTrans.custrecord_lic_maintenance_start_date = license.maintenanceStartDate; objTrans.custrecord_lic_maintenance_end_date = license.maintenanceEndDate; objTrans.custrecord_lic_status = license.status; objTrans.custrecord_lic_tier = license.tier; if(license.contactDetails){ objTrans.custrecord_lic_company_name = license.contactDetails.company; objTrans.custrecord_lic_country = license.contactDetails.country; objTrans.custrecord_lic_region = license.contactDetails.region; } if(license.contactDetails.technicalContact){ objTrans.custrecord_lic_tech_contact_email = license.contactDetails.technicalContact.email; objTrans.custrecord_lic_tech_contact_name = license.contactDetails.technicalContact.name; objTrans.custrecord_lic_tech_contact_address1 = license.contactDetails.technicalContact.address1; objTrans.custrecord_lic_tech_contact_address2 = license.contactDetails.technicalContact.address2; objTrans.custrecord_lic_tech_contact_city = license.contactDetails.technicalContact.city; objTrans.custrecord_lic_tech_contact_postcode = license.contactDetails.technicalContact.postcode; } if(license.contactDetails.billingContact){ objTrans.custrecord_lic_billing_contact_email = license.contactDetails.billingContact.email; objTrans.custrecord_lic_billing_contact_name = license.contactDetails.billingContact.name; objTrans.custrecord_lic_billing_contact_address1 = license.contactDetails.billingContact.address1; objTrans.custrecord_lic_billing_contact_address2 = license.contactDetails.billingContact.address2; objTrans.custrecord_lic_billing_contact_city = license.contactDetails.billingContact.city; objTrans.custrecord_lic_billing_contact_postcode = license.contactDetails.billingContact.postcode; } if(license.partnerDetails){ objTrans.custrecord_lic_partner_type = license.partnerDetails.partnerType; objTrans.custrecord_lic_partner_name = license.partnerDetails.partnerName; if(license.partnerDetails.billingContact){ objTrans.custrecord_lic_pnr_billing_contact_email = license.partnerDetails.billingContact.email; objTrans.custrecord_lic_pnr_billing_contact_name = license.partnerDetails.billingContact.name; } } objTrans.custrecord_lic_customer_domain = (objTrans.custrecord_lic_tech_contact_email).split('@')[1]; objTrans.custrecord_lic_raw_json = JSON.stringify(license); objInputs.push(objTrans); return true; }); //sNextLink = ''; if(objLinks.next){ var sLink = objLinks.next.href.split('offset=')[1]; var sOffset = sLink.split('&')[0]; nOffset = parseInt(sOffset) + arrLicenses.length; sNextLink = 'https://marketplace.atlassian.com' + objLinks.next.href; sLastLink = sNextLink; } else{ var dNewLastUpdate = new Date (dLastUpdate.setDate(dLastUpdate.getDate() + 1)); log.audit({ title: 'getInputData', details: 'dNewLastUpdate: ' + dNewLastUpdate}); var recDeploy = record.load({type: 'scriptdeployment', id: 15484}); recDeploy.setValue({fieldId: 'custscript_lichist_lastupdate', value: dNewLastUpdate}); //var id = recDeploy.save(); var recDeploy = record.load({type: 'scriptdeployment', id: 15630}); recDeploy.setValue({fieldId: 'custscript_lichist_lastupdate', value: dNewLastUpdate}); //var id = recDeploy.save(); var recDeploy = record.load({type: 'scriptdeployment', id: 15631}); recDeploy.setValue({fieldId: 'custscript_lichist_lastupdate', value: dNewLastUpdate}); //var id = recDeploy.save(); } } } else{ var errAtlassian = error.create({ name: 'SERVER_ERROR', message: response.code +': ' + response.body, notifyOff: false }); throw errAtlassian; } } log.audit({ title: 'getInputData', details: 'objInputs: ' + JSON.stringify(objInputs)}); log.audit({ title: 'getInputData', details: 'objInputs Count: ' + objInputs.length}); return objInputs; } /** * Executes when the map entry point is triggered and applies to each key/value pair. * * @param {MapSummary} context - Data collection containing the key/value pairs to process through the map stage * @since 2015.1 */ function map(context) { var objContext = JSON.parse(context.value); var keyMap = objContext.key; var objContent = {}; objContent.value = []; objContent.text = []; objContent.date = []; fldValues.forEach(function(field, indx) { objContent.value.push({fieldId: field, value: objContext[field]}); }); fldDate.forEach(function(field, indx) { var arrDate = objContext[field].split('-'); sDate = arrDate[1] + '/' + arrDate[2] + '/' + arrDate[0]; objContent.date.push({fieldId: field, value: sDate}); }); fldTxt.forEach(function(field, indx) { objContent.text.push({fieldId: field, text: objContext[field]}); }); context.write({ key: keyMap, value: objContent }); } /** * Executes when the reduce entry point is triggered and applies to each group. * * @param {ReduceSummary} context - Data collection containing the groups to process through the reduce stage * @since 2015.1 */ reduce = function (context) { var id = context.key; var objValue = JSON.parse(context.values[0]).value; var objText = JSON.parse(context.values[0]).text; var objDate = JSON.parse(context.values[0]).date; var rec; var src = search.create({type: 'customrecord_atl_marketplace_license', columns: ['internalid'], filters: ['externalid', 'anyof', objValue[0].value]}); var res = src.run().getRange({start: 0, end: 1}); if(res.length > 0){ rec = record.load({type: 'customrecord_atl_marketplace_license', id: res[0].id}); } else{ rec = record.create({type: 'customrecord_atl_marketplace_license'}); } rec.setValue({fieldId: 'custrecord_mp_type', value: ATLASSIANTYPE}); objValue.forEach(function(field, indx) { rec.setValue(field); }); objText.forEach(function(field, indx) { rec.setText(field); }); objDate.forEach(function(field, indx) { field.value = format.parse({ value:new Date(field.value), type: format.Type.DATE}); rec.setValue(field); }); var id = rec.save(); /////Linking Starts Here //log.audit({ title: 'reduce', details: 'Atlassian Transaction Saved: ' + id}); rec = record.load({type: 'customrecord_atl_marketplace_license', id: id}); //log.audit({ title: 'reduce', details: 'Searching Customer: ' + rec.getValue({fieldId: 'custrecord_company'}) + ':' + rec.getValue({fieldId: 'custrecord_customer_domain'})}); var src = search.create({type: 'customer', columns: ['internalid', 'isinactive']}); src.filters = []; src.filters.push(search.createFilter({name: 'companyname', operator: 'is', values: rec.getValue({fieldId: 'custrecord_lic_company_name'}).substring(0, 83)})); //src.filters.push(search.createFilter({name: 'custentity_domain', operator: 'is', values: rec.getValue({fieldId: 'custrecord_customer_domain'})})); var res = src.run().getRange({start: 0, end: 1}); //customer var idCustomer; if(res.length > 0){ //log.audit({ title: 'reduce', details: 'Customer: found'}); if( res[0].getValue({name: 'isinactive'}) == true ){ record.submitFields({ type: 'customer', id: res[0].id, values: {isinactive: false}}); } rec.setValue({fieldId: 'custrecord_lic_company', value: res[0].id}); idCustomer = res[0].id; } else{ //log.audit({ title: 'reduce', details: 'Customer: not found'}); //log.audit({ title: 'reduce', details: 'Customer: Creating New customer'}); var recCustomer = record.create({type: 'customer'}); recCustomer.setValue({fieldId: 'subsidiary', value : 1}); if(rec.getValue({fieldId: 'custrecord_lic_company_name'}).length > 83){ recCustomer.setValue({fieldId: 'companyname', value : rec.getValue({fieldId: 'custrecord_lic_company_name'}).substring(0, 83)}); recCustomer.setValue({fieldId: 'comments', value : 'Full Company Name: ' + rec.getValue({fieldId: 'custrecord_lic_company_name'})}); } else{ recCustomer.setValue({fieldId: 'companyname', value : rec.getValue({fieldId: 'custrecord_lic_company_name'})}); } recCustomer.setValue({fieldId: 'custentity_domain', value : rec.getValue({fieldId: 'custrecord_lic_customer_domain'})}); idCustomer = recCustomer.save(); //log.audit({ title: 'reduce', details: 'Customer: New customer created ' + idCustomer}); rec.setValue({fieldId: 'custrecord_lic_company', value: idCustomer}); } var id = rec.save(); rec = record.load({type: 'customrecord_atl_marketplace_license', id: id}); //tech contact if(rec.getValue({fieldId: 'custrecord_lic_tech_contact_email'}) != '' && rec.getValue({fieldId: 'custrecord_lic_tech_contact_email'}) != null){ //log.audit({ title: 'reduce', details: 'Searching: Tech Contact Email ' + rec.getValue({fieldId: 'custrecord_technical_contact_email'})}); var src = search.create({type: 'customer', columns: ['internalid']}); src.filters = []; src.filters.push(search.createFilter({name: 'email', operator: 'is', values: rec.getValue({fieldId: 'custrecord_lic_tech_contact_email'})})); var res = src.run().getRange({start: 0, end: 1}); if(res.length > 0){ //log.audit({ title: 'reduce', details: 'Searching: Tech Email Found'}); rec.setValue({fieldId: 'custrecord_lic_tech_contact', value: res[0].id}); idContact = res[0].id; } else{ //log.audit({ title: 'reduce', details: 'Searching: Tech Email Not Found'}); //log.audit({ title: 'reduce', details: 'Searching: Tech Contact Name'}); if(rec.getValue({fieldId: 'custrecord_lic_tech_contact_name'}) != '' && rec.getValue({fieldId: 'custrecord_lic_tech_contact_name'}) != null){ var src = search.create({type: 'contact', columns: ['internalid']}); src.filters = []; src.filters.push(search.createFilter({name: 'entityid', operator: 'is', values: rec.getValue({fieldId: 'custrecord_lic_tech_contact_name'})})); src.filters.push(search.createFilter({name: 'company', operator: 'anyof', values: idCustomer})); var res = src.run().getRange({start: 0, end: 1}); var idContact; if(res.length > 0){ //log.audit({ title: 'reduce', details: 'Searching: Tech Contact Name Found'}); rec.setValue({fieldId: 'custrecord_lic_tech_contact', value: res[0].id}); idContact = res[0].id; } else{ //log.audit({ title: 'reduce', details: 'Searching: Tech Contact Name Not Found'}); //log.audit({ title: 'reduce', details: 'Creating: Creating new Tech Contact'}); var recContact = record.create({type: 'contact'}); recContact.setValue({fieldId: 'subsidiary', value : 1}); recContact.setValue({fieldId: 'company', value : idCustomer}); recContact.setValue({fieldId: 'entityid', value : rec.getValue({fieldId: 'custrecord_lic_tech_contact_name'})}); recContact.setValue({fieldId: 'email', value : rec.getValue({fieldId: 'custrecord_lic_tech_contact_email'})}); idContact = recContact.save(); rec.setValue({fieldId: 'custrecord_lic_tech_contact', value: idContact}); } } else{ var src = search.create({type: 'contact', columns: ['internalid']}); src.filters = []; src.filters.push(search.createFilter({name: 'entityid', operator: 'is', values: rec.getValue({fieldId: 'custrecord_lic_company_name'}) + ' Tech Contact'})); src.filters.push(search.createFilter({name: 'company', operator: 'anyof', values: idCustomer})); var res = src.run().getRange({start: 0, end: 1}); var idContact; if(res.length > 0){ //log.audit({ title: 'reduce', details: 'Searching: Tech Contact Name Found'}); rec.setValue({fieldId: 'custrecord_lic_tech_contact', value: res[0].id}); idContact = res[0].id; } else{ //log.audit({ title: 'reduce', details: 'Creating: Creating new Tech Contact'}); var recContact = record.create({type: 'contact'}); recContact.setValue({fieldId: 'subsidiary', value : 1}); recContact.setValue({fieldId: 'company', value : idCustomer}); recContact.setValue({fieldId: 'entityid', value : rec.getValue({fieldId: 'custrecord_lic_company_name'}) + ' Tech Contact'}); recContact.setValue({fieldId: 'email', value : rec.getValue({fieldId: 'custrecord_lic_tech_contact_email'})}); idContact = recContact.save(); rec.setValue({fieldId: 'custrecord_technical_contact', value: idContact}); } } } //billing contact if the same as tech if(rec.getValue({fieldId: 'custrecord_lic_tech_contact_email'}) == rec.getValue({fieldId: 'custrecord_lic_billing_contact_email'})){ //log.audit({ title: 'reduce', details: 'Checking: Tech Contact same as Bill Contact'}); rec.setValue({fieldId: 'custrecord_lic_billing_contact', value: idContact}); } } var id = rec.save(); rec = record.load({type: 'customrecord_atl_marketplace_license', id: id}); //billing contact if not the same as tech if(rec.getValue({fieldId: 'custrecord_lic_billing_contact_email'}) && rec.getValue({fieldId: 'custrecord_lic_billing_contact_email'}) != rec.getValue({fieldId: 'custrecord_lic_tech_contact_email'})){ //log.audit({ title: 'reduce', details: 'Searching: Bill Contact Email ' + rec.getValue({fieldId: 'custrecord_billing_contact_email'})}); var src = search.create({type: 'customer', columns: ['internalid']}); src.filters = []; src.filters.push(search.createFilter({name: 'email', operator: 'is', values: rec.getValue({fieldId: 'custrecord_lic_billing_contact_email'})})); var res = src.run().getRange({start: 0, end: 1}); var idContact; if(res.length > 0){ rec.setValue({fieldId: 'custrecord_lic_billing_contact', value: res[0].id}); //log.audit({ title: 'reduce', details: 'Searching: Bill Email Found'}); idContact = res[0].id; } else{ //log.audit({ title: 'reduce', details: 'Searching: Bill Contact Name'}); if(rec.getValue({fieldId: 'custrecord_lic_billing_contact_name'}) != '' && rec.getValue({fieldId: 'custrecord_lic_billing_contact_name'}) != null){ var src = search.create({type: 'contact', columns: ['internalid']}); src.filters = []; src.filters.push(search.createFilter({name: 'entityid', operator: 'is', values: rec.getValue({fieldId: 'custrecord_lic_billing_contact_name'})})); src.filters.push(search.createFilter({name: 'company', operator: 'anyof', values: idCustomer})); var res = src.run().getRange({start: 0, end: 1}); var idContact; if(res.length > 0){ //log.audit({ title: 'reduce', details: 'Searching: Bill Contact Name Found'}); rec.setValue({fieldId: 'custrecord_lic_billing_contact', value: res[0].id}); idContact = res[0].id; } else{ //log.audit({ title: 'reduce', details: 'Creating: Creating new Bill Contact'}); var recContact = record.create({type: 'contact'}); recContact.setValue({fieldId: 'subsidiary', value : 1}); recContact.setValue({fieldId: 'company', value : idCustomer}); recContact.setValue({fieldId: 'entityid', value : rec.getValue({fieldId: 'custrecord_lic_billing_contact_name'})}); recContact.setValue({fieldId: 'email', value : rec.getValue({fieldId: 'custrecord_lic_billing_contact_email'})}); idContact = recContact.save(); rec.setValue({fieldId: 'custrecord_lic_billing_contact', value: idContact}); } } else{ var src = search.create({type: 'contact', columns: ['internalid']}); src.filters = []; src.filters.push(search.createFilter({name: 'entityid', operator: 'is', values: rec.getValue({fieldId: 'custrecord_lic_company_name'}) + ' Billing Contact'})); src.filters.push(search.createFilter({name: 'company', operator: 'anyof', values: idCustomer})); var res = src.run().getRange({start: 0, end: 1}); var idContact; if(res.length > 0){ //log.audit({ title: 'reduce', details: 'Searching: Bill Contact Name Found'}); rec.setValue({fieldId: 'custrecord_lic_billing_contact', value: res[0].id}); idContact = res[0].id; } else{ //log.audit({ title: 'reduce', details: 'Creating: Creating new Bill Contact'}); var recContact = record.create({type: 'contact'}); recContact.setValue({fieldId: 'subsidiary', value : 1}); recContact.setValue({fieldId: 'company', value : idCustomer}); recContact.setValue({fieldId: 'entityid', value : rec.getValue({fieldId: 'custrecord_lic_company_name'}) + ' Billing Contact'}); recContact.setValue({fieldId: 'email', value : rec.getValue({fieldId: 'custrecord_lic_billing_contact_email'})}); idContact = recContact.save(); rec.setValue({fieldId: 'custrecord_lic_billing_contact', value: idContact}); } } } } var id = rec.save(); rec = record.load({type: 'customrecord_atl_marketplace_license', id: id}); //log.audit({ title: 'reduce', details: 'Searching Partner: ' + rec.getValue({fieldId: 'custrecord_partner_name'})}); //partner if(rec.getValue({fieldId: 'custrecord_lic_partner_name'}) != '' && rec.getValue({fieldId: 'custrecord_lic_partner_name'}) != null){ var src = search.create({type: 'partner', columns: ['internalid']}); src.filters = []; src.filters.push(search.createFilter({name: 'entityid', operator: 'is', values: rec.getValue({fieldId: 'custrecord_lic_partner_name'})})); var res = src.run().getRange({start: 0, end: 1}); var idPartner; if(res.length > 0){ rec.setValue({fieldId: 'custrecord_lic_partner', value: res[0].id}); idPartner = res[0].id; } else{ var recPartner = record.create({type: 'partner'}); recPartner.setValue({fieldId: 'subsidiary', value : 1}); recPartner.setValue({fieldId: 'companyname', value : rec.getValue({fieldId: 'custrecord_lic_partner_name'})}); idPartner = recPartner.save(); rec.setValue({fieldId: 'custrecord_lic_partner', value: idPartner}); } if(rec.getValue({fieldId: 'custrecord_lic_pnr_billing_contact_email'})){ var src = search.create({type: 'contact', columns: ['internalid']}); src.filters = []; src.filters.push(search.createFilter({name: 'email', operator: 'is', values: rec.getValue({fieldId: 'custrecord_lic_pnr_billing_contact_email'})})); var res = src.run().getRange({start: 0, end: 1}); if(res.length > 0){ rec.setValue({fieldId: 'custrecord_lic_pnr_billing_contact', value: res[0].id});//missing idContact = res[0].id; } else{ var src = search.create({type: 'contact', columns: ['internalid']}); if(rec.getValue({fieldId: 'custrecord_lic_pnr_billing_contact_name'}) != '' && rec.getValue({fieldId: 'custrecord_lic_pnr_billing_contact_name'}) != null){ src.filters = []; src.filters.push(search.createFilter({name: 'entityid', operator: 'is', values: rec.getValue({fieldId: 'custrecord_lic_pnr_billing_contact_name'})})); src.filters.push(search.createFilter({name: 'company', operator: 'anyof', values: idPartner})); var res = src.run().getRange({start: 0, end: 1}); var idContact; if(res.length > 0){ rec.setValue({fieldId: 'custrecord_lic_pnr_billing_contact', value: res[0].id});//missing idContact = res[0].id; } else{ var recContact = record.create({type: 'contact'}); recContact.setValue({fieldId: 'subsidiary', value : 1}); recContact.setValue({fieldId: 'company', value : idPartner}); recContact.setValue({fieldId: 'entityid', value : rec.getValue({fieldId: 'custrecord_lic_pnr_billing_contact_name'})}); recContact.setValue({fieldId: 'email', value : rec.getValue({fieldId: 'custrecord_lic_pnr_billing_contact_email'})}); idContact = recContact.save(); rec.setValue({fieldId: 'custrecord_lic_pnr_billing_contact', value: idContact});//missing } } else{ src.filters = []; src.filters.push(search.createFilter({name: 'entityid', operator: 'is', values: rec.getValue({fieldId: 'custrecord_lic_partner_name'}) + ' Contact'})); src.filters.push(search.createFilter({name: 'company', operator: 'anyof', values: idPartner})); var res = src.run().getRange({start: 0, end: 1}); var idContact; if(res.length > 0){ rec.setValue({fieldId: 'custrecord_lic_pnr_billing_contact', value: res[0].id});//missing idContact = res[0].id; } else{ var recContact = record.create({type: 'contact'}); recContact.setValue({fieldId: 'subsidiary', value : 1}); recContact.setValue({fieldId: 'company', value : idPartner}); recContact.setValue({fieldId: 'entityid', value : rec.getValue({fieldId: 'custrecord_lic_partner_name'}) + ' Contact'}); recContact.setValue({fieldId: 'email', value : rec.getValue({fieldId: 'custrecord_lic_pnr_billing_contact_email'})}); idContact = recContact.save(); rec.setValue({fieldId: 'custrecord_lic_pnr_billing_contact', value: idContact});//missing } } } } } var id = rec.save(); } /** * Executes when the summarize entry point is triggered and applies to the result set. * * @param {Summary} summary - Holds statistics regarding the execution of a map/reduce script * @since 2015.1 */ summarize = function (summary) { var errorMsg = []; var inputSummary = summary.inputSummary; var mapSummary = summary.mapSummary; var reduceSummary = summary.reduceSummary; if(summary.inputSummary.error){ var msg = 'Error was: ' + summary.inputSummary.error + '\n'; errorMsg.push(msg); } //log.audit({ title: 'summarize', details: 'offset: ' + nOffset}); var nProcessed = 0; var nErrored = 0; reduceSummary.keys.iterator().each(function (key, executionCount, completionState){ if (completionState === 'COMPLETE'){ nProcessed++; } else if (completionState === 'FAILED'){ nErrored++; } return true; }); reduceSummary.errors.iterator().each(function(key, value){ var msg = 'Process id: ' + key + '. Error was: ' + JSON.parse(value).message + '\n'; errorMsg.push(msg); return true; }); var sMessage = ''; if(errorMsg.length > 0){ sMessage = 'Error on importing Atlassian Transaction. Please visit this article in TSM for details (https://rocketeers.atlassian.net/l/c/FhNAcJwj): ' + JSON.stringify(errorMsg); } else{ sMessage = 'Successful'; } var recLog = record.create({type: 'customrecord_atlassian_summary', isDynamic: true}); recLog.setValue({fieldId: 'custrecord_atlassum_message', value: sMessage}); recLog.setValue({fieldId: 'custrecord_atlassum_numprocessed', value: parseInt(nProcessed) + parseInt(nErrored)}); recLog.setValue({fieldId: 'custrecord_atlassum_error', value: nErrored}); var id = recLog.save(); var scriptTask = task.create({taskType: task.TaskType.MAP_REDUCE}); scriptTask.scriptId = 'customscript_pullatlassian_lichist_mr'; scriptTask.deploymentId = null; var id = scriptTask.submit(); } return { getInputData: getInputData, map: map, reduce: reduce, summarize: summarize }; });
/** * @NApiVersion 2.x * @NScriptType UserEventScript * @NModuleScope SameAccount */ define(['N/file', 'N/sftp', 'N/error'], function(file, sftp, error) { return { beforeLoad: function(){ var portNumber = -1; var connectTimeout = -1; var transferTimeout = -1; //these variables can be taken as parameters of the script instead if (portNumber < sftp.MIN_PORT_NUMBER || portNumber > sftp.MAX_PORT_NUMBER) portNumber = sftp.DEFAULT_PORT_NUMBER; if (connectTimeout < sftp.MIN_CONNECT_TIMEOUT) connectTimeout = sftp.MIN_CONNECT_TIMEOUT; else if (connectTimeout > sftp.MAX_CONNECT_TIMEOUT) connectTimeout = sftp.MAX_CONNECT_TIMEOUT; var connection = sftp.createConnection({ username: 'sftpuser', keyId: 'custkey1', url: '192.168.0.100', port: portNumber, directory: 'inbound', timeout: connectTimeout, hostKey: "AAAAB3NzaC1yc2EAAAADAQABAAABAQDMifKH2vTxdiype8nem7+lS3x7dTQR/A67KdsR/5C2WUcDipBzYhHbnG6Am12Nd2tlM01LnaBZA6/8P4Y9x/sGTxtsdE/MzeGDUBn6HBlQvgIrhX62wgoKGQ+P2lEAO1+Vz8y3/MB1NmD7Fc62cJ9Mu88YA6jwJOIPZeHYNVyIm9OrY6VyzYyvSJhH0x7SXyvGnijJQF4G8C4c8u/UVpF/sE16xKZtly2Rx0aDL2FsDRtpyPmM602/R6ISbsmgab3MzzAEIu+zLDMdIBJn3cDhNt1F7Rar6Tu0u18KCkk8GPxbnxDuG4sCNOnXPYkDXSMUbM/ocRjYGtqdZUMmeTf3" }); // can also be a big file (created for example by async search) var myFileToUpload = file.create({ name: 'originalname.txt', fileType: file.Type.PLAINTEXT, contents: 'I am a test file.' }); if (myFileToUpload.size > connection.MAX_FILE_SIZE) throw error.create({name:"FILE_IS_TOO_BIG", message:"The file you are trying to upload is too big"}); var minTransferTimeout = 10; if (transferTimeout > connection.MAX_TRANSFER_TIMEOUT) transferTimeout = connection.MAX_TRANSFER_TIMEOUT; else if (transferTimeout < minTransferTimeout) transferTimeout = minTransferTimteout; connection.upload({ directory: 'files', filename: 'test.txt', file: myFileToUpload, replaceExisting: true, timeout: transferTimeout }); } }; });
4
[{"tag": "IP_ADDRESS", "value": "192.168.0.100", "start": 927, "end": 940}, {"tag": "KEY", "value": "AAAAB3NzaC1yc2EAAAADAQABAAABAQDMifKH2vTxdiype8nem7+lS3x7dTQR/A67KdsR/5C2WUcDipBzYhHbnG6Am12Nd2tlM01LnaBZA6/8P4Y9x/sGTxtsdE/MzeGDUBn6HBlQvgIrhX62wgoKGQ+P2lEAO1+Vz8y3/MB1NmD7Fc62cJ9Mu88YA6jwJOIPZeHYNVyIm9OrY6VyzYyvSJhH0x7SXyvGnijJQF4G8C4c8u/UVpF/sE16xKZtly2Rx0aDL2FsDRtpyPmM602/R6ISbsmgab3MzzAEIu+zLDMdIBJn3cDhNt1F7Rar6Tu0u18KCkk8GPxbnxDuG4sCNOnXPYkDXSMUbM/ocRjYGtqdZUMmeTf3", "start": 1082, "end": 1454}]
true
2
/** * @NApiVersion 2.x * @NScriptType UserEventScript * @NModuleScope SameAccount */ define(['N/file', 'N/sftp', 'N/error'], function(file, sftp, error) { return { beforeLoad: function(){ var portNumber = -1; var connectTimeout = -1; var transferTimeout = -1; //these variables can be taken as parameters of the script instead if (portNumber < sftp.MIN_PORT_NUMBER || portNumber > sftp.MAX_PORT_NUMBER) portNumber = sftp.DEFAULT_PORT_NUMBER; if (connectTimeout < sftp.MIN_CONNECT_TIMEOUT) connectTimeout = sftp.MIN_CONNECT_TIMEOUT; else if (connectTimeout > sftp.MAX_CONNECT_TIMEOUT) connectTimeout = sftp.MAX_CONNECT_TIMEOUT; var connection = sftp.createConnection({ username: 'sftpuser', keyId: 'custkey1', url: '192.168.0.100', port: portNumber, directory: 'inbound', timeout: connectTimeout, hostKey: "ax5kh6jaqkcd2tiexxs8v6xjo8yv8a6b" }); // can also be a big file (created for example by async search) var myFileToUpload = file.create({ name: 'originalname.txt', fileType: file.Type.PLAINTEXT, contents: 'I am a test file.' }); if (myFileToUpload.size > connection.MAX_FILE_SIZE) throw error.create({name:"FILE_IS_TOO_BIG", message:"The file you are trying to upload is too big"}); var minTransferTimeout = 10; if (transferTimeout > connection.MAX_TRANSFER_TIMEOUT) transferTimeout = connection.MAX_TRANSFER_TIMEOUT; else if (transferTimeout < minTransferTimeout) transferTimeout = minTransferTimteout; connection.upload({ directory: 'files', filename: 'test.txt', file: myFileToUpload, replaceExisting: true, timeout: transferTimeout }); } }; });
true
/** * @NApiVersion 2.x * @NScriptType UserEventScript * @NModuleScope SameAccount */ define(['N/file', 'N/sftp', 'N/error'], function(file, sftp, error) { return { beforeLoad: function(){ var portNumber = -1; var connectTimeout = -1; var transferTimeout = -1; //these variables can be taken as parameters of the script instead if (portNumber < sftp.MIN_PORT_NUMBER || portNumber > sftp.MAX_PORT_NUMBER) portNumber = sftp.DEFAULT_PORT_NUMBER; if (connectTimeout < sftp.MIN_CONNECT_TIMEOUT) connectTimeout = sftp.MIN_CONNECT_TIMEOUT; else if (connectTimeout > sftp.MAX_CONNECT_TIMEOUT) connectTimeout = sftp.MAX_CONNECT_TIMEOUT; var connection = sftp.createConnection({ username: 'sftpuser', keyId: 'custkey1', url: '192.168.0.100', port: portNumber, directory: 'inbound', timeout: connectTimeout, hostKey: "PI:KEY:ax5kh6jaqkcd2tiexxs8v6xjo8yv8a6bEND_PI" }); // can also be a big file (created for example by async search) var myFileToUpload = file.create({ name: 'originalname.txt', fileType: file.Type.PLAINTEXT, contents: 'I am a test file.' }); if (myFileToUpload.size > connection.MAX_FILE_SIZE) throw error.create({name:"FILE_IS_TOO_BIG", message:"The file you are trying to upload is too big"}); var minTransferTimeout = 10; if (transferTimeout > connection.MAX_TRANSFER_TIMEOUT) transferTimeout = connection.MAX_TRANSFER_TIMEOUT; else if (transferTimeout < minTransferTimeout) transferTimeout = minTransferTimteout; connection.upload({ directory: 'files', filename: 'test.txt', file: myFileToUpload, replaceExisting: true, timeout: transferTimeout }); } }; });
/** * @NApiVersion 2.1 */ require(['N/task', 'N/runtime', 'N/email'], (task, runtime, email) => { // Store the script ID of the script to submit // // Update the following statement so it uses the script ID // of the map/reduce script record you want to submit const mapReduceScriptId = 'customscript_test_mapreduce_script'; // Create a map/reduce task // // Update the deploymentId parameter to use the script ID of // the deployment record for your map/reduce script let mrTask = task.create({ taskType: task.TaskType.MAP_REDUCE, scriptId: mapReduceScriptId, deploymentId: 'customdeploy_test_mapreduce_script' }); // Submit the map/reduce task let mrTaskId = mrTask.submit(); // Check the status of the task, and send an email if the // task has a status of FAILED // // Update the authorId value with the internal ID of the user // who is the email sender. Update the recipientEmail value // with the email address of the recipient. let taskStatus = task.checkStatus(mrTaskId); if (taskStatus.status === 'FAILED') { const authorId = -5; const recipientEmail = 'notify@myCompany.com'; email.send({ author: authorId, recipients: recipientEmail, subject: 'Failure executing map/reduce job!', body: 'Map reduce task: ' + mapReduceScriptId + ' has failed.' }); } });
795
[{"tag": "EMAIL", "value": "notify@myCompany.com", "start": 1196, "end": 1216}]
true
1
/** * @NApiVersion 2.1 */ require(['N/task', 'N/runtime', 'N/email'], (task, runtime, email) => { // Store the script ID of the script to submit // // Update the following statement so it uses the script ID // of the map/reduce script record you want to submit const mapReduceScriptId = 'customscript_test_mapreduce_script'; // Create a map/reduce task // // Update the deploymentId parameter to use the script ID of // the deployment record for your map/reduce script let mrTask = task.create({ taskType: task.TaskType.MAP_REDUCE, scriptId: mapReduceScriptId, deploymentId: 'customdeploy_test_mapreduce_script' }); // Submit the map/reduce task let mrTaskId = mrTask.submit(); // Check the status of the task, and send an email if the // task has a status of FAILED // // Update the authorId value with the internal ID of the user // who is the email sender. Update the recipientEmail value // with the email address of the recipient. let taskStatus = task.checkStatus(mrTaskId); if (taskStatus.status === 'FAILED') { const authorId = -5; const recipientEmail = 'ychag@example.com'; email.send({ author: authorId, recipients: recipientEmail, subject: 'Failure executing map/reduce job!', body: 'Map reduce task: ' + mapReduceScriptId + ' has failed.' }); } });
true
/** * @NApiVersion 2.1 */ require(['N/task', 'N/runtime', 'N/email'], (task, runtime, email) => { // Store the script ID of the script to submit // // Update the following statement so it uses the script ID // of the map/reduce script record you want to submit const mapReduceScriptId = 'customscript_test_mapreduce_script'; // Create a map/reduce task // // Update the deploymentId parameter to use the script ID of // the deployment record for your map/reduce script let mrTask = task.create({ taskType: task.TaskType.MAP_REDUCE, scriptId: mapReduceScriptId, deploymentId: 'customdeploy_test_mapreduce_script' }); // Submit the map/reduce task let mrTaskId = mrTask.submit(); // Check the status of the task, and send an email if the // task has a status of FAILED // // Update the authorId value with the internal ID of the user // who is the email sender. Update the recipientEmail value // with the email address of the recipient. let taskStatus = task.checkStatus(mrTaskId); if (taskStatus.status === 'FAILED') { const authorId = -5; const recipientEmail = 'PI:EMAIL:ychag@example.comEND_PI'; email.send({ author: authorId, recipients: recipientEmail, subject: 'Failure executing map/reduce job!', body: 'Map reduce task: ' + mapReduceScriptId + ' has failed.' }); } });
/** * @NApiVersion 2.x * @NScriptType ClientScript * Author: Ankith Ravindran * Created on: Fri May 30 2023 * Modified on: Wed May 31 2023 14:23:11 * SuiteScript Version: 2.0 * Description: Client script for List the contacts that has been registered via the webform to get access to the customer portal. * * Copyright (c) 2023 MailPlus Pty. Ltd. */ define(['N/email', 'N/runtime', 'N/search', 'N/record', 'N/http', 'N/log', 'N/error', 'N/url', 'N/format', 'N/currentRecord' ], function (email, runtime, search, record, http, log, error, url, format, currentRecord) { var zee = 0; var userId = 0; var role = 0; var baseURL = 'https://1048144.app.netsuite.com'; if (runtime.EnvType == "SANDBOX") { baseURL = 'https://1048144-sb3.app.netsuite.com'; } role = runtime.getCurrentUser().role; var userName = runtime.getCurrentUser().name; var userId = runtime.getCurrentUser().id; var currRec = currentRecord.get(); var total_months = 14; var today = new Date(); var today_day_in_month = today.getDate(); var today_day_in_week = today.getDay(); var today_month = today.getMonth() + 1; var today_year = today.getFullYear(); var totalTop50Contacts = 0; var totalReminingContacts = 0; if (today_day_in_month < 10) { today_day_in_month = '0' + today_day_in_month; } if (today_month < 10) { today_month = '0' + (today_month); } var todayString = today_day_in_month + '/' + today_month + '/' + today_year; var current_year_month = today_year + '-' + today_month; var difference_months = total_months - parseInt(today_month); function isWeekday(year, month, day) { var day = new Date(year, month, day).getDay(); return day != 0 && day != 6; } function getWeekdaysInMonth(month, year) { var days = daysInMonth(month, year); var weekdays = 0; for (var i = 0; i < days; i++) { if (isWeekday(year, month, i + 1)) weekdays++; } return weekdays; } function daysInMonth(iMonth, iYear) { return 32 - new Date(iYear, iMonth, 32).getDate(); } function pageLoad() { $('.range_filter_section').addClass('hide'); $('.range_filter_section_top').addClass('hide'); $('.date_filter_section').addClass('hide'); $('.period_dropdown_section').addClass('hide'); $('.loading_section').removeClass('hide'); } function afterSubmit() { $('.loading_section').addClass('hide'); $('.table_section').removeClass('hide'); $('.cust_filter_section').removeClass('hide'); $('.cust_dropdown_section').removeClass('hide'); $('.zee_available_buttons_section').removeClass('hide'); $('.instruction_div').removeClass('hide'); $('.filter_buttons_section').removeClass('hide'); $('.zee_label_section').removeClass('hide'); $('.show_buttons_section').removeClass('hide'); $('.zee_dropdown_section').removeClass('hide'); // $('.tabs_div').removeClass('hide'); $('.paramAccountActivated_label_section').removeClass('hide'); $('.paramAccountActivated_section').removeClass('hide'); $('.customerCountDiv').removeClass('hide'); } var paramUserId = null; function pageInit() { $("#NS_MENU_ID0-item0").css("background-color", "#CFE0CE"); $("#NS_MENU_ID0-item0 a").css("background-color", "#CFE0CE"); $("#body").css("background-color", "#CFE0CE"); $("#tbl_submitter").css("display", "none"); var val1 = currentRecord.get(); paramUserId = val1.getValue({ fieldId: 'custpage_sales_rep_id' }); customerContactListDataSet = []; customerContactListSet = []; customerContactListDataSet2 = []; customerContactListSet2 = []; $("#applyFilter").click(function () { zee = $( '#zee_dropdown option:selected').val(); var paramAccountActivated = $( '#paramAccountActivated_dropdown option:selected').val(); var typeOfCustomer = $( '#typeOfCustomer_dropdown option:selected').val(); var url = baseURL + "/app/site/hosting/scriptlet.nl?script=1745&deploy=1&zee=" + zee + '&activated=' + paramAccountActivated + '&type=' + typeOfCustomer; window.location.href = url; }); $("#clearFilter").click(function () { var url = baseURL + "/app/site/hosting/scriptlet.nl?script=1745&deploy=1" window.location.href = url; }); submitSearch(); var dataTable = $('#mpexusage-customer_contact_list').DataTable(); var dataTable2 = $('#mpexusage-customer_contact_list_remaining').DataTable(); var today = new Date(); var today_year = today.getFullYear(); var today_month = today.getMonth(); var today_day = today.getDate(); /** * Click for Instructions Section Collapse */ $('.collapse').on('shown.bs.collapse', function () { $(".range_filter_section_top").css("padding-top", "500px"); }) $('.collapse').on('hide.bs.collapse', function () { $(".range_filter_section_top").css("padding-top", "0px"); }) $('.createPasswordEmail').click(function () { var contactInternalId = $(this).attr("data-id"); console.log('contactInternalId: ' + contactInternalId); var contactRecord = record.load({ type: record.Type.CONTACT, id: parseInt(contactInternalId), isDynamic: true }); contactRecord.setValue({ fieldId: 'custentity_create_password_email', value: 1 }); contactRecord.save(); var convertLink = 'https://1048144.app.netsuite.com/app/site/hosting/scriptlet.nl?script=1745&deploy=1'; window.location.href = convertLink; }) $('.accountActivated').click(function () { var contactInternalId = $(this).attr("data-id"); console.log('contactInternalId: ' + contactInternalId); var contactRecord = record.load({ type: record.Type.CONTACT, id: parseInt(contactInternalId), isDynamic: true }); contactRecord.setValue({ fieldId: 'custentity_password_setup_completed', value: 1 }); contactRecord.save(); var convertLink = 'https://1048144.app.netsuite.com/app/site/hosting/scriptlet.nl?script=1745&deploy=1'; window.location.href = convertLink; }); $(".displayIncrement").click(function () { console.log('inside display increment'); var val1 = currentRecord.get(); var displayContacts = parseInt(val1.getValue({ fieldId: 'custpage_displaylist', })); var totalContacts = parseInt($('#totalDisplayContacts').val()); // var displayContacts = parseInt($('#displayContacts').val()); zee = $( '#zee_dropdown option:selected').val(); var paramAccountActivated = $( '#paramAccountActivated_dropdown option:selected').val(); var typeOfCustomer = $( '#typeOfCustomer_dropdown option:selected').val(); if (isNullorEmpty(displayContacts)) { } var intialDisplay = (displayContacts + 1); if ((totalContacts - intialDisplay) > 30) { var finalDisplay = intialDisplay + 30; } else { var finalDisplay = totalContacts; } var url = baseURL + "/app/site/hosting/scriptlet.nl?script=1745&deploy=1&zee=" + zee + '&activated=' + paramAccountActivated + '&type=' + typeOfCustomer + '&intial=' + intialDisplay + '&final=' + finalDisplay; window.location.href = url; }); $(".displayDecrement").click(function () { console.log('inside display increment'); var val1 = currentRecord.get(); zee = $( '#zee_dropdown option:selected').val(); var paramAccountActivated = $( '#paramAccountActivated_dropdown option:selected').val(); var typeOfCustomer = $( '#typeOfCustomer_dropdown option:selected').val(); var displayContacts = parseInt(val1.getValue({ fieldId: 'custpage_displaylist', })); var intialDisplay = parseInt(val1.getValue({ fieldId: 'custpage_initialdisplaylist', })); var totalContacts = parseInt($('#totalDisplayContacts').val()); // var displayContacts = parseInt($('#displayContacts').val()); if (!isNullorEmpty(intialDisplay) && intialDisplay != 0) { intialDisplay = intialDisplay - 30; if (intialDisplay == 1) { intialDisplay = 0; } if ((totalContacts - intialDisplay) > 30) { var finalDisplay = intialDisplay + 30; } else { var finalDisplay = totalContacts; } var url = baseURL + "/app/site/hosting/scriptlet.nl?script=1745&deploy=1&zee=" + zee + '&activated=' + paramAccountActivated + '&type=' + typeOfCustomer + '&intial=' + intialDisplay + '&final=' + finalDisplay; window.location.href = url; } else { var url = baseURL + "/app/site/hosting/scriptlet.nl?script=1745&deploy=1&zee=" + zee + '&activated=' + paramAccountActivated + '&type=' + typeOfCustomer; } var url = baseURL + "/app/site/hosting/scriptlet.nl?script=1745&deploy=1&zee=" + zee + '&activated=' + paramAccountActivated + '&type=' + typeOfCustomer + '&intial=' + intialDisplay + '&final=' + finalDisplay; window.location.href = url; }); $(".sendEmail").click(function () { console.log('inside Send Email') var customerInternalId = $(this).attr("data-id"); var salesrepid = $(this).attr("data-sales"); var contactid = $(this).attr("data-contact"); var contactEmail = $(this).attr("data-contactemail"); var contactName = $(this).attr("data-contactname"); var contactPhone = $(this).attr("data-contactphone"); var contactNameArray = contactName.split(' '); var val1 = currentRecord.get(); val1.setValue({ fieldId: 'custpage_customer_id', value: customerInternalId }); val1.setValue({ fieldId: 'custpage_sales_rep_id', value: salesrepid }); val1.setValue({ fieldId: 'custpage_contact_id', value: contactid }); val1.setValue({ fieldId: 'custpage_contact_fname', value: contactNameArray[0] }); val1.setValue({ fieldId: 'custpage_contact_lname', value: contactNameArray[1] }); val1.setValue({ fieldId: 'custpage_contact_email', value: contactEmail }); val1.setValue({ fieldId: 'custpage_contact_phone', value: contactPhone }); $('#submitter').trigger('click'); }); //On click of close icon in the modal $('.close').click(function () { $("#myModal").hide(); }); } //Initialise the DataTable with headers. function submitSearch() { // duringSubmit(); dataTable = $('#mpexusage-customer_contact_list').DataTable({ destroy: true, data: customerContactListDataSet, pageLength: 1000, order: [[4, 'asc'], [3, 'asc']], columns: [{ title: 'USAGE' }, { title: 'ID' }, { title: 'COMPANY NAME' }, { title: 'FRANCHISEE' }, { title: 'CONTACT CREATED' }, { title: 'CONTACT INTERNAL ID' }, { title: 'CONTACT NAME' }, { title: 'CONTACT EMAIL' }, { title: 'CONTACT PHONE' }, { title: 'CREATE PASSWORD EMAIL SENT?' }, { title: 'CREATE PASSWORD EMAIL SENT - COUNT' }, { title: 'ACCOUNT ACTIVATED' }, { title: 'USAGE SOURCE STATUS' }], columnDefs: [{ targets: [2, 3, 9, 10, 11, 12], className: 'bolded' }, { targets: [2], className: 'col-xs-3' }], rowCallback: function (row, data, index) { if (!isNullorEmpty(data[12])) { if (data[12] == 'MANUAL BARCODES') { $('td', row).css('background-color', '#ff9090'); } else if (data[12] == 'DIGITAL LABEL') { $('td', row).css('background-color', '#86c8bc'); } else { $('td', row).css('background-color', '#adcf9f'); } } else if (data[9] == 'Yes' && data[11] == 'Yes') { $('td', row).css('background-color', '#adcf9f'); } else if (data[9] == 'Yes' && data[11] != 'Yes') { if (parseInt(data[10]) == 4) { $('td', row).css('background-color', '#DB6C79'); $('td', row).css('font-weight', 'bold'); $(row).css('outline', 'auto'); } else if (parseInt(data[10]) > 4) { $('td', row).css('background-color', '#B31312'); $('td', row).css('font-weight', 'bold'); $('td', row).css('color', 'white'); $(row).css('outline', 'auto'); } else { $('td', row).css('background-color', '#ffd7a5'); } } } }); dataTable2 = $('#mpexusage-customer_contact_list_remaining').DataTable({ destroy: true, data: customerContactListDataSet2, pageLength: 1000, order: [[4, 'asc'], [3, 'asc']], columns: [{ title: 'USAGE' }, { title: 'ID' }, { title: 'COMPANY NAME' }, { title: 'FRANCHISEE' }, { title: 'CONTACT CREATED' }, { title: 'CONTACT INTERNAL ID' }, { title: 'CONTACT NAME' }, { title: 'CONTACT EMAIL' }, { title: 'CONTACT PHONE' }, { title: 'CREATE PASSWORD EMAIL SENT?' }, { title: 'CREATE PASSWORD EMAIL SENT - COUNT' }, { title: 'ACCOUNT ACTIVATED' }, { title: 'USAGE SOURCE STATUS' }], columnDefs: [{ targets: [2, 3, 9, 10, 11, 12], className: 'bolded' }, { targets: [2], className: 'col-xs-3' }], rowCallback: function (row, data, index) { if (!isNullorEmpty(data[12])) { if (data[12] == 'MANUAL BARCODES') { $('td', row).css('background-color', '#ff9090'); } else if (data[12] == 'DIGITAL LABEL') { $('td', row).css('background-color', '#86c8bc'); } else { $('td', row).css('background-color', '#adcf9f'); } } else if (data[9] == 'Yes' && data[11] == 'Yes') { $('td', row).css('background-color', '#adcf9f'); } else if (data[9] == 'Yes' && data[11] != 'Yes') { if (parseInt(data[10]) == 4) { $('td', row).css('background-color', '#DB6C79'); $('td', row).css('font-weight', 'bold'); $(row).css('outline', 'auto'); } else if (parseInt(data[10]) > 4) { $('td', row).css('background-color', '#B31312'); $('td', row).css('font-weight', 'bold'); $('td', row).css('color', 'white'); $(row).css('outline', 'auto'); } else { $('td', row).css('background-color', '#ffd7a5'); } } } }); loadSearch(); afterSubmit(); } function loadSearch() { zee = $( '#zee_dropdown option:selected').val(); var paramAccountActivated = $( '#paramAccountActivated_dropdown option:selected').val(); var typeOfCustomer = $( '#typeOfCustomer_dropdown option:selected').val(); console.log('paramAccountActivated: ' + paramAccountActivated); if (typeOfCustomer == 1) { if (paramAccountActivated == 1) { //Search Name: Customer Contacts - Mail/Parcel Operator Role var custContactListMailOperatorRoleSearch = search.load({ type: 'customer', id: 'customsearch_cust_contact_mail_parcel__6' }); } else { //Search Name: Customer Contacts - Mail/Parcel Operator Role var custContactListMailOperatorRoleSearch = search.load({ type: 'customer', id: 'customsearch_cust_contact_mail_parcel_ro' }); } if (!isNullorEmpty(zee)) { custContactListMailOperatorRoleSearch.filters.push(search.createFilter({ name: 'partner', join: null, operator: search.Operator.IS, values: zee })); } // if (paramAccountActivated == 1) { // custContactListMailOperatorRoleSearch.filters.push(search.createFilter({ // name: 'custentity_create_password_email', // join: 'contact', // operator: search.Operator.ANYOF, // values: ["1"] // })); // custContactListMailOperatorRoleSearch.filters.push(search.createFilter({ // name: 'custentity_password_setup_completed', // join: 'contact', // operator: search.Operator.ANYOF, // values: ["1"] // })); // } else { // custContactListMailOperatorRoleSearch.filters.push(search.createFilter({ // name: 'custentity_create_password_email', // join: 'contact', // operator: search.Operator.ANYOF, // values: ["1", "@NONE@"] // })); // custContactListMailOperatorRoleSearch.filters.push(search.createFilter({ // name: 'custentity_password_setup_completed', // join: 'contact', // operator: search.Operator.ANYOF, // values: ["@NONE@"] // })); // } custContactListMailOperatorRoleSearch.run().each(function ( custContactListMailOperatorRoleResultSet) { var custInternalID = custContactListMailOperatorRoleResultSet.getValue({ name: 'internalid' }); var custEntityID = custContactListMailOperatorRoleResultSet.getValue({ name: 'entityid' }); var custName = custContactListMailOperatorRoleResultSet.getValue({ name: 'companyname' }); var zeeID = custContactListMailOperatorRoleResultSet.getValue({ name: 'partner' }); var zeeName = custContactListMailOperatorRoleResultSet.getText({ name: 'partner' }); var contactCreated = custContactListMailOperatorRoleResultSet.getValue({ name: 'datecreated', join: "contact", }); var contactInternalId = custContactListMailOperatorRoleResultSet.getValue({ name: "internalid", join: "contact", }); var contactName = custContactListMailOperatorRoleResultSet.getValue({ name: "entityid", join: "contact", }); var contactEmail = custContactListMailOperatorRoleResultSet.getValue({ name: "email", join: "contact", }); var contactPhone = custContactListMailOperatorRoleResultSet.getValue({ name: "phone", join: "contact", }); var contactCreatePasswordEmail = custContactListMailOperatorRoleResultSet.getValue({ name: "custentity_create_password_email", join: "contact", }); if (contactCreatePasswordEmail == 1) { contactCreatePasswordEmail = 'Yes' } else { contactCreatePasswordEmail = '' } var contactPasswordSetupCompleted = custContactListMailOperatorRoleResultSet.getValue({ name: "custentity_password_setup_completed", join: "contact", }); var contactCreatePasswordEmailCount = custContactListMailOperatorRoleResultSet.getValue({ name: "custentity_create_password_email_count", join: "contact", }); if (isNullorEmpty(contactCreatePasswordEmailCount)) { contactCreatePasswordEmailCount = 0; } if (contactPasswordSetupCompleted == 1) { contactPasswordSetupCompleted = 'Yes' } else { contactPasswordSetupCompleted = '' } if (contactCreatePasswordEmailCount == 0 && contactCreatePasswordEmail == 'Yes' && contactPasswordSetupCompleted == 'Yes') { contactCreatePasswordEmailCount = 1; } customerContactListSet.push({ custInternalID: custInternalID, custEntityID: custEntityID, custName: custName, zeeID: zeeID, zeeName: zeeName, contactCreated: contactCreated, contactInternalId: contactInternalId, contactName: contactName, contactEmail: contactEmail, contactPhone: contactPhone, contactCreatePasswordEmail: contactCreatePasswordEmail, contactPasswordSetupCompleted: contactPasswordSetupCompleted, contactCreatePasswordEmailCount: contactCreatePasswordEmailCount }); totalTop50Contacts++; return true; }); console.log(customerContactListSet); } if (typeOfCustomer == 2) { if (paramAccountActivated == 1) { //Search Name: Customer Contacts - Manual Migration - Remaining var custContactListManualMIgrationRemainingSearch = search.load({ type: 'customer', id: 'customsearch_cust_contact_mail_parcel__7' }); } else { //Search Name: Customer Contacts - Manual Migration - Remaining var custContactListManualMIgrationRemainingSearch = search.load({ type: 'customer', id: 'customsearch_cust_contact_mail_parcel__4' }); } if (!isNullorEmpty(zee)) { custContactListManualMIgrationRemainingSearch.filters.push(search.createFilter({ name: 'partner', join: null, operator: search.Operator.IS, values: zee })); } // if (paramAccountActivated == 1) { // custContactListManualMIgrationRemainingSearch.filters.push(search.createFilter({ // name: 'custentity_create_password_email', // join: 'contact', // operator: search.Operator.ANYOF, // values: ["1"] // })); // custContactListManualMIgrationRemainingSearch.filters.push(search.createFilter({ // name: 'custentity_password_setup_completed', // join: 'contact', // operator: search.Operator.ANYOF, // values: ["1"] // })); // } else { // custContactListManualMIgrationRemainingSearch.filters.push(search.createFilter({ // name: 'custentity_create_password_email', // join: 'contact', // operator: search.Operator.ANYOF, // values: ["1", "@NONE@"] // })); // custContactListManualMIgrationRemainingSearch.filters.push(search.createFilter({ // name: 'custentity_password_setup_completed', // join: 'contact', // operator: search.Operator.ANYOF, // values: ["@NONE@"] // })); // } custContactListManualMIgrationRemainingSearch.run().each(function ( custContactListManualMIgrationRemainingSearchRseultSet) { var custInternalID = custContactListManualMIgrationRemainingSearchRseultSet.getValue({ name: 'internalid' }); var custEntityID = custContactListManualMIgrationRemainingSearchRseultSet.getValue({ name: 'entityid' }); var custName = custContactListManualMIgrationRemainingSearchRseultSet.getValue({ name: 'companyname' }); var zeeID = custContactListManualMIgrationRemainingSearchRseultSet.getValue({ name: 'partner' }); var zeeName = custContactListManualMIgrationRemainingSearchRseultSet.getText({ name: 'partner' }); var contactCreated = custContactListManualMIgrationRemainingSearchRseultSet.getValue({ name: 'datecreated', join: "contact", }); var contactInternalId = custContactListManualMIgrationRemainingSearchRseultSet.getValue({ name: "internalid", join: "contact", }); var contactName = custContactListManualMIgrationRemainingSearchRseultSet.getValue({ name: "entityid", join: "contact", }); var contactEmail = custContactListManualMIgrationRemainingSearchRseultSet.getValue({ name: "email", join: "contact", }); var contactPhone = custContactListManualMIgrationRemainingSearchRseultSet.getValue({ name: "phone", join: "contact", }); var contactCreatePasswordEmail = custContactListManualMIgrationRemainingSearchRseultSet.getValue({ name: "custentity_create_password_email", join: "contact", }); if (contactCreatePasswordEmail == 1) { contactCreatePasswordEmail = 'Yes' } else { contactCreatePasswordEmail = '' } var contactPasswordSetupCompleted = custContactListManualMIgrationRemainingSearchRseultSet.getValue({ name: "custentity_password_setup_completed", join: "contact", }); var contactCreatePasswordEmailCount = custContactListManualMIgrationRemainingSearchRseultSet.getValue({ name: "custentity_create_password_email_count", join: "contact", }); if (isNullorEmpty(contactCreatePasswordEmailCount)) { contactCreatePasswordEmailCount = 0; } if (contactPasswordSetupCompleted == 1) { contactPasswordSetupCompleted = 'Yes' } else { contactPasswordSetupCompleted = '' } if (contactCreatePasswordEmailCount == 0 && contactCreatePasswordEmail == 'Yes' && contactPasswordSetupCompleted == 'Yes') { contactCreatePasswordEmailCount = 1; } customerContactListSet2.push({ custInternalID: custInternalID, custEntityID: custEntityID, custName: custName, zeeID: zeeID, zeeName: zeeName, contactCreated: contactCreated, contactInternalId: contactInternalId, contactName: contactName, contactEmail: contactEmail, contactPhone: contactPhone, contactCreatePasswordEmail: contactCreatePasswordEmail, contactPasswordSetupCompleted: contactPasswordSetupCompleted, contactCreatePasswordEmailCount: contactCreatePasswordEmailCount }); totalReminingContacts++; return true; }); console.log(customerContactListSet2) } loadDatatable(customerContactListSet, customerContactListSet2); debt_set = []; } function loadDatatable(customerContactListRows, customerContactListRemainingRows) { customerContactListDataSet = []; csvSet = []; customerContactListDataSet2 = []; csvSet2 = []; var noUsageCustomerCount = 0; var manualUsageCustomerCount = 0; var digitalLabelUsageCustomerCount = 0; var val1 = currentRecord.get(); var paramAccountActivated = $( '#paramAccountActivated_dropdown option:selected').val(); var typeOfCustomer = $( '#typeOfCustomer_dropdown option:selected').val(); var customerCountAccountActivated = 0; if (!isNullorEmpty(customerContactListRows)) { $('#totalDisplayContacts').val(customerContactListRows.length); val1.setValue({ fieldId: 'custpage_totalcontactlist', value: totalDisplayContacts }); customerContactListRows.forEach(function (customerContactListRow, index) { var contactCreatedArray = customerContactListRow.contactCreated.split(' '); var contactCreatedDateSplit = contactCreatedArray[0].split('/'); if (parseInt(contactCreatedDateSplit[1]) < 10) { contactCreatedDateSplit[1] = '0' + contactCreatedDateSplit[1] } if (parseInt(contactCreatedDateSplit[0]) < 10) { contactCreatedDateSplit[0] = '0' + contactCreatedDateSplit[0] } var contactCreatedDateSplitString = contactCreatedDateSplit[2] + '-' + contactCreatedDateSplit[1] + '-' + contactCreatedDateSplit[0]; var date_from = dateISOToNetsuite(contactCreatedDateSplitString); console.log('date_from: ' + date_from) console.log('customerContactListRow.custInternalID: ' + customerContactListRow.custInternalID); var date = new Date(), y = date.getFullYear(), m = date.getMonth(); var firstDay = new Date(y, m, 1); var lastDay = new Date(y, m + 1, 0); firstDay.setHours(0, 0, 0, 0); lastDay.setHours(0, 0, 0, 0); firstDay = GetFormattedDate(firstDay); lastDay = GetFormattedDate(lastDay); var sendSignUpEmail = customerContactListRow.contactEmail; if (customerContactListRow.contactCreatePasswordEmail == 'Yes' && customerContactListRow.contactPasswordSetupCompleted == 'Yes') { //Search Name: All MP Products - Source/Week var mpProductSourcePerWeekSearch = search.load({ type: 'customrecord_customer_product_stock', id: 'customsearch_prod_stock_usage_report___6' }); mpProductSourcePerWeekSearch.filters.push(search.createFilter({ name: 'internalid', join: 'custrecord_cust_prod_stock_customer', operator: search.Operator.IS, values: parseInt(customerContactListRow.custInternalID) })); mpProductSourcePerWeekSearch.filters.push(search.createFilter({ name: 'custrecord_barcode_source', operator: search.Operator.ANYOF, values: ["1", "@NONE@"] })); mpProductSourcePerWeekSearch.filters.push(search.createFilter({ name: 'custrecord_cust_date_stock_used', join: null, operator: search.Operator.ONORAFTER, values: date_from })); customerCountAccountActivated++; console.log('customerCountAccountActivated: ' + customerCountAccountActivated) var resultRange = mpProductSourcePerWeekSearch.run().getRange({ start: 0, end: 1 }); if (resultRange.length == 0) { //Search Name: All MP Products - Source/Week var mpProductSourcePerWeekSearch = search.load({ type: 'customrecord_customer_product_stock', id: 'customsearch_prod_stock_usage_report___6' }); mpProductSourcePerWeekSearch.filters.push(search.createFilter({ name: 'internalid', join: 'custrecord_cust_prod_stock_customer', operator: search.Operator.IS, values: parseInt(customerContactListRow.custInternalID) })); mpProductSourcePerWeekSearch.filters.push(search.createFilter({ name: 'custrecord_barcode_source', operator: search.Operator.NONEOF, values: ["1", "@NONE@"] })); mpProductSourcePerWeekSearch.filters.push(search.createFilter({ name: 'custrecord_cust_date_stock_used', join: null, operator: search.Operator.ONORAFTER, values: date_from })); console.log('mpProductSourcePerWeekSearch.run(): ' + mpProductSourcePerWeekSearch.run()) var resultRange = mpProductSourcePerWeekSearch.run().getRange({ start: 0, end: 1 }); if (resultRange.length == 0) { var currentStatus = 'NO USAGE'; noUsageCustomerCount++; // var linkURL = '<a href="https://1048144.app.netsuite.com/app/site/hosting/scriptlet.nl?script=1712&deploy=1&start_date=' + contactCreatedDateSplitString + '&last_date=' + lastDay + '&zee=' + customerContactListRow.zeeID + '&custid=' + customerContactListRow.custInternalID + '&freq=daily" target="_blank" style="font-weight: bold; cursor: pointer !important;width: 50%;border-radius: 30px;padding: 2.5%;" class="button-shadow"><i class="fa-solid fa-chart-simple" style="font-size: 25px;color: #337ab7"></i></a>' var linkURL = '<a href="https://1048144.app.netsuite.com/app/site/hosting/scriptlet.nl?script=1712&deploy=1&start_date=' + contactCreatedDateSplitString + '&last_date=' + lastDay + '&zee=' + customerContactListRow.zeeID + '&custid=' + customerContactListRow.custInternalID + '&freq=daily" target="_blank" style="font-weight: bold; cursor: pointer !important;width: 50%;border-radius: 30px;padding: 2.5%;" class=""><img src="https://1048144.app.netsuite.com/core/media/media.nl?id=6399648&c=1048144&h=IV0eZcpDJAJvpDCshlu59Ny5BQ1HZwqvu2FIRmE9CZHL8AN3" style="height: 3em; width: 3em;"></a>' } else { var currentStatus = 'DIGITAL LABEL' digitalLabelUsageCustomerCount++; var linkURL = '<a href="https://1048144.app.netsuite.com/app/site/hosting/scriptlet.nl?script=1712&deploy=1&start_date=' + contactCreatedDateSplitString + '&last_date=' + lastDay + '&zee=' + customerContactListRow.zeeID + '&custid=' + customerContactListRow.custInternalID + '&freq=daily" target="_blank" style="font-weight: bold; cursor: pointer !important;width: 50%;border-radius: 30px;padding: 2.5%;" class=""><img src="https://1048144.app.netsuite.com/core/media/media.nl?id=6399648&c=1048144&h=IV0eZcpDJAJvpDCshlu59Ny5BQ1HZwqvu2FIRmE9CZHL8AN3" style="height: 3em; width: 3em;"></a>' } } else { var currentStatus = 'MANUAL BARCODES'; manualUsageCustomerCount++; var linkURL = '<a href="https://1048144.app.netsuite.com/app/site/hosting/scriptlet.nl?script=1712&deploy=1&start_date=' + contactCreatedDateSplitString + '&last_date=' + lastDay + '&zee=' + customerContactListRow.zeeID + '&custid=' + customerContactListRow.custInternalID + '&freq=daily" target="_blank" style="font-weight: bold; cursor: pointer !important;width: 50%;border-radius: 30px;padding: 2.5%;" class=""><img src="https://1048144.app.netsuite.com/core/media/media.nl?id=6399648&c=1048144&h=IV0eZcpDJAJvpDCshlu59Ny5BQ1HZwqvu2FIRmE9CZHL8AN3" style="height: 3em; width: 3em;"></a>' } } else if (customerContactListRow.contactCreatePasswordEmail != 'Yes' && customerContactListRow.contactPasswordSetupCompleted != 'Yes') { var linkURL = '' var currentStatus = '' if (role == 3 || role == 1032) { //Administrator or System Support linkURL = '<input type="button" id="" data-id="' + customerContactListRow.contactInternalId + '" value="CREATE PASSWORD EMAIL SENT" class="form-control btn btn-xs btn-primary createPasswordEmail button-shadow" style="font-weight: bold; cursor: pointer !important;width: fit-content;border-radius: 30px" /> </br><a href="https://1048144.app.netsuite.com/app/site/hosting/scriptlet.nl?script=1712&deploy=1&start_date=' + contactCreatedDateSplitString + '&last_date=' + lastDay + '&zee=' + customerContactListRow.zeeID + '&custid=' + customerContactListRow.custInternalID + '&freq=daily" target="_blank" style="font-weight: bold; cursor: pointer !important;width: 50%;border-radius: 30px;padding: 2.5%;" class=""><img src="https://1048144.app.netsuite.com/core/media/media.nl?id=6399648&c=1048144&h=IV0eZcpDJAJvpDCshlu59Ny5BQ1HZwqvu2FIRmE9CZHL8AN3" style="height: 3em; width: 3em;"></a>'; } else { var linkURL = '<a href="https://1048144.app.netsuite.com/app/site/hosting/scriptlet.nl?script=1712&deploy=1&start_date=' + contactCreatedDateSplitString + '&last_date=' + lastDay + '&zee=' + customerContactListRow.zeeID + '&custid=' + customerContactListRow.custInternalID + '&freq=daily" target="_blank" style="font-weight: bold; cursor: pointer !important;width: 50%;border-radius: 30px;padding: 2.5%;" class=""><img src="https://1048144.app.netsuite.com/core/media/media.nl?id=6399648&c=1048144&h=IV0eZcpDJAJvpDCshlu59Ny5BQ1HZwqvu2FIRmE9CZHL8AN3" style="height: 3em; width: 3em;"></a>' } } else if (customerContactListRow.contactCreatePasswordEmail == 'Yes' && customerContactListRow.contactPasswordSetupCompleted != 'Yes') { var linkURL = '' var currentStatus = ''; if (role == 3 || role == 1032) { //Administrator or System Support linkURL = '<input type="button" id="" data-id="' + customerContactListRow.contactInternalId + '" value="ACTIVATED" class="form-control btn btn-xs btn-success accountActivated button-shadow" style="font-weight: bold; cursor: pointer !important;width: fit-content;border-radius: 30px" /> </br><a href="https://1048144.app.netsuite.com/app/site/hosting/scriptlet.nl?script=1712&deploy=1&start_date=' + contactCreatedDateSplitString + '&last_date=' + lastDay + '&zee=' + customerContactListRow.zeeID + '&custid=' + customerContactListRow.custInternalID + '&freq=daily" target="_blank" style="font-weight: bold; cursor: pointer !important;width: 50%;border-radius: 30px;padding: 2.5%;" class=""><img src="https://1048144.app.netsuite.com/core/media/media.nl?id=6399648&c=1048144&h=IV0eZcpDJAJvpDCshlu59Ny5BQ1HZwqvu2FIRmE9CZHL8AN3" style="height: 3em; width: 3em;"></a>'; var franchiseeSalesRepAssigned = nlapiLookupField('customer', parseInt(customerContactListRow.contactInternalId), 'partner.custentity_sales_rep_assigned'); salesRepId = franchiseeSalesRepAssigned; if (franchiseeSalesRepAssigned == '668712') { salesRepEmail = 'belinda.urbani@mailplus.com.au'; salesRepName = 'Belinda Urbani'; salesRepId = 668712 } else if (franchiseeSalesRepAssigned == '696160') { salesRepEmail = 'kerina.helliwell@mailplus.com.au' salesRepName = 'Kerina Helliwell'; salesRepId = 696160 } else { salesRepEmail = 'lee.russell@mailplus.com.au'; salesRepName = 'Lee Russell'; salesRepId = 668711 } var sendSignUpEmail = '<a data-id="' + customerContactListRow.custInternalID + '" data-sales="' + salesRepId + '" data-contact="' + customerContactListRow.contactInternalId + '" data-contactemail="' + customerContactListRow.contactEmail + '" data-contactName="' + customerContactListRow.contactName + '" data-contactPhone="' + customerContactListRow.contactPhone + '" data-salesrecordid="" style="font-weight: bold; cursor: pointer !important;width: 50%;border-radius: 30px;padding: 2.5%;" class="sendEmail"><button class="button-shadow"><div class="svg-wrapper-1"><div class="svg-wrapper"><svg height="24" width="24" viewBox="0 0 24 24" xmlns="http://www.w3.org/2000/svg"><path d="M0 0h24v24H0z" fill="none"></path><path d="M1.946 9.315c-.522-.174-.527-.455.01-.634l19.087-6.362c.529-.176.832.12.684.638l-5.454 19.086c-.15.529-.455.547-.679.045L12 14l6-8-8 6-8.054-2.685z" fill="currentColor"></path></svg></div></div><span>Resend</span></button></a></br></br>' + customerContactListRow.contactEmail; // linkURL = // '<a href="" class="accountActivated button-shadow" style="cursor: pointer !important;" ><img src="https://1048144.app.netsuite.com/core/media/media.nl?id=6399647&c=1048144&h=RuKYj6ulVT3rxPGWwg3OnnI6wETYrFW3BjGkTbg6dg7ms7wv" style="height: 3em; width: 3em;"></a><input type="button" id="" data-id="' + // customerContactListRow.contactInternalId + // '" value="ACTIVATED" class="form-control btn btn-xs btn-success accountActivated button-shadow" style="font-weight: bold; cursor: pointer !important;width: fit-content;border-radius: 30px" /> </br><a href="https://1048144.app.netsuite.com/app/site/hosting/scriptlet.nl?script=1712&deploy=1&start_date=' + contactCreatedDateSplitString + '&last_date=' + lastDay + '&zee=' + customerContactListRow.zeeID + '&custid=' + customerContactListRow.custInternalID + '&freq=daily" target="_blank" style="font-weight: bold; cursor: pointer !important;width: 50%;border-radius: 30px;padding: 2.5%;" class="button-shadow"><i class="fa-solid fa-chart-simple" style="font-size: 25px;color: #337ab7"></i></a>'; } else { var linkURL = '<a href="https://1048144.app.netsuite.com/app/site/hosting/scriptlet.nl?script=1712&deploy=1&start_date=' + contactCreatedDateSplitString + '&last_date=' + lastDay + '&zee=' + customerContactListRow.zeeID + '&custid=' + customerContactListRow.custInternalID + '&freq=daily" target="_blank" style="font-weight: bold; cursor: pointer !important;width: 50%;border-radius: 30px;padding: 2.5%;" class=""><img src="https://1048144.app.netsuite.com/core/media/media.nl?id=6399648&c=1048144&h=IV0eZcpDJAJvpDCshlu59Ny5BQ1HZwqvu2FIRmE9CZHL8AN3" style="height: 3em; width: 3em;"></a>'; } } var customerIDLink = '<a href="https://1048144.app.netsuite.com/app/common/entity/custjob.nl?id=' + customerContactListRow.custInternalID + '&whence=" target="_blank"><b>' + customerContactListRow.custEntityID + '</b></a>'; if (role == 3 || role == 1032) { var contactIdLink = '<a href="https://1048144.app.netsuite.com/app/common/entity/contact.nl?id=' + customerContactListRow.contactInternalId + '&whence=" target="_blank"><b>Edit Contact</b></a>'; // var franchiseeSalesRepAssigned = nlapiLookupField('customer', parseInt(customerContactListRow.contactInternalId), 'partner.custentity_sales_rep_assigned'); // salesRepId = franchiseeSalesRepAssigned; // if (franchiseeSalesRepAssigned == '668712') { // salesRepEmail = 'belinda.urbani@mailplus.com.au'; // salesRepName = 'Belinda Urbani'; // salesRepId = 668712 // } else if (franchiseeSalesRepAssigned == '696160') { // salesRepEmail = 'kerina.helliwell@mailplus.com.au' // salesRepName = 'Kerina Helliwell'; // salesRepId = 696160 // } else { // salesRepEmail = 'lee.russell@mailplus.com.au'; // salesRepName = 'Lee Russell'; // salesRepId = 668711 // } // var sendSignUpEmail = // '<a data-id="' + // customerContactListRow.custInternalID + // '" data-sales="' + // salesRepId + // '" data-contact="' + // customerContactListRow.contactInternalId + // '" data-contactemail="' + // customerContactListRow.contactEmail + // '" data-contactName="' + // customerContactListRow.contactName + // '" data-contactPhone="' + // customerContactListRow.contactPhone + // '" data-salesrecordid="" style="font-weight: bold; cursor: pointer !important;width: 50%;border-radius: 30px;padding: 2.5%;" class="sendEmail"><button><div class="svg-wrapper-1"><div class="svg-wrapper"><svg height="24" width="24" viewBox="0 0 24 24" xmlns="http://www.w3.org/2000/svg"><path d="M0 0h24v24H0z" fill="none"></path><path d="M1.946 9.315c-.522-.174-.527-.455.01-.634l19.087-6.362c.529-.176.832.12.684.638l-5.454 19.086c-.15.529-.455.547-.679.045L12 14l6-8-8 6-8.054-2.685z" fill="currentColor"></path></svg></div></div><span>Send</span></button></a></br>' + customerContactListRow.contactEmail; } else { var contactIdLink = customerContactListRow.contactInternalId; // var sendSignUpEmail = customerContactListRow.contactEmail; } customerContactListDataSet.push([linkURL, customerIDLink, customerContactListRow.custName, customerContactListRow.zeeName, contactCreatedDateSplitString, contactIdLink, customerContactListRow.contactName, sendSignUpEmail, customerContactListRow.contactPhone, customerContactListRow.contactCreatePasswordEmail, parseInt(customerContactListRow.contactCreatePasswordEmailCount), customerContactListRow.contactPasswordSetupCompleted, currentStatus ]); csvSet.push([customerContactListRow.custInternalID, customerContactListRow.custName, customerContactListRow.zeeName, contactCreatedDateSplitString, customerContactListRow.contactInternalId, customerContactListRow.contactName, customerContactListRow.contactEmail, customerContactListRow.contactPhone, customerContactListRow.contactCreatePasswordEmail, customerContactListRow.contactCreatePasswordEmailCount, customerContactListRow.contactPasswordSetupCompleted ]); }); } var datatable = $('#mpexusage-customer_contact_list').DataTable(); datatable.clear(); datatable.rows.add(customerContactListDataSet); datatable.draw(); saveCsv(csvSet); var customerCountRemainingAccountActivated = 0; if (!isNullorEmpty(customerContactListRemainingRows)) { var customerContactListRemainingLength = customerContactListRemainingRows.length; $('#totalDisplayContacts').val(customerContactListRemainingLength); val1.setValue({ fieldId: 'custpage_totalcontactlist', value: customerContactListRemainingLength }); console.log('customerContactListRemainingLength: ' + customerContactListRemainingLength); var intialDisplay = 0; var displayList = 0; if (customerContactListRemainingLength <= 30) { displayList = customerContactListRemainingLength; val1.setValue({ fieldId: 'custpage_displaylist', value: displayList }); $('#displayContacts').val(intialDisplay + ' - ' + displayList); } else if (customerContactListRemainingLength > 30) { var initialDisplayNumber = val1.getValue({ fieldId: 'custpage_initialdisplaylist', }); var finalDisplayListNumber = val1.getValue({ fieldId: 'custpage_displaylist', }); if (isNullorEmpty(finalDisplayListNumber) || initialDisplayNumber == 0) { displayList = 30; val1.setValue({ fieldId: 'custpage_displaylist', value: displayList }); $('#displayContacts').val('(' + intialDisplay + ' - ' + displayList + ') / ' + customerContactListRemainingLength); } else if (initialDisplayNumber > 30) { intialDisplay = initialDisplayNumber - 1; displayList = finalDisplayListNumber; val1.setValue({ fieldId: 'custpage_displaylist', value: displayList }); $('#displayContacts').val('(' + intialDisplay + ' - ' + displayList + ') / ' + customerContactListRemainingLength); } } console.log('intialDisplay: ' + intialDisplay); console.log('displayList: ' + displayList); for (var x = intialDisplay; x < displayList; x++) { console.log('x: ' + x); var contactCreatedArray = customerContactListRemainingRows[x].contactCreated.split(' '); var contactCreatedDateSplit = contactCreatedArray[0].split('/'); if (parseInt(contactCreatedDateSplit[1]) < 10) { contactCreatedDateSplit[1] = '0' + contactCreatedDateSplit[1] } if (parseInt(contactCreatedDateSplit[0]) < 10) { contactCreatedDateSplit[0] = '0' + contactCreatedDateSplit[0] } var contactCreatedDateSplitString = contactCreatedDateSplit[2] + '-' + contactCreatedDateSplit[1] + '-' + contactCreatedDateSplit[0]; var date_from = dateISOToNetsuite(contactCreatedDateSplitString); // console.log('date_from: ' + date_from) // console.log('customerContactListRow.custInternalID: ' + customerContactListRow.custInternalID); var date = new Date(), y = date.getFullYear(), m = date.getMonth(); var firstDay = new Date(y, m, 1); var lastDay = new Date(y, m + 1, 0); firstDay.setHours(0, 0, 0, 0); lastDay.setHours(0, 0, 0, 0); firstDay = GetFormattedDate(firstDay); lastDay = GetFormattedDate(lastDay); var sendSignUpEmail = customerContactListRemainingRows[x].contactEmail; if (customerContactListRemainingRows[x].contactCreatePasswordEmail == 'Yes' && customerContactListRemainingRows[x].contactPasswordSetupCompleted == 'Yes') { //Search Name: All MP Products - Source/Week var mpProductSourcePerWeekSearch = search.load({ type: 'customrecord_customer_product_stock', id: 'customsearch_prod_stock_usage_report___6' }); mpProductSourcePerWeekSearch.filters.push(search.createFilter({ name: 'internalid', join: 'custrecord_cust_prod_stock_customer', operator: search.Operator.IS, values: parseInt(customerContactListRemainingRows[x].custInternalID) })); mpProductSourcePerWeekSearch.filters.push(search.createFilter({ name: 'custrecord_barcode_source', operator: search.Operator.ANYOF, values: ["1", "@NONE@"] })); mpProductSourcePerWeekSearch.filters.push(search.createFilter({ name: 'custrecord_cust_date_stock_used', join: null, operator: search.Operator.ONORAFTER, values: date_from })); customerCountRemainingAccountActivated++; console.log('customerCountRemainingAccountActivated: ' + customerCountRemainingAccountActivated) var resultRange = mpProductSourcePerWeekSearch.run().getRange({ start: 0, end: 1 }); if (resultRange.length == 0) { //Search Name: All MP Products - Source/Week var mpProductSourcePerWeekSearch = search.load({ type: 'customrecord_customer_product_stock', id: 'customsearch_prod_stock_usage_report___6' }); mpProductSourcePerWeekSearch.filters.push(search.createFilter({ name: 'internalid', join: 'custrecord_cust_prod_stock_customer', operator: search.Operator.IS, values: parseInt(customerContactListRemainingRows[x].custInternalID) })); mpProductSourcePerWeekSearch.filters.push(search.createFilter({ name: 'custrecord_barcode_source', operator: search.Operator.NONEOF, values: ["1", "@NONE@"] })); mpProductSourcePerWeekSearch.filters.push(search.createFilter({ name: 'custrecord_cust_date_stock_used', join: null, operator: search.Operator.ONORAFTER, values: date_from })); console.log('mpProductSourcePerWeekSearch.run(): ' + mpProductSourcePerWeekSearch.run()) var resultRange = mpProductSourcePerWeekSearch.run().getRange({ start: 0, end: 1 }); if (resultRange.length == 0) { var currentStatus = 'NO USAGE'; noUsageCustomerCount++; // var linkURL = '<a href="https://1048144.app.netsuite.com/app/site/hosting/scriptlet.nl?script=1712&deploy=1&start_date=' + contactCreatedDateSplitString + '&last_date=' + lastDay + '&zee=' + customerContactListRow.zeeID + '&custid=' + customerContactListRow.custInternalID + '&freq=daily" target="_blank" style="font-weight: bold; cursor: pointer !important;width: 50%;border-radius: 30px;padding: 2.5%;" class="button-shadow"><i class="fa-solid fa-chart-simple" style="font-size: 25px;color: #337ab7"></i></a>' var linkURL = '<a href="https://1048144.app.netsuite.com/app/site/hosting/scriptlet.nl?script=1712&deploy=1&start_date=' + contactCreatedDateSplitString + '&last_date=' + lastDay + '&zee=' + customerContactListRemainingRows[x].zeeID + '&custid=' + customerContactListRemainingRows[x].custInternalID + '&freq=daily" target="_blank" style="font-weight: bold; cursor: pointer !important;width: 50%;border-radius: 30px;padding: 2.5%;" class=""><img src="https://1048144.app.netsuite.com/core/media/media.nl?id=6399648&c=1048144&h=IV0eZcpDJAJvpDCshlu59Ny5BQ1HZwqvu2FIRmE9CZHL8AN3" style="height: 3em; width: 3em;"></a>' } else { var currentStatus = 'DIGITAL LABEL' digitalLabelUsageCustomerCount++; var linkURL = '<a href="https://1048144.app.netsuite.com/app/site/hosting/scriptlet.nl?script=1712&deploy=1&start_date=' + contactCreatedDateSplitString + '&last_date=' + lastDay + '&zee=' + customerContactListRemainingRows[x].zeeID + '&custid=' + customerContactListRemainingRows[x].custInternalID + '&freq=daily" target="_blank" style="font-weight: bold; cursor: pointer !important;width: 50%;border-radius: 30px;padding: 2.5%;" class=""><img src="https://1048144.app.netsuite.com/core/media/media.nl?id=6399648&c=1048144&h=IV0eZcpDJAJvpDCshlu59Ny5BQ1HZwqvu2FIRmE9CZHL8AN3" style="height: 3em; width: 3em;"></a>' } } else { var currentStatus = 'MANUAL BARCODES'; manualUsageCustomerCount++; var linkURL = '<a href="https://1048144.app.netsuite.com/app/site/hosting/scriptlet.nl?script=1712&deploy=1&start_date=' + contactCreatedDateSplitString + '&last_date=' + lastDay + '&zee=' + customerContactListRemainingRows[x].zeeID + '&custid=' + customerContactListRemainingRows[x].custInternalID + '&freq=daily" target="_blank" style="font-weight: bold; cursor: pointer !important;width: 50%;border-radius: 30px;padding: 2.5%;" class=""><img src="https://1048144.app.netsuite.com/core/media/media.nl?id=6399648&c=1048144&h=IV0eZcpDJAJvpDCshlu59Ny5BQ1HZwqvu2FIRmE9CZHL8AN3" style="height: 3em; width: 3em;"></a>' } } else if (customerContactListRemainingRows[x].contactCreatePasswordEmail != 'Yes' && customerContactListRemainingRows[x].contactPasswordSetupCompleted != 'Yes') { var linkURL = '' var currentStatus = '' if (role == 3 || role == 1032) { //Administrator or System Support linkURL = '<input type="button" id="" data-id="' + customerContactListRemainingRows[x].contactInternalId + '" value="CREATE PASSWORD EMAIL SENT" class="form-control btn btn-xs btn-primary createPasswordEmail button-shadow" style="font-weight: bold; cursor: pointer !important;width: fit-content;border-radius: 30px" /> </br><a href="https://1048144.app.netsuite.com/app/site/hosting/scriptlet.nl?script=1712&deploy=1&start_date=' + contactCreatedDateSplitString + '&last_date=' + lastDay + '&zee=' + customerContactListRemainingRows[x].zeeID + '&custid=' + customerContactListRemainingRows[x].custInternalID + '&freq=daily" target="_blank" style="font-weight: bold; cursor: pointer !important;width: 50%;border-radius: 30px;padding: 2.5%;" class=""><img src="https://1048144.app.netsuite.com/core/media/media.nl?id=6399648&c=1048144&h=IV0eZcpDJAJvpDCshlu59Ny5BQ1HZwqvu2FIRmE9CZHL8AN3" style="height: 3em; width: 3em;"></a>'; } else { var linkURL = '<a href="https://1048144.app.netsuite.com/app/site/hosting/scriptlet.nl?script=1712&deploy=1&start_date=' + contactCreatedDateSplitString + '&last_date=' + lastDay + '&zee=' + customerContactListRow.zeeID + '&custid=' + customerContactListRemainingRows[x].custInternalID + '&freq=daily" target="_blank" style="font-weight: bold; cursor: pointer !important;width: 50%;border-radius: 30px;padding: 2.5%;" class=""><img src="https://1048144.app.netsuite.com/core/media/media.nl?id=6399648&c=1048144&h=IV0eZcpDJAJvpDCshlu59Ny5BQ1HZwqvu2FIRmE9CZHL8AN3" style="height: 3em; width: 3em;"></a>' } } else if (customerContactListRemainingRows[x].contactCreatePasswordEmail == 'Yes' && customerContactListRemainingRows[x].contactPasswordSetupCompleted != 'Yes') { var linkURL = '' var currentStatus = ''; if (role == 3 || role == 1032) { //Administrator or System Support linkURL = '<input type="button" id="" data-id="' + customerContactListRemainingRows[x].contactInternalId + '" value="ACTIVATED" class="form-control btn btn-xs btn-success accountActivated button-shadow" style="font-weight: bold; cursor: pointer !important;width: fit-content;border-radius: 30px" /> </br><a href="https://1048144.app.netsuite.com/app/site/hosting/scriptlet.nl?script=1712&deploy=1&start_date=' + contactCreatedDateSplitString + '&last_date=' + lastDay + '&zee=' + customerContactListRemainingRows[x].zeeID + '&custid=' + customerContactListRemainingRows[x].custInternalID + '&freq=daily" target="_blank" style="font-weight: bold; cursor: pointer !important;width: 50%;border-radius: 30px;padding: 2.5%;" class=""><img src="https://1048144.app.netsuite.com/core/media/media.nl?id=6399648&c=1048144&h=IV0eZcpDJAJvpDCshlu59Ny5BQ1HZwqvu2FIRmE9CZHL8AN3" style="height: 3em; width: 3em;"></a>'; var franchiseeSalesRepAssigned = nlapiLookupField('customer', parseInt(customerContactListRemainingRows[x].contactInternalId), 'partner.custentity_sales_rep_assigned'); salesRepId = franchiseeSalesRepAssigned; if (franchiseeSalesRepAssigned == '668712') { salesRepEmail = 'belinda.urbani@mailplus.com.au'; salesRepName = 'Belinda Urbani'; salesRepId = 668712 } else if (franchiseeSalesRepAssigned == '696160') { salesRepEmail = 'kerina.helliwell@mailplus.com.au' salesRepName = 'Kerina Helliwell'; salesRepId = 696160 } else { salesRepEmail = 'lee.russell@mailplus.com.au'; salesRepName = 'Lee Russell'; salesRepId = 668711 } var sendSignUpEmail = '<a data-id="' + customerContactListRemainingRows[x].custInternalID + '" data-sales="' + salesRepId + '" data-contact="' + customerContactListRemainingRows[x].contactInternalId + '" data-contactemail="' + customerContactListRemainingRows[x].contactEmail + '" data-contactName="' + customerContactListRemainingRows[x].contactName + '" data-contactPhone="' + customerContactListRemainingRows[x].contactPhone + '" data-salesrecordid="" style="font-weight: bold; cursor: pointer !important;width: 50%;border-radius: 30px;padding: 2.5%;" class="sendEmail"><button class="button-shadow"><div class="svg-wrapper-1"><div class="svg-wrapper"><svg height="24" width="24" viewBox="0 0 24 24" xmlns="http://www.w3.org/2000/svg"><path d="M0 0h24v24H0z" fill="none"></path><path d="M1.946 9.315c-.522-.174-.527-.455.01-.634l19.087-6.362c.529-.176.832.12.684.638l-5.454 19.086c-.15.529-.455.547-.679.045L12 14l6-8-8 6-8.054-2.685z" fill="currentColor"></path></svg></div></div><span>Resend</span></button></a></br></br>' + customerContactListRemainingRows[x].contactEmail; // linkURL = // '<a href="" class="accountActivated button-shadow" style="cursor: pointer !important;" ><img src="https://1048144.app.netsuite.com/core/media/media.nl?id=6399647&c=1048144&h=RuKYj6ulVT3rxPGWwg3OnnI6wETYrFW3BjGkTbg6dg7ms7wv" style="height: 3em; width: 3em;"></a><input type="button" id="" data-id="' + // customerContactListRow.contactInternalId + // '" value="ACTIVATED" class="form-control btn btn-xs btn-success accountActivated button-shadow" style="font-weight: bold; cursor: pointer !important;width: fit-content;border-radius: 30px" /> </br><a href="https://1048144.app.netsuite.com/app/site/hosting/scriptlet.nl?script=1712&deploy=1&start_date=' + contactCreatedDateSplitString + '&last_date=' + lastDay + '&zee=' + customerContactListRow.zeeID + '&custid=' + customerContactListRow.custInternalID + '&freq=daily" target="_blank" style="font-weight: bold; cursor: pointer !important;width: 50%;border-radius: 30px;padding: 2.5%;" class="button-shadow"><i class="fa-solid fa-chart-simple" style="font-size: 25px;color: #337ab7"></i></a>'; } else { var linkURL = '<a href="https://1048144.app.netsuite.com/app/site/hosting/scriptlet.nl?script=1712&deploy=1&start_date=' + contactCreatedDateSplitString + '&last_date=' + lastDay + '&zee=' + customerContactListRemainingRows[x].zeeID + '&custid=' + customerContactListRemainingRows[x].custInternalID + '&freq=daily" target="_blank" style="font-weight: bold; cursor: pointer !important;width: 50%;border-radius: 30px;padding: 2.5%;" class=""><img src="https://1048144.app.netsuite.com/core/media/media.nl?id=6399648&c=1048144&h=IV0eZcpDJAJvpDCshlu59Ny5BQ1HZwqvu2FIRmE9CZHL8AN3" style="height: 3em; width: 3em;"></a>'; } } var customerIDLink = '<a href="https://1048144.app.netsuite.com/app/common/entity/custjob.nl?id=' + customerContactListRemainingRows[x].custInternalID + '&whence=" target="_blank"><b>' + customerContactListRemainingRows[x].custEntityID + '</b></a>'; if (role == 3 || role == 1032) { var contactIdLink = '<a href="https://1048144.app.netsuite.com/app/common/entity/contact.nl?id=' + customerContactListRemainingRows[x].contactInternalId + '&whence=" target="_blank"><b>Edit Contact</b></a>'; // var franchiseeSalesRepAssigned = nlapiLookupField('customer', parseInt(customerContactListRow.contactInternalId), 'partner.custentity_sales_rep_assigned'); // salesRepId = franchiseeSalesRepAssigned; // if (franchiseeSalesRepAssigned == '668712') { // salesRepEmail = 'belinda.urbani@mailplus.com.au'; // salesRepName = 'Belinda Urbani'; // salesRepId = 668712 // } else if (franchiseeSalesRepAssigned == '696160') { // salesRepEmail = 'kerina.helliwell@mailplus.com.au' // salesRepName = 'Kerina Helliwell'; // salesRepId = 696160 // } else { // salesRepEmail = 'lee.russell@mailplus.com.au'; // salesRepName = 'Lee Russell'; // salesRepId = 668711 // } // var sendSignUpEmail = // '<a data-id="' + // customerContactListRow.custInternalID + // '" data-sales="' + // salesRepId + // '" data-contact="' + // customerContactListRow.contactInternalId + // '" data-contactemail="' + // customerContactListRow.contactEmail + // '" data-contactName="' + // customerContactListRow.contactName + // '" data-contactPhone="' + // customerContactListRow.contactPhone + // '" data-salesrecordid="" style="font-weight: bold; cursor: pointer !important;width: 50%;border-radius: 30px;padding: 2.5%;" class="sendEmail"><button><div class="svg-wrapper-1"><div class="svg-wrapper"><svg height="24" width="24" viewBox="0 0 24 24" xmlns="http://www.w3.org/2000/svg"><path d="M0 0h24v24H0z" fill="none"></path><path d="M1.946 9.315c-.522-.174-.527-.455.01-.634l19.087-6.362c.529-.176.832.12.684.638l-5.454 19.086c-.15.529-.455.547-.679.045L12 14l6-8-8 6-8.054-2.685z" fill="currentColor"></path></svg></div></div><span>Send</span></button></a></br>' + customerContactListRow.contactEmail; } else { var contactIdLink = customerContactListRemainingRows[x].contactInternalId; // var sendSignUpEmail = customerContactListRow.contactEmail; } customerContactListDataSet2.push([linkURL, customerIDLink, customerContactListRemainingRows[x].custName, customerContactListRemainingRows[x].zeeName, contactCreatedDateSplitString, contactIdLink, customerContactListRemainingRows[x].contactName, sendSignUpEmail, customerContactListRemainingRows[x].contactPhone, customerContactListRemainingRows[x].contactCreatePasswordEmail, parseInt(customerContactListRemainingRows[x].contactCreatePasswordEmailCount), customerContactListRemainingRows[x].contactPasswordSetupCompleted, currentStatus ]); csvSet2.push([customerContactListRemainingRows[x].custInternalID, customerContactListRemainingRows[x].custName, customerContactListRemainingRows[x].zeeName, contactCreatedDateSplitString, customerContactListRemainingRows[x].contactInternalId, customerContactListRemainingRows[x].contactName, customerContactListRemainingRows[x].contactEmail, customerContactListRemainingRows[x].contactPhone, customerContactListRemainingRows[x].contactCreatePasswordEmail, customerContactListRemainingRows[x].contactCreatePasswordEmailCount, customerContactListRemainingRows[x].contactPasswordSetupCompleted ]); } // customerContactListRemainingRows.forEach(function (customerContactListRow, index) { // console.log('index: ' + index); // // if (index < displayList) { // // var contactCreatedArray = customerContactListRow.contactCreated.split(' '); // // var contactCreatedDateSplit = contactCreatedArray[0].split('/'); // // if (parseInt(contactCreatedDateSplit[1]) < 10) { // // contactCreatedDateSplit[1] = '0' + contactCreatedDateSplit[1] // // } // // if (parseInt(contactCreatedDateSplit[0]) < 10) { // // contactCreatedDateSplit[0] = '0' + contactCreatedDateSplit[0] // // } // // var contactCreatedDateSplitString = contactCreatedDateSplit[2] + '-' + contactCreatedDateSplit[1] + '-' + // // contactCreatedDateSplit[0]; // // var date_from = dateISOToNetsuite(contactCreatedDateSplitString); // // // console.log('date_from: ' + date_from) // // // console.log('customerContactListRow.custInternalID: ' + customerContactListRow.custInternalID); // // var date = new Date(), y = date.getFullYear(), m = date.getMonth(); // // var firstDay = new Date(y, m, 1); // // var lastDay = new Date(y, m + 1, 0); // // firstDay.setHours(0, 0, 0, 0); // // lastDay.setHours(0, 0, 0, 0); // // firstDay = GetFormattedDate(firstDay); // // lastDay = GetFormattedDate(lastDay); // // var sendSignUpEmail = customerContactListRow.contactEmail; // // if (customerContactListRow.contactCreatePasswordEmail == 'Yes' && customerContactListRow.contactPasswordSetupCompleted == 'Yes') { // // //Search Name: All MP Products - Source/Week // // var mpProductSourcePerWeekSearch = search.load({ // // type: 'customrecord_customer_product_stock', // // id: 'customsearch_prod_stock_usage_report___6' // // }); // // mpProductSourcePerWeekSearch.filters.push(search.createFilter({ // // name: 'internalid', // // join: 'custrecord_cust_prod_stock_customer', // // operator: search.Operator.IS, // // values: parseInt(customerContactListRow.custInternalID) // // })); // // mpProductSourcePerWeekSearch.filters.push(search.createFilter({ // // name: 'custrecord_barcode_source', // // operator: search.Operator.ANYOF, // // values: ["1", "@NONE@"] // // })); // // mpProductSourcePerWeekSearch.filters.push(search.createFilter({ // // name: 'custrecord_cust_date_stock_used', // // join: null, // // operator: search.Operator.ONORAFTER, // // values: date_from // // })); // // customerCountRemainingAccountActivated++; // // console.log('customerCountRemainingAccountActivated: ' + customerCountRemainingAccountActivated) // // var resultRange = mpProductSourcePerWeekSearch.run().getRange({ // // start: 0, // // end: 1 // // }); // // if (resultRange.length == 0) { // // //Search Name: All MP Products - Source/Week // // var mpProductSourcePerWeekSearch = search.load({ // // type: 'customrecord_customer_product_stock', // // id: 'customsearch_prod_stock_usage_report___6' // // }); // // mpProductSourcePerWeekSearch.filters.push(search.createFilter({ // // name: 'internalid', // // join: 'custrecord_cust_prod_stock_customer', // // operator: search.Operator.IS, // // values: parseInt(customerContactListRow.custInternalID) // // })); // // mpProductSourcePerWeekSearch.filters.push(search.createFilter({ // // name: 'custrecord_barcode_source', // // operator: search.Operator.NONEOF, // // values: ["1", "@NONE@"] // // })); // // mpProductSourcePerWeekSearch.filters.push(search.createFilter({ // // name: 'custrecord_cust_date_stock_used', // // join: null, // // operator: search.Operator.ONORAFTER, // // values: date_from // // })); // // console.log('mpProductSourcePerWeekSearch.run(): ' + mpProductSourcePerWeekSearch.run()) // // var resultRange = mpProductSourcePerWeekSearch.run().getRange({ // // start: 0, // // end: 1 // // }); // // if (resultRange.length == 0) { // // var currentStatus = 'NO USAGE' // // // var linkURL = '<a href="https://1048144.app.netsuite.com/app/site/hosting/scriptlet.nl?script=1712&deploy=1&start_date=' + contactCreatedDateSplitString + '&last_date=' + lastDay + '&zee=' + customerContactListRow.zeeID + '&custid=' + customerContactListRow.custInternalID + '&freq=daily" target="_blank" style="font-weight: bold; cursor: pointer !important;width: 50%;border-radius: 30px;padding: 2.5%;" class="button-shadow"><i class="fa-solid fa-chart-simple" style="font-size: 25px;color: #337ab7"></i></a>' // // var linkURL = '<a href="https://1048144.app.netsuite.com/app/site/hosting/scriptlet.nl?script=1712&deploy=1&start_date=' + contactCreatedDateSplitString + '&last_date=' + lastDay + '&zee=' + customerContactListRow.zeeID + '&custid=' + customerContactListRow.custInternalID + '&freq=daily" target="_blank" style="font-weight: bold; cursor: pointer !important;width: 50%;border-radius: 30px;padding: 2.5%;" class=""><img src="https://1048144.app.netsuite.com/core/media/media.nl?id=6399648&c=1048144&h=IV0eZcpDJAJvpDCshlu59Ny5BQ1HZwqvu2FIRmE9CZHL8AN3" style="height: 3em; width: 3em;"></a>' // // } else { // // var currentStatus = 'DIGITAL LABEL' // // var linkURL = '<a href="https://1048144.app.netsuite.com/app/site/hosting/scriptlet.nl?script=1712&deploy=1&start_date=' + contactCreatedDateSplitString + '&last_date=' + lastDay + '&zee=' + customerContactListRow.zeeID + '&custid=' + customerContactListRow.custInternalID + '&freq=daily" target="_blank" style="font-weight: bold; cursor: pointer !important;width: 50%;border-radius: 30px;padding: 2.5%;" class=""><img src="https://1048144.app.netsuite.com/core/media/media.nl?id=6399648&c=1048144&h=IV0eZcpDJAJvpDCshlu59Ny5BQ1HZwqvu2FIRmE9CZHL8AN3" style="height: 3em; width: 3em;"></a>' // // } // // } else { // // var currentStatus = 'MANUAL BARCODES' // // var linkURL = '<a href="https://1048144.app.netsuite.com/app/site/hosting/scriptlet.nl?script=1712&deploy=1&start_date=' + contactCreatedDateSplitString + '&last_date=' + lastDay + '&zee=' + customerContactListRow.zeeID + '&custid=' + customerContactListRow.custInternalID + '&freq=daily" target="_blank" style="font-weight: bold; cursor: pointer !important;width: 50%;border-radius: 30px;padding: 2.5%;" class=""><img src="https://1048144.app.netsuite.com/core/media/media.nl?id=6399648&c=1048144&h=IV0eZcpDJAJvpDCshlu59Ny5BQ1HZwqvu2FIRmE9CZHL8AN3" style="height: 3em; width: 3em;"></a>' // // } // // } else if (customerContactListRow.contactCreatePasswordEmail != 'Yes' && customerContactListRow.contactPasswordSetupCompleted != 'Yes') { // // var linkURL = '' // // var currentStatus = '' // // if (role == 3 || role == 1032) { //Administrator or System Support // // linkURL = // // '<input type="button" id="" data-id="' + // // customerContactListRow.contactInternalId + // // '" value="CREATE PASSWORD EMAIL SENT" class="form-control btn btn-xs btn-primary createPasswordEmail button-shadow" style="font-weight: bold; cursor: pointer !important;width: fit-content;border-radius: 30px" /> </br><a href="https://1048144.app.netsuite.com/app/site/hosting/scriptlet.nl?script=1712&deploy=1&start_date=' + contactCreatedDateSplitString + '&last_date=' + lastDay + '&zee=' + customerContactListRow.zeeID + '&custid=' + customerContactListRow.custInternalID + '&freq=daily" target="_blank" style="font-weight: bold; cursor: pointer !important;width: 50%;border-radius: 30px;padding: 2.5%;" class=""><img src="https://1048144.app.netsuite.com/core/media/media.nl?id=6399648&c=1048144&h=IV0eZcpDJAJvpDCshlu59Ny5BQ1HZwqvu2FIRmE9CZHL8AN3" style="height: 3em; width: 3em;"></a>'; // // } else { // // var linkURL = '<a href="https://1048144.app.netsuite.com/app/site/hosting/scriptlet.nl?script=1712&deploy=1&start_date=' + contactCreatedDateSplitString + '&last_date=' + lastDay + '&zee=' + customerContactListRow.zeeID + '&custid=' + customerContactListRow.custInternalID + '&freq=daily" target="_blank" style="font-weight: bold; cursor: pointer !important;width: 50%;border-radius: 30px;padding: 2.5%;" class=""><img src="https://1048144.app.netsuite.com/core/media/media.nl?id=6399648&c=1048144&h=IV0eZcpDJAJvpDCshlu59Ny5BQ1HZwqvu2FIRmE9CZHL8AN3" style="height: 3em; width: 3em;"></a>' // // } // // } else if (customerContactListRow.contactCreatePasswordEmail == 'Yes' && customerContactListRow.contactPasswordSetupCompleted != 'Yes') { // // var linkURL = '' // // var currentStatus = ''; // // if (role == 3 || role == 1032) { //Administrator or System Support // // linkURL = // // '<input type="button" id="" data-id="' + // // customerContactListRow.contactInternalId + // // '" value="ACTIVATED" class="form-control btn btn-xs btn-success accountActivated button-shadow" style="font-weight: bold; cursor: pointer !important;width: fit-content;border-radius: 30px" /> </br><a href="https://1048144.app.netsuite.com/app/site/hosting/scriptlet.nl?script=1712&deploy=1&start_date=' + contactCreatedDateSplitString + '&last_date=' + lastDay + '&zee=' + customerContactListRow.zeeID + '&custid=' + customerContactListRow.custInternalID + '&freq=daily" target="_blank" style="font-weight: bold; cursor: pointer !important;width: 50%;border-radius: 30px;padding: 2.5%;" class=""><img src="https://1048144.app.netsuite.com/core/media/media.nl?id=6399648&c=1048144&h=IV0eZcpDJAJvpDCshlu59Ny5BQ1HZwqvu2FIRmE9CZHL8AN3" style="height: 3em; width: 3em;"></a>'; // // var franchiseeSalesRepAssigned = nlapiLookupField('customer', parseInt(customerContactListRow.contactInternalId), 'partner.custentity_sales_rep_assigned'); // // salesRepId = franchiseeSalesRepAssigned; // // if (franchiseeSalesRepAssigned == '668712') { // // salesRepEmail = 'belinda.urbani@mailplus.com.au'; // // salesRepName = 'Belinda Urbani'; // // salesRepId = 668712 // // } else if (franchiseeSalesRepAssigned == '696160') { // // salesRepEmail = 'kerina.helliwell@mailplus.com.au' // // salesRepName = 'Kerina Helliwell'; // // salesRepId = 696160 // // } else { // // salesRepEmail = 'lee.russell@mailplus.com.au'; // // salesRepName = 'Lee Russell'; // // salesRepId = 668711 // // } // // var sendSignUpEmail = // // '<a data-id="' + // // customerContactListRow.custInternalID + // // '" data-sales="' + // // salesRepId + // // '" data-contact="' + // // customerContactListRow.contactInternalId + // // '" data-contactemail="' + // // customerContactListRow.contactEmail + // // '" data-contactName="' + // // customerContactListRow.contactName + // // '" data-contactPhone="' + // // customerContactListRow.contactPhone + // // '" data-salesrecordid="" style="font-weight: bold; cursor: pointer !important;width: 50%;border-radius: 30px;padding: 2.5%;" class="sendEmail"><button class="button-shadow"><div class="svg-wrapper-1"><div class="svg-wrapper"><svg height="24" width="24" viewBox="0 0 24 24" xmlns="http://www.w3.org/2000/svg"><path d="M0 0h24v24H0z" fill="none"></path><path d="M1.946 9.315c-.522-.174-.527-.455.01-.634l19.087-6.362c.529-.176.832.12.684.638l-5.454 19.086c-.15.529-.455.547-.679.045L12 14l6-8-8 6-8.054-2.685z" fill="currentColor"></path></svg></div></div><span>Resend</span></button></a></br></br>' + customerContactListRow.contactEmail; // // // linkURL = // // // '<a href="" class="accountActivated button-shadow" style="cursor: pointer !important;" ><img src="https://1048144.app.netsuite.com/core/media/media.nl?id=6399647&c=1048144&h=RuKYj6ulVT3rxPGWwg3OnnI6wETYrFW3BjGkTbg6dg7ms7wv" style="height: 3em; width: 3em;"></a><input type="button" id="" data-id="' + // // // customerContactListRow.contactInternalId + // // // '" value="ACTIVATED" class="form-control btn btn-xs btn-success accountActivated button-shadow" style="font-weight: bold; cursor: pointer !important;width: fit-content;border-radius: 30px" /> </br><a href="https://1048144.app.netsuite.com/app/site/hosting/scriptlet.nl?script=1712&deploy=1&start_date=' + contactCreatedDateSplitString + '&last_date=' + lastDay + '&zee=' + customerContactListRow.zeeID + '&custid=' + customerContactListRow.custInternalID + '&freq=daily" target="_blank" style="font-weight: bold; cursor: pointer !important;width: 50%;border-radius: 30px;padding: 2.5%;" class="button-shadow"><i class="fa-solid fa-chart-simple" style="font-size: 25px;color: #337ab7"></i></a>'; // // } else { // // var linkURL = '<a href="https://1048144.app.netsuite.com/app/site/hosting/scriptlet.nl?script=1712&deploy=1&start_date=' + contactCreatedDateSplitString + '&last_date=' + lastDay + '&zee=' + customerContactListRow.zeeID + '&custid=' + customerContactListRow.custInternalID + '&freq=daily" target="_blank" style="font-weight: bold; cursor: pointer !important;width: 50%;border-radius: 30px;padding: 2.5%;" class=""><img src="https://1048144.app.netsuite.com/core/media/media.nl?id=6399648&c=1048144&h=IV0eZcpDJAJvpDCshlu59Ny5BQ1HZwqvu2FIRmE9CZHL8AN3" style="height: 3em; width: 3em;"></a>'; // // } // // } // // var customerIDLink = // // '<a href="https://1048144.app.netsuite.com/app/common/entity/custjob.nl?id=' + // // customerContactListRow.custInternalID + '&whence=" target="_blank"><b>' + // // customerContactListRow.custEntityID + '</b></a>'; // // if (role == 3 || role == 1032) { // // var contactIdLink = // // '<a href="https://1048144.app.netsuite.com/app/common/entity/contact.nl?id=' + // // customerContactListRow.contactInternalId + '&whence=" target="_blank"><b>Edit Contact</b></a>'; // // // var franchiseeSalesRepAssigned = nlapiLookupField('customer', parseInt(customerContactListRow.contactInternalId), 'partner.custentity_sales_rep_assigned'); // // // salesRepId = franchiseeSalesRepAssigned; // // // if (franchiseeSalesRepAssigned == '668712') { // // // salesRepEmail = 'belinda.urbani@mailplus.com.au'; // // // salesRepName = 'Belinda Urbani'; // // // salesRepId = 668712 // // // } else if (franchiseeSalesRepAssigned == '696160') { // // // salesRepEmail = 'kerina.helliwell@mailplus.com.au' // // // salesRepName = 'Kerina Helliwell'; // // // salesRepId = 696160 // // // } else { // // // salesRepEmail = 'lee.russell@mailplus.com.au'; // // // salesRepName = 'Lee Russell'; // // // salesRepId = 668711 // // // } // // // var sendSignUpEmail = // // // '<a data-id="' + // // // customerContactListRow.custInternalID + // // // '" data-sales="' + // // // salesRepId + // // // '" data-contact="' + // // // customerContactListRow.contactInternalId + // // // '" data-contactemail="' + // // // customerContactListRow.contactEmail + // // // '" data-contactName="' + // // // customerContactListRow.contactName + // // // '" data-contactPhone="' + // // // customerContactListRow.contactPhone + // // // '" data-salesrecordid="" style="font-weight: bold; cursor: pointer !important;width: 50%;border-radius: 30px;padding: 2.5%;" class="sendEmail"><button><div class="svg-wrapper-1"><div class="svg-wrapper"><svg height="24" width="24" viewBox="0 0 24 24" xmlns="http://www.w3.org/2000/svg"><path d="M0 0h24v24H0z" fill="none"></path><path d="M1.946 9.315c-.522-.174-.527-.455.01-.634l19.087-6.362c.529-.176.832.12.684.638l-5.454 19.086c-.15.529-.455.547-.679.045L12 14l6-8-8 6-8.054-2.685z" fill="currentColor"></path></svg></div></div><span>Send</span></button></a></br>' + customerContactListRow.contactEmail; // // } else { // // var contactIdLink = customerContactListRow.contactInternalId; // // // var sendSignUpEmail = customerContactListRow.contactEmail; // // } // // customerContactListDataSet2.push([linkURL, // // customerIDLink, // // customerContactListRow.custName, customerContactListRow.zeeName, contactCreatedDateSplitString, contactIdLink, customerContactListRow.contactName, sendSignUpEmail, customerContactListRow.contactPhone, customerContactListRow.contactCreatePasswordEmail, parseInt(customerContactListRow.contactCreatePasswordEmailCount), customerContactListRow.contactPasswordSetupCompleted, currentStatus // // ]); // // csvSet2.push([customerContactListRow.custInternalID, // // customerContactListRow.custName, customerContactListRow.zeeName, contactCreatedDateSplitString, customerContactListRow.contactInternalId, customerContactListRow.contactName, customerContactListRow.contactEmail, customerContactListRow.contactPhone, customerContactListRow.contactCreatePasswordEmail, customerContactListRow.contactCreatePasswordEmailCount, customerContactListRow.contactPasswordSetupCompleted // // ]); // // } // }); } var datatable2 = $('#mpexusage-customer_contact_list_remaining').DataTable(); datatable2.clear(); datatable2.rows.add(customerContactListDataSet2); datatable2.draw(); saveCsv(csvSet2); $('#noUsageCount').val(noUsageCustomerCount); $('#manualUsageCount').val(manualUsageCustomerCount); $('#digitalUsageCount').val(digitalLabelUsageCustomerCount); return true; } /** * Load the string stored in the hidden field 'custpage_table_csv'. * Converts it to a CSV file. * Creates a hidden link to download the file and triggers the click of the link. */ function downloadCsv() { var today = new Date(); today = formatDate(today); var val1 = currentRecord.get(); var csv = val1.getValue({ fieldId: 'custpage_table_csv', }); today = replaceAll(today); var a = document.createElement("a"); document.body.appendChild(a); a.style = "display: none"; var content_type = 'text/csv'; var csvFile = new Blob([csv], { type: content_type }); var url = window.URL.createObjectURL(csvFile); var filename = 'Customer Cancellation List_' + today + '.csv'; a.href = url; a.download = filename; a.click(); window.URL.revokeObjectURL(url); } function getDateStoreNS() { var date = new Date(); if (date.getHours() > 6) { date.setDate(date.getDate() + 1); } format.format({ value: date, type: format.Type.DATE, timezone: format.Timezone.AUSTRALIA_SYDNEY }) return date; } function saveRecord() { return true; } /** * Create the CSV and store it in the hidden field 'custpage_table_csv' as a string. * @param {Array} ordersDataSet The `billsDataSet` created in `loadDatatable()`. */ function saveCsv(ordersDataSet) { var sep = "sep=;"; var headers = ["Customer Internal ID", "Customer Entity ID", "Customer Name", "Franchisee", "Status", "Cancellation Requested Date", "Cancellation Date", "Cancellation Progress" ] headers = headers.join(';'); // .join(', ') var csv = sep + "\n" + headers + "\n"; ordersDataSet.forEach(function (row) { row = row.join(';'); csv += row; csv += "\n"; }); var val1 = currentRecord.get(); val1.setValue({ fieldId: 'custpage_table_csv', value: csv }); return true; } function formatDate(testDate) { console.log('testDate: ' + testDate); var responseDate = format.format({ value: testDate, type: format.Type.DATE }); console.log('responseDate: ' + responseDate); return responseDate; } function replaceAll(string) { return string.split("/").join("-"); } /** * Used to pass the values of `date_from` and `date_to` between the scripts and to Netsuite for the records and the search. * @param {String} date_iso "2020-06-01" * @returns {String} date_netsuite "1/6/2020" */ function dateISOToNetsuite(date_iso) { var date_netsuite = ''; if (!isNullorEmpty(date_iso)) { var date_utc = new Date(date_iso); // var date_netsuite = nlapiDateToString(date_utc); var date_netsuite = format.format({ value: date_utc, type: format.Type.DATE }); } return date_netsuite; } function GetFormattedDate(todayDate) { var month = pad(todayDate.getMonth() + 1); var day = pad(todayDate.getDate()); var year = (todayDate.getFullYear()); return year + "-" + month + "-" + day; } function pad(s) { return (s < 10) ? '0' + s : s; } /** * [getDate description] - Get the current date * @return {[String]} [description] - return the string date */ function getDate() { var date = new Date(); date = format.format({ value: date, type: format.Type.DATE, timezone: format.Timezone.AUSTRALIA_SYDNEY }); return date; } function isNullorEmpty(val) { if (val == '' || val == null) { return true; } else { return false; } } return { pageInit: pageInit, saveRecord: saveRecord, downloadCsv: downloadCsv } });
701
[{"tag": "EMAIL", "value": "belinda.urbani@mailplus.com.au", "start": 46697, "end": 46727}, {"tag": "EMAIL", "value": "kerina.helliwell@mailplus.com.au", "start": 46977, "end": 47009}, {"tag": "EMAIL", "value": "lee.russell@mailplus.com.au", "start": 47216, "end": 47243}, {"tag": "EMAIL", "value": "belinda.urbani@mailplus.com.au", "start": 51740, "end": 51770}, {"tag": "EMAIL", "value": "kerina.helliwell@mailplus.com.au", "start": 52016, "end": 52048}, {"tag": "EMAIL", "value": "lee.russell@mailplus.com.au", "start": 52251, "end": 52278}, {"tag": "EMAIL", "value": "belinda.urbani@mailplus.com.au", "start": 70195, "end": 70225}, {"tag": "EMAIL", "value": "kerina.helliwell@mailplus.com.au", "start": 70475, "end": 70507}, {"tag": "EMAIL", "value": "lee.russell@mailplus.com.au", "start": 70714, "end": 70741}, {"tag": "EMAIL", "value": "belinda.urbani@mailplus.com.au", "start": 75381, "end": 75411}, {"tag": "EMAIL", "value": "kerina.helliwell@mailplus.com.au", "start": 75657, "end": 75689}, {"tag": "EMAIL", "value": "lee.russell@mailplus.com.au", "start": 75892, "end": 75919}, {"tag": "EMAIL", "value": "belinda.urbani@mailplus.com.au", "start": 92025, "end": 92055}, {"tag": "EMAIL", "value": "kerina.helliwell@mailplus.com.au", "start": 92345, "end": 92377}, {"tag": "EMAIL", "value": "lee.russell@mailplus.com.au", "start": 92624, "end": 92651}, {"tag": "EMAIL", "value": "belinda.urbani@mailplus.com.au", "start": 97518, "end": 97548}, {"tag": "EMAIL", "value": "kerina.helliwell@mailplus.com.au", "start": 97834, "end": 97866}, {"tag": "EMAIL", "value": "lee.russell@mailplus.com.au", "start": 98109, "end": 98136}]
true
18
/** * @NApiVersion 2.x * @NScriptType ClientScript * Author: Ankith Ravindran * Created on: Fri May 30 2023 * Modified on: Wed May 31 2023 14:23:11 * SuiteScript Version: 2.0 * Description: Client script for List the contacts that has been registered via the webform to get access to the customer portal. * * Copyright (c) 2023 MailPlus Pty. Ltd. */ define(['N/email', 'N/runtime', 'N/search', 'N/record', 'N/http', 'N/log', 'N/error', 'N/url', 'N/format', 'N/currentRecord' ], function (email, runtime, search, record, http, log, error, url, format, currentRecord) { var zee = 0; var userId = 0; var role = 0; var baseURL = 'https://1048144.app.netsuite.com'; if (runtime.EnvType == "SANDBOX") { baseURL = 'https://1048144-sb3.app.netsuite.com'; } role = runtime.getCurrentUser().role; var userName = runtime.getCurrentUser().name; var userId = runtime.getCurrentUser().id; var currRec = currentRecord.get(); var total_months = 14; var today = new Date(); var today_day_in_month = today.getDate(); var today_day_in_week = today.getDay(); var today_month = today.getMonth() + 1; var today_year = today.getFullYear(); var totalTop50Contacts = 0; var totalReminingContacts = 0; if (today_day_in_month < 10) { today_day_in_month = '0' + today_day_in_month; } if (today_month < 10) { today_month = '0' + (today_month); } var todayString = today_day_in_month + '/' + today_month + '/' + today_year; var current_year_month = today_year + '-' + today_month; var difference_months = total_months - parseInt(today_month); function isWeekday(year, month, day) { var day = new Date(year, month, day).getDay(); return day != 0 && day != 6; } function getWeekdaysInMonth(month, year) { var days = daysInMonth(month, year); var weekdays = 0; for (var i = 0; i < days; i++) { if (isWeekday(year, month, i + 1)) weekdays++; } return weekdays; } function daysInMonth(iMonth, iYear) { return 32 - new Date(iYear, iMonth, 32).getDate(); } function pageLoad() { $('.range_filter_section').addClass('hide'); $('.range_filter_section_top').addClass('hide'); $('.date_filter_section').addClass('hide'); $('.period_dropdown_section').addClass('hide'); $('.loading_section').removeClass('hide'); } function afterSubmit() { $('.loading_section').addClass('hide'); $('.table_section').removeClass('hide'); $('.cust_filter_section').removeClass('hide'); $('.cust_dropdown_section').removeClass('hide'); $('.zee_available_buttons_section').removeClass('hide'); $('.instruction_div').removeClass('hide'); $('.filter_buttons_section').removeClass('hide'); $('.zee_label_section').removeClass('hide'); $('.show_buttons_section').removeClass('hide'); $('.zee_dropdown_section').removeClass('hide'); // $('.tabs_div').removeClass('hide'); $('.paramAccountActivated_label_section').removeClass('hide'); $('.paramAccountActivated_section').removeClass('hide'); $('.customerCountDiv').removeClass('hide'); } var paramUserId = null; function pageInit() { $("#NS_MENU_ID0-item0").css("background-color", "#CFE0CE"); $("#NS_MENU_ID0-item0 a").css("background-color", "#CFE0CE"); $("#body").css("background-color", "#CFE0CE"); $("#tbl_submitter").css("display", "none"); var val1 = currentRecord.get(); paramUserId = val1.getValue({ fieldId: 'custpage_sales_rep_id' }); customerContactListDataSet = []; customerContactListSet = []; customerContactListDataSet2 = []; customerContactListSet2 = []; $("#applyFilter").click(function () { zee = $( '#zee_dropdown option:selected').val(); var paramAccountActivated = $( '#paramAccountActivated_dropdown option:selected').val(); var typeOfCustomer = $( '#typeOfCustomer_dropdown option:selected').val(); var url = baseURL + "/app/site/hosting/scriptlet.nl?script=1745&deploy=1&zee=" + zee + '&activated=' + paramAccountActivated + '&type=' + typeOfCustomer; window.location.href = url; }); $("#clearFilter").click(function () { var url = baseURL + "/app/site/hosting/scriptlet.nl?script=1745&deploy=1" window.location.href = url; }); submitSearch(); var dataTable = $('#mpexusage-customer_contact_list').DataTable(); var dataTable2 = $('#mpexusage-customer_contact_list_remaining').DataTable(); var today = new Date(); var today_year = today.getFullYear(); var today_month = today.getMonth(); var today_day = today.getDate(); /** * Click for Instructions Section Collapse */ $('.collapse').on('shown.bs.collapse', function () { $(".range_filter_section_top").css("padding-top", "500px"); }) $('.collapse').on('hide.bs.collapse', function () { $(".range_filter_section_top").css("padding-top", "0px"); }) $('.createPasswordEmail').click(function () { var contactInternalId = $(this).attr("data-id"); console.log('contactInternalId: ' + contactInternalId); var contactRecord = record.load({ type: record.Type.CONTACT, id: parseInt(contactInternalId), isDynamic: true }); contactRecord.setValue({ fieldId: 'custentity_create_password_email', value: 1 }); contactRecord.save(); var convertLink = 'https://1048144.app.netsuite.com/app/site/hosting/scriptlet.nl?script=1745&deploy=1'; window.location.href = convertLink; }) $('.accountActivated').click(function () { var contactInternalId = $(this).attr("data-id"); console.log('contactInternalId: ' + contactInternalId); var contactRecord = record.load({ type: record.Type.CONTACT, id: parseInt(contactInternalId), isDynamic: true }); contactRecord.setValue({ fieldId: 'custentity_password_setup_completed', value: 1 }); contactRecord.save(); var convertLink = 'https://1048144.app.netsuite.com/app/site/hosting/scriptlet.nl?script=1745&deploy=1'; window.location.href = convertLink; }); $(".displayIncrement").click(function () { console.log('inside display increment'); var val1 = currentRecord.get(); var displayContacts = parseInt(val1.getValue({ fieldId: 'custpage_displaylist', })); var totalContacts = parseInt($('#totalDisplayContacts').val()); // var displayContacts = parseInt($('#displayContacts').val()); zee = $( '#zee_dropdown option:selected').val(); var paramAccountActivated = $( '#paramAccountActivated_dropdown option:selected').val(); var typeOfCustomer = $( '#typeOfCustomer_dropdown option:selected').val(); if (isNullorEmpty(displayContacts)) { } var intialDisplay = (displayContacts + 1); if ((totalContacts - intialDisplay) > 30) { var finalDisplay = intialDisplay + 30; } else { var finalDisplay = totalContacts; } var url = baseURL + "/app/site/hosting/scriptlet.nl?script=1745&deploy=1&zee=" + zee + '&activated=' + paramAccountActivated + '&type=' + typeOfCustomer + '&intial=' + intialDisplay + '&final=' + finalDisplay; window.location.href = url; }); $(".displayDecrement").click(function () { console.log('inside display increment'); var val1 = currentRecord.get(); zee = $( '#zee_dropdown option:selected').val(); var paramAccountActivated = $( '#paramAccountActivated_dropdown option:selected').val(); var typeOfCustomer = $( '#typeOfCustomer_dropdown option:selected').val(); var displayContacts = parseInt(val1.getValue({ fieldId: 'custpage_displaylist', })); var intialDisplay = parseInt(val1.getValue({ fieldId: 'custpage_initialdisplaylist', })); var totalContacts = parseInt($('#totalDisplayContacts').val()); // var displayContacts = parseInt($('#displayContacts').val()); if (!isNullorEmpty(intialDisplay) && intialDisplay != 0) { intialDisplay = intialDisplay - 30; if (intialDisplay == 1) { intialDisplay = 0; } if ((totalContacts - intialDisplay) > 30) { var finalDisplay = intialDisplay + 30; } else { var finalDisplay = totalContacts; } var url = baseURL + "/app/site/hosting/scriptlet.nl?script=1745&deploy=1&zee=" + zee + '&activated=' + paramAccountActivated + '&type=' + typeOfCustomer + '&intial=' + intialDisplay + '&final=' + finalDisplay; window.location.href = url; } else { var url = baseURL + "/app/site/hosting/scriptlet.nl?script=1745&deploy=1&zee=" + zee + '&activated=' + paramAccountActivated + '&type=' + typeOfCustomer; } var url = baseURL + "/app/site/hosting/scriptlet.nl?script=1745&deploy=1&zee=" + zee + '&activated=' + paramAccountActivated + '&type=' + typeOfCustomer + '&intial=' + intialDisplay + '&final=' + finalDisplay; window.location.href = url; }); $(".sendEmail").click(function () { console.log('inside Send Email') var customerInternalId = $(this).attr("data-id"); var salesrepid = $(this).attr("data-sales"); var contactid = $(this).attr("data-contact"); var contactEmail = $(this).attr("data-contactemail"); var contactName = $(this).attr("data-contactname"); var contactPhone = $(this).attr("data-contactphone"); var contactNameArray = contactName.split(' '); var val1 = currentRecord.get(); val1.setValue({ fieldId: 'custpage_customer_id', value: customerInternalId }); val1.setValue({ fieldId: 'custpage_sales_rep_id', value: salesrepid }); val1.setValue({ fieldId: 'custpage_contact_id', value: contactid }); val1.setValue({ fieldId: 'custpage_contact_fname', value: contactNameArray[0] }); val1.setValue({ fieldId: 'custpage_contact_lname', value: contactNameArray[1] }); val1.setValue({ fieldId: 'custpage_contact_email', value: contactEmail }); val1.setValue({ fieldId: 'custpage_contact_phone', value: contactPhone }); $('#submitter').trigger('click'); }); //On click of close icon in the modal $('.close').click(function () { $("#myModal").hide(); }); } //Initialise the DataTable with headers. function submitSearch() { // duringSubmit(); dataTable = $('#mpexusage-customer_contact_list').DataTable({ destroy: true, data: customerContactListDataSet, pageLength: 1000, order: [[4, 'asc'], [3, 'asc']], columns: [{ title: 'USAGE' }, { title: 'ID' }, { title: 'COMPANY NAME' }, { title: 'FRANCHISEE' }, { title: 'CONTACT CREATED' }, { title: 'CONTACT INTERNAL ID' }, { title: 'CONTACT NAME' }, { title: 'CONTACT EMAIL' }, { title: 'CONTACT PHONE' }, { title: 'CREATE PASSWORD EMAIL SENT?' }, { title: 'CREATE PASSWORD EMAIL SENT - COUNT' }, { title: 'ACCOUNT ACTIVATED' }, { title: 'USAGE SOURCE STATUS' }], columnDefs: [{ targets: [2, 3, 9, 10, 11, 12], className: 'bolded' }, { targets: [2], className: 'col-xs-3' }], rowCallback: function (row, data, index) { if (!isNullorEmpty(data[12])) { if (data[12] == 'MANUAL BARCODES') { $('td', row).css('background-color', '#ff9090'); } else if (data[12] == 'DIGITAL LABEL') { $('td', row).css('background-color', '#86c8bc'); } else { $('td', row).css('background-color', '#adcf9f'); } } else if (data[9] == 'Yes' && data[11] == 'Yes') { $('td', row).css('background-color', '#adcf9f'); } else if (data[9] == 'Yes' && data[11] != 'Yes') { if (parseInt(data[10]) == 4) { $('td', row).css('background-color', '#DB6C79'); $('td', row).css('font-weight', 'bold'); $(row).css('outline', 'auto'); } else if (parseInt(data[10]) > 4) { $('td', row).css('background-color', '#B31312'); $('td', row).css('font-weight', 'bold'); $('td', row).css('color', 'white'); $(row).css('outline', 'auto'); } else { $('td', row).css('background-color', '#ffd7a5'); } } } }); dataTable2 = $('#mpexusage-customer_contact_list_remaining').DataTable({ destroy: true, data: customerContactListDataSet2, pageLength: 1000, order: [[4, 'asc'], [3, 'asc']], columns: [{ title: 'USAGE' }, { title: 'ID' }, { title: 'COMPANY NAME' }, { title: 'FRANCHISEE' }, { title: 'CONTACT CREATED' }, { title: 'CONTACT INTERNAL ID' }, { title: 'CONTACT NAME' }, { title: 'CONTACT EMAIL' }, { title: 'CONTACT PHONE' }, { title: 'CREATE PASSWORD EMAIL SENT?' }, { title: 'CREATE PASSWORD EMAIL SENT - COUNT' }, { title: 'ACCOUNT ACTIVATED' }, { title: 'USAGE SOURCE STATUS' }], columnDefs: [{ targets: [2, 3, 9, 10, 11, 12], className: 'bolded' }, { targets: [2], className: 'col-xs-3' }], rowCallback: function (row, data, index) { if (!isNullorEmpty(data[12])) { if (data[12] == 'MANUAL BARCODES') { $('td', row).css('background-color', '#ff9090'); } else if (data[12] == 'DIGITAL LABEL') { $('td', row).css('background-color', '#86c8bc'); } else { $('td', row).css('background-color', '#adcf9f'); } } else if (data[9] == 'Yes' && data[11] == 'Yes') { $('td', row).css('background-color', '#adcf9f'); } else if (data[9] == 'Yes' && data[11] != 'Yes') { if (parseInt(data[10]) == 4) { $('td', row).css('background-color', '#DB6C79'); $('td', row).css('font-weight', 'bold'); $(row).css('outline', 'auto'); } else if (parseInt(data[10]) > 4) { $('td', row).css('background-color', '#B31312'); $('td', row).css('font-weight', 'bold'); $('td', row).css('color', 'white'); $(row).css('outline', 'auto'); } else { $('td', row).css('background-color', '#ffd7a5'); } } } }); loadSearch(); afterSubmit(); } function loadSearch() { zee = $( '#zee_dropdown option:selected').val(); var paramAccountActivated = $( '#paramAccountActivated_dropdown option:selected').val(); var typeOfCustomer = $( '#typeOfCustomer_dropdown option:selected').val(); console.log('paramAccountActivated: ' + paramAccountActivated); if (typeOfCustomer == 1) { if (paramAccountActivated == 1) { //Search Name: Customer Contacts - Mail/Parcel Operator Role var custContactListMailOperatorRoleSearch = search.load({ type: 'customer', id: 'customsearch_cust_contact_mail_parcel__6' }); } else { //Search Name: Customer Contacts - Mail/Parcel Operator Role var custContactListMailOperatorRoleSearch = search.load({ type: 'customer', id: 'customsearch_cust_contact_mail_parcel_ro' }); } if (!isNullorEmpty(zee)) { custContactListMailOperatorRoleSearch.filters.push(search.createFilter({ name: 'partner', join: null, operator: search.Operator.IS, values: zee })); } // if (paramAccountActivated == 1) { // custContactListMailOperatorRoleSearch.filters.push(search.createFilter({ // name: 'custentity_create_password_email', // join: 'contact', // operator: search.Operator.ANYOF, // values: ["1"] // })); // custContactListMailOperatorRoleSearch.filters.push(search.createFilter({ // name: 'custentity_password_setup_completed', // join: 'contact', // operator: search.Operator.ANYOF, // values: ["1"] // })); // } else { // custContactListMailOperatorRoleSearch.filters.push(search.createFilter({ // name: 'custentity_create_password_email', // join: 'contact', // operator: search.Operator.ANYOF, // values: ["1", "@NONE@"] // })); // custContactListMailOperatorRoleSearch.filters.push(search.createFilter({ // name: 'custentity_password_setup_completed', // join: 'contact', // operator: search.Operator.ANYOF, // values: ["@NONE@"] // })); // } custContactListMailOperatorRoleSearch.run().each(function ( custContactListMailOperatorRoleResultSet) { var custInternalID = custContactListMailOperatorRoleResultSet.getValue({ name: 'internalid' }); var custEntityID = custContactListMailOperatorRoleResultSet.getValue({ name: 'entityid' }); var custName = custContactListMailOperatorRoleResultSet.getValue({ name: 'companyname' }); var zeeID = custContactListMailOperatorRoleResultSet.getValue({ name: 'partner' }); var zeeName = custContactListMailOperatorRoleResultSet.getText({ name: 'partner' }); var contactCreated = custContactListMailOperatorRoleResultSet.getValue({ name: 'datecreated', join: "contact", }); var contactInternalId = custContactListMailOperatorRoleResultSet.getValue({ name: "internalid", join: "contact", }); var contactName = custContactListMailOperatorRoleResultSet.getValue({ name: "entityid", join: "contact", }); var contactEmail = custContactListMailOperatorRoleResultSet.getValue({ name: "email", join: "contact", }); var contactPhone = custContactListMailOperatorRoleResultSet.getValue({ name: "phone", join: "contact", }); var contactCreatePasswordEmail = custContactListMailOperatorRoleResultSet.getValue({ name: "custentity_create_password_email", join: "contact", }); if (contactCreatePasswordEmail == 1) { contactCreatePasswordEmail = 'Yes' } else { contactCreatePasswordEmail = '' } var contactPasswordSetupCompleted = custContactListMailOperatorRoleResultSet.getValue({ name: "custentity_password_setup_completed", join: "contact", }); var contactCreatePasswordEmailCount = custContactListMailOperatorRoleResultSet.getValue({ name: "custentity_create_password_email_count", join: "contact", }); if (isNullorEmpty(contactCreatePasswordEmailCount)) { contactCreatePasswordEmailCount = 0; } if (contactPasswordSetupCompleted == 1) { contactPasswordSetupCompleted = 'Yes' } else { contactPasswordSetupCompleted = '' } if (contactCreatePasswordEmailCount == 0 && contactCreatePasswordEmail == 'Yes' && contactPasswordSetupCompleted == 'Yes') { contactCreatePasswordEmailCount = 1; } customerContactListSet.push({ custInternalID: custInternalID, custEntityID: custEntityID, custName: custName, zeeID: zeeID, zeeName: zeeName, contactCreated: contactCreated, contactInternalId: contactInternalId, contactName: contactName, contactEmail: contactEmail, contactPhone: contactPhone, contactCreatePasswordEmail: contactCreatePasswordEmail, contactPasswordSetupCompleted: contactPasswordSetupCompleted, contactCreatePasswordEmailCount: contactCreatePasswordEmailCount }); totalTop50Contacts++; return true; }); console.log(customerContactListSet); } if (typeOfCustomer == 2) { if (paramAccountActivated == 1) { //Search Name: Customer Contacts - Manual Migration - Remaining var custContactListManualMIgrationRemainingSearch = search.load({ type: 'customer', id: 'customsearch_cust_contact_mail_parcel__7' }); } else { //Search Name: Customer Contacts - Manual Migration - Remaining var custContactListManualMIgrationRemainingSearch = search.load({ type: 'customer', id: 'customsearch_cust_contact_mail_parcel__4' }); } if (!isNullorEmpty(zee)) { custContactListManualMIgrationRemainingSearch.filters.push(search.createFilter({ name: 'partner', join: null, operator: search.Operator.IS, values: zee })); } // if (paramAccountActivated == 1) { // custContactListManualMIgrationRemainingSearch.filters.push(search.createFilter({ // name: 'custentity_create_password_email', // join: 'contact', // operator: search.Operator.ANYOF, // values: ["1"] // })); // custContactListManualMIgrationRemainingSearch.filters.push(search.createFilter({ // name: 'custentity_password_setup_completed', // join: 'contact', // operator: search.Operator.ANYOF, // values: ["1"] // })); // } else { // custContactListManualMIgrationRemainingSearch.filters.push(search.createFilter({ // name: 'custentity_create_password_email', // join: 'contact', // operator: search.Operator.ANYOF, // values: ["1", "@NONE@"] // })); // custContactListManualMIgrationRemainingSearch.filters.push(search.createFilter({ // name: 'custentity_password_setup_completed', // join: 'contact', // operator: search.Operator.ANYOF, // values: ["@NONE@"] // })); // } custContactListManualMIgrationRemainingSearch.run().each(function ( custContactListManualMIgrationRemainingSearchRseultSet) { var custInternalID = custContactListManualMIgrationRemainingSearchRseultSet.getValue({ name: 'internalid' }); var custEntityID = custContactListManualMIgrationRemainingSearchRseultSet.getValue({ name: 'entityid' }); var custName = custContactListManualMIgrationRemainingSearchRseultSet.getValue({ name: 'companyname' }); var zeeID = custContactListManualMIgrationRemainingSearchRseultSet.getValue({ name: 'partner' }); var zeeName = custContactListManualMIgrationRemainingSearchRseultSet.getText({ name: 'partner' }); var contactCreated = custContactListManualMIgrationRemainingSearchRseultSet.getValue({ name: 'datecreated', join: "contact", }); var contactInternalId = custContactListManualMIgrationRemainingSearchRseultSet.getValue({ name: "internalid", join: "contact", }); var contactName = custContactListManualMIgrationRemainingSearchRseultSet.getValue({ name: "entityid", join: "contact", }); var contactEmail = custContactListManualMIgrationRemainingSearchRseultSet.getValue({ name: "email", join: "contact", }); var contactPhone = custContactListManualMIgrationRemainingSearchRseultSet.getValue({ name: "phone", join: "contact", }); var contactCreatePasswordEmail = custContactListManualMIgrationRemainingSearchRseultSet.getValue({ name: "custentity_create_password_email", join: "contact", }); if (contactCreatePasswordEmail == 1) { contactCreatePasswordEmail = 'Yes' } else { contactCreatePasswordEmail = '' } var contactPasswordSetupCompleted = custContactListManualMIgrationRemainingSearchRseultSet.getValue({ name: "custentity_password_setup_completed", join: "contact", }); var contactCreatePasswordEmailCount = custContactListManualMIgrationRemainingSearchRseultSet.getValue({ name: "custentity_create_password_email_count", join: "contact", }); if (isNullorEmpty(contactCreatePasswordEmailCount)) { contactCreatePasswordEmailCount = 0; } if (contactPasswordSetupCompleted == 1) { contactPasswordSetupCompleted = 'Yes' } else { contactPasswordSetupCompleted = '' } if (contactCreatePasswordEmailCount == 0 && contactCreatePasswordEmail == 'Yes' && contactPasswordSetupCompleted == 'Yes') { contactCreatePasswordEmailCount = 1; } customerContactListSet2.push({ custInternalID: custInternalID, custEntityID: custEntityID, custName: custName, zeeID: zeeID, zeeName: zeeName, contactCreated: contactCreated, contactInternalId: contactInternalId, contactName: contactName, contactEmail: contactEmail, contactPhone: contactPhone, contactCreatePasswordEmail: contactCreatePasswordEmail, contactPasswordSetupCompleted: contactPasswordSetupCompleted, contactCreatePasswordEmailCount: contactCreatePasswordEmailCount }); totalReminingContacts++; return true; }); console.log(customerContactListSet2) } loadDatatable(customerContactListSet, customerContactListSet2); debt_set = []; } function loadDatatable(customerContactListRows, customerContactListRemainingRows) { customerContactListDataSet = []; csvSet = []; customerContactListDataSet2 = []; csvSet2 = []; var noUsageCustomerCount = 0; var manualUsageCustomerCount = 0; var digitalLabelUsageCustomerCount = 0; var val1 = currentRecord.get(); var paramAccountActivated = $( '#paramAccountActivated_dropdown option:selected').val(); var typeOfCustomer = $( '#typeOfCustomer_dropdown option:selected').val(); var customerCountAccountActivated = 0; if (!isNullorEmpty(customerContactListRows)) { $('#totalDisplayContacts').val(customerContactListRows.length); val1.setValue({ fieldId: 'custpage_totalcontactlist', value: totalDisplayContacts }); customerContactListRows.forEach(function (customerContactListRow, index) { var contactCreatedArray = customerContactListRow.contactCreated.split(' '); var contactCreatedDateSplit = contactCreatedArray[0].split('/'); if (parseInt(contactCreatedDateSplit[1]) < 10) { contactCreatedDateSplit[1] = '0' + contactCreatedDateSplit[1] } if (parseInt(contactCreatedDateSplit[0]) < 10) { contactCreatedDateSplit[0] = '0' + contactCreatedDateSplit[0] } var contactCreatedDateSplitString = contactCreatedDateSplit[2] + '-' + contactCreatedDateSplit[1] + '-' + contactCreatedDateSplit[0]; var date_from = dateISOToNetsuite(contactCreatedDateSplitString); console.log('date_from: ' + date_from) console.log('customerContactListRow.custInternalID: ' + customerContactListRow.custInternalID); var date = new Date(), y = date.getFullYear(), m = date.getMonth(); var firstDay = new Date(y, m, 1); var lastDay = new Date(y, m + 1, 0); firstDay.setHours(0, 0, 0, 0); lastDay.setHours(0, 0, 0, 0); firstDay = GetFormattedDate(firstDay); lastDay = GetFormattedDate(lastDay); var sendSignUpEmail = customerContactListRow.contactEmail; if (customerContactListRow.contactCreatePasswordEmail == 'Yes' && customerContactListRow.contactPasswordSetupCompleted == 'Yes') { //Search Name: All MP Products - Source/Week var mpProductSourcePerWeekSearch = search.load({ type: 'customrecord_customer_product_stock', id: 'customsearch_prod_stock_usage_report___6' }); mpProductSourcePerWeekSearch.filters.push(search.createFilter({ name: 'internalid', join: 'custrecord_cust_prod_stock_customer', operator: search.Operator.IS, values: parseInt(customerContactListRow.custInternalID) })); mpProductSourcePerWeekSearch.filters.push(search.createFilter({ name: 'custrecord_barcode_source', operator: search.Operator.ANYOF, values: ["1", "@NONE@"] })); mpProductSourcePerWeekSearch.filters.push(search.createFilter({ name: 'custrecord_cust_date_stock_used', join: null, operator: search.Operator.ONORAFTER, values: date_from })); customerCountAccountActivated++; console.log('customerCountAccountActivated: ' + customerCountAccountActivated) var resultRange = mpProductSourcePerWeekSearch.run().getRange({ start: 0, end: 1 }); if (resultRange.length == 0) { //Search Name: All MP Products - Source/Week var mpProductSourcePerWeekSearch = search.load({ type: 'customrecord_customer_product_stock', id: 'customsearch_prod_stock_usage_report___6' }); mpProductSourcePerWeekSearch.filters.push(search.createFilter({ name: 'internalid', join: 'custrecord_cust_prod_stock_customer', operator: search.Operator.IS, values: parseInt(customerContactListRow.custInternalID) })); mpProductSourcePerWeekSearch.filters.push(search.createFilter({ name: 'custrecord_barcode_source', operator: search.Operator.NONEOF, values: ["1", "@NONE@"] })); mpProductSourcePerWeekSearch.filters.push(search.createFilter({ name: 'custrecord_cust_date_stock_used', join: null, operator: search.Operator.ONORAFTER, values: date_from })); console.log('mpProductSourcePerWeekSearch.run(): ' + mpProductSourcePerWeekSearch.run()) var resultRange = mpProductSourcePerWeekSearch.run().getRange({ start: 0, end: 1 }); if (resultRange.length == 0) { var currentStatus = 'NO USAGE'; noUsageCustomerCount++; // var linkURL = '<a href="https://1048144.app.netsuite.com/app/site/hosting/scriptlet.nl?script=1712&deploy=1&start_date=' + contactCreatedDateSplitString + '&last_date=' + lastDay + '&zee=' + customerContactListRow.zeeID + '&custid=' + customerContactListRow.custInternalID + '&freq=daily" target="_blank" style="font-weight: bold; cursor: pointer !important;width: 50%;border-radius: 30px;padding: 2.5%;" class="button-shadow"><i class="fa-solid fa-chart-simple" style="font-size: 25px;color: #337ab7"></i></a>' var linkURL = '<a href="https://1048144.app.netsuite.com/app/site/hosting/scriptlet.nl?script=1712&deploy=1&start_date=' + contactCreatedDateSplitString + '&last_date=' + lastDay + '&zee=' + customerContactListRow.zeeID + '&custid=' + customerContactListRow.custInternalID + '&freq=daily" target="_blank" style="font-weight: bold; cursor: pointer !important;width: 50%;border-radius: 30px;padding: 2.5%;" class=""><img src="https://1048144.app.netsuite.com/core/media/media.nl?id=6399648&c=1048144&h=IV0eZcpDJAJvpDCshlu59Ny5BQ1HZwqvu2FIRmE9CZHL8AN3" style="height: 3em; width: 3em;"></a>' } else { var currentStatus = 'DIGITAL LABEL' digitalLabelUsageCustomerCount++; var linkURL = '<a href="https://1048144.app.netsuite.com/app/site/hosting/scriptlet.nl?script=1712&deploy=1&start_date=' + contactCreatedDateSplitString + '&last_date=' + lastDay + '&zee=' + customerContactListRow.zeeID + '&custid=' + customerContactListRow.custInternalID + '&freq=daily" target="_blank" style="font-weight: bold; cursor: pointer !important;width: 50%;border-radius: 30px;padding: 2.5%;" class=""><img src="https://1048144.app.netsuite.com/core/media/media.nl?id=6399648&c=1048144&h=IV0eZcpDJAJvpDCshlu59Ny5BQ1HZwqvu2FIRmE9CZHL8AN3" style="height: 3em; width: 3em;"></a>' } } else { var currentStatus = 'MANUAL BARCODES'; manualUsageCustomerCount++; var linkURL = '<a href="https://1048144.app.netsuite.com/app/site/hosting/scriptlet.nl?script=1712&deploy=1&start_date=' + contactCreatedDateSplitString + '&last_date=' + lastDay + '&zee=' + customerContactListRow.zeeID + '&custid=' + customerContactListRow.custInternalID + '&freq=daily" target="_blank" style="font-weight: bold; cursor: pointer !important;width: 50%;border-radius: 30px;padding: 2.5%;" class=""><img src="https://1048144.app.netsuite.com/core/media/media.nl?id=6399648&c=1048144&h=IV0eZcpDJAJvpDCshlu59Ny5BQ1HZwqvu2FIRmE9CZHL8AN3" style="height: 3em; width: 3em;"></a>' } } else if (customerContactListRow.contactCreatePasswordEmail != 'Yes' && customerContactListRow.contactPasswordSetupCompleted != 'Yes') { var linkURL = '' var currentStatus = '' if (role == 3 || role == 1032) { //Administrator or System Support linkURL = '<input type="button" id="" data-id="' + customerContactListRow.contactInternalId + '" value="CREATE PASSWORD EMAIL SENT" class="form-control btn btn-xs btn-primary createPasswordEmail button-shadow" style="font-weight: bold; cursor: pointer !important;width: fit-content;border-radius: 30px" /> </br><a href="https://1048144.app.netsuite.com/app/site/hosting/scriptlet.nl?script=1712&deploy=1&start_date=' + contactCreatedDateSplitString + '&last_date=' + lastDay + '&zee=' + customerContactListRow.zeeID + '&custid=' + customerContactListRow.custInternalID + '&freq=daily" target="_blank" style="font-weight: bold; cursor: pointer !important;width: 50%;border-radius: 30px;padding: 2.5%;" class=""><img src="https://1048144.app.netsuite.com/core/media/media.nl?id=6399648&c=1048144&h=IV0eZcpDJAJvpDCshlu59Ny5BQ1HZwqvu2FIRmE9CZHL8AN3" style="height: 3em; width: 3em;"></a>'; } else { var linkURL = '<a href="https://1048144.app.netsuite.com/app/site/hosting/scriptlet.nl?script=1712&deploy=1&start_date=' + contactCreatedDateSplitString + '&last_date=' + lastDay + '&zee=' + customerContactListRow.zeeID + '&custid=' + customerContactListRow.custInternalID + '&freq=daily" target="_blank" style="font-weight: bold; cursor: pointer !important;width: 50%;border-radius: 30px;padding: 2.5%;" class=""><img src="https://1048144.app.netsuite.com/core/media/media.nl?id=6399648&c=1048144&h=IV0eZcpDJAJvpDCshlu59Ny5BQ1HZwqvu2FIRmE9CZHL8AN3" style="height: 3em; width: 3em;"></a>' } } else if (customerContactListRow.contactCreatePasswordEmail == 'Yes' && customerContactListRow.contactPasswordSetupCompleted != 'Yes') { var linkURL = '' var currentStatus = ''; if (role == 3 || role == 1032) { //Administrator or System Support linkURL = '<input type="button" id="" data-id="' + customerContactListRow.contactInternalId + '" value="ACTIVATED" class="form-control btn btn-xs btn-success accountActivated button-shadow" style="font-weight: bold; cursor: pointer !important;width: fit-content;border-radius: 30px" /> </br><a href="https://1048144.app.netsuite.com/app/site/hosting/scriptlet.nl?script=1712&deploy=1&start_date=' + contactCreatedDateSplitString + '&last_date=' + lastDay + '&zee=' + customerContactListRow.zeeID + '&custid=' + customerContactListRow.custInternalID + '&freq=daily" target="_blank" style="font-weight: bold; cursor: pointer !important;width: 50%;border-radius: 30px;padding: 2.5%;" class=""><img src="https://1048144.app.netsuite.com/core/media/media.nl?id=6399648&c=1048144&h=IV0eZcpDJAJvpDCshlu59Ny5BQ1HZwqvu2FIRmE9CZHL8AN3" style="height: 3em; width: 3em;"></a>'; var franchiseeSalesRepAssigned = nlapiLookupField('customer', parseInt(customerContactListRow.contactInternalId), 'partner.custentity_sales_rep_assigned'); salesRepId = franchiseeSalesRepAssigned; if (franchiseeSalesRepAssigned == '668712') { salesRepEmail = 'ychag@example.com'; salesRepName = 'Belinda Urbani'; salesRepId = 668712 } else if (franchiseeSalesRepAssigned == '696160') { salesRepEmail = 'hzdkv@example.com' salesRepName = 'Kerina Helliwell'; salesRepId = 696160 } else { salesRepEmail = 'kenaa@example.com'; salesRepName = 'Lee Russell'; salesRepId = 668711 } var sendSignUpEmail = '<a data-id="' + customerContactListRow.custInternalID + '" data-sales="' + salesRepId + '" data-contact="' + customerContactListRow.contactInternalId + '" data-contactemail="' + customerContactListRow.contactEmail + '" data-contactName="' + customerContactListRow.contactName + '" data-contactPhone="' + customerContactListRow.contactPhone + '" data-salesrecordid="" style="font-weight: bold; cursor: pointer !important;width: 50%;border-radius: 30px;padding: 2.5%;" class="sendEmail"><button class="button-shadow"><div class="svg-wrapper-1"><div class="svg-wrapper"><svg height="24" width="24" viewBox="0 0 24 24" xmlns="http://www.w3.org/2000/svg"><path d="M0 0h24v24H0z" fill="none"></path><path d="M1.946 9.315c-.522-.174-.527-.455.01-.634l19.087-6.362c.529-.176.832.12.684.638l-5.454 19.086c-.15.529-.455.547-.679.045L12 14l6-8-8 6-8.054-2.685z" fill="currentColor"></path></svg></div></div><span>Resend</span></button></a></br></br>' + customerContactListRow.contactEmail; // linkURL = // '<a href="" class="accountActivated button-shadow" style="cursor: pointer !important;" ><img src="https://1048144.app.netsuite.com/core/media/media.nl?id=6399647&c=1048144&h=RuKYj6ulVT3rxPGWwg3OnnI6wETYrFW3BjGkTbg6dg7ms7wv" style="height: 3em; width: 3em;"></a><input type="button" id="" data-id="' + // customerContactListRow.contactInternalId + // '" value="ACTIVATED" class="form-control btn btn-xs btn-success accountActivated button-shadow" style="font-weight: bold; cursor: pointer !important;width: fit-content;border-radius: 30px" /> </br><a href="https://1048144.app.netsuite.com/app/site/hosting/scriptlet.nl?script=1712&deploy=1&start_date=' + contactCreatedDateSplitString + '&last_date=' + lastDay + '&zee=' + customerContactListRow.zeeID + '&custid=' + customerContactListRow.custInternalID + '&freq=daily" target="_blank" style="font-weight: bold; cursor: pointer !important;width: 50%;border-radius: 30px;padding: 2.5%;" class="button-shadow"><i class="fa-solid fa-chart-simple" style="font-size: 25px;color: #337ab7"></i></a>'; } else { var linkURL = '<a href="https://1048144.app.netsuite.com/app/site/hosting/scriptlet.nl?script=1712&deploy=1&start_date=' + contactCreatedDateSplitString + '&last_date=' + lastDay + '&zee=' + customerContactListRow.zeeID + '&custid=' + customerContactListRow.custInternalID + '&freq=daily" target="_blank" style="font-weight: bold; cursor: pointer !important;width: 50%;border-radius: 30px;padding: 2.5%;" class=""><img src="https://1048144.app.netsuite.com/core/media/media.nl?id=6399648&c=1048144&h=IV0eZcpDJAJvpDCshlu59Ny5BQ1HZwqvu2FIRmE9CZHL8AN3" style="height: 3em; width: 3em;"></a>'; } } var customerIDLink = '<a href="https://1048144.app.netsuite.com/app/common/entity/custjob.nl?id=' + customerContactListRow.custInternalID + '&whence=" target="_blank"><b>' + customerContactListRow.custEntityID + '</b></a>'; if (role == 3 || role == 1032) { var contactIdLink = '<a href="https://1048144.app.netsuite.com/app/common/entity/contact.nl?id=' + customerContactListRow.contactInternalId + '&whence=" target="_blank"><b>Edit Contact</b></a>'; // var franchiseeSalesRepAssigned = nlapiLookupField('customer', parseInt(customerContactListRow.contactInternalId), 'partner.custentity_sales_rep_assigned'); // salesRepId = franchiseeSalesRepAssigned; // if (franchiseeSalesRepAssigned == '668712') { // salesRepEmail = 'ychag@example.com'; // salesRepName = 'Belinda Urbani'; // salesRepId = 668712 // } else if (franchiseeSalesRepAssigned == '696160') { // salesRepEmail = 'hzdkv@example.com' // salesRepName = 'Kerina Helliwell'; // salesRepId = 696160 // } else { // salesRepEmail = 'kenaa@example.com'; // salesRepName = 'Lee Russell'; // salesRepId = 668711 // } // var sendSignUpEmail = // '<a data-id="' + // customerContactListRow.custInternalID + // '" data-sales="' + // salesRepId + // '" data-contact="' + // customerContactListRow.contactInternalId + // '" data-contactemail="' + // customerContactListRow.contactEmail + // '" data-contactName="' + // customerContactListRow.contactName + // '" data-contactPhone="' + // customerContactListRow.contactPhone + // '" data-salesrecordid="" style="font-weight: bold; cursor: pointer !important;width: 50%;border-radius: 30px;padding: 2.5%;" class="sendEmail"><button><div class="svg-wrapper-1"><div class="svg-wrapper"><svg height="24" width="24" viewBox="0 0 24 24" xmlns="http://www.w3.org/2000/svg"><path d="M0 0h24v24H0z" fill="none"></path><path d="M1.946 9.315c-.522-.174-.527-.455.01-.634l19.087-6.362c.529-.176.832.12.684.638l-5.454 19.086c-.15.529-.455.547-.679.045L12 14l6-8-8 6-8.054-2.685z" fill="currentColor"></path></svg></div></div><span>Send</span></button></a></br>' + customerContactListRow.contactEmail; } else { var contactIdLink = customerContactListRow.contactInternalId; // var sendSignUpEmail = customerContactListRow.contactEmail; } customerContactListDataSet.push([linkURL, customerIDLink, customerContactListRow.custName, customerContactListRow.zeeName, contactCreatedDateSplitString, contactIdLink, customerContactListRow.contactName, sendSignUpEmail, customerContactListRow.contactPhone, customerContactListRow.contactCreatePasswordEmail, parseInt(customerContactListRow.contactCreatePasswordEmailCount), customerContactListRow.contactPasswordSetupCompleted, currentStatus ]); csvSet.push([customerContactListRow.custInternalID, customerContactListRow.custName, customerContactListRow.zeeName, contactCreatedDateSplitString, customerContactListRow.contactInternalId, customerContactListRow.contactName, customerContactListRow.contactEmail, customerContactListRow.contactPhone, customerContactListRow.contactCreatePasswordEmail, customerContactListRow.contactCreatePasswordEmailCount, customerContactListRow.contactPasswordSetupCompleted ]); }); } var datatable = $('#mpexusage-customer_contact_list').DataTable(); datatable.clear(); datatable.rows.add(customerContactListDataSet); datatable.draw(); saveCsv(csvSet); var customerCountRemainingAccountActivated = 0; if (!isNullorEmpty(customerContactListRemainingRows)) { var customerContactListRemainingLength = customerContactListRemainingRows.length; $('#totalDisplayContacts').val(customerContactListRemainingLength); val1.setValue({ fieldId: 'custpage_totalcontactlist', value: customerContactListRemainingLength }); console.log('customerContactListRemainingLength: ' + customerContactListRemainingLength); var intialDisplay = 0; var displayList = 0; if (customerContactListRemainingLength <= 30) { displayList = customerContactListRemainingLength; val1.setValue({ fieldId: 'custpage_displaylist', value: displayList }); $('#displayContacts').val(intialDisplay + ' - ' + displayList); } else if (customerContactListRemainingLength > 30) { var initialDisplayNumber = val1.getValue({ fieldId: 'custpage_initialdisplaylist', }); var finalDisplayListNumber = val1.getValue({ fieldId: 'custpage_displaylist', }); if (isNullorEmpty(finalDisplayListNumber) || initialDisplayNumber == 0) { displayList = 30; val1.setValue({ fieldId: 'custpage_displaylist', value: displayList }); $('#displayContacts').val('(' + intialDisplay + ' - ' + displayList + ') / ' + customerContactListRemainingLength); } else if (initialDisplayNumber > 30) { intialDisplay = initialDisplayNumber - 1; displayList = finalDisplayListNumber; val1.setValue({ fieldId: 'custpage_displaylist', value: displayList }); $('#displayContacts').val('(' + intialDisplay + ' - ' + displayList + ') / ' + customerContactListRemainingLength); } } console.log('intialDisplay: ' + intialDisplay); console.log('displayList: ' + displayList); for (var x = intialDisplay; x < displayList; x++) { console.log('x: ' + x); var contactCreatedArray = customerContactListRemainingRows[x].contactCreated.split(' '); var contactCreatedDateSplit = contactCreatedArray[0].split('/'); if (parseInt(contactCreatedDateSplit[1]) < 10) { contactCreatedDateSplit[1] = '0' + contactCreatedDateSplit[1] } if (parseInt(contactCreatedDateSplit[0]) < 10) { contactCreatedDateSplit[0] = '0' + contactCreatedDateSplit[0] } var contactCreatedDateSplitString = contactCreatedDateSplit[2] + '-' + contactCreatedDateSplit[1] + '-' + contactCreatedDateSplit[0]; var date_from = dateISOToNetsuite(contactCreatedDateSplitString); // console.log('date_from: ' + date_from) // console.log('customerContactListRow.custInternalID: ' + customerContactListRow.custInternalID); var date = new Date(), y = date.getFullYear(), m = date.getMonth(); var firstDay = new Date(y, m, 1); var lastDay = new Date(y, m + 1, 0); firstDay.setHours(0, 0, 0, 0); lastDay.setHours(0, 0, 0, 0); firstDay = GetFormattedDate(firstDay); lastDay = GetFormattedDate(lastDay); var sendSignUpEmail = customerContactListRemainingRows[x].contactEmail; if (customerContactListRemainingRows[x].contactCreatePasswordEmail == 'Yes' && customerContactListRemainingRows[x].contactPasswordSetupCompleted == 'Yes') { //Search Name: All MP Products - Source/Week var mpProductSourcePerWeekSearch = search.load({ type: 'customrecord_customer_product_stock', id: 'customsearch_prod_stock_usage_report___6' }); mpProductSourcePerWeekSearch.filters.push(search.createFilter({ name: 'internalid', join: 'custrecord_cust_prod_stock_customer', operator: search.Operator.IS, values: parseInt(customerContactListRemainingRows[x].custInternalID) })); mpProductSourcePerWeekSearch.filters.push(search.createFilter({ name: 'custrecord_barcode_source', operator: search.Operator.ANYOF, values: ["1", "@NONE@"] })); mpProductSourcePerWeekSearch.filters.push(search.createFilter({ name: 'custrecord_cust_date_stock_used', join: null, operator: search.Operator.ONORAFTER, values: date_from })); customerCountRemainingAccountActivated++; console.log('customerCountRemainingAccountActivated: ' + customerCountRemainingAccountActivated) var resultRange = mpProductSourcePerWeekSearch.run().getRange({ start: 0, end: 1 }); if (resultRange.length == 0) { //Search Name: All MP Products - Source/Week var mpProductSourcePerWeekSearch = search.load({ type: 'customrecord_customer_product_stock', id: 'customsearch_prod_stock_usage_report___6' }); mpProductSourcePerWeekSearch.filters.push(search.createFilter({ name: 'internalid', join: 'custrecord_cust_prod_stock_customer', operator: search.Operator.IS, values: parseInt(customerContactListRemainingRows[x].custInternalID) })); mpProductSourcePerWeekSearch.filters.push(search.createFilter({ name: 'custrecord_barcode_source', operator: search.Operator.NONEOF, values: ["1", "@NONE@"] })); mpProductSourcePerWeekSearch.filters.push(search.createFilter({ name: 'custrecord_cust_date_stock_used', join: null, operator: search.Operator.ONORAFTER, values: date_from })); console.log('mpProductSourcePerWeekSearch.run(): ' + mpProductSourcePerWeekSearch.run()) var resultRange = mpProductSourcePerWeekSearch.run().getRange({ start: 0, end: 1 }); if (resultRange.length == 0) { var currentStatus = 'NO USAGE'; noUsageCustomerCount++; // var linkURL = '<a href="https://1048144.app.netsuite.com/app/site/hosting/scriptlet.nl?script=1712&deploy=1&start_date=' + contactCreatedDateSplitString + '&last_date=' + lastDay + '&zee=' + customerContactListRow.zeeID + '&custid=' + customerContactListRow.custInternalID + '&freq=daily" target="_blank" style="font-weight: bold; cursor: pointer !important;width: 50%;border-radius: 30px;padding: 2.5%;" class="button-shadow"><i class="fa-solid fa-chart-simple" style="font-size: 25px;color: #337ab7"></i></a>' var linkURL = '<a href="https://1048144.app.netsuite.com/app/site/hosting/scriptlet.nl?script=1712&deploy=1&start_date=' + contactCreatedDateSplitString + '&last_date=' + lastDay + '&zee=' + customerContactListRemainingRows[x].zeeID + '&custid=' + customerContactListRemainingRows[x].custInternalID + '&freq=daily" target="_blank" style="font-weight: bold; cursor: pointer !important;width: 50%;border-radius: 30px;padding: 2.5%;" class=""><img src="https://1048144.app.netsuite.com/core/media/media.nl?id=6399648&c=1048144&h=IV0eZcpDJAJvpDCshlu59Ny5BQ1HZwqvu2FIRmE9CZHL8AN3" style="height: 3em; width: 3em;"></a>' } else { var currentStatus = 'DIGITAL LABEL' digitalLabelUsageCustomerCount++; var linkURL = '<a href="https://1048144.app.netsuite.com/app/site/hosting/scriptlet.nl?script=1712&deploy=1&start_date=' + contactCreatedDateSplitString + '&last_date=' + lastDay + '&zee=' + customerContactListRemainingRows[x].zeeID + '&custid=' + customerContactListRemainingRows[x].custInternalID + '&freq=daily" target="_blank" style="font-weight: bold; cursor: pointer !important;width: 50%;border-radius: 30px;padding: 2.5%;" class=""><img src="https://1048144.app.netsuite.com/core/media/media.nl?id=6399648&c=1048144&h=IV0eZcpDJAJvpDCshlu59Ny5BQ1HZwqvu2FIRmE9CZHL8AN3" style="height: 3em; width: 3em;"></a>' } } else { var currentStatus = 'MANUAL BARCODES'; manualUsageCustomerCount++; var linkURL = '<a href="https://1048144.app.netsuite.com/app/site/hosting/scriptlet.nl?script=1712&deploy=1&start_date=' + contactCreatedDateSplitString + '&last_date=' + lastDay + '&zee=' + customerContactListRemainingRows[x].zeeID + '&custid=' + customerContactListRemainingRows[x].custInternalID + '&freq=daily" target="_blank" style="font-weight: bold; cursor: pointer !important;width: 50%;border-radius: 30px;padding: 2.5%;" class=""><img src="https://1048144.app.netsuite.com/core/media/media.nl?id=6399648&c=1048144&h=IV0eZcpDJAJvpDCshlu59Ny5BQ1HZwqvu2FIRmE9CZHL8AN3" style="height: 3em; width: 3em;"></a>' } } else if (customerContactListRemainingRows[x].contactCreatePasswordEmail != 'Yes' && customerContactListRemainingRows[x].contactPasswordSetupCompleted != 'Yes') { var linkURL = '' var currentStatus = '' if (role == 3 || role == 1032) { //Administrator or System Support linkURL = '<input type="button" id="" data-id="' + customerContactListRemainingRows[x].contactInternalId + '" value="CREATE PASSWORD EMAIL SENT" class="form-control btn btn-xs btn-primary createPasswordEmail button-shadow" style="font-weight: bold; cursor: pointer !important;width: fit-content;border-radius: 30px" /> </br><a href="https://1048144.app.netsuite.com/app/site/hosting/scriptlet.nl?script=1712&deploy=1&start_date=' + contactCreatedDateSplitString + '&last_date=' + lastDay + '&zee=' + customerContactListRemainingRows[x].zeeID + '&custid=' + customerContactListRemainingRows[x].custInternalID + '&freq=daily" target="_blank" style="font-weight: bold; cursor: pointer !important;width: 50%;border-radius: 30px;padding: 2.5%;" class=""><img src="https://1048144.app.netsuite.com/core/media/media.nl?id=6399648&c=1048144&h=IV0eZcpDJAJvpDCshlu59Ny5BQ1HZwqvu2FIRmE9CZHL8AN3" style="height: 3em; width: 3em;"></a>'; } else { var linkURL = '<a href="https://1048144.app.netsuite.com/app/site/hosting/scriptlet.nl?script=1712&deploy=1&start_date=' + contactCreatedDateSplitString + '&last_date=' + lastDay + '&zee=' + customerContactListRow.zeeID + '&custid=' + customerContactListRemainingRows[x].custInternalID + '&freq=daily" target="_blank" style="font-weight: bold; cursor: pointer !important;width: 50%;border-radius: 30px;padding: 2.5%;" class=""><img src="https://1048144.app.netsuite.com/core/media/media.nl?id=6399648&c=1048144&h=IV0eZcpDJAJvpDCshlu59Ny5BQ1HZwqvu2FIRmE9CZHL8AN3" style="height: 3em; width: 3em;"></a>' } } else if (customerContactListRemainingRows[x].contactCreatePasswordEmail == 'Yes' && customerContactListRemainingRows[x].contactPasswordSetupCompleted != 'Yes') { var linkURL = '' var currentStatus = ''; if (role == 3 || role == 1032) { //Administrator or System Support linkURL = '<input type="button" id="" data-id="' + customerContactListRemainingRows[x].contactInternalId + '" value="ACTIVATED" class="form-control btn btn-xs btn-success accountActivated button-shadow" style="font-weight: bold; cursor: pointer !important;width: fit-content;border-radius: 30px" /> </br><a href="https://1048144.app.netsuite.com/app/site/hosting/scriptlet.nl?script=1712&deploy=1&start_date=' + contactCreatedDateSplitString + '&last_date=' + lastDay + '&zee=' + customerContactListRemainingRows[x].zeeID + '&custid=' + customerContactListRemainingRows[x].custInternalID + '&freq=daily" target="_blank" style="font-weight: bold; cursor: pointer !important;width: 50%;border-radius: 30px;padding: 2.5%;" class=""><img src="https://1048144.app.netsuite.com/core/media/media.nl?id=6399648&c=1048144&h=IV0eZcpDJAJvpDCshlu59Ny5BQ1HZwqvu2FIRmE9CZHL8AN3" style="height: 3em; width: 3em;"></a>'; var franchiseeSalesRepAssigned = nlapiLookupField('customer', parseInt(customerContactListRemainingRows[x].contactInternalId), 'partner.custentity_sales_rep_assigned'); salesRepId = franchiseeSalesRepAssigned; if (franchiseeSalesRepAssigned == '668712') { salesRepEmail = 'ychag@example.com'; salesRepName = 'Belinda Urbani'; salesRepId = 668712 } else if (franchiseeSalesRepAssigned == '696160') { salesRepEmail = 'hzdkv@example.com' salesRepName = 'Kerina Helliwell'; salesRepId = 696160 } else { salesRepEmail = 'kenaa@example.com'; salesRepName = 'Lee Russell'; salesRepId = 668711 } var sendSignUpEmail = '<a data-id="' + customerContactListRemainingRows[x].custInternalID + '" data-sales="' + salesRepId + '" data-contact="' + customerContactListRemainingRows[x].contactInternalId + '" data-contactemail="' + customerContactListRemainingRows[x].contactEmail + '" data-contactName="' + customerContactListRemainingRows[x].contactName + '" data-contactPhone="' + customerContactListRemainingRows[x].contactPhone + '" data-salesrecordid="" style="font-weight: bold; cursor: pointer !important;width: 50%;border-radius: 30px;padding: 2.5%;" class="sendEmail"><button class="button-shadow"><div class="svg-wrapper-1"><div class="svg-wrapper"><svg height="24" width="24" viewBox="0 0 24 24" xmlns="http://www.w3.org/2000/svg"><path d="M0 0h24v24H0z" fill="none"></path><path d="M1.946 9.315c-.522-.174-.527-.455.01-.634l19.087-6.362c.529-.176.832.12.684.638l-5.454 19.086c-.15.529-.455.547-.679.045L12 14l6-8-8 6-8.054-2.685z" fill="currentColor"></path></svg></div></div><span>Resend</span></button></a></br></br>' + customerContactListRemainingRows[x].contactEmail; // linkURL = // '<a href="" class="accountActivated button-shadow" style="cursor: pointer !important;" ><img src="https://1048144.app.netsuite.com/core/media/media.nl?id=6399647&c=1048144&h=RuKYj6ulVT3rxPGWwg3OnnI6wETYrFW3BjGkTbg6dg7ms7wv" style="height: 3em; width: 3em;"></a><input type="button" id="" data-id="' + // customerContactListRow.contactInternalId + // '" value="ACTIVATED" class="form-control btn btn-xs btn-success accountActivated button-shadow" style="font-weight: bold; cursor: pointer !important;width: fit-content;border-radius: 30px" /> </br><a href="https://1048144.app.netsuite.com/app/site/hosting/scriptlet.nl?script=1712&deploy=1&start_date=' + contactCreatedDateSplitString + '&last_date=' + lastDay + '&zee=' + customerContactListRow.zeeID + '&custid=' + customerContactListRow.custInternalID + '&freq=daily" target="_blank" style="font-weight: bold; cursor: pointer !important;width: 50%;border-radius: 30px;padding: 2.5%;" class="button-shadow"><i class="fa-solid fa-chart-simple" style="font-size: 25px;color: #337ab7"></i></a>'; } else { var linkURL = '<a href="https://1048144.app.netsuite.com/app/site/hosting/scriptlet.nl?script=1712&deploy=1&start_date=' + contactCreatedDateSplitString + '&last_date=' + lastDay + '&zee=' + customerContactListRemainingRows[x].zeeID + '&custid=' + customerContactListRemainingRows[x].custInternalID + '&freq=daily" target="_blank" style="font-weight: bold; cursor: pointer !important;width: 50%;border-radius: 30px;padding: 2.5%;" class=""><img src="https://1048144.app.netsuite.com/core/media/media.nl?id=6399648&c=1048144&h=IV0eZcpDJAJvpDCshlu59Ny5BQ1HZwqvu2FIRmE9CZHL8AN3" style="height: 3em; width: 3em;"></a>'; } } var customerIDLink = '<a href="https://1048144.app.netsuite.com/app/common/entity/custjob.nl?id=' + customerContactListRemainingRows[x].custInternalID + '&whence=" target="_blank"><b>' + customerContactListRemainingRows[x].custEntityID + '</b></a>'; if (role == 3 || role == 1032) { var contactIdLink = '<a href="https://1048144.app.netsuite.com/app/common/entity/contact.nl?id=' + customerContactListRemainingRows[x].contactInternalId + '&whence=" target="_blank"><b>Edit Contact</b></a>'; // var franchiseeSalesRepAssigned = nlapiLookupField('customer', parseInt(customerContactListRow.contactInternalId), 'partner.custentity_sales_rep_assigned'); // salesRepId = franchiseeSalesRepAssigned; // if (franchiseeSalesRepAssigned == '668712') { // salesRepEmail = 'ychag@example.com'; // salesRepName = 'Belinda Urbani'; // salesRepId = 668712 // } else if (franchiseeSalesRepAssigned == '696160') { // salesRepEmail = 'hzdkv@example.com' // salesRepName = 'Kerina Helliwell'; // salesRepId = 696160 // } else { // salesRepEmail = 'kenaa@example.com'; // salesRepName = 'Lee Russell'; // salesRepId = 668711 // } // var sendSignUpEmail = // '<a data-id="' + // customerContactListRow.custInternalID + // '" data-sales="' + // salesRepId + // '" data-contact="' + // customerContactListRow.contactInternalId + // '" data-contactemail="' + // customerContactListRow.contactEmail + // '" data-contactName="' + // customerContactListRow.contactName + // '" data-contactPhone="' + // customerContactListRow.contactPhone + // '" data-salesrecordid="" style="font-weight: bold; cursor: pointer !important;width: 50%;border-radius: 30px;padding: 2.5%;" class="sendEmail"><button><div class="svg-wrapper-1"><div class="svg-wrapper"><svg height="24" width="24" viewBox="0 0 24 24" xmlns="http://www.w3.org/2000/svg"><path d="M0 0h24v24H0z" fill="none"></path><path d="M1.946 9.315c-.522-.174-.527-.455.01-.634l19.087-6.362c.529-.176.832.12.684.638l-5.454 19.086c-.15.529-.455.547-.679.045L12 14l6-8-8 6-8.054-2.685z" fill="currentColor"></path></svg></div></div><span>Send</span></button></a></br>' + customerContactListRow.contactEmail; } else { var contactIdLink = customerContactListRemainingRows[x].contactInternalId; // var sendSignUpEmail = customerContactListRow.contactEmail; } customerContactListDataSet2.push([linkURL, customerIDLink, customerContactListRemainingRows[x].custName, customerContactListRemainingRows[x].zeeName, contactCreatedDateSplitString, contactIdLink, customerContactListRemainingRows[x].contactName, sendSignUpEmail, customerContactListRemainingRows[x].contactPhone, customerContactListRemainingRows[x].contactCreatePasswordEmail, parseInt(customerContactListRemainingRows[x].contactCreatePasswordEmailCount), customerContactListRemainingRows[x].contactPasswordSetupCompleted, currentStatus ]); csvSet2.push([customerContactListRemainingRows[x].custInternalID, customerContactListRemainingRows[x].custName, customerContactListRemainingRows[x].zeeName, contactCreatedDateSplitString, customerContactListRemainingRows[x].contactInternalId, customerContactListRemainingRows[x].contactName, customerContactListRemainingRows[x].contactEmail, customerContactListRemainingRows[x].contactPhone, customerContactListRemainingRows[x].contactCreatePasswordEmail, customerContactListRemainingRows[x].contactCreatePasswordEmailCount, customerContactListRemainingRows[x].contactPasswordSetupCompleted ]); } // customerContactListRemainingRows.forEach(function (customerContactListRow, index) { // console.log('index: ' + index); // // if (index < displayList) { // // var contactCreatedArray = customerContactListRow.contactCreated.split(' '); // // var contactCreatedDateSplit = contactCreatedArray[0].split('/'); // // if (parseInt(contactCreatedDateSplit[1]) < 10) { // // contactCreatedDateSplit[1] = '0' + contactCreatedDateSplit[1] // // } // // if (parseInt(contactCreatedDateSplit[0]) < 10) { // // contactCreatedDateSplit[0] = '0' + contactCreatedDateSplit[0] // // } // // var contactCreatedDateSplitString = contactCreatedDateSplit[2] + '-' + contactCreatedDateSplit[1] + '-' + // // contactCreatedDateSplit[0]; // // var date_from = dateISOToNetsuite(contactCreatedDateSplitString); // // // console.log('date_from: ' + date_from) // // // console.log('customerContactListRow.custInternalID: ' + customerContactListRow.custInternalID); // // var date = new Date(), y = date.getFullYear(), m = date.getMonth(); // // var firstDay = new Date(y, m, 1); // // var lastDay = new Date(y, m + 1, 0); // // firstDay.setHours(0, 0, 0, 0); // // lastDay.setHours(0, 0, 0, 0); // // firstDay = GetFormattedDate(firstDay); // // lastDay = GetFormattedDate(lastDay); // // var sendSignUpEmail = customerContactListRow.contactEmail; // // if (customerContactListRow.contactCreatePasswordEmail == 'Yes' && customerContactListRow.contactPasswordSetupCompleted == 'Yes') { // // //Search Name: All MP Products - Source/Week // // var mpProductSourcePerWeekSearch = search.load({ // // type: 'customrecord_customer_product_stock', // // id: 'customsearch_prod_stock_usage_report___6' // // }); // // mpProductSourcePerWeekSearch.filters.push(search.createFilter({ // // name: 'internalid', // // join: 'custrecord_cust_prod_stock_customer', // // operator: search.Operator.IS, // // values: parseInt(customerContactListRow.custInternalID) // // })); // // mpProductSourcePerWeekSearch.filters.push(search.createFilter({ // // name: 'custrecord_barcode_source', // // operator: search.Operator.ANYOF, // // values: ["1", "@NONE@"] // // })); // // mpProductSourcePerWeekSearch.filters.push(search.createFilter({ // // name: 'custrecord_cust_date_stock_used', // // join: null, // // operator: search.Operator.ONORAFTER, // // values: date_from // // })); // // customerCountRemainingAccountActivated++; // // console.log('customerCountRemainingAccountActivated: ' + customerCountRemainingAccountActivated) // // var resultRange = mpProductSourcePerWeekSearch.run().getRange({ // // start: 0, // // end: 1 // // }); // // if (resultRange.length == 0) { // // //Search Name: All MP Products - Source/Week // // var mpProductSourcePerWeekSearch = search.load({ // // type: 'customrecord_customer_product_stock', // // id: 'customsearch_prod_stock_usage_report___6' // // }); // // mpProductSourcePerWeekSearch.filters.push(search.createFilter({ // // name: 'internalid', // // join: 'custrecord_cust_prod_stock_customer', // // operator: search.Operator.IS, // // values: parseInt(customerContactListRow.custInternalID) // // })); // // mpProductSourcePerWeekSearch.filters.push(search.createFilter({ // // name: 'custrecord_barcode_source', // // operator: search.Operator.NONEOF, // // values: ["1", "@NONE@"] // // })); // // mpProductSourcePerWeekSearch.filters.push(search.createFilter({ // // name: 'custrecord_cust_date_stock_used', // // join: null, // // operator: search.Operator.ONORAFTER, // // values: date_from // // })); // // console.log('mpProductSourcePerWeekSearch.run(): ' + mpProductSourcePerWeekSearch.run()) // // var resultRange = mpProductSourcePerWeekSearch.run().getRange({ // // start: 0, // // end: 1 // // }); // // if (resultRange.length == 0) { // // var currentStatus = 'NO USAGE' // // // var linkURL = '<a href="https://1048144.app.netsuite.com/app/site/hosting/scriptlet.nl?script=1712&deploy=1&start_date=' + contactCreatedDateSplitString + '&last_date=' + lastDay + '&zee=' + customerContactListRow.zeeID + '&custid=' + customerContactListRow.custInternalID + '&freq=daily" target="_blank" style="font-weight: bold; cursor: pointer !important;width: 50%;border-radius: 30px;padding: 2.5%;" class="button-shadow"><i class="fa-solid fa-chart-simple" style="font-size: 25px;color: #337ab7"></i></a>' // // var linkURL = '<a href="https://1048144.app.netsuite.com/app/site/hosting/scriptlet.nl?script=1712&deploy=1&start_date=' + contactCreatedDateSplitString + '&last_date=' + lastDay + '&zee=' + customerContactListRow.zeeID + '&custid=' + customerContactListRow.custInternalID + '&freq=daily" target="_blank" style="font-weight: bold; cursor: pointer !important;width: 50%;border-radius: 30px;padding: 2.5%;" class=""><img src="https://1048144.app.netsuite.com/core/media/media.nl?id=6399648&c=1048144&h=IV0eZcpDJAJvpDCshlu59Ny5BQ1HZwqvu2FIRmE9CZHL8AN3" style="height: 3em; width: 3em;"></a>' // // } else { // // var currentStatus = 'DIGITAL LABEL' // // var linkURL = '<a href="https://1048144.app.netsuite.com/app/site/hosting/scriptlet.nl?script=1712&deploy=1&start_date=' + contactCreatedDateSplitString + '&last_date=' + lastDay + '&zee=' + customerContactListRow.zeeID + '&custid=' + customerContactListRow.custInternalID + '&freq=daily" target="_blank" style="font-weight: bold; cursor: pointer !important;width: 50%;border-radius: 30px;padding: 2.5%;" class=""><img src="https://1048144.app.netsuite.com/core/media/media.nl?id=6399648&c=1048144&h=IV0eZcpDJAJvpDCshlu59Ny5BQ1HZwqvu2FIRmE9CZHL8AN3" style="height: 3em; width: 3em;"></a>' // // } // // } else { // // var currentStatus = 'MANUAL BARCODES' // // var linkURL = '<a href="https://1048144.app.netsuite.com/app/site/hosting/scriptlet.nl?script=1712&deploy=1&start_date=' + contactCreatedDateSplitString + '&last_date=' + lastDay + '&zee=' + customerContactListRow.zeeID + '&custid=' + customerContactListRow.custInternalID + '&freq=daily" target="_blank" style="font-weight: bold; cursor: pointer !important;width: 50%;border-radius: 30px;padding: 2.5%;" class=""><img src="https://1048144.app.netsuite.com/core/media/media.nl?id=6399648&c=1048144&h=IV0eZcpDJAJvpDCshlu59Ny5BQ1HZwqvu2FIRmE9CZHL8AN3" style="height: 3em; width: 3em;"></a>' // // } // // } else if (customerContactListRow.contactCreatePasswordEmail != 'Yes' && customerContactListRow.contactPasswordSetupCompleted != 'Yes') { // // var linkURL = '' // // var currentStatus = '' // // if (role == 3 || role == 1032) { //Administrator or System Support // // linkURL = // // '<input type="button" id="" data-id="' + // // customerContactListRow.contactInternalId + // // '" value="CREATE PASSWORD EMAIL SENT" class="form-control btn btn-xs btn-primary createPasswordEmail button-shadow" style="font-weight: bold; cursor: pointer !important;width: fit-content;border-radius: 30px" /> </br><a href="https://1048144.app.netsuite.com/app/site/hosting/scriptlet.nl?script=1712&deploy=1&start_date=' + contactCreatedDateSplitString + '&last_date=' + lastDay + '&zee=' + customerContactListRow.zeeID + '&custid=' + customerContactListRow.custInternalID + '&freq=daily" target="_blank" style="font-weight: bold; cursor: pointer !important;width: 50%;border-radius: 30px;padding: 2.5%;" class=""><img src="https://1048144.app.netsuite.com/core/media/media.nl?id=6399648&c=1048144&h=IV0eZcpDJAJvpDCshlu59Ny5BQ1HZwqvu2FIRmE9CZHL8AN3" style="height: 3em; width: 3em;"></a>'; // // } else { // // var linkURL = '<a href="https://1048144.app.netsuite.com/app/site/hosting/scriptlet.nl?script=1712&deploy=1&start_date=' + contactCreatedDateSplitString + '&last_date=' + lastDay + '&zee=' + customerContactListRow.zeeID + '&custid=' + customerContactListRow.custInternalID + '&freq=daily" target="_blank" style="font-weight: bold; cursor: pointer !important;width: 50%;border-radius: 30px;padding: 2.5%;" class=""><img src="https://1048144.app.netsuite.com/core/media/media.nl?id=6399648&c=1048144&h=IV0eZcpDJAJvpDCshlu59Ny5BQ1HZwqvu2FIRmE9CZHL8AN3" style="height: 3em; width: 3em;"></a>' // // } // // } else if (customerContactListRow.contactCreatePasswordEmail == 'Yes' && customerContactListRow.contactPasswordSetupCompleted != 'Yes') { // // var linkURL = '' // // var currentStatus = ''; // // if (role == 3 || role == 1032) { //Administrator or System Support // // linkURL = // // '<input type="button" id="" data-id="' + // // customerContactListRow.contactInternalId + // // '" value="ACTIVATED" class="form-control btn btn-xs btn-success accountActivated button-shadow" style="font-weight: bold; cursor: pointer !important;width: fit-content;border-radius: 30px" /> </br><a href="https://1048144.app.netsuite.com/app/site/hosting/scriptlet.nl?script=1712&deploy=1&start_date=' + contactCreatedDateSplitString + '&last_date=' + lastDay + '&zee=' + customerContactListRow.zeeID + '&custid=' + customerContactListRow.custInternalID + '&freq=daily" target="_blank" style="font-weight: bold; cursor: pointer !important;width: 50%;border-radius: 30px;padding: 2.5%;" class=""><img src="https://1048144.app.netsuite.com/core/media/media.nl?id=6399648&c=1048144&h=IV0eZcpDJAJvpDCshlu59Ny5BQ1HZwqvu2FIRmE9CZHL8AN3" style="height: 3em; width: 3em;"></a>'; // // var franchiseeSalesRepAssigned = nlapiLookupField('customer', parseInt(customerContactListRow.contactInternalId), 'partner.custentity_sales_rep_assigned'); // // salesRepId = franchiseeSalesRepAssigned; // // if (franchiseeSalesRepAssigned == '668712') { // // salesRepEmail = 'ychag@example.com'; // // salesRepName = 'Belinda Urbani'; // // salesRepId = 668712 // // } else if (franchiseeSalesRepAssigned == '696160') { // // salesRepEmail = 'hzdkv@example.com' // // salesRepName = 'Kerina Helliwell'; // // salesRepId = 696160 // // } else { // // salesRepEmail = 'kenaa@example.com'; // // salesRepName = 'Lee Russell'; // // salesRepId = 668711 // // } // // var sendSignUpEmail = // // '<a data-id="' + // // customerContactListRow.custInternalID + // // '" data-sales="' + // // salesRepId + // // '" data-contact="' + // // customerContactListRow.contactInternalId + // // '" data-contactemail="' + // // customerContactListRow.contactEmail + // // '" data-contactName="' + // // customerContactListRow.contactName + // // '" data-contactPhone="' + // // customerContactListRow.contactPhone + // // '" data-salesrecordid="" style="font-weight: bold; cursor: pointer !important;width: 50%;border-radius: 30px;padding: 2.5%;" class="sendEmail"><button class="button-shadow"><div class="svg-wrapper-1"><div class="svg-wrapper"><svg height="24" width="24" viewBox="0 0 24 24" xmlns="http://www.w3.org/2000/svg"><path d="M0 0h24v24H0z" fill="none"></path><path d="M1.946 9.315c-.522-.174-.527-.455.01-.634l19.087-6.362c.529-.176.832.12.684.638l-5.454 19.086c-.15.529-.455.547-.679.045L12 14l6-8-8 6-8.054-2.685z" fill="currentColor"></path></svg></div></div><span>Resend</span></button></a></br></br>' + customerContactListRow.contactEmail; // // // linkURL = // // // '<a href="" class="accountActivated button-shadow" style="cursor: pointer !important;" ><img src="https://1048144.app.netsuite.com/core/media/media.nl?id=6399647&c=1048144&h=RuKYj6ulVT3rxPGWwg3OnnI6wETYrFW3BjGkTbg6dg7ms7wv" style="height: 3em; width: 3em;"></a><input type="button" id="" data-id="' + // // // customerContactListRow.contactInternalId + // // // '" value="ACTIVATED" class="form-control btn btn-xs btn-success accountActivated button-shadow" style="font-weight: bold; cursor: pointer !important;width: fit-content;border-radius: 30px" /> </br><a href="https://1048144.app.netsuite.com/app/site/hosting/scriptlet.nl?script=1712&deploy=1&start_date=' + contactCreatedDateSplitString + '&last_date=' + lastDay + '&zee=' + customerContactListRow.zeeID + '&custid=' + customerContactListRow.custInternalID + '&freq=daily" target="_blank" style="font-weight: bold; cursor: pointer !important;width: 50%;border-radius: 30px;padding: 2.5%;" class="button-shadow"><i class="fa-solid fa-chart-simple" style="font-size: 25px;color: #337ab7"></i></a>'; // // } else { // // var linkURL = '<a href="https://1048144.app.netsuite.com/app/site/hosting/scriptlet.nl?script=1712&deploy=1&start_date=' + contactCreatedDateSplitString + '&last_date=' + lastDay + '&zee=' + customerContactListRow.zeeID + '&custid=' + customerContactListRow.custInternalID + '&freq=daily" target="_blank" style="font-weight: bold; cursor: pointer !important;width: 50%;border-radius: 30px;padding: 2.5%;" class=""><img src="https://1048144.app.netsuite.com/core/media/media.nl?id=6399648&c=1048144&h=IV0eZcpDJAJvpDCshlu59Ny5BQ1HZwqvu2FIRmE9CZHL8AN3" style="height: 3em; width: 3em;"></a>'; // // } // // } // // var customerIDLink = // // '<a href="https://1048144.app.netsuite.com/app/common/entity/custjob.nl?id=' + // // customerContactListRow.custInternalID + '&whence=" target="_blank"><b>' + // // customerContactListRow.custEntityID + '</b></a>'; // // if (role == 3 || role == 1032) { // // var contactIdLink = // // '<a href="https://1048144.app.netsuite.com/app/common/entity/contact.nl?id=' + // // customerContactListRow.contactInternalId + '&whence=" target="_blank"><b>Edit Contact</b></a>'; // // // var franchiseeSalesRepAssigned = nlapiLookupField('customer', parseInt(customerContactListRow.contactInternalId), 'partner.custentity_sales_rep_assigned'); // // // salesRepId = franchiseeSalesRepAssigned; // // // if (franchiseeSalesRepAssigned == '668712') { // // // salesRepEmail = 'ychag@example.com'; // // // salesRepName = 'Belinda Urbani'; // // // salesRepId = 668712 // // // } else if (franchiseeSalesRepAssigned == '696160') { // // // salesRepEmail = 'hzdkv@example.com' // // // salesRepName = 'Kerina Helliwell'; // // // salesRepId = 696160 // // // } else { // // // salesRepEmail = 'kenaa@example.com'; // // // salesRepName = 'Lee Russell'; // // // salesRepId = 668711 // // // } // // // var sendSignUpEmail = // // // '<a data-id="' + // // // customerContactListRow.custInternalID + // // // '" data-sales="' + // // // salesRepId + // // // '" data-contact="' + // // // customerContactListRow.contactInternalId + // // // '" data-contactemail="' + // // // customerContactListRow.contactEmail + // // // '" data-contactName="' + // // // customerContactListRow.contactName + // // // '" data-contactPhone="' + // // // customerContactListRow.contactPhone + // // // '" data-salesrecordid="" style="font-weight: bold; cursor: pointer !important;width: 50%;border-radius: 30px;padding: 2.5%;" class="sendEmail"><button><div class="svg-wrapper-1"><div class="svg-wrapper"><svg height="24" width="24" viewBox="0 0 24 24" xmlns="http://www.w3.org/2000/svg"><path d="M0 0h24v24H0z" fill="none"></path><path d="M1.946 9.315c-.522-.174-.527-.455.01-.634l19.087-6.362c.529-.176.832.12.684.638l-5.454 19.086c-.15.529-.455.547-.679.045L12 14l6-8-8 6-8.054-2.685z" fill="currentColor"></path></svg></div></div><span>Send</span></button></a></br>' + customerContactListRow.contactEmail; // // } else { // // var contactIdLink = customerContactListRow.contactInternalId; // // // var sendSignUpEmail = customerContactListRow.contactEmail; // // } // // customerContactListDataSet2.push([linkURL, // // customerIDLink, // // customerContactListRow.custName, customerContactListRow.zeeName, contactCreatedDateSplitString, contactIdLink, customerContactListRow.contactName, sendSignUpEmail, customerContactListRow.contactPhone, customerContactListRow.contactCreatePasswordEmail, parseInt(customerContactListRow.contactCreatePasswordEmailCount), customerContactListRow.contactPasswordSetupCompleted, currentStatus // // ]); // // csvSet2.push([customerContactListRow.custInternalID, // // customerContactListRow.custName, customerContactListRow.zeeName, contactCreatedDateSplitString, customerContactListRow.contactInternalId, customerContactListRow.contactName, customerContactListRow.contactEmail, customerContactListRow.contactPhone, customerContactListRow.contactCreatePasswordEmail, customerContactListRow.contactCreatePasswordEmailCount, customerContactListRow.contactPasswordSetupCompleted // // ]); // // } // }); } var datatable2 = $('#mpexusage-customer_contact_list_remaining').DataTable(); datatable2.clear(); datatable2.rows.add(customerContactListDataSet2); datatable2.draw(); saveCsv(csvSet2); $('#noUsageCount').val(noUsageCustomerCount); $('#manualUsageCount').val(manualUsageCustomerCount); $('#digitalUsageCount').val(digitalLabelUsageCustomerCount); return true; } /** * Load the string stored in the hidden field 'custpage_table_csv'. * Converts it to a CSV file. * Creates a hidden link to download the file and triggers the click of the link. */ function downloadCsv() { var today = new Date(); today = formatDate(today); var val1 = currentRecord.get(); var csv = val1.getValue({ fieldId: 'custpage_table_csv', }); today = replaceAll(today); var a = document.createElement("a"); document.body.appendChild(a); a.style = "display: none"; var content_type = 'text/csv'; var csvFile = new Blob([csv], { type: content_type }); var url = window.URL.createObjectURL(csvFile); var filename = 'Customer Cancellation List_' + today + '.csv'; a.href = url; a.download = filename; a.click(); window.URL.revokeObjectURL(url); } function getDateStoreNS() { var date = new Date(); if (date.getHours() > 6) { date.setDate(date.getDate() + 1); } format.format({ value: date, type: format.Type.DATE, timezone: format.Timezone.AUSTRALIA_SYDNEY }) return date; } function saveRecord() { return true; } /** * Create the CSV and store it in the hidden field 'custpage_table_csv' as a string. * @param {Array} ordersDataSet The `billsDataSet` created in `loadDatatable()`. */ function saveCsv(ordersDataSet) { var sep = "sep=;"; var headers = ["Customer Internal ID", "Customer Entity ID", "Customer Name", "Franchisee", "Status", "Cancellation Requested Date", "Cancellation Date", "Cancellation Progress" ] headers = headers.join(';'); // .join(', ') var csv = sep + "\n" + headers + "\n"; ordersDataSet.forEach(function (row) { row = row.join(';'); csv += row; csv += "\n"; }); var val1 = currentRecord.get(); val1.setValue({ fieldId: 'custpage_table_csv', value: csv }); return true; } function formatDate(testDate) { console.log('testDate: ' + testDate); var responseDate = format.format({ value: testDate, type: format.Type.DATE }); console.log('responseDate: ' + responseDate); return responseDate; } function replaceAll(string) { return string.split("/").join("-"); } /** * Used to pass the values of `date_from` and `date_to` between the scripts and to Netsuite for the records and the search. * @param {String} date_iso "2020-06-01" * @returns {String} date_netsuite "1/6/2020" */ function dateISOToNetsuite(date_iso) { var date_netsuite = ''; if (!isNullorEmpty(date_iso)) { var date_utc = new Date(date_iso); // var date_netsuite = nlapiDateToString(date_utc); var date_netsuite = format.format({ value: date_utc, type: format.Type.DATE }); } return date_netsuite; } function GetFormattedDate(todayDate) { var month = pad(todayDate.getMonth() + 1); var day = pad(todayDate.getDate()); var year = (todayDate.getFullYear()); return year + "-" + month + "-" + day; } function pad(s) { return (s < 10) ? '0' + s : s; } /** * [getDate description] - Get the current date * @return {[String]} [description] - return the string date */ function getDate() { var date = new Date(); date = format.format({ value: date, type: format.Type.DATE, timezone: format.Timezone.AUSTRALIA_SYDNEY }); return date; } function isNullorEmpty(val) { if (val == '' || val == null) { return true; } else { return false; } } return { pageInit: pageInit, saveRecord: saveRecord, downloadCsv: downloadCsv } });
true
/** * @NApiVersion 2.x * @NScriptType ClientScript * Author: Ankith Ravindran * Created on: Fri May 30 2023 * Modified on: Wed May 31 2023 14:23:11 * SuiteScript Version: 2.0 * Description: Client script for List the contacts that has been registered via the webform to get access to the customer portal. * * Copyright (c) 2023 MailPlus Pty. Ltd. */ define(['N/email', 'N/runtime', 'N/search', 'N/record', 'N/http', 'N/log', 'N/error', 'N/url', 'N/format', 'N/currentRecord' ], function (email, runtime, search, record, http, log, error, url, format, currentRecord) { var zee = 0; var userId = 0; var role = 0; var baseURL = 'https://1048144.app.netsuite.com'; if (runtime.EnvType == "SANDBOX") { baseURL = 'https://1048144-sb3.app.netsuite.com'; } role = runtime.getCurrentUser().role; var userName = runtime.getCurrentUser().name; var userId = runtime.getCurrentUser().id; var currRec = currentRecord.get(); var total_months = 14; var today = new Date(); var today_day_in_month = today.getDate(); var today_day_in_week = today.getDay(); var today_month = today.getMonth() + 1; var today_year = today.getFullYear(); var totalTop50Contacts = 0; var totalReminingContacts = 0; if (today_day_in_month < 10) { today_day_in_month = '0' + today_day_in_month; } if (today_month < 10) { today_month = '0' + (today_month); } var todayString = today_day_in_month + '/' + today_month + '/' + today_year; var current_year_month = today_year + '-' + today_month; var difference_months = total_months - parseInt(today_month); function isWeekday(year, month, day) { var day = new Date(year, month, day).getDay(); return day != 0 && day != 6; } function getWeekdaysInMonth(month, year) { var days = daysInMonth(month, year); var weekdays = 0; for (var i = 0; i < days; i++) { if (isWeekday(year, month, i + 1)) weekdays++; } return weekdays; } function daysInMonth(iMonth, iYear) { return 32 - new Date(iYear, iMonth, 32).getDate(); } function pageLoad() { $('.range_filter_section').addClass('hide'); $('.range_filter_section_top').addClass('hide'); $('.date_filter_section').addClass('hide'); $('.period_dropdown_section').addClass('hide'); $('.loading_section').removeClass('hide'); } function afterSubmit() { $('.loading_section').addClass('hide'); $('.table_section').removeClass('hide'); $('.cust_filter_section').removeClass('hide'); $('.cust_dropdown_section').removeClass('hide'); $('.zee_available_buttons_section').removeClass('hide'); $('.instruction_div').removeClass('hide'); $('.filter_buttons_section').removeClass('hide'); $('.zee_label_section').removeClass('hide'); $('.show_buttons_section').removeClass('hide'); $('.zee_dropdown_section').removeClass('hide'); // $('.tabs_div').removeClass('hide'); $('.paramAccountActivated_label_section').removeClass('hide'); $('.paramAccountActivated_section').removeClass('hide'); $('.customerCountDiv').removeClass('hide'); } var paramUserId = null; function pageInit() { $("#NS_MENU_ID0-item0").css("background-color", "#CFE0CE"); $("#NS_MENU_ID0-item0 a").css("background-color", "#CFE0CE"); $("#body").css("background-color", "#CFE0CE"); $("#tbl_submitter").css("display", "none"); var val1 = currentRecord.get(); paramUserId = val1.getValue({ fieldId: 'custpage_sales_rep_id' }); customerContactListDataSet = []; customerContactListSet = []; customerContactListDataSet2 = []; customerContactListSet2 = []; $("#applyFilter").click(function () { zee = $( '#zee_dropdown option:selected').val(); var paramAccountActivated = $( '#paramAccountActivated_dropdown option:selected').val(); var typeOfCustomer = $( '#typeOfCustomer_dropdown option:selected').val(); var url = baseURL + "/app/site/hosting/scriptlet.nl?script=1745&deploy=1&zee=" + zee + '&activated=' + paramAccountActivated + '&type=' + typeOfCustomer; window.location.href = url; }); $("#clearFilter").click(function () { var url = baseURL + "/app/site/hosting/scriptlet.nl?script=1745&deploy=1" window.location.href = url; }); submitSearch(); var dataTable = $('#mpexusage-customer_contact_list').DataTable(); var dataTable2 = $('#mpexusage-customer_contact_list_remaining').DataTable(); var today = new Date(); var today_year = today.getFullYear(); var today_month = today.getMonth(); var today_day = today.getDate(); /** * Click for Instructions Section Collapse */ $('.collapse').on('shown.bs.collapse', function () { $(".range_filter_section_top").css("padding-top", "500px"); }) $('.collapse').on('hide.bs.collapse', function () { $(".range_filter_section_top").css("padding-top", "0px"); }) $('.createPasswordEmail').click(function () { var contactInternalId = $(this).attr("data-id"); console.log('contactInternalId: ' + contactInternalId); var contactRecord = record.load({ type: record.Type.CONTACT, id: parseInt(contactInternalId), isDynamic: true }); contactRecord.setValue({ fieldId: 'custentity_create_password_email', value: 1 }); contactRecord.save(); var convertLink = 'https://1048144.app.netsuite.com/app/site/hosting/scriptlet.nl?script=1745&deploy=1'; window.location.href = convertLink; }) $('.accountActivated').click(function () { var contactInternalId = $(this).attr("data-id"); console.log('contactInternalId: ' + contactInternalId); var contactRecord = record.load({ type: record.Type.CONTACT, id: parseInt(contactInternalId), isDynamic: true }); contactRecord.setValue({ fieldId: 'custentity_password_setup_completed', value: 1 }); contactRecord.save(); var convertLink = 'https://1048144.app.netsuite.com/app/site/hosting/scriptlet.nl?script=1745&deploy=1'; window.location.href = convertLink; }); $(".displayIncrement").click(function () { console.log('inside display increment'); var val1 = currentRecord.get(); var displayContacts = parseInt(val1.getValue({ fieldId: 'custpage_displaylist', })); var totalContacts = parseInt($('#totalDisplayContacts').val()); // var displayContacts = parseInt($('#displayContacts').val()); zee = $( '#zee_dropdown option:selected').val(); var paramAccountActivated = $( '#paramAccountActivated_dropdown option:selected').val(); var typeOfCustomer = $( '#typeOfCustomer_dropdown option:selected').val(); if (isNullorEmpty(displayContacts)) { } var intialDisplay = (displayContacts + 1); if ((totalContacts - intialDisplay) > 30) { var finalDisplay = intialDisplay + 30; } else { var finalDisplay = totalContacts; } var url = baseURL + "/app/site/hosting/scriptlet.nl?script=1745&deploy=1&zee=" + zee + '&activated=' + paramAccountActivated + '&type=' + typeOfCustomer + '&intial=' + intialDisplay + '&final=' + finalDisplay; window.location.href = url; }); $(".displayDecrement").click(function () { console.log('inside display increment'); var val1 = currentRecord.get(); zee = $( '#zee_dropdown option:selected').val(); var paramAccountActivated = $( '#paramAccountActivated_dropdown option:selected').val(); var typeOfCustomer = $( '#typeOfCustomer_dropdown option:selected').val(); var displayContacts = parseInt(val1.getValue({ fieldId: 'custpage_displaylist', })); var intialDisplay = parseInt(val1.getValue({ fieldId: 'custpage_initialdisplaylist', })); var totalContacts = parseInt($('#totalDisplayContacts').val()); // var displayContacts = parseInt($('#displayContacts').val()); if (!isNullorEmpty(intialDisplay) && intialDisplay != 0) { intialDisplay = intialDisplay - 30; if (intialDisplay == 1) { intialDisplay = 0; } if ((totalContacts - intialDisplay) > 30) { var finalDisplay = intialDisplay + 30; } else { var finalDisplay = totalContacts; } var url = baseURL + "/app/site/hosting/scriptlet.nl?script=1745&deploy=1&zee=" + zee + '&activated=' + paramAccountActivated + '&type=' + typeOfCustomer + '&intial=' + intialDisplay + '&final=' + finalDisplay; window.location.href = url; } else { var url = baseURL + "/app/site/hosting/scriptlet.nl?script=1745&deploy=1&zee=" + zee + '&activated=' + paramAccountActivated + '&type=' + typeOfCustomer; } var url = baseURL + "/app/site/hosting/scriptlet.nl?script=1745&deploy=1&zee=" + zee + '&activated=' + paramAccountActivated + '&type=' + typeOfCustomer + '&intial=' + intialDisplay + '&final=' + finalDisplay; window.location.href = url; }); $(".sendEmail").click(function () { console.log('inside Send Email') var customerInternalId = $(this).attr("data-id"); var salesrepid = $(this).attr("data-sales"); var contactid = $(this).attr("data-contact"); var contactEmail = $(this).attr("data-contactemail"); var contactName = $(this).attr("data-contactname"); var contactPhone = $(this).attr("data-contactphone"); var contactNameArray = contactName.split(' '); var val1 = currentRecord.get(); val1.setValue({ fieldId: 'custpage_customer_id', value: customerInternalId }); val1.setValue({ fieldId: 'custpage_sales_rep_id', value: salesrepid }); val1.setValue({ fieldId: 'custpage_contact_id', value: contactid }); val1.setValue({ fieldId: 'custpage_contact_fname', value: contactNameArray[0] }); val1.setValue({ fieldId: 'custpage_contact_lname', value: contactNameArray[1] }); val1.setValue({ fieldId: 'custpage_contact_email', value: contactEmail }); val1.setValue({ fieldId: 'custpage_contact_phone', value: contactPhone }); $('#submitter').trigger('click'); }); //On click of close icon in the modal $('.close').click(function () { $("#myModal").hide(); }); } //Initialise the DataTable with headers. function submitSearch() { // duringSubmit(); dataTable = $('#mpexusage-customer_contact_list').DataTable({ destroy: true, data: customerContactListDataSet, pageLength: 1000, order: [[4, 'asc'], [3, 'asc']], columns: [{ title: 'USAGE' }, { title: 'ID' }, { title: 'COMPANY NAME' }, { title: 'FRANCHISEE' }, { title: 'CONTACT CREATED' }, { title: 'CONTACT INTERNAL ID' }, { title: 'CONTACT NAME' }, { title: 'CONTACT EMAIL' }, { title: 'CONTACT PHONE' }, { title: 'CREATE PASSWORD EMAIL SENT?' }, { title: 'CREATE PASSWORD EMAIL SENT - COUNT' }, { title: 'ACCOUNT ACTIVATED' }, { title: 'USAGE SOURCE STATUS' }], columnDefs: [{ targets: [2, 3, 9, 10, 11, 12], className: 'bolded' }, { targets: [2], className: 'col-xs-3' }], rowCallback: function (row, data, index) { if (!isNullorEmpty(data[12])) { if (data[12] == 'MANUAL BARCODES') { $('td', row).css('background-color', '#ff9090'); } else if (data[12] == 'DIGITAL LABEL') { $('td', row).css('background-color', '#86c8bc'); } else { $('td', row).css('background-color', '#adcf9f'); } } else if (data[9] == 'Yes' && data[11] == 'Yes') { $('td', row).css('background-color', '#adcf9f'); } else if (data[9] == 'Yes' && data[11] != 'Yes') { if (parseInt(data[10]) == 4) { $('td', row).css('background-color', '#DB6C79'); $('td', row).css('font-weight', 'bold'); $(row).css('outline', 'auto'); } else if (parseInt(data[10]) > 4) { $('td', row).css('background-color', '#B31312'); $('td', row).css('font-weight', 'bold'); $('td', row).css('color', 'white'); $(row).css('outline', 'auto'); } else { $('td', row).css('background-color', '#ffd7a5'); } } } }); dataTable2 = $('#mpexusage-customer_contact_list_remaining').DataTable({ destroy: true, data: customerContactListDataSet2, pageLength: 1000, order: [[4, 'asc'], [3, 'asc']], columns: [{ title: 'USAGE' }, { title: 'ID' }, { title: 'COMPANY NAME' }, { title: 'FRANCHISEE' }, { title: 'CONTACT CREATED' }, { title: 'CONTACT INTERNAL ID' }, { title: 'CONTACT NAME' }, { title: 'CONTACT EMAIL' }, { title: 'CONTACT PHONE' }, { title: 'CREATE PASSWORD EMAIL SENT?' }, { title: 'CREATE PASSWORD EMAIL SENT - COUNT' }, { title: 'ACCOUNT ACTIVATED' }, { title: 'USAGE SOURCE STATUS' }], columnDefs: [{ targets: [2, 3, 9, 10, 11, 12], className: 'bolded' }, { targets: [2], className: 'col-xs-3' }], rowCallback: function (row, data, index) { if (!isNullorEmpty(data[12])) { if (data[12] == 'MANUAL BARCODES') { $('td', row).css('background-color', '#ff9090'); } else if (data[12] == 'DIGITAL LABEL') { $('td', row).css('background-color', '#86c8bc'); } else { $('td', row).css('background-color', '#adcf9f'); } } else if (data[9] == 'Yes' && data[11] == 'Yes') { $('td', row).css('background-color', '#adcf9f'); } else if (data[9] == 'Yes' && data[11] != 'Yes') { if (parseInt(data[10]) == 4) { $('td', row).css('background-color', '#DB6C79'); $('td', row).css('font-weight', 'bold'); $(row).css('outline', 'auto'); } else if (parseInt(data[10]) > 4) { $('td', row).css('background-color', '#B31312'); $('td', row).css('font-weight', 'bold'); $('td', row).css('color', 'white'); $(row).css('outline', 'auto'); } else { $('td', row).css('background-color', '#ffd7a5'); } } } }); loadSearch(); afterSubmit(); } function loadSearch() { zee = $( '#zee_dropdown option:selected').val(); var paramAccountActivated = $( '#paramAccountActivated_dropdown option:selected').val(); var typeOfCustomer = $( '#typeOfCustomer_dropdown option:selected').val(); console.log('paramAccountActivated: ' + paramAccountActivated); if (typeOfCustomer == 1) { if (paramAccountActivated == 1) { //Search Name: Customer Contacts - Mail/Parcel Operator Role var custContactListMailOperatorRoleSearch = search.load({ type: 'customer', id: 'customsearch_cust_contact_mail_parcel__6' }); } else { //Search Name: Customer Contacts - Mail/Parcel Operator Role var custContactListMailOperatorRoleSearch = search.load({ type: 'customer', id: 'customsearch_cust_contact_mail_parcel_ro' }); } if (!isNullorEmpty(zee)) { custContactListMailOperatorRoleSearch.filters.push(search.createFilter({ name: 'partner', join: null, operator: search.Operator.IS, values: zee })); } // if (paramAccountActivated == 1) { // custContactListMailOperatorRoleSearch.filters.push(search.createFilter({ // name: 'custentity_create_password_email', // join: 'contact', // operator: search.Operator.ANYOF, // values: ["1"] // })); // custContactListMailOperatorRoleSearch.filters.push(search.createFilter({ // name: 'custentity_password_setup_completed', // join: 'contact', // operator: search.Operator.ANYOF, // values: ["1"] // })); // } else { // custContactListMailOperatorRoleSearch.filters.push(search.createFilter({ // name: 'custentity_create_password_email', // join: 'contact', // operator: search.Operator.ANYOF, // values: ["1", "@NONE@"] // })); // custContactListMailOperatorRoleSearch.filters.push(search.createFilter({ // name: 'custentity_password_setup_completed', // join: 'contact', // operator: search.Operator.ANYOF, // values: ["@NONE@"] // })); // } custContactListMailOperatorRoleSearch.run().each(function ( custContactListMailOperatorRoleResultSet) { var custInternalID = custContactListMailOperatorRoleResultSet.getValue({ name: 'internalid' }); var custEntityID = custContactListMailOperatorRoleResultSet.getValue({ name: 'entityid' }); var custName = custContactListMailOperatorRoleResultSet.getValue({ name: 'companyname' }); var zeeID = custContactListMailOperatorRoleResultSet.getValue({ name: 'partner' }); var zeeName = custContactListMailOperatorRoleResultSet.getText({ name: 'partner' }); var contactCreated = custContactListMailOperatorRoleResultSet.getValue({ name: 'datecreated', join: "contact", }); var contactInternalId = custContactListMailOperatorRoleResultSet.getValue({ name: "internalid", join: "contact", }); var contactName = custContactListMailOperatorRoleResultSet.getValue({ name: "entityid", join: "contact", }); var contactEmail = custContactListMailOperatorRoleResultSet.getValue({ name: "email", join: "contact", }); var contactPhone = custContactListMailOperatorRoleResultSet.getValue({ name: "phone", join: "contact", }); var contactCreatePasswordEmail = custContactListMailOperatorRoleResultSet.getValue({ name: "custentity_create_password_email", join: "contact", }); if (contactCreatePasswordEmail == 1) { contactCreatePasswordEmail = 'Yes' } else { contactCreatePasswordEmail = '' } var contactPasswordSetupCompleted = custContactListMailOperatorRoleResultSet.getValue({ name: "custentity_password_setup_completed", join: "contact", }); var contactCreatePasswordEmailCount = custContactListMailOperatorRoleResultSet.getValue({ name: "custentity_create_password_email_count", join: "contact", }); if (isNullorEmpty(contactCreatePasswordEmailCount)) { contactCreatePasswordEmailCount = 0; } if (contactPasswordSetupCompleted == 1) { contactPasswordSetupCompleted = 'Yes' } else { contactPasswordSetupCompleted = '' } if (contactCreatePasswordEmailCount == 0 && contactCreatePasswordEmail == 'Yes' && contactPasswordSetupCompleted == 'Yes') { contactCreatePasswordEmailCount = 1; } customerContactListSet.push({ custInternalID: custInternalID, custEntityID: custEntityID, custName: custName, zeeID: zeeID, zeeName: zeeName, contactCreated: contactCreated, contactInternalId: contactInternalId, contactName: contactName, contactEmail: contactEmail, contactPhone: contactPhone, contactCreatePasswordEmail: contactCreatePasswordEmail, contactPasswordSetupCompleted: contactPasswordSetupCompleted, contactCreatePasswordEmailCount: contactCreatePasswordEmailCount }); totalTop50Contacts++; return true; }); console.log(customerContactListSet); } if (typeOfCustomer == 2) { if (paramAccountActivated == 1) { //Search Name: Customer Contacts - Manual Migration - Remaining var custContactListManualMIgrationRemainingSearch = search.load({ type: 'customer', id: 'customsearch_cust_contact_mail_parcel__7' }); } else { //Search Name: Customer Contacts - Manual Migration - Remaining var custContactListManualMIgrationRemainingSearch = search.load({ type: 'customer', id: 'customsearch_cust_contact_mail_parcel__4' }); } if (!isNullorEmpty(zee)) { custContactListManualMIgrationRemainingSearch.filters.push(search.createFilter({ name: 'partner', join: null, operator: search.Operator.IS, values: zee })); } // if (paramAccountActivated == 1) { // custContactListManualMIgrationRemainingSearch.filters.push(search.createFilter({ // name: 'custentity_create_password_email', // join: 'contact', // operator: search.Operator.ANYOF, // values: ["1"] // })); // custContactListManualMIgrationRemainingSearch.filters.push(search.createFilter({ // name: 'custentity_password_setup_completed', // join: 'contact', // operator: search.Operator.ANYOF, // values: ["1"] // })); // } else { // custContactListManualMIgrationRemainingSearch.filters.push(search.createFilter({ // name: 'custentity_create_password_email', // join: 'contact', // operator: search.Operator.ANYOF, // values: ["1", "@NONE@"] // })); // custContactListManualMIgrationRemainingSearch.filters.push(search.createFilter({ // name: 'custentity_password_setup_completed', // join: 'contact', // operator: search.Operator.ANYOF, // values: ["@NONE@"] // })); // } custContactListManualMIgrationRemainingSearch.run().each(function ( custContactListManualMIgrationRemainingSearchRseultSet) { var custInternalID = custContactListManualMIgrationRemainingSearchRseultSet.getValue({ name: 'internalid' }); var custEntityID = custContactListManualMIgrationRemainingSearchRseultSet.getValue({ name: 'entityid' }); var custName = custContactListManualMIgrationRemainingSearchRseultSet.getValue({ name: 'companyname' }); var zeeID = custContactListManualMIgrationRemainingSearchRseultSet.getValue({ name: 'partner' }); var zeeName = custContactListManualMIgrationRemainingSearchRseultSet.getText({ name: 'partner' }); var contactCreated = custContactListManualMIgrationRemainingSearchRseultSet.getValue({ name: 'datecreated', join: "contact", }); var contactInternalId = custContactListManualMIgrationRemainingSearchRseultSet.getValue({ name: "internalid", join: "contact", }); var contactName = custContactListManualMIgrationRemainingSearchRseultSet.getValue({ name: "entityid", join: "contact", }); var contactEmail = custContactListManualMIgrationRemainingSearchRseultSet.getValue({ name: "email", join: "contact", }); var contactPhone = custContactListManualMIgrationRemainingSearchRseultSet.getValue({ name: "phone", join: "contact", }); var contactCreatePasswordEmail = custContactListManualMIgrationRemainingSearchRseultSet.getValue({ name: "custentity_create_password_email", join: "contact", }); if (contactCreatePasswordEmail == 1) { contactCreatePasswordEmail = 'Yes' } else { contactCreatePasswordEmail = '' } var contactPasswordSetupCompleted = custContactListManualMIgrationRemainingSearchRseultSet.getValue({ name: "custentity_password_setup_completed", join: "contact", }); var contactCreatePasswordEmailCount = custContactListManualMIgrationRemainingSearchRseultSet.getValue({ name: "custentity_create_password_email_count", join: "contact", }); if (isNullorEmpty(contactCreatePasswordEmailCount)) { contactCreatePasswordEmailCount = 0; } if (contactPasswordSetupCompleted == 1) { contactPasswordSetupCompleted = 'Yes' } else { contactPasswordSetupCompleted = '' } if (contactCreatePasswordEmailCount == 0 && contactCreatePasswordEmail == 'Yes' && contactPasswordSetupCompleted == 'Yes') { contactCreatePasswordEmailCount = 1; } customerContactListSet2.push({ custInternalID: custInternalID, custEntityID: custEntityID, custName: custName, zeeID: zeeID, zeeName: zeeName, contactCreated: contactCreated, contactInternalId: contactInternalId, contactName: contactName, contactEmail: contactEmail, contactPhone: contactPhone, contactCreatePasswordEmail: contactCreatePasswordEmail, contactPasswordSetupCompleted: contactPasswordSetupCompleted, contactCreatePasswordEmailCount: contactCreatePasswordEmailCount }); totalReminingContacts++; return true; }); console.log(customerContactListSet2) } loadDatatable(customerContactListSet, customerContactListSet2); debt_set = []; } function loadDatatable(customerContactListRows, customerContactListRemainingRows) { customerContactListDataSet = []; csvSet = []; customerContactListDataSet2 = []; csvSet2 = []; var noUsageCustomerCount = 0; var manualUsageCustomerCount = 0; var digitalLabelUsageCustomerCount = 0; var val1 = currentRecord.get(); var paramAccountActivated = $( '#paramAccountActivated_dropdown option:selected').val(); var typeOfCustomer = $( '#typeOfCustomer_dropdown option:selected').val(); var customerCountAccountActivated = 0; if (!isNullorEmpty(customerContactListRows)) { $('#totalDisplayContacts').val(customerContactListRows.length); val1.setValue({ fieldId: 'custpage_totalcontactlist', value: totalDisplayContacts }); customerContactListRows.forEach(function (customerContactListRow, index) { var contactCreatedArray = customerContactListRow.contactCreated.split(' '); var contactCreatedDateSplit = contactCreatedArray[0].split('/'); if (parseInt(contactCreatedDateSplit[1]) < 10) { contactCreatedDateSplit[1] = '0' + contactCreatedDateSplit[1] } if (parseInt(contactCreatedDateSplit[0]) < 10) { contactCreatedDateSplit[0] = '0' + contactCreatedDateSplit[0] } var contactCreatedDateSplitString = contactCreatedDateSplit[2] + '-' + contactCreatedDateSplit[1] + '-' + contactCreatedDateSplit[0]; var date_from = dateISOToNetsuite(contactCreatedDateSplitString); console.log('date_from: ' + date_from) console.log('customerContactListRow.custInternalID: ' + customerContactListRow.custInternalID); var date = new Date(), y = date.getFullYear(), m = date.getMonth(); var firstDay = new Date(y, m, 1); var lastDay = new Date(y, m + 1, 0); firstDay.setHours(0, 0, 0, 0); lastDay.setHours(0, 0, 0, 0); firstDay = GetFormattedDate(firstDay); lastDay = GetFormattedDate(lastDay); var sendSignUpEmail = customerContactListRow.contactEmail; if (customerContactListRow.contactCreatePasswordEmail == 'Yes' && customerContactListRow.contactPasswordSetupCompleted == 'Yes') { //Search Name: All MP Products - Source/Week var mpProductSourcePerWeekSearch = search.load({ type: 'customrecord_customer_product_stock', id: 'customsearch_prod_stock_usage_report___6' }); mpProductSourcePerWeekSearch.filters.push(search.createFilter({ name: 'internalid', join: 'custrecord_cust_prod_stock_customer', operator: search.Operator.IS, values: parseInt(customerContactListRow.custInternalID) })); mpProductSourcePerWeekSearch.filters.push(search.createFilter({ name: 'custrecord_barcode_source', operator: search.Operator.ANYOF, values: ["1", "@NONE@"] })); mpProductSourcePerWeekSearch.filters.push(search.createFilter({ name: 'custrecord_cust_date_stock_used', join: null, operator: search.Operator.ONORAFTER, values: date_from })); customerCountAccountActivated++; console.log('customerCountAccountActivated: ' + customerCountAccountActivated) var resultRange = mpProductSourcePerWeekSearch.run().getRange({ start: 0, end: 1 }); if (resultRange.length == 0) { //Search Name: All MP Products - Source/Week var mpProductSourcePerWeekSearch = search.load({ type: 'customrecord_customer_product_stock', id: 'customsearch_prod_stock_usage_report___6' }); mpProductSourcePerWeekSearch.filters.push(search.createFilter({ name: 'internalid', join: 'custrecord_cust_prod_stock_customer', operator: search.Operator.IS, values: parseInt(customerContactListRow.custInternalID) })); mpProductSourcePerWeekSearch.filters.push(search.createFilter({ name: 'custrecord_barcode_source', operator: search.Operator.NONEOF, values: ["1", "@NONE@"] })); mpProductSourcePerWeekSearch.filters.push(search.createFilter({ name: 'custrecord_cust_date_stock_used', join: null, operator: search.Operator.ONORAFTER, values: date_from })); console.log('mpProductSourcePerWeekSearch.run(): ' + mpProductSourcePerWeekSearch.run()) var resultRange = mpProductSourcePerWeekSearch.run().getRange({ start: 0, end: 1 }); if (resultRange.length == 0) { var currentStatus = 'NO USAGE'; noUsageCustomerCount++; // var linkURL = '<a href="https://1048144.app.netsuite.com/app/site/hosting/scriptlet.nl?script=1712&deploy=1&start_date=' + contactCreatedDateSplitString + '&last_date=' + lastDay + '&zee=' + customerContactListRow.zeeID + '&custid=' + customerContactListRow.custInternalID + '&freq=daily" target="_blank" style="font-weight: bold; cursor: pointer !important;width: 50%;border-radius: 30px;padding: 2.5%;" class="button-shadow"><i class="fa-solid fa-chart-simple" style="font-size: 25px;color: #337ab7"></i></a>' var linkURL = '<a href="https://1048144.app.netsuite.com/app/site/hosting/scriptlet.nl?script=1712&deploy=1&start_date=' + contactCreatedDateSplitString + '&last_date=' + lastDay + '&zee=' + customerContactListRow.zeeID + '&custid=' + customerContactListRow.custInternalID + '&freq=daily" target="_blank" style="font-weight: bold; cursor: pointer !important;width: 50%;border-radius: 30px;padding: 2.5%;" class=""><img src="https://1048144.app.netsuite.com/core/media/media.nl?id=6399648&c=1048144&h=IV0eZcpDJAJvpDCshlu59Ny5BQ1HZwqvu2FIRmE9CZHL8AN3" style="height: 3em; width: 3em;"></a>' } else { var currentStatus = 'DIGITAL LABEL' digitalLabelUsageCustomerCount++; var linkURL = '<a href="https://1048144.app.netsuite.com/app/site/hosting/scriptlet.nl?script=1712&deploy=1&start_date=' + contactCreatedDateSplitString + '&last_date=' + lastDay + '&zee=' + customerContactListRow.zeeID + '&custid=' + customerContactListRow.custInternalID + '&freq=daily" target="_blank" style="font-weight: bold; cursor: pointer !important;width: 50%;border-radius: 30px;padding: 2.5%;" class=""><img src="https://1048144.app.netsuite.com/core/media/media.nl?id=6399648&c=1048144&h=IV0eZcpDJAJvpDCshlu59Ny5BQ1HZwqvu2FIRmE9CZHL8AN3" style="height: 3em; width: 3em;"></a>' } } else { var currentStatus = 'MANUAL BARCODES'; manualUsageCustomerCount++; var linkURL = '<a href="https://1048144.app.netsuite.com/app/site/hosting/scriptlet.nl?script=1712&deploy=1&start_date=' + contactCreatedDateSplitString + '&last_date=' + lastDay + '&zee=' + customerContactListRow.zeeID + '&custid=' + customerContactListRow.custInternalID + '&freq=daily" target="_blank" style="font-weight: bold; cursor: pointer !important;width: 50%;border-radius: 30px;padding: 2.5%;" class=""><img src="https://1048144.app.netsuite.com/core/media/media.nl?id=6399648&c=1048144&h=IV0eZcpDJAJvpDCshlu59Ny5BQ1HZwqvu2FIRmE9CZHL8AN3" style="height: 3em; width: 3em;"></a>' } } else if (customerContactListRow.contactCreatePasswordEmail != 'Yes' && customerContactListRow.contactPasswordSetupCompleted != 'Yes') { var linkURL = '' var currentStatus = '' if (role == 3 || role == 1032) { //Administrator or System Support linkURL = '<input type="button" id="" data-id="' + customerContactListRow.contactInternalId + '" value="CREATE PASSWORD EMAIL SENT" class="form-control btn btn-xs btn-primary createPasswordEmail button-shadow" style="font-weight: bold; cursor: pointer !important;width: fit-content;border-radius: 30px" /> </br><a href="https://1048144.app.netsuite.com/app/site/hosting/scriptlet.nl?script=1712&deploy=1&start_date=' + contactCreatedDateSplitString + '&last_date=' + lastDay + '&zee=' + customerContactListRow.zeeID + '&custid=' + customerContactListRow.custInternalID + '&freq=daily" target="_blank" style="font-weight: bold; cursor: pointer !important;width: 50%;border-radius: 30px;padding: 2.5%;" class=""><img src="https://1048144.app.netsuite.com/core/media/media.nl?id=6399648&c=1048144&h=IV0eZcpDJAJvpDCshlu59Ny5BQ1HZwqvu2FIRmE9CZHL8AN3" style="height: 3em; width: 3em;"></a>'; } else { var linkURL = '<a href="https://1048144.app.netsuite.com/app/site/hosting/scriptlet.nl?script=1712&deploy=1&start_date=' + contactCreatedDateSplitString + '&last_date=' + lastDay + '&zee=' + customerContactListRow.zeeID + '&custid=' + customerContactListRow.custInternalID + '&freq=daily" target="_blank" style="font-weight: bold; cursor: pointer !important;width: 50%;border-radius: 30px;padding: 2.5%;" class=""><img src="https://1048144.app.netsuite.com/core/media/media.nl?id=6399648&c=1048144&h=IV0eZcpDJAJvpDCshlu59Ny5BQ1HZwqvu2FIRmE9CZHL8AN3" style="height: 3em; width: 3em;"></a>' } } else if (customerContactListRow.contactCreatePasswordEmail == 'Yes' && customerContactListRow.contactPasswordSetupCompleted != 'Yes') { var linkURL = '' var currentStatus = ''; if (role == 3 || role == 1032) { //Administrator or System Support linkURL = '<input type="button" id="" data-id="' + customerContactListRow.contactInternalId + '" value="ACTIVATED" class="form-control btn btn-xs btn-success accountActivated button-shadow" style="font-weight: bold; cursor: pointer !important;width: fit-content;border-radius: 30px" /> </br><a href="https://1048144.app.netsuite.com/app/site/hosting/scriptlet.nl?script=1712&deploy=1&start_date=' + contactCreatedDateSplitString + '&last_date=' + lastDay + '&zee=' + customerContactListRow.zeeID + '&custid=' + customerContactListRow.custInternalID + '&freq=daily" target="_blank" style="font-weight: bold; cursor: pointer !important;width: 50%;border-radius: 30px;padding: 2.5%;" class=""><img src="https://1048144.app.netsuite.com/core/media/media.nl?id=6399648&c=1048144&h=IV0eZcpDJAJvpDCshlu59Ny5BQ1HZwqvu2FIRmE9CZHL8AN3" style="height: 3em; width: 3em;"></a>'; var franchiseeSalesRepAssigned = nlapiLookupField('customer', parseInt(customerContactListRow.contactInternalId), 'partner.custentity_sales_rep_assigned'); salesRepId = franchiseeSalesRepAssigned; if (franchiseeSalesRepAssigned == '668712') { salesRepEmail = 'PI:EMAIL:ychag@example.comEND_PI'; salesRepName = 'Belinda Urbani'; salesRepId = 668712 } else if (franchiseeSalesRepAssigned == '696160') { salesRepEmail = 'PI:EMAIL:hzdkv@example.comEND_PI' salesRepName = 'Kerina Helliwell'; salesRepId = 696160 } else { salesRepEmail = 'PI:EMAIL:kenaa@example.comEND_PI'; salesRepName = 'Lee Russell'; salesRepId = 668711 } var sendSignUpEmail = '<a data-id="' + customerContactListRow.custInternalID + '" data-sales="' + salesRepId + '" data-contact="' + customerContactListRow.contactInternalId + '" data-contactemail="' + customerContactListRow.contactEmail + '" data-contactName="' + customerContactListRow.contactName + '" data-contactPhone="' + customerContactListRow.contactPhone + '" data-salesrecordid="" style="font-weight: bold; cursor: pointer !important;width: 50%;border-radius: 30px;padding: 2.5%;" class="sendEmail"><button class="button-shadow"><div class="svg-wrapper-1"><div class="svg-wrapper"><svg height="24" width="24" viewBox="0 0 24 24" xmlns="http://www.w3.org/2000/svg"><path d="M0 0h24v24H0z" fill="none"></path><path d="M1.946 9.315c-.522-.174-.527-.455.01-.634l19.087-6.362c.529-.176.832.12.684.638l-5.454 19.086c-.15.529-.455.547-.679.045L12 14l6-8-8 6-8.054-2.685z" fill="currentColor"></path></svg></div></div><span>Resend</span></button></a></br></br>' + customerContactListRow.contactEmail; // linkURL = // '<a href="" class="accountActivated button-shadow" style="cursor: pointer !important;" ><img src="https://1048144.app.netsuite.com/core/media/media.nl?id=6399647&c=1048144&h=RuKYj6ulVT3rxPGWwg3OnnI6wETYrFW3BjGkTbg6dg7ms7wv" style="height: 3em; width: 3em;"></a><input type="button" id="" data-id="' + // customerContactListRow.contactInternalId + // '" value="ACTIVATED" class="form-control btn btn-xs btn-success accountActivated button-shadow" style="font-weight: bold; cursor: pointer !important;width: fit-content;border-radius: 30px" /> </br><a href="https://1048144.app.netsuite.com/app/site/hosting/scriptlet.nl?script=1712&deploy=1&start_date=' + contactCreatedDateSplitString + '&last_date=' + lastDay + '&zee=' + customerContactListRow.zeeID + '&custid=' + customerContactListRow.custInternalID + '&freq=daily" target="_blank" style="font-weight: bold; cursor: pointer !important;width: 50%;border-radius: 30px;padding: 2.5%;" class="button-shadow"><i class="fa-solid fa-chart-simple" style="font-size: 25px;color: #337ab7"></i></a>'; } else { var linkURL = '<a href="https://1048144.app.netsuite.com/app/site/hosting/scriptlet.nl?script=1712&deploy=1&start_date=' + contactCreatedDateSplitString + '&last_date=' + lastDay + '&zee=' + customerContactListRow.zeeID + '&custid=' + customerContactListRow.custInternalID + '&freq=daily" target="_blank" style="font-weight: bold; cursor: pointer !important;width: 50%;border-radius: 30px;padding: 2.5%;" class=""><img src="https://1048144.app.netsuite.com/core/media/media.nl?id=6399648&c=1048144&h=IV0eZcpDJAJvpDCshlu59Ny5BQ1HZwqvu2FIRmE9CZHL8AN3" style="height: 3em; width: 3em;"></a>'; } } var customerIDLink = '<a href="https://1048144.app.netsuite.com/app/common/entity/custjob.nl?id=' + customerContactListRow.custInternalID + '&whence=" target="_blank"><b>' + customerContactListRow.custEntityID + '</b></a>'; if (role == 3 || role == 1032) { var contactIdLink = '<a href="https://1048144.app.netsuite.com/app/common/entity/contact.nl?id=' + customerContactListRow.contactInternalId + '&whence=" target="_blank"><b>Edit Contact</b></a>'; // var franchiseeSalesRepAssigned = nlapiLookupField('customer', parseInt(customerContactListRow.contactInternalId), 'partner.custentity_sales_rep_assigned'); // salesRepId = franchiseeSalesRepAssigned; // if (franchiseeSalesRepAssigned == '668712') { // salesRepEmail = 'PI:EMAIL:ychag@example.comEND_PI'; // salesRepName = 'Belinda Urbani'; // salesRepId = 668712 // } else if (franchiseeSalesRepAssigned == '696160') { // salesRepEmail = 'PI:EMAIL:hzdkv@example.comEND_PI' // salesRepName = 'Kerina Helliwell'; // salesRepId = 696160 // } else { // salesRepEmail = 'PI:EMAIL:kenaa@example.comEND_PI'; // salesRepName = 'Lee Russell'; // salesRepId = 668711 // } // var sendSignUpEmail = // '<a data-id="' + // customerContactListRow.custInternalID + // '" data-sales="' + // salesRepId + // '" data-contact="' + // customerContactListRow.contactInternalId + // '" data-contactemail="' + // customerContactListRow.contactEmail + // '" data-contactName="' + // customerContactListRow.contactName + // '" data-contactPhone="' + // customerContactListRow.contactPhone + // '" data-salesrecordid="" style="font-weight: bold; cursor: pointer !important;width: 50%;border-radius: 30px;padding: 2.5%;" class="sendEmail"><button><div class="svg-wrapper-1"><div class="svg-wrapper"><svg height="24" width="24" viewBox="0 0 24 24" xmlns="http://www.w3.org/2000/svg"><path d="M0 0h24v24H0z" fill="none"></path><path d="M1.946 9.315c-.522-.174-.527-.455.01-.634l19.087-6.362c.529-.176.832.12.684.638l-5.454 19.086c-.15.529-.455.547-.679.045L12 14l6-8-8 6-8.054-2.685z" fill="currentColor"></path></svg></div></div><span>Send</span></button></a></br>' + customerContactListRow.contactEmail; } else { var contactIdLink = customerContactListRow.contactInternalId; // var sendSignUpEmail = customerContactListRow.contactEmail; } customerContactListDataSet.push([linkURL, customerIDLink, customerContactListRow.custName, customerContactListRow.zeeName, contactCreatedDateSplitString, contactIdLink, customerContactListRow.contactName, sendSignUpEmail, customerContactListRow.contactPhone, customerContactListRow.contactCreatePasswordEmail, parseInt(customerContactListRow.contactCreatePasswordEmailCount), customerContactListRow.contactPasswordSetupCompleted, currentStatus ]); csvSet.push([customerContactListRow.custInternalID, customerContactListRow.custName, customerContactListRow.zeeName, contactCreatedDateSplitString, customerContactListRow.contactInternalId, customerContactListRow.contactName, customerContactListRow.contactEmail, customerContactListRow.contactPhone, customerContactListRow.contactCreatePasswordEmail, customerContactListRow.contactCreatePasswordEmailCount, customerContactListRow.contactPasswordSetupCompleted ]); }); } var datatable = $('#mpexusage-customer_contact_list').DataTable(); datatable.clear(); datatable.rows.add(customerContactListDataSet); datatable.draw(); saveCsv(csvSet); var customerCountRemainingAccountActivated = 0; if (!isNullorEmpty(customerContactListRemainingRows)) { var customerContactListRemainingLength = customerContactListRemainingRows.length; $('#totalDisplayContacts').val(customerContactListRemainingLength); val1.setValue({ fieldId: 'custpage_totalcontactlist', value: customerContactListRemainingLength }); console.log('customerContactListRemainingLength: ' + customerContactListRemainingLength); var intialDisplay = 0; var displayList = 0; if (customerContactListRemainingLength <= 30) { displayList = customerContactListRemainingLength; val1.setValue({ fieldId: 'custpage_displaylist', value: displayList }); $('#displayContacts').val(intialDisplay + ' - ' + displayList); } else if (customerContactListRemainingLength > 30) { var initialDisplayNumber = val1.getValue({ fieldId: 'custpage_initialdisplaylist', }); var finalDisplayListNumber = val1.getValue({ fieldId: 'custpage_displaylist', }); if (isNullorEmpty(finalDisplayListNumber) || initialDisplayNumber == 0) { displayList = 30; val1.setValue({ fieldId: 'custpage_displaylist', value: displayList }); $('#displayContacts').val('(' + intialDisplay + ' - ' + displayList + ') / ' + customerContactListRemainingLength); } else if (initialDisplayNumber > 30) { intialDisplay = initialDisplayNumber - 1; displayList = finalDisplayListNumber; val1.setValue({ fieldId: 'custpage_displaylist', value: displayList }); $('#displayContacts').val('(' + intialDisplay + ' - ' + displayList + ') / ' + customerContactListRemainingLength); } } console.log('intialDisplay: ' + intialDisplay); console.log('displayList: ' + displayList); for (var x = intialDisplay; x < displayList; x++) { console.log('x: ' + x); var contactCreatedArray = customerContactListRemainingRows[x].contactCreated.split(' '); var contactCreatedDateSplit = contactCreatedArray[0].split('/'); if (parseInt(contactCreatedDateSplit[1]) < 10) { contactCreatedDateSplit[1] = '0' + contactCreatedDateSplit[1] } if (parseInt(contactCreatedDateSplit[0]) < 10) { contactCreatedDateSplit[0] = '0' + contactCreatedDateSplit[0] } var contactCreatedDateSplitString = contactCreatedDateSplit[2] + '-' + contactCreatedDateSplit[1] + '-' + contactCreatedDateSplit[0]; var date_from = dateISOToNetsuite(contactCreatedDateSplitString); // console.log('date_from: ' + date_from) // console.log('customerContactListRow.custInternalID: ' + customerContactListRow.custInternalID); var date = new Date(), y = date.getFullYear(), m = date.getMonth(); var firstDay = new Date(y, m, 1); var lastDay = new Date(y, m + 1, 0); firstDay.setHours(0, 0, 0, 0); lastDay.setHours(0, 0, 0, 0); firstDay = GetFormattedDate(firstDay); lastDay = GetFormattedDate(lastDay); var sendSignUpEmail = customerContactListRemainingRows[x].contactEmail; if (customerContactListRemainingRows[x].contactCreatePasswordEmail == 'Yes' && customerContactListRemainingRows[x].contactPasswordSetupCompleted == 'Yes') { //Search Name: All MP Products - Source/Week var mpProductSourcePerWeekSearch = search.load({ type: 'customrecord_customer_product_stock', id: 'customsearch_prod_stock_usage_report___6' }); mpProductSourcePerWeekSearch.filters.push(search.createFilter({ name: 'internalid', join: 'custrecord_cust_prod_stock_customer', operator: search.Operator.IS, values: parseInt(customerContactListRemainingRows[x].custInternalID) })); mpProductSourcePerWeekSearch.filters.push(search.createFilter({ name: 'custrecord_barcode_source', operator: search.Operator.ANYOF, values: ["1", "@NONE@"] })); mpProductSourcePerWeekSearch.filters.push(search.createFilter({ name: 'custrecord_cust_date_stock_used', join: null, operator: search.Operator.ONORAFTER, values: date_from })); customerCountRemainingAccountActivated++; console.log('customerCountRemainingAccountActivated: ' + customerCountRemainingAccountActivated) var resultRange = mpProductSourcePerWeekSearch.run().getRange({ start: 0, end: 1 }); if (resultRange.length == 0) { //Search Name: All MP Products - Source/Week var mpProductSourcePerWeekSearch = search.load({ type: 'customrecord_customer_product_stock', id: 'customsearch_prod_stock_usage_report___6' }); mpProductSourcePerWeekSearch.filters.push(search.createFilter({ name: 'internalid', join: 'custrecord_cust_prod_stock_customer', operator: search.Operator.IS, values: parseInt(customerContactListRemainingRows[x].custInternalID) })); mpProductSourcePerWeekSearch.filters.push(search.createFilter({ name: 'custrecord_barcode_source', operator: search.Operator.NONEOF, values: ["1", "@NONE@"] })); mpProductSourcePerWeekSearch.filters.push(search.createFilter({ name: 'custrecord_cust_date_stock_used', join: null, operator: search.Operator.ONORAFTER, values: date_from })); console.log('mpProductSourcePerWeekSearch.run(): ' + mpProductSourcePerWeekSearch.run()) var resultRange = mpProductSourcePerWeekSearch.run().getRange({ start: 0, end: 1 }); if (resultRange.length == 0) { var currentStatus = 'NO USAGE'; noUsageCustomerCount++; // var linkURL = '<a href="https://1048144.app.netsuite.com/app/site/hosting/scriptlet.nl?script=1712&deploy=1&start_date=' + contactCreatedDateSplitString + '&last_date=' + lastDay + '&zee=' + customerContactListRow.zeeID + '&custid=' + customerContactListRow.custInternalID + '&freq=daily" target="_blank" style="font-weight: bold; cursor: pointer !important;width: 50%;border-radius: 30px;padding: 2.5%;" class="button-shadow"><i class="fa-solid fa-chart-simple" style="font-size: 25px;color: #337ab7"></i></a>' var linkURL = '<a href="https://1048144.app.netsuite.com/app/site/hosting/scriptlet.nl?script=1712&deploy=1&start_date=' + contactCreatedDateSplitString + '&last_date=' + lastDay + '&zee=' + customerContactListRemainingRows[x].zeeID + '&custid=' + customerContactListRemainingRows[x].custInternalID + '&freq=daily" target="_blank" style="font-weight: bold; cursor: pointer !important;width: 50%;border-radius: 30px;padding: 2.5%;" class=""><img src="https://1048144.app.netsuite.com/core/media/media.nl?id=6399648&c=1048144&h=IV0eZcpDJAJvpDCshlu59Ny5BQ1HZwqvu2FIRmE9CZHL8AN3" style="height: 3em; width: 3em;"></a>' } else { var currentStatus = 'DIGITAL LABEL' digitalLabelUsageCustomerCount++; var linkURL = '<a href="https://1048144.app.netsuite.com/app/site/hosting/scriptlet.nl?script=1712&deploy=1&start_date=' + contactCreatedDateSplitString + '&last_date=' + lastDay + '&zee=' + customerContactListRemainingRows[x].zeeID + '&custid=' + customerContactListRemainingRows[x].custInternalID + '&freq=daily" target="_blank" style="font-weight: bold; cursor: pointer !important;width: 50%;border-radius: 30px;padding: 2.5%;" class=""><img src="https://1048144.app.netsuite.com/core/media/media.nl?id=6399648&c=1048144&h=IV0eZcpDJAJvpDCshlu59Ny5BQ1HZwqvu2FIRmE9CZHL8AN3" style="height: 3em; width: 3em;"></a>' } } else { var currentStatus = 'MANUAL BARCODES'; manualUsageCustomerCount++; var linkURL = '<a href="https://1048144.app.netsuite.com/app/site/hosting/scriptlet.nl?script=1712&deploy=1&start_date=' + contactCreatedDateSplitString + '&last_date=' + lastDay + '&zee=' + customerContactListRemainingRows[x].zeeID + '&custid=' + customerContactListRemainingRows[x].custInternalID + '&freq=daily" target="_blank" style="font-weight: bold; cursor: pointer !important;width: 50%;border-radius: 30px;padding: 2.5%;" class=""><img src="https://1048144.app.netsuite.com/core/media/media.nl?id=6399648&c=1048144&h=IV0eZcpDJAJvpDCshlu59Ny5BQ1HZwqvu2FIRmE9CZHL8AN3" style="height: 3em; width: 3em;"></a>' } } else if (customerContactListRemainingRows[x].contactCreatePasswordEmail != 'Yes' && customerContactListRemainingRows[x].contactPasswordSetupCompleted != 'Yes') { var linkURL = '' var currentStatus = '' if (role == 3 || role == 1032) { //Administrator or System Support linkURL = '<input type="button" id="" data-id="' + customerContactListRemainingRows[x].contactInternalId + '" value="CREATE PASSWORD EMAIL SENT" class="form-control btn btn-xs btn-primary createPasswordEmail button-shadow" style="font-weight: bold; cursor: pointer !important;width: fit-content;border-radius: 30px" /> </br><a href="https://1048144.app.netsuite.com/app/site/hosting/scriptlet.nl?script=1712&deploy=1&start_date=' + contactCreatedDateSplitString + '&last_date=' + lastDay + '&zee=' + customerContactListRemainingRows[x].zeeID + '&custid=' + customerContactListRemainingRows[x].custInternalID + '&freq=daily" target="_blank" style="font-weight: bold; cursor: pointer !important;width: 50%;border-radius: 30px;padding: 2.5%;" class=""><img src="https://1048144.app.netsuite.com/core/media/media.nl?id=6399648&c=1048144&h=IV0eZcpDJAJvpDCshlu59Ny5BQ1HZwqvu2FIRmE9CZHL8AN3" style="height: 3em; width: 3em;"></a>'; } else { var linkURL = '<a href="https://1048144.app.netsuite.com/app/site/hosting/scriptlet.nl?script=1712&deploy=1&start_date=' + contactCreatedDateSplitString + '&last_date=' + lastDay + '&zee=' + customerContactListRow.zeeID + '&custid=' + customerContactListRemainingRows[x].custInternalID + '&freq=daily" target="_blank" style="font-weight: bold; cursor: pointer !important;width: 50%;border-radius: 30px;padding: 2.5%;" class=""><img src="https://1048144.app.netsuite.com/core/media/media.nl?id=6399648&c=1048144&h=IV0eZcpDJAJvpDCshlu59Ny5BQ1HZwqvu2FIRmE9CZHL8AN3" style="height: 3em; width: 3em;"></a>' } } else if (customerContactListRemainingRows[x].contactCreatePasswordEmail == 'Yes' && customerContactListRemainingRows[x].contactPasswordSetupCompleted != 'Yes') { var linkURL = '' var currentStatus = ''; if (role == 3 || role == 1032) { //Administrator or System Support linkURL = '<input type="button" id="" data-id="' + customerContactListRemainingRows[x].contactInternalId + '" value="ACTIVATED" class="form-control btn btn-xs btn-success accountActivated button-shadow" style="font-weight: bold; cursor: pointer !important;width: fit-content;border-radius: 30px" /> </br><a href="https://1048144.app.netsuite.com/app/site/hosting/scriptlet.nl?script=1712&deploy=1&start_date=' + contactCreatedDateSplitString + '&last_date=' + lastDay + '&zee=' + customerContactListRemainingRows[x].zeeID + '&custid=' + customerContactListRemainingRows[x].custInternalID + '&freq=daily" target="_blank" style="font-weight: bold; cursor: pointer !important;width: 50%;border-radius: 30px;padding: 2.5%;" class=""><img src="https://1048144.app.netsuite.com/core/media/media.nl?id=6399648&c=1048144&h=IV0eZcpDJAJvpDCshlu59Ny5BQ1HZwqvu2FIRmE9CZHL8AN3" style="height: 3em; width: 3em;"></a>'; var franchiseeSalesRepAssigned = nlapiLookupField('customer', parseInt(customerContactListRemainingRows[x].contactInternalId), 'partner.custentity_sales_rep_assigned'); salesRepId = franchiseeSalesRepAssigned; if (franchiseeSalesRepAssigned == '668712') { salesRepEmail = 'PI:EMAIL:ychag@example.comEND_PI'; salesRepName = 'Belinda Urbani'; salesRepId = 668712 } else if (franchiseeSalesRepAssigned == '696160') { salesRepEmail = 'PI:EMAIL:hzdkv@example.comEND_PI' salesRepName = 'Kerina Helliwell'; salesRepId = 696160 } else { salesRepEmail = 'PI:EMAIL:kenaa@example.comEND_PI'; salesRepName = 'Lee Russell'; salesRepId = 668711 } var sendSignUpEmail = '<a data-id="' + customerContactListRemainingRows[x].custInternalID + '" data-sales="' + salesRepId + '" data-contact="' + customerContactListRemainingRows[x].contactInternalId + '" data-contactemail="' + customerContactListRemainingRows[x].contactEmail + '" data-contactName="' + customerContactListRemainingRows[x].contactName + '" data-contactPhone="' + customerContactListRemainingRows[x].contactPhone + '" data-salesrecordid="" style="font-weight: bold; cursor: pointer !important;width: 50%;border-radius: 30px;padding: 2.5%;" class="sendEmail"><button class="button-shadow"><div class="svg-wrapper-1"><div class="svg-wrapper"><svg height="24" width="24" viewBox="0 0 24 24" xmlns="http://www.w3.org/2000/svg"><path d="M0 0h24v24H0z" fill="none"></path><path d="M1.946 9.315c-.522-.174-.527-.455.01-.634l19.087-6.362c.529-.176.832.12.684.638l-5.454 19.086c-.15.529-.455.547-.679.045L12 14l6-8-8 6-8.054-2.685z" fill="currentColor"></path></svg></div></div><span>Resend</span></button></a></br></br>' + customerContactListRemainingRows[x].contactEmail; // linkURL = // '<a href="" class="accountActivated button-shadow" style="cursor: pointer !important;" ><img src="https://1048144.app.netsuite.com/core/media/media.nl?id=6399647&c=1048144&h=RuKYj6ulVT3rxPGWwg3OnnI6wETYrFW3BjGkTbg6dg7ms7wv" style="height: 3em; width: 3em;"></a><input type="button" id="" data-id="' + // customerContactListRow.contactInternalId + // '" value="ACTIVATED" class="form-control btn btn-xs btn-success accountActivated button-shadow" style="font-weight: bold; cursor: pointer !important;width: fit-content;border-radius: 30px" /> </br><a href="https://1048144.app.netsuite.com/app/site/hosting/scriptlet.nl?script=1712&deploy=1&start_date=' + contactCreatedDateSplitString + '&last_date=' + lastDay + '&zee=' + customerContactListRow.zeeID + '&custid=' + customerContactListRow.custInternalID + '&freq=daily" target="_blank" style="font-weight: bold; cursor: pointer !important;width: 50%;border-radius: 30px;padding: 2.5%;" class="button-shadow"><i class="fa-solid fa-chart-simple" style="font-size: 25px;color: #337ab7"></i></a>'; } else { var linkURL = '<a href="https://1048144.app.netsuite.com/app/site/hosting/scriptlet.nl?script=1712&deploy=1&start_date=' + contactCreatedDateSplitString + '&last_date=' + lastDay + '&zee=' + customerContactListRemainingRows[x].zeeID + '&custid=' + customerContactListRemainingRows[x].custInternalID + '&freq=daily" target="_blank" style="font-weight: bold; cursor: pointer !important;width: 50%;border-radius: 30px;padding: 2.5%;" class=""><img src="https://1048144.app.netsuite.com/core/media/media.nl?id=6399648&c=1048144&h=IV0eZcpDJAJvpDCshlu59Ny5BQ1HZwqvu2FIRmE9CZHL8AN3" style="height: 3em; width: 3em;"></a>'; } } var customerIDLink = '<a href="https://1048144.app.netsuite.com/app/common/entity/custjob.nl?id=' + customerContactListRemainingRows[x].custInternalID + '&whence=" target="_blank"><b>' + customerContactListRemainingRows[x].custEntityID + '</b></a>'; if (role == 3 || role == 1032) { var contactIdLink = '<a href="https://1048144.app.netsuite.com/app/common/entity/contact.nl?id=' + customerContactListRemainingRows[x].contactInternalId + '&whence=" target="_blank"><b>Edit Contact</b></a>'; // var franchiseeSalesRepAssigned = nlapiLookupField('customer', parseInt(customerContactListRow.contactInternalId), 'partner.custentity_sales_rep_assigned'); // salesRepId = franchiseeSalesRepAssigned; // if (franchiseeSalesRepAssigned == '668712') { // salesRepEmail = 'PI:EMAIL:ychag@example.comEND_PI'; // salesRepName = 'Belinda Urbani'; // salesRepId = 668712 // } else if (franchiseeSalesRepAssigned == '696160') { // salesRepEmail = 'PI:EMAIL:hzdkv@example.comEND_PI' // salesRepName = 'Kerina Helliwell'; // salesRepId = 696160 // } else { // salesRepEmail = 'PI:EMAIL:kenaa@example.comEND_PI'; // salesRepName = 'Lee Russell'; // salesRepId = 668711 // } // var sendSignUpEmail = // '<a data-id="' + // customerContactListRow.custInternalID + // '" data-sales="' + // salesRepId + // '" data-contact="' + // customerContactListRow.contactInternalId + // '" data-contactemail="' + // customerContactListRow.contactEmail + // '" data-contactName="' + // customerContactListRow.contactName + // '" data-contactPhone="' + // customerContactListRow.contactPhone + // '" data-salesrecordid="" style="font-weight: bold; cursor: pointer !important;width: 50%;border-radius: 30px;padding: 2.5%;" class="sendEmail"><button><div class="svg-wrapper-1"><div class="svg-wrapper"><svg height="24" width="24" viewBox="0 0 24 24" xmlns="http://www.w3.org/2000/svg"><path d="M0 0h24v24H0z" fill="none"></path><path d="M1.946 9.315c-.522-.174-.527-.455.01-.634l19.087-6.362c.529-.176.832.12.684.638l-5.454 19.086c-.15.529-.455.547-.679.045L12 14l6-8-8 6-8.054-2.685z" fill="currentColor"></path></svg></div></div><span>Send</span></button></a></br>' + customerContactListRow.contactEmail; } else { var contactIdLink = customerContactListRemainingRows[x].contactInternalId; // var sendSignUpEmail = customerContactListRow.contactEmail; } customerContactListDataSet2.push([linkURL, customerIDLink, customerContactListRemainingRows[x].custName, customerContactListRemainingRows[x].zeeName, contactCreatedDateSplitString, contactIdLink, customerContactListRemainingRows[x].contactName, sendSignUpEmail, customerContactListRemainingRows[x].contactPhone, customerContactListRemainingRows[x].contactCreatePasswordEmail, parseInt(customerContactListRemainingRows[x].contactCreatePasswordEmailCount), customerContactListRemainingRows[x].contactPasswordSetupCompleted, currentStatus ]); csvSet2.push([customerContactListRemainingRows[x].custInternalID, customerContactListRemainingRows[x].custName, customerContactListRemainingRows[x].zeeName, contactCreatedDateSplitString, customerContactListRemainingRows[x].contactInternalId, customerContactListRemainingRows[x].contactName, customerContactListRemainingRows[x].contactEmail, customerContactListRemainingRows[x].contactPhone, customerContactListRemainingRows[x].contactCreatePasswordEmail, customerContactListRemainingRows[x].contactCreatePasswordEmailCount, customerContactListRemainingRows[x].contactPasswordSetupCompleted ]); } // customerContactListRemainingRows.forEach(function (customerContactListRow, index) { // console.log('index: ' + index); // // if (index < displayList) { // // var contactCreatedArray = customerContactListRow.contactCreated.split(' '); // // var contactCreatedDateSplit = contactCreatedArray[0].split('/'); // // if (parseInt(contactCreatedDateSplit[1]) < 10) { // // contactCreatedDateSplit[1] = '0' + contactCreatedDateSplit[1] // // } // // if (parseInt(contactCreatedDateSplit[0]) < 10) { // // contactCreatedDateSplit[0] = '0' + contactCreatedDateSplit[0] // // } // // var contactCreatedDateSplitString = contactCreatedDateSplit[2] + '-' + contactCreatedDateSplit[1] + '-' + // // contactCreatedDateSplit[0]; // // var date_from = dateISOToNetsuite(contactCreatedDateSplitString); // // // console.log('date_from: ' + date_from) // // // console.log('customerContactListRow.custInternalID: ' + customerContactListRow.custInternalID); // // var date = new Date(), y = date.getFullYear(), m = date.getMonth(); // // var firstDay = new Date(y, m, 1); // // var lastDay = new Date(y, m + 1, 0); // // firstDay.setHours(0, 0, 0, 0); // // lastDay.setHours(0, 0, 0, 0); // // firstDay = GetFormattedDate(firstDay); // // lastDay = GetFormattedDate(lastDay); // // var sendSignUpEmail = customerContactListRow.contactEmail; // // if (customerContactListRow.contactCreatePasswordEmail == 'Yes' && customerContactListRow.contactPasswordSetupCompleted == 'Yes') { // // //Search Name: All MP Products - Source/Week // // var mpProductSourcePerWeekSearch = search.load({ // // type: 'customrecord_customer_product_stock', // // id: 'customsearch_prod_stock_usage_report___6' // // }); // // mpProductSourcePerWeekSearch.filters.push(search.createFilter({ // // name: 'internalid', // // join: 'custrecord_cust_prod_stock_customer', // // operator: search.Operator.IS, // // values: parseInt(customerContactListRow.custInternalID) // // })); // // mpProductSourcePerWeekSearch.filters.push(search.createFilter({ // // name: 'custrecord_barcode_source', // // operator: search.Operator.ANYOF, // // values: ["1", "@NONE@"] // // })); // // mpProductSourcePerWeekSearch.filters.push(search.createFilter({ // // name: 'custrecord_cust_date_stock_used', // // join: null, // // operator: search.Operator.ONORAFTER, // // values: date_from // // })); // // customerCountRemainingAccountActivated++; // // console.log('customerCountRemainingAccountActivated: ' + customerCountRemainingAccountActivated) // // var resultRange = mpProductSourcePerWeekSearch.run().getRange({ // // start: 0, // // end: 1 // // }); // // if (resultRange.length == 0) { // // //Search Name: All MP Products - Source/Week // // var mpProductSourcePerWeekSearch = search.load({ // // type: 'customrecord_customer_product_stock', // // id: 'customsearch_prod_stock_usage_report___6' // // }); // // mpProductSourcePerWeekSearch.filters.push(search.createFilter({ // // name: 'internalid', // // join: 'custrecord_cust_prod_stock_customer', // // operator: search.Operator.IS, // // values: parseInt(customerContactListRow.custInternalID) // // })); // // mpProductSourcePerWeekSearch.filters.push(search.createFilter({ // // name: 'custrecord_barcode_source', // // operator: search.Operator.NONEOF, // // values: ["1", "@NONE@"] // // })); // // mpProductSourcePerWeekSearch.filters.push(search.createFilter({ // // name: 'custrecord_cust_date_stock_used', // // join: null, // // operator: search.Operator.ONORAFTER, // // values: date_from // // })); // // console.log('mpProductSourcePerWeekSearch.run(): ' + mpProductSourcePerWeekSearch.run()) // // var resultRange = mpProductSourcePerWeekSearch.run().getRange({ // // start: 0, // // end: 1 // // }); // // if (resultRange.length == 0) { // // var currentStatus = 'NO USAGE' // // // var linkURL = '<a href="https://1048144.app.netsuite.com/app/site/hosting/scriptlet.nl?script=1712&deploy=1&start_date=' + contactCreatedDateSplitString + '&last_date=' + lastDay + '&zee=' + customerContactListRow.zeeID + '&custid=' + customerContactListRow.custInternalID + '&freq=daily" target="_blank" style="font-weight: bold; cursor: pointer !important;width: 50%;border-radius: 30px;padding: 2.5%;" class="button-shadow"><i class="fa-solid fa-chart-simple" style="font-size: 25px;color: #337ab7"></i></a>' // // var linkURL = '<a href="https://1048144.app.netsuite.com/app/site/hosting/scriptlet.nl?script=1712&deploy=1&start_date=' + contactCreatedDateSplitString + '&last_date=' + lastDay + '&zee=' + customerContactListRow.zeeID + '&custid=' + customerContactListRow.custInternalID + '&freq=daily" target="_blank" style="font-weight: bold; cursor: pointer !important;width: 50%;border-radius: 30px;padding: 2.5%;" class=""><img src="https://1048144.app.netsuite.com/core/media/media.nl?id=6399648&c=1048144&h=IV0eZcpDJAJvpDCshlu59Ny5BQ1HZwqvu2FIRmE9CZHL8AN3" style="height: 3em; width: 3em;"></a>' // // } else { // // var currentStatus = 'DIGITAL LABEL' // // var linkURL = '<a href="https://1048144.app.netsuite.com/app/site/hosting/scriptlet.nl?script=1712&deploy=1&start_date=' + contactCreatedDateSplitString + '&last_date=' + lastDay + '&zee=' + customerContactListRow.zeeID + '&custid=' + customerContactListRow.custInternalID + '&freq=daily" target="_blank" style="font-weight: bold; cursor: pointer !important;width: 50%;border-radius: 30px;padding: 2.5%;" class=""><img src="https://1048144.app.netsuite.com/core/media/media.nl?id=6399648&c=1048144&h=IV0eZcpDJAJvpDCshlu59Ny5BQ1HZwqvu2FIRmE9CZHL8AN3" style="height: 3em; width: 3em;"></a>' // // } // // } else { // // var currentStatus = 'MANUAL BARCODES' // // var linkURL = '<a href="https://1048144.app.netsuite.com/app/site/hosting/scriptlet.nl?script=1712&deploy=1&start_date=' + contactCreatedDateSplitString + '&last_date=' + lastDay + '&zee=' + customerContactListRow.zeeID + '&custid=' + customerContactListRow.custInternalID + '&freq=daily" target="_blank" style="font-weight: bold; cursor: pointer !important;width: 50%;border-radius: 30px;padding: 2.5%;" class=""><img src="https://1048144.app.netsuite.com/core/media/media.nl?id=6399648&c=1048144&h=IV0eZcpDJAJvpDCshlu59Ny5BQ1HZwqvu2FIRmE9CZHL8AN3" style="height: 3em; width: 3em;"></a>' // // } // // } else if (customerContactListRow.contactCreatePasswordEmail != 'Yes' && customerContactListRow.contactPasswordSetupCompleted != 'Yes') { // // var linkURL = '' // // var currentStatus = '' // // if (role == 3 || role == 1032) { //Administrator or System Support // // linkURL = // // '<input type="button" id="" data-id="' + // // customerContactListRow.contactInternalId + // // '" value="CREATE PASSWORD EMAIL SENT" class="form-control btn btn-xs btn-primary createPasswordEmail button-shadow" style="font-weight: bold; cursor: pointer !important;width: fit-content;border-radius: 30px" /> </br><a href="https://1048144.app.netsuite.com/app/site/hosting/scriptlet.nl?script=1712&deploy=1&start_date=' + contactCreatedDateSplitString + '&last_date=' + lastDay + '&zee=' + customerContactListRow.zeeID + '&custid=' + customerContactListRow.custInternalID + '&freq=daily" target="_blank" style="font-weight: bold; cursor: pointer !important;width: 50%;border-radius: 30px;padding: 2.5%;" class=""><img src="https://1048144.app.netsuite.com/core/media/media.nl?id=6399648&c=1048144&h=IV0eZcpDJAJvpDCshlu59Ny5BQ1HZwqvu2FIRmE9CZHL8AN3" style="height: 3em; width: 3em;"></a>'; // // } else { // // var linkURL = '<a href="https://1048144.app.netsuite.com/app/site/hosting/scriptlet.nl?script=1712&deploy=1&start_date=' + contactCreatedDateSplitString + '&last_date=' + lastDay + '&zee=' + customerContactListRow.zeeID + '&custid=' + customerContactListRow.custInternalID + '&freq=daily" target="_blank" style="font-weight: bold; cursor: pointer !important;width: 50%;border-radius: 30px;padding: 2.5%;" class=""><img src="https://1048144.app.netsuite.com/core/media/media.nl?id=6399648&c=1048144&h=IV0eZcpDJAJvpDCshlu59Ny5BQ1HZwqvu2FIRmE9CZHL8AN3" style="height: 3em; width: 3em;"></a>' // // } // // } else if (customerContactListRow.contactCreatePasswordEmail == 'Yes' && customerContactListRow.contactPasswordSetupCompleted != 'Yes') { // // var linkURL = '' // // var currentStatus = ''; // // if (role == 3 || role == 1032) { //Administrator or System Support // // linkURL = // // '<input type="button" id="" data-id="' + // // customerContactListRow.contactInternalId + // // '" value="ACTIVATED" class="form-control btn btn-xs btn-success accountActivated button-shadow" style="font-weight: bold; cursor: pointer !important;width: fit-content;border-radius: 30px" /> </br><a href="https://1048144.app.netsuite.com/app/site/hosting/scriptlet.nl?script=1712&deploy=1&start_date=' + contactCreatedDateSplitString + '&last_date=' + lastDay + '&zee=' + customerContactListRow.zeeID + '&custid=' + customerContactListRow.custInternalID + '&freq=daily" target="_blank" style="font-weight: bold; cursor: pointer !important;width: 50%;border-radius: 30px;padding: 2.5%;" class=""><img src="https://1048144.app.netsuite.com/core/media/media.nl?id=6399648&c=1048144&h=IV0eZcpDJAJvpDCshlu59Ny5BQ1HZwqvu2FIRmE9CZHL8AN3" style="height: 3em; width: 3em;"></a>'; // // var franchiseeSalesRepAssigned = nlapiLookupField('customer', parseInt(customerContactListRow.contactInternalId), 'partner.custentity_sales_rep_assigned'); // // salesRepId = franchiseeSalesRepAssigned; // // if (franchiseeSalesRepAssigned == '668712') { // // salesRepEmail = 'PI:EMAIL:ychag@example.comEND_PI'; // // salesRepName = 'Belinda Urbani'; // // salesRepId = 668712 // // } else if (franchiseeSalesRepAssigned == '696160') { // // salesRepEmail = 'PI:EMAIL:hzdkv@example.comEND_PI' // // salesRepName = 'Kerina Helliwell'; // // salesRepId = 696160 // // } else { // // salesRepEmail = 'PI:EMAIL:kenaa@example.comEND_PI'; // // salesRepName = 'Lee Russell'; // // salesRepId = 668711 // // } // // var sendSignUpEmail = // // '<a data-id="' + // // customerContactListRow.custInternalID + // // '" data-sales="' + // // salesRepId + // // '" data-contact="' + // // customerContactListRow.contactInternalId + // // '" data-contactemail="' + // // customerContactListRow.contactEmail + // // '" data-contactName="' + // // customerContactListRow.contactName + // // '" data-contactPhone="' + // // customerContactListRow.contactPhone + // // '" data-salesrecordid="" style="font-weight: bold; cursor: pointer !important;width: 50%;border-radius: 30px;padding: 2.5%;" class="sendEmail"><button class="button-shadow"><div class="svg-wrapper-1"><div class="svg-wrapper"><svg height="24" width="24" viewBox="0 0 24 24" xmlns="http://www.w3.org/2000/svg"><path d="M0 0h24v24H0z" fill="none"></path><path d="M1.946 9.315c-.522-.174-.527-.455.01-.634l19.087-6.362c.529-.176.832.12.684.638l-5.454 19.086c-.15.529-.455.547-.679.045L12 14l6-8-8 6-8.054-2.685z" fill="currentColor"></path></svg></div></div><span>Resend</span></button></a></br></br>' + customerContactListRow.contactEmail; // // // linkURL = // // // '<a href="" class="accountActivated button-shadow" style="cursor: pointer !important;" ><img src="https://1048144.app.netsuite.com/core/media/media.nl?id=6399647&c=1048144&h=RuKYj6ulVT3rxPGWwg3OnnI6wETYrFW3BjGkTbg6dg7ms7wv" style="height: 3em; width: 3em;"></a><input type="button" id="" data-id="' + // // // customerContactListRow.contactInternalId + // // // '" value="ACTIVATED" class="form-control btn btn-xs btn-success accountActivated button-shadow" style="font-weight: bold; cursor: pointer !important;width: fit-content;border-radius: 30px" /> </br><a href="https://1048144.app.netsuite.com/app/site/hosting/scriptlet.nl?script=1712&deploy=1&start_date=' + contactCreatedDateSplitString + '&last_date=' + lastDay + '&zee=' + customerContactListRow.zeeID + '&custid=' + customerContactListRow.custInternalID + '&freq=daily" target="_blank" style="font-weight: bold; cursor: pointer !important;width: 50%;border-radius: 30px;padding: 2.5%;" class="button-shadow"><i class="fa-solid fa-chart-simple" style="font-size: 25px;color: #337ab7"></i></a>'; // // } else { // // var linkURL = '<a href="https://1048144.app.netsuite.com/app/site/hosting/scriptlet.nl?script=1712&deploy=1&start_date=' + contactCreatedDateSplitString + '&last_date=' + lastDay + '&zee=' + customerContactListRow.zeeID + '&custid=' + customerContactListRow.custInternalID + '&freq=daily" target="_blank" style="font-weight: bold; cursor: pointer !important;width: 50%;border-radius: 30px;padding: 2.5%;" class=""><img src="https://1048144.app.netsuite.com/core/media/media.nl?id=6399648&c=1048144&h=IV0eZcpDJAJvpDCshlu59Ny5BQ1HZwqvu2FIRmE9CZHL8AN3" style="height: 3em; width: 3em;"></a>'; // // } // // } // // var customerIDLink = // // '<a href="https://1048144.app.netsuite.com/app/common/entity/custjob.nl?id=' + // // customerContactListRow.custInternalID + '&whence=" target="_blank"><b>' + // // customerContactListRow.custEntityID + '</b></a>'; // // if (role == 3 || role == 1032) { // // var contactIdLink = // // '<a href="https://1048144.app.netsuite.com/app/common/entity/contact.nl?id=' + // // customerContactListRow.contactInternalId + '&whence=" target="_blank"><b>Edit Contact</b></a>'; // // // var franchiseeSalesRepAssigned = nlapiLookupField('customer', parseInt(customerContactListRow.contactInternalId), 'partner.custentity_sales_rep_assigned'); // // // salesRepId = franchiseeSalesRepAssigned; // // // if (franchiseeSalesRepAssigned == '668712') { // // // salesRepEmail = 'PI:EMAIL:ychag@example.comEND_PI'; // // // salesRepName = 'Belinda Urbani'; // // // salesRepId = 668712 // // // } else if (franchiseeSalesRepAssigned == '696160') { // // // salesRepEmail = 'PI:EMAIL:hzdkv@example.comEND_PI' // // // salesRepName = 'Kerina Helliwell'; // // // salesRepId = 696160 // // // } else { // // // salesRepEmail = 'PI:EMAIL:kenaa@example.comEND_PI'; // // // salesRepName = 'Lee Russell'; // // // salesRepId = 668711 // // // } // // // var sendSignUpEmail = // // // '<a data-id="' + // // // customerContactListRow.custInternalID + // // // '" data-sales="' + // // // salesRepId + // // // '" data-contact="' + // // // customerContactListRow.contactInternalId + // // // '" data-contactemail="' + // // // customerContactListRow.contactEmail + // // // '" data-contactName="' + // // // customerContactListRow.contactName + // // // '" data-contactPhone="' + // // // customerContactListRow.contactPhone + // // // '" data-salesrecordid="" style="font-weight: bold; cursor: pointer !important;width: 50%;border-radius: 30px;padding: 2.5%;" class="sendEmail"><button><div class="svg-wrapper-1"><div class="svg-wrapper"><svg height="24" width="24" viewBox="0 0 24 24" xmlns="http://www.w3.org/2000/svg"><path d="M0 0h24v24H0z" fill="none"></path><path d="M1.946 9.315c-.522-.174-.527-.455.01-.634l19.087-6.362c.529-.176.832.12.684.638l-5.454 19.086c-.15.529-.455.547-.679.045L12 14l6-8-8 6-8.054-2.685z" fill="currentColor"></path></svg></div></div><span>Send</span></button></a></br>' + customerContactListRow.contactEmail; // // } else { // // var contactIdLink = customerContactListRow.contactInternalId; // // // var sendSignUpEmail = customerContactListRow.contactEmail; // // } // // customerContactListDataSet2.push([linkURL, // // customerIDLink, // // customerContactListRow.custName, customerContactListRow.zeeName, contactCreatedDateSplitString, contactIdLink, customerContactListRow.contactName, sendSignUpEmail, customerContactListRow.contactPhone, customerContactListRow.contactCreatePasswordEmail, parseInt(customerContactListRow.contactCreatePasswordEmailCount), customerContactListRow.contactPasswordSetupCompleted, currentStatus // // ]); // // csvSet2.push([customerContactListRow.custInternalID, // // customerContactListRow.custName, customerContactListRow.zeeName, contactCreatedDateSplitString, customerContactListRow.contactInternalId, customerContactListRow.contactName, customerContactListRow.contactEmail, customerContactListRow.contactPhone, customerContactListRow.contactCreatePasswordEmail, customerContactListRow.contactCreatePasswordEmailCount, customerContactListRow.contactPasswordSetupCompleted // // ]); // // } // }); } var datatable2 = $('#mpexusage-customer_contact_list_remaining').DataTable(); datatable2.clear(); datatable2.rows.add(customerContactListDataSet2); datatable2.draw(); saveCsv(csvSet2); $('#noUsageCount').val(noUsageCustomerCount); $('#manualUsageCount').val(manualUsageCustomerCount); $('#digitalUsageCount').val(digitalLabelUsageCustomerCount); return true; } /** * Load the string stored in the hidden field 'custpage_table_csv'. * Converts it to a CSV file. * Creates a hidden link to download the file and triggers the click of the link. */ function downloadCsv() { var today = new Date(); today = formatDate(today); var val1 = currentRecord.get(); var csv = val1.getValue({ fieldId: 'custpage_table_csv', }); today = replaceAll(today); var a = document.createElement("a"); document.body.appendChild(a); a.style = "display: none"; var content_type = 'text/csv'; var csvFile = new Blob([csv], { type: content_type }); var url = window.URL.createObjectURL(csvFile); var filename = 'Customer Cancellation List_' + today + '.csv'; a.href = url; a.download = filename; a.click(); window.URL.revokeObjectURL(url); } function getDateStoreNS() { var date = new Date(); if (date.getHours() > 6) { date.setDate(date.getDate() + 1); } format.format({ value: date, type: format.Type.DATE, timezone: format.Timezone.AUSTRALIA_SYDNEY }) return date; } function saveRecord() { return true; } /** * Create the CSV and store it in the hidden field 'custpage_table_csv' as a string. * @param {Array} ordersDataSet The `billsDataSet` created in `loadDatatable()`. */ function saveCsv(ordersDataSet) { var sep = "sep=;"; var headers = ["Customer Internal ID", "Customer Entity ID", "Customer Name", "Franchisee", "Status", "Cancellation Requested Date", "Cancellation Date", "Cancellation Progress" ] headers = headers.join(';'); // .join(', ') var csv = sep + "\n" + headers + "\n"; ordersDataSet.forEach(function (row) { row = row.join(';'); csv += row; csv += "\n"; }); var val1 = currentRecord.get(); val1.setValue({ fieldId: 'custpage_table_csv', value: csv }); return true; } function formatDate(testDate) { console.log('testDate: ' + testDate); var responseDate = format.format({ value: testDate, type: format.Type.DATE }); console.log('responseDate: ' + responseDate); return responseDate; } function replaceAll(string) { return string.split("/").join("-"); } /** * Used to pass the values of `date_from` and `date_to` between the scripts and to Netsuite for the records and the search. * @param {String} date_iso "2020-06-01" * @returns {String} date_netsuite "1/6/2020" */ function dateISOToNetsuite(date_iso) { var date_netsuite = ''; if (!isNullorEmpty(date_iso)) { var date_utc = new Date(date_iso); // var date_netsuite = nlapiDateToString(date_utc); var date_netsuite = format.format({ value: date_utc, type: format.Type.DATE }); } return date_netsuite; } function GetFormattedDate(todayDate) { var month = pad(todayDate.getMonth() + 1); var day = pad(todayDate.getDate()); var year = (todayDate.getFullYear()); return year + "-" + month + "-" + day; } function pad(s) { return (s < 10) ? '0' + s : s; } /** * [getDate description] - Get the current date * @return {[String]} [description] - return the string date */ function getDate() { var date = new Date(); date = format.format({ value: date, type: format.Type.DATE, timezone: format.Timezone.AUSTRALIA_SYDNEY }); return date; } function isNullorEmpty(val) { if (val == '' || val == null) { return true; } else { return false; } } return { pageInit: pageInit, saveRecord: saveRecord, downloadCsv: downloadCsv } });
/** * job.ext.getStatus.js * @description Get External Job Status * @module clv/job/getStatus * @NApiVersion 2.0 * @NScriptType Suitelet * @author Miquel Brazil <miquel@leprechaunpromotions.com> */ define(['N/https', 'N/search', "N/record", "N/log"], function (https, search, record, log) { var id = ""; var jobnumber; var data = []; var objRecord; var orderStatusVariables = []; var has_data = []; function loadRecord() { objRecord = record.load({ type: record.Type.SALES_ORDER, id: id }); orderStatusVariables.push({ approval_request: objRecord.getValue({fieldId: "custbody_lp_status_approval_request"}), artwork_setup: objRecord.getValue({fieldId: "custbody_lp_status_artwork_setup"}), payment: objRecord.getValue({fieldId: "custbody_lp_status_payment"}), stock: objRecord.getValue({fieldId: "custbody_lp_status_stock"}) }); data.push({ custbody_lp_status_stock: objRecord.getValue({fieldId: "custbody_lp_status_stock"}), custbody_lp_status_artwork_setup: objRecord.getValue({fieldId: "custbody_lp_status_artwork_setup"}), custbody_lp_status_payment: objRecord.getValue({fieldId: "custbody_lp_status_payment"}), custbody_lp_status_approval_request: objRecord.getValue({fieldId: "custbody_lp_status_approval_request"}), tranid: objRecord.getText({fieldId: "tranid"}), otherrefnum: objRecord.getText({fieldId: "otherrefnum"}), saleseffectivedate: objRecord.getText({fieldId: "saleseffectivedate"}), entity: objRecord.getText({fieldId: "entity"}), custbody_lp_email_approval: objRecord.getText({fieldId: "custbody_lp_email_approval"}), custbody_lpl_so_total_less_shipcost: objRecord.getText({fieldId: "custbody_lpl_so_total_less_shipcost"}), shipaddress: objRecord.getText({fieldId: "shipaddress"}), carrier: objRecord.getText({fieldId: "carrier"}), shipmethod: objRecord.getText({fieldId: "shipmethod"}), shipdate: objRecord.getText({fieldId: "shipdate"}), custbody_lp_shipping_arrival_date: objRecord.getText({fieldId: "custbody_lp_shipping_arrival_date"}), custbody_lp_approval_request: objRecord.getText({fieldId: "custbody_lp_approval_request"}), linkedtrackingnumbers: objRecord.getText({fieldId: "linkedtrackingnumbers"}), status: getOrderStatus(orderStatusVariables), has_data: "true" }); } function getOrderStatus(orderStatusVariables) { var status = {text_status: "Your Order Is Being Processed ", value_status: "-1"}; if (orderStatusVariables[0].stock === "2") { status = {text_status: "Stock Issues", value_status: "2"}; return status; } if (orderStatusVariables[0].artwork_setup === "4") { status = {text_status: "Art Issues", value_status: "4"}; return status; } if (orderStatusVariables[0].approval_request === "2") { status = {text_status: "Queued For Revision", value_status: "2"}; return status; } if (orderStatusVariables[0].approval_request === "3") { status = {text_status: "Pending Response", value_status: "3"}; return status; } if (orderStatusVariables[0].payment === "5") { status = {text_status: "Pending Payment Response", value_status: "5"}; return status; } if (orderStatusVariables[0].approval_request === "1" & orderStatusVariables[0].artwork_setup == "1" & (orderStatusVariables[0].payment == "1" || "2" || "3") & (orderStatusVariables[0].stock == "1" || "3")) { status = {text_status: "Queued For Printing", value_status: "12"}; return status; } return status; } function createSearch() { search.create({ type: search.Type.SALES_ORDER, filters: [{ name: 'tranid', operator: search.Operator.IS, values: [jobnumber] }], }).run().each(processResult); function processResult(result) { id = result.id; log.debug({}); return true; } } function inspect(context) { jobnumber = context.request.parameters.jobNumber; context.response.setHeader({ name: 'Content-Type', value: 'application/json; charset=utf-8' }); createSearch(); if (id === "") { data.push({has_data: "false"}); } else { loadRecord(); } context.response.write(JSON.stringify({ data: data, })); } return { onRequest: inspect } });
940
[{"tag": "EMAIL", "value": "miquel@leprechaunpromotions.com", "start": 168, "end": 199}]
true
1
/** * job.ext.getStatus.js * @description Get External Job Status * @module clv/job/getStatus * @NApiVersion 2.0 * @NScriptType Suitelet * @author Miquel Brazil <anpch@example.com> */ define(['N/https', 'N/search', "N/record", "N/log"], function (https, search, record, log) { var id = ""; var jobnumber; var data = []; var objRecord; var orderStatusVariables = []; var has_data = []; function loadRecord() { objRecord = record.load({ type: record.Type.SALES_ORDER, id: id }); orderStatusVariables.push({ approval_request: objRecord.getValue({fieldId: "custbody_lp_status_approval_request"}), artwork_setup: objRecord.getValue({fieldId: "custbody_lp_status_artwork_setup"}), payment: objRecord.getValue({fieldId: "custbody_lp_status_payment"}), stock: objRecord.getValue({fieldId: "custbody_lp_status_stock"}) }); data.push({ custbody_lp_status_stock: objRecord.getValue({fieldId: "custbody_lp_status_stock"}), custbody_lp_status_artwork_setup: objRecord.getValue({fieldId: "custbody_lp_status_artwork_setup"}), custbody_lp_status_payment: objRecord.getValue({fieldId: "custbody_lp_status_payment"}), custbody_lp_status_approval_request: objRecord.getValue({fieldId: "custbody_lp_status_approval_request"}), tranid: objRecord.getText({fieldId: "tranid"}), otherrefnum: objRecord.getText({fieldId: "otherrefnum"}), saleseffectivedate: objRecord.getText({fieldId: "saleseffectivedate"}), entity: objRecord.getText({fieldId: "entity"}), custbody_lp_email_approval: objRecord.getText({fieldId: "custbody_lp_email_approval"}), custbody_lpl_so_total_less_shipcost: objRecord.getText({fieldId: "custbody_lpl_so_total_less_shipcost"}), shipaddress: objRecord.getText({fieldId: "shipaddress"}), carrier: objRecord.getText({fieldId: "carrier"}), shipmethod: objRecord.getText({fieldId: "shipmethod"}), shipdate: objRecord.getText({fieldId: "shipdate"}), custbody_lp_shipping_arrival_date: objRecord.getText({fieldId: "custbody_lp_shipping_arrival_date"}), custbody_lp_approval_request: objRecord.getText({fieldId: "custbody_lp_approval_request"}), linkedtrackingnumbers: objRecord.getText({fieldId: "linkedtrackingnumbers"}), status: getOrderStatus(orderStatusVariables), has_data: "true" }); } function getOrderStatus(orderStatusVariables) { var status = {text_status: "Your Order Is Being Processed ", value_status: "-1"}; if (orderStatusVariables[0].stock === "2") { status = {text_status: "Stock Issues", value_status: "2"}; return status; } if (orderStatusVariables[0].artwork_setup === "4") { status = {text_status: "Art Issues", value_status: "4"}; return status; } if (orderStatusVariables[0].approval_request === "2") { status = {text_status: "Queued For Revision", value_status: "2"}; return status; } if (orderStatusVariables[0].approval_request === "3") { status = {text_status: "Pending Response", value_status: "3"}; return status; } if (orderStatusVariables[0].payment === "5") { status = {text_status: "Pending Payment Response", value_status: "5"}; return status; } if (orderStatusVariables[0].approval_request === "1" & orderStatusVariables[0].artwork_setup == "1" & (orderStatusVariables[0].payment == "1" || "2" || "3") & (orderStatusVariables[0].stock == "1" || "3")) { status = {text_status: "Queued For Printing", value_status: "12"}; return status; } return status; } function createSearch() { search.create({ type: search.Type.SALES_ORDER, filters: [{ name: 'tranid', operator: search.Operator.IS, values: [jobnumber] }], }).run().each(processResult); function processResult(result) { id = result.id; log.debug({}); return true; } } function inspect(context) { jobnumber = context.request.parameters.jobNumber; context.response.setHeader({ name: 'Content-Type', value: 'application/json; charset=utf-8' }); createSearch(); if (id === "") { data.push({has_data: "false"}); } else { loadRecord(); } context.response.write(JSON.stringify({ data: data, })); } return { onRequest: inspect } });
true
/** * job.ext.getStatus.js * @description Get External Job Status * @module clv/job/getStatus * @NApiVersion 2.0 * @NScriptType Suitelet * @author Miquel Brazil <PI:EMAIL:anpch@example.comEND_PI> */ define(['N/https', 'N/search', "N/record", "N/log"], function (https, search, record, log) { var id = ""; var jobnumber; var data = []; var objRecord; var orderStatusVariables = []; var has_data = []; function loadRecord() { objRecord = record.load({ type: record.Type.SALES_ORDER, id: id }); orderStatusVariables.push({ approval_request: objRecord.getValue({fieldId: "custbody_lp_status_approval_request"}), artwork_setup: objRecord.getValue({fieldId: "custbody_lp_status_artwork_setup"}), payment: objRecord.getValue({fieldId: "custbody_lp_status_payment"}), stock: objRecord.getValue({fieldId: "custbody_lp_status_stock"}) }); data.push({ custbody_lp_status_stock: objRecord.getValue({fieldId: "custbody_lp_status_stock"}), custbody_lp_status_artwork_setup: objRecord.getValue({fieldId: "custbody_lp_status_artwork_setup"}), custbody_lp_status_payment: objRecord.getValue({fieldId: "custbody_lp_status_payment"}), custbody_lp_status_approval_request: objRecord.getValue({fieldId: "custbody_lp_status_approval_request"}), tranid: objRecord.getText({fieldId: "tranid"}), otherrefnum: objRecord.getText({fieldId: "otherrefnum"}), saleseffectivedate: objRecord.getText({fieldId: "saleseffectivedate"}), entity: objRecord.getText({fieldId: "entity"}), custbody_lp_email_approval: objRecord.getText({fieldId: "custbody_lp_email_approval"}), custbody_lpl_so_total_less_shipcost: objRecord.getText({fieldId: "custbody_lpl_so_total_less_shipcost"}), shipaddress: objRecord.getText({fieldId: "shipaddress"}), carrier: objRecord.getText({fieldId: "carrier"}), shipmethod: objRecord.getText({fieldId: "shipmethod"}), shipdate: objRecord.getText({fieldId: "shipdate"}), custbody_lp_shipping_arrival_date: objRecord.getText({fieldId: "custbody_lp_shipping_arrival_date"}), custbody_lp_approval_request: objRecord.getText({fieldId: "custbody_lp_approval_request"}), linkedtrackingnumbers: objRecord.getText({fieldId: "linkedtrackingnumbers"}), status: getOrderStatus(orderStatusVariables), has_data: "true" }); } function getOrderStatus(orderStatusVariables) { var status = {text_status: "Your Order Is Being Processed ", value_status: "-1"}; if (orderStatusVariables[0].stock === "2") { status = {text_status: "Stock Issues", value_status: "2"}; return status; } if (orderStatusVariables[0].artwork_setup === "4") { status = {text_status: "Art Issues", value_status: "4"}; return status; } if (orderStatusVariables[0].approval_request === "2") { status = {text_status: "Queued For Revision", value_status: "2"}; return status; } if (orderStatusVariables[0].approval_request === "3") { status = {text_status: "Pending Response", value_status: "3"}; return status; } if (orderStatusVariables[0].payment === "5") { status = {text_status: "Pending Payment Response", value_status: "5"}; return status; } if (orderStatusVariables[0].approval_request === "1" & orderStatusVariables[0].artwork_setup == "1" & (orderStatusVariables[0].payment == "1" || "2" || "3") & (orderStatusVariables[0].stock == "1" || "3")) { status = {text_status: "Queued For Printing", value_status: "12"}; return status; } return status; } function createSearch() { search.create({ type: search.Type.SALES_ORDER, filters: [{ name: 'tranid', operator: search.Operator.IS, values: [jobnumber] }], }).run().each(processResult); function processResult(result) { id = result.id; log.debug({}); return true; } } function inspect(context) { jobnumber = context.request.parameters.jobNumber; context.response.setHeader({ name: 'Content-Type', value: 'application/json; charset=utf-8' }); createSearch(); if (id === "") { data.push({has_data: "false"}); } else { loadRecord(); } context.response.write(JSON.stringify({ data: data, })); } return { onRequest: inspect } });
/** * NetSuite RESTlet framework - RESTlet. * * @author Felipe Chang <felipechang@hardcake.org> * * @NApiVersion 2.x * @NModuleScope SameAccount * @NScriptType RESTlet */ define(["require", "exports", "./controller", "./lib/lib", "N/log"], function (require, exports, Controllers, lib_1, log) { Object.defineProperty(exports, "__esModule", { value: true }); /** * Validate model and deal with errors * @param {Object} request - Request object * @return {string} */ function validate(request) { //Response container var res = { error: false, message: "" }; //Get request parameters var params = request.requestParams; //Uppercase HTTP method var http = request.httpMethod ? request.httpMethod.toUpperCase() : ""; //HTTP Method must be defined if (!http) { return lib_1.error("script error: httpMethod not defined"); } //HTTP Params must be defined if (!params) { return lib_1.error("script error: requestParams not defined"); } //Get and remove model var model = lib_1.proper(params.model); delete params.model; //Get and remove method var method = params.method; delete params.method; //Query parameter model is not found if (!model) { var models = []; //Return all model options for (var i in Controllers) { if (Controllers.hasOwnProperty(i)) { models.push(i.toLowerCase()); } } return JSON.stringify([{ models: models }]); } //Model is not found among controllers if (!Controllers[model]) { return lib_1.error("invalid model name"); } //Build controller var controller = new Controllers[model](params, method); //HTTP method is not defined in controller if (!controller[http]) { return lib_1.error("invalid model httpMethod"); } //Get response try { res = controller[http](); } catch (e) { log.error("e", e); return lib_1.error(e.message || e); } //Send error if no response if (!res) { return lib_1.error("method not retuning data"); } //Return response as text return JSON.stringify(res); } /** * get event handler * @param {EntryPoints.RESTlet.get} ctx - The parameters from the HTTP request URL as key-value pairs * @return {string} Returns a String when request "Content-Type" is "text/plain" * or an Object when request "Content-Type" is "application/json" */ function get(ctx) { return validate({ requestParams: ctx, httpMethod: "get" }); } exports.get = get; /** * post event handler * @param {EntryPoints.RESTlet.post} ctx - Request body is a String when request "Content-Type" is "text/plain" * or an Object when request "Content-Type" is "application/json" * @return {string} Returns a String when request "Content-Type" is "text/plain" * or an Object when request "Content-Type" is "application/json" */ function post(ctx) { return validate({ requestParams: ctx, httpMethod: "post" }); } exports.post = post; /** * put event handler * @param {EntryPoints.RESTlet.put} ctx - Request body is a String when request "Content-Type" is "text/plain" * or an Object when request "Content-Type" is "application/json" * @return {string} Returns a String when request "Content-Type" is "text/plain" * or an Object when request "Content-Type" is "application/json" */ function put(ctx) { return validate({ requestParams: ctx, httpMethod: "put" }); } exports.put = put; /** * delete event handler * @param {EntryPoints.RESTlet.delete_} ctx - The parameters from the HTTP request URL as key-value pairs * @return {string} Returns a String when request "Content-Type" is "text/plain" * or an Object when request "Content-Type" is "application/json" */ function del(ctx) { return validate({ requestParams: ctx, httpMethod: "delete" }); } exports.delete = del; });
282
[{"tag": "EMAIL", "value": "felipechang@hardcake.org", "start": 73, "end": 97}]
true
1
/** * NetSuite RESTlet framework - RESTlet. * * @author Felipe Chang <nnheo@example.com> * * @NApiVersion 2.x * @NModuleScope SameAccount * @NScriptType RESTlet */ define(["require", "exports", "./controller", "./lib/lib", "N/log"], function (require, exports, Controllers, lib_1, log) { Object.defineProperty(exports, "__esModule", { value: true }); /** * Validate model and deal with errors * @param {Object} request - Request object * @return {string} */ function validate(request) { //Response container var res = { error: false, message: "" }; //Get request parameters var params = request.requestParams; //Uppercase HTTP method var http = request.httpMethod ? request.httpMethod.toUpperCase() : ""; //HTTP Method must be defined if (!http) { return lib_1.error("script error: httpMethod not defined"); } //HTTP Params must be defined if (!params) { return lib_1.error("script error: requestParams not defined"); } //Get and remove model var model = lib_1.proper(params.model); delete params.model; //Get and remove method var method = params.method; delete params.method; //Query parameter model is not found if (!model) { var models = []; //Return all model options for (var i in Controllers) { if (Controllers.hasOwnProperty(i)) { models.push(i.toLowerCase()); } } return JSON.stringify([{ models: models }]); } //Model is not found among controllers if (!Controllers[model]) { return lib_1.error("invalid model name"); } //Build controller var controller = new Controllers[model](params, method); //HTTP method is not defined in controller if (!controller[http]) { return lib_1.error("invalid model httpMethod"); } //Get response try { res = controller[http](); } catch (e) { log.error("e", e); return lib_1.error(e.message || e); } //Send error if no response if (!res) { return lib_1.error("method not retuning data"); } //Return response as text return JSON.stringify(res); } /** * get event handler * @param {EntryPoints.RESTlet.get} ctx - The parameters from the HTTP request URL as key-value pairs * @return {string} Returns a String when request "Content-Type" is "text/plain" * or an Object when request "Content-Type" is "application/json" */ function get(ctx) { return validate({ requestParams: ctx, httpMethod: "get" }); } exports.get = get; /** * post event handler * @param {EntryPoints.RESTlet.post} ctx - Request body is a String when request "Content-Type" is "text/plain" * or an Object when request "Content-Type" is "application/json" * @return {string} Returns a String when request "Content-Type" is "text/plain" * or an Object when request "Content-Type" is "application/json" */ function post(ctx) { return validate({ requestParams: ctx, httpMethod: "post" }); } exports.post = post; /** * put event handler * @param {EntryPoints.RESTlet.put} ctx - Request body is a String when request "Content-Type" is "text/plain" * or an Object when request "Content-Type" is "application/json" * @return {string} Returns a String when request "Content-Type" is "text/plain" * or an Object when request "Content-Type" is "application/json" */ function put(ctx) { return validate({ requestParams: ctx, httpMethod: "put" }); } exports.put = put; /** * delete event handler * @param {EntryPoints.RESTlet.delete_} ctx - The parameters from the HTTP request URL as key-value pairs * @return {string} Returns a String when request "Content-Type" is "text/plain" * or an Object when request "Content-Type" is "application/json" */ function del(ctx) { return validate({ requestParams: ctx, httpMethod: "delete" }); } exports.delete = del; });
true
/** * NetSuite RESTlet framework - RESTlet. * * @author Felipe Chang <PI:EMAIL:nnheo@example.comEND_PI> * * @NApiVersion 2.x * @NModuleScope SameAccount * @NScriptType RESTlet */ define(["require", "exports", "./controller", "./lib/lib", "N/log"], function (require, exports, Controllers, lib_1, log) { Object.defineProperty(exports, "__esModule", { value: true }); /** * Validate model and deal with errors * @param {Object} request - Request object * @return {string} */ function validate(request) { //Response container var res = { error: false, message: "" }; //Get request parameters var params = request.requestParams; //Uppercase HTTP method var http = request.httpMethod ? request.httpMethod.toUpperCase() : ""; //HTTP Method must be defined if (!http) { return lib_1.error("script error: httpMethod not defined"); } //HTTP Params must be defined if (!params) { return lib_1.error("script error: requestParams not defined"); } //Get and remove model var model = lib_1.proper(params.model); delete params.model; //Get and remove method var method = params.method; delete params.method; //Query parameter model is not found if (!model) { var models = []; //Return all model options for (var i in Controllers) { if (Controllers.hasOwnProperty(i)) { models.push(i.toLowerCase()); } } return JSON.stringify([{ models: models }]); } //Model is not found among controllers if (!Controllers[model]) { return lib_1.error("invalid model name"); } //Build controller var controller = new Controllers[model](params, method); //HTTP method is not defined in controller if (!controller[http]) { return lib_1.error("invalid model httpMethod"); } //Get response try { res = controller[http](); } catch (e) { log.error("e", e); return lib_1.error(e.message || e); } //Send error if no response if (!res) { return lib_1.error("method not retuning data"); } //Return response as text return JSON.stringify(res); } /** * get event handler * @param {EntryPoints.RESTlet.get} ctx - The parameters from the HTTP request URL as key-value pairs * @return {string} Returns a String when request "Content-Type" is "text/plain" * or an Object when request "Content-Type" is "application/json" */ function get(ctx) { return validate({ requestParams: ctx, httpMethod: "get" }); } exports.get = get; /** * post event handler * @param {EntryPoints.RESTlet.post} ctx - Request body is a String when request "Content-Type" is "text/plain" * or an Object when request "Content-Type" is "application/json" * @return {string} Returns a String when request "Content-Type" is "text/plain" * or an Object when request "Content-Type" is "application/json" */ function post(ctx) { return validate({ requestParams: ctx, httpMethod: "post" }); } exports.post = post; /** * put event handler * @param {EntryPoints.RESTlet.put} ctx - Request body is a String when request "Content-Type" is "text/plain" * or an Object when request "Content-Type" is "application/json" * @return {string} Returns a String when request "Content-Type" is "text/plain" * or an Object when request "Content-Type" is "application/json" */ function put(ctx) { return validate({ requestParams: ctx, httpMethod: "put" }); } exports.put = put; /** * delete event handler * @param {EntryPoints.RESTlet.delete_} ctx - The parameters from the HTTP request URL as key-value pairs * @return {string} Returns a String when request "Content-Type" is "text/plain" * or an Object when request "Content-Type" is "application/json" */ function del(ctx) { return validate({ requestParams: ctx, httpMethod: "delete" }); } exports.delete = del; });
/** * @NApiVersion 2.0 * @NScriptType Suitelet * * Module Description * * NSVersion Date Author * 2.00 2021-09-20 09:33:08 Anesu * * Description: xxxxxxxx * * @Last Modified by: Anesu * @Last Modified time: 2021-09-20 09:33:08 * */ define(['N/ui/serverWidget', 'N/email', 'N/runtime', 'N/search', 'N/record', 'N/http', 'N/log', 'N/redirect', 'N/task', 'N/format'], function (ui, email, runtime, search, record, http, log, redirect, task, format) { var zee = 0; var role = 0; var baseURL = 'https://1048144.app.netsuite.com'; if (runtime.EnvType == "SANDBOX") { baseURL = 'https://1048144-sb3.app.netsuite.com'; } role = runtime.getCurrentUser().role; if (role == 1000) { zee = runtime.getCurrentUser().id; } else if (role == 3) { //Administrator zee = 6; //test } else if (role == 1032) { // System Support zee = 425904; //test-AR } function onRequest(context) { if (context.request.method === 'GET') { var is_params = false; type = context.request.parameters.type; var params_params = context.request.parameters if (!isNullorEmpty(params_params.custparam_params)) { var params = JSON.parse(context.request.parameters.custparam_params); } var zee_id = 0; var zee_name = ''; zee_state = ''; var selector = ''; /** * If Comming from 1.0 Page */ var selection_params = context.request.parameters; // &zeename=Surry+Hills&zeeid=469&pagenum=0&zeestate=NSW if (!isNullorEmpty(selection_params.zeeid)) { zee_id = selection_params.zeeid; zee_name = selection_params.zeename; zee_state = selection_params.zeestate; if (selection_params.selector){ selector = selection_params.selector } } if (!isNullorEmpty(params)) { is_params = true; zee_id = parseInt(params.zeeid); zee_name = params.zeename; zee_state = params.zeestate; if (params.selector){ selector = params.selector; } } var form = ui.createForm({ title: ' ' }); // Load jQuery var inlineHtml = '<script src="https://code.jquery.com/jquery-1.12.4.min.js" integrity="sha384-nvAa0+6Qg9clwYCGGPpDQLVpLNn0fRaROjHqs13t4Ggj3Ez50XnGQqc/r8MhnRDZ" crossorigin="anonymous"></script>'; // Load Tooltip inlineHtml += '<script src="https://unpkg.com/@popperjs/core@2"></script>'; // Load Bootstrap inlineHtml += '<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/3.4.1/css/bootstrap.min.css" integrity="sha384-HSMxcRTRxnN+Bdg0JdbxYKrThecOKuH5zCYotlSAcp1+c8xmyTe9GYg1l9a69psu" crossorigin="anonymous">'; inlineHtml += '<script src="https://stackpath.bootstrapcdn.com/bootstrap/3.4.1/js/bootstrap.min.js" integrity="sha384-aJ21OjlMXNL5UyIl/XNwTMqvzeRMZH2w8c5cRVpzpU8Y5bApTppSuUkhZXN0VxHd" crossorigin="anonymous"></script>'; // Load DataTables // inlineHtml += '<link rel="stylesheet" type="text/css" href="//cdn.datatables.net/1.10.21/css/jquery.dataTables.min.css">'; inlineHtml += '<link rel="stylesheet" type="text/css" href="//cdn.datatables.net/1.12.0/css/jquery.dataTables.min.css">'; inlineHtml += '<script type="text/javascript" charset="utf8" src="//cdn.datatables.net/1.10.21/js/jquery.dataTables.min.js"></script>'; inlineHtml += '<script type="text/javascript" charset="utf8" src="//cdn.datatables.net/rowgroup/1.1.3/js/dataTables.rowGroup.min.js"></script> ' inlineHtml += '<script type="text/javascript" charset="utf8" src="//cdn.datatables.net/buttons/2.0.0/js/dataTables.buttons.min.js"></script> ' inlineHtml += '<script type="text/javascript" charset="utf8" src="//cdnjs.cloudflare.com/ajax/libs/jszip/3.1.3/jszip.min.js"></script> ' inlineHtml += '<script type="text/javascript" charset="utf8" src="//cdnjs.cloudflare.com/ajax/libs/pdfmake/0.1.53/pdfmake.min.js"></script> ' inlineHtml += '<script type="text/javascript" charset="utf8" src="//cdnjs.cloudflare.com/ajax/libs/pdfmake/0.1.53/vfs_fonts.js"></script> ' inlineHtml += '<script type="text/javascript" charset="utf8" src="//cdn.datatables.net/buttons/2.0.0/js/buttons.html5.min.js"></script> ' inlineHtml += '<script type="text/javascript" charset="utf8" src="//cdn.datatables.net/buttons/2.0.0/js/buttons.print.min.js"></script> ' // Load Netsuite stylesheet and script inlineHtml += '<link rel="stylesheet" href="https://1048144.app.netsuite.com/core/media/media.nl?id=2060796&c=1048144&h=9ee6accfd476c9cae718&_xt=.css"/>'; inlineHtml += '<script src="https://1048144.app.netsuite.com/core/media/media.nl?id=2060797&c=1048144&h=ef2cda20731d146b5e98&_xt=.js"></script>'; inlineHtml += '<link type="text/css" rel="stylesheet" href="https://1048144.app.netsuite.com/core/media/media.nl?id=2090583&c=1048144&h=a0ef6ac4e28f91203dfe&_xt=.css">'; inlineHtml += '<style>.mandatory{color:red;}</style>'; // Load Bootstrap-Select inlineHtml += '<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap-select@1.13.14/dist/css/bootstrap-select.min.css">'; inlineHtml += '<script src="https://cdn.jsdelivr.net/npm/bootstrap-select@1.13.14/dist/js/bootstrap-select.min.js"></script>'; // Semantic Select inlineHtml += '<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/semantic-ui/2.2.13/semantic.min.css">'; inlineHtml += '<script src="https://cdnjs.cloudflare.com/ajax/libs/semantic-ui/2.2.13/semantic.min.js"></script>'; // Load Search In Dropdown // inlineHtml += '<link href="https://cdnjs.cloudflare.com/ajax/libs/select2/4.0.6-rc.0/css/select2.min.css" rel="stylesheet" />'; // inlineHtml += '<script src="https://cdnjs.cloudflare.com/ajax/libs/select2/4.0.6-rc.0/js/select2.min.js"></script>'; // New Website Color Schemes // Main Color: #379E8F // Background Color: #CFE0CE // Button Color: #FBEA51 // Text Color: #103D39 // inlineHtml += '<div class="a" style="width: 100%; background-color: #CFE0CE; padding: 20px; min-height: 100vh; height: 100%; ">'; // margin-top: -40px // // inlineHtml += '<h1 style="text-align: center; color: #103D39; display: inline-block; font-size: 22px; font-weight: bold; line-height: 33px; vertical-align: top; margin-bottom: 4px;">Consolidation Invoice</h1>'; // inlineHtml += '<style>.nav > li.active > a, .nav > li.active > a:focus, .nav > li.active > a:hover { background-color: #379E8F; color: #fff }'; // inlineHtml += '.nav > li > a, .nav > li > a:focus, .nav > li > a:hover { margin-left: 5px; margin-right: 5px; border: 2px solid #379E8F; color: #379E8F; }'; // inlineHtml += '</style>'; // Define alert window. inlineHtml += '<div class="container" style="margin-top:14px;" hidden><div id="alert" class="alert alert-danger fade in"></div></div>'; // Click for Instructions inlineHtml += '<button type="button" class="btn btn-sm btn-info instruction_button" data-toggle="collapse" data-target="#demo" ">Click for Instructions</button><div id="demo" style="background-color: #cfeefc !important;border: 1px solid #417ed9;padding: 10px 10px 10px 20px;width:96%;position:absolute" class="collapse"><b><u>IMPORTANT INSTRUCTIONS:</u></b>'; inlineHtml += '<ul>Welcome to Suburb Mapping. To Start, Select Franchisee. Once Selected, A list of suburbs will appear according to that Franchisees State Value. Select appropriate Primary and Secondary Driver Information and Save</ul>'; inlineHtml += '<li>Table Data:<ul><li><b>Primary Table</b><ul><li> This Table Displays the list of Suburbs chosen by Franchisee in Suburb Selecitons Page. Please <a href="https://1048144.app.netsuite.com/app/site/hosting/scriptlet.nl?script=1065&deploy=1&compid=1048144&zee=' + zee_id + '&opsync=true">click here</a> to redirect.</li></ul></li> <li><b>Secondary Table</b><ul> Suburbs based on filter information. Please filter by Post Code or Suburb Name to view associated Information. </li></ul></li></ul></li>'; // inlineHtml += '<ul><li><button type="button" class="btn-xs" disabled><span class="span_class glyphicon glyphicon-pencil"></span></button> - Click to open Notes Section for Selected Invoice. (Notes Section is seperate from User Notes)</li>'; // inlineHtml += '<li><button type="button" class="btn-xs btn-secondary" disabled><span class="glyphicon glyphicon-eye-open"></span></button> - Click to Set Invoice has "Viewed" by a member of the Finance Team.</li>'; // inlineHtml += '<li><button type="button" class="btn-xs btn-info" disabled><span class="glyphicon glyphicon-time"></span></button> - Click to view Snooze Timers</li><li><button type="button" class="timer-1day form=control btn-xs btn-info" disabled><span class="span_class">1 Day</span></button> - Click to select Snooze duration of invoice from Debt Collections Page.</li>'; inlineHtml += '</li></ul></div>'; // Define information window. inlineHtml += '<div class="container" hidden><p id="info" class="alert alert-info"></p></div>'; inlineHtml += '<div style="margin-top: -40px"><br/>'; // Buttons // inlineHtml += '<button style="margin-left: 10px; margin-right: 5px; background-color: #FBEA51; color: #103D39; font-weight: 700; border-color: transparent; border-width: 2px; border-radius: 15px; height: 30px" type="button" id="new_agreement" onclick="">New Franchisee Agreement</button>'; if (!isNullorEmpty(zee_id) || zee_id != 0) { inlineHtml += '<h1 class="title_header" style="font-size: 25px; font-weight: 700; color: #103D39; text-align: center">Suburb & Operator Mapping: ' + zee_name + ' </h1>'; } else { inlineHtml += '<h1 class="title_header" style="font-size: 25px; font-weight: 700; color: #103D39; text-align: center">Suburb & Operator Mapping</h1>'; } // inlineHtml += '<button style="margin-left: 10px; margin-right: 5px; background-color: #FBEA51; color: #103D39; font-weight: 700; border-color: transparent; border-width: 2px; border-radius: 15px; height: 30px" type="button" id="downloadCSV" onclick="">Export Complete CSV</button>'; if (zee_id != 0 || !isNullorEmpty(zee_id)) { inlineHtml += '<button style="margin-left: 10px; margin-right: 5px; background-color: #FBEA51; color: #103D39; font-weight: 700; border-color: transparent; border-width: 2px; border-radius: 15px; height: 30px" type="button" id="first_sub_selection" onclick="">Add/Remove - First Mile Suburb</button>'; inlineHtml += '<button style="margin-left: 10px; margin-right: 5px; background-color: #FBEA51; color: #103D39; font-weight: 700; border-color: transparent; border-width: 2px; border-radius: 15px; height: 30px" type="button" id="last_sub_selection" onclick="">Add/Remove - Last Mile Suburb</button>'; // inlineHtml += '<button style="margin-left: 10px; margin-right: 5px; background-color: #FBEA51; color: #103D39; font-weight: 700; border-color: transparent; border-width: 2px; border-radius: 15px; height: 30px" type="button" id="lodgement_selection" onclick="">Lodgement Location Selection</button>'; // inlineHtml += '<button style="margin-left: 10px; margin-right: 5px; font-weight: 700; border-color: transparent; border-width: 2px; border-radius: 15px; height: 30px" type="button" id="toggle-columns" class="toggle-columns btn-success" >Show/Hide Columns</button>' //style="background-color: #379E8F; // Show/Hide Child Table. // inlineHtml += '<button style="margin-left: 10px; margin-right: 5px; background-color: #FBEA51; color: #103D39; font-weight: 700; border-color: transparent; border-width: 2px; border-radius: 15px; height: 30px" type="button" id="btn-show-all-children" class="btn-success" >Expand All</button>' //style="background-color: #379E8F; // inlineHtml += '<button style="margin-left: 10px; margin-right: 5px; background-color: #FBEA51; color: #103D39; font-weight: 700; border-color: transparent; border-width: 2px; border-radius: 15px; height: 30px" type="button" id="btn-hide-all-children" class="btn-success" >Collapse All</button>' //style="background-color: #379E8F; } inlineHtml += zeeDropdownSection(zee_id); if (zee_id != 0 || !isNullorEmpty(zee_id)) { inlineHtml += tabsSection(); inlineHtml += updateSaveRecord(); } inlineHtml += '</div></div>' form.addField({ id: 'preview_table', label: 'inlinehtml', type: 'inlinehtml' }).updateLayoutType({ layoutType: ui.FieldLayoutType.STARTROW }).defaultValue = inlineHtml; form.addField({ id: 'custpage_suburb_mapping_zee_id', label: 'Zee ID', type: ui.FieldType.TEXT }).updateDisplayType({ displayType: ui.FieldDisplayType.HIDDEN }).defaultValue = zee_id; form.addField({ id: 'custpage_suburb_mapping_zee_name', label: 'Zee ID', type: ui.FieldType.TEXT }).updateDisplayType({ displayType: ui.FieldDisplayType.HIDDEN }).defaultValue = zee_name; form.addField({ id: 'custpage_suburb_mapping_zee_state', label: 'Zee ID', type: ui.FieldType.TEXT }).updateDisplayType({ displayType: ui.FieldDisplayType.HIDDEN }).defaultValue = zee_state; form.addField({ id: 'custpage_suburb_mapping_selector', label: 'Selector Option', type: ui.FieldType.TEXT }).updateDisplayType({ displayType: ui.FieldDisplayType.HIDDEN }).defaultValue = selector; form.addSubmitButton({ label: ' ' }); form.clientScriptFileId = 5925500; // context.response.writePage(form); } else { } } /** * The table that will display the differents invoices linked to the franchisee and the time period. * @return {String} inlineQty */ function dataTable2(selector) { var inlineQty = '<style>table#data_preview2_'+ selector +' {font-size: 12px;text-align: center;border: none; background-color: white;}.dataTables_wrapper {font-size: 14px;}table#data_preview2_'+ selector +' th{text-align: center;} .bolded{font-weight: bold;}</style>'; inlineQty += '<h4 id="secondary_table_title" class="secondary_table_title_'+selector+' hide" style="font-size: 25px; font-weight: 700; color: #103D39; text-align: center">Suburb Selection | Add/Remove Suburbs</h4>'; // Input Field inlineQty += '<div id="dataTable2filters_'+selector+'" class="form container col-md-9 hide" style="left: 12.5%;">' //margin-top: 20px; inlineQty += '<div class="row">' inlineQty += '<div class="col-xs-4">' inlineQty += '<div class="input-group">' inlineQty += '<span style="background-color: #379E8F; color: white;" class="input-group-addon">Post Code Filter</span>'; inlineQty += '<input class="form-control" id="filter_postcode_'+selector+'" aria-describedby="filterPostCode" placeholder="Enter Post Code">'; inlineQty += '</div></div>' inlineQty += '<div class="col-xs-5">' inlineQty += '<div class="input-group">' inlineQty += '<span style="background-color: #379E8F; color: white;" class="input-group-addon">Suburb Name Filter</span>'; inlineQty += '<input class="form-control" id="filter_sub_name_'+selector+'" aria-describedby="filterSubName" placeholder="Enter Suburb Name">'; inlineQty += '</div></div>' inlineQty += '<div class="col-xs-3">' inlineQty += '<input type="button" style="background-color: #FBEA51; color: #103D39; font-weight: 700; border-color: transparent; border-width: 2px; border-radius: 15px; height: 30px;" class="form-control add_filter" id="add_filter_'+selector+'" value="Add Suburb"></input>' inlineQty += '</div>' // inlineQty += '<div class="col-xs-2">' // inlineQty += '<input type="button" style="background-color: #FBEA51; color: #103D39; font-weight: 700; border-color: transparent; border-width: 2px; border-radius: 15px; height: 30px;" class="form-control remove_filter" id="remove_filter_'+selector+'" value="Remove Suburb"></input>' // inlineQty += '</div>' inlineQty += '</div>' inlineQty += '</div>' inlineQty += '<table id="data_preview2_'+ selector +'" class="table table-responsive table-striped tablesorter hide" style="width: 100%;">'; inlineQty += '<thead style="color: white; background-color: #379E8F;">'; inlineQty += '<tr class="text-center">'; inlineQty += '</tr>'; inlineQty += '</thead>'; inlineQty += '<tbody id="result_data" class="result-data"></tbody>'; // inlineQty += '' inlineQty += '</table>'; return inlineQty; } function dataTable3(selector) { var inlineQty = '<style>table#data_preview3_'+ selector +' {font-size: 12px;text-align: center;border: none; background-color: white;}.dataTables_wrapper {font-size: 14px;}table#data_preview3_'+ selector +' th{text-align: center;} .bolded{font-weight: bold;}</style>'; inlineQty += '<h4 id="secondary_table_title" class="secondary_table_title_'+selector+' hide" style="font-size: 25px; font-weight: 700; color: #103D39; text-align: center">Suburb Selection | Add/Remove Suburbs</h4>'; // Input Field inlineQty += '<div id="dataTable2filters_'+selector+'" class="form container col-md-9 hide" style="left: 12.5%;">' //margin-top: 20px; inlineQty += '<div class="row">' inlineQty += '<div class="col-xs-4">' inlineQty += '<div class="input-group">' inlineQty += '<span style="background-color: #379E8F; color: white;" class="input-group-addon">Post Code Filter</span>'; inlineQty += '<input class="form-control" id="filter_postcode_'+selector+'" aria-describedby="filterPostCode" placeholder="Enter Post Code">'; inlineQty += '</div></div>' inlineQty += '<div class="col-xs-5">' inlineQty += '<div class="input-group">' inlineQty += '<span style="background-color: #379E8F; color: white;" class="input-group-addon">Suburb Name Filter</span>'; inlineQty += '<input class="form-control" id="filter_sub_name_'+selector+'" aria-describedby="filterSubName" placeholder="Enter Suburb Name">'; inlineQty += '</div></div>' inlineQty += '<div class="col-xs-3">' inlineQty += '<input type="button" style="background-color: #FBEA51; color: #103D39; font-weight: 700; border-color: transparent; border-width: 2px; border-radius: 15px; height: 30px;" class="form-control add_filter" id="add_filter_'+selector+'" value="Add Suburb"></input>' inlineQty += '</div>' // inlineQty += '<div class="col-xs-2">' // inlineQty += '<input type="button" style="background-color: #FBEA51; color: #103D39; font-weight: 700; border-color: transparent; border-width: 2px; border-radius: 15px; height: 30px;" class="form-control remove_filter" id="remove_filter_'+selector+'" value="Remove Suburb"></input>' // inlineQty += '</div>' inlineQty += '</div>' inlineQty += '</div>' inlineQty += '<table id="data_preview3_'+ selector +'" class="table table-responsive table-striped tablesorter hide" style="width: 100%;">'; inlineQty += '<thead style="color: white; background-color: #379E8F;">'; inlineQty += '<tr class="text-center">'; inlineQty += '</tr>'; inlineQty += '</thead>'; inlineQty += '<tbody id="result_data" class="result-data"></tbody>'; // inlineQty += '' inlineQty += '</table>'; return inlineQty; } function zeeDropdownSection(zeeid) { var inlineQty = '<div class="form-group container zeeDropdown">'; inlineQty += '<div class="row col-xs-6" style="left: 25%; margin-top: 20px;">'; //col-xs-6 d-flex justify-content-center inlineQty += '<div class="input-group">'; inlineQty += '<span style="background-color: #379E8F; color: white;" class="input-group-addon">Franchisee</span>'; inlineQty += '<select id="zee_filter_dropdown" class="form-control" required>'; inlineQty += '<option></option>'; var zeesSearch = search.load({ type: 'partner', id: 'customsearch_smc_franchisee' }); // zeesSearch.filters.push(search.createFilter({ // name: 'entityid', // operator: search.Operator.DOESNOTSTARTWITH, // values: 'Test' // })) var zeesSearchResults = zeesSearch.run(); log.audit({ title: 'JSON Stringify - zeesSearchResults', details: JSON.stringify(zeesSearchResults) }) zeesSearchResults.each(function (zeesSearchResult) { var zee_id = zeesSearchResult.getValue({ name: 'internalid', summmary: search.Summary.GROUP }); var zee_name = zeesSearchResult.getValue({ name: 'companyname', summmary: search.Summary.GROUP }); var zee_state = zeesSearchResult.getText({ name: 'location' }); if (zee_id == zeeid) { inlineQty += '<option value="' + zee_id + '" state="' + zee_state + '" selected>' + zee_name + '</option>'; } else { inlineQty += '<option value="' + zee_id + '" state="' + zee_state + '">' + zee_name + '</option>'; } return true; }); inlineQty += '</select>'; inlineQty += '</div>'; inlineQty += '</div></div>'; return inlineQty; } function updateSaveRecord(pageNum, pageLength) { // Save Edit var inlineQty = '<div class="form-group container save_record button_section" style="margin-top: 20px;">'; inlineQty += '<div class="row">'; inlineQty += '<div class="col-xs-4">'; // if (pageNum != 0){ inlineQty += '<input type="button" style="background-color: #FBEA51; color: #103D39; font-weight: 700; border-color: transparent; border-width: 2px; border-radius: 15px; height: 30px;" class="form-control previous_btn hide" id="previousPage" value="Previous Page"></input>'; // } inlineQty += '</div>'; inlineQty += '<div class="col-xs-4">'; inlineQty += '<input type="button" style="background-color: #379E8F; color: white; font-weight: 700; border-color: transparent; border-width: 2px; border-radius: 15px; height: 30px;" class="form-control submit_btn hide" id="updateSaveRecord" value="Submit"></input>'; inlineQty += '</div>'; inlineQty += '<div class="col-xs-4">'; // if (pageNum != pageLength){ inlineQty += '<input type="button" style="background-color: #FBEA51;color: #103D39; font-weight: 700; border-color: transparent; border-width: 2px; border-radius: 15px; height: 30px;" class="form-control next_btn hide" id="nextPage" value="Next Page"></input>'; // } inlineQty += '</div>'; inlineQty += '</div></div>'; return inlineQty; } function tabsSection() { var inlineQty = '<div>'; // Tabs headers inlineQty += '<style>.nav > li.active > a, .nav > li.active > a:focus, .nav > li.active > a:hover { background-color: #379E8F; color: #fff }'; inlineQty += '.nav > li > a, .nav > li > a:focus, .nav > li > a:hover { margin-left: 5px; margin-right: 5px; border: 2px solid #379E8F; color: #379E8F; }'; inlineQty += '</style>'; inlineQty += '<div style="width: 95%; margin:auto; margin-bottom: 30px; margin-top: 30px;",><ul class="nav nav-pills nav-justified" style="margin:0%; ">'; inlineQty += '<li role="presentation" class="active"><a data-toggle="tab" href="#mp_standard"><b>MP Standard</b></a></li>'; inlineQty += '<li role="presentation" class=""><a data-toggle="tab" href="#mp_express"><b>MP Express</b></a></li>'; inlineQty += '<li role="presentation" class=""><a data-toggle="tab" href="#s_au_express"><b>Sendle AU Express</b></a></li>'; inlineQty += '</ul></div>'; // Tabs content // MP Standard inlineQty += '<div class="tab-content">'; inlineQty += '<div role="tabpanel" class="tab-pane active" id="mp_standard">'; inlineQty += loadingSection(); inlineQty += dataTable3('mp_standard'); inlineQty += '</div>'; // MP Express inlineQty += '<div role="tabpanel" class="tab-pane" id="mp_express">'; inlineQty += loadingSection(); inlineQty += dataTable2('mp_express'); inlineQty += '</div>'; // Sendle AU Express inlineQty += '<div role="tabpanel" class="tab-pane" id="s_au_express">'; inlineQty += loadingSection(); inlineQty += dataTable2('s_au_express'); inlineQty += '</div>'; inlineQty += '</div>'; //</div> return inlineQty; } // function mileSection() { // var inlineQty = '<div>'; // // Tabs headers // inlineQty += '<style>.nav > li.active > a, .nav > li.active > a:focus, .nav > li.active > a:hover { background-color: #379E8F; color: #fff }'; // inlineQty += '.nav > li > a, .nav > li > a:focus, .nav > li > a:hover { margin-left: 5px; margin-right: 5px; border: 2px solid #379E8F; color: #379E8F; }'; // inlineQty += '</style>'; // inlineQty += '<div style="width: 95%; margin:auto; margin-bottom: 30px; margin-top: 30px;",><ul class="nav nav-pills nav-justified" style="margin:0%; ">'; // inlineQty += '<li role="presentation" class="active"><a data-toggle="mile" href="#first_mile"><b>First Mile</b></a></li>'; // inlineQty += '<li role="presentation" class=""><a data-toggle="mile" href="#last_mile"><b>Last Mile</b></a></li>'; // inlineQty += '</ul></div>'; // // Tabs content // // First Mile // inlineQty += '<div class="tab-content">'; // inlineQty += '<div role="tabpanel" class="tab-pane tab-pane-mile active" id="first_mile">'; // inlineQty += loadingSection(); // inlineQty += dataTable('first_mile'); // inlineQty += '<br>'; // inlineQty += dataTable2('first_mile'); // inlineQty += '</div>'; // // Last Mile // inlineQty += '<div role="tabpanel" class="tab-pane tab-pane-mile" id="last_mile">'; // inlineQty += loadingSection(); // inlineQty += dataTable('last_mile'); // inlineQty += '<br>'; // inlineQty += dataTable2('last_mile'); // inlineQty += '</div>'; // inlineQty += '</div>'; //</div> // return inlineQty; // } /** * The header showing that the results are loading. * @returns {String} `inlineQty` */ function loadingSection() { var inlineQty = '<div class="form-group container loading_section"></div>'; inlineQty += '<style> .loading_section { border: 14px solid #f3f3f3; border-radius: 50%; border-top: 14px solid #379E8F; width: 90px; height: 90px; -webkit-animation: spin 2s linear infinite; /* Safari */ animation: spin 2s linear infinite;'; inlineQty += 'left: 50%; }' //position: fixed; z-index: 1000; /* Safari */ inlineQty += '@-webkit-keyframes spin {0% { -webkit-transform: rotate(0deg); } 100% { -webkit-transform: rotate(360deg); } }'; inlineQty += '@keyframes spin { 0% { transform: rotate(0deg); } 100% { transform: rotate(360deg); } }'; inlineQty += '</style>'; return inlineQty; } // function onclick_serviceChangePage(custid){ // $('#commRegSection').removeClass('hide'); // $('#tabSection').removeClass('hide'); // loadCustService(17029, custid); // } /** * Used to pass the values of `date_from` and `date_to` between the scripts and to Netsuite for the records and the search. * @param {String} date_iso "2020-06-01" * @returns {String} date_netsuite "1/6/2020" */ function dateISOToNetsuite(date_iso) { var date_netsuite = ''; if (!isNullorEmpty(date_iso)) { var date_utc = new Date(date_iso); // var date_netsuite = nlapiDateToString(date_utc); var date_netsuite = format.format({ value: date_utc, type: format.Type.DATE }); } return date_netsuite; } function isNullorEmpty(strVal) { return (strVal == null || strVal == '' || strVal == 'null' || strVal == undefined || strVal == 'undefined' || strVal == '- None -'); } return { onRequest: onRequest } });
213
[{"tag": "KEY", "value": "sha384-aJ21OjlMXNL5UyIl/XNwTMqvzeRMZH2w8c5cRVpzpU8Y5bApTppSuUkhZXN0VxHd", "start": 3177, "end": 3248}, {"tag": "KEY", "value": "sha384-HSMxcRTRxnN+Bdg0JdbxYKrThecOKuH5zCYotlSAcp1+c8xmyTe9GYg1l9a69psu", "start": 2954, "end": 3025}, {"tag": "KEY", "value": "sha384-nvAa0+6Qg9clwYCGGPpDQLVpLNn0fRaROjHqs13t4Ggj3Ez50XnGQqc/r8MhnRDZ", "start": 2557, "end": 2628}]
true
3
/** * @NApiVersion 2.0 * @NScriptType Suitelet * * Module Description * * NSVersion Date Author * 2.00 2021-09-20 09:33:08 Anesu * * Description: xxxxxxxx * * @Last Modified by: Anesu * @Last Modified time: 2021-09-20 09:33:08 * */ define(['N/ui/serverWidget', 'N/email', 'N/runtime', 'N/search', 'N/record', 'N/http', 'N/log', 'N/redirect', 'N/task', 'N/format'], function (ui, email, runtime, search, record, http, log, redirect, task, format) { var zee = 0; var role = 0; var baseURL = 'https://1048144.app.netsuite.com'; if (runtime.EnvType == "SANDBOX") { baseURL = 'https://1048144-sb3.app.netsuite.com'; } role = runtime.getCurrentUser().role; if (role == 1000) { zee = runtime.getCurrentUser().id; } else if (role == 3) { //Administrator zee = 6; //test } else if (role == 1032) { // System Support zee = 425904; //test-AR } function onRequest(context) { if (context.request.method === 'GET') { var is_params = false; type = context.request.parameters.type; var params_params = context.request.parameters if (!isNullorEmpty(params_params.custparam_params)) { var params = JSON.parse(context.request.parameters.custparam_params); } var zee_id = 0; var zee_name = ''; zee_state = ''; var selector = ''; /** * If Comming from 1.0 Page */ var selection_params = context.request.parameters; // &zeename=Surry+Hills&zeeid=469&pagenum=0&zeestate=NSW if (!isNullorEmpty(selection_params.zeeid)) { zee_id = selection_params.zeeid; zee_name = selection_params.zeename; zee_state = selection_params.zeestate; if (selection_params.selector){ selector = selection_params.selector } } if (!isNullorEmpty(params)) { is_params = true; zee_id = parseInt(params.zeeid); zee_name = params.zeename; zee_state = params.zeestate; if (params.selector){ selector = params.selector; } } var form = ui.createForm({ title: ' ' }); // Load jQuery var inlineHtml = '<script src="https://code.jquery.com/jquery-1.12.4.min.js" integrity="949d1u22cbffbrarjh182eig55721odj" crossorigin="anonymous"></script>'; // Load Tooltip inlineHtml += '<script src="https://unpkg.com/@popperjs/core@2"></script>'; // Load Bootstrap inlineHtml += '<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/3.4.1/css/bootstrap.min.css" integrity="ngw6fo1pu3tjgnp9jnlp7vnwvfqb9yn7" crossorigin="anonymous">'; inlineHtml += '<script src="https://stackpath.bootstrapcdn.com/bootstrap/3.4.1/js/bootstrap.min.js" integrity="caf86f4uutaoxfysmf7anj01xl6sv3ps" crossorigin="anonymous"></script>'; // Load DataTables // inlineHtml += '<link rel="stylesheet" type="text/css" href="//cdn.datatables.net/1.10.21/css/jquery.dataTables.min.css">'; inlineHtml += '<link rel="stylesheet" type="text/css" href="//cdn.datatables.net/1.12.0/css/jquery.dataTables.min.css">'; inlineHtml += '<script type="text/javascript" charset="utf8" src="//cdn.datatables.net/1.10.21/js/jquery.dataTables.min.js"></script>'; inlineHtml += '<script type="text/javascript" charset="utf8" src="//cdn.datatables.net/rowgroup/1.1.3/js/dataTables.rowGroup.min.js"></script> ' inlineHtml += '<script type="text/javascript" charset="utf8" src="//cdn.datatables.net/buttons/2.0.0/js/dataTables.buttons.min.js"></script> ' inlineHtml += '<script type="text/javascript" charset="utf8" src="//cdnjs.cloudflare.com/ajax/libs/jszip/3.1.3/jszip.min.js"></script> ' inlineHtml += '<script type="text/javascript" charset="utf8" src="//cdnjs.cloudflare.com/ajax/libs/pdfmake/0.1.53/pdfmake.min.js"></script> ' inlineHtml += '<script type="text/javascript" charset="utf8" src="//cdnjs.cloudflare.com/ajax/libs/pdfmake/0.1.53/vfs_fonts.js"></script> ' inlineHtml += '<script type="text/javascript" charset="utf8" src="//cdn.datatables.net/buttons/2.0.0/js/buttons.html5.min.js"></script> ' inlineHtml += '<script type="text/javascript" charset="utf8" src="//cdn.datatables.net/buttons/2.0.0/js/buttons.print.min.js"></script> ' // Load Netsuite stylesheet and script inlineHtml += '<link rel="stylesheet" href="https://1048144.app.netsuite.com/core/media/media.nl?id=2060796&c=1048144&h=9ee6accfd476c9cae718&_xt=.css"/>'; inlineHtml += '<script src="https://1048144.app.netsuite.com/core/media/media.nl?id=2060797&c=1048144&h=ef2cda20731d146b5e98&_xt=.js"></script>'; inlineHtml += '<link type="text/css" rel="stylesheet" href="https://1048144.app.netsuite.com/core/media/media.nl?id=2090583&c=1048144&h=a0ef6ac4e28f91203dfe&_xt=.css">'; inlineHtml += '<style>.mandatory{color:red;}</style>'; // Load Bootstrap-Select inlineHtml += '<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap-select@1.13.14/dist/css/bootstrap-select.min.css">'; inlineHtml += '<script src="https://cdn.jsdelivr.net/npm/bootstrap-select@1.13.14/dist/js/bootstrap-select.min.js"></script>'; // Semantic Select inlineHtml += '<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/semantic-ui/2.2.13/semantic.min.css">'; inlineHtml += '<script src="https://cdnjs.cloudflare.com/ajax/libs/semantic-ui/2.2.13/semantic.min.js"></script>'; // Load Search In Dropdown // inlineHtml += '<link href="https://cdnjs.cloudflare.com/ajax/libs/select2/4.0.6-rc.0/css/select2.min.css" rel="stylesheet" />'; // inlineHtml += '<script src="https://cdnjs.cloudflare.com/ajax/libs/select2/4.0.6-rc.0/js/select2.min.js"></script>'; // New Website Color Schemes // Main Color: #379E8F // Background Color: #CFE0CE // Button Color: #FBEA51 // Text Color: #103D39 // inlineHtml += '<div class="a" style="width: 100%; background-color: #CFE0CE; padding: 20px; min-height: 100vh; height: 100%; ">'; // margin-top: -40px // // inlineHtml += '<h1 style="text-align: center; color: #103D39; display: inline-block; font-size: 22px; font-weight: bold; line-height: 33px; vertical-align: top; margin-bottom: 4px;">Consolidation Invoice</h1>'; // inlineHtml += '<style>.nav > li.active > a, .nav > li.active > a:focus, .nav > li.active > a:hover { background-color: #379E8F; color: #fff }'; // inlineHtml += '.nav > li > a, .nav > li > a:focus, .nav > li > a:hover { margin-left: 5px; margin-right: 5px; border: 2px solid #379E8F; color: #379E8F; }'; // inlineHtml += '</style>'; // Define alert window. inlineHtml += '<div class="container" style="margin-top:14px;" hidden><div id="alert" class="alert alert-danger fade in"></div></div>'; // Click for Instructions inlineHtml += '<button type="button" class="btn btn-sm btn-info instruction_button" data-toggle="collapse" data-target="#demo" ">Click for Instructions</button><div id="demo" style="background-color: #cfeefc !important;border: 1px solid #417ed9;padding: 10px 10px 10px 20px;width:96%;position:absolute" class="collapse"><b><u>IMPORTANT INSTRUCTIONS:</u></b>'; inlineHtml += '<ul>Welcome to Suburb Mapping. To Start, Select Franchisee. Once Selected, A list of suburbs will appear according to that Franchisees State Value. Select appropriate Primary and Secondary Driver Information and Save</ul>'; inlineHtml += '<li>Table Data:<ul><li><b>Primary Table</b><ul><li> This Table Displays the list of Suburbs chosen by Franchisee in Suburb Selecitons Page. Please <a href="https://1048144.app.netsuite.com/app/site/hosting/scriptlet.nl?script=1065&deploy=1&compid=1048144&zee=' + zee_id + '&opsync=true">click here</a> to redirect.</li></ul></li> <li><b>Secondary Table</b><ul> Suburbs based on filter information. Please filter by Post Code or Suburb Name to view associated Information. </li></ul></li></ul></li>'; // inlineHtml += '<ul><li><button type="button" class="btn-xs" disabled><span class="span_class glyphicon glyphicon-pencil"></span></button> - Click to open Notes Section for Selected Invoice. (Notes Section is seperate from User Notes)</li>'; // inlineHtml += '<li><button type="button" class="btn-xs btn-secondary" disabled><span class="glyphicon glyphicon-eye-open"></span></button> - Click to Set Invoice has "Viewed" by a member of the Finance Team.</li>'; // inlineHtml += '<li><button type="button" class="btn-xs btn-info" disabled><span class="glyphicon glyphicon-time"></span></button> - Click to view Snooze Timers</li><li><button type="button" class="timer-1day form=control btn-xs btn-info" disabled><span class="span_class">1 Day</span></button> - Click to select Snooze duration of invoice from Debt Collections Page.</li>'; inlineHtml += '</li></ul></div>'; // Define information window. inlineHtml += '<div class="container" hidden><p id="info" class="alert alert-info"></p></div>'; inlineHtml += '<div style="margin-top: -40px"><br/>'; // Buttons // inlineHtml += '<button style="margin-left: 10px; margin-right: 5px; background-color: #FBEA51; color: #103D39; font-weight: 700; border-color: transparent; border-width: 2px; border-radius: 15px; height: 30px" type="button" id="new_agreement" onclick="">New Franchisee Agreement</button>'; if (!isNullorEmpty(zee_id) || zee_id != 0) { inlineHtml += '<h1 class="title_header" style="font-size: 25px; font-weight: 700; color: #103D39; text-align: center">Suburb & Operator Mapping: ' + zee_name + ' </h1>'; } else { inlineHtml += '<h1 class="title_header" style="font-size: 25px; font-weight: 700; color: #103D39; text-align: center">Suburb & Operator Mapping</h1>'; } // inlineHtml += '<button style="margin-left: 10px; margin-right: 5px; background-color: #FBEA51; color: #103D39; font-weight: 700; border-color: transparent; border-width: 2px; border-radius: 15px; height: 30px" type="button" id="downloadCSV" onclick="">Export Complete CSV</button>'; if (zee_id != 0 || !isNullorEmpty(zee_id)) { inlineHtml += '<button style="margin-left: 10px; margin-right: 5px; background-color: #FBEA51; color: #103D39; font-weight: 700; border-color: transparent; border-width: 2px; border-radius: 15px; height: 30px" type="button" id="first_sub_selection" onclick="">Add/Remove - First Mile Suburb</button>'; inlineHtml += '<button style="margin-left: 10px; margin-right: 5px; background-color: #FBEA51; color: #103D39; font-weight: 700; border-color: transparent; border-width: 2px; border-radius: 15px; height: 30px" type="button" id="last_sub_selection" onclick="">Add/Remove - Last Mile Suburb</button>'; // inlineHtml += '<button style="margin-left: 10px; margin-right: 5px; background-color: #FBEA51; color: #103D39; font-weight: 700; border-color: transparent; border-width: 2px; border-radius: 15px; height: 30px" type="button" id="lodgement_selection" onclick="">Lodgement Location Selection</button>'; // inlineHtml += '<button style="margin-left: 10px; margin-right: 5px; font-weight: 700; border-color: transparent; border-width: 2px; border-radius: 15px; height: 30px" type="button" id="toggle-columns" class="toggle-columns btn-success" >Show/Hide Columns</button>' //style="background-color: #379E8F; // Show/Hide Child Table. // inlineHtml += '<button style="margin-left: 10px; margin-right: 5px; background-color: #FBEA51; color: #103D39; font-weight: 700; border-color: transparent; border-width: 2px; border-radius: 15px; height: 30px" type="button" id="btn-show-all-children" class="btn-success" >Expand All</button>' //style="background-color: #379E8F; // inlineHtml += '<button style="margin-left: 10px; margin-right: 5px; background-color: #FBEA51; color: #103D39; font-weight: 700; border-color: transparent; border-width: 2px; border-radius: 15px; height: 30px" type="button" id="btn-hide-all-children" class="btn-success" >Collapse All</button>' //style="background-color: #379E8F; } inlineHtml += zeeDropdownSection(zee_id); if (zee_id != 0 || !isNullorEmpty(zee_id)) { inlineHtml += tabsSection(); inlineHtml += updateSaveRecord(); } inlineHtml += '</div></div>' form.addField({ id: 'preview_table', label: 'inlinehtml', type: 'inlinehtml' }).updateLayoutType({ layoutType: ui.FieldLayoutType.STARTROW }).defaultValue = inlineHtml; form.addField({ id: 'custpage_suburb_mapping_zee_id', label: 'Zee ID', type: ui.FieldType.TEXT }).updateDisplayType({ displayType: ui.FieldDisplayType.HIDDEN }).defaultValue = zee_id; form.addField({ id: 'custpage_suburb_mapping_zee_name', label: 'Zee ID', type: ui.FieldType.TEXT }).updateDisplayType({ displayType: ui.FieldDisplayType.HIDDEN }).defaultValue = zee_name; form.addField({ id: 'custpage_suburb_mapping_zee_state', label: 'Zee ID', type: ui.FieldType.TEXT }).updateDisplayType({ displayType: ui.FieldDisplayType.HIDDEN }).defaultValue = zee_state; form.addField({ id: 'custpage_suburb_mapping_selector', label: 'Selector Option', type: ui.FieldType.TEXT }).updateDisplayType({ displayType: ui.FieldDisplayType.HIDDEN }).defaultValue = selector; form.addSubmitButton({ label: ' ' }); form.clientScriptFileId = 5925500; // context.response.writePage(form); } else { } } /** * The table that will display the differents invoices linked to the franchisee and the time period. * @return {String} inlineQty */ function dataTable2(selector) { var inlineQty = '<style>table#data_preview2_'+ selector +' {font-size: 12px;text-align: center;border: none; background-color: white;}.dataTables_wrapper {font-size: 14px;}table#data_preview2_'+ selector +' th{text-align: center;} .bolded{font-weight: bold;}</style>'; inlineQty += '<h4 id="secondary_table_title" class="secondary_table_title_'+selector+' hide" style="font-size: 25px; font-weight: 700; color: #103D39; text-align: center">Suburb Selection | Add/Remove Suburbs</h4>'; // Input Field inlineQty += '<div id="dataTable2filters_'+selector+'" class="form container col-md-9 hide" style="left: 12.5%;">' //margin-top: 20px; inlineQty += '<div class="row">' inlineQty += '<div class="col-xs-4">' inlineQty += '<div class="input-group">' inlineQty += '<span style="background-color: #379E8F; color: white;" class="input-group-addon">Post Code Filter</span>'; inlineQty += '<input class="form-control" id="filter_postcode_'+selector+'" aria-describedby="filterPostCode" placeholder="Enter Post Code">'; inlineQty += '</div></div>' inlineQty += '<div class="col-xs-5">' inlineQty += '<div class="input-group">' inlineQty += '<span style="background-color: #379E8F; color: white;" class="input-group-addon">Suburb Name Filter</span>'; inlineQty += '<input class="form-control" id="filter_sub_name_'+selector+'" aria-describedby="filterSubName" placeholder="Enter Suburb Name">'; inlineQty += '</div></div>' inlineQty += '<div class="col-xs-3">' inlineQty += '<input type="button" style="background-color: #FBEA51; color: #103D39; font-weight: 700; border-color: transparent; border-width: 2px; border-radius: 15px; height: 30px;" class="form-control add_filter" id="add_filter_'+selector+'" value="Add Suburb"></input>' inlineQty += '</div>' // inlineQty += '<div class="col-xs-2">' // inlineQty += '<input type="button" style="background-color: #FBEA51; color: #103D39; font-weight: 700; border-color: transparent; border-width: 2px; border-radius: 15px; height: 30px;" class="form-control remove_filter" id="remove_filter_'+selector+'" value="Remove Suburb"></input>' // inlineQty += '</div>' inlineQty += '</div>' inlineQty += '</div>' inlineQty += '<table id="data_preview2_'+ selector +'" class="table table-responsive table-striped tablesorter hide" style="width: 100%;">'; inlineQty += '<thead style="color: white; background-color: #379E8F;">'; inlineQty += '<tr class="text-center">'; inlineQty += '</tr>'; inlineQty += '</thead>'; inlineQty += '<tbody id="result_data" class="result-data"></tbody>'; // inlineQty += '' inlineQty += '</table>'; return inlineQty; } function dataTable3(selector) { var inlineQty = '<style>table#data_preview3_'+ selector +' {font-size: 12px;text-align: center;border: none; background-color: white;}.dataTables_wrapper {font-size: 14px;}table#data_preview3_'+ selector +' th{text-align: center;} .bolded{font-weight: bold;}</style>'; inlineQty += '<h4 id="secondary_table_title" class="secondary_table_title_'+selector+' hide" style="font-size: 25px; font-weight: 700; color: #103D39; text-align: center">Suburb Selection | Add/Remove Suburbs</h4>'; // Input Field inlineQty += '<div id="dataTable2filters_'+selector+'" class="form container col-md-9 hide" style="left: 12.5%;">' //margin-top: 20px; inlineQty += '<div class="row">' inlineQty += '<div class="col-xs-4">' inlineQty += '<div class="input-group">' inlineQty += '<span style="background-color: #379E8F; color: white;" class="input-group-addon">Post Code Filter</span>'; inlineQty += '<input class="form-control" id="filter_postcode_'+selector+'" aria-describedby="filterPostCode" placeholder="Enter Post Code">'; inlineQty += '</div></div>' inlineQty += '<div class="col-xs-5">' inlineQty += '<div class="input-group">' inlineQty += '<span style="background-color: #379E8F; color: white;" class="input-group-addon">Suburb Name Filter</span>'; inlineQty += '<input class="form-control" id="filter_sub_name_'+selector+'" aria-describedby="filterSubName" placeholder="Enter Suburb Name">'; inlineQty += '</div></div>' inlineQty += '<div class="col-xs-3">' inlineQty += '<input type="button" style="background-color: #FBEA51; color: #103D39; font-weight: 700; border-color: transparent; border-width: 2px; border-radius: 15px; height: 30px;" class="form-control add_filter" id="add_filter_'+selector+'" value="Add Suburb"></input>' inlineQty += '</div>' // inlineQty += '<div class="col-xs-2">' // inlineQty += '<input type="button" style="background-color: #FBEA51; color: #103D39; font-weight: 700; border-color: transparent; border-width: 2px; border-radius: 15px; height: 30px;" class="form-control remove_filter" id="remove_filter_'+selector+'" value="Remove Suburb"></input>' // inlineQty += '</div>' inlineQty += '</div>' inlineQty += '</div>' inlineQty += '<table id="data_preview3_'+ selector +'" class="table table-responsive table-striped tablesorter hide" style="width: 100%;">'; inlineQty += '<thead style="color: white; background-color: #379E8F;">'; inlineQty += '<tr class="text-center">'; inlineQty += '</tr>'; inlineQty += '</thead>'; inlineQty += '<tbody id="result_data" class="result-data"></tbody>'; // inlineQty += '' inlineQty += '</table>'; return inlineQty; } function zeeDropdownSection(zeeid) { var inlineQty = '<div class="form-group container zeeDropdown">'; inlineQty += '<div class="row col-xs-6" style="left: 25%; margin-top: 20px;">'; //col-xs-6 d-flex justify-content-center inlineQty += '<div class="input-group">'; inlineQty += '<span style="background-color: #379E8F; color: white;" class="input-group-addon">Franchisee</span>'; inlineQty += '<select id="zee_filter_dropdown" class="form-control" required>'; inlineQty += '<option></option>'; var zeesSearch = search.load({ type: 'partner', id: 'customsearch_smc_franchisee' }); // zeesSearch.filters.push(search.createFilter({ // name: 'entityid', // operator: search.Operator.DOESNOTSTARTWITH, // values: 'Test' // })) var zeesSearchResults = zeesSearch.run(); log.audit({ title: 'JSON Stringify - zeesSearchResults', details: JSON.stringify(zeesSearchResults) }) zeesSearchResults.each(function (zeesSearchResult) { var zee_id = zeesSearchResult.getValue({ name: 'internalid', summmary: search.Summary.GROUP }); var zee_name = zeesSearchResult.getValue({ name: 'companyname', summmary: search.Summary.GROUP }); var zee_state = zeesSearchResult.getText({ name: 'location' }); if (zee_id == zeeid) { inlineQty += '<option value="' + zee_id + '" state="' + zee_state + '" selected>' + zee_name + '</option>'; } else { inlineQty += '<option value="' + zee_id + '" state="' + zee_state + '">' + zee_name + '</option>'; } return true; }); inlineQty += '</select>'; inlineQty += '</div>'; inlineQty += '</div></div>'; return inlineQty; } function updateSaveRecord(pageNum, pageLength) { // Save Edit var inlineQty = '<div class="form-group container save_record button_section" style="margin-top: 20px;">'; inlineQty += '<div class="row">'; inlineQty += '<div class="col-xs-4">'; // if (pageNum != 0){ inlineQty += '<input type="button" style="background-color: #FBEA51; color: #103D39; font-weight: 700; border-color: transparent; border-width: 2px; border-radius: 15px; height: 30px;" class="form-control previous_btn hide" id="previousPage" value="Previous Page"></input>'; // } inlineQty += '</div>'; inlineQty += '<div class="col-xs-4">'; inlineQty += '<input type="button" style="background-color: #379E8F; color: white; font-weight: 700; border-color: transparent; border-width: 2px; border-radius: 15px; height: 30px;" class="form-control submit_btn hide" id="updateSaveRecord" value="Submit"></input>'; inlineQty += '</div>'; inlineQty += '<div class="col-xs-4">'; // if (pageNum != pageLength){ inlineQty += '<input type="button" style="background-color: #FBEA51;color: #103D39; font-weight: 700; border-color: transparent; border-width: 2px; border-radius: 15px; height: 30px;" class="form-control next_btn hide" id="nextPage" value="Next Page"></input>'; // } inlineQty += '</div>'; inlineQty += '</div></div>'; return inlineQty; } function tabsSection() { var inlineQty = '<div>'; // Tabs headers inlineQty += '<style>.nav > li.active > a, .nav > li.active > a:focus, .nav > li.active > a:hover { background-color: #379E8F; color: #fff }'; inlineQty += '.nav > li > a, .nav > li > a:focus, .nav > li > a:hover { margin-left: 5px; margin-right: 5px; border: 2px solid #379E8F; color: #379E8F; }'; inlineQty += '</style>'; inlineQty += '<div style="width: 95%; margin:auto; margin-bottom: 30px; margin-top: 30px;",><ul class="nav nav-pills nav-justified" style="margin:0%; ">'; inlineQty += '<li role="presentation" class="active"><a data-toggle="tab" href="#mp_standard"><b>MP Standard</b></a></li>'; inlineQty += '<li role="presentation" class=""><a data-toggle="tab" href="#mp_express"><b>MP Express</b></a></li>'; inlineQty += '<li role="presentation" class=""><a data-toggle="tab" href="#s_au_express"><b>Sendle AU Express</b></a></li>'; inlineQty += '</ul></div>'; // Tabs content // MP Standard inlineQty += '<div class="tab-content">'; inlineQty += '<div role="tabpanel" class="tab-pane active" id="mp_standard">'; inlineQty += loadingSection(); inlineQty += dataTable3('mp_standard'); inlineQty += '</div>'; // MP Express inlineQty += '<div role="tabpanel" class="tab-pane" id="mp_express">'; inlineQty += loadingSection(); inlineQty += dataTable2('mp_express'); inlineQty += '</div>'; // Sendle AU Express inlineQty += '<div role="tabpanel" class="tab-pane" id="s_au_express">'; inlineQty += loadingSection(); inlineQty += dataTable2('s_au_express'); inlineQty += '</div>'; inlineQty += '</div>'; //</div> return inlineQty; } // function mileSection() { // var inlineQty = '<div>'; // // Tabs headers // inlineQty += '<style>.nav > li.active > a, .nav > li.active > a:focus, .nav > li.active > a:hover { background-color: #379E8F; color: #fff }'; // inlineQty += '.nav > li > a, .nav > li > a:focus, .nav > li > a:hover { margin-left: 5px; margin-right: 5px; border: 2px solid #379E8F; color: #379E8F; }'; // inlineQty += '</style>'; // inlineQty += '<div style="width: 95%; margin:auto; margin-bottom: 30px; margin-top: 30px;",><ul class="nav nav-pills nav-justified" style="margin:0%; ">'; // inlineQty += '<li role="presentation" class="active"><a data-toggle="mile" href="#first_mile"><b>First Mile</b></a></li>'; // inlineQty += '<li role="presentation" class=""><a data-toggle="mile" href="#last_mile"><b>Last Mile</b></a></li>'; // inlineQty += '</ul></div>'; // // Tabs content // // First Mile // inlineQty += '<div class="tab-content">'; // inlineQty += '<div role="tabpanel" class="tab-pane tab-pane-mile active" id="first_mile">'; // inlineQty += loadingSection(); // inlineQty += dataTable('first_mile'); // inlineQty += '<br>'; // inlineQty += dataTable2('first_mile'); // inlineQty += '</div>'; // // Last Mile // inlineQty += '<div role="tabpanel" class="tab-pane tab-pane-mile" id="last_mile">'; // inlineQty += loadingSection(); // inlineQty += dataTable('last_mile'); // inlineQty += '<br>'; // inlineQty += dataTable2('last_mile'); // inlineQty += '</div>'; // inlineQty += '</div>'; //</div> // return inlineQty; // } /** * The header showing that the results are loading. * @returns {String} `inlineQty` */ function loadingSection() { var inlineQty = '<div class="form-group container loading_section"></div>'; inlineQty += '<style> .loading_section { border: 14px solid #f3f3f3; border-radius: 50%; border-top: 14px solid #379E8F; width: 90px; height: 90px; -webkit-animation: spin 2s linear infinite; /* Safari */ animation: spin 2s linear infinite;'; inlineQty += 'left: 50%; }' //position: fixed; z-index: 1000; /* Safari */ inlineQty += '@-webkit-keyframes spin {0% { -webkit-transform: rotate(0deg); } 100% { -webkit-transform: rotate(360deg); } }'; inlineQty += '@keyframes spin { 0% { transform: rotate(0deg); } 100% { transform: rotate(360deg); } }'; inlineQty += '</style>'; return inlineQty; } // function onclick_serviceChangePage(custid){ // $('#commRegSection').removeClass('hide'); // $('#tabSection').removeClass('hide'); // loadCustService(17029, custid); // } /** * Used to pass the values of `date_from` and `date_to` between the scripts and to Netsuite for the records and the search. * @param {String} date_iso "2020-06-01" * @returns {String} date_netsuite "1/6/2020" */ function dateISOToNetsuite(date_iso) { var date_netsuite = ''; if (!isNullorEmpty(date_iso)) { var date_utc = new Date(date_iso); // var date_netsuite = nlapiDateToString(date_utc); var date_netsuite = format.format({ value: date_utc, type: format.Type.DATE }); } return date_netsuite; } function isNullorEmpty(strVal) { return (strVal == null || strVal == '' || strVal == 'null' || strVal == undefined || strVal == 'undefined' || strVal == '- None -'); } return { onRequest: onRequest } });
true
/** * @NApiVersion 2.0 * @NScriptType Suitelet * * Module Description * * NSVersion Date Author * 2.00 2021-09-20 09:33:08 Anesu * * Description: xxxxxxxx * * @Last Modified by: Anesu * @Last Modified time: 2021-09-20 09:33:08 * */ define(['N/ui/serverWidget', 'N/email', 'N/runtime', 'N/search', 'N/record', 'N/http', 'N/log', 'N/redirect', 'N/task', 'N/format'], function (ui, email, runtime, search, record, http, log, redirect, task, format) { var zee = 0; var role = 0; var baseURL = 'https://1048144.app.netsuite.com'; if (runtime.EnvType == "SANDBOX") { baseURL = 'https://1048144-sb3.app.netsuite.com'; } role = runtime.getCurrentUser().role; if (role == 1000) { zee = runtime.getCurrentUser().id; } else if (role == 3) { //Administrator zee = 6; //test } else if (role == 1032) { // System Support zee = 425904; //test-AR } function onRequest(context) { if (context.request.method === 'GET') { var is_params = false; type = context.request.parameters.type; var params_params = context.request.parameters if (!isNullorEmpty(params_params.custparam_params)) { var params = JSON.parse(context.request.parameters.custparam_params); } var zee_id = 0; var zee_name = ''; zee_state = ''; var selector = ''; /** * If Comming from 1.0 Page */ var selection_params = context.request.parameters; // &zeename=Surry+Hills&zeeid=469&pagenum=0&zeestate=NSW if (!isNullorEmpty(selection_params.zeeid)) { zee_id = selection_params.zeeid; zee_name = selection_params.zeename; zee_state = selection_params.zeestate; if (selection_params.selector){ selector = selection_params.selector } } if (!isNullorEmpty(params)) { is_params = true; zee_id = parseInt(params.zeeid); zee_name = params.zeename; zee_state = params.zeestate; if (params.selector){ selector = params.selector; } } var form = ui.createForm({ title: ' ' }); // Load jQuery var inlineHtml = '<script src="https://code.jquery.com/jquery-1.12.4.min.js" integrity="PI:KEY:949d1u22cbffbrarjh182eig55721odjEND_PI" crossorigin="anonymous"></script>'; // Load Tooltip inlineHtml += '<script src="https://unpkg.com/@popperjs/core@2"></script>'; // Load Bootstrap inlineHtml += '<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/3.4.1/css/bootstrap.min.css" integrity="PI:KEY:ngw6fo1pu3tjgnp9jnlp7vnwvfqb9yn7END_PI" crossorigin="anonymous">'; inlineHtml += '<script src="https://stackpath.bootstrapcdn.com/bootstrap/3.4.1/js/bootstrap.min.js" integrity="PI:KEY:caf86f4uutaoxfysmf7anj01xl6sv3psEND_PI" crossorigin="anonymous"></script>'; // Load DataTables // inlineHtml += '<link rel="stylesheet" type="text/css" href="//cdn.datatables.net/1.10.21/css/jquery.dataTables.min.css">'; inlineHtml += '<link rel="stylesheet" type="text/css" href="//cdn.datatables.net/1.12.0/css/jquery.dataTables.min.css">'; inlineHtml += '<script type="text/javascript" charset="utf8" src="//cdn.datatables.net/1.10.21/js/jquery.dataTables.min.js"></script>'; inlineHtml += '<script type="text/javascript" charset="utf8" src="//cdn.datatables.net/rowgroup/1.1.3/js/dataTables.rowGroup.min.js"></script> ' inlineHtml += '<script type="text/javascript" charset="utf8" src="//cdn.datatables.net/buttons/2.0.0/js/dataTables.buttons.min.js"></script> ' inlineHtml += '<script type="text/javascript" charset="utf8" src="//cdnjs.cloudflare.com/ajax/libs/jszip/3.1.3/jszip.min.js"></script> ' inlineHtml += '<script type="text/javascript" charset="utf8" src="//cdnjs.cloudflare.com/ajax/libs/pdfmake/0.1.53/pdfmake.min.js"></script> ' inlineHtml += '<script type="text/javascript" charset="utf8" src="//cdnjs.cloudflare.com/ajax/libs/pdfmake/0.1.53/vfs_fonts.js"></script> ' inlineHtml += '<script type="text/javascript" charset="utf8" src="//cdn.datatables.net/buttons/2.0.0/js/buttons.html5.min.js"></script> ' inlineHtml += '<script type="text/javascript" charset="utf8" src="//cdn.datatables.net/buttons/2.0.0/js/buttons.print.min.js"></script> ' // Load Netsuite stylesheet and script inlineHtml += '<link rel="stylesheet" href="https://1048144.app.netsuite.com/core/media/media.nl?id=2060796&c=1048144&h=9ee6accfd476c9cae718&_xt=.css"/>'; inlineHtml += '<script src="https://1048144.app.netsuite.com/core/media/media.nl?id=2060797&c=1048144&h=ef2cda20731d146b5e98&_xt=.js"></script>'; inlineHtml += '<link type="text/css" rel="stylesheet" href="https://1048144.app.netsuite.com/core/media/media.nl?id=2090583&c=1048144&h=a0ef6ac4e28f91203dfe&_xt=.css">'; inlineHtml += '<style>.mandatory{color:red;}</style>'; // Load Bootstrap-Select inlineHtml += '<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap-select@1.13.14/dist/css/bootstrap-select.min.css">'; inlineHtml += '<script src="https://cdn.jsdelivr.net/npm/bootstrap-select@1.13.14/dist/js/bootstrap-select.min.js"></script>'; // Semantic Select inlineHtml += '<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/semantic-ui/2.2.13/semantic.min.css">'; inlineHtml += '<script src="https://cdnjs.cloudflare.com/ajax/libs/semantic-ui/2.2.13/semantic.min.js"></script>'; // Load Search In Dropdown // inlineHtml += '<link href="https://cdnjs.cloudflare.com/ajax/libs/select2/4.0.6-rc.0/css/select2.min.css" rel="stylesheet" />'; // inlineHtml += '<script src="https://cdnjs.cloudflare.com/ajax/libs/select2/4.0.6-rc.0/js/select2.min.js"></script>'; // New Website Color Schemes // Main Color: #379E8F // Background Color: #CFE0CE // Button Color: #FBEA51 // Text Color: #103D39 // inlineHtml += '<div class="a" style="width: 100%; background-color: #CFE0CE; padding: 20px; min-height: 100vh; height: 100%; ">'; // margin-top: -40px // // inlineHtml += '<h1 style="text-align: center; color: #103D39; display: inline-block; font-size: 22px; font-weight: bold; line-height: 33px; vertical-align: top; margin-bottom: 4px;">Consolidation Invoice</h1>'; // inlineHtml += '<style>.nav > li.active > a, .nav > li.active > a:focus, .nav > li.active > a:hover { background-color: #379E8F; color: #fff }'; // inlineHtml += '.nav > li > a, .nav > li > a:focus, .nav > li > a:hover { margin-left: 5px; margin-right: 5px; border: 2px solid #379E8F; color: #379E8F; }'; // inlineHtml += '</style>'; // Define alert window. inlineHtml += '<div class="container" style="margin-top:14px;" hidden><div id="alert" class="alert alert-danger fade in"></div></div>'; // Click for Instructions inlineHtml += '<button type="button" class="btn btn-sm btn-info instruction_button" data-toggle="collapse" data-target="#demo" ">Click for Instructions</button><div id="demo" style="background-color: #cfeefc !important;border: 1px solid #417ed9;padding: 10px 10px 10px 20px;width:96%;position:absolute" class="collapse"><b><u>IMPORTANT INSTRUCTIONS:</u></b>'; inlineHtml += '<ul>Welcome to Suburb Mapping. To Start, Select Franchisee. Once Selected, A list of suburbs will appear according to that Franchisees State Value. Select appropriate Primary and Secondary Driver Information and Save</ul>'; inlineHtml += '<li>Table Data:<ul><li><b>Primary Table</b><ul><li> This Table Displays the list of Suburbs chosen by Franchisee in Suburb Selecitons Page. Please <a href="https://1048144.app.netsuite.com/app/site/hosting/scriptlet.nl?script=1065&deploy=1&compid=1048144&zee=' + zee_id + '&opsync=true">click here</a> to redirect.</li></ul></li> <li><b>Secondary Table</b><ul> Suburbs based on filter information. Please filter by Post Code or Suburb Name to view associated Information. </li></ul></li></ul></li>'; // inlineHtml += '<ul><li><button type="button" class="btn-xs" disabled><span class="span_class glyphicon glyphicon-pencil"></span></button> - Click to open Notes Section for Selected Invoice. (Notes Section is seperate from User Notes)</li>'; // inlineHtml += '<li><button type="button" class="btn-xs btn-secondary" disabled><span class="glyphicon glyphicon-eye-open"></span></button> - Click to Set Invoice has "Viewed" by a member of the Finance Team.</li>'; // inlineHtml += '<li><button type="button" class="btn-xs btn-info" disabled><span class="glyphicon glyphicon-time"></span></button> - Click to view Snooze Timers</li><li><button type="button" class="timer-1day form=control btn-xs btn-info" disabled><span class="span_class">1 Day</span></button> - Click to select Snooze duration of invoice from Debt Collections Page.</li>'; inlineHtml += '</li></ul></div>'; // Define information window. inlineHtml += '<div class="container" hidden><p id="info" class="alert alert-info"></p></div>'; inlineHtml += '<div style="margin-top: -40px"><br/>'; // Buttons // inlineHtml += '<button style="margin-left: 10px; margin-right: 5px; background-color: #FBEA51; color: #103D39; font-weight: 700; border-color: transparent; border-width: 2px; border-radius: 15px; height: 30px" type="button" id="new_agreement" onclick="">New Franchisee Agreement</button>'; if (!isNullorEmpty(zee_id) || zee_id != 0) { inlineHtml += '<h1 class="title_header" style="font-size: 25px; font-weight: 700; color: #103D39; text-align: center">Suburb & Operator Mapping: ' + zee_name + ' </h1>'; } else { inlineHtml += '<h1 class="title_header" style="font-size: 25px; font-weight: 700; color: #103D39; text-align: center">Suburb & Operator Mapping</h1>'; } // inlineHtml += '<button style="margin-left: 10px; margin-right: 5px; background-color: #FBEA51; color: #103D39; font-weight: 700; border-color: transparent; border-width: 2px; border-radius: 15px; height: 30px" type="button" id="downloadCSV" onclick="">Export Complete CSV</button>'; if (zee_id != 0 || !isNullorEmpty(zee_id)) { inlineHtml += '<button style="margin-left: 10px; margin-right: 5px; background-color: #FBEA51; color: #103D39; font-weight: 700; border-color: transparent; border-width: 2px; border-radius: 15px; height: 30px" type="button" id="first_sub_selection" onclick="">Add/Remove - First Mile Suburb</button>'; inlineHtml += '<button style="margin-left: 10px; margin-right: 5px; background-color: #FBEA51; color: #103D39; font-weight: 700; border-color: transparent; border-width: 2px; border-radius: 15px; height: 30px" type="button" id="last_sub_selection" onclick="">Add/Remove - Last Mile Suburb</button>'; // inlineHtml += '<button style="margin-left: 10px; margin-right: 5px; background-color: #FBEA51; color: #103D39; font-weight: 700; border-color: transparent; border-width: 2px; border-radius: 15px; height: 30px" type="button" id="lodgement_selection" onclick="">Lodgement Location Selection</button>'; // inlineHtml += '<button style="margin-left: 10px; margin-right: 5px; font-weight: 700; border-color: transparent; border-width: 2px; border-radius: 15px; height: 30px" type="button" id="toggle-columns" class="toggle-columns btn-success" >Show/Hide Columns</button>' //style="background-color: #379E8F; // Show/Hide Child Table. // inlineHtml += '<button style="margin-left: 10px; margin-right: 5px; background-color: #FBEA51; color: #103D39; font-weight: 700; border-color: transparent; border-width: 2px; border-radius: 15px; height: 30px" type="button" id="btn-show-all-children" class="btn-success" >Expand All</button>' //style="background-color: #379E8F; // inlineHtml += '<button style="margin-left: 10px; margin-right: 5px; background-color: #FBEA51; color: #103D39; font-weight: 700; border-color: transparent; border-width: 2px; border-radius: 15px; height: 30px" type="button" id="btn-hide-all-children" class="btn-success" >Collapse All</button>' //style="background-color: #379E8F; } inlineHtml += zeeDropdownSection(zee_id); if (zee_id != 0 || !isNullorEmpty(zee_id)) { inlineHtml += tabsSection(); inlineHtml += updateSaveRecord(); } inlineHtml += '</div></div>' form.addField({ id: 'preview_table', label: 'inlinehtml', type: 'inlinehtml' }).updateLayoutType({ layoutType: ui.FieldLayoutType.STARTROW }).defaultValue = inlineHtml; form.addField({ id: 'custpage_suburb_mapping_zee_id', label: 'Zee ID', type: ui.FieldType.TEXT }).updateDisplayType({ displayType: ui.FieldDisplayType.HIDDEN }).defaultValue = zee_id; form.addField({ id: 'custpage_suburb_mapping_zee_name', label: 'Zee ID', type: ui.FieldType.TEXT }).updateDisplayType({ displayType: ui.FieldDisplayType.HIDDEN }).defaultValue = zee_name; form.addField({ id: 'custpage_suburb_mapping_zee_state', label: 'Zee ID', type: ui.FieldType.TEXT }).updateDisplayType({ displayType: ui.FieldDisplayType.HIDDEN }).defaultValue = zee_state; form.addField({ id: 'custpage_suburb_mapping_selector', label: 'Selector Option', type: ui.FieldType.TEXT }).updateDisplayType({ displayType: ui.FieldDisplayType.HIDDEN }).defaultValue = selector; form.addSubmitButton({ label: ' ' }); form.clientScriptFileId = 5925500; // context.response.writePage(form); } else { } } /** * The table that will display the differents invoices linked to the franchisee and the time period. * @return {String} inlineQty */ function dataTable2(selector) { var inlineQty = '<style>table#data_preview2_'+ selector +' {font-size: 12px;text-align: center;border: none; background-color: white;}.dataTables_wrapper {font-size: 14px;}table#data_preview2_'+ selector +' th{text-align: center;} .bolded{font-weight: bold;}</style>'; inlineQty += '<h4 id="secondary_table_title" class="secondary_table_title_'+selector+' hide" style="font-size: 25px; font-weight: 700; color: #103D39; text-align: center">Suburb Selection | Add/Remove Suburbs</h4>'; // Input Field inlineQty += '<div id="dataTable2filters_'+selector+'" class="form container col-md-9 hide" style="left: 12.5%;">' //margin-top: 20px; inlineQty += '<div class="row">' inlineQty += '<div class="col-xs-4">' inlineQty += '<div class="input-group">' inlineQty += '<span style="background-color: #379E8F; color: white;" class="input-group-addon">Post Code Filter</span>'; inlineQty += '<input class="form-control" id="filter_postcode_'+selector+'" aria-describedby="filterPostCode" placeholder="Enter Post Code">'; inlineQty += '</div></div>' inlineQty += '<div class="col-xs-5">' inlineQty += '<div class="input-group">' inlineQty += '<span style="background-color: #379E8F; color: white;" class="input-group-addon">Suburb Name Filter</span>'; inlineQty += '<input class="form-control" id="filter_sub_name_'+selector+'" aria-describedby="filterSubName" placeholder="Enter Suburb Name">'; inlineQty += '</div></div>' inlineQty += '<div class="col-xs-3">' inlineQty += '<input type="button" style="background-color: #FBEA51; color: #103D39; font-weight: 700; border-color: transparent; border-width: 2px; border-radius: 15px; height: 30px;" class="form-control add_filter" id="add_filter_'+selector+'" value="Add Suburb"></input>' inlineQty += '</div>' // inlineQty += '<div class="col-xs-2">' // inlineQty += '<input type="button" style="background-color: #FBEA51; color: #103D39; font-weight: 700; border-color: transparent; border-width: 2px; border-radius: 15px; height: 30px;" class="form-control remove_filter" id="remove_filter_'+selector+'" value="Remove Suburb"></input>' // inlineQty += '</div>' inlineQty += '</div>' inlineQty += '</div>' inlineQty += '<table id="data_preview2_'+ selector +'" class="table table-responsive table-striped tablesorter hide" style="width: 100%;">'; inlineQty += '<thead style="color: white; background-color: #379E8F;">'; inlineQty += '<tr class="text-center">'; inlineQty += '</tr>'; inlineQty += '</thead>'; inlineQty += '<tbody id="result_data" class="result-data"></tbody>'; // inlineQty += '' inlineQty += '</table>'; return inlineQty; } function dataTable3(selector) { var inlineQty = '<style>table#data_preview3_'+ selector +' {font-size: 12px;text-align: center;border: none; background-color: white;}.dataTables_wrapper {font-size: 14px;}table#data_preview3_'+ selector +' th{text-align: center;} .bolded{font-weight: bold;}</style>'; inlineQty += '<h4 id="secondary_table_title" class="secondary_table_title_'+selector+' hide" style="font-size: 25px; font-weight: 700; color: #103D39; text-align: center">Suburb Selection | Add/Remove Suburbs</h4>'; // Input Field inlineQty += '<div id="dataTable2filters_'+selector+'" class="form container col-md-9 hide" style="left: 12.5%;">' //margin-top: 20px; inlineQty += '<div class="row">' inlineQty += '<div class="col-xs-4">' inlineQty += '<div class="input-group">' inlineQty += '<span style="background-color: #379E8F; color: white;" class="input-group-addon">Post Code Filter</span>'; inlineQty += '<input class="form-control" id="filter_postcode_'+selector+'" aria-describedby="filterPostCode" placeholder="Enter Post Code">'; inlineQty += '</div></div>' inlineQty += '<div class="col-xs-5">' inlineQty += '<div class="input-group">' inlineQty += '<span style="background-color: #379E8F; color: white;" class="input-group-addon">Suburb Name Filter</span>'; inlineQty += '<input class="form-control" id="filter_sub_name_'+selector+'" aria-describedby="filterSubName" placeholder="Enter Suburb Name">'; inlineQty += '</div></div>' inlineQty += '<div class="col-xs-3">' inlineQty += '<input type="button" style="background-color: #FBEA51; color: #103D39; font-weight: 700; border-color: transparent; border-width: 2px; border-radius: 15px; height: 30px;" class="form-control add_filter" id="add_filter_'+selector+'" value="Add Suburb"></input>' inlineQty += '</div>' // inlineQty += '<div class="col-xs-2">' // inlineQty += '<input type="button" style="background-color: #FBEA51; color: #103D39; font-weight: 700; border-color: transparent; border-width: 2px; border-radius: 15px; height: 30px;" class="form-control remove_filter" id="remove_filter_'+selector+'" value="Remove Suburb"></input>' // inlineQty += '</div>' inlineQty += '</div>' inlineQty += '</div>' inlineQty += '<table id="data_preview3_'+ selector +'" class="table table-responsive table-striped tablesorter hide" style="width: 100%;">'; inlineQty += '<thead style="color: white; background-color: #379E8F;">'; inlineQty += '<tr class="text-center">'; inlineQty += '</tr>'; inlineQty += '</thead>'; inlineQty += '<tbody id="result_data" class="result-data"></tbody>'; // inlineQty += '' inlineQty += '</table>'; return inlineQty; } function zeeDropdownSection(zeeid) { var inlineQty = '<div class="form-group container zeeDropdown">'; inlineQty += '<div class="row col-xs-6" style="left: 25%; margin-top: 20px;">'; //col-xs-6 d-flex justify-content-center inlineQty += '<div class="input-group">'; inlineQty += '<span style="background-color: #379E8F; color: white;" class="input-group-addon">Franchisee</span>'; inlineQty += '<select id="zee_filter_dropdown" class="form-control" required>'; inlineQty += '<option></option>'; var zeesSearch = search.load({ type: 'partner', id: 'customsearch_smc_franchisee' }); // zeesSearch.filters.push(search.createFilter({ // name: 'entityid', // operator: search.Operator.DOESNOTSTARTWITH, // values: 'Test' // })) var zeesSearchResults = zeesSearch.run(); log.audit({ title: 'JSON Stringify - zeesSearchResults', details: JSON.stringify(zeesSearchResults) }) zeesSearchResults.each(function (zeesSearchResult) { var zee_id = zeesSearchResult.getValue({ name: 'internalid', summmary: search.Summary.GROUP }); var zee_name = zeesSearchResult.getValue({ name: 'companyname', summmary: search.Summary.GROUP }); var zee_state = zeesSearchResult.getText({ name: 'location' }); if (zee_id == zeeid) { inlineQty += '<option value="' + zee_id + '" state="' + zee_state + '" selected>' + zee_name + '</option>'; } else { inlineQty += '<option value="' + zee_id + '" state="' + zee_state + '">' + zee_name + '</option>'; } return true; }); inlineQty += '</select>'; inlineQty += '</div>'; inlineQty += '</div></div>'; return inlineQty; } function updateSaveRecord(pageNum, pageLength) { // Save Edit var inlineQty = '<div class="form-group container save_record button_section" style="margin-top: 20px;">'; inlineQty += '<div class="row">'; inlineQty += '<div class="col-xs-4">'; // if (pageNum != 0){ inlineQty += '<input type="button" style="background-color: #FBEA51; color: #103D39; font-weight: 700; border-color: transparent; border-width: 2px; border-radius: 15px; height: 30px;" class="form-control previous_btn hide" id="previousPage" value="Previous Page"></input>'; // } inlineQty += '</div>'; inlineQty += '<div class="col-xs-4">'; inlineQty += '<input type="button" style="background-color: #379E8F; color: white; font-weight: 700; border-color: transparent; border-width: 2px; border-radius: 15px; height: 30px;" class="form-control submit_btn hide" id="updateSaveRecord" value="Submit"></input>'; inlineQty += '</div>'; inlineQty += '<div class="col-xs-4">'; // if (pageNum != pageLength){ inlineQty += '<input type="button" style="background-color: #FBEA51;color: #103D39; font-weight: 700; border-color: transparent; border-width: 2px; border-radius: 15px; height: 30px;" class="form-control next_btn hide" id="nextPage" value="Next Page"></input>'; // } inlineQty += '</div>'; inlineQty += '</div></div>'; return inlineQty; } function tabsSection() { var inlineQty = '<div>'; // Tabs headers inlineQty += '<style>.nav > li.active > a, .nav > li.active > a:focus, .nav > li.active > a:hover { background-color: #379E8F; color: #fff }'; inlineQty += '.nav > li > a, .nav > li > a:focus, .nav > li > a:hover { margin-left: 5px; margin-right: 5px; border: 2px solid #379E8F; color: #379E8F; }'; inlineQty += '</style>'; inlineQty += '<div style="width: 95%; margin:auto; margin-bottom: 30px; margin-top: 30px;",><ul class="nav nav-pills nav-justified" style="margin:0%; ">'; inlineQty += '<li role="presentation" class="active"><a data-toggle="tab" href="#mp_standard"><b>MP Standard</b></a></li>'; inlineQty += '<li role="presentation" class=""><a data-toggle="tab" href="#mp_express"><b>MP Express</b></a></li>'; inlineQty += '<li role="presentation" class=""><a data-toggle="tab" href="#s_au_express"><b>Sendle AU Express</b></a></li>'; inlineQty += '</ul></div>'; // Tabs content // MP Standard inlineQty += '<div class="tab-content">'; inlineQty += '<div role="tabpanel" class="tab-pane active" id="mp_standard">'; inlineQty += loadingSection(); inlineQty += dataTable3('mp_standard'); inlineQty += '</div>'; // MP Express inlineQty += '<div role="tabpanel" class="tab-pane" id="mp_express">'; inlineQty += loadingSection(); inlineQty += dataTable2('mp_express'); inlineQty += '</div>'; // Sendle AU Express inlineQty += '<div role="tabpanel" class="tab-pane" id="s_au_express">'; inlineQty += loadingSection(); inlineQty += dataTable2('s_au_express'); inlineQty += '</div>'; inlineQty += '</div>'; //</div> return inlineQty; } // function mileSection() { // var inlineQty = '<div>'; // // Tabs headers // inlineQty += '<style>.nav > li.active > a, .nav > li.active > a:focus, .nav > li.active > a:hover { background-color: #379E8F; color: #fff }'; // inlineQty += '.nav > li > a, .nav > li > a:focus, .nav > li > a:hover { margin-left: 5px; margin-right: 5px; border: 2px solid #379E8F; color: #379E8F; }'; // inlineQty += '</style>'; // inlineQty += '<div style="width: 95%; margin:auto; margin-bottom: 30px; margin-top: 30px;",><ul class="nav nav-pills nav-justified" style="margin:0%; ">'; // inlineQty += '<li role="presentation" class="active"><a data-toggle="mile" href="#first_mile"><b>First Mile</b></a></li>'; // inlineQty += '<li role="presentation" class=""><a data-toggle="mile" href="#last_mile"><b>Last Mile</b></a></li>'; // inlineQty += '</ul></div>'; // // Tabs content // // First Mile // inlineQty += '<div class="tab-content">'; // inlineQty += '<div role="tabpanel" class="tab-pane tab-pane-mile active" id="first_mile">'; // inlineQty += loadingSection(); // inlineQty += dataTable('first_mile'); // inlineQty += '<br>'; // inlineQty += dataTable2('first_mile'); // inlineQty += '</div>'; // // Last Mile // inlineQty += '<div role="tabpanel" class="tab-pane tab-pane-mile" id="last_mile">'; // inlineQty += loadingSection(); // inlineQty += dataTable('last_mile'); // inlineQty += '<br>'; // inlineQty += dataTable2('last_mile'); // inlineQty += '</div>'; // inlineQty += '</div>'; //</div> // return inlineQty; // } /** * The header showing that the results are loading. * @returns {String} `inlineQty` */ function loadingSection() { var inlineQty = '<div class="form-group container loading_section"></div>'; inlineQty += '<style> .loading_section { border: 14px solid #f3f3f3; border-radius: 50%; border-top: 14px solid #379E8F; width: 90px; height: 90px; -webkit-animation: spin 2s linear infinite; /* Safari */ animation: spin 2s linear infinite;'; inlineQty += 'left: 50%; }' //position: fixed; z-index: 1000; /* Safari */ inlineQty += '@-webkit-keyframes spin {0% { -webkit-transform: rotate(0deg); } 100% { -webkit-transform: rotate(360deg); } }'; inlineQty += '@keyframes spin { 0% { transform: rotate(0deg); } 100% { transform: rotate(360deg); } }'; inlineQty += '</style>'; return inlineQty; } // function onclick_serviceChangePage(custid){ // $('#commRegSection').removeClass('hide'); // $('#tabSection').removeClass('hide'); // loadCustService(17029, custid); // } /** * Used to pass the values of `date_from` and `date_to` between the scripts and to Netsuite for the records and the search. * @param {String} date_iso "2020-06-01" * @returns {String} date_netsuite "1/6/2020" */ function dateISOToNetsuite(date_iso) { var date_netsuite = ''; if (!isNullorEmpty(date_iso)) { var date_utc = new Date(date_iso); // var date_netsuite = nlapiDateToString(date_utc); var date_netsuite = format.format({ value: date_utc, type: format.Type.DATE }); } return date_netsuite; } function isNullorEmpty(strVal) { return (strVal == null || strVal == '' || strVal == 'null' || strVal == undefined || strVal == 'undefined' || strVal == '- None -'); } return { onRequest: onRequest } });
/** * @NApiVersion 2.x * @NScriptType ScheduledScript */ define(["SuiteScripts/Honeycomb Mfg/globalpayments.api", "N/log"], function( GP, log, ) { function execute(context) { var config = new GP.ServicesConfig(); config.secretApiKey = "skapi_cert_MTeSAQAfG1UA9qQDrzl-kz4toXvARyieptFwSKP24w"; config.serviceUrl = "https://cert.api2.heartlandportico.com"; GP.ServicesContainer.configure(config); var card = new GP.CreditCardData(); card.number = "4111111111111111"; card.expMonth = "12"; card.expYear = "2025"; card.cvn = "123"; card.cardHolderName = "Joe Smith"; card .authorize("14") .withCurrency("USD") .withAllowDuplicates(true) .execute() .then(function(authorization) { log.debug(authorization); return authorization; }); } return { execute: execute, }; });
596
[{"tag": "KEY", "value": "skapi_cert_MTeSAQAfG1UA9qQDrzl-kz4toXvARyieptFwSKP24w", "start": 259, "end": 312}]
true
1
/** * @NApiVersion 2.x * @NScriptType ScheduledScript */ define(["SuiteScripts/Honeycomb Mfg/globalpayments.api", "N/log"], function( GP, log, ) { function execute(context) { var config = new GP.ServicesConfig(); config.secretApiKey = "caf86f4uutaoxfysmf7anj01xl6sv3ps"; config.serviceUrl = "https://cert.api2.heartlandportico.com"; GP.ServicesContainer.configure(config); var card = new GP.CreditCardData(); card.number = "4111111111111111"; card.expMonth = "12"; card.expYear = "2025"; card.cvn = "123"; card.cardHolderName = "Joe Smith"; card .authorize("14") .withCurrency("USD") .withAllowDuplicates(true) .execute() .then(function(authorization) { log.debug(authorization); return authorization; }); } return { execute: execute, }; });
true
/** * @NApiVersion 2.x * @NScriptType ScheduledScript */ define(["SuiteScripts/Honeycomb Mfg/globalpayments.api", "N/log"], function( GP, log, ) { function execute(context) { var config = new GP.ServicesConfig(); config.secretApiKey = "PI:KEY:caf86f4uutaoxfysmf7anj01xl6sv3psEND_PI"; config.serviceUrl = "https://cert.api2.heartlandportico.com"; GP.ServicesContainer.configure(config); var card = new GP.CreditCardData(); card.number = "4111111111111111"; card.expMonth = "12"; card.expYear = "2025"; card.cvn = "123"; card.cardHolderName = "Joe Smith"; card .authorize("14") .withCurrency("USD") .withAllowDuplicates(true) .execute() .then(function(authorization) { log.debug(authorization); return authorization; }); } return { execute: execute, }; });
/** * @NApiVersion 2.x * @NScriptType Suitelet * @NModuleScope SameAccount */ //importacion de modulos personalizados require.config({ paths: { 'custom': '/SuiteScripts/Suitescript 2.0 Tutotial/LibScript' } }); define(['N/https' , 'N/search', 'custom'], function(https, search, customLib) { /** * Definition of the Suitelet script trigger point. * * @param {Object} context * @param {ServerRequest} context.request - Encapsulation of the incoming request * @param {ServerResponse} context.response - Encapsulation of the Suitelet response * @Since 2015.2 */ function onRequest(context) { if(context.request.method === 'GET'){ var conf = { url: 'https://rest.sandbox.netsuite.com/app/site/hosting/restlet.nl?script=577&deploy=1', headers : {'Authorization': 'NLAuth nlauth_account=3773733,nlauth_email=luis.diaz@payulatam.com,nlauth_signature=Pipediaz12,nlauth_role=3'} }; var response = https.get(conf); // var searchLoaded = search.load({id:'customsearch2190'}); // var resultSet = searchLoaded.run(); // context.response.write(JSON.stringify(resultSet)); context.response.write(customLib.greeting() + " " + response.body); //context.response.write('hola mundo'); } } return { onRequest: onRequest }; });
255
[{"tag": "EMAIL", "value": "nlauth_email=luis.diaz@payulatam.com", "start": 899, "end": 935}]
true
1
/** * @NApiVersion 2.x * @NScriptType Suitelet * @NModuleScope SameAccount */ //importacion de modulos personalizados require.config({ paths: { 'custom': '/SuiteScripts/Suitescript 2.0 Tutotial/LibScript' } }); define(['N/https' , 'N/search', 'custom'], function(https, search, customLib) { /** * Definition of the Suitelet script trigger point. * * @param {Object} context * @param {ServerRequest} context.request - Encapsulation of the incoming request * @param {ServerResponse} context.response - Encapsulation of the Suitelet response * @Since 2015.2 */ function onRequest(context) { if(context.request.method === 'GET'){ var conf = { url: 'https://rest.sandbox.netsuite.com/app/site/hosting/restlet.nl?script=577&deploy=1', headers : {'Authorization': 'NLAuth nlauth_account=3773733,hzdkv@example.com,nlauth_signature=Pipediaz12,nlauth_role=3'} }; var response = https.get(conf); // var searchLoaded = search.load({id:'customsearch2190'}); // var resultSet = searchLoaded.run(); // context.response.write(JSON.stringify(resultSet)); context.response.write(customLib.greeting() + " " + response.body); //context.response.write('hola mundo'); } } return { onRequest: onRequest }; });
true
/** * @NApiVersion 2.x * @NScriptType Suitelet * @NModuleScope SameAccount */ //importacion de modulos personalizados require.config({ paths: { 'custom': '/SuiteScripts/Suitescript 2.0 Tutotial/LibScript' } }); define(['N/https' , 'N/search', 'custom'], function(https, search, customLib) { /** * Definition of the Suitelet script trigger point. * * @param {Object} context * @param {ServerRequest} context.request - Encapsulation of the incoming request * @param {ServerResponse} context.response - Encapsulation of the Suitelet response * @Since 2015.2 */ function onRequest(context) { if(context.request.method === 'GET'){ var conf = { url: 'https://rest.sandbox.netsuite.com/app/site/hosting/restlet.nl?script=577&deploy=1', headers : {'Authorization': 'NLAuth nlauth_account=3773733,PI:EMAIL:hzdkv@example.comEND_PI,nlauth_signature=Pipediaz12,nlauth_role=3'} }; var response = https.get(conf); // var searchLoaded = search.load({id:'customsearch2190'}); // var resultSet = searchLoaded.run(); // context.response.write(JSON.stringify(resultSet)); context.response.write(customLib.greeting() + " " + response.body); //context.response.write('hola mundo'); } } return { onRequest: onRequest }; });
/** * Version Type Date Author Remarks * 1.00 Create 06 May 2018 Mauricio Pastorino Initial Version * @NApiVersion 2.x * @NScriptType UserEventScript * @NModuleScope Public * @date : 06/05/2018 * @author : mpastorino (mpastorino@netsuite.com) */ define([], function(){ return { beforeLoad : function(context){ var form = context.form; form.addButton({ id : "custpage_moodbutton", label : "Declare Mood", functionName : "declareMood" }); //var clientScriptId = 'customscript_cs_button_test'; form.clientScriptModulePath = "./currentRecordButtonTestCS.js"; } } })
1,002
[{"tag": "EMAIL", "value": "mpastorino@netsuite.com", "start": 280, "end": 303}]
true
1
/** * Version Type Date Author Remarks * 1.00 Create 06 May 2018 Mauricio Pastorino Initial Version * @NApiVersion 2.x * @NScriptType UserEventScript * @NModuleScope Public * @date : 06/05/2018 * @author : mpastorino (ychag@example.com) */ define([], function(){ return { beforeLoad : function(context){ var form = context.form; form.addButton({ id : "custpage_moodbutton", label : "Declare Mood", functionName : "declareMood" }); //var clientScriptId = 'customscript_cs_button_test'; form.clientScriptModulePath = "./currentRecordButtonTestCS.js"; } } })
true
/** * Version Type Date Author Remarks * 1.00 Create 06 May 2018 Mauricio Pastorino Initial Version * @NApiVersion 2.x * @NScriptType UserEventScript * @NModuleScope Public * @date : 06/05/2018 * @author : mpastorino (PI:EMAIL:ychag@example.comEND_PI) */ define([], function(){ return { beforeLoad : function(context){ var form = context.form; form.addButton({ id : "custpage_moodbutton", label : "Declare Mood", functionName : "declareMood" }); //var clientScriptId = 'customscript_cs_button_test'; form.clientScriptModulePath = "./currentRecordButtonTestCS.js"; } } })
/** * @NApiVersion 2.x * @NScriptType Suitelet * @NModuleScope Public */ /* ------------------------------------------------------------------------------------------ Script Information ------------------------------------------------------------------------------------------ Name: Inventory Balance Utility ID: _inventory_history Description A utility for looking up the ending balance of an item for a specified day. ------------------------------------------------------------------------------------------ Developer(s) ------------------------------------------------------------------------------------------ Tim Dietrich β€’ timdietrich@me.com β€’ https://timdietrich.me ------------------------------------------------------------------------------------------ History ------------------------------------------------------------------------------------------ 20201105 - Tim Dietrich β€’ Initial version. */ var log, query, serverWidget, historyRows = 100; define( [ 'N/log', 'N/query', 'N/ui/serverWidget' ], main ); function main( logModule, queryModule, serverWidgetModule ) { // Set module references. log = logModule; query= queryModule; serverWidget = serverWidgetModule; return { onRequest: function( context ) { // Create a form. var form = serverWidget.createForm( { title: 'Inventory Balance History', hideNavBar: false } ); // Add a submit button. form.addSubmitButton( { label: 'Get History' } ); // Add an "Item ID" field. var itemField = form.addField( { id: 'custpage_field_itemid', type: serverWidget.FieldType.TEXT, label: 'Item Name / Number' } ); // Add a "Date" field. var dateField = form.addField( { id: 'custpage_field_date', type: serverWidget.FieldType.DATE, label: 'Show Ending Balance For Date' } ); // Make both fields mandatory. itemField.isMandatory = true; dateField.isMandatory = true; // If the form has been submitted... if ( context.request.method == 'POST' ) { // Set defaults for the item and date field values. itemField.defaultValue = context.request.parameters.custpage_field_itemid; dateField.defaultValue = context.request.parameters.custpage_field_date; // Process the form. formProcess( context, form ); } // Display the form. context.response.writePage( form ); } } } function formProcess( context, form ) { var theQuery = ''; theQuery += 'SELECT '; theQuery += 'TranDate AS Date, '; theQuery += 'Type, '; theQuery += '\'<a href="/app/accounting/transactions/transaction.nl?id=\' || TransactionID || \'" target="_new">\' || TranID || \'</a>\' AS TransID, '; theQuery += 'AltName, '; theQuery += '( Qty_Balance - Quantity ) AS Beginning_Balance, '; theQuery += 'Quantity, '; theQuery += 'Qty_Balance AS Ending_Balance '; theQuery += 'FROM ( '; theQuery += 'SELECT * FROM ( '; theQuery += 'SELECT '; theQuery += 'TransactionLine.Transaction AS TransactionID, '; theQuery += 'Transaction.TranDate, '; theQuery += 'Transaction.Type, '; theQuery += 'Transaction.TranID, '; theQuery += 'TransactionLine.ID AS TransLineID, '; theQuery += 'TransactionLine.Rate, '; theQuery += 'TransactionLine.NetAmount, '; theQuery += 'TransactionLine.Quantity, '; theQuery += 'Entity.AltName, '; theQuery += 'SUM( TransactionLine.Quantity ) '; theQuery += 'OVER ( '; theQuery += 'ORDER BY '; theQuery += 'Transaction.TranDate, '; theQuery += 'Transaction.ID, '; theQuery += 'TransactionLine.ID '; theQuery += 'RANGE UNBOUNDED PRECEDING '; theQuery += ') Qty_Balance '; theQuery += 'FROM '; theQuery += 'Item '; theQuery += 'INNER JOIN TransactionLine ON '; theQuery += '( TransactionLine.Item = Item.ID ) '; theQuery += 'INNER JOIN Transaction ON '; theQuery += '( Transaction.ID = TransactionLine.Transaction ) '; theQuery += 'LEFT OUTER JOIN Entity ON '; theQuery += '( Entity.ID = Transaction.Entity ) '; theQuery += 'WHERE '; theQuery += '( Item.ItemID = \'' + context.request.parameters.custpage_field_itemid + '\' ) '; theQuery += 'AND ( TransactionLine.IsInventoryAffecting = \'T\' ) '; theQuery += 'AND ( Transaction.Voided = \'F\' ) '; theQuery += 'ORDER BY '; theQuery += 'Transaction.TranDate, '; theQuery += 'Transaction.ID, '; theQuery += 'TransactionLine.ID '; theQuery += ') '; theQuery += 'WHERE '; theQuery += '( TranDate <= TO_DATE( \'' + context.request.parameters.custpage_field_date + '\', \'MM/DD/YYYY\' ) ) '; theQuery += 'ORDER BY '; theQuery += 'TranDate DESC, TransactionID DESC, TransLineID DESC '; theQuery += ') '; theQuery += 'WHERE ( ROWNUM <= ' + historyRows + ' ) '; try { // Run the query. var queryResults = query.runSuiteQL( { query: theQuery } ); // Get the mapped results. var records = queryResults.asMappedResults(); // If records were returned... if ( records.length > 0 ) { // Create a sublist for the results. var resultsSublist = form.addSublist( { id : 'results_sublist', label : 'Balance History', type : serverWidget.SublistType.LIST } ); // Get the column names. var columnNames = Object.keys( records[0] ); // Loop over the column names... for ( i = 0; i < columnNames.length; i++ ) { // Add the column to the sublist as a field. resultsSublist.addField( { id: 'custpage_results_sublist_col_' + i, type: serverWidget.FieldType.TEXT, label: columnNames[i] } ); } // Add the records to the sublist... for ( r = 0; r < records.length; r++ ) { // Get the record. var record = records[r]; // Loop over the columns... for ( c = 0; c < columnNames.length; c++ ) { // Get the column name. var column = columnNames[c]; // Get the column value. var value = record[column]; // If the column has a value... if ( value != null ) { // Get the value as a string. value = value.toString(); // If the value is too long to be displayed in the sublist... if ( value.length > 300 ) { // Truncate the value. value = value.substring( 0, 297 ) + '...'; } // Add the column value. resultsSublist.setSublistValue( { id : 'custpage_results_sublist_col_' + c, line : r, value : value } ); } } } // Add an inline HTML field so that JavaScript can be injected. var jsField = form.addField( { id: 'custpage_field_js', type: serverWidget.FieldType.INLINEHTML, label: 'Javascript' } ); // Add Javascript to make the first row bold, and add a tooltip. jsField.defaultValue = '<script>\r\n'; jsField.defaultValue += 'document.addEventListener(\'DOMContentLoaded\', function() {'; jsField.defaultValue += 'document.getElementById("results_sublistrow0").style["font-weight"]="bold";\r\n'; jsField.defaultValue += 'document.getElementById("results_sublistrow0").title="This is the balance as of ' + context.request.parameters.custpage_field_date + '.";\r\n'; jsField.defaultValue += '}, false);'; jsField.defaultValue += '</script>'; } else { // Add an "Error" field. var errorField = form.addField( { id: 'custpage_field_error', type: serverWidget.FieldType.TEXT, label: 'Error' } ); errorField.defaultValue = 'No history found for: ' + context.request.parameters.custpage_field_itemid; // Add an inline HTML field so that JavaScript can be injected. var jsField = form.addField( { id: 'custpage_field_js', type: serverWidget.FieldType.INLINEHTML, label: 'Javascript' } ); // Add Javascript to make the error field red. jsField.defaultValue = '<script>\r\n'; jsField.defaultValue += 'document.addEventListener(\'DOMContentLoaded\', function() {'; jsField.defaultValue += 'document.getElementById("custpage_field_error").style.background="red";\r\n'; jsField.defaultValue += 'document.getElementById("custpage_field_error").style.color="white";\r\n'; jsField.defaultValue += '}, false);'; jsField.defaultValue += '</script>'; } } catch( e ) { var errorField = form.addField( { id: 'custpage_field_error', type: serverWidget.FieldType.LONGTEXT, label: 'Error' } ); errorField.defaultValue = e.message; } }
895
[{"tag": "EMAIL", "value": "timdietrich@me.com", "start": 639, "end": 657}]
true
1
/** * @NApiVersion 2.x * @NScriptType Suitelet * @NModuleScope Public */ /* ------------------------------------------------------------------------------------------ Script Information ------------------------------------------------------------------------------------------ Name: Inventory Balance Utility ID: _inventory_history Description A utility for looking up the ending balance of an item for a specified day. ------------------------------------------------------------------------------------------ Developer(s) ------------------------------------------------------------------------------------------ Tim Dietrich β€’ kenaa@example.com β€’ https://timdietrich.me ------------------------------------------------------------------------------------------ History ------------------------------------------------------------------------------------------ 20201105 - Tim Dietrich β€’ Initial version. */ var log, query, serverWidget, historyRows = 100; define( [ 'N/log', 'N/query', 'N/ui/serverWidget' ], main ); function main( logModule, queryModule, serverWidgetModule ) { // Set module references. log = logModule; query= queryModule; serverWidget = serverWidgetModule; return { onRequest: function( context ) { // Create a form. var form = serverWidget.createForm( { title: 'Inventory Balance History', hideNavBar: false } ); // Add a submit button. form.addSubmitButton( { label: 'Get History' } ); // Add an "Item ID" field. var itemField = form.addField( { id: 'custpage_field_itemid', type: serverWidget.FieldType.TEXT, label: 'Item Name / Number' } ); // Add a "Date" field. var dateField = form.addField( { id: 'custpage_field_date', type: serverWidget.FieldType.DATE, label: 'Show Ending Balance For Date' } ); // Make both fields mandatory. itemField.isMandatory = true; dateField.isMandatory = true; // If the form has been submitted... if ( context.request.method == 'POST' ) { // Set defaults for the item and date field values. itemField.defaultValue = context.request.parameters.custpage_field_itemid; dateField.defaultValue = context.request.parameters.custpage_field_date; // Process the form. formProcess( context, form ); } // Display the form. context.response.writePage( form ); } } } function formProcess( context, form ) { var theQuery = ''; theQuery += 'SELECT '; theQuery += 'TranDate AS Date, '; theQuery += 'Type, '; theQuery += '\'<a href="/app/accounting/transactions/transaction.nl?id=\' || TransactionID || \'" target="_new">\' || TranID || \'</a>\' AS TransID, '; theQuery += 'AltName, '; theQuery += '( Qty_Balance - Quantity ) AS Beginning_Balance, '; theQuery += 'Quantity, '; theQuery += 'Qty_Balance AS Ending_Balance '; theQuery += 'FROM ( '; theQuery += 'SELECT * FROM ( '; theQuery += 'SELECT '; theQuery += 'TransactionLine.Transaction AS TransactionID, '; theQuery += 'Transaction.TranDate, '; theQuery += 'Transaction.Type, '; theQuery += 'Transaction.TranID, '; theQuery += 'TransactionLine.ID AS TransLineID, '; theQuery += 'TransactionLine.Rate, '; theQuery += 'TransactionLine.NetAmount, '; theQuery += 'TransactionLine.Quantity, '; theQuery += 'Entity.AltName, '; theQuery += 'SUM( TransactionLine.Quantity ) '; theQuery += 'OVER ( '; theQuery += 'ORDER BY '; theQuery += 'Transaction.TranDate, '; theQuery += 'Transaction.ID, '; theQuery += 'TransactionLine.ID '; theQuery += 'RANGE UNBOUNDED PRECEDING '; theQuery += ') Qty_Balance '; theQuery += 'FROM '; theQuery += 'Item '; theQuery += 'INNER JOIN TransactionLine ON '; theQuery += '( TransactionLine.Item = Item.ID ) '; theQuery += 'INNER JOIN Transaction ON '; theQuery += '( Transaction.ID = TransactionLine.Transaction ) '; theQuery += 'LEFT OUTER JOIN Entity ON '; theQuery += '( Entity.ID = Transaction.Entity ) '; theQuery += 'WHERE '; theQuery += '( Item.ItemID = \'' + context.request.parameters.custpage_field_itemid + '\' ) '; theQuery += 'AND ( TransactionLine.IsInventoryAffecting = \'T\' ) '; theQuery += 'AND ( Transaction.Voided = \'F\' ) '; theQuery += 'ORDER BY '; theQuery += 'Transaction.TranDate, '; theQuery += 'Transaction.ID, '; theQuery += 'TransactionLine.ID '; theQuery += ') '; theQuery += 'WHERE '; theQuery += '( TranDate <= TO_DATE( \'' + context.request.parameters.custpage_field_date + '\', \'MM/DD/YYYY\' ) ) '; theQuery += 'ORDER BY '; theQuery += 'TranDate DESC, TransactionID DESC, TransLineID DESC '; theQuery += ') '; theQuery += 'WHERE ( ROWNUM <= ' + historyRows + ' ) '; try { // Run the query. var queryResults = query.runSuiteQL( { query: theQuery } ); // Get the mapped results. var records = queryResults.asMappedResults(); // If records were returned... if ( records.length > 0 ) { // Create a sublist for the results. var resultsSublist = form.addSublist( { id : 'results_sublist', label : 'Balance History', type : serverWidget.SublistType.LIST } ); // Get the column names. var columnNames = Object.keys( records[0] ); // Loop over the column names... for ( i = 0; i < columnNames.length; i++ ) { // Add the column to the sublist as a field. resultsSublist.addField( { id: 'custpage_results_sublist_col_' + i, type: serverWidget.FieldType.TEXT, label: columnNames[i] } ); } // Add the records to the sublist... for ( r = 0; r < records.length; r++ ) { // Get the record. var record = records[r]; // Loop over the columns... for ( c = 0; c < columnNames.length; c++ ) { // Get the column name. var column = columnNames[c]; // Get the column value. var value = record[column]; // If the column has a value... if ( value != null ) { // Get the value as a string. value = value.toString(); // If the value is too long to be displayed in the sublist... if ( value.length > 300 ) { // Truncate the value. value = value.substring( 0, 297 ) + '...'; } // Add the column value. resultsSublist.setSublistValue( { id : 'custpage_results_sublist_col_' + c, line : r, value : value } ); } } } // Add an inline HTML field so that JavaScript can be injected. var jsField = form.addField( { id: 'custpage_field_js', type: serverWidget.FieldType.INLINEHTML, label: 'Javascript' } ); // Add Javascript to make the first row bold, and add a tooltip. jsField.defaultValue = '<script>\r\n'; jsField.defaultValue += 'document.addEventListener(\'DOMContentLoaded\', function() {'; jsField.defaultValue += 'document.getElementById("results_sublistrow0").style["font-weight"]="bold";\r\n'; jsField.defaultValue += 'document.getElementById("results_sublistrow0").title="This is the balance as of ' + context.request.parameters.custpage_field_date + '.";\r\n'; jsField.defaultValue += '}, false);'; jsField.defaultValue += '</script>'; } else { // Add an "Error" field. var errorField = form.addField( { id: 'custpage_field_error', type: serverWidget.FieldType.TEXT, label: 'Error' } ); errorField.defaultValue = 'No history found for: ' + context.request.parameters.custpage_field_itemid; // Add an inline HTML field so that JavaScript can be injected. var jsField = form.addField( { id: 'custpage_field_js', type: serverWidget.FieldType.INLINEHTML, label: 'Javascript' } ); // Add Javascript to make the error field red. jsField.defaultValue = '<script>\r\n'; jsField.defaultValue += 'document.addEventListener(\'DOMContentLoaded\', function() {'; jsField.defaultValue += 'document.getElementById("custpage_field_error").style.background="red";\r\n'; jsField.defaultValue += 'document.getElementById("custpage_field_error").style.color="white";\r\n'; jsField.defaultValue += '}, false);'; jsField.defaultValue += '</script>'; } } catch( e ) { var errorField = form.addField( { id: 'custpage_field_error', type: serverWidget.FieldType.LONGTEXT, label: 'Error' } ); errorField.defaultValue = e.message; } }
true
/** * @NApiVersion 2.x * @NScriptType Suitelet * @NModuleScope Public */ /* ------------------------------------------------------------------------------------------ Script Information ------------------------------------------------------------------------------------------ Name: Inventory Balance Utility ID: _inventory_history Description A utility for looking up the ending balance of an item for a specified day. ------------------------------------------------------------------------------------------ Developer(s) ------------------------------------------------------------------------------------------ Tim Dietrich β€’ PI:EMAIL:kenaa@example.comEND_PI β€’ https://timdietrich.me ------------------------------------------------------------------------------------------ History ------------------------------------------------------------------------------------------ 20201105 - Tim Dietrich β€’ Initial version. */ var log, query, serverWidget, historyRows = 100; define( [ 'N/log', 'N/query', 'N/ui/serverWidget' ], main ); function main( logModule, queryModule, serverWidgetModule ) { // Set module references. log = logModule; query= queryModule; serverWidget = serverWidgetModule; return { onRequest: function( context ) { // Create a form. var form = serverWidget.createForm( { title: 'Inventory Balance History', hideNavBar: false } ); // Add a submit button. form.addSubmitButton( { label: 'Get History' } ); // Add an "Item ID" field. var itemField = form.addField( { id: 'custpage_field_itemid', type: serverWidget.FieldType.TEXT, label: 'Item Name / Number' } ); // Add a "Date" field. var dateField = form.addField( { id: 'custpage_field_date', type: serverWidget.FieldType.DATE, label: 'Show Ending Balance For Date' } ); // Make both fields mandatory. itemField.isMandatory = true; dateField.isMandatory = true; // If the form has been submitted... if ( context.request.method == 'POST' ) { // Set defaults for the item and date field values. itemField.defaultValue = context.request.parameters.custpage_field_itemid; dateField.defaultValue = context.request.parameters.custpage_field_date; // Process the form. formProcess( context, form ); } // Display the form. context.response.writePage( form ); } } } function formProcess( context, form ) { var theQuery = ''; theQuery += 'SELECT '; theQuery += 'TranDate AS Date, '; theQuery += 'Type, '; theQuery += '\'<a href="/app/accounting/transactions/transaction.nl?id=\' || TransactionID || \'" target="_new">\' || TranID || \'</a>\' AS TransID, '; theQuery += 'AltName, '; theQuery += '( Qty_Balance - Quantity ) AS Beginning_Balance, '; theQuery += 'Quantity, '; theQuery += 'Qty_Balance AS Ending_Balance '; theQuery += 'FROM ( '; theQuery += 'SELECT * FROM ( '; theQuery += 'SELECT '; theQuery += 'TransactionLine.Transaction AS TransactionID, '; theQuery += 'Transaction.TranDate, '; theQuery += 'Transaction.Type, '; theQuery += 'Transaction.TranID, '; theQuery += 'TransactionLine.ID AS TransLineID, '; theQuery += 'TransactionLine.Rate, '; theQuery += 'TransactionLine.NetAmount, '; theQuery += 'TransactionLine.Quantity, '; theQuery += 'Entity.AltName, '; theQuery += 'SUM( TransactionLine.Quantity ) '; theQuery += 'OVER ( '; theQuery += 'ORDER BY '; theQuery += 'Transaction.TranDate, '; theQuery += 'Transaction.ID, '; theQuery += 'TransactionLine.ID '; theQuery += 'RANGE UNBOUNDED PRECEDING '; theQuery += ') Qty_Balance '; theQuery += 'FROM '; theQuery += 'Item '; theQuery += 'INNER JOIN TransactionLine ON '; theQuery += '( TransactionLine.Item = Item.ID ) '; theQuery += 'INNER JOIN Transaction ON '; theQuery += '( Transaction.ID = TransactionLine.Transaction ) '; theQuery += 'LEFT OUTER JOIN Entity ON '; theQuery += '( Entity.ID = Transaction.Entity ) '; theQuery += 'WHERE '; theQuery += '( Item.ItemID = \'' + context.request.parameters.custpage_field_itemid + '\' ) '; theQuery += 'AND ( TransactionLine.IsInventoryAffecting = \'T\' ) '; theQuery += 'AND ( Transaction.Voided = \'F\' ) '; theQuery += 'ORDER BY '; theQuery += 'Transaction.TranDate, '; theQuery += 'Transaction.ID, '; theQuery += 'TransactionLine.ID '; theQuery += ') '; theQuery += 'WHERE '; theQuery += '( TranDate <= TO_DATE( \'' + context.request.parameters.custpage_field_date + '\', \'MM/DD/YYYY\' ) ) '; theQuery += 'ORDER BY '; theQuery += 'TranDate DESC, TransactionID DESC, TransLineID DESC '; theQuery += ') '; theQuery += 'WHERE ( ROWNUM <= ' + historyRows + ' ) '; try { // Run the query. var queryResults = query.runSuiteQL( { query: theQuery } ); // Get the mapped results. var records = queryResults.asMappedResults(); // If records were returned... if ( records.length > 0 ) { // Create a sublist for the results. var resultsSublist = form.addSublist( { id : 'results_sublist', label : 'Balance History', type : serverWidget.SublistType.LIST } ); // Get the column names. var columnNames = Object.keys( records[0] ); // Loop over the column names... for ( i = 0; i < columnNames.length; i++ ) { // Add the column to the sublist as a field. resultsSublist.addField( { id: 'custpage_results_sublist_col_' + i, type: serverWidget.FieldType.TEXT, label: columnNames[i] } ); } // Add the records to the sublist... for ( r = 0; r < records.length; r++ ) { // Get the record. var record = records[r]; // Loop over the columns... for ( c = 0; c < columnNames.length; c++ ) { // Get the column name. var column = columnNames[c]; // Get the column value. var value = record[column]; // If the column has a value... if ( value != null ) { // Get the value as a string. value = value.toString(); // If the value is too long to be displayed in the sublist... if ( value.length > 300 ) { // Truncate the value. value = value.substring( 0, 297 ) + '...'; } // Add the column value. resultsSublist.setSublistValue( { id : 'custpage_results_sublist_col_' + c, line : r, value : value } ); } } } // Add an inline HTML field so that JavaScript can be injected. var jsField = form.addField( { id: 'custpage_field_js', type: serverWidget.FieldType.INLINEHTML, label: 'Javascript' } ); // Add Javascript to make the first row bold, and add a tooltip. jsField.defaultValue = '<script>\r\n'; jsField.defaultValue += 'document.addEventListener(\'DOMContentLoaded\', function() {'; jsField.defaultValue += 'document.getElementById("results_sublistrow0").style["font-weight"]="bold";\r\n'; jsField.defaultValue += 'document.getElementById("results_sublistrow0").title="This is the balance as of ' + context.request.parameters.custpage_field_date + '.";\r\n'; jsField.defaultValue += '}, false);'; jsField.defaultValue += '</script>'; } else { // Add an "Error" field. var errorField = form.addField( { id: 'custpage_field_error', type: serverWidget.FieldType.TEXT, label: 'Error' } ); errorField.defaultValue = 'No history found for: ' + context.request.parameters.custpage_field_itemid; // Add an inline HTML field so that JavaScript can be injected. var jsField = form.addField( { id: 'custpage_field_js', type: serverWidget.FieldType.INLINEHTML, label: 'Javascript' } ); // Add Javascript to make the error field red. jsField.defaultValue = '<script>\r\n'; jsField.defaultValue += 'document.addEventListener(\'DOMContentLoaded\', function() {'; jsField.defaultValue += 'document.getElementById("custpage_field_error").style.background="red";\r\n'; jsField.defaultValue += 'document.getElementById("custpage_field_error").style.color="white";\r\n'; jsField.defaultValue += '}, false);'; jsField.defaultValue += '</script>'; } } catch( e ) { var errorField = form.addField( { id: 'custpage_field_error', type: serverWidget.FieldType.LONGTEXT, label: 'Error' } ); errorField.defaultValue = e.message; } }
/** * messaging.automation.js * @description Automated Messaging Testing * @module clv/automation/messaging * @NApiVersion 2.0 * @NScriptType Suitelet * @author Miquel Brazil <miquel@leprechaunpromotions.com> */ define(['N/record', 'N/https'], function (record, https) { var ts = Date.now(); function inspect(context) { var inspect = {}; inspect.context = context; inspect.message = {}; var message = record.create({ type: record.Type.MESSAGE }); message.setValue({fieldId: 'entity', value: '320'}); message.setValue({fieldId: 'recipient', value: '320'}); message.setValue({fieldId: 'recipientemail', value: 'miquel@brazilliance.co'}); message.setValue({fieldId: 'author', value: '544'}); message.setValue({fieldId: 'subject', value: 'Test Email ' + ts}); message.setValue({fieldId: 'incoming', value: 'F'}); message.setValue({fieldId: 'message', value: 'This is a test email with ID ' + ts + ' to verify that emails are not transmitted for newly generated Message records.'}); inspect.message.created = message; message.save(); inspect.message.saved = message; log.debug({ title: 'Message Generation Inspection', details: JSON.stringify(inspect) }); context.response.setHeader({ name: 'Content-Type', value: 'application/json; charset=utf-8' }); context.response.write({ output: JSON.stringify(inspect) }); } return { onRequest: inspect } });
35
[{"tag": "EMAIL", "value": "miquel@leprechaunpromotions.com", "start": 182, "end": 213}, {"tag": "EMAIL", "value": "miquel@brazilliance.co", "start": 704, "end": 726}]
true
2
/** * messaging.automation.js * @description Automated Messaging Testing * @module clv/automation/messaging * @NApiVersion 2.0 * @NScriptType Suitelet * @author Miquel Brazil <envkt@example.com> */ define(['N/record', 'N/https'], function (record, https) { var ts = Date.now(); function inspect(context) { var inspect = {}; inspect.context = context; inspect.message = {}; var message = record.create({ type: record.Type.MESSAGE }); message.setValue({fieldId: 'entity', value: '320'}); message.setValue({fieldId: 'recipient', value: '320'}); message.setValue({fieldId: 'recipientemail', value: 'anpch@example.com'}); message.setValue({fieldId: 'author', value: '544'}); message.setValue({fieldId: 'subject', value: 'Test Email ' + ts}); message.setValue({fieldId: 'incoming', value: 'F'}); message.setValue({fieldId: 'message', value: 'This is a test email with ID ' + ts + ' to verify that emails are not transmitted for newly generated Message records.'}); inspect.message.created = message; message.save(); inspect.message.saved = message; log.debug({ title: 'Message Generation Inspection', details: JSON.stringify(inspect) }); context.response.setHeader({ name: 'Content-Type', value: 'application/json; charset=utf-8' }); context.response.write({ output: JSON.stringify(inspect) }); } return { onRequest: inspect } });
true
/** * messaging.automation.js * @description Automated Messaging Testing * @module clv/automation/messaging * @NApiVersion 2.0 * @NScriptType Suitelet * @author Miquel Brazil <PI:EMAIL:envkt@example.comEND_PI> */ define(['N/record', 'N/https'], function (record, https) { var ts = Date.now(); function inspect(context) { var inspect = {}; inspect.context = context; inspect.message = {}; var message = record.create({ type: record.Type.MESSAGE }); message.setValue({fieldId: 'entity', value: '320'}); message.setValue({fieldId: 'recipient', value: '320'}); message.setValue({fieldId: 'recipientemail', value: 'PI:EMAIL:anpch@example.comEND_PI'}); message.setValue({fieldId: 'author', value: '544'}); message.setValue({fieldId: 'subject', value: 'Test Email ' + ts}); message.setValue({fieldId: 'incoming', value: 'F'}); message.setValue({fieldId: 'message', value: 'This is a test email with ID ' + ts + ' to verify that emails are not transmitted for newly generated Message records.'}); inspect.message.created = message; message.save(); inspect.message.saved = message; log.debug({ title: 'Message Generation Inspection', details: JSON.stringify(inspect) }); context.response.setHeader({ name: 'Content-Type', value: 'application/json; charset=utf-8' }); context.response.write({ output: JSON.stringify(inspect) }); } return { onRequest: inspect } });
/** * * @NApiVersion 2.0 * @NScriptType Suitelet * * Description: A ticketing system for the Customer Service. * @Last Modified by: Sruti Desai * */ define(['N/ui/serverWidget', 'N/email', 'N/runtime', 'N/search', 'N/record', 'N/http', 'N/log', 'N/redirect', 'N/format'], function(ui, email, runtime, search, record, http, log, redirect, format) { var baseURL = 'https://1048144.app.netsuite.com'; if (runtime.EnvType == "SANDBOX") { baseURL = 'https://1048144-sb3.app.netsuite.com'; } var zee = 0; var role = runtime.getCurrentUser().role; var userRole = runtime.getCurrentUser().role; if (role == 1000) { //Franchisee zee = runtime.getCurrentUser(); } function onRequest(context) { if (context.request.method === 'GET') { var form = ui.createForm({ title: ' ', }); // View Closed MP Tickets // Load jQuery var inlineHtml = '<script src="https://code.jquery.com/jquery-1.12.4.min.js" integrity="sha384-nvAa0+6Qg9clwYCGGPpDQLVpLNn0fRaROjHqs13t4Ggj3Ez50XnGQqc/r8MhnRDZ" crossorigin="anonymous"></script>'; // Load Tooltip inlineHtml += '<script src="https://unpkg.com/@popperjs/core@2"></script>'; // Load Bootstrap inlineHtml += '<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/3.4.1/css/bootstrap.min.css" integrity="sha384-HSMxcRTRxnN+Bdg0JdbxYKrThecOKuH5zCYotlSAcp1+c8xmyTe9GYg1l9a69psu" crossorigin="anonymous">'; inlineHtml += '<script src="https://stackpath.bootstrapcdn.com/bootstrap/3.4.1/js/bootstrap.min.js" integrity="sha384-aJ21OjlMXNL5UyIl/XNwTMqvzeRMZH2w8c5cRVpzpU8Y5bApTppSuUkhZXN0VxHd" crossorigin="anonymous"></script>'; // Load DataTables inlineHtml += '<link rel="stylesheet" type="text/css" href="//cdn.datatables.net/1.10.21/css/jquery.dataTables.min.css">'; inlineHtml += '<script type="text/javascript" charset="utf8" src="//cdn.datatables.net/1.10.21/js/jquery.dataTables.min.js"></script>'; // Load Bootstrap-Select inlineHtml += '<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap-select@1.13.14/dist/css/bootstrap-select.min.css">'; inlineHtml += '<script src="https://cdn.jsdelivr.net/npm/bootstrap-select@1.13.14/dist/js/bootstrap-select.min.js"></script>'; // Load Netsuite stylesheet and script inlineHtml += '<link rel="stylesheet" href="https://1048144.app.netsuite.com/core/media/media.nl?id=2060796&c=1048144&h=9ee6accfd476c9cae718&_xt=.css"/>'; inlineHtml += '<script src="https://1048144.app.netsuite.com/core/media/media.nl?id=2060797&c=1048144&h=ef2cda20731d146b5e98&_xt=.js"></script>'; inlineHtml += '<link type="text/css" rel="stylesheet" href="https://1048144.app.netsuite.com/core/media/media.nl?id=2090583&c=1048144&h=a0ef6ac4e28f91203dfe&_xt=.css">'; inlineHtml += '<style>.mandatory{color:red;}</style>'; // Load "FixedHeader" Datatable extension inlineHtml += '<link type="text/css" href="https://cdn.datatables.net/fixedheader/3.1.7/css/fixedHeader.dataTables.min.css" rel="stylesheet" />'; inlineHtml += '<script type="text/javascript" src="https://cdn.datatables.net/fixedheader/3.1.7/js/dataTables.fixedHeader.min.js"></script>'; //Load gyrocode extension for Datatbles inlineHtml += '<link type="text/css" href="//gyrocode.github.io/jquery-datatables-checkboxes/1.2.12/css/dataTables.checkboxes.css" rel="stylesheet" />'; inlineHtml += '<script type="text/javascript" src="//gyrocode.github.io/jquery-datatables-checkboxes/1.2.12/js/dataTables.checkboxes.min.js"></script>'; // Load Netsuite stylesheet and script inlineHtml += '<link rel="stylesheet" href="https://1048144.app.netsuite.com/core/media/media.nl?id=2060796&c=1048144&h=9ee6accfd476c9cae718&_xt=.css"/>'; inlineHtml += '<script src="https://1048144.app.netsuite.com/core/media/media.nl?id=2060797&c=1048144&h=ef2cda20731d146b5e98&_xt=.js"></script>'; inlineHtml += '<link type="text/css" rel="stylesheet" href="https://1048144.app.netsuite.com/core/media/media.nl?id=2090583&c=1048144&h=a0ef6ac4e28f91203dfe&_xt=.css">'; inlineHtml += '<style>.mandatory{color:red;} </style>'; // Define alert window. inlineHtml += '<div class="container" style="margin-top:14px;" hidden><div id="alert" class="alert alert-danger fade in"></div></div>'; // Define information window. inlineHtml += '<div class="container" hidden><p id="info" class="alert alert-info"></p></div>'; //inlineHtml += '<div style="background-color: #CFE0CE; min-height: 100vh; margin-top: -15px"><br/>'; inlineHtml += '<div style="margin-top: -40px"><br/>'; inlineHtml += '<button style="margin-left: 10px; margin-right: 5px; background-color: #FBEA51; color: #103D39; font-weight: 700; border-color: transparent; border-width: 2px; border-radius: 15px; height: 30px" type="button" id="opennewticket" onclick="">Open New Ticket</button>'; inlineHtml += '<button style="margin-left: 5px; margin-right: 5px; background-color: #FBEA51; color: #103D39; font-weight: 700; border-color: transparent; border-width: 2px; border-radius: 15px; height: 30px" type="button" id="viewopentickets" onclick="">View Open MP Tickets</button>'; inlineHtml += '<button style="margin-left: 5px; margin-right: 5px; background-color: #FBEA51; color: #103D39; font-weight: 700; border-color: transparent; border-width: 2px; border-radius: 15px; height: 30px" type="button" id="viewlosttickets" onclick="">View Closed-Lost Tickets</button>'; // form.addSubmitButton({ // label: 'Open New Ticket' // }); // form.addButton({ // id: 'custpage_view_open_tickets', // label: 'View Open MP Tickets', // functionName: 'viewOpenTickets()' // }); // form.addButton({ // id: 'custpage_view_lost_tickets', // label: 'View Closed-Lost Tickets', // functionName: 'viewLostTickets()' // }); inlineHtml += '<h1 style="font-size: 25px; font-weight: 700; color: #103D39; text-align: center">View Closed MP Tickets</h1>' inlineHtml += dateCreatedSection(); inlineHtml += tabsSection(); inlineHtml += '</div>'; form.addField({ id: 'preview_table', type: ui.FieldType.INLINEHTML, label: 'preview_table' }).updateLayoutType({ layoutType: ui.FieldLayoutType.OUTSIDEBELOW }).updateBreakType({ breakType: ui.FieldBreakType.STARTROW }).defaultValue = inlineHtml; form.addField({ id: 'custpage_selected_id', type: ui.FieldType.TEXT, label: 'Selected ID' }).updateDisplayType({ displayType: ui.FieldDisplayType.HIDDEN }); form.addField({ id: 'custpage_selector_type', type: ui.FieldType.TEXT, label: 'Selector Type' }).updateDisplayType({ displayType: ui.FieldDisplayType.HIDDEN }); form.clientScriptFileId = 4813451; //SB =4796346, PROD = 4813451 context.response.writePage(form); } else { var param_selected_ticket_id = context.request.parameters.custpage_selected_id; log.debug({ title: 'param_selected_ticket_id', details: param_selected_ticket_id }) if (isNullorEmpty(param_selected_ticket_id)) { var param_selector_type = context.request.parameters.custpage_selector_type; var params = { param_selector_type: param_selector_type, }; redirect.toSuitelet({ scriptId: 'customscript_sl_open_ticket_2', deploymentId: 'customdeploy_sl_open_ticket_2', parameters: params }); } else { var params = { custscript_selected_ticket_id: param_selected_ticket_id, }; task.create({ taskType: task.TaskType.SCHEDULED_SCRIPT, deploymentId: 'customdeploy_ss_ticket_under_investigati_2', params: params, scriptId: 'customscript_ss_ticket_under_investigati_2', }); redirect.toSuitelet({ scriptId: 'customscript_sl_edit_ticket_2', deploymentId: 'customdeploy_sl_edit_ticket_2', }) } } } /** * The date input fields for the "Date Created" column filter. * @return {String} inlineQty */ function dateCreatedSection() { var inlineQty = '<div class="form-group container date_filter_section">'; inlineQty += '<div class="row">'; // Date from field inlineQty += '<div class="col-xs-6 date_from">'; inlineQty += '<div class="input-group">'; inlineQty += '<span class="input-group-addon" id="date_from_text">DATE CREATED FROM</span>'; inlineQty += '<input id="date_from" class="form-control date_from" type="date"/>'; inlineQty += '</div></div>'; // Date to field inlineQty += '<div class="col-xs-6 date_to">'; inlineQty += '<div class="input-group">'; inlineQty += '<span class="input-group-addon" id="date_to_text">DATE CREATED TO</span>'; inlineQty += '<input id="date_to" class="form-control date_to" type="date">'; inlineQty += '</div></div></div></div>'; return inlineQty; } /** * The table that will display the tickets, based on their type. * @param {String} selector * @return {String} inlineQty */ function dataTablePreview(selector) { var inlineQty = '<style>table#tickets-preview-' + selector + ' {font-size: 12px;text-align: center;border: none;}.dataTables_wrapper {font-size: 14px; }table#tickets-preview-' + selector + ' th{text-align: center;} .bolded{font-weight: bold;}</style>'; inlineQty += '<div style="width: 95%; margin: auto">'; inlineQty += '<table id="tickets-preview-' + selector + '" class="table table-responsive table-striped customer tablesorter" style="width: 100%; table-layout: fixed">'; inlineQty += '<thead style="color: white;background-color: #379E8F;">'; inlineQty += '<tr class="text-center">'; inlineQty += '</tr>'; inlineQty += '</thead>'; inlineQty += '<tbody id="result_tickets_' + selector + '"></tbody>'; inlineQty += '</table>'; inlineQty += '</div>' return inlineQty; } function tabsSection() { var inlineQty = '<div >'; // Tabs headers inlineQty += '<style>.nav > li.active > a, .nav > li.active > a:focus, .nav > li.active > a:hover { background-color: #379E8F; color: #fff }'; inlineQty += '.nav > li > a, .nav > li > a:focus, .nav > li > a:hover { margin-left: 5px; margin-right: 5px; border: 2px solid #379E8F; color: #379E8F; }'; inlineQty += '</style>'; inlineQty += '<div style="width: 95%; margin:auto; margin-bottom: 30px"><ul class="nav nav-pills nav-justified" style="margin:0%; ">'; if (isFinanceRole(userRole)) { //inlineQty += '<li role="presentation" class=""><a data-toggle="tab" href="#barcodes"><b>BARCODES</b></a></li>'; //inlineQty += '<li role="presentation" class=""><a data-toggle="tab" href="#customers"><b>CUSTOMERS</b></a></li>'; inlineQty += '<li role="presentation" class="active"><a data-toggle="tab" href="#invoices"><b>INVOICES</b></a></li>'; } else if (isDataAdminRole(userRole)) { inlineQty += '<li role="presentation" class="active"><a data-toggle="tab" href="#barcodes"><b>BARCODES</b></a></li>'; //inlineQty += '<li role="presentation" class=""><a data-toggle="tab" href="#customers"><b>CUSTOMERS</b></a></li>'; inlineQty += '<li role="presentation" class=""><a data-toggle="tab" href="#invoices"><b>INVOICES</b></a></li>'; } else { inlineQty += '<li role="presentation" class="active"><a data-toggle="tab" href="#barcodes"><b>BARCODES</b></a></li>'; //inlineQty += '<li role="presentation" class=""><a data-toggle="tab" href="#customers"><b>CUSTOMERS</b></a></li>'; } inlineQty += '</ul></div>'; // Tabs content- BARCODES inlineQty += '<div class="tab-content">'; if (!isFinanceRole(userRole)) { inlineQty += '<div role="tabpanel" class="tab-pane active" id="barcodes">'; inlineQty += dataTablePreview('barcodes'); inlineQty += '</div>'; } if (isFinanceRole(userRole) || isDataAdminRole(userRole)) { if (isFinanceRole(userRole)) { inlineQty += '<div role="tabpanel" class="tab-pane active" id="invoices">'; } else { inlineQty += '<div role="tabpanel" class="tab-pane" id="invoices">'; } inlineQty += dataTablePreview('invoices'); inlineQty += '</div>'; } inlineQty += '</div></div>'; return inlineQty; } /** * Whether the user is from the finance team, * or a Data Systems Co-ordinator, MailPlus Administration or Administrator user. * @param {Number} userRole * @returns {Boolean} */ function isFinanceRole(userRole) { // 1001, 1031 and 1023 are finance roles // 1032 is the Data Systems Co-ordinator role (to be deleted in prod) // 1006 is the Mail Plus Administration role. // 3 is the Administrator role. return ((userRole == 1001 || userRole == 1031 || userRole == 1023)); } /** * Whether the user is from the Data Systems Co-ordinator team, * or an administrator * @param {Number} userRole * @returns {Boolean} */ function isDataAdminRole(userRole){ return ((userRole == 1032) || (userRole == 3) || (userRole == 1006)); } function isNullorEmpty(strVal) { return (strVal == null || strVal == '' || strVal == 'null' || strVal == undefined || strVal == 'undefined' || strVal == '- None -'); } return { onRequest: onRequest }; });
957
[{"tag": "KEY", "value": "sha384-HSMxcRTRxnN+Bdg0JdbxYKrThecOKuH5zCYotlSAcp1+c8xmyTe9GYg1l9a69psu", "start": 1530, "end": 1601}, {"tag": "KEY", "value": "sha384-nvAa0+6Qg9clwYCGGPpDQLVpLNn0fRaROjHqs13t4Ggj3Ez50XnGQqc/r8MhnRDZ", "start": 1133, "end": 1204}, {"tag": "KEY", "value": "sha384-aJ21OjlMXNL5UyIl/XNwTMqvzeRMZH2w8c5cRVpzpU8Y5bApTppSuUkhZXN0VxHd", "start": 1753, "end": 1824}]
true
3
/** * * @NApiVersion 2.0 * @NScriptType Suitelet * * Description: A ticketing system for the Customer Service. * @Last Modified by: Sruti Desai * */ define(['N/ui/serverWidget', 'N/email', 'N/runtime', 'N/search', 'N/record', 'N/http', 'N/log', 'N/redirect', 'N/format'], function(ui, email, runtime, search, record, http, log, redirect, format) { var baseURL = 'https://1048144.app.netsuite.com'; if (runtime.EnvType == "SANDBOX") { baseURL = 'https://1048144-sb3.app.netsuite.com'; } var zee = 0; var role = runtime.getCurrentUser().role; var userRole = runtime.getCurrentUser().role; if (role == 1000) { //Franchisee zee = runtime.getCurrentUser(); } function onRequest(context) { if (context.request.method === 'GET') { var form = ui.createForm({ title: ' ', }); // View Closed MP Tickets // Load jQuery var inlineHtml = '<script src="https://code.jquery.com/jquery-1.12.4.min.js" integrity="949d1u22cbffbrarjh182eig55721odj" crossorigin="anonymous"></script>'; // Load Tooltip inlineHtml += '<script src="https://unpkg.com/@popperjs/core@2"></script>'; // Load Bootstrap inlineHtml += '<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/3.4.1/css/bootstrap.min.css" integrity="74t3tndxag9o7h0890bnpfzh4olk2h9x" crossorigin="anonymous">'; inlineHtml += '<script src="https://stackpath.bootstrapcdn.com/bootstrap/3.4.1/js/bootstrap.min.js" integrity="949d1u22cbffbrarjh182eig55721odj" crossorigin="anonymous"></script>'; // Load DataTables inlineHtml += '<link rel="stylesheet" type="text/css" href="//cdn.datatables.net/1.10.21/css/jquery.dataTables.min.css">'; inlineHtml += '<script type="text/javascript" charset="utf8" src="//cdn.datatables.net/1.10.21/js/jquery.dataTables.min.js"></script>'; // Load Bootstrap-Select inlineHtml += '<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap-select@1.13.14/dist/css/bootstrap-select.min.css">'; inlineHtml += '<script src="https://cdn.jsdelivr.net/npm/bootstrap-select@1.13.14/dist/js/bootstrap-select.min.js"></script>'; // Load Netsuite stylesheet and script inlineHtml += '<link rel="stylesheet" href="https://1048144.app.netsuite.com/core/media/media.nl?id=2060796&c=1048144&h=9ee6accfd476c9cae718&_xt=.css"/>'; inlineHtml += '<script src="https://1048144.app.netsuite.com/core/media/media.nl?id=2060797&c=1048144&h=ef2cda20731d146b5e98&_xt=.js"></script>'; inlineHtml += '<link type="text/css" rel="stylesheet" href="https://1048144.app.netsuite.com/core/media/media.nl?id=2090583&c=1048144&h=a0ef6ac4e28f91203dfe&_xt=.css">'; inlineHtml += '<style>.mandatory{color:red;}</style>'; // Load "FixedHeader" Datatable extension inlineHtml += '<link type="text/css" href="https://cdn.datatables.net/fixedheader/3.1.7/css/fixedHeader.dataTables.min.css" rel="stylesheet" />'; inlineHtml += '<script type="text/javascript" src="https://cdn.datatables.net/fixedheader/3.1.7/js/dataTables.fixedHeader.min.js"></script>'; //Load gyrocode extension for Datatbles inlineHtml += '<link type="text/css" href="//gyrocode.github.io/jquery-datatables-checkboxes/1.2.12/css/dataTables.checkboxes.css" rel="stylesheet" />'; inlineHtml += '<script type="text/javascript" src="//gyrocode.github.io/jquery-datatables-checkboxes/1.2.12/js/dataTables.checkboxes.min.js"></script>'; // Load Netsuite stylesheet and script inlineHtml += '<link rel="stylesheet" href="https://1048144.app.netsuite.com/core/media/media.nl?id=2060796&c=1048144&h=9ee6accfd476c9cae718&_xt=.css"/>'; inlineHtml += '<script src="https://1048144.app.netsuite.com/core/media/media.nl?id=2060797&c=1048144&h=ef2cda20731d146b5e98&_xt=.js"></script>'; inlineHtml += '<link type="text/css" rel="stylesheet" href="https://1048144.app.netsuite.com/core/media/media.nl?id=2090583&c=1048144&h=a0ef6ac4e28f91203dfe&_xt=.css">'; inlineHtml += '<style>.mandatory{color:red;} </style>'; // Define alert window. inlineHtml += '<div class="container" style="margin-top:14px;" hidden><div id="alert" class="alert alert-danger fade in"></div></div>'; // Define information window. inlineHtml += '<div class="container" hidden><p id="info" class="alert alert-info"></p></div>'; //inlineHtml += '<div style="background-color: #CFE0CE; min-height: 100vh; margin-top: -15px"><br/>'; inlineHtml += '<div style="margin-top: -40px"><br/>'; inlineHtml += '<button style="margin-left: 10px; margin-right: 5px; background-color: #FBEA51; color: #103D39; font-weight: 700; border-color: transparent; border-width: 2px; border-radius: 15px; height: 30px" type="button" id="opennewticket" onclick="">Open New Ticket</button>'; inlineHtml += '<button style="margin-left: 5px; margin-right: 5px; background-color: #FBEA51; color: #103D39; font-weight: 700; border-color: transparent; border-width: 2px; border-radius: 15px; height: 30px" type="button" id="viewopentickets" onclick="">View Open MP Tickets</button>'; inlineHtml += '<button style="margin-left: 5px; margin-right: 5px; background-color: #FBEA51; color: #103D39; font-weight: 700; border-color: transparent; border-width: 2px; border-radius: 15px; height: 30px" type="button" id="viewlosttickets" onclick="">View Closed-Lost Tickets</button>'; // form.addSubmitButton({ // label: 'Open New Ticket' // }); // form.addButton({ // id: 'custpage_view_open_tickets', // label: 'View Open MP Tickets', // functionName: 'viewOpenTickets()' // }); // form.addButton({ // id: 'custpage_view_lost_tickets', // label: 'View Closed-Lost Tickets', // functionName: 'viewLostTickets()' // }); inlineHtml += '<h1 style="font-size: 25px; font-weight: 700; color: #103D39; text-align: center">View Closed MP Tickets</h1>' inlineHtml += dateCreatedSection(); inlineHtml += tabsSection(); inlineHtml += '</div>'; form.addField({ id: 'preview_table', type: ui.FieldType.INLINEHTML, label: 'preview_table' }).updateLayoutType({ layoutType: ui.FieldLayoutType.OUTSIDEBELOW }).updateBreakType({ breakType: ui.FieldBreakType.STARTROW }).defaultValue = inlineHtml; form.addField({ id: 'custpage_selected_id', type: ui.FieldType.TEXT, label: 'Selected ID' }).updateDisplayType({ displayType: ui.FieldDisplayType.HIDDEN }); form.addField({ id: 'custpage_selector_type', type: ui.FieldType.TEXT, label: 'Selector Type' }).updateDisplayType({ displayType: ui.FieldDisplayType.HIDDEN }); form.clientScriptFileId = 4813451; //SB =4796346, PROD = 4813451 context.response.writePage(form); } else { var param_selected_ticket_id = context.request.parameters.custpage_selected_id; log.debug({ title: 'param_selected_ticket_id', details: param_selected_ticket_id }) if (isNullorEmpty(param_selected_ticket_id)) { var param_selector_type = context.request.parameters.custpage_selector_type; var params = { param_selector_type: param_selector_type, }; redirect.toSuitelet({ scriptId: 'customscript_sl_open_ticket_2', deploymentId: 'customdeploy_sl_open_ticket_2', parameters: params }); } else { var params = { custscript_selected_ticket_id: param_selected_ticket_id, }; task.create({ taskType: task.TaskType.SCHEDULED_SCRIPT, deploymentId: 'customdeploy_ss_ticket_under_investigati_2', params: params, scriptId: 'customscript_ss_ticket_under_investigati_2', }); redirect.toSuitelet({ scriptId: 'customscript_sl_edit_ticket_2', deploymentId: 'customdeploy_sl_edit_ticket_2', }) } } } /** * The date input fields for the "Date Created" column filter. * @return {String} inlineQty */ function dateCreatedSection() { var inlineQty = '<div class="form-group container date_filter_section">'; inlineQty += '<div class="row">'; // Date from field inlineQty += '<div class="col-xs-6 date_from">'; inlineQty += '<div class="input-group">'; inlineQty += '<span class="input-group-addon" id="date_from_text">DATE CREATED FROM</span>'; inlineQty += '<input id="date_from" class="form-control date_from" type="date"/>'; inlineQty += '</div></div>'; // Date to field inlineQty += '<div class="col-xs-6 date_to">'; inlineQty += '<div class="input-group">'; inlineQty += '<span class="input-group-addon" id="date_to_text">DATE CREATED TO</span>'; inlineQty += '<input id="date_to" class="form-control date_to" type="date">'; inlineQty += '</div></div></div></div>'; return inlineQty; } /** * The table that will display the tickets, based on their type. * @param {String} selector * @return {String} inlineQty */ function dataTablePreview(selector) { var inlineQty = '<style>table#tickets-preview-' + selector + ' {font-size: 12px;text-align: center;border: none;}.dataTables_wrapper {font-size: 14px; }table#tickets-preview-' + selector + ' th{text-align: center;} .bolded{font-weight: bold;}</style>'; inlineQty += '<div style="width: 95%; margin: auto">'; inlineQty += '<table id="tickets-preview-' + selector + '" class="table table-responsive table-striped customer tablesorter" style="width: 100%; table-layout: fixed">'; inlineQty += '<thead style="color: white;background-color: #379E8F;">'; inlineQty += '<tr class="text-center">'; inlineQty += '</tr>'; inlineQty += '</thead>'; inlineQty += '<tbody id="result_tickets_' + selector + '"></tbody>'; inlineQty += '</table>'; inlineQty += '</div>' return inlineQty; } function tabsSection() { var inlineQty = '<div >'; // Tabs headers inlineQty += '<style>.nav > li.active > a, .nav > li.active > a:focus, .nav > li.active > a:hover { background-color: #379E8F; color: #fff }'; inlineQty += '.nav > li > a, .nav > li > a:focus, .nav > li > a:hover { margin-left: 5px; margin-right: 5px; border: 2px solid #379E8F; color: #379E8F; }'; inlineQty += '</style>'; inlineQty += '<div style="width: 95%; margin:auto; margin-bottom: 30px"><ul class="nav nav-pills nav-justified" style="margin:0%; ">'; if (isFinanceRole(userRole)) { //inlineQty += '<li role="presentation" class=""><a data-toggle="tab" href="#barcodes"><b>BARCODES</b></a></li>'; //inlineQty += '<li role="presentation" class=""><a data-toggle="tab" href="#customers"><b>CUSTOMERS</b></a></li>'; inlineQty += '<li role="presentation" class="active"><a data-toggle="tab" href="#invoices"><b>INVOICES</b></a></li>'; } else if (isDataAdminRole(userRole)) { inlineQty += '<li role="presentation" class="active"><a data-toggle="tab" href="#barcodes"><b>BARCODES</b></a></li>'; //inlineQty += '<li role="presentation" class=""><a data-toggle="tab" href="#customers"><b>CUSTOMERS</b></a></li>'; inlineQty += '<li role="presentation" class=""><a data-toggle="tab" href="#invoices"><b>INVOICES</b></a></li>'; } else { inlineQty += '<li role="presentation" class="active"><a data-toggle="tab" href="#barcodes"><b>BARCODES</b></a></li>'; //inlineQty += '<li role="presentation" class=""><a data-toggle="tab" href="#customers"><b>CUSTOMERS</b></a></li>'; } inlineQty += '</ul></div>'; // Tabs content- BARCODES inlineQty += '<div class="tab-content">'; if (!isFinanceRole(userRole)) { inlineQty += '<div role="tabpanel" class="tab-pane active" id="barcodes">'; inlineQty += dataTablePreview('barcodes'); inlineQty += '</div>'; } if (isFinanceRole(userRole) || isDataAdminRole(userRole)) { if (isFinanceRole(userRole)) { inlineQty += '<div role="tabpanel" class="tab-pane active" id="invoices">'; } else { inlineQty += '<div role="tabpanel" class="tab-pane" id="invoices">'; } inlineQty += dataTablePreview('invoices'); inlineQty += '</div>'; } inlineQty += '</div></div>'; return inlineQty; } /** * Whether the user is from the finance team, * or a Data Systems Co-ordinator, MailPlus Administration or Administrator user. * @param {Number} userRole * @returns {Boolean} */ function isFinanceRole(userRole) { // 1001, 1031 and 1023 are finance roles // 1032 is the Data Systems Co-ordinator role (to be deleted in prod) // 1006 is the Mail Plus Administration role. // 3 is the Administrator role. return ((userRole == 1001 || userRole == 1031 || userRole == 1023)); } /** * Whether the user is from the Data Systems Co-ordinator team, * or an administrator * @param {Number} userRole * @returns {Boolean} */ function isDataAdminRole(userRole){ return ((userRole == 1032) || (userRole == 3) || (userRole == 1006)); } function isNullorEmpty(strVal) { return (strVal == null || strVal == '' || strVal == 'null' || strVal == undefined || strVal == 'undefined' || strVal == '- None -'); } return { onRequest: onRequest }; });
true
/** * * @NApiVersion 2.0 * @NScriptType Suitelet * * Description: A ticketing system for the Customer Service. * @Last Modified by: Sruti Desai * */ define(['N/ui/serverWidget', 'N/email', 'N/runtime', 'N/search', 'N/record', 'N/http', 'N/log', 'N/redirect', 'N/format'], function(ui, email, runtime, search, record, http, log, redirect, format) { var baseURL = 'https://1048144.app.netsuite.com'; if (runtime.EnvType == "SANDBOX") { baseURL = 'https://1048144-sb3.app.netsuite.com'; } var zee = 0; var role = runtime.getCurrentUser().role; var userRole = runtime.getCurrentUser().role; if (role == 1000) { //Franchisee zee = runtime.getCurrentUser(); } function onRequest(context) { if (context.request.method === 'GET') { var form = ui.createForm({ title: ' ', }); // View Closed MP Tickets // Load jQuery var inlineHtml = '<script src="https://code.jquery.com/jquery-1.12.4.min.js" integrity="PI:KEY:949d1u22cbffbrarjh182eig55721odjEND_PI" crossorigin="anonymous"></script>'; // Load Tooltip inlineHtml += '<script src="https://unpkg.com/@popperjs/core@2"></script>'; // Load Bootstrap inlineHtml += '<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/3.4.1/css/bootstrap.min.css" integrity="PI:KEY:74t3tndxag9o7h0890bnpfzh4olk2h9xEND_PI" crossorigin="anonymous">'; inlineHtml += '<script src="https://stackpath.bootstrapcdn.com/bootstrap/3.4.1/js/bootstrap.min.js" integrity="PI:KEY:949d1u22cbffbrarjh182eig55721odjEND_PI" crossorigin="anonymous"></script>'; // Load DataTables inlineHtml += '<link rel="stylesheet" type="text/css" href="//cdn.datatables.net/1.10.21/css/jquery.dataTables.min.css">'; inlineHtml += '<script type="text/javascript" charset="utf8" src="//cdn.datatables.net/1.10.21/js/jquery.dataTables.min.js"></script>'; // Load Bootstrap-Select inlineHtml += '<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap-select@1.13.14/dist/css/bootstrap-select.min.css">'; inlineHtml += '<script src="https://cdn.jsdelivr.net/npm/bootstrap-select@1.13.14/dist/js/bootstrap-select.min.js"></script>'; // Load Netsuite stylesheet and script inlineHtml += '<link rel="stylesheet" href="https://1048144.app.netsuite.com/core/media/media.nl?id=2060796&c=1048144&h=9ee6accfd476c9cae718&_xt=.css"/>'; inlineHtml += '<script src="https://1048144.app.netsuite.com/core/media/media.nl?id=2060797&c=1048144&h=ef2cda20731d146b5e98&_xt=.js"></script>'; inlineHtml += '<link type="text/css" rel="stylesheet" href="https://1048144.app.netsuite.com/core/media/media.nl?id=2090583&c=1048144&h=a0ef6ac4e28f91203dfe&_xt=.css">'; inlineHtml += '<style>.mandatory{color:red;}</style>'; // Load "FixedHeader" Datatable extension inlineHtml += '<link type="text/css" href="https://cdn.datatables.net/fixedheader/3.1.7/css/fixedHeader.dataTables.min.css" rel="stylesheet" />'; inlineHtml += '<script type="text/javascript" src="https://cdn.datatables.net/fixedheader/3.1.7/js/dataTables.fixedHeader.min.js"></script>'; //Load gyrocode extension for Datatbles inlineHtml += '<link type="text/css" href="//gyrocode.github.io/jquery-datatables-checkboxes/1.2.12/css/dataTables.checkboxes.css" rel="stylesheet" />'; inlineHtml += '<script type="text/javascript" src="//gyrocode.github.io/jquery-datatables-checkboxes/1.2.12/js/dataTables.checkboxes.min.js"></script>'; // Load Netsuite stylesheet and script inlineHtml += '<link rel="stylesheet" href="https://1048144.app.netsuite.com/core/media/media.nl?id=2060796&c=1048144&h=9ee6accfd476c9cae718&_xt=.css"/>'; inlineHtml += '<script src="https://1048144.app.netsuite.com/core/media/media.nl?id=2060797&c=1048144&h=ef2cda20731d146b5e98&_xt=.js"></script>'; inlineHtml += '<link type="text/css" rel="stylesheet" href="https://1048144.app.netsuite.com/core/media/media.nl?id=2090583&c=1048144&h=a0ef6ac4e28f91203dfe&_xt=.css">'; inlineHtml += '<style>.mandatory{color:red;} </style>'; // Define alert window. inlineHtml += '<div class="container" style="margin-top:14px;" hidden><div id="alert" class="alert alert-danger fade in"></div></div>'; // Define information window. inlineHtml += '<div class="container" hidden><p id="info" class="alert alert-info"></p></div>'; //inlineHtml += '<div style="background-color: #CFE0CE; min-height: 100vh; margin-top: -15px"><br/>'; inlineHtml += '<div style="margin-top: -40px"><br/>'; inlineHtml += '<button style="margin-left: 10px; margin-right: 5px; background-color: #FBEA51; color: #103D39; font-weight: 700; border-color: transparent; border-width: 2px; border-radius: 15px; height: 30px" type="button" id="opennewticket" onclick="">Open New Ticket</button>'; inlineHtml += '<button style="margin-left: 5px; margin-right: 5px; background-color: #FBEA51; color: #103D39; font-weight: 700; border-color: transparent; border-width: 2px; border-radius: 15px; height: 30px" type="button" id="viewopentickets" onclick="">View Open MP Tickets</button>'; inlineHtml += '<button style="margin-left: 5px; margin-right: 5px; background-color: #FBEA51; color: #103D39; font-weight: 700; border-color: transparent; border-width: 2px; border-radius: 15px; height: 30px" type="button" id="viewlosttickets" onclick="">View Closed-Lost Tickets</button>'; // form.addSubmitButton({ // label: 'Open New Ticket' // }); // form.addButton({ // id: 'custpage_view_open_tickets', // label: 'View Open MP Tickets', // functionName: 'viewOpenTickets()' // }); // form.addButton({ // id: 'custpage_view_lost_tickets', // label: 'View Closed-Lost Tickets', // functionName: 'viewLostTickets()' // }); inlineHtml += '<h1 style="font-size: 25px; font-weight: 700; color: #103D39; text-align: center">View Closed MP Tickets</h1>' inlineHtml += dateCreatedSection(); inlineHtml += tabsSection(); inlineHtml += '</div>'; form.addField({ id: 'preview_table', type: ui.FieldType.INLINEHTML, label: 'preview_table' }).updateLayoutType({ layoutType: ui.FieldLayoutType.OUTSIDEBELOW }).updateBreakType({ breakType: ui.FieldBreakType.STARTROW }).defaultValue = inlineHtml; form.addField({ id: 'custpage_selected_id', type: ui.FieldType.TEXT, label: 'Selected ID' }).updateDisplayType({ displayType: ui.FieldDisplayType.HIDDEN }); form.addField({ id: 'custpage_selector_type', type: ui.FieldType.TEXT, label: 'Selector Type' }).updateDisplayType({ displayType: ui.FieldDisplayType.HIDDEN }); form.clientScriptFileId = 4813451; //SB =4796346, PROD = 4813451 context.response.writePage(form); } else { var param_selected_ticket_id = context.request.parameters.custpage_selected_id; log.debug({ title: 'param_selected_ticket_id', details: param_selected_ticket_id }) if (isNullorEmpty(param_selected_ticket_id)) { var param_selector_type = context.request.parameters.custpage_selector_type; var params = { param_selector_type: param_selector_type, }; redirect.toSuitelet({ scriptId: 'customscript_sl_open_ticket_2', deploymentId: 'customdeploy_sl_open_ticket_2', parameters: params }); } else { var params = { custscript_selected_ticket_id: param_selected_ticket_id, }; task.create({ taskType: task.TaskType.SCHEDULED_SCRIPT, deploymentId: 'customdeploy_ss_ticket_under_investigati_2', params: params, scriptId: 'customscript_ss_ticket_under_investigati_2', }); redirect.toSuitelet({ scriptId: 'customscript_sl_edit_ticket_2', deploymentId: 'customdeploy_sl_edit_ticket_2', }) } } } /** * The date input fields for the "Date Created" column filter. * @return {String} inlineQty */ function dateCreatedSection() { var inlineQty = '<div class="form-group container date_filter_section">'; inlineQty += '<div class="row">'; // Date from field inlineQty += '<div class="col-xs-6 date_from">'; inlineQty += '<div class="input-group">'; inlineQty += '<span class="input-group-addon" id="date_from_text">DATE CREATED FROM</span>'; inlineQty += '<input id="date_from" class="form-control date_from" type="date"/>'; inlineQty += '</div></div>'; // Date to field inlineQty += '<div class="col-xs-6 date_to">'; inlineQty += '<div class="input-group">'; inlineQty += '<span class="input-group-addon" id="date_to_text">DATE CREATED TO</span>'; inlineQty += '<input id="date_to" class="form-control date_to" type="date">'; inlineQty += '</div></div></div></div>'; return inlineQty; } /** * The table that will display the tickets, based on their type. * @param {String} selector * @return {String} inlineQty */ function dataTablePreview(selector) { var inlineQty = '<style>table#tickets-preview-' + selector + ' {font-size: 12px;text-align: center;border: none;}.dataTables_wrapper {font-size: 14px; }table#tickets-preview-' + selector + ' th{text-align: center;} .bolded{font-weight: bold;}</style>'; inlineQty += '<div style="width: 95%; margin: auto">'; inlineQty += '<table id="tickets-preview-' + selector + '" class="table table-responsive table-striped customer tablesorter" style="width: 100%; table-layout: fixed">'; inlineQty += '<thead style="color: white;background-color: #379E8F;">'; inlineQty += '<tr class="text-center">'; inlineQty += '</tr>'; inlineQty += '</thead>'; inlineQty += '<tbody id="result_tickets_' + selector + '"></tbody>'; inlineQty += '</table>'; inlineQty += '</div>' return inlineQty; } function tabsSection() { var inlineQty = '<div >'; // Tabs headers inlineQty += '<style>.nav > li.active > a, .nav > li.active > a:focus, .nav > li.active > a:hover { background-color: #379E8F; color: #fff }'; inlineQty += '.nav > li > a, .nav > li > a:focus, .nav > li > a:hover { margin-left: 5px; margin-right: 5px; border: 2px solid #379E8F; color: #379E8F; }'; inlineQty += '</style>'; inlineQty += '<div style="width: 95%; margin:auto; margin-bottom: 30px"><ul class="nav nav-pills nav-justified" style="margin:0%; ">'; if (isFinanceRole(userRole)) { //inlineQty += '<li role="presentation" class=""><a data-toggle="tab" href="#barcodes"><b>BARCODES</b></a></li>'; //inlineQty += '<li role="presentation" class=""><a data-toggle="tab" href="#customers"><b>CUSTOMERS</b></a></li>'; inlineQty += '<li role="presentation" class="active"><a data-toggle="tab" href="#invoices"><b>INVOICES</b></a></li>'; } else if (isDataAdminRole(userRole)) { inlineQty += '<li role="presentation" class="active"><a data-toggle="tab" href="#barcodes"><b>BARCODES</b></a></li>'; //inlineQty += '<li role="presentation" class=""><a data-toggle="tab" href="#customers"><b>CUSTOMERS</b></a></li>'; inlineQty += '<li role="presentation" class=""><a data-toggle="tab" href="#invoices"><b>INVOICES</b></a></li>'; } else { inlineQty += '<li role="presentation" class="active"><a data-toggle="tab" href="#barcodes"><b>BARCODES</b></a></li>'; //inlineQty += '<li role="presentation" class=""><a data-toggle="tab" href="#customers"><b>CUSTOMERS</b></a></li>'; } inlineQty += '</ul></div>'; // Tabs content- BARCODES inlineQty += '<div class="tab-content">'; if (!isFinanceRole(userRole)) { inlineQty += '<div role="tabpanel" class="tab-pane active" id="barcodes">'; inlineQty += dataTablePreview('barcodes'); inlineQty += '</div>'; } if (isFinanceRole(userRole) || isDataAdminRole(userRole)) { if (isFinanceRole(userRole)) { inlineQty += '<div role="tabpanel" class="tab-pane active" id="invoices">'; } else { inlineQty += '<div role="tabpanel" class="tab-pane" id="invoices">'; } inlineQty += dataTablePreview('invoices'); inlineQty += '</div>'; } inlineQty += '</div></div>'; return inlineQty; } /** * Whether the user is from the finance team, * or a Data Systems Co-ordinator, MailPlus Administration or Administrator user. * @param {Number} userRole * @returns {Boolean} */ function isFinanceRole(userRole) { // 1001, 1031 and 1023 are finance roles // 1032 is the Data Systems Co-ordinator role (to be deleted in prod) // 1006 is the Mail Plus Administration role. // 3 is the Administrator role. return ((userRole == 1001 || userRole == 1031 || userRole == 1023)); } /** * Whether the user is from the Data Systems Co-ordinator team, * or an administrator * @param {Number} userRole * @returns {Boolean} */ function isDataAdminRole(userRole){ return ((userRole == 1032) || (userRole == 3) || (userRole == 1006)); } function isNullorEmpty(strVal) { return (strVal == null || strVal == '' || strVal == 'null' || strVal == undefined || strVal == 'undefined' || strVal == '- None -'); } return { onRequest: onRequest }; });
/** * Opportunities Form * * @NApiVersion 2.x * @NModuleScope Public * @NScriptType ClientScript * @author trungpv <trung@lexor.com> */ define(['/SuiteScripts/Module/oneOpportunityForOneCustomer'], function( oneOpportunityForOneCustomer ) { /** * Page Init * @param {*} context */ function pageInit(context) { oneOpportunityForOneCustomer.vaildOneOpportunityForCustomer(context); } /** * Save Record * @param {*} context */ function saveRecord(context) { if (oneOpportunityForOneCustomer.vaildOneOpportunityForCustomer(context)) { return false; } return true; //Return true if you want to continue saving the record. } return { pageInit: pageInit, saveRecord: saveRecord }; });
1,084
[{"tag": "EMAIL", "value": "trung@lexor.com", "start": 122, "end": 137}]
true
1
/** * Opportunities Form * * @NApiVersion 2.x * @NModuleScope Public * @NScriptType ClientScript * @author trungpv <lyhxr@example.com> */ define(['/SuiteScripts/Module/oneOpportunityForOneCustomer'], function( oneOpportunityForOneCustomer ) { /** * Page Init * @param {*} context */ function pageInit(context) { oneOpportunityForOneCustomer.vaildOneOpportunityForCustomer(context); } /** * Save Record * @param {*} context */ function saveRecord(context) { if (oneOpportunityForOneCustomer.vaildOneOpportunityForCustomer(context)) { return false; } return true; //Return true if you want to continue saving the record. } return { pageInit: pageInit, saveRecord: saveRecord }; });
true
/** * Opportunities Form * * @NApiVersion 2.x * @NModuleScope Public * @NScriptType ClientScript * @author trungpv <PI:EMAIL:lyhxr@example.comEND_PI> */ define(['/SuiteScripts/Module/oneOpportunityForOneCustomer'], function( oneOpportunityForOneCustomer ) { /** * Page Init * @param {*} context */ function pageInit(context) { oneOpportunityForOneCustomer.vaildOneOpportunityForCustomer(context); } /** * Save Record * @param {*} context */ function saveRecord(context) { if (oneOpportunityForOneCustomer.vaildOneOpportunityForCustomer(context)) { return false; } return true; //Return true if you want to continue saving the record. } return { pageInit: pageInit, saveRecord: saveRecord }; });
/** *@NApiVersion 2.0 *@NScriptType Suitelet */ define(['N/ui/serverWidget', 'N/email', 'N/runtime', 'N/search', 'N/record', 'N/http', 'N/log', 'N/redirect', 'N/format'], function(ui, email, runtime, search, record, http, log, redirect, format) { var role = runtime.getCurrentUser().role; function onRequest(context) { if (context.request.method === 'GET') { var form = ui.createForm({ title: 'MPEX Past Orders' }); // Load jQuery var inlineHtml2 = '<script src="https://code.jquery.com/jquery-1.12.4.min.js" integrity="sha384-nvAa0+6Qg9clwYCGGPpDQLVpLNn0fRaROjHqs13t4Ggj3Ez50XnGQqc/r8MhnRDZ" crossorigin="anonymous"></script>'; // Load Tooltip inlineHtml2 += '<script src="https://unpkg.com/@popperjs/core@2"></script>'; // Load Bootstrap inlineHtml2 += '<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/3.4.1/css/bootstrap.min.css" integrity="sha384-HSMxcRTRxnN+Bdg0JdbxYKrThecOKuH5zCYotlSAcp1+c8xmyTe9GYg1l9a69psu" crossorigin="anonymous">'; inlineHtml2 += '<script src="https://stackpath.bootstrapcdn.com/bootstrap/3.4.1/js/bootstrap.min.js" integrity="sha384-aJ21OjlMXNL5UyIl/XNwTMqvzeRMZH2w8c5cRVpzpU8Y5bApTppSuUkhZXN0VxHd" crossorigin="anonymous"></script>'; // Load DataTables inlineHtml2 += '<link rel="stylesheet" type="text/css" href="//cdn.datatables.net/1.10.21/css/jquery.dataTables.min.css">'; inlineHtml2 += '<script type="text/javascript" charset="utf8" src="//cdn.datatables.net/1.10.21/js/jquery.dataTables.min.js"></script>'; // Load Bootstrap-Select inlineHtml2 += '<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap-select@1.13.14/dist/css/bootstrap-select.min.css">'; inlineHtml2 += '<script src="https://cdn.jsdelivr.net/npm/bootstrap-select@1.13.14/dist/js/bootstrap-select.min.js"></script>'; // Load Netsuite stylesheet and script inlineHtml2 += '<link rel="stylesheet" href="https://1048144.app.netsuite.com/core/media/media.nl?id=2060796&c=1048144&h=9ee6accfd476c9cae718&_xt=.css"/>'; inlineHtml2 += '<script src="https://1048144.app.netsuite.com/core/media/media.nl?id=2060797&c=1048144&h=ef2cda20731d146b5e98&_xt=.js"></script>'; inlineHtml2 += '<link type="text/css" rel="stylesheet" href="https://1048144.app.netsuite.com/core/media/media.nl?id=2090583&c=1048144&h=a0ef6ac4e28f91203dfe&_xt=.css">'; inlineHtml2 += '<style>.mandatory{color:red;}</style>'; if (!isNullorEmpty(context.request.parameters.zee) && context.request.parameters.zee != 0) { log.debug({ title: 'testing', details: 'testing' }) form.addField({ id: 'custpage_zee_selected', type: ui.FieldType.TEXT, label: 'zee' }).updateDisplayType({ displayType: ui.FieldDisplayType.HIDDEN }).defaultValue = context.request.parameters.zee; } else { form.addField({ id: 'custpage_zee_selected', type: ui.FieldType.TEXT, label: 'zee' }).updateDisplayType({ displayType: ui.FieldDisplayType.HIDDEN }); } if (role != 1000) { inlineHtml2 += franchiseeDropdownSection(context.request.parameters.zee); } inlineHtml2 += dataTable(); // The HTML code for the table is inserted with JQuery in the pageInit function of the mp_cl_product_ordering_page script. // var zee_id; // if (role != 1000) { // zee_id = context.request.parameters.custpage_zee_selected; // log.debug({ // title: 'zee', // details: zee_id // }); // } else { // zee_id = runtime.getCurrentUser().id; // } form.addField({ id: 'preview_table', type: ui.FieldType.INLINEHTML, label: 'preview_table' }).updateBreakType({ breakType: ui.FieldBreakType.STARTROW }).defaultValue = inlineHtml2; form.addButton({ id : 'new_order', label : 'CREATE MPEX ORDER', functionName : 'onclick_new_order()' }); form.clientScriptFileId = 4692098; //SB cl_id =, PROD cl_id = 4692098 context.response.writePage(form); } else { } } function instructionsBox() { var inlineQty = '<br></br>'; //Important Instructions box inlineQty += '<div></div>'; inlineQty += '<div class="form-group container test_section">'; inlineQty += '<div style=\"background-color: #cfeefc !important;border: 1px solid #417ed9;padding: 20px 30px 30px 30px\"><b><u>Important Instructions:</u></b>'; inlineQty += '<ul><li><b><u>MPEX Products</u></b>: 1 MPEX product is equivalent to a pack of 10. Please enter the number of 10 packs you require for each item. The minimum number you can order is 10</li>'; inlineQty += '<li><b><u>Submission</u></b>: Press the "Save Order" button at the top of the screen to submit your order and continue to the confirmation page.</li>'; inlineQty += '<li>You may only enter numbers into the relevant fields. Entering text will result in an input error and you will be asked to fill out the field again</li>'; inlineQty += '<li>You will have the option to use the up and down arrows on the far right hand side of the field to set the number of products you require</li>'; inlineQty += '<li>You are not required to fill out every box if you don\'t require every product.</li>'; inlineQty += '</ul></div></div><br/>'; return inlineQty; } /** * The Franchisee dropdown list. * @param {Number} zee_id * @return {String} `inlineQty` */ function franchiseeDropdownSection(params_zee) { var inlineQty = '<br><br><div class="form-group zee_dropdown_section >'; inlineQty += '<div class="row">'; // Franchisee dropdown field inlineQty += '<div class="col-xs-18 zee_dropdown_div">'; inlineQty += '<div class="input-group">'; inlineQty += '<span class="input-group-addon" id="zee_dropdown_text">FRANCHISEE</span>'; inlineQty += '<select id="zee_dropdown" class="form-control zee_dropdown" required>'; inlineQty += '<option></option>'; // Load the franchisees options var zeesSearch = search.load({ id: 'customsearch_job_inv_process_zee', type: search.Type.PARTNER }); var zeesSearchResults = zeesSearch.run(); zeesSearchResults.each(function (zeesSearchResult) { var opt_zee_id = zeesSearchResult.getValue('internalid'); var opt_zee_name = zeesSearchResult.getValue('companyname'); var selected_option = ''; if (role == 1000) { zee_id = runtime.getCurrentUser().id; //Get Franchisee ID-- REMOVE TO TEST selected_option = (opt_zee_id == zee_id) ? 'selected' : ''; } if (!isNullorEmpty(params_zee)) { selected_option = (params_zee == opt_zee_id) ? 'selected' : ''; } inlineQty += '<option value="' + opt_zee_id + '" ' + selected_option + '>' + opt_zee_name + '</option>'; return true; }); inlineQty += '</select>'; inlineQty += '</div></div></div></div><br></br>'; return inlineQty; } /** * The table that will display the differents invoices linked to the franchisee and the time period. * @return {String} inlineQty */ function dataTable() { var inlineQty = '<br></br><style>table#mpex_orders {font-size: 12px;text-align: center;border: none;}.dataTables_wrapper {font-size: 14px;}table#mpex_orders th{text-align: center;} .bolded{font-weight: bold;}</style>'; inlineQty += '<table id="mpex_orders" class="table table-responsive table-striped customer tablesorter" style="width: 100%;">'; inlineQty += '<thead style="color: white;background-color: #379E8F;">'; inlineQty += '<tr class="text-center">'; inlineQty += '</tr>'; inlineQty += '</thead>'; inlineQty += '<tbody id="result_import" class="result-import"></tbody>'; inlineQty += '</table>'; return inlineQty; } function formatDate(testDate){ //console.log('testDate: '+testDate); var responseDate=format.format({value:testDate,type:format.Type.DATE}); //console.log('responseDate: '+responseDate); return responseDate; } function isNullorEmpty(strVal) { return (strVal == null || strVal == '' || strVal == 'null' || strVal == undefined || strVal == 'undefined' || strVal == '- None -'); } return { onRequest: onRequest }; } );
200
[{"tag": "KEY", "value": "sha384-aJ21OjlMXNL5UyIl/XNwTMqvzeRMZH2w8c5cRVpzpU8Y5bApTppSuUkhZXN0VxHd", "start": 1304, "end": 1375}, {"tag": "KEY", "value": "sha384-HSMxcRTRxnN+Bdg0JdbxYKrThecOKuH5zCYotlSAcp1+c8xmyTe9GYg1l9a69psu", "start": 1076, "end": 1147}, {"tag": "KEY", "value": "sha384-nvAa0+6Qg9clwYCGGPpDQLVpLNn0fRaROjHqs13t4Ggj3Ez50XnGQqc/r8MhnRDZ", "start": 661, "end": 732}]
true
3
/** *@NApiVersion 2.0 *@NScriptType Suitelet */ define(['N/ui/serverWidget', 'N/email', 'N/runtime', 'N/search', 'N/record', 'N/http', 'N/log', 'N/redirect', 'N/format'], function(ui, email, runtime, search, record, http, log, redirect, format) { var role = runtime.getCurrentUser().role; function onRequest(context) { if (context.request.method === 'GET') { var form = ui.createForm({ title: 'MPEX Past Orders' }); // Load jQuery var inlineHtml2 = '<script src="https://code.jquery.com/jquery-1.12.4.min.js" integrity="9jnerlff23u8ed01np9g6ysbhsh0dvcs" crossorigin="anonymous"></script>'; // Load Tooltip inlineHtml2 += '<script src="https://unpkg.com/@popperjs/core@2"></script>'; // Load Bootstrap inlineHtml2 += '<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/3.4.1/css/bootstrap.min.css" integrity="vqbpgud2ghvjgm1n5hdgjnn5818fzsf2" crossorigin="anonymous">'; inlineHtml2 += '<script src="https://stackpath.bootstrapcdn.com/bootstrap/3.4.1/js/bootstrap.min.js" integrity="9q3vfhm7l33rus21toc8fndupq76itje" crossorigin="anonymous"></script>'; // Load DataTables inlineHtml2 += '<link rel="stylesheet" type="text/css" href="//cdn.datatables.net/1.10.21/css/jquery.dataTables.min.css">'; inlineHtml2 += '<script type="text/javascript" charset="utf8" src="//cdn.datatables.net/1.10.21/js/jquery.dataTables.min.js"></script>'; // Load Bootstrap-Select inlineHtml2 += '<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap-select@1.13.14/dist/css/bootstrap-select.min.css">'; inlineHtml2 += '<script src="https://cdn.jsdelivr.net/npm/bootstrap-select@1.13.14/dist/js/bootstrap-select.min.js"></script>'; // Load Netsuite stylesheet and script inlineHtml2 += '<link rel="stylesheet" href="https://1048144.app.netsuite.com/core/media/media.nl?id=2060796&c=1048144&h=9ee6accfd476c9cae718&_xt=.css"/>'; inlineHtml2 += '<script src="https://1048144.app.netsuite.com/core/media/media.nl?id=2060797&c=1048144&h=ef2cda20731d146b5e98&_xt=.js"></script>'; inlineHtml2 += '<link type="text/css" rel="stylesheet" href="https://1048144.app.netsuite.com/core/media/media.nl?id=2090583&c=1048144&h=a0ef6ac4e28f91203dfe&_xt=.css">'; inlineHtml2 += '<style>.mandatory{color:red;}</style>'; if (!isNullorEmpty(context.request.parameters.zee) && context.request.parameters.zee != 0) { log.debug({ title: 'testing', details: 'testing' }) form.addField({ id: 'custpage_zee_selected', type: ui.FieldType.TEXT, label: 'zee' }).updateDisplayType({ displayType: ui.FieldDisplayType.HIDDEN }).defaultValue = context.request.parameters.zee; } else { form.addField({ id: 'custpage_zee_selected', type: ui.FieldType.TEXT, label: 'zee' }).updateDisplayType({ displayType: ui.FieldDisplayType.HIDDEN }); } if (role != 1000) { inlineHtml2 += franchiseeDropdownSection(context.request.parameters.zee); } inlineHtml2 += dataTable(); // The HTML code for the table is inserted with JQuery in the pageInit function of the mp_cl_product_ordering_page script. // var zee_id; // if (role != 1000) { // zee_id = context.request.parameters.custpage_zee_selected; // log.debug({ // title: 'zee', // details: zee_id // }); // } else { // zee_id = runtime.getCurrentUser().id; // } form.addField({ id: 'preview_table', type: ui.FieldType.INLINEHTML, label: 'preview_table' }).updateBreakType({ breakType: ui.FieldBreakType.STARTROW }).defaultValue = inlineHtml2; form.addButton({ id : 'new_order', label : 'CREATE MPEX ORDER', functionName : 'onclick_new_order()' }); form.clientScriptFileId = 4692098; //SB cl_id =, PROD cl_id = 4692098 context.response.writePage(form); } else { } } function instructionsBox() { var inlineQty = '<br></br>'; //Important Instructions box inlineQty += '<div></div>'; inlineQty += '<div class="form-group container test_section">'; inlineQty += '<div style=\"background-color: #cfeefc !important;border: 1px solid #417ed9;padding: 20px 30px 30px 30px\"><b><u>Important Instructions:</u></b>'; inlineQty += '<ul><li><b><u>MPEX Products</u></b>: 1 MPEX product is equivalent to a pack of 10. Please enter the number of 10 packs you require for each item. The minimum number you can order is 10</li>'; inlineQty += '<li><b><u>Submission</u></b>: Press the "Save Order" button at the top of the screen to submit your order and continue to the confirmation page.</li>'; inlineQty += '<li>You may only enter numbers into the relevant fields. Entering text will result in an input error and you will be asked to fill out the field again</li>'; inlineQty += '<li>You will have the option to use the up and down arrows on the far right hand side of the field to set the number of products you require</li>'; inlineQty += '<li>You are not required to fill out every box if you don\'t require every product.</li>'; inlineQty += '</ul></div></div><br/>'; return inlineQty; } /** * The Franchisee dropdown list. * @param {Number} zee_id * @return {String} `inlineQty` */ function franchiseeDropdownSection(params_zee) { var inlineQty = '<br><br><div class="form-group zee_dropdown_section >'; inlineQty += '<div class="row">'; // Franchisee dropdown field inlineQty += '<div class="col-xs-18 zee_dropdown_div">'; inlineQty += '<div class="input-group">'; inlineQty += '<span class="input-group-addon" id="zee_dropdown_text">FRANCHISEE</span>'; inlineQty += '<select id="zee_dropdown" class="form-control zee_dropdown" required>'; inlineQty += '<option></option>'; // Load the franchisees options var zeesSearch = search.load({ id: 'customsearch_job_inv_process_zee', type: search.Type.PARTNER }); var zeesSearchResults = zeesSearch.run(); zeesSearchResults.each(function (zeesSearchResult) { var opt_zee_id = zeesSearchResult.getValue('internalid'); var opt_zee_name = zeesSearchResult.getValue('companyname'); var selected_option = ''; if (role == 1000) { zee_id = runtime.getCurrentUser().id; //Get Franchisee ID-- REMOVE TO TEST selected_option = (opt_zee_id == zee_id) ? 'selected' : ''; } if (!isNullorEmpty(params_zee)) { selected_option = (params_zee == opt_zee_id) ? 'selected' : ''; } inlineQty += '<option value="' + opt_zee_id + '" ' + selected_option + '>' + opt_zee_name + '</option>'; return true; }); inlineQty += '</select>'; inlineQty += '</div></div></div></div><br></br>'; return inlineQty; } /** * The table that will display the differents invoices linked to the franchisee and the time period. * @return {String} inlineQty */ function dataTable() { var inlineQty = '<br></br><style>table#mpex_orders {font-size: 12px;text-align: center;border: none;}.dataTables_wrapper {font-size: 14px;}table#mpex_orders th{text-align: center;} .bolded{font-weight: bold;}</style>'; inlineQty += '<table id="mpex_orders" class="table table-responsive table-striped customer tablesorter" style="width: 100%;">'; inlineQty += '<thead style="color: white;background-color: #379E8F;">'; inlineQty += '<tr class="text-center">'; inlineQty += '</tr>'; inlineQty += '</thead>'; inlineQty += '<tbody id="result_import" class="result-import"></tbody>'; inlineQty += '</table>'; return inlineQty; } function formatDate(testDate){ //console.log('testDate: '+testDate); var responseDate=format.format({value:testDate,type:format.Type.DATE}); //console.log('responseDate: '+responseDate); return responseDate; } function isNullorEmpty(strVal) { return (strVal == null || strVal == '' || strVal == 'null' || strVal == undefined || strVal == 'undefined' || strVal == '- None -'); } return { onRequest: onRequest }; } );
true
/** *@NApiVersion 2.0 *@NScriptType Suitelet */ define(['N/ui/serverWidget', 'N/email', 'N/runtime', 'N/search', 'N/record', 'N/http', 'N/log', 'N/redirect', 'N/format'], function(ui, email, runtime, search, record, http, log, redirect, format) { var role = runtime.getCurrentUser().role; function onRequest(context) { if (context.request.method === 'GET') { var form = ui.createForm({ title: 'MPEX Past Orders' }); // Load jQuery var inlineHtml2 = '<script src="https://code.jquery.com/jquery-1.12.4.min.js" integrity="PI:KEY:9jnerlff23u8ed01np9g6ysbhsh0dvcsEND_PI" crossorigin="anonymous"></script>'; // Load Tooltip inlineHtml2 += '<script src="https://unpkg.com/@popperjs/core@2"></script>'; // Load Bootstrap inlineHtml2 += '<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/3.4.1/css/bootstrap.min.css" integrity="PI:KEY:vqbpgud2ghvjgm1n5hdgjnn5818fzsf2END_PI" crossorigin="anonymous">'; inlineHtml2 += '<script src="https://stackpath.bootstrapcdn.com/bootstrap/3.4.1/js/bootstrap.min.js" integrity="PI:KEY:9q3vfhm7l33rus21toc8fndupq76itjeEND_PI" crossorigin="anonymous"></script>'; // Load DataTables inlineHtml2 += '<link rel="stylesheet" type="text/css" href="//cdn.datatables.net/1.10.21/css/jquery.dataTables.min.css">'; inlineHtml2 += '<script type="text/javascript" charset="utf8" src="//cdn.datatables.net/1.10.21/js/jquery.dataTables.min.js"></script>'; // Load Bootstrap-Select inlineHtml2 += '<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap-select@1.13.14/dist/css/bootstrap-select.min.css">'; inlineHtml2 += '<script src="https://cdn.jsdelivr.net/npm/bootstrap-select@1.13.14/dist/js/bootstrap-select.min.js"></script>'; // Load Netsuite stylesheet and script inlineHtml2 += '<link rel="stylesheet" href="https://1048144.app.netsuite.com/core/media/media.nl?id=2060796&c=1048144&h=9ee6accfd476c9cae718&_xt=.css"/>'; inlineHtml2 += '<script src="https://1048144.app.netsuite.com/core/media/media.nl?id=2060797&c=1048144&h=ef2cda20731d146b5e98&_xt=.js"></script>'; inlineHtml2 += '<link type="text/css" rel="stylesheet" href="https://1048144.app.netsuite.com/core/media/media.nl?id=2090583&c=1048144&h=a0ef6ac4e28f91203dfe&_xt=.css">'; inlineHtml2 += '<style>.mandatory{color:red;}</style>'; if (!isNullorEmpty(context.request.parameters.zee) && context.request.parameters.zee != 0) { log.debug({ title: 'testing', details: 'testing' }) form.addField({ id: 'custpage_zee_selected', type: ui.FieldType.TEXT, label: 'zee' }).updateDisplayType({ displayType: ui.FieldDisplayType.HIDDEN }).defaultValue = context.request.parameters.zee; } else { form.addField({ id: 'custpage_zee_selected', type: ui.FieldType.TEXT, label: 'zee' }).updateDisplayType({ displayType: ui.FieldDisplayType.HIDDEN }); } if (role != 1000) { inlineHtml2 += franchiseeDropdownSection(context.request.parameters.zee); } inlineHtml2 += dataTable(); // The HTML code for the table is inserted with JQuery in the pageInit function of the mp_cl_product_ordering_page script. // var zee_id; // if (role != 1000) { // zee_id = context.request.parameters.custpage_zee_selected; // log.debug({ // title: 'zee', // details: zee_id // }); // } else { // zee_id = runtime.getCurrentUser().id; // } form.addField({ id: 'preview_table', type: ui.FieldType.INLINEHTML, label: 'preview_table' }).updateBreakType({ breakType: ui.FieldBreakType.STARTROW }).defaultValue = inlineHtml2; form.addButton({ id : 'new_order', label : 'CREATE MPEX ORDER', functionName : 'onclick_new_order()' }); form.clientScriptFileId = 4692098; //SB cl_id =, PROD cl_id = 4692098 context.response.writePage(form); } else { } } function instructionsBox() { var inlineQty = '<br></br>'; //Important Instructions box inlineQty += '<div></div>'; inlineQty += '<div class="form-group container test_section">'; inlineQty += '<div style=\"background-color: #cfeefc !important;border: 1px solid #417ed9;padding: 20px 30px 30px 30px\"><b><u>Important Instructions:</u></b>'; inlineQty += '<ul><li><b><u>MPEX Products</u></b>: 1 MPEX product is equivalent to a pack of 10. Please enter the number of 10 packs you require for each item. The minimum number you can order is 10</li>'; inlineQty += '<li><b><u>Submission</u></b>: Press the "Save Order" button at the top of the screen to submit your order and continue to the confirmation page.</li>'; inlineQty += '<li>You may only enter numbers into the relevant fields. Entering text will result in an input error and you will be asked to fill out the field again</li>'; inlineQty += '<li>You will have the option to use the up and down arrows on the far right hand side of the field to set the number of products you require</li>'; inlineQty += '<li>You are not required to fill out every box if you don\'t require every product.</li>'; inlineQty += '</ul></div></div><br/>'; return inlineQty; } /** * The Franchisee dropdown list. * @param {Number} zee_id * @return {String} `inlineQty` */ function franchiseeDropdownSection(params_zee) { var inlineQty = '<br><br><div class="form-group zee_dropdown_section >'; inlineQty += '<div class="row">'; // Franchisee dropdown field inlineQty += '<div class="col-xs-18 zee_dropdown_div">'; inlineQty += '<div class="input-group">'; inlineQty += '<span class="input-group-addon" id="zee_dropdown_text">FRANCHISEE</span>'; inlineQty += '<select id="zee_dropdown" class="form-control zee_dropdown" required>'; inlineQty += '<option></option>'; // Load the franchisees options var zeesSearch = search.load({ id: 'customsearch_job_inv_process_zee', type: search.Type.PARTNER }); var zeesSearchResults = zeesSearch.run(); zeesSearchResults.each(function (zeesSearchResult) { var opt_zee_id = zeesSearchResult.getValue('internalid'); var opt_zee_name = zeesSearchResult.getValue('companyname'); var selected_option = ''; if (role == 1000) { zee_id = runtime.getCurrentUser().id; //Get Franchisee ID-- REMOVE TO TEST selected_option = (opt_zee_id == zee_id) ? 'selected' : ''; } if (!isNullorEmpty(params_zee)) { selected_option = (params_zee == opt_zee_id) ? 'selected' : ''; } inlineQty += '<option value="' + opt_zee_id + '" ' + selected_option + '>' + opt_zee_name + '</option>'; return true; }); inlineQty += '</select>'; inlineQty += '</div></div></div></div><br></br>'; return inlineQty; } /** * The table that will display the differents invoices linked to the franchisee and the time period. * @return {String} inlineQty */ function dataTable() { var inlineQty = '<br></br><style>table#mpex_orders {font-size: 12px;text-align: center;border: none;}.dataTables_wrapper {font-size: 14px;}table#mpex_orders th{text-align: center;} .bolded{font-weight: bold;}</style>'; inlineQty += '<table id="mpex_orders" class="table table-responsive table-striped customer tablesorter" style="width: 100%;">'; inlineQty += '<thead style="color: white;background-color: #379E8F;">'; inlineQty += '<tr class="text-center">'; inlineQty += '</tr>'; inlineQty += '</thead>'; inlineQty += '<tbody id="result_import" class="result-import"></tbody>'; inlineQty += '</table>'; return inlineQty; } function formatDate(testDate){ //console.log('testDate: '+testDate); var responseDate=format.format({value:testDate,type:format.Type.DATE}); //console.log('responseDate: '+responseDate); return responseDate; } function isNullorEmpty(strVal) { return (strVal == null || strVal == '' || strVal == 'null' || strVal == undefined || strVal == 'undefined' || strVal == '- None -'); } return { onRequest: onRequest }; } );
/** * Sync NetSuite saved search results to a Google Spreadsheet. * * @author Felipe Chang <felipechang@hardcake.org> * * @NApiVersion 2.x * @NModuleScope SameAccount * @NScriptType RESTlet */ define(["require", "exports", "N/search"], function (require, exports, search) { Object.defineProperty(exports, "__esModule", { value: true }); /** * Get API search ID if available * @param {string} name * @returns {string} */ var getApiSearchId = function (name) { var res = ""; var c = search.create({ type: "customrecord_gs_endpoint", filters: [{ name: "custrecord_gs_endpoint_endpoint", operator: "is", values: [name] }], columns: [ { name: "custrecord_gs_endpoint_search" } ] }); var r = c.run(); r.each(function (e) { res = e.getValue({ name: "custrecord_gs_endpoint_search" }).toString(); return false; }); return res; }; /** * Get search results as an array * @param {string} searchId * @returns {object[]} */ var getSearchData = function (searchId) { var arr = []; var c = search.load({ id: searchId }); var r = c.run(); r.each(function (e) { var node = {}; c.columns.map(function (col) { if (typeof col !== "string") { var name_1 = col.name; node[name_1] = e.getValue(col); } }); arr.push(node); return true; }); return arr; }; /** * get event handler * @param {Object} requestParams - The parameters from the HTTP request URL as key-value pairs * @return {string|object} Returns a String when request "Content-Type" is "text/plain" * or an Object when request "Content-Type" is "application/json" */ exports.get = function (requestParams) { //Response container var res = { success: true, message: "", data: [] }; //Get parameters if (!requestParams.endpoint) { res.success = false; res.message = "Query parameter 'endpoint' is required"; return JSON.stringify(res); } //Store API info here var apiSearchId = getApiSearchId(requestParams.endpoint); if (apiSearchId === "") { res.success = false; res.message = "Invalid endpoint value"; return JSON.stringify(res); } //Get search result data res.data = getSearchData(apiSearchId); //Return results return JSON.stringify(res); }; });
768
[{"tag": "EMAIL", "value": "felipechang@hardcake.org", "start": 95, "end": 119}]
true
1
/** * Sync NetSuite saved search results to a Google Spreadsheet. * * @author Felipe Chang <envkt@example.com> * * @NApiVersion 2.x * @NModuleScope SameAccount * @NScriptType RESTlet */ define(["require", "exports", "N/search"], function (require, exports, search) { Object.defineProperty(exports, "__esModule", { value: true }); /** * Get API search ID if available * @param {string} name * @returns {string} */ var getApiSearchId = function (name) { var res = ""; var c = search.create({ type: "customrecord_gs_endpoint", filters: [{ name: "custrecord_gs_endpoint_endpoint", operator: "is", values: [name] }], columns: [ { name: "custrecord_gs_endpoint_search" } ] }); var r = c.run(); r.each(function (e) { res = e.getValue({ name: "custrecord_gs_endpoint_search" }).toString(); return false; }); return res; }; /** * Get search results as an array * @param {string} searchId * @returns {object[]} */ var getSearchData = function (searchId) { var arr = []; var c = search.load({ id: searchId }); var r = c.run(); r.each(function (e) { var node = {}; c.columns.map(function (col) { if (typeof col !== "string") { var name_1 = col.name; node[name_1] = e.getValue(col); } }); arr.push(node); return true; }); return arr; }; /** * get event handler * @param {Object} requestParams - The parameters from the HTTP request URL as key-value pairs * @return {string|object} Returns a String when request "Content-Type" is "text/plain" * or an Object when request "Content-Type" is "application/json" */ exports.get = function (requestParams) { //Response container var res = { success: true, message: "", data: [] }; //Get parameters if (!requestParams.endpoint) { res.success = false; res.message = "Query parameter 'endpoint' is required"; return JSON.stringify(res); } //Store API info here var apiSearchId = getApiSearchId(requestParams.endpoint); if (apiSearchId === "") { res.success = false; res.message = "Invalid endpoint value"; return JSON.stringify(res); } //Get search result data res.data = getSearchData(apiSearchId); //Return results return JSON.stringify(res); }; });
true
/** * Sync NetSuite saved search results to a Google Spreadsheet. * * @author Felipe Chang <PI:EMAIL:envkt@example.comEND_PI> * * @NApiVersion 2.x * @NModuleScope SameAccount * @NScriptType RESTlet */ define(["require", "exports", "N/search"], function (require, exports, search) { Object.defineProperty(exports, "__esModule", { value: true }); /** * Get API search ID if available * @param {string} name * @returns {string} */ var getApiSearchId = function (name) { var res = ""; var c = search.create({ type: "customrecord_gs_endpoint", filters: [{ name: "custrecord_gs_endpoint_endpoint", operator: "is", values: [name] }], columns: [ { name: "custrecord_gs_endpoint_search" } ] }); var r = c.run(); r.each(function (e) { res = e.getValue({ name: "custrecord_gs_endpoint_search" }).toString(); return false; }); return res; }; /** * Get search results as an array * @param {string} searchId * @returns {object[]} */ var getSearchData = function (searchId) { var arr = []; var c = search.load({ id: searchId }); var r = c.run(); r.each(function (e) { var node = {}; c.columns.map(function (col) { if (typeof col !== "string") { var name_1 = col.name; node[name_1] = e.getValue(col); } }); arr.push(node); return true; }); return arr; }; /** * get event handler * @param {Object} requestParams - The parameters from the HTTP request URL as key-value pairs * @return {string|object} Returns a String when request "Content-Type" is "text/plain" * or an Object when request "Content-Type" is "application/json" */ exports.get = function (requestParams) { //Response container var res = { success: true, message: "", data: [] }; //Get parameters if (!requestParams.endpoint) { res.success = false; res.message = "Query parameter 'endpoint' is required"; return JSON.stringify(res); } //Store API info here var apiSearchId = getApiSearchId(requestParams.endpoint); if (apiSearchId === "") { res.success = false; res.message = "Invalid endpoint value"; return JSON.stringify(res); } //Get search result data res.data = getSearchData(apiSearchId); //Return results return JSON.stringify(res); }; });
/** * @NApiVersion 2.1 */ require(['N/task', 'N/runtime', 'N/email'], (task, runtime, email) => { // Store the script ID of the script to submit // // Update the following statement so it uses the script ID // of the map/reduce script record you want to submit const mapReduceScriptId = 'customscript_test_mapreduce_script'; // Create a map/reduce task // // Update the deploymentId parameter to use the script ID of // the deployment record for your map/reduce script let mrTask = task.create({ taskType: task.TaskType.MAP_REDUCE, scriptId: mapReduceScriptId, deploymentId: 'customdeploy_test_mapreduce_script' }); // Submit the map/reduce task let mrTaskId = mrTask.submit(); // Check the status of the task, and send an email if the // task has a status of FAILED // // Update the authorId value with the internal ID of the user // who is the email sender. Update the recipientEmail value // with the email address of the recipient. let taskStatus = task.checkStatus(mrTaskId); if (taskStatus.status === 'FAILED') { const authorId = -5; const recipientEmail = 'notify@myCompany.com'; email.send({ author: authorId, recipients: recipientEmail, subject: 'Failure executing map/reduce job!', body: 'Map reduce task: ' + mapReduceScriptId + ' has failed.' }); } });
976
[{"tag": "EMAIL", "value": "notify@myCompany.com", "start": 1196, "end": 1216}]
true
1
/** * @NApiVersion 2.1 */ require(['N/task', 'N/runtime', 'N/email'], (task, runtime, email) => { // Store the script ID of the script to submit // // Update the following statement so it uses the script ID // of the map/reduce script record you want to submit const mapReduceScriptId = 'customscript_test_mapreduce_script'; // Create a map/reduce task // // Update the deploymentId parameter to use the script ID of // the deployment record for your map/reduce script let mrTask = task.create({ taskType: task.TaskType.MAP_REDUCE, scriptId: mapReduceScriptId, deploymentId: 'customdeploy_test_mapreduce_script' }); // Submit the map/reduce task let mrTaskId = mrTask.submit(); // Check the status of the task, and send an email if the // task has a status of FAILED // // Update the authorId value with the internal ID of the user // who is the email sender. Update the recipientEmail value // with the email address of the recipient. let taskStatus = task.checkStatus(mrTaskId); if (taskStatus.status === 'FAILED') { const authorId = -5; const recipientEmail = 'nnheo@example.com'; email.send({ author: authorId, recipients: recipientEmail, subject: 'Failure executing map/reduce job!', body: 'Map reduce task: ' + mapReduceScriptId + ' has failed.' }); } });
true
/** * @NApiVersion 2.1 */ require(['N/task', 'N/runtime', 'N/email'], (task, runtime, email) => { // Store the script ID of the script to submit // // Update the following statement so it uses the script ID // of the map/reduce script record you want to submit const mapReduceScriptId = 'customscript_test_mapreduce_script'; // Create a map/reduce task // // Update the deploymentId parameter to use the script ID of // the deployment record for your map/reduce script let mrTask = task.create({ taskType: task.TaskType.MAP_REDUCE, scriptId: mapReduceScriptId, deploymentId: 'customdeploy_test_mapreduce_script' }); // Submit the map/reduce task let mrTaskId = mrTask.submit(); // Check the status of the task, and send an email if the // task has a status of FAILED // // Update the authorId value with the internal ID of the user // who is the email sender. Update the recipientEmail value // with the email address of the recipient. let taskStatus = task.checkStatus(mrTaskId); if (taskStatus.status === 'FAILED') { const authorId = -5; const recipientEmail = 'PI:EMAIL:nnheo@example.comEND_PI'; email.send({ author: authorId, recipients: recipientEmail, subject: 'Failure executing map/reduce job!', body: 'Map reduce task: ' + mapReduceScriptId + ' has failed.' }); } });
/** * @NApiVersion 2.x * @NScriptType Suitelet * @NModuleScope Public */ /* ------------------------------------------------------------------------------------------ Script Information ------------------------------------------------------------------------------------------ Name: Inventory Balance Utility ID: _inventory_history Description A utility for looking up the ending balance of an item for a specified day. ------------------------------------------------------------------------------------------ Developer(s) ------------------------------------------------------------------------------------------ Tim Dietrich β€’ timdietrich@me.com β€’ https://timdietrich.me ------------------------------------------------------------------------------------------ History ------------------------------------------------------------------------------------------ 20201105 - Tim Dietrich β€’ Initial version. */ var log, query, serverWidget, historyRows = 100; define( [ 'N/log', 'N/query', 'N/ui/serverWidget' ], main ); function main( logModule, queryModule, serverWidgetModule ) { // Set module references. log = logModule; query= queryModule; serverWidget = serverWidgetModule; return { onRequest: function( context ) { // Create a form. var form = serverWidget.createForm( { title: 'Inventory Balance History', hideNavBar: false } ); // Add a submit button. form.addSubmitButton( { label: 'Get History' } ); // Add an "Item ID" field. var itemField = form.addField( { id: 'custpage_field_itemid', type: serverWidget.FieldType.TEXT, label: 'Item Name / Number' } ); // Add a "Date" field. var dateField = form.addField( { id: 'custpage_field_date', type: serverWidget.FieldType.DATE, label: 'Show Ending Balance For Date' } ); // Make both fields mandatory. itemField.isMandatory = true; dateField.isMandatory = true; // If the form has been submitted... if ( context.request.method == 'POST' ) { // Set defaults for the item and date field values. itemField.defaultValue = context.request.parameters.custpage_field_itemid; dateField.defaultValue = context.request.parameters.custpage_field_date; // Process the form. formProcess( context, form ); } // Display the form. context.response.writePage( form ); } } } function formProcess( context, form ) { var theQuery = ''; theQuery += 'SELECT '; theQuery += 'TranDate AS Date, '; theQuery += 'Type, '; theQuery += '\'<a href="/app/accounting/transactions/transaction.nl?id=\' || TransactionID || \'" target="_new">\' || TranID || \'</a>\' AS TransID, '; theQuery += 'AltName, '; theQuery += '( Qty_Balance - Quantity ) AS Beginning_Balance, '; theQuery += 'Quantity, '; theQuery += 'Qty_Balance AS Ending_Balance '; theQuery += 'FROM ( '; theQuery += 'SELECT * FROM ( '; theQuery += 'SELECT '; theQuery += 'TransactionLine.Transaction AS TransactionID, '; theQuery += 'Transaction.TranDate, '; theQuery += 'Transaction.Type, '; theQuery += 'Transaction.TranID, '; theQuery += 'TransactionLine.ID AS TransLineID, '; theQuery += 'TransactionLine.Rate, '; theQuery += 'TransactionLine.NetAmount, '; theQuery += 'TransactionLine.Quantity, '; theQuery += 'Entity.AltName, '; theQuery += 'SUM( TransactionLine.Quantity ) '; theQuery += 'OVER ( '; theQuery += 'ORDER BY '; theQuery += 'Transaction.TranDate, '; theQuery += 'Transaction.ID, '; theQuery += 'TransactionLine.ID '; theQuery += 'RANGE UNBOUNDED PRECEDING '; theQuery += ') Qty_Balance '; theQuery += 'FROM '; theQuery += 'Item '; theQuery += 'INNER JOIN TransactionLine ON '; theQuery += '( TransactionLine.Item = Item.ID ) '; theQuery += 'INNER JOIN Transaction ON '; theQuery += '( Transaction.ID = TransactionLine.Transaction ) '; theQuery += 'LEFT OUTER JOIN Entity ON '; theQuery += '( Entity.ID = Transaction.Entity ) '; theQuery += 'WHERE '; theQuery += '( Item.ItemID = \'' + context.request.parameters.custpage_field_itemid + '\' ) '; theQuery += 'AND ( TransactionLine.IsInventoryAffecting = \'T\' ) '; theQuery += 'AND ( Transaction.Voided = \'F\' ) '; theQuery += 'ORDER BY '; theQuery += 'Transaction.TranDate, '; theQuery += 'Transaction.ID, '; theQuery += 'TransactionLine.ID '; theQuery += ') '; theQuery += 'WHERE '; theQuery += '( TranDate <= TO_DATE( \'' + context.request.parameters.custpage_field_date + '\', \'MM/DD/YYYY\' ) ) '; theQuery += 'ORDER BY '; theQuery += 'TranDate DESC, TransactionID DESC, TransLineID DESC '; theQuery += ') '; theQuery += 'WHERE ( ROWNUM <= ' + historyRows + ' ) '; try { // Run the query. var queryResults = query.runSuiteQL( { query: theQuery } ); // Get the mapped results. var records = queryResults.asMappedResults(); // If records were returned... if ( records.length > 0 ) { // Create a sublist for the results. var resultsSublist = form.addSublist( { id : 'results_sublist', label : 'Balance History', type : serverWidget.SublistType.LIST } ); // Get the column names. var columnNames = Object.keys( records[0] ); // Loop over the column names... for ( i = 0; i < columnNames.length; i++ ) { // Add the column to the sublist as a field. resultsSublist.addField( { id: 'custpage_results_sublist_col_' + i, type: serverWidget.FieldType.TEXT, label: columnNames[i] } ); } // Add the records to the sublist... for ( r = 0; r < records.length; r++ ) { // Get the record. var record = records[r]; // Loop over the columns... for ( c = 0; c < columnNames.length; c++ ) { // Get the column name. var column = columnNames[c]; // Get the column value. var value = record[column]; // If the column has a value... if ( value != null ) { // Get the value as a string. value = value.toString(); // If the value is too long to be displayed in the sublist... if ( value.length > 300 ) { // Truncate the value. value = value.substring( 0, 297 ) + '...'; } // Add the column value. resultsSublist.setSublistValue( { id : 'custpage_results_sublist_col_' + c, line : r, value : value } ); } } } // Add an inline HTML field so that JavaScript can be injected. var jsField = form.addField( { id: 'custpage_field_js', type: serverWidget.FieldType.INLINEHTML, label: 'Javascript' } ); // Add Javascript to make the first row bold, and add a tooltip. jsField.defaultValue = '<script>\r\n'; jsField.defaultValue += 'document.addEventListener(\'DOMContentLoaded\', function() {'; jsField.defaultValue += 'document.getElementById("results_sublistrow0").style["font-weight"]="bold";\r\n'; jsField.defaultValue += 'document.getElementById("results_sublistrow0").title="This is the balance as of ' + context.request.parameters.custpage_field_date + '.";\r\n'; jsField.defaultValue += '}, false);'; jsField.defaultValue += '</script>'; } else { // Add an "Error" field. var errorField = form.addField( { id: 'custpage_field_error', type: serverWidget.FieldType.TEXT, label: 'Error' } ); errorField.defaultValue = 'No history found for: ' + context.request.parameters.custpage_field_itemid; // Add an inline HTML field so that JavaScript can be injected. var jsField = form.addField( { id: 'custpage_field_js', type: serverWidget.FieldType.INLINEHTML, label: 'Javascript' } ); // Add Javascript to make the error field red. jsField.defaultValue = '<script>\r\n'; jsField.defaultValue += 'document.addEventListener(\'DOMContentLoaded\', function() {'; jsField.defaultValue += 'document.getElementById("custpage_field_error").style.background="red";\r\n'; jsField.defaultValue += 'document.getElementById("custpage_field_error").style.color="white";\r\n'; jsField.defaultValue += '}, false);'; jsField.defaultValue += '</script>'; } } catch( e ) { var errorField = form.addField( { id: 'custpage_field_error', type: serverWidget.FieldType.LONGTEXT, label: 'Error' } ); errorField.defaultValue = e.message; } }
449
[{"tag": "EMAIL", "value": "timdietrich@me.com", "start": 639, "end": 657}]
true
1
/** * @NApiVersion 2.x * @NScriptType Suitelet * @NModuleScope Public */ /* ------------------------------------------------------------------------------------------ Script Information ------------------------------------------------------------------------------------------ Name: Inventory Balance Utility ID: _inventory_history Description A utility for looking up the ending balance of an item for a specified day. ------------------------------------------------------------------------------------------ Developer(s) ------------------------------------------------------------------------------------------ Tim Dietrich β€’ envkt@example.com β€’ https://timdietrich.me ------------------------------------------------------------------------------------------ History ------------------------------------------------------------------------------------------ 20201105 - Tim Dietrich β€’ Initial version. */ var log, query, serverWidget, historyRows = 100; define( [ 'N/log', 'N/query', 'N/ui/serverWidget' ], main ); function main( logModule, queryModule, serverWidgetModule ) { // Set module references. log = logModule; query= queryModule; serverWidget = serverWidgetModule; return { onRequest: function( context ) { // Create a form. var form = serverWidget.createForm( { title: 'Inventory Balance History', hideNavBar: false } ); // Add a submit button. form.addSubmitButton( { label: 'Get History' } ); // Add an "Item ID" field. var itemField = form.addField( { id: 'custpage_field_itemid', type: serverWidget.FieldType.TEXT, label: 'Item Name / Number' } ); // Add a "Date" field. var dateField = form.addField( { id: 'custpage_field_date', type: serverWidget.FieldType.DATE, label: 'Show Ending Balance For Date' } ); // Make both fields mandatory. itemField.isMandatory = true; dateField.isMandatory = true; // If the form has been submitted... if ( context.request.method == 'POST' ) { // Set defaults for the item and date field values. itemField.defaultValue = context.request.parameters.custpage_field_itemid; dateField.defaultValue = context.request.parameters.custpage_field_date; // Process the form. formProcess( context, form ); } // Display the form. context.response.writePage( form ); } } } function formProcess( context, form ) { var theQuery = ''; theQuery += 'SELECT '; theQuery += 'TranDate AS Date, '; theQuery += 'Type, '; theQuery += '\'<a href="/app/accounting/transactions/transaction.nl?id=\' || TransactionID || \'" target="_new">\' || TranID || \'</a>\' AS TransID, '; theQuery += 'AltName, '; theQuery += '( Qty_Balance - Quantity ) AS Beginning_Balance, '; theQuery += 'Quantity, '; theQuery += 'Qty_Balance AS Ending_Balance '; theQuery += 'FROM ( '; theQuery += 'SELECT * FROM ( '; theQuery += 'SELECT '; theQuery += 'TransactionLine.Transaction AS TransactionID, '; theQuery += 'Transaction.TranDate, '; theQuery += 'Transaction.Type, '; theQuery += 'Transaction.TranID, '; theQuery += 'TransactionLine.ID AS TransLineID, '; theQuery += 'TransactionLine.Rate, '; theQuery += 'TransactionLine.NetAmount, '; theQuery += 'TransactionLine.Quantity, '; theQuery += 'Entity.AltName, '; theQuery += 'SUM( TransactionLine.Quantity ) '; theQuery += 'OVER ( '; theQuery += 'ORDER BY '; theQuery += 'Transaction.TranDate, '; theQuery += 'Transaction.ID, '; theQuery += 'TransactionLine.ID '; theQuery += 'RANGE UNBOUNDED PRECEDING '; theQuery += ') Qty_Balance '; theQuery += 'FROM '; theQuery += 'Item '; theQuery += 'INNER JOIN TransactionLine ON '; theQuery += '( TransactionLine.Item = Item.ID ) '; theQuery += 'INNER JOIN Transaction ON '; theQuery += '( Transaction.ID = TransactionLine.Transaction ) '; theQuery += 'LEFT OUTER JOIN Entity ON '; theQuery += '( Entity.ID = Transaction.Entity ) '; theQuery += 'WHERE '; theQuery += '( Item.ItemID = \'' + context.request.parameters.custpage_field_itemid + '\' ) '; theQuery += 'AND ( TransactionLine.IsInventoryAffecting = \'T\' ) '; theQuery += 'AND ( Transaction.Voided = \'F\' ) '; theQuery += 'ORDER BY '; theQuery += 'Transaction.TranDate, '; theQuery += 'Transaction.ID, '; theQuery += 'TransactionLine.ID '; theQuery += ') '; theQuery += 'WHERE '; theQuery += '( TranDate <= TO_DATE( \'' + context.request.parameters.custpage_field_date + '\', \'MM/DD/YYYY\' ) ) '; theQuery += 'ORDER BY '; theQuery += 'TranDate DESC, TransactionID DESC, TransLineID DESC '; theQuery += ') '; theQuery += 'WHERE ( ROWNUM <= ' + historyRows + ' ) '; try { // Run the query. var queryResults = query.runSuiteQL( { query: theQuery } ); // Get the mapped results. var records = queryResults.asMappedResults(); // If records were returned... if ( records.length > 0 ) { // Create a sublist for the results. var resultsSublist = form.addSublist( { id : 'results_sublist', label : 'Balance History', type : serverWidget.SublistType.LIST } ); // Get the column names. var columnNames = Object.keys( records[0] ); // Loop over the column names... for ( i = 0; i < columnNames.length; i++ ) { // Add the column to the sublist as a field. resultsSublist.addField( { id: 'custpage_results_sublist_col_' + i, type: serverWidget.FieldType.TEXT, label: columnNames[i] } ); } // Add the records to the sublist... for ( r = 0; r < records.length; r++ ) { // Get the record. var record = records[r]; // Loop over the columns... for ( c = 0; c < columnNames.length; c++ ) { // Get the column name. var column = columnNames[c]; // Get the column value. var value = record[column]; // If the column has a value... if ( value != null ) { // Get the value as a string. value = value.toString(); // If the value is too long to be displayed in the sublist... if ( value.length > 300 ) { // Truncate the value. value = value.substring( 0, 297 ) + '...'; } // Add the column value. resultsSublist.setSublistValue( { id : 'custpage_results_sublist_col_' + c, line : r, value : value } ); } } } // Add an inline HTML field so that JavaScript can be injected. var jsField = form.addField( { id: 'custpage_field_js', type: serverWidget.FieldType.INLINEHTML, label: 'Javascript' } ); // Add Javascript to make the first row bold, and add a tooltip. jsField.defaultValue = '<script>\r\n'; jsField.defaultValue += 'document.addEventListener(\'DOMContentLoaded\', function() {'; jsField.defaultValue += 'document.getElementById("results_sublistrow0").style["font-weight"]="bold";\r\n'; jsField.defaultValue += 'document.getElementById("results_sublistrow0").title="This is the balance as of ' + context.request.parameters.custpage_field_date + '.";\r\n'; jsField.defaultValue += '}, false);'; jsField.defaultValue += '</script>'; } else { // Add an "Error" field. var errorField = form.addField( { id: 'custpage_field_error', type: serverWidget.FieldType.TEXT, label: 'Error' } ); errorField.defaultValue = 'No history found for: ' + context.request.parameters.custpage_field_itemid; // Add an inline HTML field so that JavaScript can be injected. var jsField = form.addField( { id: 'custpage_field_js', type: serverWidget.FieldType.INLINEHTML, label: 'Javascript' } ); // Add Javascript to make the error field red. jsField.defaultValue = '<script>\r\n'; jsField.defaultValue += 'document.addEventListener(\'DOMContentLoaded\', function() {'; jsField.defaultValue += 'document.getElementById("custpage_field_error").style.background="red";\r\n'; jsField.defaultValue += 'document.getElementById("custpage_field_error").style.color="white";\r\n'; jsField.defaultValue += '}, false);'; jsField.defaultValue += '</script>'; } } catch( e ) { var errorField = form.addField( { id: 'custpage_field_error', type: serverWidget.FieldType.LONGTEXT, label: 'Error' } ); errorField.defaultValue = e.message; } }
true
/** * @NApiVersion 2.x * @NScriptType Suitelet * @NModuleScope Public */ /* ------------------------------------------------------------------------------------------ Script Information ------------------------------------------------------------------------------------------ Name: Inventory Balance Utility ID: _inventory_history Description A utility for looking up the ending balance of an item for a specified day. ------------------------------------------------------------------------------------------ Developer(s) ------------------------------------------------------------------------------------------ Tim Dietrich β€’ PI:EMAIL:envkt@example.comEND_PI β€’ https://timdietrich.me ------------------------------------------------------------------------------------------ History ------------------------------------------------------------------------------------------ 20201105 - Tim Dietrich β€’ Initial version. */ var log, query, serverWidget, historyRows = 100; define( [ 'N/log', 'N/query', 'N/ui/serverWidget' ], main ); function main( logModule, queryModule, serverWidgetModule ) { // Set module references. log = logModule; query= queryModule; serverWidget = serverWidgetModule; return { onRequest: function( context ) { // Create a form. var form = serverWidget.createForm( { title: 'Inventory Balance History', hideNavBar: false } ); // Add a submit button. form.addSubmitButton( { label: 'Get History' } ); // Add an "Item ID" field. var itemField = form.addField( { id: 'custpage_field_itemid', type: serverWidget.FieldType.TEXT, label: 'Item Name / Number' } ); // Add a "Date" field. var dateField = form.addField( { id: 'custpage_field_date', type: serverWidget.FieldType.DATE, label: 'Show Ending Balance For Date' } ); // Make both fields mandatory. itemField.isMandatory = true; dateField.isMandatory = true; // If the form has been submitted... if ( context.request.method == 'POST' ) { // Set defaults for the item and date field values. itemField.defaultValue = context.request.parameters.custpage_field_itemid; dateField.defaultValue = context.request.parameters.custpage_field_date; // Process the form. formProcess( context, form ); } // Display the form. context.response.writePage( form ); } } } function formProcess( context, form ) { var theQuery = ''; theQuery += 'SELECT '; theQuery += 'TranDate AS Date, '; theQuery += 'Type, '; theQuery += '\'<a href="/app/accounting/transactions/transaction.nl?id=\' || TransactionID || \'" target="_new">\' || TranID || \'</a>\' AS TransID, '; theQuery += 'AltName, '; theQuery += '( Qty_Balance - Quantity ) AS Beginning_Balance, '; theQuery += 'Quantity, '; theQuery += 'Qty_Balance AS Ending_Balance '; theQuery += 'FROM ( '; theQuery += 'SELECT * FROM ( '; theQuery += 'SELECT '; theQuery += 'TransactionLine.Transaction AS TransactionID, '; theQuery += 'Transaction.TranDate, '; theQuery += 'Transaction.Type, '; theQuery += 'Transaction.TranID, '; theQuery += 'TransactionLine.ID AS TransLineID, '; theQuery += 'TransactionLine.Rate, '; theQuery += 'TransactionLine.NetAmount, '; theQuery += 'TransactionLine.Quantity, '; theQuery += 'Entity.AltName, '; theQuery += 'SUM( TransactionLine.Quantity ) '; theQuery += 'OVER ( '; theQuery += 'ORDER BY '; theQuery += 'Transaction.TranDate, '; theQuery += 'Transaction.ID, '; theQuery += 'TransactionLine.ID '; theQuery += 'RANGE UNBOUNDED PRECEDING '; theQuery += ') Qty_Balance '; theQuery += 'FROM '; theQuery += 'Item '; theQuery += 'INNER JOIN TransactionLine ON '; theQuery += '( TransactionLine.Item = Item.ID ) '; theQuery += 'INNER JOIN Transaction ON '; theQuery += '( Transaction.ID = TransactionLine.Transaction ) '; theQuery += 'LEFT OUTER JOIN Entity ON '; theQuery += '( Entity.ID = Transaction.Entity ) '; theQuery += 'WHERE '; theQuery += '( Item.ItemID = \'' + context.request.parameters.custpage_field_itemid + '\' ) '; theQuery += 'AND ( TransactionLine.IsInventoryAffecting = \'T\' ) '; theQuery += 'AND ( Transaction.Voided = \'F\' ) '; theQuery += 'ORDER BY '; theQuery += 'Transaction.TranDate, '; theQuery += 'Transaction.ID, '; theQuery += 'TransactionLine.ID '; theQuery += ') '; theQuery += 'WHERE '; theQuery += '( TranDate <= TO_DATE( \'' + context.request.parameters.custpage_field_date + '\', \'MM/DD/YYYY\' ) ) '; theQuery += 'ORDER BY '; theQuery += 'TranDate DESC, TransactionID DESC, TransLineID DESC '; theQuery += ') '; theQuery += 'WHERE ( ROWNUM <= ' + historyRows + ' ) '; try { // Run the query. var queryResults = query.runSuiteQL( { query: theQuery } ); // Get the mapped results. var records = queryResults.asMappedResults(); // If records were returned... if ( records.length > 0 ) { // Create a sublist for the results. var resultsSublist = form.addSublist( { id : 'results_sublist', label : 'Balance History', type : serverWidget.SublistType.LIST } ); // Get the column names. var columnNames = Object.keys( records[0] ); // Loop over the column names... for ( i = 0; i < columnNames.length; i++ ) { // Add the column to the sublist as a field. resultsSublist.addField( { id: 'custpage_results_sublist_col_' + i, type: serverWidget.FieldType.TEXT, label: columnNames[i] } ); } // Add the records to the sublist... for ( r = 0; r < records.length; r++ ) { // Get the record. var record = records[r]; // Loop over the columns... for ( c = 0; c < columnNames.length; c++ ) { // Get the column name. var column = columnNames[c]; // Get the column value. var value = record[column]; // If the column has a value... if ( value != null ) { // Get the value as a string. value = value.toString(); // If the value is too long to be displayed in the sublist... if ( value.length > 300 ) { // Truncate the value. value = value.substring( 0, 297 ) + '...'; } // Add the column value. resultsSublist.setSublistValue( { id : 'custpage_results_sublist_col_' + c, line : r, value : value } ); } } } // Add an inline HTML field so that JavaScript can be injected. var jsField = form.addField( { id: 'custpage_field_js', type: serverWidget.FieldType.INLINEHTML, label: 'Javascript' } ); // Add Javascript to make the first row bold, and add a tooltip. jsField.defaultValue = '<script>\r\n'; jsField.defaultValue += 'document.addEventListener(\'DOMContentLoaded\', function() {'; jsField.defaultValue += 'document.getElementById("results_sublistrow0").style["font-weight"]="bold";\r\n'; jsField.defaultValue += 'document.getElementById("results_sublistrow0").title="This is the balance as of ' + context.request.parameters.custpage_field_date + '.";\r\n'; jsField.defaultValue += '}, false);'; jsField.defaultValue += '</script>'; } else { // Add an "Error" field. var errorField = form.addField( { id: 'custpage_field_error', type: serverWidget.FieldType.TEXT, label: 'Error' } ); errorField.defaultValue = 'No history found for: ' + context.request.parameters.custpage_field_itemid; // Add an inline HTML field so that JavaScript can be injected. var jsField = form.addField( { id: 'custpage_field_js', type: serverWidget.FieldType.INLINEHTML, label: 'Javascript' } ); // Add Javascript to make the error field red. jsField.defaultValue = '<script>\r\n'; jsField.defaultValue += 'document.addEventListener(\'DOMContentLoaded\', function() {'; jsField.defaultValue += 'document.getElementById("custpage_field_error").style.background="red";\r\n'; jsField.defaultValue += 'document.getElementById("custpage_field_error").style.color="white";\r\n'; jsField.defaultValue += '}, false);'; jsField.defaultValue += '</script>'; } } catch( e ) { var errorField = form.addField( { id: 'custpage_field_error', type: serverWidget.FieldType.LONGTEXT, label: 'Error' } ); errorField.defaultValue = e.message; } }
/** * @NApiVersion 2.0 * @NScriptType Suitelet * * Module Description * * NSVersion Date Author * 2.00 2020-10-22 09:33:08 Anesu * * Description: Automation of Debt Collection Process * * @Last Modified by: Anesu * @Last Modified time: 2020-10-22 16:49:26 * */ define(['N/ui/serverWidget', 'N/email', 'N/runtime', 'N/search', 'N/record', 'N/http', 'N/log', 'N/redirect', 'N/task', 'N/format'], function(ui, email, runtime, search, record, http, log, redirect, task, format) { var zee = 0; var role = 0; var baseURL = 'https://1048144.app.netsuite.com'; if (runtime.EnvType == "SANDBOX") { baseURL = 'https://1048144-sb3.app.netsuite.com'; } role = runtime.getCurrentUser().role; if (role == 1000) { zee = runtime.getCurrentUser().id; } else if (role == 3) { //Administrator zee = 6; //test } else if (role == 1032) { // System Support zee = 425904; //test-AR } function onRequest(context) { if (context.request.method === 'GET') { var is_params = 'T'; type = context.request.parameters.type; log.debug({ title: 'User', details: runtime.getCurrentUser().id }) var form = ui.createForm({ title: 'Debt Collection' }); // Load jQuery var inlineHtml = '<script type="text/javascript" src="https://cdn.jsdelivr.net/jquery/latest/jquery.min.js"></script>'; inlineHtml += '<script src="https://code.jquery.com/jquery-1.12.4.min.js" integrity="sha384-nvAa0+6Qg9clwYCGGPpDQLVpLNn0fRaROjHqs13t4Ggj3Ez50XnGQqc/r8MhnRDZ" crossorigin="anonymous"></script>'; // Load Tooltip inlineHtml += '<script src="https://unpkg.com/@popperjs/core@2"></script>'; // Load Bootstrap inlineHtml += '<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/3.4.1/css/bootstrap.min.css" integrity="sha384-HSMxcRTRxnN+Bdg0JdbxYKrThecOKuH5zCYotlSAcp1+c8xmyTe9GYg1l9a69psu" crossorigin="anonymous">'; inlineHtml += '<script src="https://stackpath.bootstrapcdn.com/bootstrap/3.4.1/js/bootstrap.min.js" integrity="sha384-aJ21OjlMXNL5UyIl/XNwTMqvzeRMZH2w8c5cRVpzpU8Y5bApTppSuUkhZXN0VxHd" crossorigin="anonymous"></script>'; // Load DataTables inlineHtml += '<link rel="stylesheet" type="text/css" href="//cdn.datatables.net/1.10.21/css/jquery.dataTables.min.css">'; inlineHtml += '<script type="text/javascript" charset="utf8" src="//cdn.datatables.net/1.10.21/js/jquery.dataTables.min.js"></script>'; // Load Bootstrap-Select inlineHtml += '<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap-select@1.13.14/dist/css/bootstrap-select.min.css">'; inlineHtml += '<script src="https://cdn.jsdelivr.net/npm/bootstrap-select@1.13.14/dist/js/bootstrap-select.min.js"></script>'; // Load Netsuite stylesheet and script inlineHtml += '<link rel="stylesheet" href="https://1048144.app.netsuite.com/core/media/media.nl?id=2060796&c=1048144&h=9ee6accfd476c9cae718&_xt=.css"/>'; inlineHtml += '<script src="https://1048144.app.netsuite.com/core/media/media.nl?id=2060797&c=1048144&h=ef2cda20731d146b5e98&_xt=.js"></script>'; inlineHtml += '<link type="text/css" rel="stylesheet" href="https://1048144.app.netsuite.com/core/media/media.nl?id=2090583&c=1048144&h=a0ef6ac4e28f91203dfe&_xt=.css">'; inlineHtml += '<style>.mandatory{color:red;}</style>'; //Date Range Picker inlineHtml += '<script type="text/javascript" src="https://cdn.jsdelivr.net/momentjs/latest/moment.min.js"></script>' inlineHtml += '<script type="text/javascript" src="https://cdn.jsdelivr.net/npm/daterangepicker/daterangepicker.min.js"></script>' inlineHtml += '<link rel="stylesheet" type="text/css" href="https://cdn.jsdelivr.net/npm/daterangepicker/daterangepicker.css" />' inlineHtml += '<div class="a" style="width: 100%; background-color: #CFE0CE; padding: 20px; min-height: 100%; height: 100%;">'; // inlineHtml += '<h1 style="text-align: center; color: #103D39; display: inline-block; font-size: 22px; font-weight: bold; line-height: 33px; vertical-align: top; margin-bottom: 4px;">Consolidation Invoice</h1>'; inlineHtml += '<style>.nav > li.active > a, .nav > li.active > a:focus, .nav > li.active > a:hover { background-color: #379E8F; color: #fff }'; inlineHtml += '.nav > li > a, .nav > li > a:focus, .nav > li > a:hover { margin-left: 5px; margin-right: 5px; border: 2px solid #379E8F; color: #379E8F; }'; inlineHtml += '</style>'; // Popup Notes Section inlineHtml += '<div id="myModal" class="modal fade bs-example-modal-sm" tabindex="-1" role="dialog" aria-labelledby="mySmallModalLabel" aria-hidden="true"><div class="modal-dialog modal-sm" role="document" style="width :max-content"><div class="modal-content" style="width :max-content; max-width: 900px"><div class="modal-header"><button type="button" class="close" data-dismiss="modal" aria-label="Close"><span aria-hidden="true">&times;</span></button><h4 class="modal-title panel panel-info" id="exampleModalLabel">Notes Section</h4><br> </div><div class="modal-body"></div><div class="modal-footer"><button type="button" class="btn btn-default" data-dismiss="modal">Close</button></div></div></div></div>'; inlineHtml += '<div id="myModal2" class="modal fade bs-example-modal-sm" tabindex="-1" role="dialog" aria-labelledby="mySmallModalLabel" aria-hidden="true"><div class="modal-dialog modal-sm" role="document" style="width :max-content"><div class="modal-content" style="width :max-content; max-width: 900px"><div class="modal-header"><button type="button" class="close" data-dismiss="modal" aria-label="Close"><span aria-hidden="true">&times;</span></button><h4 class="modal-title panel panel-info" id="exampleModalLabel">Snooze Timers</h4><br> </div><div class="modal-body"></div><div class="modal-footer"><button type="button" class="btn btn-default" data-dismiss="modal">Close</button></div></div></div></div>'; inlineHtml += '<div id="myModal3" class="modal fade bs-example-modal-sm" tabindex="-1" role="dialog" aria-labelledby="mySmallModalLabel" aria-hidden="true"><div class="modal-dialog modal-sm" role="document" style="width :max-content"><div class="modal-content" style="width :max-content; max-width: 900px"><div class="modal-header"><button type="button" class="close" data-dismiss="modal" aria-label="Close"><span aria-hidden="true">&times;</span></button><h4 class="modal-title panel panel-info" id="exampleModalLabel">Assign Customer to Team Member</h4><br> </div><div class="modal-body"></div><div class="modal-footer"><button type="button" class="btn btn-default" data-dismiss="modal">Close</button></div></div></div></div>'; // Click for Instructions inlineHtml += '<button type="button" class="btn btn-sm btn-info instruction_button" data-toggle="collapse" data-target="#demo" style="background-color: #FBEA51; color: #103D39;">Click for Instructions</button><div id="demo" style="background-color: #cfeefc !important;border: 1px solid #417ed9;padding: 10px 10px 10px 20px;width:96%;position:absolute" class="collapse"><b><u>IMPORTANT INSTRUCTIONS:</u></b>'; inlineHtml += '<ul><li><input type="button" class="btn-xs" style="background-color: #fff; color: black;" disabled value="Submit Search" /> - <ul><li>Click "Submit Search" to load Datatable using current parameters</li></ul></li>' inlineHtml += '<li>Functionalities available on the Debt Collections Table:<ul><li><b>Sort</b><ul><li>Click on column headers to sort collections invoices according to the values in the columns. This is default to "Days Overdue".</li><li>Hold "Shift" and click another column to sort according to multiple columns.</li></ul></li><li><b>Search</b><ul><li>You can search for specific Customer or Invoice by typing into the "Search" field</li></ul></li></ul></li>'; inlineHtml += '<li>Table Filters:<ul><li><b>Matching MAAP Allocation</b><ul><li><button type="button" class="btn-xs btn-success " disabled><span class="glyphicon glyphicon-plus"></span></button> - Click to apply MAAP Allocation filters search filters on table. ONLY click once. </li><li><button type="button" class="btn-xs btn-danger " disabled><span class="glyphicon glyphicon-minus"></span></button> - Click to remove MAAP Allocation search filter from table. This is set default to "Days Overdue".</li></ul></li> <li><b>MP Ticket Column</b><ul><button type="button" class="btn-xs btn-success" disabled><span class="glyphicon glyphicon-plus"></span></button> - Click to apply MAAP Allocation filters search filters on table. ONLY click once. </li></ul></li></ul></li><li>Clickable Actions Available Per Invoice in DataTable:</li>'; inlineHtml += '<ul><li><button type="button" class="btn-xs" disabled><span class="span_class glyphicon glyphicon-pencil"></span></button> - Click to open Notes Section for Selected Invoice. (Notes Section is seperate from User Notes)</li>'; inlineHtml += '<li><button type="button" class="btn-xs btn-secondary" disabled><span class="glyphicon glyphicon-eye-open"></span></button> - Click to Set Invoice has "Viewed" by a member of the Finance Team.</li>'; inlineHtml += '<li><button type="button" class="btn-xs btn-info" disabled><span class="glyphicon glyphicon-time"></span></button> - Click to view Snooze Timers</li><li><button type="button" class="timer-1day form=control btn-xs btn-info" disabled><span class="span_class">1 Day</span></button> - Click to select Snooze duration of invoice from Debt Collections Page.</li>'; inlineHtml += '</li></ul></div>'; // Service Debtors Email inlineHtml += '<button type="button" id="redirect_serv_debt" class="btn btn-sm btn-info" style="background-color: #FBEA51; color: #103D39; margin-left: 20px;">Service Debtors Email Notifcation</button>' inlineHtml += loadingSection(); inlineHtml += rangeSelection(); inlineHtml += dateFilterSection(); inlineHtml += tableFilter(); inlineHtml += dataTable(); inlineHtml += '</div></div>' form.addButton({ id: 'submit', label: 'Submit Search' }); form.addField({ id: 'preview_table', label: 'inlinehtml', type: 'inlinehtml' }).updateLayoutType({ layoutType: ui.FieldLayoutType.STARTROW }).defaultValue = inlineHtml; form.clientScriptFileId = 4497169; //4241008 context.response.writePage(form); } else {} } /** * The table that will display the differents invoices linked to the franchisee and the time period. * @return {String} inlineQty */ function dataTable() { var inlineQty = '<style>table#debt_preview {font-size: 12px;text-align: center;border: none;}.dataTables_wrapper {font-size: 14px;}table#debt_preview th{text-align: center;} .bolded{font-weight: bold;}</style>'; inlineQty += '<table id="debt_preview" class="table table-responsive table-striped customer tablesorter hide" style="width: 100%;">'; inlineQty += '<thead style="color: white; background-color: #379E8F;">'; inlineQty += '<tr class="text-center">'; inlineQty += '</tr>'; inlineQty += '</thead>'; inlineQty += '<tbody id="result_debt" class="result-debt"></tbody>'; inlineQty += '</table>'; return inlineQty; } /** * The date input fields to filter the invoices. * Even if the parameters `date_from` and `date_to` are defined, they can't be initiated in the HTML code. * They are initiated with jQuery in the `pageInit()` function. * @return {String} `inlineQty` */ function tableFilter() { var inlineQty = '<div id="table_filter_section" class="table_filters_section hide">'; inlineQty += '<div class="form-group container">'; inlineQty += '<div class="row">'; inlineQty += '<div class="col-xs-12 heading1"><h4><span class="label label-default col-xs-12" style="background-color: #379E8F; color: white;">TABLE FILTERS</span></h4></div>'; inlineQty += '</div>'; inlineQty += '</div>'; inlineQty += '<div class="form-group container table_filter_section">'; inlineQty += '<div class="row">'; inlineQty += '<div class="col-sm-4 showMPTicket_box">'; inlineQty += '<div class="input-group">'; inlineQty += '<span class="input-group-addon" id="showMPTicket_box" >Show/Hide | MP Ticket Column</span>'; inlineQty += '<button type="button" id="showMPTicket_box" class="toggle-mp-ticket btn btn-success" style="background-color: #379E8F;"><span class="span_class glyphicon glyphicon-plus"></span></button>' inlineQty += '</div></div>'; // // MAAP Allocation inlineQty += '<div class="col-sm-5 showMAAP_box">'; inlineQty += '<div class="input-group">'; inlineQty += '<span class="input-group-addon" id="showMAAP_box">Show/Hide | Matching MAAP Allocation</span>'; inlineQty += '<button type="button" id="showMAAP_box" class="toggle-maap btn btn-success" style="background-color: #379E8F;"><span class="span_class glyphicon glyphicon-plus"></span></button>' inlineQty += '<button type="button" id="showMAAP_box" class="toggle-maap-danger btn btn-danger"><span class="span_class glyphicon glyphicon-minus"></span></button>' inlineQty += '</div></div>'; //Toggle MAAP Bank Account inlineQty += '<div class="col-sm-auto showMAAP_bank">'; inlineQty += '<div class="input-group">'; inlineQty += '<span class="input-group-addon" id="showMAAP_bank">Show/Hide | MAAP Bank Account</span>'; inlineQty += '<button type="button" id="showMAAP_bank" class="toggle-maap-bank btn btn-danger"><span class="span_class glyphicon glyphicon-minus"></span></button>' inlineQty += '</div></div>'; inlineQty += '</div></div>'; inlineQty += '<div class="form-group container table_filter_section2">'; inlineQty += '<div class="row">'; inlineQty += '<div class="col-xs-6 showCustStartDate">'; inlineQty += '<div class="input-group">'; inlineQty += '<span class="input-group-addon" id="showCustStartDate">Filter | Customer Start Date Column</span>'; inlineQty += '<input type="text" id="cust_Start_date" class="form-control" name="daterange" value="Please Select Filter Range"/>' // // inlineQty += '<button type="button" id="showCustStartDate" class="add-date-filter btn btn-success" style="background-color: #379E8F;"><span class="span_class glyphicon glyphicon-plus"></span></button>' // inlineQty += '<button type="button" id="showCustStartDate" class="remove-date-filter btn btn-danger"><span class="span_class glyphicon glyphicon-minus"></span></button>' inlineQty += '</div></div>'; inlineQty += '</div></div>'; inlineQty += '</div>'; return inlineQty; } /** * The header showing that the results are loading. * @returns {String} `inlineQty` */ function loadingSection() { var inlineQty = '<div id="loading_section" class="form-group container loading_section" style="text-align:center">'; inlineQty += '<div class="row">'; inlineQty += '<div class="col-xs-12 loading_div color--primary-1 page-header-text" style="margin-bottom: 20px; text-align: center; color: #379e8f; font-size: 40px">'; inlineQty += '<h1>Loading Preferences ...</h1>'; inlineQty += '</div></div></div>'; return inlineQty; } function rangeSelection() { var inlineQty = '<div class="form-group container range_filter_section_top">'; inlineQty += '<div class="row">'; inlineQty += '<div class="col-xs-12 heading1"><h4><span class="label label-default col-xs-12" style="background-color: #379E8F; color: white;">RANGE FILTER</span></h4></div>'; inlineQty += '</div>'; inlineQty += '</div>'; inlineQty += '<div class="form-group container range_filter_section">'; inlineQty += '<div class="row">'; inlineQty += '<div class="col-xs-12 range_section">'; inlineQty += '<div class="input-group">'; inlineQty += '<span class="input-group-addon" id="range_filter_text">Range Selection</span>'; inlineQty += '<select multiple id="range_filter" class="form-control">'; inlineQty += '<option value="1">MPEX Products</option>'; inlineQty += '<option value="2" selected>0 - 59 Days</option>'; inlineQty += '<option value="3">60+ Days</option>'; inlineQty += '<option value="0">- None -</option>'; inlineQty += '</select>'; inlineQty += '</div></div>'; inlineQty += '</div></div>'; inlineQty += '<div class="form-group container team_filter_section">'; inlineQty += '<div class="row">'; inlineQty += '<div class="col-xs-12 team_section">'; inlineQty += '<div class="input-group">'; inlineQty += '<span class="input-group-addon" id="team_filter_text">Team Member Selection</span>'; inlineQty += '<select id="team_filter" class="form-control">'; inlineQty += '<option value="" selected>- None -</option>'; inlineQty += '<option value="691582">Turkan</option>'; // inlineQty += '<option value="1403209">Jasmeet</option>'; // inlineQty += '<option value="429450">Jori</option>'; // inlineQty += '<option value="1626909">Azalea</option>'; inlineQty += '<option value="1672674">Madillon</option>'; inlineQty += '<option value="755585">Yassine</option>'; inlineQty += '<option value="924435">Test</option>'; // inlineQty += '<option value=""></option>'; inlineQty += '</select>'; inlineQty += '</div></div>'; inlineQty += '</div></div>'; inlineQty += '</div></div>'; return inlineQty; } /** * The date input fields to filter the invoices. * Even if the parameters `date_from` and `date_to` are defined, they can't be initiated in the HTML code. * They are initiated with jQuery in the `pageInit()` function. * @return {String} `inlineQty` */ function dateFilterSection() { var inlineQty = '<div class="form-group container date_filter_section">'; inlineQty += '<div class="row">'; inlineQty += '<div class="col-xs-12 heading1"><h4><span class="label label-default col-xs-12" style="background-color: #379E8F; color: white;">DATE FILTER</span></h4></div>'; inlineQty += '</div>'; inlineQty += '</div>'; inlineQty += periodDropdownSection(); inlineQty += '<div class="form-group container date_filter_section">'; inlineQty += '<div class="row">'; // Date from field inlineQty += '<div class="col-xs-6 date_from">'; inlineQty += '<div class="input-group">'; inlineQty += '<span class="input-group-addon" id="date_from_text">From</span>'; inlineQty += '<input id="date_from" class="form-control date_from" type="date"/>'; inlineQty += '</div></div>'; // Date to field inlineQty += '<div class="col-xs-6 date_to">'; inlineQty += '<div class="input-group">'; inlineQty += '<span class="input-group-addon" id="date_to_text">To</span>'; inlineQty += '<input id="date_to" class="form-control date_to" type="date">'; inlineQty += '</div></div></div></div>'; return inlineQty; } /** * The period dropdown field. * @param {String} date_from * @param {String} date_to * @return {String} `inlineQty` */ function periodDropdownSection(date_from, date_to) { var selected_option = (isNullorEmpty(date_from) && isNullorEmpty(date_to)) ? 'selected' : ''; var inlineQty = '<div class="form-group container period_dropdown_section">'; inlineQty += '<div class="row">'; // Period dropdown field inlineQty += '<div class="col-xs-12 period_dropdown_div">'; inlineQty += '<div class="input-group">'; inlineQty += '<span class="input-group-addon" id="period_dropdown_text">Period</span>'; inlineQty += '<select id="period_dropdown" class="form-control">'; inlineQty += '<option ' + selected_option + '></option>'; inlineQty += '<option value="this_week">This Week</option>'; inlineQty += '<option value="last_week">Last Week</option>'; inlineQty += '<option value="this_month">This Month</option>'; inlineQty += '<option value="last_month">Last Month</option>'; inlineQty += '<option value="full_year">Full Year (1 Jan -)</option>'; inlineQty += '<option value="financial_year">Financial Year (1 Jul -)</option>'; inlineQty += '</select>'; inlineQty += '</div></div></div></div>'; return inlineQty; } /** * Used to pass the values of `date_from` and `date_to` between the scripts and to Netsuite for the records and the search. * @param {String} date_iso "2020-06-01" * @returns {String} date_netsuite "1/6/2020" */ function dateISOToNetsuite(date_iso) { var date_netsuite = ''; if (!isNullorEmpty(date_iso)) { var date_utc = new Date(date_iso); // var date_netsuite = nlapiDateToString(date_utc); var date_netsuite = format.format({ value: date_utc, type: format.Type.DATE }); } return date_netsuite; } function isNullorEmpty(val) { if (val == '' || val == null) { return true; } else { return false; } } return { onRequest: onRequest } } );
352
[{"tag": "KEY", "value": "sha384-nvAa0+6Qg9clwYCGGPpDQLVpLNn0fRaROjHqs13t4Ggj3Ez50XnGQqc/r8MhnRDZ", "start": 1825, "end": 1896}, {"tag": "KEY", "value": "sha384-aJ21OjlMXNL5UyIl/XNwTMqvzeRMZH2w8c5cRVpzpU8Y5bApTppSuUkhZXN0VxHd", "start": 2471, "end": 2542}, {"tag": "KEY", "value": "sha384-HSMxcRTRxnN+Bdg0JdbxYKrThecOKuH5zCYotlSAcp1+c8xmyTe9GYg1l9a69psu", "start": 2243, "end": 2314}]
true
3
/** * @NApiVersion 2.0 * @NScriptType Suitelet * * Module Description * * NSVersion Date Author * 2.00 2020-10-22 09:33:08 Anesu * * Description: Automation of Debt Collection Process * * @Last Modified by: Anesu * @Last Modified time: 2020-10-22 16:49:26 * */ define(['N/ui/serverWidget', 'N/email', 'N/runtime', 'N/search', 'N/record', 'N/http', 'N/log', 'N/redirect', 'N/task', 'N/format'], function(ui, email, runtime, search, record, http, log, redirect, task, format) { var zee = 0; var role = 0; var baseURL = 'https://1048144.app.netsuite.com'; if (runtime.EnvType == "SANDBOX") { baseURL = 'https://1048144-sb3.app.netsuite.com'; } role = runtime.getCurrentUser().role; if (role == 1000) { zee = runtime.getCurrentUser().id; } else if (role == 3) { //Administrator zee = 6; //test } else if (role == 1032) { // System Support zee = 425904; //test-AR } function onRequest(context) { if (context.request.method === 'GET') { var is_params = 'T'; type = context.request.parameters.type; log.debug({ title: 'User', details: runtime.getCurrentUser().id }) var form = ui.createForm({ title: 'Debt Collection' }); // Load jQuery var inlineHtml = '<script type="text/javascript" src="https://cdn.jsdelivr.net/jquery/latest/jquery.min.js"></script>'; inlineHtml += '<script src="https://code.jquery.com/jquery-1.12.4.min.js" integrity="949d1u22cbffbrarjh182eig55721odj" crossorigin="anonymous"></script>'; // Load Tooltip inlineHtml += '<script src="https://unpkg.com/@popperjs/core@2"></script>'; // Load Bootstrap inlineHtml += '<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/3.4.1/css/bootstrap.min.css" integrity="caf86f4uutaoxfysmf7anj01xl6sv3ps" crossorigin="anonymous">'; inlineHtml += '<script src="https://stackpath.bootstrapcdn.com/bootstrap/3.4.1/js/bootstrap.min.js" integrity="949d1u22cbffbrarjh182eig55721odj" crossorigin="anonymous"></script>'; // Load DataTables inlineHtml += '<link rel="stylesheet" type="text/css" href="//cdn.datatables.net/1.10.21/css/jquery.dataTables.min.css">'; inlineHtml += '<script type="text/javascript" charset="utf8" src="//cdn.datatables.net/1.10.21/js/jquery.dataTables.min.js"></script>'; // Load Bootstrap-Select inlineHtml += '<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap-select@1.13.14/dist/css/bootstrap-select.min.css">'; inlineHtml += '<script src="https://cdn.jsdelivr.net/npm/bootstrap-select@1.13.14/dist/js/bootstrap-select.min.js"></script>'; // Load Netsuite stylesheet and script inlineHtml += '<link rel="stylesheet" href="https://1048144.app.netsuite.com/core/media/media.nl?id=2060796&c=1048144&h=9ee6accfd476c9cae718&_xt=.css"/>'; inlineHtml += '<script src="https://1048144.app.netsuite.com/core/media/media.nl?id=2060797&c=1048144&h=ef2cda20731d146b5e98&_xt=.js"></script>'; inlineHtml += '<link type="text/css" rel="stylesheet" href="https://1048144.app.netsuite.com/core/media/media.nl?id=2090583&c=1048144&h=a0ef6ac4e28f91203dfe&_xt=.css">'; inlineHtml += '<style>.mandatory{color:red;}</style>'; //Date Range Picker inlineHtml += '<script type="text/javascript" src="https://cdn.jsdelivr.net/momentjs/latest/moment.min.js"></script>' inlineHtml += '<script type="text/javascript" src="https://cdn.jsdelivr.net/npm/daterangepicker/daterangepicker.min.js"></script>' inlineHtml += '<link rel="stylesheet" type="text/css" href="https://cdn.jsdelivr.net/npm/daterangepicker/daterangepicker.css" />' inlineHtml += '<div class="a" style="width: 100%; background-color: #CFE0CE; padding: 20px; min-height: 100%; height: 100%;">'; // inlineHtml += '<h1 style="text-align: center; color: #103D39; display: inline-block; font-size: 22px; font-weight: bold; line-height: 33px; vertical-align: top; margin-bottom: 4px;">Consolidation Invoice</h1>'; inlineHtml += '<style>.nav > li.active > a, .nav > li.active > a:focus, .nav > li.active > a:hover { background-color: #379E8F; color: #fff }'; inlineHtml += '.nav > li > a, .nav > li > a:focus, .nav > li > a:hover { margin-left: 5px; margin-right: 5px; border: 2px solid #379E8F; color: #379E8F; }'; inlineHtml += '</style>'; // Popup Notes Section inlineHtml += '<div id="myModal" class="modal fade bs-example-modal-sm" tabindex="-1" role="dialog" aria-labelledby="mySmallModalLabel" aria-hidden="true"><div class="modal-dialog modal-sm" role="document" style="width :max-content"><div class="modal-content" style="width :max-content; max-width: 900px"><div class="modal-header"><button type="button" class="close" data-dismiss="modal" aria-label="Close"><span aria-hidden="true">&times;</span></button><h4 class="modal-title panel panel-info" id="exampleModalLabel">Notes Section</h4><br> </div><div class="modal-body"></div><div class="modal-footer"><button type="button" class="btn btn-default" data-dismiss="modal">Close</button></div></div></div></div>'; inlineHtml += '<div id="myModal2" class="modal fade bs-example-modal-sm" tabindex="-1" role="dialog" aria-labelledby="mySmallModalLabel" aria-hidden="true"><div class="modal-dialog modal-sm" role="document" style="width :max-content"><div class="modal-content" style="width :max-content; max-width: 900px"><div class="modal-header"><button type="button" class="close" data-dismiss="modal" aria-label="Close"><span aria-hidden="true">&times;</span></button><h4 class="modal-title panel panel-info" id="exampleModalLabel">Snooze Timers</h4><br> </div><div class="modal-body"></div><div class="modal-footer"><button type="button" class="btn btn-default" data-dismiss="modal">Close</button></div></div></div></div>'; inlineHtml += '<div id="myModal3" class="modal fade bs-example-modal-sm" tabindex="-1" role="dialog" aria-labelledby="mySmallModalLabel" aria-hidden="true"><div class="modal-dialog modal-sm" role="document" style="width :max-content"><div class="modal-content" style="width :max-content; max-width: 900px"><div class="modal-header"><button type="button" class="close" data-dismiss="modal" aria-label="Close"><span aria-hidden="true">&times;</span></button><h4 class="modal-title panel panel-info" id="exampleModalLabel">Assign Customer to Team Member</h4><br> </div><div class="modal-body"></div><div class="modal-footer"><button type="button" class="btn btn-default" data-dismiss="modal">Close</button></div></div></div></div>'; // Click for Instructions inlineHtml += '<button type="button" class="btn btn-sm btn-info instruction_button" data-toggle="collapse" data-target="#demo" style="background-color: #FBEA51; color: #103D39;">Click for Instructions</button><div id="demo" style="background-color: #cfeefc !important;border: 1px solid #417ed9;padding: 10px 10px 10px 20px;width:96%;position:absolute" class="collapse"><b><u>IMPORTANT INSTRUCTIONS:</u></b>'; inlineHtml += '<ul><li><input type="button" class="btn-xs" style="background-color: #fff; color: black;" disabled value="Submit Search" /> - <ul><li>Click "Submit Search" to load Datatable using current parameters</li></ul></li>' inlineHtml += '<li>Functionalities available on the Debt Collections Table:<ul><li><b>Sort</b><ul><li>Click on column headers to sort collections invoices according to the values in the columns. This is default to "Days Overdue".</li><li>Hold "Shift" and click another column to sort according to multiple columns.</li></ul></li><li><b>Search</b><ul><li>You can search for specific Customer or Invoice by typing into the "Search" field</li></ul></li></ul></li>'; inlineHtml += '<li>Table Filters:<ul><li><b>Matching MAAP Allocation</b><ul><li><button type="button" class="btn-xs btn-success " disabled><span class="glyphicon glyphicon-plus"></span></button> - Click to apply MAAP Allocation filters search filters on table. ONLY click once. </li><li><button type="button" class="btn-xs btn-danger " disabled><span class="glyphicon glyphicon-minus"></span></button> - Click to remove MAAP Allocation search filter from table. This is set default to "Days Overdue".</li></ul></li> <li><b>MP Ticket Column</b><ul><button type="button" class="btn-xs btn-success" disabled><span class="glyphicon glyphicon-plus"></span></button> - Click to apply MAAP Allocation filters search filters on table. ONLY click once. </li></ul></li></ul></li><li>Clickable Actions Available Per Invoice in DataTable:</li>'; inlineHtml += '<ul><li><button type="button" class="btn-xs" disabled><span class="span_class glyphicon glyphicon-pencil"></span></button> - Click to open Notes Section for Selected Invoice. (Notes Section is seperate from User Notes)</li>'; inlineHtml += '<li><button type="button" class="btn-xs btn-secondary" disabled><span class="glyphicon glyphicon-eye-open"></span></button> - Click to Set Invoice has "Viewed" by a member of the Finance Team.</li>'; inlineHtml += '<li><button type="button" class="btn-xs btn-info" disabled><span class="glyphicon glyphicon-time"></span></button> - Click to view Snooze Timers</li><li><button type="button" class="timer-1day form=control btn-xs btn-info" disabled><span class="span_class">1 Day</span></button> - Click to select Snooze duration of invoice from Debt Collections Page.</li>'; inlineHtml += '</li></ul></div>'; // Service Debtors Email inlineHtml += '<button type="button" id="redirect_serv_debt" class="btn btn-sm btn-info" style="background-color: #FBEA51; color: #103D39; margin-left: 20px;">Service Debtors Email Notifcation</button>' inlineHtml += loadingSection(); inlineHtml += rangeSelection(); inlineHtml += dateFilterSection(); inlineHtml += tableFilter(); inlineHtml += dataTable(); inlineHtml += '</div></div>' form.addButton({ id: 'submit', label: 'Submit Search' }); form.addField({ id: 'preview_table', label: 'inlinehtml', type: 'inlinehtml' }).updateLayoutType({ layoutType: ui.FieldLayoutType.STARTROW }).defaultValue = inlineHtml; form.clientScriptFileId = 4497169; //4241008 context.response.writePage(form); } else {} } /** * The table that will display the differents invoices linked to the franchisee and the time period. * @return {String} inlineQty */ function dataTable() { var inlineQty = '<style>table#debt_preview {font-size: 12px;text-align: center;border: none;}.dataTables_wrapper {font-size: 14px;}table#debt_preview th{text-align: center;} .bolded{font-weight: bold;}</style>'; inlineQty += '<table id="debt_preview" class="table table-responsive table-striped customer tablesorter hide" style="width: 100%;">'; inlineQty += '<thead style="color: white; background-color: #379E8F;">'; inlineQty += '<tr class="text-center">'; inlineQty += '</tr>'; inlineQty += '</thead>'; inlineQty += '<tbody id="result_debt" class="result-debt"></tbody>'; inlineQty += '</table>'; return inlineQty; } /** * The date input fields to filter the invoices. * Even if the parameters `date_from` and `date_to` are defined, they can't be initiated in the HTML code. * They are initiated with jQuery in the `pageInit()` function. * @return {String} `inlineQty` */ function tableFilter() { var inlineQty = '<div id="table_filter_section" class="table_filters_section hide">'; inlineQty += '<div class="form-group container">'; inlineQty += '<div class="row">'; inlineQty += '<div class="col-xs-12 heading1"><h4><span class="label label-default col-xs-12" style="background-color: #379E8F; color: white;">TABLE FILTERS</span></h4></div>'; inlineQty += '</div>'; inlineQty += '</div>'; inlineQty += '<div class="form-group container table_filter_section">'; inlineQty += '<div class="row">'; inlineQty += '<div class="col-sm-4 showMPTicket_box">'; inlineQty += '<div class="input-group">'; inlineQty += '<span class="input-group-addon" id="showMPTicket_box" >Show/Hide | MP Ticket Column</span>'; inlineQty += '<button type="button" id="showMPTicket_box" class="toggle-mp-ticket btn btn-success" style="background-color: #379E8F;"><span class="span_class glyphicon glyphicon-plus"></span></button>' inlineQty += '</div></div>'; // // MAAP Allocation inlineQty += '<div class="col-sm-5 showMAAP_box">'; inlineQty += '<div class="input-group">'; inlineQty += '<span class="input-group-addon" id="showMAAP_box">Show/Hide | Matching MAAP Allocation</span>'; inlineQty += '<button type="button" id="showMAAP_box" class="toggle-maap btn btn-success" style="background-color: #379E8F;"><span class="span_class glyphicon glyphicon-plus"></span></button>' inlineQty += '<button type="button" id="showMAAP_box" class="toggle-maap-danger btn btn-danger"><span class="span_class glyphicon glyphicon-minus"></span></button>' inlineQty += '</div></div>'; //Toggle MAAP Bank Account inlineQty += '<div class="col-sm-auto showMAAP_bank">'; inlineQty += '<div class="input-group">'; inlineQty += '<span class="input-group-addon" id="showMAAP_bank">Show/Hide | MAAP Bank Account</span>'; inlineQty += '<button type="button" id="showMAAP_bank" class="toggle-maap-bank btn btn-danger"><span class="span_class glyphicon glyphicon-minus"></span></button>' inlineQty += '</div></div>'; inlineQty += '</div></div>'; inlineQty += '<div class="form-group container table_filter_section2">'; inlineQty += '<div class="row">'; inlineQty += '<div class="col-xs-6 showCustStartDate">'; inlineQty += '<div class="input-group">'; inlineQty += '<span class="input-group-addon" id="showCustStartDate">Filter | Customer Start Date Column</span>'; inlineQty += '<input type="text" id="cust_Start_date" class="form-control" name="daterange" value="Please Select Filter Range"/>' // // inlineQty += '<button type="button" id="showCustStartDate" class="add-date-filter btn btn-success" style="background-color: #379E8F;"><span class="span_class glyphicon glyphicon-plus"></span></button>' // inlineQty += '<button type="button" id="showCustStartDate" class="remove-date-filter btn btn-danger"><span class="span_class glyphicon glyphicon-minus"></span></button>' inlineQty += '</div></div>'; inlineQty += '</div></div>'; inlineQty += '</div>'; return inlineQty; } /** * The header showing that the results are loading. * @returns {String} `inlineQty` */ function loadingSection() { var inlineQty = '<div id="loading_section" class="form-group container loading_section" style="text-align:center">'; inlineQty += '<div class="row">'; inlineQty += '<div class="col-xs-12 loading_div color--primary-1 page-header-text" style="margin-bottom: 20px; text-align: center; color: #379e8f; font-size: 40px">'; inlineQty += '<h1>Loading Preferences ...</h1>'; inlineQty += '</div></div></div>'; return inlineQty; } function rangeSelection() { var inlineQty = '<div class="form-group container range_filter_section_top">'; inlineQty += '<div class="row">'; inlineQty += '<div class="col-xs-12 heading1"><h4><span class="label label-default col-xs-12" style="background-color: #379E8F; color: white;">RANGE FILTER</span></h4></div>'; inlineQty += '</div>'; inlineQty += '</div>'; inlineQty += '<div class="form-group container range_filter_section">'; inlineQty += '<div class="row">'; inlineQty += '<div class="col-xs-12 range_section">'; inlineQty += '<div class="input-group">'; inlineQty += '<span class="input-group-addon" id="range_filter_text">Range Selection</span>'; inlineQty += '<select multiple id="range_filter" class="form-control">'; inlineQty += '<option value="1">MPEX Products</option>'; inlineQty += '<option value="2" selected>0 - 59 Days</option>'; inlineQty += '<option value="3">60+ Days</option>'; inlineQty += '<option value="0">- None -</option>'; inlineQty += '</select>'; inlineQty += '</div></div>'; inlineQty += '</div></div>'; inlineQty += '<div class="form-group container team_filter_section">'; inlineQty += '<div class="row">'; inlineQty += '<div class="col-xs-12 team_section">'; inlineQty += '<div class="input-group">'; inlineQty += '<span class="input-group-addon" id="team_filter_text">Team Member Selection</span>'; inlineQty += '<select id="team_filter" class="form-control">'; inlineQty += '<option value="" selected>- None -</option>'; inlineQty += '<option value="691582">Turkan</option>'; // inlineQty += '<option value="1403209">Jasmeet</option>'; // inlineQty += '<option value="429450">Jori</option>'; // inlineQty += '<option value="1626909">Azalea</option>'; inlineQty += '<option value="1672674">Madillon</option>'; inlineQty += '<option value="755585">Yassine</option>'; inlineQty += '<option value="924435">Test</option>'; // inlineQty += '<option value=""></option>'; inlineQty += '</select>'; inlineQty += '</div></div>'; inlineQty += '</div></div>'; inlineQty += '</div></div>'; return inlineQty; } /** * The date input fields to filter the invoices. * Even if the parameters `date_from` and `date_to` are defined, they can't be initiated in the HTML code. * They are initiated with jQuery in the `pageInit()` function. * @return {String} `inlineQty` */ function dateFilterSection() { var inlineQty = '<div class="form-group container date_filter_section">'; inlineQty += '<div class="row">'; inlineQty += '<div class="col-xs-12 heading1"><h4><span class="label label-default col-xs-12" style="background-color: #379E8F; color: white;">DATE FILTER</span></h4></div>'; inlineQty += '</div>'; inlineQty += '</div>'; inlineQty += periodDropdownSection(); inlineQty += '<div class="form-group container date_filter_section">'; inlineQty += '<div class="row">'; // Date from field inlineQty += '<div class="col-xs-6 date_from">'; inlineQty += '<div class="input-group">'; inlineQty += '<span class="input-group-addon" id="date_from_text">From</span>'; inlineQty += '<input id="date_from" class="form-control date_from" type="date"/>'; inlineQty += '</div></div>'; // Date to field inlineQty += '<div class="col-xs-6 date_to">'; inlineQty += '<div class="input-group">'; inlineQty += '<span class="input-group-addon" id="date_to_text">To</span>'; inlineQty += '<input id="date_to" class="form-control date_to" type="date">'; inlineQty += '</div></div></div></div>'; return inlineQty; } /** * The period dropdown field. * @param {String} date_from * @param {String} date_to * @return {String} `inlineQty` */ function periodDropdownSection(date_from, date_to) { var selected_option = (isNullorEmpty(date_from) && isNullorEmpty(date_to)) ? 'selected' : ''; var inlineQty = '<div class="form-group container period_dropdown_section">'; inlineQty += '<div class="row">'; // Period dropdown field inlineQty += '<div class="col-xs-12 period_dropdown_div">'; inlineQty += '<div class="input-group">'; inlineQty += '<span class="input-group-addon" id="period_dropdown_text">Period</span>'; inlineQty += '<select id="period_dropdown" class="form-control">'; inlineQty += '<option ' + selected_option + '></option>'; inlineQty += '<option value="this_week">This Week</option>'; inlineQty += '<option value="last_week">Last Week</option>'; inlineQty += '<option value="this_month">This Month</option>'; inlineQty += '<option value="last_month">Last Month</option>'; inlineQty += '<option value="full_year">Full Year (1 Jan -)</option>'; inlineQty += '<option value="financial_year">Financial Year (1 Jul -)</option>'; inlineQty += '</select>'; inlineQty += '</div></div></div></div>'; return inlineQty; } /** * Used to pass the values of `date_from` and `date_to` between the scripts and to Netsuite for the records and the search. * @param {String} date_iso "2020-06-01" * @returns {String} date_netsuite "1/6/2020" */ function dateISOToNetsuite(date_iso) { var date_netsuite = ''; if (!isNullorEmpty(date_iso)) { var date_utc = new Date(date_iso); // var date_netsuite = nlapiDateToString(date_utc); var date_netsuite = format.format({ value: date_utc, type: format.Type.DATE }); } return date_netsuite; } function isNullorEmpty(val) { if (val == '' || val == null) { return true; } else { return false; } } return { onRequest: onRequest } } );
true
/** * @NApiVersion 2.0 * @NScriptType Suitelet * * Module Description * * NSVersion Date Author * 2.00 2020-10-22 09:33:08 Anesu * * Description: Automation of Debt Collection Process * * @Last Modified by: Anesu * @Last Modified time: 2020-10-22 16:49:26 * */ define(['N/ui/serverWidget', 'N/email', 'N/runtime', 'N/search', 'N/record', 'N/http', 'N/log', 'N/redirect', 'N/task', 'N/format'], function(ui, email, runtime, search, record, http, log, redirect, task, format) { var zee = 0; var role = 0; var baseURL = 'https://1048144.app.netsuite.com'; if (runtime.EnvType == "SANDBOX") { baseURL = 'https://1048144-sb3.app.netsuite.com'; } role = runtime.getCurrentUser().role; if (role == 1000) { zee = runtime.getCurrentUser().id; } else if (role == 3) { //Administrator zee = 6; //test } else if (role == 1032) { // System Support zee = 425904; //test-AR } function onRequest(context) { if (context.request.method === 'GET') { var is_params = 'T'; type = context.request.parameters.type; log.debug({ title: 'User', details: runtime.getCurrentUser().id }) var form = ui.createForm({ title: 'Debt Collection' }); // Load jQuery var inlineHtml = '<script type="text/javascript" src="https://cdn.jsdelivr.net/jquery/latest/jquery.min.js"></script>'; inlineHtml += '<script src="https://code.jquery.com/jquery-1.12.4.min.js" integrity="PI:KEY:949d1u22cbffbrarjh182eig55721odjEND_PI" crossorigin="anonymous"></script>'; // Load Tooltip inlineHtml += '<script src="https://unpkg.com/@popperjs/core@2"></script>'; // Load Bootstrap inlineHtml += '<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/3.4.1/css/bootstrap.min.css" integrity="PI:KEY:caf86f4uutaoxfysmf7anj01xl6sv3psEND_PI" crossorigin="anonymous">'; inlineHtml += '<script src="https://stackpath.bootstrapcdn.com/bootstrap/3.4.1/js/bootstrap.min.js" integrity="PI:KEY:949d1u22cbffbrarjh182eig55721odjEND_PI" crossorigin="anonymous"></script>'; // Load DataTables inlineHtml += '<link rel="stylesheet" type="text/css" href="//cdn.datatables.net/1.10.21/css/jquery.dataTables.min.css">'; inlineHtml += '<script type="text/javascript" charset="utf8" src="//cdn.datatables.net/1.10.21/js/jquery.dataTables.min.js"></script>'; // Load Bootstrap-Select inlineHtml += '<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap-select@1.13.14/dist/css/bootstrap-select.min.css">'; inlineHtml += '<script src="https://cdn.jsdelivr.net/npm/bootstrap-select@1.13.14/dist/js/bootstrap-select.min.js"></script>'; // Load Netsuite stylesheet and script inlineHtml += '<link rel="stylesheet" href="https://1048144.app.netsuite.com/core/media/media.nl?id=2060796&c=1048144&h=9ee6accfd476c9cae718&_xt=.css"/>'; inlineHtml += '<script src="https://1048144.app.netsuite.com/core/media/media.nl?id=2060797&c=1048144&h=ef2cda20731d146b5e98&_xt=.js"></script>'; inlineHtml += '<link type="text/css" rel="stylesheet" href="https://1048144.app.netsuite.com/core/media/media.nl?id=2090583&c=1048144&h=a0ef6ac4e28f91203dfe&_xt=.css">'; inlineHtml += '<style>.mandatory{color:red;}</style>'; //Date Range Picker inlineHtml += '<script type="text/javascript" src="https://cdn.jsdelivr.net/momentjs/latest/moment.min.js"></script>' inlineHtml += '<script type="text/javascript" src="https://cdn.jsdelivr.net/npm/daterangepicker/daterangepicker.min.js"></script>' inlineHtml += '<link rel="stylesheet" type="text/css" href="https://cdn.jsdelivr.net/npm/daterangepicker/daterangepicker.css" />' inlineHtml += '<div class="a" style="width: 100%; background-color: #CFE0CE; padding: 20px; min-height: 100%; height: 100%;">'; // inlineHtml += '<h1 style="text-align: center; color: #103D39; display: inline-block; font-size: 22px; font-weight: bold; line-height: 33px; vertical-align: top; margin-bottom: 4px;">Consolidation Invoice</h1>'; inlineHtml += '<style>.nav > li.active > a, .nav > li.active > a:focus, .nav > li.active > a:hover { background-color: #379E8F; color: #fff }'; inlineHtml += '.nav > li > a, .nav > li > a:focus, .nav > li > a:hover { margin-left: 5px; margin-right: 5px; border: 2px solid #379E8F; color: #379E8F; }'; inlineHtml += '</style>'; // Popup Notes Section inlineHtml += '<div id="myModal" class="modal fade bs-example-modal-sm" tabindex="-1" role="dialog" aria-labelledby="mySmallModalLabel" aria-hidden="true"><div class="modal-dialog modal-sm" role="document" style="width :max-content"><div class="modal-content" style="width :max-content; max-width: 900px"><div class="modal-header"><button type="button" class="close" data-dismiss="modal" aria-label="Close"><span aria-hidden="true">&times;</span></button><h4 class="modal-title panel panel-info" id="exampleModalLabel">Notes Section</h4><br> </div><div class="modal-body"></div><div class="modal-footer"><button type="button" class="btn btn-default" data-dismiss="modal">Close</button></div></div></div></div>'; inlineHtml += '<div id="myModal2" class="modal fade bs-example-modal-sm" tabindex="-1" role="dialog" aria-labelledby="mySmallModalLabel" aria-hidden="true"><div class="modal-dialog modal-sm" role="document" style="width :max-content"><div class="modal-content" style="width :max-content; max-width: 900px"><div class="modal-header"><button type="button" class="close" data-dismiss="modal" aria-label="Close"><span aria-hidden="true">&times;</span></button><h4 class="modal-title panel panel-info" id="exampleModalLabel">Snooze Timers</h4><br> </div><div class="modal-body"></div><div class="modal-footer"><button type="button" class="btn btn-default" data-dismiss="modal">Close</button></div></div></div></div>'; inlineHtml += '<div id="myModal3" class="modal fade bs-example-modal-sm" tabindex="-1" role="dialog" aria-labelledby="mySmallModalLabel" aria-hidden="true"><div class="modal-dialog modal-sm" role="document" style="width :max-content"><div class="modal-content" style="width :max-content; max-width: 900px"><div class="modal-header"><button type="button" class="close" data-dismiss="modal" aria-label="Close"><span aria-hidden="true">&times;</span></button><h4 class="modal-title panel panel-info" id="exampleModalLabel">Assign Customer to Team Member</h4><br> </div><div class="modal-body"></div><div class="modal-footer"><button type="button" class="btn btn-default" data-dismiss="modal">Close</button></div></div></div></div>'; // Click for Instructions inlineHtml += '<button type="button" class="btn btn-sm btn-info instruction_button" data-toggle="collapse" data-target="#demo" style="background-color: #FBEA51; color: #103D39;">Click for Instructions</button><div id="demo" style="background-color: #cfeefc !important;border: 1px solid #417ed9;padding: 10px 10px 10px 20px;width:96%;position:absolute" class="collapse"><b><u>IMPORTANT INSTRUCTIONS:</u></b>'; inlineHtml += '<ul><li><input type="button" class="btn-xs" style="background-color: #fff; color: black;" disabled value="Submit Search" /> - <ul><li>Click "Submit Search" to load Datatable using current parameters</li></ul></li>' inlineHtml += '<li>Functionalities available on the Debt Collections Table:<ul><li><b>Sort</b><ul><li>Click on column headers to sort collections invoices according to the values in the columns. This is default to "Days Overdue".</li><li>Hold "Shift" and click another column to sort according to multiple columns.</li></ul></li><li><b>Search</b><ul><li>You can search for specific Customer or Invoice by typing into the "Search" field</li></ul></li></ul></li>'; inlineHtml += '<li>Table Filters:<ul><li><b>Matching MAAP Allocation</b><ul><li><button type="button" class="btn-xs btn-success " disabled><span class="glyphicon glyphicon-plus"></span></button> - Click to apply MAAP Allocation filters search filters on table. ONLY click once. </li><li><button type="button" class="btn-xs btn-danger " disabled><span class="glyphicon glyphicon-minus"></span></button> - Click to remove MAAP Allocation search filter from table. This is set default to "Days Overdue".</li></ul></li> <li><b>MP Ticket Column</b><ul><button type="button" class="btn-xs btn-success" disabled><span class="glyphicon glyphicon-plus"></span></button> - Click to apply MAAP Allocation filters search filters on table. ONLY click once. </li></ul></li></ul></li><li>Clickable Actions Available Per Invoice in DataTable:</li>'; inlineHtml += '<ul><li><button type="button" class="btn-xs" disabled><span class="span_class glyphicon glyphicon-pencil"></span></button> - Click to open Notes Section for Selected Invoice. (Notes Section is seperate from User Notes)</li>'; inlineHtml += '<li><button type="button" class="btn-xs btn-secondary" disabled><span class="glyphicon glyphicon-eye-open"></span></button> - Click to Set Invoice has "Viewed" by a member of the Finance Team.</li>'; inlineHtml += '<li><button type="button" class="btn-xs btn-info" disabled><span class="glyphicon glyphicon-time"></span></button> - Click to view Snooze Timers</li><li><button type="button" class="timer-1day form=control btn-xs btn-info" disabled><span class="span_class">1 Day</span></button> - Click to select Snooze duration of invoice from Debt Collections Page.</li>'; inlineHtml += '</li></ul></div>'; // Service Debtors Email inlineHtml += '<button type="button" id="redirect_serv_debt" class="btn btn-sm btn-info" style="background-color: #FBEA51; color: #103D39; margin-left: 20px;">Service Debtors Email Notifcation</button>' inlineHtml += loadingSection(); inlineHtml += rangeSelection(); inlineHtml += dateFilterSection(); inlineHtml += tableFilter(); inlineHtml += dataTable(); inlineHtml += '</div></div>' form.addButton({ id: 'submit', label: 'Submit Search' }); form.addField({ id: 'preview_table', label: 'inlinehtml', type: 'inlinehtml' }).updateLayoutType({ layoutType: ui.FieldLayoutType.STARTROW }).defaultValue = inlineHtml; form.clientScriptFileId = 4497169; //4241008 context.response.writePage(form); } else {} } /** * The table that will display the differents invoices linked to the franchisee and the time period. * @return {String} inlineQty */ function dataTable() { var inlineQty = '<style>table#debt_preview {font-size: 12px;text-align: center;border: none;}.dataTables_wrapper {font-size: 14px;}table#debt_preview th{text-align: center;} .bolded{font-weight: bold;}</style>'; inlineQty += '<table id="debt_preview" class="table table-responsive table-striped customer tablesorter hide" style="width: 100%;">'; inlineQty += '<thead style="color: white; background-color: #379E8F;">'; inlineQty += '<tr class="text-center">'; inlineQty += '</tr>'; inlineQty += '</thead>'; inlineQty += '<tbody id="result_debt" class="result-debt"></tbody>'; inlineQty += '</table>'; return inlineQty; } /** * The date input fields to filter the invoices. * Even if the parameters `date_from` and `date_to` are defined, they can't be initiated in the HTML code. * They are initiated with jQuery in the `pageInit()` function. * @return {String} `inlineQty` */ function tableFilter() { var inlineQty = '<div id="table_filter_section" class="table_filters_section hide">'; inlineQty += '<div class="form-group container">'; inlineQty += '<div class="row">'; inlineQty += '<div class="col-xs-12 heading1"><h4><span class="label label-default col-xs-12" style="background-color: #379E8F; color: white;">TABLE FILTERS</span></h4></div>'; inlineQty += '</div>'; inlineQty += '</div>'; inlineQty += '<div class="form-group container table_filter_section">'; inlineQty += '<div class="row">'; inlineQty += '<div class="col-sm-4 showMPTicket_box">'; inlineQty += '<div class="input-group">'; inlineQty += '<span class="input-group-addon" id="showMPTicket_box" >Show/Hide | MP Ticket Column</span>'; inlineQty += '<button type="button" id="showMPTicket_box" class="toggle-mp-ticket btn btn-success" style="background-color: #379E8F;"><span class="span_class glyphicon glyphicon-plus"></span></button>' inlineQty += '</div></div>'; // // MAAP Allocation inlineQty += '<div class="col-sm-5 showMAAP_box">'; inlineQty += '<div class="input-group">'; inlineQty += '<span class="input-group-addon" id="showMAAP_box">Show/Hide | Matching MAAP Allocation</span>'; inlineQty += '<button type="button" id="showMAAP_box" class="toggle-maap btn btn-success" style="background-color: #379E8F;"><span class="span_class glyphicon glyphicon-plus"></span></button>' inlineQty += '<button type="button" id="showMAAP_box" class="toggle-maap-danger btn btn-danger"><span class="span_class glyphicon glyphicon-minus"></span></button>' inlineQty += '</div></div>'; //Toggle MAAP Bank Account inlineQty += '<div class="col-sm-auto showMAAP_bank">'; inlineQty += '<div class="input-group">'; inlineQty += '<span class="input-group-addon" id="showMAAP_bank">Show/Hide | MAAP Bank Account</span>'; inlineQty += '<button type="button" id="showMAAP_bank" class="toggle-maap-bank btn btn-danger"><span class="span_class glyphicon glyphicon-minus"></span></button>' inlineQty += '</div></div>'; inlineQty += '</div></div>'; inlineQty += '<div class="form-group container table_filter_section2">'; inlineQty += '<div class="row">'; inlineQty += '<div class="col-xs-6 showCustStartDate">'; inlineQty += '<div class="input-group">'; inlineQty += '<span class="input-group-addon" id="showCustStartDate">Filter | Customer Start Date Column</span>'; inlineQty += '<input type="text" id="cust_Start_date" class="form-control" name="daterange" value="Please Select Filter Range"/>' // // inlineQty += '<button type="button" id="showCustStartDate" class="add-date-filter btn btn-success" style="background-color: #379E8F;"><span class="span_class glyphicon glyphicon-plus"></span></button>' // inlineQty += '<button type="button" id="showCustStartDate" class="remove-date-filter btn btn-danger"><span class="span_class glyphicon glyphicon-minus"></span></button>' inlineQty += '</div></div>'; inlineQty += '</div></div>'; inlineQty += '</div>'; return inlineQty; } /** * The header showing that the results are loading. * @returns {String} `inlineQty` */ function loadingSection() { var inlineQty = '<div id="loading_section" class="form-group container loading_section" style="text-align:center">'; inlineQty += '<div class="row">'; inlineQty += '<div class="col-xs-12 loading_div color--primary-1 page-header-text" style="margin-bottom: 20px; text-align: center; color: #379e8f; font-size: 40px">'; inlineQty += '<h1>Loading Preferences ...</h1>'; inlineQty += '</div></div></div>'; return inlineQty; } function rangeSelection() { var inlineQty = '<div class="form-group container range_filter_section_top">'; inlineQty += '<div class="row">'; inlineQty += '<div class="col-xs-12 heading1"><h4><span class="label label-default col-xs-12" style="background-color: #379E8F; color: white;">RANGE FILTER</span></h4></div>'; inlineQty += '</div>'; inlineQty += '</div>'; inlineQty += '<div class="form-group container range_filter_section">'; inlineQty += '<div class="row">'; inlineQty += '<div class="col-xs-12 range_section">'; inlineQty += '<div class="input-group">'; inlineQty += '<span class="input-group-addon" id="range_filter_text">Range Selection</span>'; inlineQty += '<select multiple id="range_filter" class="form-control">'; inlineQty += '<option value="1">MPEX Products</option>'; inlineQty += '<option value="2" selected>0 - 59 Days</option>'; inlineQty += '<option value="3">60+ Days</option>'; inlineQty += '<option value="0">- None -</option>'; inlineQty += '</select>'; inlineQty += '</div></div>'; inlineQty += '</div></div>'; inlineQty += '<div class="form-group container team_filter_section">'; inlineQty += '<div class="row">'; inlineQty += '<div class="col-xs-12 team_section">'; inlineQty += '<div class="input-group">'; inlineQty += '<span class="input-group-addon" id="team_filter_text">Team Member Selection</span>'; inlineQty += '<select id="team_filter" class="form-control">'; inlineQty += '<option value="" selected>- None -</option>'; inlineQty += '<option value="691582">Turkan</option>'; // inlineQty += '<option value="1403209">Jasmeet</option>'; // inlineQty += '<option value="429450">Jori</option>'; // inlineQty += '<option value="1626909">Azalea</option>'; inlineQty += '<option value="1672674">Madillon</option>'; inlineQty += '<option value="755585">Yassine</option>'; inlineQty += '<option value="924435">Test</option>'; // inlineQty += '<option value=""></option>'; inlineQty += '</select>'; inlineQty += '</div></div>'; inlineQty += '</div></div>'; inlineQty += '</div></div>'; return inlineQty; } /** * The date input fields to filter the invoices. * Even if the parameters `date_from` and `date_to` are defined, they can't be initiated in the HTML code. * They are initiated with jQuery in the `pageInit()` function. * @return {String} `inlineQty` */ function dateFilterSection() { var inlineQty = '<div class="form-group container date_filter_section">'; inlineQty += '<div class="row">'; inlineQty += '<div class="col-xs-12 heading1"><h4><span class="label label-default col-xs-12" style="background-color: #379E8F; color: white;">DATE FILTER</span></h4></div>'; inlineQty += '</div>'; inlineQty += '</div>'; inlineQty += periodDropdownSection(); inlineQty += '<div class="form-group container date_filter_section">'; inlineQty += '<div class="row">'; // Date from field inlineQty += '<div class="col-xs-6 date_from">'; inlineQty += '<div class="input-group">'; inlineQty += '<span class="input-group-addon" id="date_from_text">From</span>'; inlineQty += '<input id="date_from" class="form-control date_from" type="date"/>'; inlineQty += '</div></div>'; // Date to field inlineQty += '<div class="col-xs-6 date_to">'; inlineQty += '<div class="input-group">'; inlineQty += '<span class="input-group-addon" id="date_to_text">To</span>'; inlineQty += '<input id="date_to" class="form-control date_to" type="date">'; inlineQty += '</div></div></div></div>'; return inlineQty; } /** * The period dropdown field. * @param {String} date_from * @param {String} date_to * @return {String} `inlineQty` */ function periodDropdownSection(date_from, date_to) { var selected_option = (isNullorEmpty(date_from) && isNullorEmpty(date_to)) ? 'selected' : ''; var inlineQty = '<div class="form-group container period_dropdown_section">'; inlineQty += '<div class="row">'; // Period dropdown field inlineQty += '<div class="col-xs-12 period_dropdown_div">'; inlineQty += '<div class="input-group">'; inlineQty += '<span class="input-group-addon" id="period_dropdown_text">Period</span>'; inlineQty += '<select id="period_dropdown" class="form-control">'; inlineQty += '<option ' + selected_option + '></option>'; inlineQty += '<option value="this_week">This Week</option>'; inlineQty += '<option value="last_week">Last Week</option>'; inlineQty += '<option value="this_month">This Month</option>'; inlineQty += '<option value="last_month">Last Month</option>'; inlineQty += '<option value="full_year">Full Year (1 Jan -)</option>'; inlineQty += '<option value="financial_year">Financial Year (1 Jul -)</option>'; inlineQty += '</select>'; inlineQty += '</div></div></div></div>'; return inlineQty; } /** * Used to pass the values of `date_from` and `date_to` between the scripts and to Netsuite for the records and the search. * @param {String} date_iso "2020-06-01" * @returns {String} date_netsuite "1/6/2020" */ function dateISOToNetsuite(date_iso) { var date_netsuite = ''; if (!isNullorEmpty(date_iso)) { var date_utc = new Date(date_iso); // var date_netsuite = nlapiDateToString(date_utc); var date_netsuite = format.format({ value: date_utc, type: format.Type.DATE }); } return date_netsuite; } function isNullorEmpty(val) { if (val == '' || val == null) { return true; } else { return false; } } return { onRequest: onRequest } } );
/** * sh_sdf_cl_example.js * * Example file to be imported into the SDF Project for Lesson 4 of the SuiteHub SDF Course * * @module sh_sdf_cl_example * * @copyright 2023 Salto * @author Eric T Grubaugh <eric@stoic.software> * * @NApiVersion 2.1 * @NModuleScope Public * @NScriptType ClientScript */ define([], () => { /** * Display a thank you to the user * * @gov 0 * * @param {Object} context * * @see [Help:pageInit]{@link https://system.netsuite.com/app/help/helpcenter.nl?fid=section_4410597671.html} */ function pageInit(context) { console.info(` *** THANK YOU for watching Lesson 4 of the Intro to SDF Course on SUITEHUB!" ***`); } return /** @alias module:sh_sdf_cl_example.js */ { pageInit }; });
1,176
[{"tag": "EMAIL", "value": "eric@stoic.software", "start": 211, "end": 230}]
true
1
/** * sh_sdf_cl_example.js * * Example file to be imported into the SDF Project for Lesson 4 of the SuiteHub SDF Course * * @module sh_sdf_cl_example * * @copyright 2023 Salto * @author Eric T Grubaugh <lyhxr@example.com> * * @NApiVersion 2.1 * @NModuleScope Public * @NScriptType ClientScript */ define([], () => { /** * Display a thank you to the user * * @gov 0 * * @param {Object} context * * @see [Help:pageInit]{@link https://system.netsuite.com/app/help/helpcenter.nl?fid=section_4410597671.html} */ function pageInit(context) { console.info(` *** THANK YOU for watching Lesson 4 of the Intro to SDF Course on SUITEHUB!" ***`); } return /** @alias module:sh_sdf_cl_example.js */ { pageInit }; });
true
/** * sh_sdf_cl_example.js * * Example file to be imported into the SDF Project for Lesson 4 of the SuiteHub SDF Course * * @module sh_sdf_cl_example * * @copyright 2023 Salto * @author Eric T Grubaugh <PI:EMAIL:lyhxr@example.comEND_PI> * * @NApiVersion 2.1 * @NModuleScope Public * @NScriptType ClientScript */ define([], () => { /** * Display a thank you to the user * * @gov 0 * * @param {Object} context * * @see [Help:pageInit]{@link https://system.netsuite.com/app/help/helpcenter.nl?fid=section_4410597671.html} */ function pageInit(context) { console.info(` *** THANK YOU for watching Lesson 4 of the Intro to SDF Course on SUITEHUB!" ***`); } return /** @alias module:sh_sdf_cl_example.js */ { pageInit }; });
/** * Wipe out data for transactions * * @NApiVersion 2.0 * @NScriptType MassUpdateScript * @author trungpv <trung@lexor.com> */ define(['N/record'], function(record) { function deleteRecord(context) { const type = context.type; const id = context.id; try { log.debug({ title: '====> Deleting ' + type + ': ' + id, details: '====> Deleting ' + type + ': ' + id }); // Delete record record.delete({ type: type, id: id }); log.debug({ title: '[Done] Deleted ' + type + ': ' + id, details: '[Done] Deleted ' + type + ': ' + id }); } catch (error) { log.error({ title: '[Error] Delete ' + type + ': ' + id, details: error }); } } return { each: deleteRecord }; });
758
[{"tag": "EMAIL", "value": "trung@lexor.com", "start": 114, "end": 129}]
true
1
/** * Wipe out data for transactions * * @NApiVersion 2.0 * @NScriptType MassUpdateScript * @author trungpv <ychag@example.com> */ define(['N/record'], function(record) { function deleteRecord(context) { const type = context.type; const id = context.id; try { log.debug({ title: '====> Deleting ' + type + ': ' + id, details: '====> Deleting ' + type + ': ' + id }); // Delete record record.delete({ type: type, id: id }); log.debug({ title: '[Done] Deleted ' + type + ': ' + id, details: '[Done] Deleted ' + type + ': ' + id }); } catch (error) { log.error({ title: '[Error] Delete ' + type + ': ' + id, details: error }); } } return { each: deleteRecord }; });
true
/** * Wipe out data for transactions * * @NApiVersion 2.0 * @NScriptType MassUpdateScript * @author trungpv <PI:EMAIL:ychag@example.comEND_PI> */ define(['N/record'], function(record) { function deleteRecord(context) { const type = context.type; const id = context.id; try { log.debug({ title: '====> Deleting ' + type + ': ' + id, details: '====> Deleting ' + type + ': ' + id }); // Delete record record.delete({ type: type, id: id }); log.debug({ title: '[Done] Deleted ' + type + ': ' + id, details: '[Done] Deleted ' + type + ': ' + id }); } catch (error) { log.error({ title: '[Error] Delete ' + type + ': ' + id, details: error }); } } return { each: deleteRecord }; });
/** * jobs.invoice.net.js * @description Auto Invoice Net Term Jobs * @module clv/jobs/invoice/net * @NApiVersion 2.0 * @NScriptType Suitelet * @author Miquel Brazil <miquel@leprechaunpromotions.com> */ define([], function () { return {} });
754
[{"tag": "EMAIL", "value": "miquel@leprechaunpromotions.com", "start": 173, "end": 204}]
true
1
/** * jobs.invoice.net.js * @description Auto Invoice Net Term Jobs * @module clv/jobs/invoice/net * @NApiVersion 2.0 * @NScriptType Suitelet * @author Miquel Brazil <kenaa@example.com> */ define([], function () { return {} });
true
/** * jobs.invoice.net.js * @description Auto Invoice Net Term Jobs * @module clv/jobs/invoice/net * @NApiVersion 2.0 * @NScriptType Suitelet * @author Miquel Brazil <PI:EMAIL:kenaa@example.comEND_PI> */ define([], function () { return {} });
/** * @NApiVersion 2.1 * @NScriptType ScheduledScript */ define(['N/https', 'N/record', 'N/search', 'N/format', 'SuiteScripts/drt_custom_module/drt_mapid_cm'], /** * @param{https} https * @param{record} record * @param{search} search */ (https, record, search, format, drt_mapid_cm) => { /** * Defines the Scheduled script trigger point. * @param {Object} scriptContext * @param {string} scriptContext.type - Script execution context. Use values from the scriptContext.InvocationType enum. * @since 2015.2 */ const execute = (scriptContext) => { try { const customVars = drt_mapid_cm.getVariables(); // Buscar plantas que tienen SGC Local var locationsArray = search.create({ type: "customrecord_ptg_folio_sgc_local", filters: [], columns: [ search.createColumn({ name: "internalid", sort: search.Sort.ASC, label: "SGC Local ID" }), search.createColumn({ name: "custrecord_ptg_sgc_local_folio", label: "Folio" }), search.createColumn({ name: "internalid", join: "CUSTRECORD_PTG_SGC_LOCAL_PLANTA", label: "Internal ID" }), search.createColumn({ name: "custrecord_ptg_sgc_local_planta", label: "Planta" }), search.createColumn({ name: "custrecord_ptg_ip_sgc", join: "CUSTRECORD_PTG_SGC_LOCAL_PLANTA", label: "PTG - IP SGC" }) ] }); let respuesta = { success: false, message: '', data: [], errors: [] }; var searchResultCount = locationsArray.runPaged().count; let locationsArrayResult = locationsArray.run().getRange(0, searchResultCount); locationsArrayResult.forEach(location => { let sgc_id = location.getValue({ name: "internalid" }); let location_id = location.getValue({ name: "internalid", join: "CUSTRECORD_PTG_SGC_LOCAL_PLANTA" }); let folio = location.getValue({ name: "custrecord_ptg_sgc_local_folio" }); let planta = location.getValue({ name: "custrecord_ptg_sgc_local_planta" }); let ip = location.getValue({ name: "custrecord_ptg_ip_sgc", join: "CUSTRECORD_PTG_SGC_LOCAL_PLANTA" }); let no_autotanque = '4802'; let limit = ''; // let limit = 'LIMIT 1'; // let fecha = "2022-08-30"; let fecha = "2022-10-01"; let fechaFin = "2022-10-06"; log.audit('Entra en la ubicaciΓ³n', `SGC ID: ${sgc_id} - Location Id: ${location_id} - Folio: ${folio} - Nombre Planta: ${planta} - IP: ${ip}`); // Getting all services by folio + 100 let credentials = { host: ip, // IP del servidor user: 'root', password: 'root', db: 'sgc', }; // let credentials = { // host: '195.179.237.153', // IP del servidor // user: 'u570911546_sgc', // password: '7837336aA', // db: 'u570911546_sgc', // }; let data = { credentials, folio, fecha, fechaFin, no_autotanque, limit } // let url = `https://b03c-177-226-112-81.ngrok.io/api/getServicios`; let url = `https://i-ptg-sgclc-middleware-api-dtt-middleware.apps.mw-cluster.kt77.p1.openshiftapps.com/api/getServicios`; let headers = { 'content-type': 'application/json', 'accept': 'application/json' } let response = https.post({ url: url, headers: headers, body: JSON.stringify(data) }); log.audit({ title: "Data:", details: JSON.stringify(data) }); let responseBody = JSON.parse(response.body); let statusResponse = responseBody.status; let servicios = responseBody.servicios; let message = responseBody.message; let oportunidadesAfectadas = []; log.audit({ title: "Status Response: ", details: `Status: ${statusResponse} - Message: ${message}` }); log.audit({ title: "Servicios: ", details: JSON.stringify(servicios) }) if (servicios.length > 0) { servicios.forEach(servicio => { let embarque = servicio.cuenta.toString().slice(-2); let cuenta = servicio.cuenta.toString().slice(0, -2).padStart(10, '0'); log.audit({ title: "Cliente: ", details: `Cliente: ${cuenta} - Embarque: ${embarque} - Autotanque: ${servicio.no_autotanque}` }); // Crear nuevo record en servicios no conciliados try { // customrecord_ptg_registro_servicios_es_l // Antes de crear servicio no conciliado, buscar si ya existe uno con el mismo folio // var customrecord_ptg_registro_servicios_es_lSearchObj = search.create({ // type: "customrecord_ptg_registro_servicios_es_l", // filters: // [ // ["custrecord_ptg_folio_reg_sin_c_2", "is", servicio.id_servicio], // "AND", // ["custrecord_ptg_planta_sin_conciliar_2", "anyof", location_id], // ], // columns: // [ // "internalid", // "custrecord_ptg_planta_sin_conciliar_2", // search.createColumn({ // name: "custrecord_ptg_ruta_sin_conciliar_2", // sort: search.Sort.ASC // }), // "custrecord_ptg_folio_reg_sin_c_2" // ] // }); // var customrecord_ptg_registro_servicios_es_lSearchObjCount = customrecord_ptg_registro_servicios_es_lSearchObj.runPaged().count; // log.debug("ValidaciΓ³n de servicio_id como folio:", customrecord_ptg_registro_servicios_es_lSearchObjCount); // if (customrecord_ptg_registro_servicios_es_lSearchObjCount > 0) { // log.audit({ // title: `Servicio ${servicio.id_servicio} ya existe.`, // details: `Folio: ${servicio.id_servicio}` // }); // } else { // Buscar numero de ruta/id del equipo en base al id de vehiculo var customrecord_ptg_equiposSearchObj = search.create({ type: "customrecord_ptg_equipos", filters: [ ["custrecord_ptg_autotanquesgc_", "is", servicio.no_autotanque], ], columns: [ "internalid", search.createColumn({ name: "name", sort: search.Sort.ASC }), "custrecord_ptg_autotanquesgc_" ] }); var customrecord_ptg_equiposSearchObjCount = customrecord_ptg_equiposSearchObj.runPaged().count; log.debug("Buscando equipo por no. autotanque:", customrecord_ptg_equiposSearchObjCount); const PUBLICO_GENERAL = customVars.publicoGeneralId; let recServicioNoConciliado = record.create({ type: "customrecord_ptg_registro_servicios_es_l", // type: "customrecord_ptg_registros_sin_conciliar", }); recServicioNoConciliado.setValue({ fieldId: "custrecord_ptg_cliente_reg_serv_est_lin", value: PUBLICO_GENERAL }); // Litros recServicioNoConciliado.setValue({ fieldId: "custrecord_ptg_cantidad_reg_serv_est_lin", value: servicio.volumen }); // Precio sin iva let precioSinIva = servicio.precio_str / 1.16; let totalSinIva = (precioSinIva.toFixed(4) * servicio.volumen).toFixed(2); let iva = (totalSinIva * 0.16).toFixed(2); recServicioNoConciliado.setValue({ fieldId: "custrecord_ptg_precio_reg_serv_est_lin", value: precioSinIva.toFixed(4) }); recServicioNoConciliado.setValue({ fieldId: "custrecord_ptg_subtotal_registro_servs_e", value: totalSinIva }); recServicioNoConciliado.setValue({ fieldId: "custrecord_ptg_impuesto_reg_serv_est_lin", value: iva }); recServicioNoConciliado.setValue({ fieldId: "custrecord_ptg_total_reg_serv_est_lin", value: (servicio.precio * servicio.volumen).toFixed(4) }); recServicioNoConciliado.setValue({ fieldId: "custrecord_ptg_form_pago_reg_serv_est_li", value: "1" }); recServicioNoConciliado.setValue({ fieldId: "custrecord_ptg_cant_old_reg_serv_est_lin", value: servicio.volumen }); if (customrecord_ptg_equiposSearchObjCount > 0) { let customrecord_ptg_equiposSearchResult = customrecord_ptg_equiposSearchObj.run().getRange({ start: 0, end: customrecord_ptg_equiposSearchObjCount }); let equipoId = customrecord_ptg_equiposSearchResult[0].getValue({ name: "internalid" }); log.debug('equipoId', equipoId); // Ruta recServicioNoConciliado.setValue({ fieldId: "custrecord_ptg_ruta_sin_conciliar_2", value: equipoId }); } recServicioNoConciliado.setValue({ fieldId: "custrecord_ptg_planta_sin_conciliar_2", value: location_id }); recServicioNoConciliado.setValue({ fieldId: "custrecord_ptg_litros_sin_conciliar_2", value: servicio.volumen }); recServicioNoConciliado.setValue({ fieldId: "custrecord_ptg_folio_reg_sin_c_2", value: servicio.id_servicio }); let fechaInicio = new Date(servicio.ts1); let fechaInicioServicio = format.parse({ value: fechaInicio, type: format.Type.DATE }) let horaInicioServicio = format.parse({ value: fechaInicio.getHours() + ':' + fechaInicio.getMinutes() + ':' + fechaInicio.getSeconds(), type: format.Type.TIMEOFDAY }); recServicioNoConciliado.setValue({ fieldId: "custrecord_ptg_sgcloc_fecha_2_", value: fechaInicioServicio }); recServicioNoConciliado.setValue({ fieldId: "custrecord_ptg_sgcloc_hora_2_", value: horaInicioServicio }); recServicioNoConciliado.setValue({ fieldId: "custrecord_ptg_folio_aut_2_", value: servicio.id_servicio }); recServicioNoConciliado.setValue({ fieldId: "custrecord_ptg_folio_sgc_2_", value: servicio.id_servicio }); recServicioNoConciliado.setValue({ fieldId: "custrecord_ptg_fechainicio_sgc_2_", value: fechaInicioServicio }); recServicioNoConciliado.setValue({ fieldId: "custrecord_ptg_foliounidad_sgc_2_", value: servicio.id_servicio }); recServicioNoConciliado.setValue({ fieldId: "custrecord_ptg_tipo_sgc_2_", value: "2" }); let servicioNoConciliadoId = recServicioNoConciliado.save(); log.debug('Registro de servicio:', servicioNoConciliadoId); oportunidadesAfectadas.push(servicioNoConciliadoId); // Update the SGC Local Folio record let recSGC = record.load({ type: "customrecord_ptg_folio_sgc_local", id: sgc_id }); recSGC.setValue({ fieldId: "custrecord_ptg_sgc_local_folio", value: servicio.id_servicio }); let savedFolio = recSGC.save(); log.debug('Folio Actualizado:', servicio.id_servicio); // } } catch (error) { log.error({ title: "Error al crear la oportunidad", details: error }); } }); } respuesta.data.push({ location: planta, oportunidades: oportunidadesAfectadas }); }); respuesta.success = (respuesta.data.length > 0) ? true : false; respuesta.message = (respuesta.data.length > 0) ? 'Se crearon las oportunidades correctamente' : 'No se crearon las oportunidades'; log.audit({ title: "Proceso finalizado...", details: `Proceso terminado: ${JSON.stringify(respuesta)}` }) // return respuesta; } catch (error) { log.debug('Error scheduled:', error) } } return { execute } });
1,034
[{"tag": "IP_ADDRESS", "value": "195.179.237.153", "start": 3502, "end": 3517}]
true
1
/** * @NApiVersion 2.1 * @NScriptType ScheduledScript */ define(['N/https', 'N/record', 'N/search', 'N/format', 'SuiteScripts/drt_custom_module/drt_mapid_cm'], /** * @param{https} https * @param{record} record * @param{search} search */ (https, record, search, format, drt_mapid_cm) => { /** * Defines the Scheduled script trigger point. * @param {Object} scriptContext * @param {string} scriptContext.type - Script execution context. Use values from the scriptContext.InvocationType enum. * @since 2015.2 */ const execute = (scriptContext) => { try { const customVars = drt_mapid_cm.getVariables(); // Buscar plantas que tienen SGC Local var locationsArray = search.create({ type: "customrecord_ptg_folio_sgc_local", filters: [], columns: [ search.createColumn({ name: "internalid", sort: search.Sort.ASC, label: "SGC Local ID" }), search.createColumn({ name: "custrecord_ptg_sgc_local_folio", label: "Folio" }), search.createColumn({ name: "internalid", join: "CUSTRECORD_PTG_SGC_LOCAL_PLANTA", label: "Internal ID" }), search.createColumn({ name: "custrecord_ptg_sgc_local_planta", label: "Planta" }), search.createColumn({ name: "custrecord_ptg_ip_sgc", join: "CUSTRECORD_PTG_SGC_LOCAL_PLANTA", label: "PTG - IP SGC" }) ] }); let respuesta = { success: false, message: '', data: [], errors: [] }; var searchResultCount = locationsArray.runPaged().count; let locationsArrayResult = locationsArray.run().getRange(0, searchResultCount); locationsArrayResult.forEach(location => { let sgc_id = location.getValue({ name: "internalid" }); let location_id = location.getValue({ name: "internalid", join: "CUSTRECORD_PTG_SGC_LOCAL_PLANTA" }); let folio = location.getValue({ name: "custrecord_ptg_sgc_local_folio" }); let planta = location.getValue({ name: "custrecord_ptg_sgc_local_planta" }); let ip = location.getValue({ name: "custrecord_ptg_ip_sgc", join: "CUSTRECORD_PTG_SGC_LOCAL_PLANTA" }); let no_autotanque = '4802'; let limit = ''; // let limit = 'LIMIT 1'; // let fecha = "2022-08-30"; let fecha = "2022-10-01"; let fechaFin = "2022-10-06"; log.audit('Entra en la ubicaciΓ³n', `SGC ID: ${sgc_id} - Location Id: ${location_id} - Folio: ${folio} - Nombre Planta: ${planta} - IP: ${ip}`); // Getting all services by folio + 100 let credentials = { host: ip, // IP del servidor user: 'root', password: 'root', db: 'sgc', }; // let credentials = { // host: '172.16.58.3', // IP del servidor // user: 'u570911546_sgc', // password: '7837336aA', // db: 'u570911546_sgc', // }; let data = { credentials, folio, fecha, fechaFin, no_autotanque, limit } // let url = `https://b03c-177-226-112-81.ngrok.io/api/getServicios`; let url = `https://i-ptg-sgclc-middleware-api-dtt-middleware.apps.mw-cluster.kt77.p1.openshiftapps.com/api/getServicios`; let headers = { 'content-type': 'application/json', 'accept': 'application/json' } let response = https.post({ url: url, headers: headers, body: JSON.stringify(data) }); log.audit({ title: "Data:", details: JSON.stringify(data) }); let responseBody = JSON.parse(response.body); let statusResponse = responseBody.status; let servicios = responseBody.servicios; let message = responseBody.message; let oportunidadesAfectadas = []; log.audit({ title: "Status Response: ", details: `Status: ${statusResponse} - Message: ${message}` }); log.audit({ title: "Servicios: ", details: JSON.stringify(servicios) }) if (servicios.length > 0) { servicios.forEach(servicio => { let embarque = servicio.cuenta.toString().slice(-2); let cuenta = servicio.cuenta.toString().slice(0, -2).padStart(10, '0'); log.audit({ title: "Cliente: ", details: `Cliente: ${cuenta} - Embarque: ${embarque} - Autotanque: ${servicio.no_autotanque}` }); // Crear nuevo record en servicios no conciliados try { // customrecord_ptg_registro_servicios_es_l // Antes de crear servicio no conciliado, buscar si ya existe uno con el mismo folio // var customrecord_ptg_registro_servicios_es_lSearchObj = search.create({ // type: "customrecord_ptg_registro_servicios_es_l", // filters: // [ // ["custrecord_ptg_folio_reg_sin_c_2", "is", servicio.id_servicio], // "AND", // ["custrecord_ptg_planta_sin_conciliar_2", "anyof", location_id], // ], // columns: // [ // "internalid", // "custrecord_ptg_planta_sin_conciliar_2", // search.createColumn({ // name: "custrecord_ptg_ruta_sin_conciliar_2", // sort: search.Sort.ASC // }), // "custrecord_ptg_folio_reg_sin_c_2" // ] // }); // var customrecord_ptg_registro_servicios_es_lSearchObjCount = customrecord_ptg_registro_servicios_es_lSearchObj.runPaged().count; // log.debug("ValidaciΓ³n de servicio_id como folio:", customrecord_ptg_registro_servicios_es_lSearchObjCount); // if (customrecord_ptg_registro_servicios_es_lSearchObjCount > 0) { // log.audit({ // title: `Servicio ${servicio.id_servicio} ya existe.`, // details: `Folio: ${servicio.id_servicio}` // }); // } else { // Buscar numero de ruta/id del equipo en base al id de vehiculo var customrecord_ptg_equiposSearchObj = search.create({ type: "customrecord_ptg_equipos", filters: [ ["custrecord_ptg_autotanquesgc_", "is", servicio.no_autotanque], ], columns: [ "internalid", search.createColumn({ name: "name", sort: search.Sort.ASC }), "custrecord_ptg_autotanquesgc_" ] }); var customrecord_ptg_equiposSearchObjCount = customrecord_ptg_equiposSearchObj.runPaged().count; log.debug("Buscando equipo por no. autotanque:", customrecord_ptg_equiposSearchObjCount); const PUBLICO_GENERAL = customVars.publicoGeneralId; let recServicioNoConciliado = record.create({ type: "customrecord_ptg_registro_servicios_es_l", // type: "customrecord_ptg_registros_sin_conciliar", }); recServicioNoConciliado.setValue({ fieldId: "custrecord_ptg_cliente_reg_serv_est_lin", value: PUBLICO_GENERAL }); // Litros recServicioNoConciliado.setValue({ fieldId: "custrecord_ptg_cantidad_reg_serv_est_lin", value: servicio.volumen }); // Precio sin iva let precioSinIva = servicio.precio_str / 1.16; let totalSinIva = (precioSinIva.toFixed(4) * servicio.volumen).toFixed(2); let iva = (totalSinIva * 0.16).toFixed(2); recServicioNoConciliado.setValue({ fieldId: "custrecord_ptg_precio_reg_serv_est_lin", value: precioSinIva.toFixed(4) }); recServicioNoConciliado.setValue({ fieldId: "custrecord_ptg_subtotal_registro_servs_e", value: totalSinIva }); recServicioNoConciliado.setValue({ fieldId: "custrecord_ptg_impuesto_reg_serv_est_lin", value: iva }); recServicioNoConciliado.setValue({ fieldId: "custrecord_ptg_total_reg_serv_est_lin", value: (servicio.precio * servicio.volumen).toFixed(4) }); recServicioNoConciliado.setValue({ fieldId: "custrecord_ptg_form_pago_reg_serv_est_li", value: "1" }); recServicioNoConciliado.setValue({ fieldId: "custrecord_ptg_cant_old_reg_serv_est_lin", value: servicio.volumen }); if (customrecord_ptg_equiposSearchObjCount > 0) { let customrecord_ptg_equiposSearchResult = customrecord_ptg_equiposSearchObj.run().getRange({ start: 0, end: customrecord_ptg_equiposSearchObjCount }); let equipoId = customrecord_ptg_equiposSearchResult[0].getValue({ name: "internalid" }); log.debug('equipoId', equipoId); // Ruta recServicioNoConciliado.setValue({ fieldId: "custrecord_ptg_ruta_sin_conciliar_2", value: equipoId }); } recServicioNoConciliado.setValue({ fieldId: "custrecord_ptg_planta_sin_conciliar_2", value: location_id }); recServicioNoConciliado.setValue({ fieldId: "custrecord_ptg_litros_sin_conciliar_2", value: servicio.volumen }); recServicioNoConciliado.setValue({ fieldId: "custrecord_ptg_folio_reg_sin_c_2", value: servicio.id_servicio }); let fechaInicio = new Date(servicio.ts1); let fechaInicioServicio = format.parse({ value: fechaInicio, type: format.Type.DATE }) let horaInicioServicio = format.parse({ value: fechaInicio.getHours() + ':' + fechaInicio.getMinutes() + ':' + fechaInicio.getSeconds(), type: format.Type.TIMEOFDAY }); recServicioNoConciliado.setValue({ fieldId: "custrecord_ptg_sgcloc_fecha_2_", value: fechaInicioServicio }); recServicioNoConciliado.setValue({ fieldId: "custrecord_ptg_sgcloc_hora_2_", value: horaInicioServicio }); recServicioNoConciliado.setValue({ fieldId: "custrecord_ptg_folio_aut_2_", value: servicio.id_servicio }); recServicioNoConciliado.setValue({ fieldId: "custrecord_ptg_folio_sgc_2_", value: servicio.id_servicio }); recServicioNoConciliado.setValue({ fieldId: "custrecord_ptg_fechainicio_sgc_2_", value: fechaInicioServicio }); recServicioNoConciliado.setValue({ fieldId: "custrecord_ptg_foliounidad_sgc_2_", value: servicio.id_servicio }); recServicioNoConciliado.setValue({ fieldId: "custrecord_ptg_tipo_sgc_2_", value: "2" }); let servicioNoConciliadoId = recServicioNoConciliado.save(); log.debug('Registro de servicio:', servicioNoConciliadoId); oportunidadesAfectadas.push(servicioNoConciliadoId); // Update the SGC Local Folio record let recSGC = record.load({ type: "customrecord_ptg_folio_sgc_local", id: sgc_id }); recSGC.setValue({ fieldId: "custrecord_ptg_sgc_local_folio", value: servicio.id_servicio }); let savedFolio = recSGC.save(); log.debug('Folio Actualizado:', servicio.id_servicio); // } } catch (error) { log.error({ title: "Error al crear la oportunidad", details: error }); } }); } respuesta.data.push({ location: planta, oportunidades: oportunidadesAfectadas }); }); respuesta.success = (respuesta.data.length > 0) ? true : false; respuesta.message = (respuesta.data.length > 0) ? 'Se crearon las oportunidades correctamente' : 'No se crearon las oportunidades'; log.audit({ title: "Proceso finalizado...", details: `Proceso terminado: ${JSON.stringify(respuesta)}` }) // return respuesta; } catch (error) { log.debug('Error scheduled:', error) } } return { execute } });
true
/** * @NApiVersion 2.1 * @NScriptType ScheduledScript */ define(['N/https', 'N/record', 'N/search', 'N/format', 'SuiteScripts/drt_custom_module/drt_mapid_cm'], /** * @param{https} https * @param{record} record * @param{search} search */ (https, record, search, format, drt_mapid_cm) => { /** * Defines the Scheduled script trigger point. * @param {Object} scriptContext * @param {string} scriptContext.type - Script execution context. Use values from the scriptContext.InvocationType enum. * @since 2015.2 */ const execute = (scriptContext) => { try { const customVars = drt_mapid_cm.getVariables(); // Buscar plantas que tienen SGC Local var locationsArray = search.create({ type: "customrecord_ptg_folio_sgc_local", filters: [], columns: [ search.createColumn({ name: "internalid", sort: search.Sort.ASC, label: "SGC Local ID" }), search.createColumn({ name: "custrecord_ptg_sgc_local_folio", label: "Folio" }), search.createColumn({ name: "internalid", join: "CUSTRECORD_PTG_SGC_LOCAL_PLANTA", label: "Internal ID" }), search.createColumn({ name: "custrecord_ptg_sgc_local_planta", label: "Planta" }), search.createColumn({ name: "custrecord_ptg_ip_sgc", join: "CUSTRECORD_PTG_SGC_LOCAL_PLANTA", label: "PTG - IP SGC" }) ] }); let respuesta = { success: false, message: '', data: [], errors: [] }; var searchResultCount = locationsArray.runPaged().count; let locationsArrayResult = locationsArray.run().getRange(0, searchResultCount); locationsArrayResult.forEach(location => { let sgc_id = location.getValue({ name: "internalid" }); let location_id = location.getValue({ name: "internalid", join: "CUSTRECORD_PTG_SGC_LOCAL_PLANTA" }); let folio = location.getValue({ name: "custrecord_ptg_sgc_local_folio" }); let planta = location.getValue({ name: "custrecord_ptg_sgc_local_planta" }); let ip = location.getValue({ name: "custrecord_ptg_ip_sgc", join: "CUSTRECORD_PTG_SGC_LOCAL_PLANTA" }); let no_autotanque = '4802'; let limit = ''; // let limit = 'LIMIT 1'; // let fecha = "2022-08-30"; let fecha = "2022-10-01"; let fechaFin = "2022-10-06"; log.audit('Entra en la ubicaciΓ³n', `SGC ID: ${sgc_id} - Location Id: ${location_id} - Folio: ${folio} - Nombre Planta: ${planta} - IP: ${ip}`); // Getting all services by folio + 100 let credentials = { host: ip, // IP del servidor user: 'root', password: 'root', db: 'sgc', }; // let credentials = { // host: 'PI:IP_ADDRESS:172.16.58.3END_PI', // IP del servidor // user: 'u570911546_sgc', // password: '7837336aA', // db: 'u570911546_sgc', // }; let data = { credentials, folio, fecha, fechaFin, no_autotanque, limit } // let url = `https://b03c-177-226-112-81.ngrok.io/api/getServicios`; let url = `https://i-ptg-sgclc-middleware-api-dtt-middleware.apps.mw-cluster.kt77.p1.openshiftapps.com/api/getServicios`; let headers = { 'content-type': 'application/json', 'accept': 'application/json' } let response = https.post({ url: url, headers: headers, body: JSON.stringify(data) }); log.audit({ title: "Data:", details: JSON.stringify(data) }); let responseBody = JSON.parse(response.body); let statusResponse = responseBody.status; let servicios = responseBody.servicios; let message = responseBody.message; let oportunidadesAfectadas = []; log.audit({ title: "Status Response: ", details: `Status: ${statusResponse} - Message: ${message}` }); log.audit({ title: "Servicios: ", details: JSON.stringify(servicios) }) if (servicios.length > 0) { servicios.forEach(servicio => { let embarque = servicio.cuenta.toString().slice(-2); let cuenta = servicio.cuenta.toString().slice(0, -2).padStart(10, '0'); log.audit({ title: "Cliente: ", details: `Cliente: ${cuenta} - Embarque: ${embarque} - Autotanque: ${servicio.no_autotanque}` }); // Crear nuevo record en servicios no conciliados try { // customrecord_ptg_registro_servicios_es_l // Antes de crear servicio no conciliado, buscar si ya existe uno con el mismo folio // var customrecord_ptg_registro_servicios_es_lSearchObj = search.create({ // type: "customrecord_ptg_registro_servicios_es_l", // filters: // [ // ["custrecord_ptg_folio_reg_sin_c_2", "is", servicio.id_servicio], // "AND", // ["custrecord_ptg_planta_sin_conciliar_2", "anyof", location_id], // ], // columns: // [ // "internalid", // "custrecord_ptg_planta_sin_conciliar_2", // search.createColumn({ // name: "custrecord_ptg_ruta_sin_conciliar_2", // sort: search.Sort.ASC // }), // "custrecord_ptg_folio_reg_sin_c_2" // ] // }); // var customrecord_ptg_registro_servicios_es_lSearchObjCount = customrecord_ptg_registro_servicios_es_lSearchObj.runPaged().count; // log.debug("ValidaciΓ³n de servicio_id como folio:", customrecord_ptg_registro_servicios_es_lSearchObjCount); // if (customrecord_ptg_registro_servicios_es_lSearchObjCount > 0) { // log.audit({ // title: `Servicio ${servicio.id_servicio} ya existe.`, // details: `Folio: ${servicio.id_servicio}` // }); // } else { // Buscar numero de ruta/id del equipo en base al id de vehiculo var customrecord_ptg_equiposSearchObj = search.create({ type: "customrecord_ptg_equipos", filters: [ ["custrecord_ptg_autotanquesgc_", "is", servicio.no_autotanque], ], columns: [ "internalid", search.createColumn({ name: "name", sort: search.Sort.ASC }), "custrecord_ptg_autotanquesgc_" ] }); var customrecord_ptg_equiposSearchObjCount = customrecord_ptg_equiposSearchObj.runPaged().count; log.debug("Buscando equipo por no. autotanque:", customrecord_ptg_equiposSearchObjCount); const PUBLICO_GENERAL = customVars.publicoGeneralId; let recServicioNoConciliado = record.create({ type: "customrecord_ptg_registro_servicios_es_l", // type: "customrecord_ptg_registros_sin_conciliar", }); recServicioNoConciliado.setValue({ fieldId: "custrecord_ptg_cliente_reg_serv_est_lin", value: PUBLICO_GENERAL }); // Litros recServicioNoConciliado.setValue({ fieldId: "custrecord_ptg_cantidad_reg_serv_est_lin", value: servicio.volumen }); // Precio sin iva let precioSinIva = servicio.precio_str / 1.16; let totalSinIva = (precioSinIva.toFixed(4) * servicio.volumen).toFixed(2); let iva = (totalSinIva * 0.16).toFixed(2); recServicioNoConciliado.setValue({ fieldId: "custrecord_ptg_precio_reg_serv_est_lin", value: precioSinIva.toFixed(4) }); recServicioNoConciliado.setValue({ fieldId: "custrecord_ptg_subtotal_registro_servs_e", value: totalSinIva }); recServicioNoConciliado.setValue({ fieldId: "custrecord_ptg_impuesto_reg_serv_est_lin", value: iva }); recServicioNoConciliado.setValue({ fieldId: "custrecord_ptg_total_reg_serv_est_lin", value: (servicio.precio * servicio.volumen).toFixed(4) }); recServicioNoConciliado.setValue({ fieldId: "custrecord_ptg_form_pago_reg_serv_est_li", value: "1" }); recServicioNoConciliado.setValue({ fieldId: "custrecord_ptg_cant_old_reg_serv_est_lin", value: servicio.volumen }); if (customrecord_ptg_equiposSearchObjCount > 0) { let customrecord_ptg_equiposSearchResult = customrecord_ptg_equiposSearchObj.run().getRange({ start: 0, end: customrecord_ptg_equiposSearchObjCount }); let equipoId = customrecord_ptg_equiposSearchResult[0].getValue({ name: "internalid" }); log.debug('equipoId', equipoId); // Ruta recServicioNoConciliado.setValue({ fieldId: "custrecord_ptg_ruta_sin_conciliar_2", value: equipoId }); } recServicioNoConciliado.setValue({ fieldId: "custrecord_ptg_planta_sin_conciliar_2", value: location_id }); recServicioNoConciliado.setValue({ fieldId: "custrecord_ptg_litros_sin_conciliar_2", value: servicio.volumen }); recServicioNoConciliado.setValue({ fieldId: "custrecord_ptg_folio_reg_sin_c_2", value: servicio.id_servicio }); let fechaInicio = new Date(servicio.ts1); let fechaInicioServicio = format.parse({ value: fechaInicio, type: format.Type.DATE }) let horaInicioServicio = format.parse({ value: fechaInicio.getHours() + ':' + fechaInicio.getMinutes() + ':' + fechaInicio.getSeconds(), type: format.Type.TIMEOFDAY }); recServicioNoConciliado.setValue({ fieldId: "custrecord_ptg_sgcloc_fecha_2_", value: fechaInicioServicio }); recServicioNoConciliado.setValue({ fieldId: "custrecord_ptg_sgcloc_hora_2_", value: horaInicioServicio }); recServicioNoConciliado.setValue({ fieldId: "custrecord_ptg_folio_aut_2_", value: servicio.id_servicio }); recServicioNoConciliado.setValue({ fieldId: "custrecord_ptg_folio_sgc_2_", value: servicio.id_servicio }); recServicioNoConciliado.setValue({ fieldId: "custrecord_ptg_fechainicio_sgc_2_", value: fechaInicioServicio }); recServicioNoConciliado.setValue({ fieldId: "custrecord_ptg_foliounidad_sgc_2_", value: servicio.id_servicio }); recServicioNoConciliado.setValue({ fieldId: "custrecord_ptg_tipo_sgc_2_", value: "2" }); let servicioNoConciliadoId = recServicioNoConciliado.save(); log.debug('Registro de servicio:', servicioNoConciliadoId); oportunidadesAfectadas.push(servicioNoConciliadoId); // Update the SGC Local Folio record let recSGC = record.load({ type: "customrecord_ptg_folio_sgc_local", id: sgc_id }); recSGC.setValue({ fieldId: "custrecord_ptg_sgc_local_folio", value: servicio.id_servicio }); let savedFolio = recSGC.save(); log.debug('Folio Actualizado:', servicio.id_servicio); // } } catch (error) { log.error({ title: "Error al crear la oportunidad", details: error }); } }); } respuesta.data.push({ location: planta, oportunidades: oportunidadesAfectadas }); }); respuesta.success = (respuesta.data.length > 0) ? true : false; respuesta.message = (respuesta.data.length > 0) ? 'Se crearon las oportunidades correctamente' : 'No se crearon las oportunidades'; log.audit({ title: "Proceso finalizado...", details: `Proceso terminado: ${JSON.stringify(respuesta)}` }) // return respuesta; } catch (error) { log.debug('Error scheduled:', error) } } return { execute } });
/** * Print out Label Items * * @NApiVersion 2.x * @NScriptType Suitelet * @author trungpv <trung@lexor.com> */ define(['N/record', 'N/render', 'N/file'], function(record, render, file) { function onRequest(context) { try { var response = context.response; var request = context.request; var customId = request.parameters.customId; if (!customId) { response.write('customId parameter missing'); } // itemfulfillment ITEM_FULFILLMENT var itemFulfillment = record.load({ type: record.Type.ITEM_FULFILLMENT, id: customId }); var renderer = render.create(); var xmlTmplFile = file.load('SuiteScripts/Lexor_Advanced_PDF_Forms/Item_Labels.xml'); renderer.templateContent = xmlTmplFile.getContents(); renderer.addRecord('record', itemFulfillment); // tranid const fileName = 'item-labels-' + itemFulfillment.getValue('tranid') + '.pdf'; // Content-Disposition: attachment; filename="filename.jpg" response.setHeader({ name: 'Content-type', value: 'application/pdf' }); response.setHeader({ name: 'Content-Disposition', value: 'attachment; filename="' + fileName + '"' }); response.renderPdf(renderer.renderAsString()); } catch (err) { log.error({ title: '[LINE_NUMBER]: ' + err.lineno, details: err }); } } return { onRequest: onRequest }; });
400
[{"tag": "EMAIL", "value": "trung@lexor.com", "start": 97, "end": 112}]
true
1
/** * Print out Label Items * * @NApiVersion 2.x * @NScriptType Suitelet * @author trungpv <anpch@example.com> */ define(['N/record', 'N/render', 'N/file'], function(record, render, file) { function onRequest(context) { try { var response = context.response; var request = context.request; var customId = request.parameters.customId; if (!customId) { response.write('customId parameter missing'); } // itemfulfillment ITEM_FULFILLMENT var itemFulfillment = record.load({ type: record.Type.ITEM_FULFILLMENT, id: customId }); var renderer = render.create(); var xmlTmplFile = file.load('SuiteScripts/Lexor_Advanced_PDF_Forms/Item_Labels.xml'); renderer.templateContent = xmlTmplFile.getContents(); renderer.addRecord('record', itemFulfillment); // tranid const fileName = 'item-labels-' + itemFulfillment.getValue('tranid') + '.pdf'; // Content-Disposition: attachment; filename="filename.jpg" response.setHeader({ name: 'Content-type', value: 'application/pdf' }); response.setHeader({ name: 'Content-Disposition', value: 'attachment; filename="' + fileName + '"' }); response.renderPdf(renderer.renderAsString()); } catch (err) { log.error({ title: '[LINE_NUMBER]: ' + err.lineno, details: err }); } } return { onRequest: onRequest }; });
true
/** * Print out Label Items * * @NApiVersion 2.x * @NScriptType Suitelet * @author trungpv <PI:EMAIL:anpch@example.comEND_PI> */ define(['N/record', 'N/render', 'N/file'], function(record, render, file) { function onRequest(context) { try { var response = context.response; var request = context.request; var customId = request.parameters.customId; if (!customId) { response.write('customId parameter missing'); } // itemfulfillment ITEM_FULFILLMENT var itemFulfillment = record.load({ type: record.Type.ITEM_FULFILLMENT, id: customId }); var renderer = render.create(); var xmlTmplFile = file.load('SuiteScripts/Lexor_Advanced_PDF_Forms/Item_Labels.xml'); renderer.templateContent = xmlTmplFile.getContents(); renderer.addRecord('record', itemFulfillment); // tranid const fileName = 'item-labels-' + itemFulfillment.getValue('tranid') + '.pdf'; // Content-Disposition: attachment; filename="filename.jpg" response.setHeader({ name: 'Content-type', value: 'application/pdf' }); response.setHeader({ name: 'Content-Disposition', value: 'attachment; filename="' + fileName + '"' }); response.renderPdf(renderer.renderAsString()); } catch (err) { log.error({ title: '[LINE_NUMBER]: ' + err.lineno, details: err }); } } return { onRequest: onRequest }; });
/** * @NApiVersion 2.x * @NScriptType UserEventScript * @NModuleScope SameAccount */ define(['N/file', 'N/sftp', 'N/error'], function(file, sftp, error) { return { beforeLoad: function(){ var portNumber = -1; var connectTimeout = -1; var transferTimeout = -1; //these variables can be taken as parameters of the script instead if (portNumber < sftp.MIN_PORT_NUMBER || portNumber > sftp.MAX_PORT_NUMBER) portNumber = sftp.DEFAULT_PORT_NUMBER; if (connectTimeout < sftp.MIN_CONNECT_TIMEOUT) connectTimeout = sftp.MIN_CONNECT_TIMEOUT; else if (connectTimeout > sftp.MAX_CONNECT_TIMEOUT) connectTimeout = sftp.MAX_CONNECT_TIMEOUT; var connection = sftp.createConnection({ username: 'sftpuser', keyId: 'custkey1', url: '192.168.0.100', port: portNumber, directory: 'inbound', timeout: connectTimeout, hostKey: "AAAAB3NzaC1yc2EAAAADAQABAAABAQDMifKH2vTxdiype8nem7+lS3x7dTQR/A67KdsR/5C2WUcDipBzYhHbnG6Am12Nd2tlM01LnaBZA6/8P4Y9x/sGTxtsdE/MzeGDUBn6HBlQvgIrhX62wgoKGQ+P2lEAO1+Vz8y3/MB1NmD7Fc62cJ9Mu88YA6jwJOIPZeHYNVyIm9OrY6VyzYyvSJhH0x7SXyvGnijJQF4G8C4c8u/UVpF/sE16xKZtly2Rx0aDL2FsDRtpyPmM602/R6ISbsmgab3MzzAEIu+zLDMdIBJn3cDhNt1F7Rar6Tu0u18KCkk8GPxbnxDuG4sCNOnXPYkDXSMUbM/ocRjYGtqdZUMmeTf3" }); // can also be a big file (created for example by async search) var myFileToUpload = file.create({ name: 'originalname.txt', fileType: file.Type.PLAINTEXT, contents: 'I am a test file.' }); if (myFileToUpload.size > connection.MAX_FILE_SIZE) throw error.create({name:"FILE_IS_TOO_BIG", message:"The file you are trying to upload is too big"}); var minTransferTimeout = 10; if (transferTimeout > connection.MAX_TRANSFER_TIMEOUT) transferTimeout = connection.MAX_TRANSFER_TIMEOUT; else if (transferTimeout < minTransferTimeout) transferTimeout = minTransferTimteout; connection.upload({ directory: 'files', filename: 'test.txt', file: myFileToUpload, replaceExisting: true, timeout: transferTimeout }); } }; });
82
[{"tag": "IP_ADDRESS", "value": "192.168.0.100", "start": 927, "end": 940}, {"tag": "KEY", "value": "AAAAB3NzaC1yc2EAAAADAQABAAABAQDMifKH2vTxdiype8nem7+lS3x7dTQR/A67KdsR/5C2WUcDipBzYhHbnG6Am12Nd2tlM01LnaBZA6/8P4Y9x/sGTxtsdE/MzeGDUBn6HBlQvgIrhX62wgoKGQ+P2lEAO1+Vz8y3/MB1NmD7Fc62cJ9Mu88YA6jwJOIPZeHYNVyIm9OrY6VyzYyvSJhH0x7SXyvGnijJQF4G8C4c8u/UVpF/sE16xKZtly2Rx0aDL2FsDRtpyPmM602/R6ISbsmgab3MzzAEIu+zLDMdIBJn3cDhNt1F7Rar6Tu0u18KCkk8GPxbnxDuG4sCNOnXPYkDXSMUbM/ocRjYGtqdZUMmeTf3", "start": 1082, "end": 1454}]
true
2
/** * @NApiVersion 2.x * @NScriptType UserEventScript * @NModuleScope SameAccount */ define(['N/file', 'N/sftp', 'N/error'], function(file, sftp, error) { return { beforeLoad: function(){ var portNumber = -1; var connectTimeout = -1; var transferTimeout = -1; //these variables can be taken as parameters of the script instead if (portNumber < sftp.MIN_PORT_NUMBER || portNumber > sftp.MAX_PORT_NUMBER) portNumber = sftp.DEFAULT_PORT_NUMBER; if (connectTimeout < sftp.MIN_CONNECT_TIMEOUT) connectTimeout = sftp.MIN_CONNECT_TIMEOUT; else if (connectTimeout > sftp.MAX_CONNECT_TIMEOUT) connectTimeout = sftp.MAX_CONNECT_TIMEOUT; var connection = sftp.createConnection({ username: 'sftpuser', keyId: 'custkey1', url: '192.168.0.100', port: portNumber, directory: 'inbound', timeout: connectTimeout, hostKey: "vqbpgud2ghvjgm1n5hdgjnn5818fzsf2" }); // can also be a big file (created for example by async search) var myFileToUpload = file.create({ name: 'originalname.txt', fileType: file.Type.PLAINTEXT, contents: 'I am a test file.' }); if (myFileToUpload.size > connection.MAX_FILE_SIZE) throw error.create({name:"FILE_IS_TOO_BIG", message:"The file you are trying to upload is too big"}); var minTransferTimeout = 10; if (transferTimeout > connection.MAX_TRANSFER_TIMEOUT) transferTimeout = connection.MAX_TRANSFER_TIMEOUT; else if (transferTimeout < minTransferTimeout) transferTimeout = minTransferTimteout; connection.upload({ directory: 'files', filename: 'test.txt', file: myFileToUpload, replaceExisting: true, timeout: transferTimeout }); } }; });
true
/** * @NApiVersion 2.x * @NScriptType UserEventScript * @NModuleScope SameAccount */ define(['N/file', 'N/sftp', 'N/error'], function(file, sftp, error) { return { beforeLoad: function(){ var portNumber = -1; var connectTimeout = -1; var transferTimeout = -1; //these variables can be taken as parameters of the script instead if (portNumber < sftp.MIN_PORT_NUMBER || portNumber > sftp.MAX_PORT_NUMBER) portNumber = sftp.DEFAULT_PORT_NUMBER; if (connectTimeout < sftp.MIN_CONNECT_TIMEOUT) connectTimeout = sftp.MIN_CONNECT_TIMEOUT; else if (connectTimeout > sftp.MAX_CONNECT_TIMEOUT) connectTimeout = sftp.MAX_CONNECT_TIMEOUT; var connection = sftp.createConnection({ username: 'sftpuser', keyId: 'custkey1', url: '192.168.0.100', port: portNumber, directory: 'inbound', timeout: connectTimeout, hostKey: "PI:KEY:vqbpgud2ghvjgm1n5hdgjnn5818fzsf2END_PI" }); // can also be a big file (created for example by async search) var myFileToUpload = file.create({ name: 'originalname.txt', fileType: file.Type.PLAINTEXT, contents: 'I am a test file.' }); if (myFileToUpload.size > connection.MAX_FILE_SIZE) throw error.create({name:"FILE_IS_TOO_BIG", message:"The file you are trying to upload is too big"}); var minTransferTimeout = 10; if (transferTimeout > connection.MAX_TRANSFER_TIMEOUT) transferTimeout = connection.MAX_TRANSFER_TIMEOUT; else if (transferTimeout < minTransferTimeout) transferTimeout = minTransferTimteout; connection.upload({ directory: 'files', filename: 'test.txt', file: myFileToUpload, replaceExisting: true, timeout: transferTimeout }); } }; });
/** * * @NApiVersion 2.0 * @NScriptType Suitelet * * Description: A ticketing system for the Customer Service. * @Last Modified by: Sruti Desai * */ define(['N/ui/serverWidget', 'N/email', 'N/runtime', 'N/search', 'N/record', 'N/http', 'N/log', 'N/redirect', 'N/format', 'N/file'], function (ui, email, runtime, search, record, http, log, redirect, format, file) { var baseURL = 'https://1048144.app.netsuite.com'; if (runtime.EnvType == "SANDBOX") { baseURL = 'https://1048144-sb3.app.netsuite.com'; } var zee = 0; var role = runtime.getCurrentUser().role; var userRole = runtime.getCurrentUser().role; var ctx = runtime.getCurrentScript(); var userId = runtime.getCurrentUser().id; if (role == 1000) { //Franchisee zee = runtime.getCurrentUser(); } function onRequest(context) { if (context.request.method === 'GET') { var ticket_id = null; var customer_id = null; var customer_number = null; var selector_id = null; var selector_number = ''; var selector_type = 'barcode_number'; var connote_number = ''; var date_created = ''; var creator_name = ''; var creator_id = null; var status_value = null; var escalated_to_it = ''; var status = ''; var customer_name = ''; var daytodayphone = ''; var daytodayemail = ''; var accountsphone = ''; var accountsemail = ''; var zee_id = null; var franchisee_name = ''; var zee_main_contact_name = ''; var zee_email = ''; var zee_main_contact_phone = ''; var zee_abn = ''; var date_stock_used = ''; var time_stock_used = ''; var final_delivery_text = ''; var selected_enquiry_status_id = null; var attachments_hyperlink = ''; var maap_bank_account_number = null; var maap_parent_bank_account_number = null; var selected_invoice_method_id = null; var accounts_cc_email = ''; var mpex_po_number = ''; var customer_po_number = ''; var terms = null; var customer_terms = ''; var account_manager = {}; var selected_invoice_cycle_id = null; var usage_report_id_1 = ''; var usage_report_id_2 = ''; var usage_report_id_3 = ''; var usage_report_id_4 = ''; var usage_report_array = []; var list_toll_issues = ''; var list_resolved_toll_issues = ''; var list_mp_ticket_issues = ''; var list_resolved_mp_ticket_issues = ''; var list_invoice_issues = ''; var list_resolved_invoice_issues = ''; var owner_list = ''; var comment = ''; var selected_label_id = null; var list_enquiry_mediums = ''; var total_enquiry_count = 0; var chat_enquiry_count = 0; var phone_enquiry_count = 0; var email_enquiry_count = 0; var phone_interaction_count = 0; var email_interaction_count = 0; var list_toll_emails = ''; var params_email = { recipient: '', subject: '', body: '', cc: '', bcc: '', records: {}, attachments_credit_memo_ids: [], attachments_usage_report_ids: [], attachments_invoice_ids: [] }; var customer_barcode_number = ''; var customer_issue = ''; var screenshot_file = ''; var browser = ''; var login_email_used = ''; var operating_system = ''; var phone_used = ''; var old_sender_name = ''; var old_sender_phone = ''; var customer_number_email_sent = 'F'; var customer_ticket_status = ''; var receiveremail = ''; var receiverphone = ''; var receivername = ''; var receiverstate = ''; var receiverzip = ''; var receiversuburb = ''; var receiveraddr1 = ''; var receiveraddr2 = ''; var prod_stock_invoice = ''; var barcodempdl = ''; var barcodesource = ''; var barcodeintegration = ''; var senderName = ''; var senderEmail = ''; var senderPhone = ''; var senderAddress = ''; var productName = '' // Load params var params = context.request.parameters.custparam_params; log.debug({ title: 'Params', details: params }) if (!isNullorEmpty(params)) { params = JSON.parse(params); log.debug({ title: 'Params not empty', details: params }); // Coming from the ticket_contact page or the edit_ticket page if (!isNullorEmpty(params.selector_number) && !isNullorEmpty(params.selector_type)) { selector_number = params.selector_number; selector_type = params.selector_type; //Coming from the ticket_contact page if (!isNullorEmpty(params.custid)) { customer_id = params.custid; } log.debug({ title: 'customer_id after ticket_contact_page : ', details: customer_id }); // Coming from the edit_ticket page if (!isNullorEmpty(params.ticket_id)) { ticket_id = parseInt(params.ticket_id); log.debug({ title: 'ticket id ISS', details: ticket_id }); // Load ticket data var ticketRecord = record.load({ type: 'customrecord_mp_ticket', id: ticket_id }); date_created = ticketRecord.getValue({ fieldId: 'created' }); creator_name = ticketRecord.getText({ fieldId: 'custrecord_creator' }); creator_id = ticketRecord.getValue({ fieldId: 'custrecord_creator' }); status_value = ticketRecord.getValue({ fieldId: 'custrecord_ticket_status' }); escalated_to_it = ticketRecord.getValue({ fieldId: 'custrecord_date_escalated_it' }); status = ticketRecord.getText({ fieldId: 'custrecord_ticket_status' }); customer_id = ticketRecord.getValue({ fieldId: 'custrecord_customer1' }); customer_name = ticketRecord.getText({ fieldId: 'custrecord_customer1' }); zee_id = ticketRecord.getValue({ fieldId: 'custrecord_zee' }); selected_enquiry_status_id = ticketRecord.getValue({ fieldId: 'custrecord_enquiry_status' }); attachments_hyperlink = ticketRecord.getValue({ fieldId: 'custrecord_mp_ticket_attachments' }); selected_label_id = ticketRecord.getValue({ fieldId: 'custrecord_ticket_label' }); list_enquiry_mediums = ticketRecord.getValue({ fieldId: 'custrecord_enquiry_medium' }); list_enquiry_mediums = java2jsArray(list_enquiry_mediums); total_enquiry_count = ticketRecord.getValue({ fieldId: 'custrecord_enquiry_count' }); chat_enquiry_count = ticketRecord.getValue({ fieldId: 'custrecord_chat_enquiry_count' }); phone_enquiry_count = ticketRecord.getValue({ fieldId: 'custrecord_phone_enquiry_count' }); phone_interaction_count = ticketRecord.getValue({ fieldId: 'custrecord_phone_interaction_count' }); email_interaction_count = ticketRecord.getValue({ fieldId: 'custrecord_email_interaction_count' }); email_enquiry_count = ticketRecord.getValue({ fieldId: 'custrecord_email_enquiry_count' }); customer_issue = ticketRecord.getValue({ fieldId: 'custrecord_customer_issue' }); screenshot_file = ticketRecord.getValue({ fieldId: 'custrecord_screenshot' }); browser = ticketRecord.getValue({ fieldId: 'custrecord_browser' }); login_email_used = ticketRecord.getValue({ fieldId: 'custrecord_login_email' }); operating_system = ticketRecord.getValue({ fieldId: 'custrecord_operating_system' }); phone_used = ticketRecord.getValue({ fieldId: 'custrecord_phone_used' }); customer_number = ticketRecord.getValue({ fieldId: 'custrecord_cust_number' }); old_sender_name = ticketRecord.getValue({ fieldId: 'custrecord_sender_name' }); old_sender_phone = ticketRecord.getValue({ fieldId: 'custrecord_sender_phone' }); customer_number_email_sent = ticketRecord.getValue({ fieldId: 'custrecord_customer_number_email_sent' }); customer_barcode_number = ticketRecord.getValue({ fieldId: 'custrecord_barcode_number' }); customer_ticket_status = ticketRecord.getText({ fieldId: 'custrecord_mp_ticket_customer_status' }); if (!isNullorEmpty(customer_barcode_number)) { var rec = record.load({ type: 'customrecord_customer_product_stock', id: customer_barcode_number, }); receiveremail = rec.getValue({ fieldId: 'custrecord_receiver_email' }); receiverphone = rec.getValue({ fieldId: 'custrecord_receiver_phone' }); receivername = rec.getValue({ fieldId: 'custrecord_receiver_name' }); receiverstate = rec.getValue({ fieldId: 'custrecord_receiver_state' }); receiverzip = rec.getValue({ fieldId: 'custrecord_receiver_postcode' }); receiversuburb = rec.getValue({ fieldId: 'custrecord_receiver_suburb' }); receiveraddr1 = rec.getValue({ fieldId: 'custrecord_receiver_addr1' }); receiveraddr2 = rec.getValue({ fieldId: 'custrecord_receiver_addr2' }); senderName = rec.getValue({ fieldId: 'custrecord_senders_name' }); senderEmail = rec.getValue({ fieldId: 'custrecord_sender_email' }); senderPhone = rec.getValue({ fieldId: 'custrecord_senders_phone' }); senderAddress = rec.getValue({ fieldId: 'custrecord_sender_address_1' }); productName = rec.getText({ fieldId: 'custrecord_cust_prod_stock_single_name' }); if (isNullorEmpty(productName)) { productName = rec.getText({ fieldId: 'custrecord_cust_stock_prod_name' }) } prod_stock_invoice = rec.getText({ fieldId: 'custrecord_prod_stock_invoice' }); barcodempdl = rec.getValue({ fieldId: 'custrecord_mpdl_number' }); barcodeintegration = rec.getValue({ fieldId: 'custrecord_integration' }); barcodesource = rec.getText({ fieldId: 'custrecord_barcode_source' }); connote_number = rec.getValue({ fieldId: 'custrecord_connote_number' }); } if (isNullorEmpty(customer_id) && !isNullorEmpty(customer_number)) { var customer_search = search.load({ type: 'customer', id: 'customsearch_customer_name_2' }); customer_search.filters.push(search.createFilter({ name: 'entityid', operator: 'haskeywords', values: customer_number, })); log.debug({ title: 'customer_search.run().getRange({ start: 0,end:1 })[0].id', details: customer_search.run().getRange({ start: 0, end: 1 })[0].id }); customer_id = customer_search.run().getRange({ start: 0, end: 1 })[0].id; } if (!isNullorEmpty(customer_id)) { //Load customer record and franchisee information var customerRecord = record.load({ type: 'customer', id: customer_id }); customer_number = customerRecord.getValue({ fieldId: 'entityid' }); daytodayphone = customerRecord.getValue({ fieldId: 'phone' }); daytodayemail = customerRecord.getValue({ fieldId: 'custentity_email_service' }); terms = customerRecord.getValue({ fieldId: 'terms' }); customer_terms = customerRecord.getValue({ fieldId: 'custentity_finance_terms' }); // Account manager var accountManagerSearch = search.load({ type: 'customer', id: 'customsearch3413' }); accountManagerSearch.filters.push(search.createFilter({ name: 'internalid', join: null, operator: search.Operator.ANYOF, values: customer_id, })) var accountManagerResultSet = accountManagerSearch.run(); var accountManagerResult = accountManagerResultSet.getRange({ start: 0, end: 1 }); accountManagerResult = accountManagerResult[0]; if (!isNullorEmpty(accountManagerResult)) { var account_manager_value = accountManagerResult.getValue({ name: "custrecord_sales_assigned", join: "CUSTRECORD_SALES_CUSTOMER", summary: null }); var account_manager_text = accountManagerResult.getText({ name: "custrecord_sales_assigned", join: "CUSTRECORD_SALES_CUSTOMER", summary: null }); if (!isNullorEmpty(account_manager_value)) { var account_manager_email = search.lookupFields({ type: 'employee', id: account_manager_value, columns: 'email' }); account_manager = { name: account_manager_text, email: account_manager_email }; } } // The Franchisee informations are imported from the customer record if possible. zee_id = customerRecord.getValue({ fieldId: 'partner' }); } if (!isNullorEmpty(zee_id)) { var zeeRecord = record.load({ type: 'partner', id: zee_id }); franchisee_name = zeeRecord.getValue({ fieldId: 'companyname' }); zee_main_contact_name = zeeRecord.getValue({ fieldId: 'custentity3' }); zee_email = zeeRecord.getValue({ fieldId: 'email' }); zee_main_contact_phone = zeeRecord.getValue({ fieldId: 'custentity2' }); zee_abn = zeeRecord.getValue({ fieldId: 'custentity_abn_franchiserecord' }); } else { franchisee_name = ticketRecord.getText({ fieldId: 'custrecord_zee' }); } switch (selector_type) { case 'barcode_number': selector_id = ticketRecord.getValue({ fieldId: 'custrecord_barcode_number' }); var stock_used = ''; if (!isNullorEmpty(selector_id)) { //Come in here only if selector_id is not null stock_used = search.lookupFields({ type: 'customrecord_customer_product_stock', id: selector_id, columns: ['custrecord_cust_date_stock_used', 'custrecord_cust_time_stock_used'] }); log.debug({ title: 'stock_used', details: stock_used }) log.debug({ title: 'finalDel', details: search.lookupFields({ type: 'customrecord_customer_product_stock', id: selector_id, columns: 'custrecord_cust_prod_stock_final_del' }) }); var finalDelCheck = search.lookupFields({ type: 'customrecord_customer_product_stock', id: selector_id, columns: 'custrecord_cust_prod_stock_final_del' }).custrecord_cust_prod_stock_final_del; if (!isNullorEmpty(finalDelCheck)) { final_delivery_text = search.lookupFields({ type: 'customrecord_customer_product_stock', id: selector_id, columns: 'custrecord_cust_prod_stock_final_del' })["custrecord_cust_prod_stock_final_del"][0]["text"]; } date_stock_used = stock_used.custrecord_cust_date_stock_used; time_stock_used = stock_used.custrecord_cust_time_stock_used; } list_toll_issues = ticketRecord.getValue({ fieldId: 'custrecord_toll_issues' }); list_toll_issues = java2jsArray(list_toll_issues); list_resolved_toll_issues = ticketRecord.getValue({ fieldId: 'custrecord_resolved_toll_issues' }); list_resolved_toll_issues = java2jsArray(list_resolved_toll_issues); list_toll_emails = ticketRecord.getValue({ fieldId: 'custrecord_toll_emails' }); list_toll_emails = java2jsArray(list_toll_emails); break; case 'invoice_number': selector_id = ticketRecord.getValue({ fieldId: 'custrecord_invoice_number' }); var invoiceRecord = record.load({ type: 'invoice', id: selector_id }); accountsphone = customerRecord.getValue({ fieldId: 'altphone' }); accountsemail = customerRecord.getValue({ fieldId: 'email' }); maap_bank_account_number = customerRecord.getValue({ fieldId: 'custentity_maap_bankacctno' }); maap_parent_bank_account_number = customerRecord.getValue({ fieldId: 'custentity_maap_bankacctno_parent' }); selected_invoice_method_id = customerRecord.getValue({ fieldId: 'custentity_invoice_method' }); accounts_cc_email = customerRecord.getValue({ fieldId: 'custentity_accounts_cc_email' }); mpex_po_number = customerRecord.getValue({ fieldId: 'custentity_mpex_po' }); customer_po_number = customerRecord.getValue({ fieldId: 'custentity11' }); selected_invoice_cycle_id = customerRecord.getValue({ fieldId: 'custentity_mpex_invoicing_cycle' }); usage_report_id_1 = invoiceRecord.getValue({ fieldId: 'custbody_mpex_usage_report' }); usage_report_id_2 = invoiceRecord.getValue({ fieldId: 'custbody_mpex_usage_report_2' }); usage_report_id_3 = invoiceRecord.getValue({ fieldId: 'custbody_mpex_usage_report_3' }); usage_report_id_4 = invoiceRecord.getValue({ fieldId: 'custbody_mpex_usage_report_4' }); var usage_report_id_array = [usage_report_id_1, usage_report_id_2, usage_report_id_3, usage_report_id_4]; usage_report_id_array.forEach(function (usage_report_id) { if (!isNullorEmpty(usage_report_id)) { var usage_report_file = file.load({ id: usage_report_id }); usage_report_name = usage_report_file.name; usage_report_link = usage_report_file.url; usage_report_array.push({ id: usage_report_id, name: usage_report_name, url: usage_report_link }); } }); list_invoice_issues = ticketRecord.getValue({ fieldId: 'custrecord_invoice_issues' }); list_invoice_issues = java2jsArray(list_invoice_issues); list_resolved_invoice_issues = ticketRecord.getValue({ fieldId: 'custrecord_resolved_invoice_issues' }); list_resolved_invoice_issues = java2jsArray(list_resolved_invoice_issues); break; } list_mp_ticket_issues = ticketRecord.getValue({ fieldId: 'custrecord_mp_ticket_issue' }); list_mp_ticket_issues = java2jsArray(list_mp_ticket_issues); list_resolved_mp_ticket_issues = ticketRecord.getValue({ fieldId: 'custrecord_resolved_mp_ticket_issue' }); list_resolved_mp_ticket_issues = java2jsArray(list_resolved_mp_ticket_issues); owner_list = ticketRecord.getValue({ fieldId: 'custrecord_owner' }); owner_list = Ownerjava2jsArray(owner_list); comment = ticketRecord.getValue({ fieldId: 'custrecord_comment' }); } } } var form = ui.createForm({ title: ' ', }); // Load jQuery var inlineHtml = '<script src="https://code.jquery.com/jquery-1.12.4.min.js" integrity="sha384-nvAa0+6Qg9clwYCGGPpDQLVpLNn0fRaROjHqs13t4Ggj3Ez50XnGQqc/r8MhnRDZ" crossorigin="anonymous"></script>'; // Load Tooltip inlineHtml += '<script src="https://unpkg.com/@popperjs/core@2"></script>'; // Load Bootstrap inlineHtml += '<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/3.4.1/css/bootstrap.min.css" integrity="sha384-HSMxcRTRxnN+Bdg0JdbxYKrThecOKuH5zCYotlSAcp1+c8xmyTe9GYg1l9a69psu" crossorigin="anonymous">'; inlineHtml += '<script src="https://stackpath.bootstrapcdn.com/bootstrap/3.4.1/js/bootstrap.min.js" integrity="sha384-aJ21OjlMXNL5UyIl/XNwTMqvzeRMZH2w8c5cRVpzpU8Y5bApTppSuUkhZXN0VxHd" crossorigin="anonymous"></script>'; // Load DataTables inlineHtml += '<link rel="stylesheet" type="text/css" href="//cdn.datatables.net/1.10.21/css/jquery.dataTables.min.css">'; inlineHtml += '<script type="text/javascript" charset="utf8" src="//cdn.datatables.net/1.10.21/js/jquery.dataTables.min.js"></script>'; // Load Summernote css/js inlineHtml += '<link href="https://cdnjs.cloudflare.com/ajax/libs/summernote/0.8.9/summernote.css" rel="stylesheet">'; inlineHtml += '<script src="https://cdnjs.cloudflare.com/ajax/libs/summernote/0.8.9/summernote.js"></script>'; // Load bootstrap-select inlineHtml += '<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap-select@1.13.14/dist/css/bootstrap-select.min.css">'; inlineHtml += '<script src="https://cdn.jsdelivr.net/npm/bootstrap-select@1.13.14/dist/js/bootstrap-select.min.js"></script>'; // Load Netsuite stylesheet and script inlineHtml += '<link rel="stylesheet" href="https://1048144.app.netsuite.com/core/media/media.nl?id=2060796&c=1048144&h=9ee6accfd476c9cae718&_xt=.css"/>'; inlineHtml += '<script src="https://1048144.app.netsuite.com/core/media/media.nl?id=2060797&c=1048144&h=ef2cda20731d146b5e98&_xt=.js"></script>'; inlineHtml += '<link type="text/css" rel="stylesheet" href="https://1048144.app.netsuite.com/core/media/media.nl?id=2090583&c=1048144&h=a0ef6ac4e28f91203dfe&_xt=.css">'; inlineHtml += '<style>.mandatory{color:red;}</style>'; // Define alert window. inlineHtml += '<div class="container" style="margin-top:14px;" hidden><div id="danger-alert" class="alert alert-danger fade in"></div></div>'; // Define information window. inlineHtml += '<div class="container" hidden><p id="info" class="alert alert-info"></p></div>'; inlineHtml += tabsSection(customer_number, ticket_id, selector_number, selector_id, selector_type, status_value, customer_name, daytodayphone, daytodayemail, franchisee_name, zee_main_contact_name, zee_email, zee_main_contact_phone, zee_abn, date_stock_used, time_stock_used, final_delivery_text, selected_enquiry_status_id, attachments_hyperlink, owner_list, list_toll_issues, list_resolved_toll_issues, comment, date_created, creator_id, creator_name, status, customer_id, accountsphone, accountsemail, zee_id, list_enquiry_mediums, total_enquiry_count, chat_enquiry_count, phone_enquiry_count, email_enquiry_count, selected_label_id, maap_bank_account_number, maap_parent_bank_account_number, account_manager, list_toll_emails, customer_barcode_number, connote_number, receiveremail, receiverphone, receivername, receiverstate, receiverzip, receiversuburb, receiveraddr1, receiveraddr2, prod_stock_invoice, barcodempdl, barcodesource, list_mp_ticket_issues, list_resolved_mp_ticket_issues, list_invoice_issues, list_resolved_invoice_issues, selected_invoice_method_id, accounts_cc_email, mpex_po_number, customer_po_number, selected_invoice_cycle_id, terms, customer_terms, screenshot_file, browser, login_email_used, operating_system, phone_used, old_sender_name, old_sender_phone, phone_interaction_count, email_interaction_count, escalated_to_it, senderName, senderAddress, senderEmail, senderPhone, productName, barcodeintegration); // inlineHtml += customerNumberSection(customer_number, ticket_id); // inlineHtml += selectorSection(ticket_id, selector_number, selector_id, selector_type, status_value); // if (!isNullorEmpty(ticket_id)) { // inlineHtml += ticketSection(dateISOToNetsuite(date_created), creator_id, creator_name, status); // } // if (isNullorEmpty(ticket_id) || (!isNullorEmpty(ticket_id) && !isNullorEmpty(customer_id)) || !isNullorEmpty(customer_number)) { // inlineHtml += customerSection(customer_name); // inlineHtml += daytodayContactSection(daytodayphone, daytodayemail, status_value, selector_type); // inlineHtml += accountsContactSection(accountsphone, accountsemail, status_value, selector_type); // } // if(isNullorEmpty(ticket_id) || (!isNullorEmpty(ticket_id) && (selector_type == 'invoice_section'))) { // inlineHtml += maapBankAccountSection(maap_bank_account_number, maap_parent_bank_account_number, selector_type); // } // if (isNullorEmpty(ticket_id) || (!isNullorEmpty(ticket_id) && !isNullorEmpty(zee_id)) || !isNullorEmpty(customer_number)) { // inlineHtml += franchiseeMainContactSection(franchisee_name, zee_main_contact_name, zee_email, zee_main_contact_phone, zee_abn); // } // inlineHtml += mpexStockUsedSection(selector_type, date_stock_used, time_stock_used); // inlineHtml += finalDeliveryEnquirySection(status_value, selector_type, final_delivery_text, selected_enquiry_status_id); // inlineHtml += attachmentsSection(attachments_hyperlink, status_value); // if (isNullorEmpty(ticket_id) || (!isNullorEmpty(ticket_id) && (selector_type == 'invoice_number'))) { // inlineHtml += otherInvoiceFieldsSection(selected_invoice_method_id, accounts_cc_email, mpex_po_number, customer_po_number, selected_invoice_cycle_id, terms, customer_terms, status_value, selector_type); // inlineHtml += openInvoicesSection(ticket_id, selector_type); // if (!isNullorEmpty(ticket_id)) { // inlineHtml += creditMemoSection(selector_type); // inlineHtml += usageReportSection(selector_type); // } // } // inlineHtml += mpexContactSection(); // inlineHtml += enquiryMediumSection(list_enquiry_mediums, selected_enquiry_status_id ,selector_type); // inlineHtml += enquiryCountSection(total_enquiry_count, chat_enquiry_count, phone_enquiry_count, email_enquiry_count); // inlineHtml += labelSection(selected_label_id, selector_type, status_value); // inlineHtml += sendEmailSection(ticket_id, status_value, account_manager,list_toll_emails); // log.debug({ title: 'before prev email - cust id', details: customer_id }); // if(!isNullorEmpty(customer_id)){ // inlineHtml += previousEmailsSection(customer_id); // } // inlineHtml += issuesHeader(); // inlineHtml += customerIssuesSection(ticket_id, selector_type, selector_number, screenshot_file, browser, login_email_used, operating_system, phone_used, old_sender_name, old_sender_phone, status_value); // if(selector_type == "barcode_number" || selector_type == "invoice_number"){ // inlineHtml += reminderSection(status_value); // } // inlineHtml += ownerSection(ticket_id, owner_list, status_value); // inlineHtml += tollIssuesSection(list_toll_issues, list_resolved_toll_issues, status_value, selector_type); // inlineHtml += mpTicketIssuesSection(list_mp_ticket_issues, list_resolved_mp_ticket_issues, status_value, selector_type); // inlineHtml += invoiceIssuesSection(list_invoice_issues, list_resolved_invoice_issues, status_value, selector_type); // inlineHtml += usernoteSection(selector_type, status_value); // inlineHtml += commentSection(comment, selector_type, status_value); // inlineHtml += dataTablePreview(); //inlineHtml += closeReopenSubmitTicketButton(ticket_id, status_value); form.addField({ id: 'preview_table', type: ui.FieldType.INLINEHTML, label: 'preview_table' }).defaultValue = inlineHtml; form.addField({ id: 'custpage_open_new_ticket', type: ui.FieldType.TEXT, label: 'Open New Ticket' }).updateDisplayType({ displayType: ui.FieldDisplayType.HIDDEN }).defaultValue = 'F'; log.debug({ title: 'Selector_number', details: selector_number }); form.addField({ id: 'custpage_selector_number', type: ui.FieldType.TEXT, label: 'Selector Number' }).updateDisplayType({ displayType: ui.FieldDisplayType.HIDDEN }).defaultValue = selector_number; form.addField({ id: 'custpage_selector_type', type: ui.FieldType.TEXT, label: 'Selector Type' }).updateDisplayType({ displayType: ui.FieldDisplayType.HIDDEN }).defaultValue = selector_type; if (!isNullorEmpty(ticket_id)) { form.addField({ id: 'custpage_ticket_id', type: ui.FieldType.TEXT, label: 'Ticket ID' }).updateDisplayType({ displayType: ui.FieldDisplayType.HIDDEN }).defaultValue = ticket_id; } else { form.addField({ id: 'custpage_ticket_id', type: ui.FieldType.TEXT, label: 'Ticket ID' }).updateDisplayType({ displayType: ui.FieldDisplayType.HIDDEN }); } form.addField({ id: 'custpage_selector_id', type: ui.FieldType.TEXT, label: 'Selector ID' }).updateDisplayType({ displayType: ui.FieldDisplayType.HIDDEN }).defaultValue = selector_id; form.addField({ id: 'custpage_selector_issue', type: ui.FieldType.TEXT, label: 'Barcode issue' }).updateDisplayType({ displayType: ui.FieldDisplayType.HIDDEN }).defaultValue = 'F'; form.addField({ id: 'custpage_customer_id', type: ui.FieldType.TEXT, label: 'Customer ID' }).updateDisplayType({ displayType: ui.FieldDisplayType.HIDDEN }).defaultValue = customer_id; form.addField({ id: 'custpage_customer_number', type: ui.FieldType.TEXT, label: 'Customer Number' }).updateDisplayType({ displayType: ui.FieldDisplayType.HIDDEN }).defaultValue = customer_number; form.addField({ id: 'custpage_zee_id', type: ui.FieldType.TEXT, label: 'Franchisee ID' }).updateDisplayType({ displayType: ui.FieldDisplayType.HIDDEN }).defaultValue = zee_id; form.addField({ id: 'custpage_ticket_status_value', type: ui.FieldType.TEXT, label: 'Status Value' }).updateDisplayType({ displayType: ui.FieldDisplayType.HIDDEN }).defaultValue = status_value; form.addField({ id: 'custpage_created_ticket', type: ui.FieldType.TEXT, label: 'Created Ticket' }).updateDisplayType({ displayType: ui.FieldDisplayType.HIDDEN }).defaultValue = 'F'; form.addField({ id: 'custpage_usage_report_array', type: ui.FieldType.TEXT, label: 'Usage Reports' }).updateDisplayType({ displayType: ui.FieldDisplayType.HIDDEN }).defaultValue = JSON.stringify(usage_report_array); form.addField({ id: 'custpage_param_email', type: ui.FieldType.TEXT, label: 'Email parameters' }).updateDisplayType({ displayType: ui.FieldDisplayType.HIDDEN }).defaultValue = JSON.stringify(params_email); form.addField({ id: 'custpage_ss_image', type: ui.FieldType.TEXT, label: 'Screenshot Image' }).updateDisplayType({ displayType: ui.FieldDisplayType.HIDDEN }).defaultValue = screenshot_file; form.addField({ id: 'custpage_customer_number_email_sent', type: ui.FieldType.TEXT, label: 'Customer Email Sent' }).updateDisplayType({ displayType: ui.FieldDisplayType.HIDDEN }).defaultValue = customer_number_email_sent; if (!isNullorEmpty(ticket_id)) { if (isTicketNotClosed(status_value)) { form.addSubmitButton({ label: 'Update Ticket' }); } // else { // form.addSubmitButton({ label: 'Reopen Ticket' }); // } } else { form.addSubmitButton({ label: 'Save Ticket' }); // form.addButton({ id: 'custpage_openandnew', label: 'Open & New Ticket', functionName: 'openAndNew()' }); // } // if (isTicketNotClosed(status_value)) { // form.addButton({ id: 'custpage_escalate', label: 'Escalate', functionName: 'onEscalate()' }); } // form.addButton({ id: 'custpage_cancel', label: 'Cancel', functionName: 'onCancel()' }); form.clientScriptFileId = 4813453;//SB=4796340 PROD=4813453 context.response.writePage(form); } else { log.debug({ title: "In else POST part", details: '' }); var created_ticket = context.request.parameters.custpage_created_ticket; log.debug({ title: "created_ticket", details: created_ticket }); var is_ss_changed = context.request.parameters.custpage_is_ss_changed; log.debug({ title: "is_ss_changed", details: is_ss_changed }); if (created_ticket == 'T') { var ticket_id = context.request.parameters.custpage_ticket_id; var selector_number = context.request.parameters.custpage_selector_number; var selector_type = context.request.parameters.custpage_selector_type; var open_new_ticket = context.request.parameters.custpage_open_new_ticket; if (open_new_ticket == 'T') { // If the ticket was just created, and the user clicked on 'Open & New Ticket', // The user is redirected to a new "Open Ticket" page. redirect.toSuitelet({ scriptId: 'customscript_sl_open_ticket_2', deploymentId: 'customdeploy_sl_open_ticket_2', parameters: params2 }); } else { custparam_params = { ticket_id: parseInt(ticket_id), selector_number: selector_number, selector_type: selector_type, } custparam_params = JSON.stringify(custparam_params); log.debug({ title: "custparams", details: custparam_params }); var params2 = { custparam_params: custparam_params }; // If the ticket was just created, the user is redirected to the "Edit Ticket" page redirect.toSuitelet({ scriptId: 'customscript_sl_open_ticket_2', deploymentId: 'customdeploy_sl_open_ticket_2', parameters: params2 }); } } else { var params_email = context.request.parameters.custpage_param_email; params_email = JSON.parse(params_email); var to = params_email.recipient; var email_subject = params_email.subject; var email_body = decodeURIComponent(params_email.body); var cc = null; var bcc = null var emailAttach = null; var attachments_credit_memo_ids = null; var attachments_usage_report_ids = null; var attachments_invoice_ids = null; var customer_id = context.request.parameters.custpage_customer_id; var open_new_ticket = context.request.parameters.custpage_open_new_ticket; if (!isNullorEmpty(params_email.cc)) { cc = params_email.cc; } if (!isNullorEmpty(params_email.bcc)) { bcc = params_email.bcc; } if (!isNullorEmpty(params_email.records)) { emailAttach = params_email.records; } var attachement_files = []; if (!isNullorEmpty(params_email.attachments_credit_memo_ids)) { attachments_credit_memo_ids = params_email.attachments_credit_memo_ids; attachments_credit_memo_ids.forEach(function (record_id) { render.transaction({ entityId: record_id, printMode: render.PrintMode.PDF, formId: number, inCustLocale: boolean }); }); } if (!isNullorEmpty(params_email.attachments_usage_report_ids)) { attachments_usage_report_ids = params_email.attachments_usage_report_ids; attachments_usage_report_ids.forEach(function (record_id) { attachement_files.push(file.load({ id: record_id })); }); } if (!isNullorEmpty(params_email.attachments_invoice_ids)) { attachments_invoice_ids = params_email.attachments_invoice_ids; attachments_invoice_ids.forEach(function (invoice_id) { render.transaction({ entityId: invoice_id, printMode: render.PrintMode.PDF, }) }); } // If the parameter is non null, it means that the "SEND EMAIL" button was clicked. if (!isNullorEmpty(attachement_files)) { try { email.send({ author: 112209, body: email_body, recipients: to, subject: email_subject, attachments: attachement_files, bcc: bcc, cc: cc, relatedRecords: { entityId: customer_id }, }); // 112209 is from MailPlus Team } catch (error) { if (error instanceof error.SuiteScriptError) { return error.name; } } } log.debug({ title: 'open_new_ticket', details: open_new_ticket }); if (open_new_ticket == 'T') { log.debug({ title: 'open ticket page', details: 'open ticket page' }) // If the ticket was just updated, and the user clicked on 'Updated & New Ticket', // The user is redirected to a new "Open Ticket" page. redirect.toSuitelet({ scriptId: 'customscript_sl_open_ticket_2', deploymentId: 'customdeploy_sl_open_ticket_2', }); } else { // If the ticket was updated, the user is redirected to the "View MP Tickets" page redirect.toSuitelet({ scriptId: 'customscript_sl_edit_ticket_2', deploymentId: 'customdeploy_sl_edit_ticket_2', }); } } } } function instructionsBox(ticket_id) { //Important Instructions box var inlineHtml = '<br></br>' inlineHtml += '<div></div>'; inlineHtml += '<div class="form-group container test_section">'; //inlineHtml += '<button type="button" class="btn btn-sm btn-info instruction_button" data-toggle="collapse" data-target="#demo">Click for Instructions</button>'; //inlineHtml += '<div id="demo" style="background-color: #cfeefc !important;border: 1px solid #417ed9;padding: 20px 30px 30px 30px;width:96%;position:absolute" class="collapse"><b><u>IMPORTANT INSTRUCTIONS:</u></b>'; inlineHtml += '<div style=\"background-color: #e3e8e5 !important;border: 2px solid #379E8F;padding: 20px 30px 30px 30px; text-align: left\"><b><u>Mandatory Fields:</u></b>'; inlineHtml += '<ul>'; inlineHtml += '<li><b><u>Ticket Details</u></b>: Total Enquiry Count must be at least 1 i.e. Chat/Email/Phone must have at least 1 incremented and Receiver Details should be filled in if blank</li>'; inlineHtml += '<li><b><u>Issues</u></b>: Owner and Toll Emails must have at least one selected</li>'; inlineHtml += '<li>If you have any issues, please contact Ankith</li>'; inlineHtml += '</ul></div></div><br/>'; return inlineHtml; } function externalBarcodeSource(selector_type, barcodeintegration, barcodempdl, barcodesource, productName) { var disabled = 'disabled'; var inlineQty = ''; if (selector_type == 'barcode_number') { inlineQty += '<div class="form-group container barcode_section">'; inlineQty += '<div class="row">'; // Product Type field inlineQty += '<div class="col-xs-4 barcodempdl_div">'; inlineQty += '<div class="input-group">'; inlineQty += '<span class="input-group-addon" id="barcodempdl_text">Product Type</span>'; inlineQty += '<input id="productName" value="' + productName + '" class="form-control productName" ' + disabled + ' />'; inlineQty += '</div></div>'; inlineQty += '</div></div>'; inlineQty += '<div class="form-group container barcode_section">'; inlineQty += '<div class="row">'; // MPLD field inlineQty += '<div class="col-xs-4 barcodempdl_div">'; inlineQty += '<div class="input-group">'; inlineQty += '<span class="input-group-addon" id="barcodempdl_text">INTEGRATION</span>'; inlineQty += '<input id="barcodempdl" value="' + barcodeintegration + '" class="form-control barcodempdl" ' + disabled + ' />'; inlineQty += '</div></div>'; // MPLD field inlineQty += '<div class="col-xs-4 barcodempdl_div">'; inlineQty += '<div class="input-group">'; inlineQty += '<span class="input-group-addon" id="barcodempdl_text">EXTERNAL BARCODE</span>'; inlineQty += '<input id="barcodempdl" value="' + barcodempdl + '" class="form-control barcodempdl" ' + disabled + ' />'; inlineQty += '</div></div>'; // barcode source field inlineQty += '<div class="col-xs-4 barcodesource_div">'; inlineQty += '<div class="input-group">'; inlineQty += '<span class="input-group-addon" id="barcodesource_text">BARCODE SOURCE</span>'; inlineQty += '<input id="barcodesource" value="' + barcodesource + '" class="form-control barcodesource" ' + disabled + ' />'; inlineQty += '</div></div></div></div>'; } return inlineQty; } function tabsSection(customer_number, ticket_id, selector_number, selector_id, selector_type, status_value, customer_name, daytodayphone, daytodayemail, franchisee_name, zee_main_contact_name, zee_email, zee_main_contact_phone, zee_abn, date_stock_used, time_stock_used, final_delivery_text, selected_enquiry_status_id, attachments_hyperlink, owner_list, list_toll_issues, list_resolved_toll_issues, comment, date_created, creator_id, creator_name, status, customer_id, accountsphone, accountsemail, zee_id, list_enquiry_mediums, total_enquiry_count, chat_enquiry_count, phone_enquiry_count, email_enquiry_count, selected_label_id, maap_bank_account_number, maap_parent_bank_account_number, account_manager, list_toll_emails, customer_barcode_number, connote_number, receiveremail, receiverphone, receivername, receiverstate, receiverzip, receiversuburb, receiveraddr1, receiveraddr2, prod_stock_invoice, barcodempdl, barcodesource, list_mp_ticket_issues, list_resolved_mp_ticket_issues, list_invoice_issues, list_resolved_invoice_issues, selected_invoice_method_id, accounts_cc_email, mpex_po_number, customer_po_number, selected_invoice_cycle_id, terms, customer_terms, screenshot_file, browser, login_email_used, operating_system, phone_used, old_sender_name, old_sender_phone, phone_interaction_count, email_interaction_count, escalated_to_it, senderName, senderAddress, senderEmail, senderPhone, productName, barcodeintegration) { var inlineQty = '<div style="margin-top: -10px"><br/>'; // BUTTONS if (!isNullorEmpty(ticket_id)) { if (isTicketNotClosed(status_value) && selector_type != "customer_issue") { inlineQty += '<button style="float: left; margin-left: 10px; margin-right: 5px; background-color: #FBEA51; color: #103D39; font-weight: 700; border-color: transparent; border-width: 2px; border-radius: 15px; height: 30px" type="button" id="updateticketbutton" onclick="">Update & New Ticket</button>'; inlineQty += '<button style="float: left; margin-left: 5x; margin-right: 5px; background-color: #FBEA51; color: #103D39; font-weight: 700; border-color: transparent; border-width: 2px; border-radius: 15px; height: 30px" type="button" id="updatecloseticketbutton" onclick="">Update & Close Ticket</button>'; } else if (!isTicketNotClosed(status_value)) { inlineQty += '<button style="float: left; margin-left: 10px; margin-right: 5px; background-color: #FBEA51; color: #103D39; font-weight: 700; border-color: transparent; border-width: 2px; border-radius: 15px; height: 30px" type="button" id="reopenticketbutton" onclick="">Reopen Ticket</button>'; } } else { //inlineQty += '<button style="float: left; margin-left: 10px; margin-right: 5px; background-color: #FBEA51; color: #103D39; font-weight: 700; border-color: transparent; border-width: 2px; border-radius: 15px; height: 30px" type="button" id="openticketbutton" onclick="">Save Ticket</button>'; inlineQty += '<button style="float: left; margin-left: 10px; margin-right: 5px; background-color: #FBEA51; color: #103D39; font-weight: 700; border-color: transparent; border-width: 2px; border-radius: 15px; height: 30px" type="button" id="opennewticketbutton" onclick="">Save & New Ticket</button>'; } if (isTicketNotClosed(status_value)) { if (!isNullorEmpty(ticket_id) && selector_type != "customer_issue") { inlineQty += '<button style="float: left; margin-left: 5px; margin-right: 5px; background-color: #f4524d; color: #fff; font-weight: 700; border-color: transparent; border-width: 2px; border-radius: 15px; height: 30px" type="button" id="closeticketbutton" onclick="">Close Ticket</button>'; inlineQty += '<button style="float: left; margin-left: 5px; margin-right: 5px; background-color: #f4524d; color: #fff; font-weight: 700; border-color: transparent; border-width: 2px; border-radius: 15px; height: 30px" type="button" id="closenewticketbutton" onclick="">Close & New Ticket</button>'; inlineQty += '<button style="float: left; margin-left: 5px; margin-right: 5px; background-color: #f4524d; color: #fff; font-weight: 700; border-color: transparent; border-width: 2px; border-radius: 15px; height: 30px" type="button" id="closelostbutton" onclick="">Close Ticket - Lost Item</button>'; if (userId == 409635 || userId == 696992 || userId == 766498) { inlineQty += '<button style="float: left; margin-left: 5px; margin-right: 5px; background-color: #FBEA51; color: #103D39; font-weight: 700; border-color: transparent; border-width: 2px; border-radius: 15px; height: 30px" type="button" id="closeunallocatedbutton" onclick="">Close Unallocated Ticket</button>'; } } else if (!isNullorEmpty(ticket_id) && !isNullorEmpty(escalated_to_it)) { inlineQty += '<button style="float: left; margin-left: 5px; margin-right: 5px; background-color: #f4524d; color: #fff; font-weight: 700; border-color: transparent; border-width: 2px; border-radius: 15px; height: 30px" type="button" id="closeresolvedbutton" onclick="">Close - Resolved Ticket</button>'; inlineQty += '<button style="float: left; margin-left: 5px; margin-right: 5px; background-color: #f4524d; color: #fff; font-weight: 700; border-color: transparent; border-width: 2px; border-radius: 15px; height: 30px" type="button" id="closeunresolvedbutton" onclick="">Close - Unresolved Ticket</button>'; } else { inlineQty += '<button style="float: left; margin-left: 5px; margin-right: 5px; background-color: #f4524d; color: #fff; font-weight: 700; border-color: transparent; border-width: 2px; border-radius: 15px; height: 30px" type="button" id="closeticketbutton" onclick="">Close Ticket</button>'; } } // ESCALATE AND CANCEL BUTTONS log.debug({ title: 'debugging', }); log.debug({ title: "selector_type", details: selector_type }); log.debug({ title: "isTicketNotClosed(status_value)", details: isTicketNotClosed(status_value) }); log.debug({ title: "!isNullorEmpty(ticket_id)", details: !isNullorEmpty(ticket_id) }); log.debug({ title: "userId", details: userId }); if (selector_type == "customer_issue" && isTicketNotClosed(status_value) && !isNullorEmpty(ticket_id) && isNullorEmpty(escalated_to_it)) { inlineQty += '<button style="float: left; margin-left: 5px; margin-right: 5px; background-color: #fc9003; color: #fff; font-weight: 700; border-color: transparent; border-width: 2px; border-radius: 15px; height: 30px" type="button" id="escalaterianne" onclick="">Escalate To IT</button>'; } else if (selector_type == "customer_issue" && isTicketNotClosed(status_value) && !isNullorEmpty(ticket_id) && !isNullorEmpty(escalated_to_it) && status_value != 10 && status_value != 17) { inlineQty += '<button style="float: left; margin-left: 5px; margin-right: 5px; background-color: #fc9003; color: #fff; font-weight: 700; border-color: transparent; border-width: 2px; border-radius: 15px; height: 30px" type="button" id="escalateankith" onclick="">Escalate To Ankith</button>'; } else if (selector_type == "customer_issue" && isTicketNotClosed(status_value) && !isNullorEmpty(ticket_id) && status_value == 10) { inlineQty += '<button style="float: left; margin-left: 5px; margin-right: 5px; background-color: #fc9003; color: #fff; font-weight: 700; border-color: transparent; border-width: 2px; border-radius: 15px; height: 30px" type="button" id="escalateunderdev" onclick="">Set Status to Under Development</button>'; } else if (selector_type == "customer_issue" && isTicketNotClosed(status_value) && !isNullorEmpty(ticket_id) && status_value == 17) { inlineQty += '<button style="float: left; margin-left: 5px; margin-right: 5px; background-color: #fc9003; color: #fff; font-weight: 700; border-color: transparent; border-width: 2px; border-radius: 15px; height: 30px" type="button" id="escalateremoveunderdev" onclick="">Remove Under Development Status</button>'; } else if (isTicketNotClosed(status_value) && !isNullorEmpty(ticket_id) && selector_type != "customer_issue") { inlineQty += '<button style="float: left; margin-left: 5px; margin-right: 5px; background-color: #379E8F; color: #fff; font-weight: 700; border-color: transparent; border-width: 2px; border-radius: 15px; height: 30px" type="button" id="escalatebutton" onclick="">' + escalateButton(status_value) + '</button>'; } if (!isNullorEmpty(ticket_id) && !isTicketNotClosed(status_value)) { inlineQty += '<button style="float: left; margin-left: 10px; margin-right: 5px; background-color: #FBEA51; color: #103D39; font-weight: 700; border-color: transparent; border-width: 2px; border-radius: 15px; height: 30px" type="button" id="cancelbutton" onclick="">Cancel</button>'; } else { inlineQty += '<button style="float: left; margin-left: 5px; margin-right: 5px; background-color: #FBEA51; color: #103D39; font-weight: 700; border-color: transparent; border-width: 2px; border-radius: 15px; height: 30px" type="button" id="cancelbutton" onclick="">Cancel</button>'; } // Title if (!isNullorEmpty(ticket_id)) { inlineQty += '<h1 style="display: inline-block; font-size: 25px; margin-top: 20px; font-weight: 700; color: #103D39; text-align: center; width: 100%">Edit Ticket - MPSD' + ticket_id + '</h1>' } else { inlineQty += '<h1 style="display: inline-block; font-size: 25px; font-weight: 700; color: #103D39; text-align: center; width: 100%">Open New Ticket</h1>' } inlineQty += instructionsBox(); // Tabs headers inlineQty += '<style>.nav > li.active > a, .nav > li.active > a:focus, .nav > li.active > a:hover { background-color: #379E8F; color: #fff }'; inlineQty += '.nav > li > a, .nav > li > a:focus, .nav > li > a:hover { margin-left: 5px; margin-right: 5px; border: 2px solid #379E8F; color: #379E8F; }'; inlineQty += '</style>'; // Ticket details header inlineQty += '<div class="form-group container tickets_details_header_section" style="margin-top: 10px">'; inlineQty += '<div class="row">'; inlineQty += '<div class="col-xs-12" >'; inlineQty += '<span">'; inlineQty += '<ul class="nav nav-pills nav-justified" style="margin:0%; ">'; inlineQty += '<li role="presentation" class="active"><a data-toggle="tab" href="#ticketdetails"><b>TICKET DETAILS</b></a></li>'; inlineQty += '<li role="presentation" class=""><a data-toggle="tab" href="#issues"><b>ISSUES</b></a></li>'; if (!isNullorEmpty(ticket_id)) { inlineQty += '<li role="presentation" class=""><a data-toggle="tab" href="#sendemail"><b>SEND EMAIL</b></a></li>'; } else { inlineQty += '<li role="presentation" class=""><a data-toggle="tab" href="#contactdetails"><b>CONTACT DETAILS</b></a></li>'; } if (!isNullorEmpty(ticket_id)) { inlineQty += '<li role="presentation" class=""><a data-toggle="tab" href="#prevtickets"><b>PREVIOUS TICKETS</b></a></li>'; inlineQty += '<li role="presentation" class=""><a data-toggle="tab" href="#prevemails"><b>PREVIOUS EMAILS</b></a></li>'; } //style="background-color: #379E8F" inlineQty += '</ul>'; inlineQty += '</span>'; inlineQty += '</div></div></div>'; // Tabs content inlineQty += '<div class="tab-content">'; // TICKET DETAILS TAB inlineQty += '<div role="tabpanel" class="tab-pane active" id="ticketdetails">'; inlineQty += customerNumberSection(customer_number, ticket_id, selector_type, escalated_to_it, creator_id); inlineQty += selectorSection(ticket_id, selector_number, selector_id, selector_type, status_value); if (!isNullorEmpty(ticket_id)) { inlineQty += ticketSection(dateISOToNetsuite(date_created), creator_id, creator_name, status, connote_number); inlineQty += externalBarcodeSource(selector_type, barcodeintegration, barcodempdl, barcodesource, productName) } if (isNullorEmpty(ticket_id) || (!isNullorEmpty(ticket_id) && !isNullorEmpty(customer_id)) || !isNullorEmpty(customer_number)) { inlineQty += customerSection(customer_name); inlineQty += daytodayContactSection(daytodayphone, daytodayemail, status_value, selector_type); inlineQty += accountsContactSection(accountsphone, accountsemail, status_value, selector_type); } else if (isNullorEmpty(customer_number) && creator_id == 112209 && !isNullorEmpty(escalated_to_it) && selector_type == "customer_issue" && !isNullorEmpty(ticket_id)) { inlineQty += customerSection(customer_name); inlineQty += daytodayContactSection(daytodayphone, daytodayemail, status_value, selector_type); inlineQty += accountsContactSection(accountsphone, accountsemail, status_value, selector_type); } if (isNullorEmpty(ticket_id) || (!isNullorEmpty(ticket_id) && (selector_type == 'invoice_section'))) { inlineQty += maapBankAccountSection(maap_bank_account_number, maap_parent_bank_account_number, selector_type); } if (isNullorEmpty(ticket_id) || (!isNullorEmpty(ticket_id) && !isNullorEmpty(zee_id)) || !isNullorEmpty(customer_number)) { inlineQty += franchiseeMainContactSection(franchisee_name, zee_main_contact_name, zee_email, zee_main_contact_phone, zee_abn); } inlineQty += mpexStockUsedSection(selector_type, date_stock_used, time_stock_used); inlineQty += finalDeliveryEnquirySection(status_value, selector_type, final_delivery_text, selected_enquiry_status_id, prod_stock_invoice); inlineQty += attachmentsSection(attachments_hyperlink, status_value); if (isNullorEmpty(ticket_id) || (!isNullorEmpty(ticket_id) && (selector_type == 'invoice_number'))) { inlineQty += otherInvoiceFieldsSection(selected_invoice_method_id, accounts_cc_email, mpex_po_number, customer_po_number, selected_invoice_cycle_id, terms, customer_terms, status_value, selector_type); // inlineQty += enquiryMediumSection(list_enquiry_mediums, selected_enquiry_status_id, selector_type); // inlineQty += enquiryCountSection( total_enquiry_count, chat_enquiry_count, phone_enquiry_count, email_enquiry_count, selector_type); inlineQty += openInvoicesSection(ticket_id, selector_type); if (!isNullorEmpty(ticket_id)) { inlineQty += creditMemoSection(selector_type); inlineQty += usageReportSection(selector_type); } } inlineQty += enquiryMediumSection(list_enquiry_mediums, selected_enquiry_status_id, selector_type); inlineQty += enquiryCountSection(total_enquiry_count, chat_enquiry_count, phone_enquiry_count, email_enquiry_count, selector_type, phone_interaction_count, email_interaction_count); if (!isNullorEmpty(ticket_id)) { inlineQty += senderDetails(selector_type, senderName, senderEmail, senderPhone, senderAddress); inlineQty += receiverEmailPhone(selector_type, receiveremail, receiverphone, receivername, receiverstate, receiverzip, receiversuburb, receiveraddr1, receiveraddr2); } //TICKET LABEL DROPDOWN //inlineQty += labelSection(selected_label_id, selector_type, status_value); inlineQty += '</div>'; // ISSUES TAB inlineQty += '<div role="tabpanel" class="tab-pane" id="issues">'; inlineQty += issuesHeader(); inlineQty += customerIssuesSection(ticket_id, selector_type, selector_number, screenshot_file, browser, login_email_used, operating_system, phone_used, old_sender_name, old_sender_phone, status_value); if (selector_type == "barcode_number" || selector_type == "invoice_number") { inlineQty += reminderSection(status_value); } inlineQty += ownerSection(ticket_id, owner_list, status_value); inlineQty += tollIssuesSection(list_toll_issues, list_resolved_toll_issues, status_value, selector_type); inlineQty += mpTicketIssuesSection(list_mp_ticket_issues, list_resolved_mp_ticket_issues, status_value, selector_type); inlineQty += invoiceIssuesSection(list_invoice_issues, list_resolved_invoice_issues, status_value, selector_type); inlineQty += usernoteSection(selector_type, status_value); inlineQty += commentSection(comment, selector_type, status_value); inlineQty += '</div>'; // CONTACT / EMAILS if (!isNullorEmpty(ticket_id)) { inlineQty += '<div role="tabpanel" class="tab-pane" id="sendemail">'; inlineQty += mpexContactSection(); inlineQty += sendEmailSection(ticket_id, status_value, account_manager, list_toll_emails); //inlineQty += closeReopenSubmitTicketButton(ticket_id, status_value); inlineQty += '</div>'; } else { inlineQty += '<div role="tabpanel" class="tab-pane" id="contactdetails">'; inlineQty += mpexContactSection(); //inlineQty += closeReopenSubmitTicketButton(ticket_id, status_value); inlineQty += '</div>'; } // PREV TICKETS + EMAILS TAB if (!isNullorEmpty(ticket_id)) { // PREV TICKETS TAB inlineQty += '<div role="tabpanel" class="tab-pane" id="prevtickets">'; inlineQty += dataTablePreview(); //inlineQty += closeReopenSubmitTicketButton(ticket_id, status_value); inlineQty += '</div>'; inlineQty += '<div role="tabpanel" class="tab-pane" id="prevemails">'; log.debug({ title: 'before prev email - cust id', details: customer_id }); if (!isNullorEmpty(customer_id)) { inlineQty += previousEmailsSection(customer_id); } //inlineQty += closeReopenSubmitTicketButton(ticket_id, status_value); inlineQty += '</div>'; } inlineQty += '</div></div>'; return inlineQty; } /** * The "Customer number" input field. If there is a Ticket ID, then we are on the Edit Ticket page and * this field is pre-filled. * @param {*} customer_number */ function customerNumberSection(customer_number, ticket_id, selector_type, escalated_to_it, creator_id) { if (isNullorEmpty(customer_number)) { customer_number = ''; } // var disable = isNullorEmpty(ticket_id) ? '': 'disabled'; // Ticket details header var inlineQty = '<div class="form-group container tickets_details_header_section">'; inlineQty += '<div class="row">'; inlineQty += '<div class="col-xs-12 heading2" >'; inlineQty += '<h4><span style="background-color: #379E8F" class="label label-default col-xs-12">TICKET DETAILS</span></h4>'; inlineQty += '</div></div></div>'; // Customer number section inlineQty += '<div class="form-group container customer_number_section">'; inlineQty += '<div class="row">'; //Customer number field inlineQty += '<div class="col-xs-12 customer_number">'; inlineQty += '<div class="input-group">'; inlineQty += '<span class="input-group-addon" id="customer_number_text">CUSTOMER NUMBER</span>'; if (customer_number == '' && isNullorEmpty(ticket_id)) { inlineQty += '<input id="customer_number_value" value=" ' + customer_number + ' " class="form-control customer_number">'; } else if (customer_number == '' && creator_id == 112209 && !isNullorEmpty(escalated_to_it) && selector_type == "customer_issue" && !isNullorEmpty(ticket_id)) { inlineQty += '<input id="customer_number_value" value=" ' + customer_number + ' " class="form-control customer_number">'; } else { inlineQty += '<input id="customer_number_value" value=" ' + customer_number + ' " class="form-control customer_number" disabled>'; } inlineQty += '</div></div></div></div>'; //Datatable for all tickets asscoiated to current customer number inlineQty += '<div class="row">'; inlineQty += '<div class="form-group container customer_number_tickets">'; inlineQty += '<style> table {font-size: 12px;text-align: center;border: none;} {font-size: 14px;} table th{text-align: center;} .dataTables_wrapper{width:78%; margin-bottom:40px; margin-left: auto; margin-right: auto; margin-top: auto;} </style>'; inlineQty += '<table cellpadding="15" id="customer_number_tickets_preview" class="table table-responsive table-striped customer tablesorter" cellspacing="0" style="width: 100%;">'; inlineQty += '<thead style="color: white;background-color: #379E8F;">'; inlineQty += '<tr class="text-center">'; inlineQty += '</tr>'; inlineQty += '</thead></table>'; inlineQty += '</div></div>'; return inlineQty; } /** * The "Barcode number" OR "Invoice Number" input field. * If there is a TICKET ID, we are in the "Edit Ticket", so we display the Ticket ID field and the selector field is disabled. * @param {Number} ticket_id * @param {String} selector_number * @param {Number} selector_id * @param {String} selector_type * @param {Number} status_value * @return {String} inlineQty */ function selectorSection(ticket_id, selector_number, selector_id, selector_type, status_value) { if (isNullorEmpty(selector_number)) { selector_number = ''; } var inlineQty = '<div class="form-group container selector_section">'; inlineQty += '<div class="row">'; if (!isNullorEmpty(ticket_id)) { // Ticket ID field inlineQty += '<div class="col-xs-6 ticket_id">'; inlineQty += '<div class="input-group">'; inlineQty += '<span class="input-group-addon" id="ticket_id_text">TICKET ID</span>'; inlineQty += '<input id="ticket_id" value="MPSD' + ticket_id + '" class="form-control ticket_id" disabled />'; inlineQty += '</div></div>'; // Selector Number field inlineQty += '<div class="col-xs-6 selector_number">'; inlineQty += '<div class="input-group">'; switch (selector_type) { case 'barcode_number': inlineQty += '<span class="input-group-addon" id="selector_text">BARCODE NUMBER</span>'; break; case 'invoice_number': inlineQty += '<span class="input-group-addon" id="selector_text">INVOICE NUMBER</span>'; break; } inlineQty += '<input id="selector_value" value="' + selector_number + '" class="form-control selector_value" disabled>'; if (selector_type == 'invoice_number') { // Open Invoice record inlineQty += '<div class="input-group-btn">'; inlineQty += '<button id="open_inv" type="button" class="btn btn-default link_inv" data-inv-id="' + selector_id + '" data-toggle="tooltip" data-placement="top" title="Open Invoice">'; inlineQty += '<span class="glyphicon glyphicon-link"></span>'; inlineQty += '</button>'; inlineQty += '</div>'; // Attach Invoice to email if (isTicketNotClosed(status_value)) { inlineQty += '<div class="input-group-btn"><button style="background-color: #379E8F" id="add_inv" type="button" class="btn btn-success add_inv" data-inv-id="' + selector_id + '" data-toggle="tooltip" data-placement="right" title="Attach to email">'; inlineQty += '<span class="glyphicon glyphicon-plus"></span>'; inlineQty += '</button></div>'; } } inlineQty += '</div></div></div></div>'; } else { inlineQty += '<div class="col-xs-12 selector_number">'; inlineQty += '<div class="input-group">'; //Input group addon text switch (selector_type) { case 'barcode_number': inlineQty += '<span class="input-group-addon" id="selector_text">BARCODE NUMBER</span>'; break; case 'invoice_number': inlineQty += '<span class="input-group-addon" id="selector_text">INVOICE NUMBER</span>'; break; case 'customer_issue': inlineQty += '<span class="input-group-addon" id="selector_text">CUSTOMER ISSUE</span>'; break; } inlineQty += '<div class="input-group-btn">'; inlineQty += '<button tabindex="-1" data-toggle="dropdown" class="btn btn-default dropdown-toggle" type="button">'; inlineQty += '<span class="caret"></span>'; inlineQty += '<span class="sr-only">Toggle Dropdown</span>'; inlineQty += '</button>'; inlineQty += '<ul class="dropdown-menu hide" style="list-style:none;margin: 2px 0 0;">'; inlineQty += '<li><a href="#">BARCODE NUMBER</a></li>'; inlineQty += '<li><a href="#">INVOICE NUMBER</a></li>'; //inlineQty += '<li><a href="#">CUSTOMER APP</a></li>'; inlineQty += '<li><a href="#">CUSTOMER PORTAL</a></li>'; // inlineQty += '<li><a href="#">UPDATE LABEL</a></li>'; inlineQty += '</ul>'; inlineQty += '</div>'; //Input text switch (selector_type) { case 'barcode_number': inlineQty += '<input id="selector_value" class="form-control selector_value" placeholder="MPEN123456">'; break; case 'invoice_number': inlineQty += '<input id="selector_value" class="form-control selector_value" placeholder="INV123456">'; break; case 'customer_app': inlineQty += '<input id="selector_value" class="form-control selector_value" placeholder="Customer App" disabled value="Customer App">'; break; case 'customer_portal': inlineQty += '<input id="selector_value" class="form-control selector_value" placeholder="Customer Portal" disabled value="Customer Portal">'; break; case 'update_label': inlineQty += '<input id="selector_value" class="form-control selector_value" placeholder="Update Label" disabled value="Update Label">'; break; } inlineQty += '</div></div></div></div>'; } return inlineQty; } /** * The informations regarding the ticket being edited. * @param {String} date_created * @param {Number} creator_id * @param {String} creator_name * @param {String} status * @return {String} inlineQty */ function ticketSection(date_created, creator_id, creator_name, status, connote_number) { if (isNullorEmpty(date_created)) { date_created = ''; } if (isNullorEmpty(creator_name)) { creator_name = ''; } if (isNullorEmpty(status)) { status = ''; } var inlineQty = '<div class="form-group container created_status_section">'; inlineQty += '<div class="row">'; // Date created field inlineQty += '<div class="col-xs-6 date_created">'; inlineQty += '<div class="input-group">'; inlineQty += '<span class="input-group-addon" id="date_created_text">DATE CREATED</span>'; inlineQty += '<input id="date_created" value="' + date_created + '" class="form-control date_created" disabled />'; inlineQty += '</div></div>'; // Creator field inlineQty += '<div class="col-xs-6 creator">'; inlineQty += '<div class="input-group">'; inlineQty += '<span class="input-group-addon" id="creator_text">CREATOR</span>'; inlineQty += '<input id="creator" value="' + creator_name + '" data-creator-id="' + creator_id + '" class="form-control creator" disabled />'; inlineQty += '</div></div></div></div>'; // Status Section inlineQty += '<div class="form-group container status_section">'; inlineQty += '<div class="row">'; // Status field inlineQty += '<div class="col-xs-6 status">'; inlineQty += '<div class="input-group">'; inlineQty += '<span class="input-group-addon" id="status_text">STATUS</span>'; inlineQty += '<input id="status" value="' + status + '" class="form-control status" disabled />'; inlineQty += '</div></div>'; // Customer Status field inlineQty += '<div class="col-xs-6 status">'; inlineQty += '<div class="input-group">'; inlineQty += '<span class="input-group-addon" id="status_text">CONNOTE NUMBER</span>'; inlineQty += '<input id="status" value="' + connote_number + '" class="form-control status" disabled />'; inlineQty += '</div></div></div></div>'; return inlineQty; } /** * The Customer name field. * The customer name field should be automatically filled based on the Selector number value. * @param {String} customer_name * @return {String} inlineQty */ function customerSection(customer_name) { if (isNullorEmpty(customer_name)) { customer_name = ''; } // Customer Section var inlineQty = '<div class="form-group container customer_section">'; inlineQty += '<div class="row">'; // Customer name field inlineQty += '<div class="col-xs-12 customer_name">'; inlineQty += '<div class="input-group">'; inlineQty += '<span class="input-group-addon" id="customer_name_text">CUSTOMER NAME</span>'; inlineQty += '<input id="customer_name" value="' + customer_name + '" class="form-control customer_name" disabled>'; inlineQty += '</div></div></div></div>'; return inlineQty; } /** * The day to day phone and email fields of the customer. * These fields should be automatically filled based on the Selector number value. * @param {String} daytodayphone * @param {String} daytodayemail * @param {Number} status_value * @param {String} selector_type * @return {String} inlineQty */ function daytodayContactSection(daytodayphone, daytodayemail, status_value, selector_type) { if (isNullorEmpty(daytodayphone)) { daytodayphone = ''; } if (isNullorEmpty(daytodayemail)) { daytodayemail = ''; } var disabled = 'disabled'; if ((isFinanceRole(userRole)) && isTicketNotClosed(status_value) && selector_type == 'invoice_number') { disabled = ''; } var inlineQty = '<div class="form-group container daytodaycontact_section">'; inlineQty += '<div class="row">'; // Day to day email field inlineQty += '<div class="col-xs-6 daytodayemail_div">'; inlineQty += '<div class="input-group">'; inlineQty += '<span class="input-group-addon" id="daytodayemail_text">DAY-TO-DAY EMAIL</span>'; inlineQty += '<input id="daytodayemail" type="email" value="' + daytodayemail + '" class="form-control daytodayemail" ' + disabled + ' />'; inlineQty += '<div class="input-group-btn">'; inlineQty += '<button type="button" style="background-color: #379E8F" class="btn btn-success add_as_recipient" data-email="' + daytodayemail + '" data-contact-id="" data-firstname="" data-toggle="tooltip" data-placement="right" title="Add as recipient">'; inlineQty += '<span class="glyphicon glyphicon-envelope"></span>'; inlineQty += '</button>'; inlineQty += '</div>'; inlineQty += '</div></div>'; // Day to day phone field inlineQty += '<div class="col-xs-6 daytodayphone_div">'; inlineQty += '<div class="input-group">'; inlineQty += '<span class="input-group-addon" id="daytodayphone_text">DAY-TO-DAY PHONE</span>'; inlineQty += '<input id="daytodayphone" type="tel" value="' + daytodayphone + '" class="form-control daytodayphone" ' + disabled + ' />'; inlineQty += '<div class="input-group-btn"><button type="button" style="background-color: #379E8F" class="btn btn-success" id="call_daytoday_phone"><span class="glyphicon glyphicon-earphone"></span></button></div>'; inlineQty += '</div></div></div></div>'; return inlineQty; } /** * The receiver phone and email fields. * These fields should be automatically filled based on the Selector number value. * @param {String} daytodayphone * @param {String} daytodayemail * @param {Number} status_value * @param {String} selector_type * @return {String} inlineQty */ function senderDetails(selector_type, senderName, senderEmail, senderPhone, senderAddress) { var disabled = 'disabled'; if (isNullorEmpty(senderName) && isNullorEmpty(senderEmail) && isNullorEmpty(senderPhone) && isNullorEmpty(senderAddress)) { disabled = ''; } var inlineQty = ''; if (selector_type == 'barcode_number') { // Sender details header var inlineQty = '<div class="form-group container tickets_details_header_section">'; inlineQty += '<div class="row">'; inlineQty += '<div class="col-xs-12 heading2" >'; inlineQty += '<h4><span style="background-color: #379E8F" class="label label-default col-xs-12">SENDER DETAILS</span></h4>'; inlineQty += '</div></div></div>'; //First Row inlineQty += '<div class="form-group container sendercontact_section">'; inlineQty += '<div class="row">'; // name field inlineQty += '<div class="col-xs-4 sendername_div">'; inlineQty += '<div class="input-group">'; inlineQty += '<span class="input-group-addon" id="sendername_text">NAME</span>'; inlineQty += '<input id="sendername" value="' + senderName + '" class="form-control sendername" ' + disabled + ' />'; inlineQty += '</div></div>'; // Day to day phone field inlineQty += '<div class="col-xs-4 senderphone_div">'; inlineQty += '<div class="input-group">'; inlineQty += '<span class="input-group-addon" id="senderphone_text">PHONE</span>'; inlineQty += '<input id="senderphone" type="tel" value="' + senderPhone + '" class="form-control senderphone" ' + disabled + ' />'; inlineQty += '<div class="input-group-btn"><button type="button" style="background-color: #379E8F" class="btn btn-success" id="call_sender_phone"><span class="glyphicon glyphicon-earphone"></span></button></div>'; inlineQty += '</div></div>'; // Day to day email field inlineQty += '<div class="col-xs-4 senderemail_div">'; inlineQty += '<div class="input-group">'; inlineQty += '<span class="input-group-addon" id="senderemail_text">EMAIL</span>'; inlineQty += '<input id="senderemail" type="email" value="' + senderEmail + '" class="form-control senderemail" ' + disabled + ' />'; inlineQty += '<div class="input-group-btn">'; inlineQty += '<button type="button" style="background-color: #379E8F" class="btn btn-success add_as_recipient" data-email="' + senderEmail + '" data-contact-id="" data-firstname="" data-toggle="tooltip" data-placement="right" title="Add as recipient">'; inlineQty += '<span class="glyphicon glyphicon-envelope"></span>'; inlineQty += '</button>'; inlineQty += '</div>'; inlineQty += '</div></div>'; inlineQty += '</div></div>'; //2nd Row inlineQty += '<div class="form-group container receivercontact2_section">'; inlineQty += '<div class="row">'; // address1 field inlineQty += '<div class="col-xs-12 senderaddress_div">'; inlineQty += '<div class="input-group">'; inlineQty += '<span class="input-group-addon" id="senderaddress_text">ADDRESS</span>'; inlineQty += '<input id="senderaddress" value="' + senderAddress + '" class="form-control senderaddress" ' + disabled + ' />'; inlineQty += '</div></div>'; inlineQty += '</div></div>'; } return inlineQty; } /** * The receiver phone and email fields. * These fields should be automatically filled based on the Selector number value. * @param {String} daytodayphone * @param {String} daytodayemail * @param {Number} status_value * @param {String} selector_type * @return {String} inlineQty */ function receiverEmailPhone(selector_type, receiveremail, receiverphone, receivername, receiverstate, receiverzip, receiversuburb, receiveraddr1, receiveraddr2) { var disabled = 'disabled'; if (isNullorEmpty(receiveremail) && isNullorEmpty(receiveraddr1) && isNullorEmpty(receiveraddr2) && isNullorEmpty(receivername) && isNullorEmpty(receiverphone) && isNullorEmpty(receiverstate) && isNullorEmpty(receiverzip) && isNullorEmpty(receiversuburb)) { disabled = ''; } var inlineQty = ''; if (selector_type == 'barcode_number') { // Receiver details header var inlineQty = '<div class="form-group container tickets_details_header_section">'; inlineQty += '<div class="row">'; inlineQty += '<div class="col-xs-12 heading2" >'; inlineQty += '<h4><span style="background-color: #379E8F" class="label label-default col-xs-12">RECEIVER DETAILS</span></h4>'; inlineQty += '</div></div></div>'; //First Row inlineQty += '<div class="form-group container receivercontact_section">'; inlineQty += '<div class="row">'; // name field inlineQty += '<div class="col-xs-4 receivername_div">'; inlineQty += '<div class="input-group">'; inlineQty += '<span class="input-group-addon" id="receivername_text">NAME</span>'; inlineQty += '<input id="receivername" value="' + receivername + '" class="form-control receivername" ' + disabled + ' />'; inlineQty += '</div></div>'; // Day to day phone field inlineQty += '<div class="col-xs-4 receiverphone_div">'; inlineQty += '<div class="input-group">'; inlineQty += '<span class="input-group-addon" id="receiverphone_text">PHONE</span>'; inlineQty += '<input id="receiverphone" type="tel" value="' + receiverphone + '" class="form-control receiverphone" ' + disabled + ' />'; inlineQty += '<div class="input-group-btn"><button type="button" style="background-color: #379E8F" class="btn btn-success" id="call_receiver_phone"><span class="glyphicon glyphicon-earphone"></span></button></div>'; inlineQty += '</div></div>'; // Day to day email field inlineQty += '<div class="col-xs-4 receiveremail_div">'; inlineQty += '<div class="input-group">'; inlineQty += '<span class="input-group-addon" id="receiveremail_text">EMAIL</span>'; inlineQty += '<input id="receiveremail" type="email" value="' + receiveremail + '" class="form-control receiveremail" ' + disabled + ' />'; inlineQty += '<div class="input-group-btn">'; inlineQty += '<button type="button" style="background-color: #379E8F" class="btn btn-success add_as_recipient" data-email="' + receiveremail + '" data-contact-id="" data-firstname="" data-toggle="tooltip" data-placement="right" title="Add as recipient">'; inlineQty += '<span class="glyphicon glyphicon-envelope"></span>'; inlineQty += '</button>'; inlineQty += '</div>'; inlineQty += '</div></div>'; inlineQty += '</div></div>'; //2nd Row inlineQty += '<div class="form-group container receivercontact2_section">'; inlineQty += '<div class="row">'; // address1 field inlineQty += '<div class="col-xs-6 receiveraddr1_div">'; inlineQty += '<div class="input-group">'; inlineQty += '<span class="input-group-addon" id="receiveraddr1_text">ADDRESS1</span>'; inlineQty += '<input id="receiveraddr1" value="' + receiveraddr1 + '" class="form-control receiveraddr1" ' + disabled + ' />'; inlineQty += '</div></div>'; // address2 field inlineQty += '<div class="col-xs-6 receiveraddr2_div">'; inlineQty += '<div class="input-group">'; inlineQty += '<span class="input-group-addon" id="receiveraddr2_text">ADDRESS2</span>'; inlineQty += '<input id="receiveraddr2" value="' + receiveraddr2 + '" class="form-control receiveraddr2" ' + disabled + ' />'; inlineQty += '</div></div>'; inlineQty += '</div></div>'; //3rd Row inlineQty += '<div class="form-group container receivercontact3_section">'; inlineQty += '<div class="row">'; // suburb field inlineQty += '<div class="col-xs-4 receiversuburb_div">'; inlineQty += '<div class="input-group">'; inlineQty += '<span class="input-group-addon" id="receiversuburb_text">SUBURB</span>'; inlineQty += '<input id="receiversuburb" value="' + receiversuburb + '" class="form-control receiversuburb" ' + disabled + ' />'; inlineQty += '</div></div>'; // postcode field inlineQty += '<div class="col-xs-4 receiverzip_div">'; inlineQty += '<div class="input-group">'; inlineQty += '<span class="input-group-addon" id="receiverzip_text">POSTCODE</span>'; inlineQty += '<input id="receiverzip" value="' + receiverzip + '" class="form-control receiverzip" ' + disabled + ' />'; inlineQty += '</div></div>'; // state field inlineQty += '<div class="col-xs-4 receiverstate_div">'; inlineQty += '<div class="input-group">'; inlineQty += '<span class="input-group-addon" id="receiverstate_text">STATE</span>'; inlineQty += '<input id="receiverstate" value="' + receiverstate + '" class="form-control receiverstate" ' + disabled + ' />'; inlineQty += '</div></div>'; inlineQty += '</div></div>'; } return inlineQty; } /** * The accounts phone and email fields of the customer. * These fields should be automatically filled based on the Invoice number value. * @param {String} accountsphone * @param {String} accountsemail * @param {Number} status_value * @param {String} selector_type * @return {String} inlineQty */ function accountsContactSection(accountsphone, accountsemail, status_value, selector_type) { if (isNullorEmpty(accountsphone)) { accountsphone = ''; } if (isNullorEmpty(accountsemail)) { accountsemail = ''; } if (selector_type == 'invoice_number') { var inlineQty = '<div class="form-group container accountscontact_section">'; if (isFinanceRole(userRole) && isTicketNotClosed(status_value)) { var disabled = ''; } else { var disabled = 'disabled'; } } else { var inlineQty = '<div class="form-group container accountscontact_section hide">'; var disabled = 'disabled'; } inlineQty += '<div class="row">'; // Accounts email field inlineQty += '<div class="col-xs-6 accountsemail_div">'; inlineQty += '<div class="input-group">'; inlineQty += '<span class="input-group-addon" id="accountsemail_text">ACCOUNTS EMAIL</span>'; inlineQty += '<input id="accountsemail" type="email" value="' + accountsemail + '" class="form-control accountsemail" ' + disabled + ' />'; inlineQty += '<div class="input-group-btn">'; inlineQty += '<button type="button" style="background-color: #379E8F" class="btn btn-success add_as_recipient" data-email="' + accountsemail + '" data-contact-id="" data-firstname="" data-toggle="tooltip" data-placement="right" title="Add as recipient">'; inlineQty += '<span class="glyphicon glyphicon-envelope"></span>'; inlineQty += '</button>'; inlineQty += '</div>'; inlineQty += '</div></div>'; // Accounts phone field inlineQty += '<div class="col-xs-6 accountsphone_div">'; inlineQty += '<div class="input-group">'; inlineQty += '<span class="input-group-addon" id="accountsphone_text">ACCOUNTS PHONE</span>'; inlineQty += '<input id="accountsphone" type="tel" value="' + accountsphone + '" class="form-control accountsphone" ' + disabled + ' />'; inlineQty += '<div class="input-group-btn"><button type="button" style="background-color: #379E8F" class="btn btn-success" id="call_accounts_phone"><span class="glyphicon glyphicon-earphone"></span></button></div>'; inlineQty += '</div></div></div></div>'; return inlineQty; } /** * * @param {Number} maap_bank_account_number * @param {Number} maap_parent_bank_account_number * @param {String} selector_type * @returns {String} inlineQty */ function maapBankAccountSection(maap_bank_account_number, maap_parent_bank_account_number, selector_type) { switch (selector_type) { case 'barcode_number': var inlineQty = '<div class="form-group container accounts_number_section hide">'; break; case 'invoice_number': var inlineQty = '<div class="form-group container accounts_number_section">'; break; } inlineQty += '<div class="row">'; // MAAP Bank Account # field inlineQty += '<div class="col-xs-6 account_number_div">'; inlineQty += '<div class="input-group">'; inlineQty += '<span class="input-group-addon" id="account_number_text">MAAP BANK ACCOUNT #</span>'; inlineQty += '<input id="account_number" type="number" value="' + maap_bank_account_number + '" class="form-control account_number" disabled />'; inlineQty += '</div></div>'; // MAAP Parent Bank Account # field inlineQty += '<div class="col-xs-6 parent_account_number_div">'; inlineQty += '<div class="input-group">'; inlineQty += '<span class="input-group-addon" id="parent_account_number_text">MAAP PARENT BANK ACCOUNT #</span>'; inlineQty += '<input id="parent_account_number" type="number" value="' + maap_parent_bank_account_number + '" class="form-control parent_account_number" disabled />'; inlineQty += '</div></div></div></div>'; return inlineQty; } /** * The Franchisee name, and its main contact name and phone number fields. * These fields should be automatically filled based on the Selector number value. * @param {String} franchisee_name * @param {String} zee_main_contact_name * @param {String} zee_email * @param {String} zee_main_contact_phone * @param {String} zee_abn * @return {String} inlineQty */ function franchiseeMainContactSection(franchisee_name, zee_main_contact_name, zee_email, zee_main_contact_phone, zee_abn) { if (isNullorEmpty(franchisee_name)) { franchisee_name = ''; } if (isNullorEmpty(zee_main_contact_name)) { zee_main_contact_name = ''; } if (isNullorEmpty(zee_email)) { zee_email = ''; } if (isNullorEmpty(zee_main_contact_phone)) { zee_main_contact_phone = ''; } if (isNullorEmpty(zee_abn)) { zee_abn = ''; } var inlineQty = '<div class="form-group container zee_main_contact_section">'; inlineQty += '<div class="row">'; // Franchisee name field inlineQty += '<div class="col-xs-6 franchisee_name">'; inlineQty += '<div class="input-group">'; inlineQty += '<span class="input-group-addon" id="franchisee_name_text">FRANCHISEE NAME</span>'; inlineQty += '<input id="franchisee_name" value="' + franchisee_name + '" class="form-control franchisee_name" disabled>'; inlineQty += '</div></div>'; // Franchisee main contact name field inlineQty += '<div class="col-xs-6 zee_main_contact_name">'; inlineQty += '<div class="input-group">'; inlineQty += '<span class="input-group-addon" id="zee_main_contact_name_text">MAIN CONTACT</span>'; inlineQty += '<input id="zee_main_contact_name" value="' + zee_main_contact_name + '" class="form-control zee_main_contact_name" disabled>'; inlineQty += '</div></div></div></div>'; // Franchisee contact details inlineQty += '<div class="form-group container zee_main_contact_section">'; inlineQty += '<div class="row">'; // Franchisee email field inlineQty += '<div class="col-xs-12 zee_email">'; inlineQty += '<div class="input-group">'; inlineQty += '<span class="input-group-addon" id="zee_email_text">FRANCHISEE EMAIL</span>'; inlineQty += '<input id="zee_email" type="email" value="' + zee_email + '" class="form-control accountsemail" disabled />'; inlineQty += '<div class="input-group-btn">'; var zee_contact_id = '0'; inlineQty += '<button type="button" style="background-color: #379E8F" class="btn btn-success add_as_recipient" data-email="' + zee_email + '" data-contact-id="' + zee_contact_id + '" data-firstname="' + franchisee_name + '" data-toggle="tooltip" data-placement="right" title="Add as recipient">'; inlineQty += '<span class="glyphicon glyphicon-envelope"></span>'; inlineQty += '</button>'; inlineQty += '</div>'; inlineQty += '</div></div></div></div>'; // Franchisee phone and ABN details inlineQty += '<div class="form-group container zee_main_contact_section">'; inlineQty += '<div class="row">'; // Franchisee main contact phone field inlineQty += '<div class="col-xs-6 zee_main_contact_phone">' inlineQty += '<div class="input-group">' inlineQty += '<span class="input-group-addon" id="zee_main_contact_phone_text">FRANCHISEE PHONE</span>'; inlineQty += '<input id="zee_main_contact_phone" type="tel" value="' + zee_main_contact_phone + '" class="form-control zee_main_contact_phone" disabled />'; inlineQty += '<div class="input-group-btn"><button style="background-color: #379E8F" type="button" class="btn btn-success" id="call_zee_main_contact_phone"><span class="glyphicon glyphicon-earphone"></span></button>'; inlineQty += '</div>'; inlineQty += '</div></div>'; // Franchisee ABN number inlineQty += '<div class="col-xs-6 zee_abn">' inlineQty += '<div class="input-group">' inlineQty += '<span class="input-group-addon" id="zee_abn_text">FRANCHISEE ABN</span>' inlineQty += '<input id="zee_abn" class="form-control zee_abn" value="' + zee_abn + '" disabled>' inlineQty += '</div></div></div></div>'; return inlineQty; } /** * The MPEX Date and Time Stock used fields. * Visible only for the barcode records. * @param {String} selector_type * @param {String} date_stock_used * @param {String} time_stock_used * @return {String} inlineQty */ function mpexStockUsedSection(selector_type, date_stock_used, time_stock_used) { if (isNullorEmpty(date_stock_used)) { date_stock_used = '' } if (isNullorEmpty(time_stock_used)) { time_stock_used = '' } var hide_class = (selector_type == 'barcode_number') ? '' : 'hide'; // MPEX Stock Used Section var inlineQty = '<div class="form-group container mpex_stock_used_section ' + hide_class + '">'; inlineQty += '<div class="row">'; // Date Stock Used inlineQty += ' <div class="col-xs-6 date_stock_used">'; inlineQty += '<div class="input-group">'; inlineQty += '<span class="input-group-addon" id="date_stock_used_text">DATE STOCK USED</span>'; inlineQty += '<input id="date_stock_used" class="form-control date_stock_used" value="' + date_stock_used + '" disabled>'; inlineQty += '</div></div>'; // Time Stock Used inlineQty += '<div class="col-xs-6 time_stock_used">'; inlineQty += '<div class="input-group">'; inlineQty += '<span class="input-group-addon" id="time_stock_used_text">TIME STOCK USED</span>'; inlineQty += '<input id="time_stock_used" class="form-control time_stock_used" value="' + time_stock_used + '" disabled>'; inlineQty += '</div></div></div></div>'; return inlineQty; } /** * The MPEX Final Delivery field is visible only for the barcode records. * The Enquiry Status field is not disabled only for the ticket that have not yet been opened. * @param {Number} status_value * @param {String} selector_type * @param {String} final_delivery_text * @param {Number} selected_enquiry_status_id * @return {String} inlineQty */ function finalDeliveryEnquirySection(status_value, selector_type, final_delivery_text, selected_enquiry_status_id, prod_stock_invoice) { if (isNullorEmpty(final_delivery_text)) { final_delivery_text = '' } if (isNullorEmpty(selected_enquiry_status_id)) { selected_enquiry_status_id = '' } var barcode_hide_class = (selector_type == 'barcode_number') ? '' : 'hide'; var nb_col_enquiry_section = (selector_type == 'barcode_number') ? '6' : '12'; var enquiry_disabled = (isTicketNotClosed(status_value)) ? '' : 'disabled'; // Final Delivery + Enquiry Status Section var inlineQty = '<div class="form-group container final_delivery_enquiry_status_section">'; inlineQty += '<div class="row">'; // Final Delivery inlineQty += '<div class="col-xs-6 final_delivery ' + barcode_hide_class + '">'; inlineQty += '<div class="input-group">'; inlineQty += '<span class="input-group-addon" id="final_delivery_text">FINAL DELIVERY</span>'; inlineQty += '<input id="final_delivery" class="form-control final_delivery" value="' + final_delivery_text + '" disabled>'; inlineQty += '</div></div>'; // Final Delivery inlineQty += '<div class="col-xs-6 invoice ' + barcode_hide_class + '">'; inlineQty += '<div class="input-group">'; inlineQty += '<span class="input-group-addon" id="invoice_text">INVOICE</span>'; inlineQty += '<input id="invoice" class="form-control invoice" value="' + prod_stock_invoice + '" disabled>'; inlineQty += '</div></div>'; inlineQty += '</div></div>'; return inlineQty; } /** * Ticket Label Section for if label on mpex was Printed or Handwritten * @param {Number} selected_label_id * @return {String} inlineQty */ function labelSection(selected_label_id, selector_type, status_value) { if (isNullorEmpty(selected_label_id)) { selected_label_id = ''; } var barcodeHideClass = (selector_type == 'barcode_number') ? '' : 'hide'; var labeldisabled = (isTicketNotClosed(status_value)) ? '' : 'disabled'; var inlineQty = '<div class="form-group container label_section ' + barcodeHideClass + '">'; inlineQty += '<div class="row">'; inlineQty += '<div class="col-xs-6 label_div">'; inlineQty += '<div class="input-group">'; inlineQty += '<span class="input-group-addon" id="label_text">TICKET LABEL</span>'; inlineQty += '<select id="label_status" class="form-control label_status" ' + labeldisabled + '>'; inlineQty += '<option></option>'; var labelColumns = new Array(); labelColumns[0] = search.createColumn({ name: 'name' }); labelColumns[1] = search.createColumn({ name: 'internalId' }); var labelResultSet = search.create({ type: 'customlist_mp_ticket_label', columns: labelColumns, }); labelResultSet.run().each(function (labelResult) { var labelName = labelResult.getValue('name'); var labelId = labelResult.getValue('internalId'); if (selected_label_id == labelId) { inlineQty += '<option value="' + labelId + '"selected>' + labelName + '</option>'; } else { inlineQty += '<option value="' + labelId + '">' + labelName + '</option>'; } return inlineQty; }); inlineQty += '</select>'; inlineQty += '</div></div></div></div>'; return inlineQty; } /** * Section containing enquiry medium type and the enquiry status of the ticket enquiry * @param list_enquiry_mediums {String}atus and * @param total_enquiry_count {Number} * @param selector_type {String} * @param status_value {Number} * @returns {string} */ function enquiryMediumSection(list_enquiry_mediums, selected_enquiry_status_id, selector_type) { //Search for enquiry mediums var hasEnquiryMediums = (!isNullorEmpty(list_enquiry_mediums)); var enquiryMediumColumns = new Array(); enquiryMediumColumns[0] = search.createColumn({ name: 'name' }); enquiryMediumColumns[1] = search.createColumn({ name: 'internalId' }); var enquiryMediumResultSet = search.create({ type: 'customlist_ticket_enquiry_mediums', columns: enquiryMediumColumns, }); //Ticket Enquiry Header // var inlineQty = '<div class="form-group container ticket_enquiry_header_section">'; // inlineQty += '<div class="row">'; // inlineQty += '<div class="col-xs-12 heading2">'; // inlineQty += '<h4><span style="background-color: #379E8F" class="label label-default col-xs-12">TICKET ENQUIRY DETAILS</span></h4>'; // inlineQty += '</div></div></div>'; //Enquiry Medium HTML var inlineQty = '<div class="form-group container enquiry_medium_section">'; inlineQty += '<div class="row">'; // inlineQty += '<div class="col-xs-6 enquiry_medium_div">'; // inlineQty += '<div class="input-group">'; // inlineQty += '<span class="input-group-addon" id="enquiry_medium_text">ENQUIRY MEDIUM</span>'; // inlineQty += '<select multiple id="enquiry_medium_status" class="form-control enquiry_medium_status" size="'+ enquiryMediumResultSet.length + '" disabled>'; // enquiryMediumResultSet.run().each(function (enquiryMediumResult) { // var enquiryMediumName = enquiryMediumResult.getValue('name'); // var enquiryMediumId = enquiryMediumResult.getValue('internalId'); // var selected = false; // if(hasEnquiryMediums){ // selected = (list_enquiry_mediums.indexOf(enquiryMediumId) !== -1); // } // if(selected) { // inlineQty += '<option value="' + enquiryMediumId + '"selected>' + enquiryMediumName + '</option>'; // }else{ // inlineQty += '<option value="' + enquiryMediumId + '">' + enquiryMediumName + '</option>'; // } // return true; // }); // inlineQty += '</select>'; // inlineQty += '</div></div>'; // Enquiry Status var enquiry_status_columns = new Array(); enquiry_status_columns[0] = search.createColumn({ name: 'name' }); enquiry_status_columns[1] = search.createColumn({ name: 'internalId' }); var enquiryStatusResultSet = search.create({ type: 'customlist_mp_ticket_enquiry', columns: enquiry_status_columns, }); inlineQty += '<div class="col-xs-6 enquiry_status_div">'; inlineQty += '<div class="input-group">'; inlineQty += '<span class="input-group-addon" id="enquiry_status_text">ENQUIRY STATUS</span>'; inlineQty += '<select id="enquiry_status" class="form-control enquiry_status">'; inlineQty += '<option></option>'; enquiryStatusResultSet.run().each(function (enquiryStatusResult) { var enquiry_status_name = enquiryStatusResult.getValue('name'); var enquiry_status_id = enquiryStatusResult.getValue('internalId'); if (enquiry_status_id == selected_enquiry_status_id) { inlineQty += '<option value="' + enquiry_status_id + '" selected>' + enquiry_status_name + '</option>'; } else { inlineQty += '<option value="' + enquiry_status_id + '">' + enquiry_status_name + '</option>'; } return true; }); inlineQty += '</select>'; inlineQty += '</div></div></div></div>'; return inlineQty; } /** * Section containing the total enquiry count and its breakdwn counts of chat, phone and email * @param total_enquiry_count * @param chat_enquiry_count * @param phone_enquiry_count * @param email_enquiry_count * @param selector_type * @returns {string} */ function enquiryCountSection(total_enquiry_count, chat_enquiry_count, phone_enquiry_count, email_enquiry_count, selector_type, phone_interaction_count, email_interaction_count) { if (isNullorEmpty(total_enquiry_count)) { total_enquiry_count = 0; } if (isNullorEmpty(chat_enquiry_count)) { chat_enquiry_count = 0; } if (isNullorEmpty(phone_enquiry_count)) { phone_enquiry_count = 0; } if (isNullorEmpty(email_enquiry_count)) { email_enquiry_count = 0; } if (isNullorEmpty(phone_interaction_count)) { phone_interaction_count = 0; } if (isNullorEmpty(email_interaction_count)) { email_interaction_count = 0; } //Total Enquiry Count HTML // var inlineQty = '<div class="form-group container enquiry_count_section">'; // inlineQty += '<div class="row">'; // inlineQty += '<div class="col-xs-12 total_enquiry_count_div">'; // inlineQty += '<div class="input-group">'; // inlineQty += '<span class="input-group-addon" id="total_enquiry_count_text">ENQUIRY COUNT</span>'; // inlineQty += '<input id="total_enquiry_count" class="form-control enquiry_count" value="' + total_enquiry_count + '" disabled />'; // inlineQty += '</div></div></div></div>'; //Enquiries by chat count var inlineQty = '<div class="form-group container enquiry_count_breakdown_section">'; inlineQty += '<div class="row">'; inlineQty += '<div class="col-xs-4 enquiry_count_by_chat">'; inlineQty += '<div class="input-group">'; inlineQty += '<span class="input-group-addon" id="enquiry_count_by_chat_text"> WEBSITE ENQUIRY </span>'; inlineQty += '<input id="enquiry_count_by_chat" value="' + chat_enquiry_count + '" class="form-control enquiry_count_by_chat" disabled>'; inlineQty += '<div class="input-group-btn">'; inlineQty += '<button type="button" style="background-color: #379E8F" class="btn btn-success increment_enquiry_count_by_chat" data-firstname="" data-toggle="tooltip" data-placement="right" title="Increment Chat Enquiry Count">'; inlineQty += '<span class="glyphicon glyphicon-plus"></span>'; inlineQty += '</button>'; inlineQty += '<button type="button" class="btn btn-danger decrement_enquiry_count_by_chat" data-firstname="" data-toggle="tooltip" data-placement="right" title="Decrement Chat Enquiry Count">'; inlineQty += '<span class="glyphicon glyphicon-minus"></span>'; inlineQty += '</button>'; inlineQty += '</div></div></div>'; inlineQty += '<div class="col-xs-4 enquiry_count_by_phone">'; inlineQty += '<div class="input-group">'; inlineQty += '<span class="input-group-addon" id="enquiry_count_by_phone_text"> PHONE ENQUIRY </span>'; inlineQty += '<input id="enquiry_count_by_phone" value="' + phone_enquiry_count + '" class="form-control enquiry_count_by_phone" disabled>'; inlineQty += '<div class="input-group-btn">'; inlineQty += '<button type="button" style="background-color: #379E8F" class="btn btn-success increment_enquiry_count_by_phone" data-firstname="" data-toggle="tooltip" data-placement="right" title="Increment Phone Enquiry Count">'; inlineQty += '<span class="glyphicon glyphicon-plus"></span>'; inlineQty += '</button>'; inlineQty += '<button type="button" class="btn btn-danger decrement_enquiry_count_by_phone" data-firstname="" data-toggle="tooltip" data-placement="right" title="Decrement Phone Enquiry Count">'; inlineQty += '<span class="glyphicon glyphicon-minus"></span>'; inlineQty += '</button>'; inlineQty += '</div></div></div>'; inlineQty += '<div class="col-xs-4 enquiry_count_by_email">'; inlineQty += '<div class="input-group">'; inlineQty += '<span class="input-group-addon" id="enquiry_count_by_email_text"> EMAIL ENQUIRY </span>'; inlineQty += '<input id="enquiry_count_by_email" value="' + email_enquiry_count + '" class="form-control enquiry_count_by_email" disabled>'; inlineQty += '<div class="input-group-btn">'; inlineQty += '<button type="button" style="background-color: #379E8F" class="btn btn-success increment_enquiry_count_by_email" data-firstname="" data-toggle="tooltip" data-placement="right" title="Increment Email Enquiry Count">'; inlineQty += '<span class="glyphicon glyphicon-plus"></span>'; inlineQty += '</button>'; inlineQty += '<button type="button" class="btn btn-danger decrement_enquiry_count_by_email" data-firstname="" data-toggle="tooltip" data-placement="right" title="Decrement Email Enquiry Count">'; inlineQty += '<span class="glyphicon glyphicon-minus"></span>'; inlineQty += '</button>'; inlineQty += '</div></div></div></div></div>'; if (selector_type == "customer_issue") { inlineQty += '<div class="form-group container interaction_count_breakdown_section">'; inlineQty += '<div class="row">'; inlineQty += '<div class="col-xs-6 interaction_count_by_phone">'; inlineQty += '<div class="input-group">'; inlineQty += '<span class="input-group-addon" id="interaction_count_by_phone_text"> PHONE INTERACTION </span>'; inlineQty += '<input id="interaction_count_by_phone" value="' + phone_interaction_count + '" class="form-control interaction_count_by_phone" disabled>'; inlineQty += '<div class="input-group-btn">'; inlineQty += '<button type="button" style="background-color: #379E8F" class="btn btn-success increment_interaction_count_by_phone" data-firstname="" data-toggle="tooltip" data-placement="right" title="Increment Phone Interaction Count">'; inlineQty += '<span class="glyphicon glyphicon-plus"></span>'; inlineQty += '</button>'; inlineQty += '<button type="button" class="btn btn-danger decrement_interaction_count_by_phone" data-firstname="" data-toggle="tooltip" data-placement="right" title="Decrement Phone interaction Count">'; inlineQty += '<span class="glyphicon glyphicon-minus"></span>'; inlineQty += '</button>'; inlineQty += '</div></div></div>'; inlineQty += '<div class="col-xs-6 interaction_count_by_email">'; inlineQty += '<div class="input-group">'; inlineQty += '<span class="input-group-addon" id="interaction_count_by_email_text"> EMAIL INTERACTION </span>'; inlineQty += '<input id="interaction_count_by_email" value="' + email_interaction_count + '" class="form-control interaction_count_by_email" disabled>'; inlineQty += '<div class="input-group-btn">'; inlineQty += '<button type="button" style="background-color: #379E8F" class="btn btn-success increment_interaction_count_by_email" data-firstname="" data-toggle="tooltip" data-placement="right" title="Increment Email Interaction Count">'; inlineQty += '<span class="glyphicon glyphicon-plus"></span>'; inlineQty += '</button>'; inlineQty += '<button type="button" class="btn btn-danger decrement_interaction_count_by_email" data-firstname="" data-toggle="tooltip" data-placement="right" title="Decrement Email Interaction Count">'; inlineQty += '<span class="glyphicon glyphicon-minus"></span>'; inlineQty += '</button>'; inlineQty += '</div></div></div></div></div>'; } return inlineQty; } /** * These fields should be displayed only for an Invoice ticket, and be edited only by the finance team. * - Invoice Method field * - Accounts cc email field * - MPEX PO # field * - Customer PO # field * - MPEX Invoicing Cycle field * @param {Number} selected_invoice_method_id * @param {String} accounts_cc_email * @param {String} mpex_po_number * @param {String} customer_po_number * @param {Number} selected_invoice_cycle_id * @param {Number} terms * @param {String} customer_terms * @param {Number} status_value * @param {String} selector_type * @return {String} inlineQty */ function otherInvoiceFieldsSection(selected_invoice_method_id, accounts_cc_email, mpex_po_number, customer_po_number, selected_invoice_cycle_id, terms, customer_terms, status_value, selector_type) { if (isNullorEmpty(accounts_cc_email)) { accounts_cc_email = '' } if (isNullorEmpty(mpex_po_number)) { mpex_po_number = '' } if (isNullorEmpty(customer_po_number)) { customer_po_number = '' } if (isNullorEmpty(customer_terms)) { customer_terms = '' } var invoice_method_columns = new Array(); invoice_method_columns[0] = search.createColumn({ name: 'name' }); invoice_method_columns[1] = search.createColumn({ name: 'internalId' }); var invoiceMethodResultSet = search.create({ type: 'customlist_invoice_method', columns: invoice_method_columns, }); switch (selector_type) { case 'barcode_number': var inlineQty = '<div class="form-group container invoice_method_accounts_cc_email_section hide">'; var disabled = 'disabled'; break; case 'invoice_number': var inlineQty = '<div class="form-group container invoice_method_accounts_cc_email_section">'; if (isFinanceRole(userRole) && isTicketNotClosed(status_value)) { var disabled = ''; } else { var disabled = 'disabled'; } break; } inlineQty += '<div class="row">'; // Invoice Method field inlineQty += '<div class="col-xs-6 invoice_method_div">'; inlineQty += '<div class="input-group">'; inlineQty += '<span class="input-group-addon" id="invoice_method_text">INVOICE METHOD</span>'; inlineQty += '<select id="invoice_method" class="form-control" ' + disabled + '>'; inlineQty += '<option></option>'; invoiceMethodResultSet.run().each(function (invoiceMethodResult) { var invoice_method_name = invoiceMethodResult.getValue('name'); var invoice_method_id = invoiceMethodResult.getValue('internalId'); if (invoice_method_id == selected_invoice_method_id) { inlineQty += '<option value="' + invoice_method_id + '" selected>' + invoice_method_name + '</option>'; } else { inlineQty += '<option value="' + invoice_method_id + '">' + invoice_method_name + '</option>'; } return true; }); inlineQty += '</select>'; inlineQty += '</div></div>'; // Accounts cc email field --> inlineQty += '<div class="col-xs-6 accounts_cc_email_div">'; inlineQty += '<div class="input-group">'; inlineQty += '<span class="input-group-addon" id="accounts_cc_email_text">ACCOUNTS CC EMAIL</span>'; inlineQty += '<input id="accounts_cc_email" type="email" value="' + accounts_cc_email + '" class="form-control accounts_cc_email" ' + disabled + '/>'; inlineQty += '<div class="input-group-btn">'; inlineQty += '<button type="button" style="background-color: #379E8F" class="btn btn-success add_as_recipient" data-email="' + accounts_cc_email + '" data-contact-id="" data-firstname="" data-toggle="tooltip" data-placement="right" title="Add as recipient">'; inlineQty += '<span class="glyphicon glyphicon-envelope"></span>'; inlineQty += '</button>'; inlineQty += '</div>'; inlineQty += '</div></div></div></div>'; switch (selector_type) { case 'barcode_number': inlineQty += '<div class="form-group container mpex_customer_po_number_section hide">'; break; case 'invoice_number': inlineQty += '<div class="form-group container mpex_customer_po_number_section">'; break; } inlineQty += '<div class="row">'; // MPEX PO # inlineQty += '<div class="col-xs-6 mpex_po_number_div">'; inlineQty += '<div class="input-group">'; inlineQty += '<span class="input-group-addon" id="mpex_po_number_text">MPEX PO #</span>'; inlineQty += '<input id="mpex_po_number" value="' + mpex_po_number + '" class="form-control mpex_po_number" ' + disabled + '/>'; inlineQty += '</div></div>'; // Customer PO # inlineQty += '<div class="col-xs-6 customer_po_number_div">'; inlineQty += '<div class="input-group">'; inlineQty += '<span class="input-group-addon" id="customer_po_number_text">CUSTOMER PO #</span>'; inlineQty += '<input id="customer_po_number" value="' + customer_po_number + '" class="form-control customer_po_number" ' + disabled + '/>'; inlineQty += '</div></div></div></div>'; // Terms fields switch (selector_type) { case 'barcode_number': inlineQty += '<div class="form-group container terms_section hide">'; break; case 'invoice_number': inlineQty += '<div class="form-group container terms_section">'; break; } inlineQty += '<div class="row">'; // Terms inlineQty += '<div class="col-xs-6 terms_div">'; inlineQty += '<div class="input-group">'; inlineQty += '<span class="input-group-addon" id="terms_text">TERMS</span>'; // Find the text related to the terms value. var terms_options = [{ "value": "", "text": "" }, { "value": "5", "text": "1% 10 Net 30" }, { "value": "6", "text": "2% 10 Net 30" }, { "value": "4", "text": "Due on receipt" }, { "value": "1", "text": "Net 15 Days" }, { "value": "2", "text": "Net 30 Days" }, { "value": "8", "text": "Net 45 Days" }, { "value": "3", "text": "Net 60 Days" }, { "value": "7", "text": "Net 7 Days" }, { "value": "9", "text": "Net 90 Days" }]; var terms_option = findObjectByKey(terms_options, "value", terms); var terms_text = isNullorEmpty(terms_option) ? '' : terms_option.text; inlineQty += '<input id="terms" class="form-control terms" value="' + terms_text + '" disabled/>'; inlineQty += '</div></div>'; // Customer's terms inlineQty += '<div class="col-xs-6 customers_terms_div">'; inlineQty += '<div class="input-group">'; inlineQty += '<span class="input-group-addon" id="customers_terms_text">' + "CUSTOMER'S TERMS</span>"; inlineQty += '<input id="customers_terms" class="form-control customers_terms" value="' + customer_terms + '" ' + disabled + '/>'; inlineQty += '</div></div></div></div>'; // MPEX Invoicing Cycle var invoice_cycle_columns = new Array(); invoice_cycle_columns[0] = search.createColumn({ name: 'name' }); invoice_cycle_columns[1] = search.createColumn({ name: 'internalId' }); var invoiceCycleResultSet = search.create({ type: 'customlist_invoicing_cyle', columns: invoice_cycle_columns, }) switch (selector_type) { case 'barcode_number': inlineQty += '<div class="form-group container mpex_invoicing_cycle_section hide">'; break; case 'invoice_number': inlineQty += '<div class="form-group container mpex_invoicing_cycle_section">'; break; } inlineQty += '<div class="row">'; inlineQty += '<div class="col-xs-12 mpex_invoicing_cycle_div">'; inlineQty += '<div class="input-group">'; inlineQty += '<span class="input-group-addon" id="mpex_invoicing_cycle_text">MPEX INVOICING CYCLE</span>'; inlineQty += '<select id="mpex_invoicing_cycle" class="form-control mpex_invoicing_cycle" ' + disabled + '>'; inlineQty += '<option></option>'; invoiceCycleResultSet.run().each(function (invoiceCycleResult) { var invoice_cycle_name = invoiceCycleResult.getValue('name'); var invoice_cycle_id = invoiceCycleResult.getValue('internalId'); if (invoice_cycle_id == selected_invoice_cycle_id) { inlineQty += '<option value="' + invoice_cycle_id + '" selected>' + invoice_cycle_name + '</option>'; } else { inlineQty += '<option value="' + invoice_cycle_id + '">' + invoice_cycle_name + '</option>'; } return true; }); inlineQty += '</select>'; inlineQty += '</div></div></div></div>'; return inlineQty; } /** * The Attachments field (an editable hyperlink) * @param {String} attachments_hyperlink * @param {Number} status_value * @returns {String} inlineQty */ function attachmentsSection(attachments_hyperlink, status_value) { if (isNullorEmpty(attachments_hyperlink)) { attachments_hyperlink = '' } var disabled = (isTicketNotClosed(status_value)) ? '' : 'disabled'; var inlineQty = '<div class="form-group container attachments_section">'; inlineQty += '<div class="row">'; inlineQty += '<div class="col-xs-12 attachments_div">'; inlineQty += '<div class="input-group">'; inlineQty += '<span class="input-group-addon" id="attachments_text">ATTACHMENTS</span>' inlineQty += '<input id="attachments" class="form-control attachments" type="url" value="' + attachments_hyperlink + '" ' + disabled + '/>'; inlineQty += '</div></div></div></div>'; return inlineQty; } /** * The customer contact details section. * Possibility for the user to add / edit the contacts. * @return {String} inlineQty */ function mpexContactSection() { // Contact details header var inlineQty = '<div class="form-group container mpex_contact_section">'; inlineQty += '<div class="row">'; inlineQty += '<div class="col-xs-12 heading2">'; inlineQty += '<h4><span style="background-color: #379E8F" class="label label-default col-xs-12">CONTACT DETAILS</span></h4>'; inlineQty += '</div>'; inlineQty += '</div></div>'; // Contact table inlineQty += '<div class="form-group container contacts_section" style="font-size: small;">'; inlineQty += '<div class="row">'; inlineQty += '<div class="col-xs-12 contacts_div">'; // Since the table is not displayed correctly when added through suitelet, // It is added with jQuery in the pageInit() function in the client script 'mp_cl_open_ticket.js'. inlineQty += '</div>'; inlineQty += '</div>'; inlineQty += '</div>'; // Add/edit contacts button inlineQty += '<div class="form-group container reviewcontacts_section">'; inlineQty += '<div class="row">'; inlineQty += '<div class="col-xs-4 col-xs-offset-4 reviewcontacts">'; inlineQty += '<input type="button" style="background-color: #379E8F; border-color: #379E8F; font-weight: 700" value="ADD/EDIT CONTACTS" class="form-control btn btn-primary" id="reviewcontacts" />'; inlineQty += '</div></div></div>'; return inlineQty; }; /** * A Datatable displaying the open invoices of the customer * @param {Number} ticket_id * @param {String} selector_type * @return {String} inlineQty */ function openInvoicesSection(ticket_id, selector_type) { if (isNullorEmpty(ticket_id)) { ticket_id = '' } var hide_class_section = (isNullorEmpty(ticket_id) || selector_type != 'invoice_number') ? 'hide' : ''; // Open invoices header var inlineQty = '<div class="form-group container open_invoices open_invoices_header ' + hide_class_section + '">'; inlineQty += '<div class="row">'; inlineQty += '<div class="col-xs-12 heading2">'; inlineQty += '<h4><span style="background-color: #379E8F" class="label label-default col-xs-12">OPEN INVOICES</span></h4>'; inlineQty += '</div></div></div>'; // Open invoices dropdown field inlineQty += '<div class="form-group container open_invoices invoices_dropdown ' + hide_class_section + '">'; inlineQty += '<div class="row">'; inlineQty += '<div class="col-xs-12 invoices_dropdown_div">'; inlineQty += '<div class="input-group">'; inlineQty += '<span class="input-group-addon" id="invoices_dropdown_text">INVOICE STATUS</span>'; inlineQty += '<select id="invoices_dropdown" class="form-control">'; inlineQty += '<option value="open" selected>Open</option>'; inlineQty += '<option value="paidInFull">Paid In Full (last 3 months)</option>'; inlineQty += '</select>'; inlineQty += '</div></div></div></div>'; // Open Invoices Datatable //inlineQty += '<div class="form-group container open_invoices open_invoices_datatable>'; //inlineQty += '</div>'; inlineQty += '<div class="form-group open_invoices open_invoices_table ' + hide_class_section + '">'; inlineQty += dataTable(); // inlineQty += '<div class="row">'; // inlineQty += '<div class="col-xs-18" id="open_invoice_dt_div">'; // // It is inserted as inline html in the script mp_cl_open_ticket // inlineQty += '</div></div></div>'; inlineQty += '</div>' return inlineQty; } function dataTable() { var inlineQty = '<style>table#invoices-preview {font-size: 12px;text-align: center;border: none;}.dataTables_wrapper {font-size: 14px;}table#invoices-preview th{text-align: center;} .bolded{font-weight: bold;}</style>'; inlineQty += '<table id="invoices-preview" class="table table-responsive table-striped customer tablesorter" style="width: 100%; table-layout: fixed">'; inlineQty += '<thead style="color: white;background-color: #379E8F;">'; inlineQty += '<tr class="text-center">'; inlineQty += '</tr>'; inlineQty += '</thead>'; inlineQty += '<tbody id="result_invoices"></tbody>'; inlineQty += '</table>'; return inlineQty; } /** * The Credit Memo Section. * Displays a table of the credit memos linked to the invoice. * Possibility to attach the credit memo PDF to the email. * @param {String} selector_type * @return {String} inlineQty */ function creditMemoSection(selector_type) { var inlineQty = ''; if (selector_type == 'invoice_number') { // Credit Memo Header inlineQty += '<div class="form-group container credit_memo credit_memo_header">'; inlineQty += '<div class="row">'; inlineQty += '<div class="col-xs-12 heading2">'; inlineQty += '<h4><span style="background-color: #379E8F" class="label label-default col-xs-12">CREDIT MEMO</span></h4>'; inlineQty += '</div></div></div>'; // Credit Memo table inlineQty += '<div class="form-group container credit_memo credit_memo_section" style="font-size: small;">'; inlineQty += '<div class="row">'; inlineQty += '<div class="col-xs-12 credit_memo_div">'; // Since the table is not displayed correctly when added through suitelet, // It is added with jQuery in the pageInit() function in the client script 'mp_cl_open_ticket.js'. inlineQty += '</div></div></div>'; } return inlineQty; } function usageReportSection(selector_type) { var inlineQty = ''; if (selector_type == 'invoice_number') { // Usage Report Header inlineQty += '<div class="form-group container usage_report usage_report_header">'; inlineQty += '<div class="row">'; inlineQty += '<div class="col-xs-12 heading2">'; inlineQty += '<h4><span style="background-color: #379E8F" class="label label-default col-xs-12">USAGE REPORT</span></h4>'; inlineQty += '</div></div></div>'; // Usage Report table inlineQty += '<div class="form-group container usage_report usage_report_section" style="font-size: small;">'; inlineQty += '<div class="row">'; inlineQty += '<div class="col-xs-12 usage_report_div">'; // Since the table is not displayed correctly when added through suitelet, // It is added with jQuery in the pageInit() function in the client script 'mp_cl_open_ticket.js'. inlineQty += '</div></div></div>'; } return inlineQty; } /** * The "Send Email" section. * Possibility for the user to send an email to the customer, based on selected templates. * @param {Number} ticket_id * @param {Number} status_value * @param {Object} account_manager * @returns {String} inlineQty */ function sendEmailSection(ticket_id, status_value, account_manager, list_toll_emails) { var has_toll_emails = (!isNullorEmpty(list_toll_emails)); if (isNullorEmpty(ticket_id) || !isTicketNotClosed(status_value)) { // The section is hidden here rather than in the openTicket function, // because we use the section to send an acknoledgement email when a ticket is opened. var inlineQty = '<div id="send_email_container" class="send_email hide">'; } else { var inlineQty = '<div id="send_email_container" class="send_email">'; } // inlineQty += '<div class="form-group container send_email header_section">'; // // Send email header // inlineQty += '<div class="row">'; // inlineQty += '<div class="col-xs-12 heading2">'; // inlineQty += '<h4><span style="background-color: #379E8F" class="label label-default col-xs-12">SEND EMAILS</span></h4>'; // inlineQty += '</div></div></div>'; inlineQty += '<br></br>' // Row addressees inlineQty += '<div class="form-group container send_email adressees_section">'; inlineQty += '<div class="row">'; inlineQty += '<div class="col-xs-12 to_section">'; inlineQty += '<div class="input-group">'; inlineQty += '<span class="input-group-addon">TO<span class="mandatory">*</span></span>'; inlineQty += '<input id="send_to" class="form-control" data-contact-id="" data-firstname=""/>'; inlineQty += '</div></div></div></div>'; // Toll addresses var toll_emails_columns = new Array(); toll_emails_columns[0] = search.createColumn({ name: 'name' }); toll_emails_columns[1] = search.createColumn({ name: 'internalId' }); var tollEmailsResultSet = search.create({ type: 'customlist_toll_emails', columns: toll_emails_columns, }) inlineQty += '<div class="form-group container send_email toll_adressees_section">'; inlineQty += '<div class="row">'; inlineQty += '<div class="col-xs-12 toll_section">'; inlineQty += '<div class="input-group">'; inlineQty += '<span class="input-group-addon">TOLL EMAILS</span>'; inlineQty += '<select multiple id="send_toll" class="form-control" size="' + tollEmailsResultSet.length + '"/>'; tollEmailsResultSet.run().each(function (tollEmailsResultSet) { var tollEmailName = tollEmailsResultSet.getValue('name'); var tollEmailId = tollEmailsResultSet.getValue('internalId'); var selected = false; if (has_toll_emails) { selected = (list_toll_emails.indexOf(tollEmailId) !== -1); } if (selected) { inlineQty += '<option value="' + tollEmailId + '" selected>' + tollEmailName + '</option>'; } else { inlineQty += '<option value="' + tollEmailId + '">' + tollEmailName + '</option>'; } return true; }); inlineQty += '</select>'; inlineQty += '</div></div></div></div>'; // Row ccs addresses inlineQty += '<div class="form-group container send_email cc_adressees_section">'; inlineQty += '<div class="row">'; inlineQty += '<div class="col-xs-6 cc_section">'; inlineQty += '<div class="input-group">'; inlineQty += '<span class="input-group-addon">CC</span>'; inlineQty += '<input id="send_cc" class="form-control"/>'; inlineQty += '</div></div>'; inlineQty += '<div class="col-xs-6 bcc_section">'; inlineQty += '<div class="input-group">'; inlineQty += '<span class="input-group-addon">BCC</span>'; inlineQty += '<input id="send_bcc" class="form-control"/>'; inlineQty += '</div></div></div></div>'; // Row account manager if (isNullorEmpty(account_manager.name)) { account_manager.name = '' } if (isNullorEmpty(account_manager.email)) { account_manager.email = '' } if (!isNullorEmpty(account_manager.email.email)) { inlineQty += '<div class="form-group container send_email acc_manager_section">'; inlineQty += '<div class="row">'; inlineQty += '<div class="col-xs-10 acc_manager_name_section">'; inlineQty += '<div class="input-group">'; inlineQty += '<span class="input-group-addon">ACCOUNT MANAGER</span>'; inlineQty += '<input id="acc_manager" class="form-control" data-email="' + account_manager.email.email + '" value="' + account_manager.name + ' - ' + account_manager.email.email + '" disabled/>'; inlineQty += '</div></div>'; inlineQty += '<div class="col-xs-2 acc_manager_button_section">'; inlineQty += '<button id="acc_manager_button" style="background-color: #379E8F; border-color: #379E8F" type="button" class="btn btn-success btn-block">ADD TO CC</button>'; inlineQty += '</div></div></div>'; } // Row Template inlineQty += '<div class="form-group container send_email template_section">'; inlineQty += '<div class="row">'; inlineQty += '<div class="col-xs-12 template_section">'; inlineQty += '<div class="input-group">'; inlineQty += '<span class="input-group-addon">TEMPLATE<span class="mandatory">*</span></span>'; inlineQty += '<select id="template" class="form-control">'; inlineQty += '<option></option>'; // Load the template options var templatesSearch = search.load({ id: 'customsearch_cctemplate_mp_ticket', type: 'customrecord_camp_comm_template' }); var templatesSearchResults = templatesSearch.run(); templatesSearchResults.each(function (templatesSearchResult) { // var tempId = templatesSearchResult.getValue('internalid'); var tempId = templatesSearchResult["id"]; var tempName = templatesSearchResult.getValue('name'); inlineQty += '<option value="' + tempId + '">' + tempName + '</option>'; return true; }); inlineQty += '</select>'; inlineQty += '</div></div></div></div>'; // Row Subject inlineQty += '<div class="form-group container send_email subject_section">'; inlineQty += '<div class="row">'; inlineQty += '<div class="col-xs-12 subject_section">'; inlineQty += '<div class="input-group">'; inlineQty += '<span class="input-group-addon">SUBJECT<span class="mandatory">*</span></span>'; inlineQty += '<input id="subject" class="form-control" />'; inlineQty += '</div></div></div></div>'; // Row Body inlineQty += '<div class="form-group container send_email body_section">'; inlineQty += '<div class="row">'; inlineQty += '<div class="col-xs-12 body_section">'; inlineQty += '<div id="email_body"></div>'; inlineQty += '</div></div></div>'; // SEND EMAIL button inlineQty += '<div class="form-group container send_email button_section">'; inlineQty += '<div class="row">'; inlineQty += '<div class="col-xs-4 col-xs-offset-4 send_email_btn">'; inlineQty += '<input type="button" style="background-color: #379E8F; border-color: #379E8F; font-weight: 700" value="SEND EMAIL" class="form-control btn btn-primary" id="send_email" />'; inlineQty += '</div></div></div></div>'; return inlineQty; }; /** * Section for the previous emails datatable * @param customer_id * @returns {string} */ function previousEmailsSection(customer_id) { var customerRecord = record.load({ type: record.Type.CUSTOMER, id: customer_id, }); var customer_internal_id = customerRecord.getValue({ fieldId: 'id' }); // Previous Emails header var inlineQty = '<div class="form-group container previous_emails_header">'; inlineQty += '<div class="row">'; inlineQty += '<div class="col-xs-12 heading2">'; inlineQty += '<h4><span style="background-color: #379E8F" class="label label-default col-xs-12">PREVIOUS EMAILS</span></h4>'; inlineQty += '</div></div></div>'; //Searching emails filtered by - internal customer id and dated before the lastmonthonefiscalquarterago (i.e. the past three months) var emailSearch = search.load({ type: 'message', id: 'customsearch_all_messages' }); var emailSearchFilter = [["customer.internalid", "anyof", customer_internal_id], "AND", ["messagedate", "after", "lastmonthonefiscalquarterago"]]; //670041, 313070 emailSearch.filterExpression = emailSearchFilter; var resultEmailSet = emailSearch.run(); var allEmails = resultEmailSet.getRange({ start: 0, end: 1000 }); //Previous Emails table setup // inlineQty += '<style> table {font-size: 12px;text-align: center;border: none;} {font-size: 14px;} table th{text-align: center;} .dataTables_wrapper{width:78%; margin:auto;} </style>'; // inlineQty += '<div class="form-group container previous_emails_section">'; // inlineQty += '<table cellpadding="15" id="emails-preview" class="table table-responsive table-striped customer tablesorter" cellspacing="0" style="width: 100%;">'; // inlineQty += '<thead style="color: white;background-color: #CFE0CE;">'; // inlineQty += '<tr class="text-center">'; // inlineQty += '<th scope="col">Message Date</th>'; // inlineQty += '<th scope="col">Author</th>'; // inlineQty += '<th scope="col">Receipients</th>'; // inlineQty += '<th scope="col">Subject</th>'; // inlineQty += '<th scope="col">More</th>'; // inlineQty += '</tr>'; // inlineQty += '</thead>'; // inlineQty += '<tbody>'; inlineQty += '<style>table#emails-preview {font-size: 12px;text-align: center;border: none; background-color: #379E8F}.dataTables_wrapper {font-size: 12px;}table#emails-preview th{background-color: #379E8F; text-align: center;}</style>'; inlineQty += '<table cellpadding="15" id="emails-preview" class="table table-responsive table-striped customer tablesorter" cellspacing="0" style="width: 100%;">'; inlineQty += '<thead style="color: white;background-color: #379E8F;">'; inlineQty += '<tr class="text-center">'; inlineQty += '<th scope="col">Message Date</th>'; inlineQty += '<th scope="col">Author</th>'; inlineQty += '<th scope="col">Receipients</th>'; inlineQty += '<th scope="col">Subject</th>'; inlineQty += '<th scope="col">More</th>'; inlineQty += '</tr>'; inlineQty += '</thead>'; inlineQty += '<tbody>'; allEmails.forEach(function (email) { var messageid = email.searchId; var date = email.getValue('messagedate'); var author = email.getValue('authoremail'); var recipients = email.getText('recipients'); var subject = email.getValue('subject'); var url = "https://1048144-sb3.app.netsuite.com/app/crm/common/crmmessage.nl?id=" + messageid; //Table row data inlineQty += '<tr>'; inlineQty += '<td> ' + date + ' </td>'; inlineQty += '<td> ' + author + ' </td>'; inlineQty += '<td> ' + recipients + ' </td>'; inlineQty += '<td> ' + subject + '</td>'; inlineQty += '<td> <a href=' + url + '> View More </a> </td>'; inlineQty += '</tr>'; }); inlineQty += '</tbody>'; inlineQty += '</table>'; //inlineQty += '</div>'; return inlineQty; } /** * @return {String} inlineQty */ function issuesHeader() { var inlineQty = '<div class="form-group container toll_issues_header_section">'; inlineQty += '<div class="row">'; inlineQty += '<div class="col-xs-12 heading1">'; inlineQty += '<h4><span style="background-color: #379E8F" class="form-group label label-default col-xs-12">ISSUES</span></h4>'; inlineQty += '</div></div></div>'; return inlineQty; } /** * @param {Number} status_value * @return {String} inlineQty */ function reminderSection(status_value) { var hide_class = (!isTicketNotClosed(status_value)) ? 'hide' : ''; var inlineQty = '<div class="form-group container reminder_section ' + hide_class + '">'; inlineQty += '<div class="row">'; // Reminder field inlineQty += '<div class="col-xs-12 reminder">'; inlineQty += '<div class="input-group">'; inlineQty += '<span class="input-group-addon" id="reminder_text">REMINDER</span>'; inlineQty += '<input id="reminder" class="form-control reminder" type="date" />'; inlineQty += '</div></div></div></div>'; return inlineQty; } /** * Based on the selected MP Issue, an Owner is allocated to the ticket. * IT issues have priority over the other issues. * Populated with selectOwner() in the pageInit function on the client script. * @param {Number} ticket_id * @param {Array} owner_list * @param {Number} status_value * @return {String} inlineQty */ function ownerSection(ticket_id, owner_list, status_value) { if (isNullorEmpty(ticket_id)) { // If ticket_id is null, owner_list as well. // In that case, only the creator of the ticket is pre-selected as the owner. var userId = runtime.getCurrentUser().id; log.debug({ title: 'userId', details: userId }) owner_list = [userId]; } var disabled = (!isTicketNotClosed(status_value)) ? 'disabled' : ''; log.debug({ title: 'owner_list', details: owner_list }) var inlineQty = '<div class="form-group container owner_section">'; inlineQty += '<div class="row">'; inlineQty += '<div class="col-xs-12 owner">'; inlineQty += '<div class="input-group">'; inlineQty += '<span class="input-group-addon" id="owner_text">OWNER<span class="mandatory">*</span></span>'; inlineQty += '<select multiple id="owner" class="form-control owner" ' + disabled + '>'; var employeeSearch = search.load({ type: 'employee', id: 'customsearch_active_employees' }); var employeeResultSet = employeeSearch.run(); employeeResultSet.each(function (employeeResult) { var employee_id = employeeResult.id; var employee_firstname = employeeResult.getValue('firstname'); var employee_lastname = employeeResult.getValue('lastname'); var employee_email = employeeResult.getValue('email'); if (owner_list.indexOf(parseInt(employee_id)) != -1) { inlineQty += '<option value="' + employee_id + '" data-email="' + employee_email + '" selected>' + employee_firstname + ' ' + employee_lastname + '</option>'; } else { inlineQty += '<option value="' + employee_id + '" data-email="' + employee_email + '">' + employee_firstname + ' ' + employee_lastname + '</option>'; } return true; }); inlineQty += '</select>'; inlineQty += '</div></div></div></div>'; return inlineQty; } function customerIssueDropdown() { //Load the customer issue list var col = new Array(); col[0] = search.createColumn({ name: 'name' }); col[1] = search.createColumn({ name: 'internalId' }); var results = search.create({ type: 'customlist_customer_ticket_issues', columns: col, }) var inlineQty = '<div class="form-group container customer_issues_dropdown_section">'; inlineQty += '<div class="row">'; inlineQty += '<div class="col-xs-12">'; inlineQty += '<div class="input-group"><span class="input-group-addon">CUSTOMER ISSUE</span>'; inlineQty += '<select id="customer_issue_dropdown" class="form-control">'; inlineQty += '<option></option>'; for (var i = 0; results != null && i < results.length; i++) { var res = results[i]; var listValue = res.getValue('name'); var listID = res.getValue('internalId'); inlineQty += '<option value="' + listID + '">' + listValue + '</option>'; // if (selected) { // inlineQty += '<option value="' + listID + '" selected>' + listValue + '</option>'; // } else { // inlineQty += '<option value="' + listID + '">' + listValue + '</option>'; // } } inlineQty += '</select>'; inlineQty += '</div></div></div></div>'; return inlineQty; } function customerIssuesSection(ticket_id, selector_type, selector_number, screenshot_file, selected_browser, login_email_used, selected_operating_system, phone_used, old_sender_name, old_sender_phone, status_value) { if (isNullorEmpty(screenshot_file)) { screenshot_file = ''; } if (isNullorEmpty(selected_browser)) { selected_browser = ''; } if (isNullorEmpty(login_email_used)) { login_email_used = ''; } if (isNullorEmpty(selected_operating_system)) { operating_system = ''; } if (isNullorEmpty(phone_used)) { phone_used = ''; } if (isNullorEmpty(old_sender_name)) { old_sender_name = ''; } if (isNullorEmpty(old_sender_phone)) { old_sender_phone = ''; } var hide_class_section_mp_app = ((selector_type == "customer_issue") && (selector_number == 'Customer App')) ? '' : 'hide'; var hide_class_section_mp_label = ((selector_type == "customer_issue") && (selector_number == 'Update Label')) ? '' : 'hide'; var is_customer_issue_hide = (selector_type != "customer_issue") ? 'hide' : ''; var hide_class_section_mp_portal = ((selector_type == "customer_issue") && (selector_number == 'Customer Portal')) ? '' : 'hide'; var inlineQty = ''; //Screenshot section if (selector_type == "customer_issue" && (selector_number == "Customer App" || selector_number == "Customer Portal") && !isNullorEmpty(ticket_id)) { inlineQty += '<div class="form-group container ss_section">'; inlineQty += '<div class="row">'; inlineQty += '<div class="col-xs-12 screenshot_div">'; inlineQty += '<div class="input-group"><span class="input-group-addon" id="screenshot_text">SCREENSHOT</span>'; inlineQty += '<input type="file" class="form-control" id="screenshot_image" value="' + screenshot_file + '">'; inlineQty += '</div></div></div></div>'; } // Browser and OS Section inlineQty += '<div class="form-group container browser_os_section ' + hide_class_section_mp_portal + ' ' + is_customer_issue_hide + '">'; inlineQty += '<div class="row">'; inlineQty += '<div class="col-xs-6 browser_div">'; inlineQty += '<div class="input-group"><span class="input-group-addon" id="browser_text">BROWSER</span>'; inlineQty += '<select id="browser_value" class="form-control label_status">'; inlineQty += '<option></option>' var browserColumns = new Array(); browserColumns[0] = search.createColumn({ name: 'name' }); browserColumns[1] = search.createColumn({ name: 'internalId' }); var browserResultSet = search.create({ type: 'customlist_common_browsers', columns: browserColumns }); browserResultSet.run().each(function (browserResult) { var browserName = browserResult.getValue('name'); var browserId = browserResult.getValue('internalId'); if (selected_browser == browserId) { inlineQty += '<option value="' + browserId + '"selected>' + browserName + '</option>'; } else { inlineQty += '<option value="' + browserId + '">' + browserName + '</option>'; } return inlineQty; }); inlineQty += '</select></div></div>'; inlineQty += '<div class="col-xs-6 os_div">'; inlineQty += '<div class="input-group"><span class="input-group-addon" id="os_text">OPERATING SYSTEM</span>'; inlineQty += '<select id="os_value" class="form-control">'; inlineQty += '<option></option>' var osColumns = new Array(); osColumns[0] = search.createColumn({ name: 'name' }); osColumns[1] = search.createColumn({ name: 'internalId' }); var osResultSet = search.create({ type: 'customlist_common_os', columns: osColumns }); osResultSet.run().each(function (osResult) { var osName = osResult.getValue('name'); var osId = osResult.getValue('internalId'); if (selected_browser == osId) { inlineQty += '<option value="' + osId + '"selected>' + osName + '</option>'; } else { inlineQty += '<option value="' + osId + '">' + osName + '</option>'; } return inlineQty; }); inlineQty += '</select>'; inlineQty += '</div></div></div></div>'; //Customer App issues - Phone section inlineQty += '<div class="form-group container ' + is_customer_issue_hide + ' phone_section ' + hide_class_section_mp_app + '">'; inlineQty += '<div class="row">'; inlineQty += '<div class="col-xs-12 phone_div">'; inlineQty += '<div class="input-group"><span class="input-group-addon" id="screenshot_text">PHONE</span>'; inlineQty += '<input type="text" class="form-control" id="phone_used" placeholder=" Google Pixel 3" value="' + phone_used + '">'; inlineQty += '</div></div></div></div>'; //Login email used section inlineQty += '<div class="form-group container login_email_used_section ' + is_customer_issue_hide + '">'; inlineQty += '<div class="row">'; inlineQty += '<div class="col-xs-12 login_email_div">'; inlineQty += '<div class="input-group">'; inlineQty += '<span class="input-group-addon" id="login_email">LOGIN EMAIL</span>'; inlineQty += '<input id="login_email_text" class="form-control" value="' + login_email_used + '"/>'; inlineQty += '</div></div></div></div>'; //Sender details name and phone number inlineQty += '<div class="form-group container ' + is_customer_issue_hide + ' sender_details_section ' + hide_class_section_mp_label + '">'; inlineQty += '<div class="row">'; inlineQty += '<div class="col-xs-6 sender_name_div">'; inlineQty += '<div class="input-group">'; inlineQty += '<span class="input-group-addon" id="sender_name">SENDER NAME</span>'; inlineQty += '<input id="sender_name_text" class="form-control" value="' + old_sender_name + '"/>'; inlineQty += '</div></div>'; inlineQty += '<div class="col-xs-6 sender_phone_div">'; inlineQty += '<div class="input-group">'; inlineQty += '<span class="input-group-addon" id="sender_phone">SENDER PHONE</span>'; inlineQty += '<input id="sender_phone_text" class="form-control" value="' + old_sender_phone + '"/>'; inlineQty += '</div></div></div></div>'; return inlineQty; } /** * The multiselect TOLL issues dropdown * @param {Array} list_toll_issues * @param {Array} list_resolved_toll_issues * @param {Number} status_value * @param {String} selector_type * @return {String} inlineQty */ function tollIssuesSection(list_toll_issues, list_resolved_toll_issues, status_value, selector_type) { // TOLL Issues var has_toll_issues = (!isNullorEmpty(list_toll_issues)); var toll_issues_columns = new Array(); toll_issues_columns[0] = search.createColumn({ name: 'name' }); toll_issues_columns[1] = search.createColumn({ name: 'internalId' }); var tollIssuesResultSet = search.create({ type: 'customlist_cust_prod_stock_toll_issues', columns: toll_issues_columns }); if (!isTicketNotClosed(status_value) || selector_type != 'barcode_number') { var inlineQty = '<div class="form-group container toll_issues_section hide">'; } else { var inlineQty = '<div class="form-group container toll_issues_section">'; } inlineQty += '<div class="row">'; inlineQty += '<div class="col-xs-12 toll_issues">'; inlineQty += '<div class="input-group"><span class="input-group-addon" id="toll_issues_text">TOLL ISSUES<span class="mandatory">*</span></span>'; inlineQty += '<select multiple id="toll_issues" class="form-control toll_issues" size="' + tollIssuesResultSet.length + '">'; tollIssuesResultSet.run().each(function (tollIssueResult) { var issue_name = tollIssueResult.getValue('name'); var issue_id = tollIssueResult.getValue('internalId'); var selected = false; if (has_toll_issues) { selected = (list_toll_issues.indexOf(issue_id) !== -1); } if (selected) { inlineQty += '<option value="' + issue_id + '" selected>' + issue_name + '</option>'; } else { inlineQty += '<option value="' + issue_id + '">' + issue_name + '</option>'; } return true; }); inlineQty += '</select>'; inlineQty += '</div></div></div></div>'; // Resolved TOLL Issues log.debug({ title: 'list_resolved_toll_issues : ', details: list_resolved_toll_issues }); var has_resolved_toll_issues = (!isNullorEmpty(list_resolved_toll_issues)); if (has_resolved_toll_issues) { var text_resolved_toll_issues = ''; tollIssuesResultSet.run().each(function (tollIssueResult) { var issue_name = tollIssueResult.getValue('name'); var issue_id = tollIssueResult.getValue('internalId'); if (list_resolved_toll_issues.indexOf(issue_id) !== -1) { text_resolved_toll_issues += issue_name + '\n'; } return true; }); log.debug({ title: 'text_resolved_toll_issues : ', details: text_resolved_toll_issues }); inlineQty += '<div class="form-group container resolved_toll_issues_section">'; inlineQty += '<div class="row">'; inlineQty += '<div class="col-xs-12 resolved_toll_issues">'; inlineQty += '<div class="input-group">'; inlineQty += '<span class="input-group-addon" id="resolved_toll_issues_text">RESOLVED TOLL ISSUES</span>'; inlineQty += '<textarea id="resolved_toll_issues" class="form-control resolved_toll_issues" rows="' + list_resolved_toll_issues.length + '" disabled>' + text_resolved_toll_issues.trim() + '</textarea>'; inlineQty += '</div></div></div></div>'; } return inlineQty; }; /** * The multiselect MP Ticket issues dropdown * @param {Array} list_mp_ticket_issues * @param {Array} list_resolved_mp_ticket_issues * @param {Number} status_value * @param {String} selector_type * @return {String} inlineQty */ function mpTicketIssuesSection(list_mp_ticket_issues, list_resolved_mp_ticket_issues, status_value, selector_type) { // MP Ticket Issues var has_mp_ticket_issues = !isNullorEmpty(list_mp_ticket_issues); var disabled_mp_issue_field = (isTicketNotClosed(status_value)) ? '' : 'disabled'; log.debug({ title: 'has_mp_ticket_issues : ', details: has_mp_ticket_issues }); if (has_mp_ticket_issues && status_value != 3) { // The MP Ticket issue section is displayed if the status is 'Closed - Unallocated' (status_value == 8) var inlineQty = '<div class="form-group container mp_issues_section">'; } else { var inlineQty = '<div class="form-group container mp_issues_section hide">'; } inlineQty += '<div class="row">'; inlineQty += '<div class="col-xs-12 mp_issues">'; var mp_ticket_issues_columns = new Array(); mp_ticket_issues_columns[0] = search.createColumn({ name: 'name' }); mp_ticket_issues_columns[1] = search.createColumn({ name: 'internalId' }); var mpTicketIssuesResultSet = search.create({ type: 'customlist_mp_ticket_issues', columns: mp_ticket_issues_columns }); inlineQty += '<div class="input-group">' inlineQty += '<span class="input-group-addon" id="mp_issues_text">MP ISSUES<span class="mandatory hide">*</span></span>'; inlineQty += '<select multiple id="mp_issues" class="form-control mp_issues" size="' + mpTicketIssuesResultSet.length + '" ' + disabled_mp_issue_field + '>'; mpTicketIssuesResultSet.run().each(function (mpTicketIssueResult) { var mp_issue_name = mpTicketIssueResult.getValue('name'); var mp_issue_id = mpTicketIssueResult.getValue('internalId'); var selected = false; if (has_mp_ticket_issues) { selected = (list_mp_ticket_issues.indexOf(mp_issue_id) !== -1); } var show_option = (selector_type == 'barcode_number' || (selector_type == 'invoice_number' && mp_issue_id == 4) || (selector_type == "customer_issue")); var selected_option = (selected) ? 'selected' : ''; if (show_option) { inlineQty += '<option value="' + mp_issue_id + '" ' + selected_option + '> ' + mp_issue_name + '</option > '; } return true; }); inlineQty += '</select>'; inlineQty += '</div></div></div></div>'; // Resolved MP Ticket Issues var has_resolved_mp_ticket_issues = !isNullorEmpty(list_resolved_mp_ticket_issues); if (has_resolved_mp_ticket_issues && selector_type != "customer_issue") { var text_resolved_mp_ticket_issues = ''; mpTicketIssuesResultSet.run().each(function (mpTicketIssueResult) { var mp_issue_name = mpTicketIssueResult.getValue('name'); var mp_issue_id = mpTicketIssueResult.getValue('internalId'); if (list_resolved_mp_ticket_issues.indexOf(mp_issue_id) !== -1) { text_resolved_mp_ticket_issues += mp_issue_name + '\n'; } return true; }); inlineQty += '<div class="form-group container resolved_mp_issues_section">'; inlineQty += '<div class="row">'; inlineQty += '<div class="col-xs-12 resolved_mp_issues">'; inlineQty += '<div class="input-group">'; inlineQty += '<span class="input-group-addon" id="resolved_mp_issues_text">RESOLVED MP ISSUES</span>'; inlineQty += '<textarea id="resolved_mp_issues" class="form-control resolved_mp_issues" rows="' + list_resolved_mp_ticket_issues.length + '" disabled>' + text_resolved_mp_ticket_issues.trim() + '</textarea>'; inlineQty += '</div></div></div></div>'; } return inlineQty; } /** * The multiselect Invoice issues dropdown * @param {Array} list_invoice_issues * @param {Array} list_resolved_invoice_issues * @param {Number} status_value * @param {String} selector_type * @return {String} inlineQty */ function invoiceIssuesSection(list_invoice_issues, list_resolved_invoice_issues, status_value, selector_type) { var has_invoice_issues = (!isNullorEmpty(list_invoice_issues)); var invoice_issues_columns = new Array(); invoice_issues_columns[0] = search.createColumn({ name: 'name' }); // Might need to be changed invoice_issues_columns[1] = search.createColumn({ name: 'internalId' }); // Might need to be changed var invoiceIssuesResultSet = search.create({ type: 'customlist_invoice_issues', columns: invoice_issues_columns }); if (!isTicketNotClosed(status_value) || selector_type != 'invoice_number') { var inlineQty = '<div class="form-group container invoice_issues_section hide">'; } else { var inlineQty = '<div class="form-group container invoice_issues_section">'; } inlineQty += '<div class="row">'; inlineQty += '<div class="col-xs-12 invoice_issues">'; inlineQty += '<div class="input-group"><span class="input-group-addon" id="invoice_issues_text">INVOICE ISSUES<span class="mandatory">*</span></span>'; inlineQty += '<select multiple id="invoice_issues" class="form-control invoice_issues">'; invoiceIssuesResultSet.run().each(function (invoiceIssueResult) { var issue_name = invoiceIssueResult.getValue('name'); // Might need to be changed var issue_id = invoiceIssueResult.getValue('internalId'); // Might need to be changed var selected = false; if (has_invoice_issues) { selected = (list_invoice_issues.indexOf(issue_id) != -1); } if (selected) { inlineQty += '<option value="' + issue_id + '" selected>' + issue_name + '</option>'; } else { inlineQty += '<option value="' + issue_id + '">' + issue_name + '</option>'; } return true; }); inlineQty += '</select>'; inlineQty += '</div></div></div></div>'; // Resolved invoice Issues log.debug({ title: 'list_resolved_invoice_issues : ', details: list_resolved_invoice_issues }); var has_resolved_invoice_issues = (!isNullorEmpty(list_resolved_invoice_issues)); if (has_resolved_invoice_issues) { var text_resolved_invoice_issues = ''; invoiceIssuesResultSet.run().each(function (invoiceIssueResult) { var issue_name = invoiceIssueResult.getValue('name'); // Might need to be changed var issue_id = invoiceIssueResult.getValue('internalId'); // Might need to be changed if (list_resolved_invoice_issues.indexOf(issue_id) !== -1) { text_resolved_invoice_issues += issue_name + '\n'; } }); log.debug({ title: 'text_resolved_invoice_issues : ', details: text_resolved_invoice_issues }); inlineQty += '<div class="form-group container resolved_invoice_issues_section">'; inlineQty += '<div class="row">'; inlineQty += '<div class="col-xs-12 resolved_invoice_issues">'; inlineQty += '<div class="input-group">'; inlineQty += '<span class="input-group-addon" id="resolved_invoice_issues_text">RESOLVED INVOICE ISSUES</span>'; inlineQty += '<textarea id="resolved_invoice_issues" class="form-control resolved_invoice_issues" rows="' + list_resolved_invoice_issues.length + '" disabled>' + text_resolved_invoice_issues.trim() + '</textarea>'; inlineQty += '</div></div></div></div>'; } return inlineQty; } /** * @param {String} selector_type * @param {Number} status_value * @return {String} inlineQty */ function usernoteSection(selector_type, status_value) { var usernote_titles_columns = new Array(); usernote_titles_columns[0] = search.createColumn({ name: 'name' }); usernote_titles_columns[1] = search.createColumn({ name: 'internalId' }); var usernoteTitlesResultSet = search.create({ type: 'customlist_user_note_title', columns: usernote_titles_columns }); // Row Title if (selector_type == 'invoice_number' && isTicketNotClosed(status_value)) { var inlineQty = '<div class="form-group container user_note user_note_title_section">'; } else { var inlineQty = '<div class="form-group container user_note user_note_title_section hide">'; } inlineQty += '<div class="row">'; inlineQty += '<div class="col-xs-12 user_note_title_section">'; inlineQty += '<div class="input-group">'; inlineQty += '<span class="input-group-addon">TITLE<span class="mandatory">*</span></span>'; inlineQty += '<select id="user_note_title" class="form-control">'; usernoteTitlesResultSet.run().each(function (usernoteTitleResult) { var title_name = usernoteTitleResult.getValue('name'); var title_id = usernoteTitleResult.getValue('internalId'); if (title_id == 3) { inlineQty += '<option value="' + title_id + '" selected>' + title_name + '</option>'; } else { inlineQty += '<option value="' + title_id + '">' + title_name + '</option>'; } return true; }); inlineQty += '</select>'; inlineQty += '</div></div></div></div>'; // Row User Note Textarea if (selector_type == 'invoice_number' && isTicketNotClosed(status_value)) { inlineQty += '<div class="form-group container user_note user_note_textarea_section">'; } else { inlineQty += '<div class="form-group container user_note user_note_textarea_section hide">'; } inlineQty += '<div class="row">'; inlineQty += '<div class="col-xs-12 user_note_textarea">'; inlineQty += '<div class="input-group">'; inlineQty += '<span class="input-group-addon" id="user_note_textarea_text">USER NOTE<span class="mandatory hide">*</span></span>'; inlineQty += '<textarea id="user_note_textarea" class="form-control user_note_textarea" rows="3"></textarea>'; inlineQty += '</div></div></div></div>'; // User Note table if (selector_type == 'invoice_number') { inlineQty += '<div class="form-group container user_note user_note_section" style="font-size: small;">'; } else { inlineQty += '<div class="form-group container user_note user_note_section hide" style="font-size: small;">'; } inlineQty += '<div class="row">'; inlineQty += '<div class="col-xs-12 user_note_div">'; // Since the table is not displayed correctly when added through suitelet, // It is added with jQuery in the pageInit() function in the client script 'mp_cl_open_ticket.js'. inlineQty += '</div>'; inlineQty += '</div>'; inlineQty += '</div>'; return inlineQty; } /** * Used to pass the values of `date_from` and `date_to` between the scripts and to Netsuite for the records and the search. * @param {String} date_iso "2020-06-01" * @returns {String} date_netsuite "1/6/2020" */ function dateISOToNetsuite(date_iso) { var date_netsuite = ''; if (!isNullorEmpty(date_iso)) { var date_netsuite = format.format({ value: date_iso, type: format.Type.DATETIME }); } return date_netsuite; } /** * The free-from text area for comments. * @param {String} comment * @param {String} selector_type * @param {Number} status_value * @return {String} inlineQty */ function commentSection(comment, selector_type, status_value) { if (isNullorEmpty(comment)) { comment = ''; } else { comment += '\n'; } switch (selector_type) { case 'barcode_number': var inlineQty = '<div class="form-group container comment_section">'; break; case 'invoice_number': var inlineQty = '<div class="form-group container comment_section hide">'; break; case 'customer_issue': var inlineQty = '<div class="form-group container comment_section">'; break; } inlineQty += '<div class="row">'; inlineQty += '<div class="col-xs-12 comment">'; inlineQty += '<div class="input-group">'; inlineQty += '<span class="input-group-addon" id="comment_text">COMMENT<span class="mandatory hide">*</span></span>'; if (isTicketNotClosed(status_value)) { inlineQty += '<textarea id="comment" class="form-control comment" rows="9">' + comment + '</textarea>'; } else { inlineQty += '<textarea id="comment" class="form-control comment" rows="9" readonly>' + comment + '</textarea>'; } inlineQty += '</div></div></div></div>'; return inlineQty; } /** * The table that will display the differents tickets linked to the customer. * @return {String} inlineQty */ function dataTablePreview() { var inlineQty = '<div class="form-group container tickets_datatable_section">'; inlineQty += '<div class="row">'; inlineQty += '<div class="col-xs-12 heading2">'; inlineQty += '<h4><span style="background-color: #379E8F" class="label label-default col-xs-12">PREVIOUS TICKETS</span></h4>'; inlineQty += '</div></div></div>'; inlineQty += '<style>table#tickets-preview {font-size: 12px;text-align: center;border: none; background-color: #379E8F}.dataTables_wrapper {font-size: 12px;}table#tickets-preview th{background-color: #379E8F; text-align: center;}</style>'; inlineQty += '<table cellpadding="15" id="tickets-preview" class="table table-responsive table-striped customer tablesorter" cellspacing="0" style="width: 100%;">'; inlineQty += '<thead style="color: white;background-color: #379E8F;">'; inlineQty += '<tr class="text-center">'; inlineQty += '</tr>'; inlineQty += '</thead>'; inlineQty += '<tbody id="result_tickets"></tbody>'; inlineQty += '</table>'; return inlineQty; } /** * The inline HTML for the close ticket button or the reopen button, * and the submitter button at the bottom of the page. * @param {Number} ticket_id * @param {Number} status_value * @return {String} inlineQty */ function closeReopenSubmitTicketButton(ticket_id, status_value) { var inlineQty = '<div class="form-group container close_reopen_submit_ticket_section">'; inlineQty += '<div class="row">'; log.debug({ title: 'status_value', details: status_value }); log.debug({ title: 'ticket_id', details: ticket_id }); if (isTicketNotClosed(status_value)) { if (!isNullorEmpty(ticket_id)) { inlineQty += '<div class="col-xs-2 close_ticket">'; inlineQty += '<input type="button" value="CLOSE TICKET" style="background-color: #FBEA51; border: 3px solid #379E8F; color: #379E8F; font-weight: 700" class="form-control btn btn-default" id="close_ticket" onclick="closeTicket()"/>'; inlineQty += '</div>'; inlineQty += '<div class="col-xs-3 close_ticket_lost">'; inlineQty += '<input type="button" value="CLOSE TICKET - LOST ITEM" style="background-color: #FBEA51; border: 3px solid #379E8F; color: #379E8F; font-weight: 700" class="form-control btn btn-default" id="close_ticket_lost" onclick="closeTicketLost()"/>'; inlineQty += '</div>'; if (userId == 409635 || userId == 696992 || userId == 766498) { inlineQty += '<div class="col-xs-3 close_unallocated_ticket hide">'; inlineQty += '<input type="button" value="CLOSE UNALLOCATED TICKET" style="background-color: #FBEA51; border: 3px solid #379E8F; color: #379E8F; font-weight: 700" class="form-control btn btn-default" id="close_unallocated_ticket" onclick="closeUnallocatedTicket()" />'; inlineQty += '</div>'; } } inlineQty += '<div class="col-xs-2 submitter">'; inlineQty += '<input type="button" style="background-color: #FBEA51; border: 3px solid #379E8F; color: #379E8F; font-weight: 700" value="UPDATE TICKET" class="form-control btn btn-primary" id="submit_ticket" />'; inlineQty += '</div>'; if (isNullorEmpty(ticket_id)) { inlineQty += '<div class="col-xs-3 open_and_new_ticket_btn">'; inlineQty += '<input type="button" style="background-color: #FBEA51; border: 3px solid #379E8F; color: #379E8F; font-weight: 700" value="OPEN AND NEW TICKET" class="form-control btn btn-primary" id="open_and_new_ticket_btn" />'; inlineQty += '</div>'; } inlineQty += '<style>.escalate:hover {box-shadow: 0 12px 16px 0 rgba(0,0,0,0.24), 0 17px 50px 0 rgba(0,0,0,0.19)}</style>'; inlineQty += '<div class="col-xs-2 escalate">'; inlineQty += '<input type="button" style="background-color: #FBEA51; border: 3px solid #379E8F; color: #379E8F; font-weight: 700" value="ESCALATE" class="form-control btn btn-default" id="escalate" onclick="onEscalate()"/>'; inlineQty += '</div>'; } else { inlineQty += '<div class="col-xs-2 col-xs-offset-2 reopen_ticket">'; inlineQty += '<input type="button" style="background-color: #FBEA51; border: 3px solid #379E8F; color: #379E8F; font-weight: 700" value="REOPEN TICKET" class="form-control btn btn-primary" id="reopen_ticket" />'; inlineQty += '</div>'; } inlineQty += '<div class="col-xs-2 cancel">'; inlineQty += '<input type="button" style="background-color: #FBEA51; border: 3px solid #379E8F; color: #379E8F; font-weight: 700" value="CANCEL" class="form-control btn btn-default" id="cancel" onclick="onCancel()"/>'; inlineQty += '</div>'; inlineQty += '</div></div>'; return inlineQty; } function Ownerjava2jsArray(javaArray) { var jsArray = new Array; if (!isNullorEmpty(javaArray)) { javaArray.forEach(function (javaValue) { var jsValue = parseInt(javaValue); jsArray.push(jsValue); }) } return jsArray; } /** * The output of .getFieldValues is a java String Array. * We want to convert it to a javaScript Array in order to read its values. * @param {Ljava.lang.String} javaArray * @return {Array} jsArray */ function java2jsArray(javaArray) { var jsArray = new Array; if (!isNullorEmpty(javaArray)) { javaArray.forEach(function (javaValue) { var jsValue = javaValue.toString(); jsArray.push(jsValue); }) } return jsArray; } /** * Parse the objects in an array, and returns an object based on the value of one of its keys. * With ES6, this function would simply be `array.find(obj => obj[key] == value)` * @param {Array} array * @param {String} key * @param {*} value * @returns {Object} */ function findObjectByKey(array, key, value) { for (var i = 0; i < array.length; i++) { if (array[i][key] === value) { return array[i]; } } return null; } /** * Returns whether a ticket is closed or not based on its status value. * @param {Number} status_value * @returns {Boolean} is_ticket_closed */ function isTicketNotClosed(status_value) { var is_ticket_not_closed = ((status_value != 3) && (status_value != 8) && (status_value != 15)) ? true : false; return is_ticket_not_closed; } function escalateButton(status) { if (status < 11) { return 'Escalate to 1st Escalation'; } else if (status == 11) { return 'Escalate to 2nd Escalation'; } else if (status == 12) { return 'Escalate to 3rd Escalation'; } else if (status == 13) { return 'Escalate to Final Escalation'; } else { return 'Escalate'; } } /** * Whether the user is from the finance team, * or a Data Systems Co-ordinator, MailPlus Administration or Administrator user. * @param {Number} userRole * @returns {Boolean} */ function isFinanceRole(userRole) { // 1001, 1031 and 1023 are finance roles // 1032 is the Data Systems Co-ordinator role (to be deleted in prod) // 1006 is the Mail Plus Administration role. // 3 is the Administrator role. return ((userRole == 1001 || userRole == 1031 || userRole == 1023) || ((userRole == 1032) || (userRole == 1006) || (userRole == 3))); } function isNullorEmpty(strVal) { return (strVal == null || strVal == '' || strVal == 'null' || strVal == undefined || strVal == 'undefined' || strVal == '- None -'); } return { onRequest: onRequest }; });
251
[{"tag": "KEY", "value": "sha384-HSMxcRTRxnN+Bdg0JdbxYKrThecOKuH5zCYotlSAcp1+c8xmyTe9GYg1l9a69psu", "start": 25392, "end": 25463}, {"tag": "KEY", "value": "sha384-aJ21OjlMXNL5UyIl/XNwTMqvzeRMZH2w8c5cRVpzpU8Y5bApTppSuUkhZXN0VxHd", "start": 25619, "end": 25690}, {"tag": "KEY", "value": "sha384-nvAa0+6Qg9clwYCGGPpDQLVpLNn0fRaROjHqs13t4Ggj3Ez50XnGQqc/r8MhnRDZ", "start": 24978, "end": 25049}]
true
3
/** * * @NApiVersion 2.0 * @NScriptType Suitelet * * Description: A ticketing system for the Customer Service. * @Last Modified by: Sruti Desai * */ define(['N/ui/serverWidget', 'N/email', 'N/runtime', 'N/search', 'N/record', 'N/http', 'N/log', 'N/redirect', 'N/format', 'N/file'], function (ui, email, runtime, search, record, http, log, redirect, format, file) { var baseURL = 'https://1048144.app.netsuite.com'; if (runtime.EnvType == "SANDBOX") { baseURL = 'https://1048144-sb3.app.netsuite.com'; } var zee = 0; var role = runtime.getCurrentUser().role; var userRole = runtime.getCurrentUser().role; var ctx = runtime.getCurrentScript(); var userId = runtime.getCurrentUser().id; if (role == 1000) { //Franchisee zee = runtime.getCurrentUser(); } function onRequest(context) { if (context.request.method === 'GET') { var ticket_id = null; var customer_id = null; var customer_number = null; var selector_id = null; var selector_number = ''; var selector_type = 'barcode_number'; var connote_number = ''; var date_created = ''; var creator_name = ''; var creator_id = null; var status_value = null; var escalated_to_it = ''; var status = ''; var customer_name = ''; var daytodayphone = ''; var daytodayemail = ''; var accountsphone = ''; var accountsemail = ''; var zee_id = null; var franchisee_name = ''; var zee_main_contact_name = ''; var zee_email = ''; var zee_main_contact_phone = ''; var zee_abn = ''; var date_stock_used = ''; var time_stock_used = ''; var final_delivery_text = ''; var selected_enquiry_status_id = null; var attachments_hyperlink = ''; var maap_bank_account_number = null; var maap_parent_bank_account_number = null; var selected_invoice_method_id = null; var accounts_cc_email = ''; var mpex_po_number = ''; var customer_po_number = ''; var terms = null; var customer_terms = ''; var account_manager = {}; var selected_invoice_cycle_id = null; var usage_report_id_1 = ''; var usage_report_id_2 = ''; var usage_report_id_3 = ''; var usage_report_id_4 = ''; var usage_report_array = []; var list_toll_issues = ''; var list_resolved_toll_issues = ''; var list_mp_ticket_issues = ''; var list_resolved_mp_ticket_issues = ''; var list_invoice_issues = ''; var list_resolved_invoice_issues = ''; var owner_list = ''; var comment = ''; var selected_label_id = null; var list_enquiry_mediums = ''; var total_enquiry_count = 0; var chat_enquiry_count = 0; var phone_enquiry_count = 0; var email_enquiry_count = 0; var phone_interaction_count = 0; var email_interaction_count = 0; var list_toll_emails = ''; var params_email = { recipient: '', subject: '', body: '', cc: '', bcc: '', records: {}, attachments_credit_memo_ids: [], attachments_usage_report_ids: [], attachments_invoice_ids: [] }; var customer_barcode_number = ''; var customer_issue = ''; var screenshot_file = ''; var browser = ''; var login_email_used = ''; var operating_system = ''; var phone_used = ''; var old_sender_name = ''; var old_sender_phone = ''; var customer_number_email_sent = 'F'; var customer_ticket_status = ''; var receiveremail = ''; var receiverphone = ''; var receivername = ''; var receiverstate = ''; var receiverzip = ''; var receiversuburb = ''; var receiveraddr1 = ''; var receiveraddr2 = ''; var prod_stock_invoice = ''; var barcodempdl = ''; var barcodesource = ''; var barcodeintegration = ''; var senderName = ''; var senderEmail = ''; var senderPhone = ''; var senderAddress = ''; var productName = '' // Load params var params = context.request.parameters.custparam_params; log.debug({ title: 'Params', details: params }) if (!isNullorEmpty(params)) { params = JSON.parse(params); log.debug({ title: 'Params not empty', details: params }); // Coming from the ticket_contact page or the edit_ticket page if (!isNullorEmpty(params.selector_number) && !isNullorEmpty(params.selector_type)) { selector_number = params.selector_number; selector_type = params.selector_type; //Coming from the ticket_contact page if (!isNullorEmpty(params.custid)) { customer_id = params.custid; } log.debug({ title: 'customer_id after ticket_contact_page : ', details: customer_id }); // Coming from the edit_ticket page if (!isNullorEmpty(params.ticket_id)) { ticket_id = parseInt(params.ticket_id); log.debug({ title: 'ticket id ISS', details: ticket_id }); // Load ticket data var ticketRecord = record.load({ type: 'customrecord_mp_ticket', id: ticket_id }); date_created = ticketRecord.getValue({ fieldId: 'created' }); creator_name = ticketRecord.getText({ fieldId: 'custrecord_creator' }); creator_id = ticketRecord.getValue({ fieldId: 'custrecord_creator' }); status_value = ticketRecord.getValue({ fieldId: 'custrecord_ticket_status' }); escalated_to_it = ticketRecord.getValue({ fieldId: 'custrecord_date_escalated_it' }); status = ticketRecord.getText({ fieldId: 'custrecord_ticket_status' }); customer_id = ticketRecord.getValue({ fieldId: 'custrecord_customer1' }); customer_name = ticketRecord.getText({ fieldId: 'custrecord_customer1' }); zee_id = ticketRecord.getValue({ fieldId: 'custrecord_zee' }); selected_enquiry_status_id = ticketRecord.getValue({ fieldId: 'custrecord_enquiry_status' }); attachments_hyperlink = ticketRecord.getValue({ fieldId: 'custrecord_mp_ticket_attachments' }); selected_label_id = ticketRecord.getValue({ fieldId: 'custrecord_ticket_label' }); list_enquiry_mediums = ticketRecord.getValue({ fieldId: 'custrecord_enquiry_medium' }); list_enquiry_mediums = java2jsArray(list_enquiry_mediums); total_enquiry_count = ticketRecord.getValue({ fieldId: 'custrecord_enquiry_count' }); chat_enquiry_count = ticketRecord.getValue({ fieldId: 'custrecord_chat_enquiry_count' }); phone_enquiry_count = ticketRecord.getValue({ fieldId: 'custrecord_phone_enquiry_count' }); phone_interaction_count = ticketRecord.getValue({ fieldId: 'custrecord_phone_interaction_count' }); email_interaction_count = ticketRecord.getValue({ fieldId: 'custrecord_email_interaction_count' }); email_enquiry_count = ticketRecord.getValue({ fieldId: 'custrecord_email_enquiry_count' }); customer_issue = ticketRecord.getValue({ fieldId: 'custrecord_customer_issue' }); screenshot_file = ticketRecord.getValue({ fieldId: 'custrecord_screenshot' }); browser = ticketRecord.getValue({ fieldId: 'custrecord_browser' }); login_email_used = ticketRecord.getValue({ fieldId: 'custrecord_login_email' }); operating_system = ticketRecord.getValue({ fieldId: 'custrecord_operating_system' }); phone_used = ticketRecord.getValue({ fieldId: 'custrecord_phone_used' }); customer_number = ticketRecord.getValue({ fieldId: 'custrecord_cust_number' }); old_sender_name = ticketRecord.getValue({ fieldId: 'custrecord_sender_name' }); old_sender_phone = ticketRecord.getValue({ fieldId: 'custrecord_sender_phone' }); customer_number_email_sent = ticketRecord.getValue({ fieldId: 'custrecord_customer_number_email_sent' }); customer_barcode_number = ticketRecord.getValue({ fieldId: 'custrecord_barcode_number' }); customer_ticket_status = ticketRecord.getText({ fieldId: 'custrecord_mp_ticket_customer_status' }); if (!isNullorEmpty(customer_barcode_number)) { var rec = record.load({ type: 'customrecord_customer_product_stock', id: customer_barcode_number, }); receiveremail = rec.getValue({ fieldId: 'custrecord_receiver_email' }); receiverphone = rec.getValue({ fieldId: 'custrecord_receiver_phone' }); receivername = rec.getValue({ fieldId: 'custrecord_receiver_name' }); receiverstate = rec.getValue({ fieldId: 'custrecord_receiver_state' }); receiverzip = rec.getValue({ fieldId: 'custrecord_receiver_postcode' }); receiversuburb = rec.getValue({ fieldId: 'custrecord_receiver_suburb' }); receiveraddr1 = rec.getValue({ fieldId: 'custrecord_receiver_addr1' }); receiveraddr2 = rec.getValue({ fieldId: 'custrecord_receiver_addr2' }); senderName = rec.getValue({ fieldId: 'custrecord_senders_name' }); senderEmail = rec.getValue({ fieldId: 'custrecord_sender_email' }); senderPhone = rec.getValue({ fieldId: 'custrecord_senders_phone' }); senderAddress = rec.getValue({ fieldId: 'custrecord_sender_address_1' }); productName = rec.getText({ fieldId: 'custrecord_cust_prod_stock_single_name' }); if (isNullorEmpty(productName)) { productName = rec.getText({ fieldId: 'custrecord_cust_stock_prod_name' }) } prod_stock_invoice = rec.getText({ fieldId: 'custrecord_prod_stock_invoice' }); barcodempdl = rec.getValue({ fieldId: 'custrecord_mpdl_number' }); barcodeintegration = rec.getValue({ fieldId: 'custrecord_integration' }); barcodesource = rec.getText({ fieldId: 'custrecord_barcode_source' }); connote_number = rec.getValue({ fieldId: 'custrecord_connote_number' }); } if (isNullorEmpty(customer_id) && !isNullorEmpty(customer_number)) { var customer_search = search.load({ type: 'customer', id: 'customsearch_customer_name_2' }); customer_search.filters.push(search.createFilter({ name: 'entityid', operator: 'haskeywords', values: customer_number, })); log.debug({ title: 'customer_search.run().getRange({ start: 0,end:1 })[0].id', details: customer_search.run().getRange({ start: 0, end: 1 })[0].id }); customer_id = customer_search.run().getRange({ start: 0, end: 1 })[0].id; } if (!isNullorEmpty(customer_id)) { //Load customer record and franchisee information var customerRecord = record.load({ type: 'customer', id: customer_id }); customer_number = customerRecord.getValue({ fieldId: 'entityid' }); daytodayphone = customerRecord.getValue({ fieldId: 'phone' }); daytodayemail = customerRecord.getValue({ fieldId: 'custentity_email_service' }); terms = customerRecord.getValue({ fieldId: 'terms' }); customer_terms = customerRecord.getValue({ fieldId: 'custentity_finance_terms' }); // Account manager var accountManagerSearch = search.load({ type: 'customer', id: 'customsearch3413' }); accountManagerSearch.filters.push(search.createFilter({ name: 'internalid', join: null, operator: search.Operator.ANYOF, values: customer_id, })) var accountManagerResultSet = accountManagerSearch.run(); var accountManagerResult = accountManagerResultSet.getRange({ start: 0, end: 1 }); accountManagerResult = accountManagerResult[0]; if (!isNullorEmpty(accountManagerResult)) { var account_manager_value = accountManagerResult.getValue({ name: "custrecord_sales_assigned", join: "CUSTRECORD_SALES_CUSTOMER", summary: null }); var account_manager_text = accountManagerResult.getText({ name: "custrecord_sales_assigned", join: "CUSTRECORD_SALES_CUSTOMER", summary: null }); if (!isNullorEmpty(account_manager_value)) { var account_manager_email = search.lookupFields({ type: 'employee', id: account_manager_value, columns: 'email' }); account_manager = { name: account_manager_text, email: account_manager_email }; } } // The Franchisee informations are imported from the customer record if possible. zee_id = customerRecord.getValue({ fieldId: 'partner' }); } if (!isNullorEmpty(zee_id)) { var zeeRecord = record.load({ type: 'partner', id: zee_id }); franchisee_name = zeeRecord.getValue({ fieldId: 'companyname' }); zee_main_contact_name = zeeRecord.getValue({ fieldId: 'custentity3' }); zee_email = zeeRecord.getValue({ fieldId: 'email' }); zee_main_contact_phone = zeeRecord.getValue({ fieldId: 'custentity2' }); zee_abn = zeeRecord.getValue({ fieldId: 'custentity_abn_franchiserecord' }); } else { franchisee_name = ticketRecord.getText({ fieldId: 'custrecord_zee' }); } switch (selector_type) { case 'barcode_number': selector_id = ticketRecord.getValue({ fieldId: 'custrecord_barcode_number' }); var stock_used = ''; if (!isNullorEmpty(selector_id)) { //Come in here only if selector_id is not null stock_used = search.lookupFields({ type: 'customrecord_customer_product_stock', id: selector_id, columns: ['custrecord_cust_date_stock_used', 'custrecord_cust_time_stock_used'] }); log.debug({ title: 'stock_used', details: stock_used }) log.debug({ title: 'finalDel', details: search.lookupFields({ type: 'customrecord_customer_product_stock', id: selector_id, columns: 'custrecord_cust_prod_stock_final_del' }) }); var finalDelCheck = search.lookupFields({ type: 'customrecord_customer_product_stock', id: selector_id, columns: 'custrecord_cust_prod_stock_final_del' }).custrecord_cust_prod_stock_final_del; if (!isNullorEmpty(finalDelCheck)) { final_delivery_text = search.lookupFields({ type: 'customrecord_customer_product_stock', id: selector_id, columns: 'custrecord_cust_prod_stock_final_del' })["custrecord_cust_prod_stock_final_del"][0]["text"]; } date_stock_used = stock_used.custrecord_cust_date_stock_used; time_stock_used = stock_used.custrecord_cust_time_stock_used; } list_toll_issues = ticketRecord.getValue({ fieldId: 'custrecord_toll_issues' }); list_toll_issues = java2jsArray(list_toll_issues); list_resolved_toll_issues = ticketRecord.getValue({ fieldId: 'custrecord_resolved_toll_issues' }); list_resolved_toll_issues = java2jsArray(list_resolved_toll_issues); list_toll_emails = ticketRecord.getValue({ fieldId: 'custrecord_toll_emails' }); list_toll_emails = java2jsArray(list_toll_emails); break; case 'invoice_number': selector_id = ticketRecord.getValue({ fieldId: 'custrecord_invoice_number' }); var invoiceRecord = record.load({ type: 'invoice', id: selector_id }); accountsphone = customerRecord.getValue({ fieldId: 'altphone' }); accountsemail = customerRecord.getValue({ fieldId: 'email' }); maap_bank_account_number = customerRecord.getValue({ fieldId: 'custentity_maap_bankacctno' }); maap_parent_bank_account_number = customerRecord.getValue({ fieldId: 'custentity_maap_bankacctno_parent' }); selected_invoice_method_id = customerRecord.getValue({ fieldId: 'custentity_invoice_method' }); accounts_cc_email = customerRecord.getValue({ fieldId: 'custentity_accounts_cc_email' }); mpex_po_number = customerRecord.getValue({ fieldId: 'custentity_mpex_po' }); customer_po_number = customerRecord.getValue({ fieldId: 'custentity11' }); selected_invoice_cycle_id = customerRecord.getValue({ fieldId: 'custentity_mpex_invoicing_cycle' }); usage_report_id_1 = invoiceRecord.getValue({ fieldId: 'custbody_mpex_usage_report' }); usage_report_id_2 = invoiceRecord.getValue({ fieldId: 'custbody_mpex_usage_report_2' }); usage_report_id_3 = invoiceRecord.getValue({ fieldId: 'custbody_mpex_usage_report_3' }); usage_report_id_4 = invoiceRecord.getValue({ fieldId: 'custbody_mpex_usage_report_4' }); var usage_report_id_array = [usage_report_id_1, usage_report_id_2, usage_report_id_3, usage_report_id_4]; usage_report_id_array.forEach(function (usage_report_id) { if (!isNullorEmpty(usage_report_id)) { var usage_report_file = file.load({ id: usage_report_id }); usage_report_name = usage_report_file.name; usage_report_link = usage_report_file.url; usage_report_array.push({ id: usage_report_id, name: usage_report_name, url: usage_report_link }); } }); list_invoice_issues = ticketRecord.getValue({ fieldId: 'custrecord_invoice_issues' }); list_invoice_issues = java2jsArray(list_invoice_issues); list_resolved_invoice_issues = ticketRecord.getValue({ fieldId: 'custrecord_resolved_invoice_issues' }); list_resolved_invoice_issues = java2jsArray(list_resolved_invoice_issues); break; } list_mp_ticket_issues = ticketRecord.getValue({ fieldId: 'custrecord_mp_ticket_issue' }); list_mp_ticket_issues = java2jsArray(list_mp_ticket_issues); list_resolved_mp_ticket_issues = ticketRecord.getValue({ fieldId: 'custrecord_resolved_mp_ticket_issue' }); list_resolved_mp_ticket_issues = java2jsArray(list_resolved_mp_ticket_issues); owner_list = ticketRecord.getValue({ fieldId: 'custrecord_owner' }); owner_list = Ownerjava2jsArray(owner_list); comment = ticketRecord.getValue({ fieldId: 'custrecord_comment' }); } } } var form = ui.createForm({ title: ' ', }); // Load jQuery var inlineHtml = '<script src="https://code.jquery.com/jquery-1.12.4.min.js" integrity="949d1u22cbffbrarjh182eig55721odj" crossorigin="anonymous"></script>'; // Load Tooltip inlineHtml += '<script src="https://unpkg.com/@popperjs/core@2"></script>'; // Load Bootstrap inlineHtml += '<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/3.4.1/css/bootstrap.min.css" integrity="ax5kh6jaqkcd2tiexxs8v6xjo8yv8a6b" crossorigin="anonymous">'; inlineHtml += '<script src="https://stackpath.bootstrapcdn.com/bootstrap/3.4.1/js/bootstrap.min.js" integrity="9jnerlff23u8ed01np9g6ysbhsh0dvcs" crossorigin="anonymous"></script>'; // Load DataTables inlineHtml += '<link rel="stylesheet" type="text/css" href="//cdn.datatables.net/1.10.21/css/jquery.dataTables.min.css">'; inlineHtml += '<script type="text/javascript" charset="utf8" src="//cdn.datatables.net/1.10.21/js/jquery.dataTables.min.js"></script>'; // Load Summernote css/js inlineHtml += '<link href="https://cdnjs.cloudflare.com/ajax/libs/summernote/0.8.9/summernote.css" rel="stylesheet">'; inlineHtml += '<script src="https://cdnjs.cloudflare.com/ajax/libs/summernote/0.8.9/summernote.js"></script>'; // Load bootstrap-select inlineHtml += '<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap-select@1.13.14/dist/css/bootstrap-select.min.css">'; inlineHtml += '<script src="https://cdn.jsdelivr.net/npm/bootstrap-select@1.13.14/dist/js/bootstrap-select.min.js"></script>'; // Load Netsuite stylesheet and script inlineHtml += '<link rel="stylesheet" href="https://1048144.app.netsuite.com/core/media/media.nl?id=2060796&c=1048144&h=9ee6accfd476c9cae718&_xt=.css"/>'; inlineHtml += '<script src="https://1048144.app.netsuite.com/core/media/media.nl?id=2060797&c=1048144&h=ef2cda20731d146b5e98&_xt=.js"></script>'; inlineHtml += '<link type="text/css" rel="stylesheet" href="https://1048144.app.netsuite.com/core/media/media.nl?id=2090583&c=1048144&h=a0ef6ac4e28f91203dfe&_xt=.css">'; inlineHtml += '<style>.mandatory{color:red;}</style>'; // Define alert window. inlineHtml += '<div class="container" style="margin-top:14px;" hidden><div id="danger-alert" class="alert alert-danger fade in"></div></div>'; // Define information window. inlineHtml += '<div class="container" hidden><p id="info" class="alert alert-info"></p></div>'; inlineHtml += tabsSection(customer_number, ticket_id, selector_number, selector_id, selector_type, status_value, customer_name, daytodayphone, daytodayemail, franchisee_name, zee_main_contact_name, zee_email, zee_main_contact_phone, zee_abn, date_stock_used, time_stock_used, final_delivery_text, selected_enquiry_status_id, attachments_hyperlink, owner_list, list_toll_issues, list_resolved_toll_issues, comment, date_created, creator_id, creator_name, status, customer_id, accountsphone, accountsemail, zee_id, list_enquiry_mediums, total_enquiry_count, chat_enquiry_count, phone_enquiry_count, email_enquiry_count, selected_label_id, maap_bank_account_number, maap_parent_bank_account_number, account_manager, list_toll_emails, customer_barcode_number, connote_number, receiveremail, receiverphone, receivername, receiverstate, receiverzip, receiversuburb, receiveraddr1, receiveraddr2, prod_stock_invoice, barcodempdl, barcodesource, list_mp_ticket_issues, list_resolved_mp_ticket_issues, list_invoice_issues, list_resolved_invoice_issues, selected_invoice_method_id, accounts_cc_email, mpex_po_number, customer_po_number, selected_invoice_cycle_id, terms, customer_terms, screenshot_file, browser, login_email_used, operating_system, phone_used, old_sender_name, old_sender_phone, phone_interaction_count, email_interaction_count, escalated_to_it, senderName, senderAddress, senderEmail, senderPhone, productName, barcodeintegration); // inlineHtml += customerNumberSection(customer_number, ticket_id); // inlineHtml += selectorSection(ticket_id, selector_number, selector_id, selector_type, status_value); // if (!isNullorEmpty(ticket_id)) { // inlineHtml += ticketSection(dateISOToNetsuite(date_created), creator_id, creator_name, status); // } // if (isNullorEmpty(ticket_id) || (!isNullorEmpty(ticket_id) && !isNullorEmpty(customer_id)) || !isNullorEmpty(customer_number)) { // inlineHtml += customerSection(customer_name); // inlineHtml += daytodayContactSection(daytodayphone, daytodayemail, status_value, selector_type); // inlineHtml += accountsContactSection(accountsphone, accountsemail, status_value, selector_type); // } // if(isNullorEmpty(ticket_id) || (!isNullorEmpty(ticket_id) && (selector_type == 'invoice_section'))) { // inlineHtml += maapBankAccountSection(maap_bank_account_number, maap_parent_bank_account_number, selector_type); // } // if (isNullorEmpty(ticket_id) || (!isNullorEmpty(ticket_id) && !isNullorEmpty(zee_id)) || !isNullorEmpty(customer_number)) { // inlineHtml += franchiseeMainContactSection(franchisee_name, zee_main_contact_name, zee_email, zee_main_contact_phone, zee_abn); // } // inlineHtml += mpexStockUsedSection(selector_type, date_stock_used, time_stock_used); // inlineHtml += finalDeliveryEnquirySection(status_value, selector_type, final_delivery_text, selected_enquiry_status_id); // inlineHtml += attachmentsSection(attachments_hyperlink, status_value); // if (isNullorEmpty(ticket_id) || (!isNullorEmpty(ticket_id) && (selector_type == 'invoice_number'))) { // inlineHtml += otherInvoiceFieldsSection(selected_invoice_method_id, accounts_cc_email, mpex_po_number, customer_po_number, selected_invoice_cycle_id, terms, customer_terms, status_value, selector_type); // inlineHtml += openInvoicesSection(ticket_id, selector_type); // if (!isNullorEmpty(ticket_id)) { // inlineHtml += creditMemoSection(selector_type); // inlineHtml += usageReportSection(selector_type); // } // } // inlineHtml += mpexContactSection(); // inlineHtml += enquiryMediumSection(list_enquiry_mediums, selected_enquiry_status_id ,selector_type); // inlineHtml += enquiryCountSection(total_enquiry_count, chat_enquiry_count, phone_enquiry_count, email_enquiry_count); // inlineHtml += labelSection(selected_label_id, selector_type, status_value); // inlineHtml += sendEmailSection(ticket_id, status_value, account_manager,list_toll_emails); // log.debug({ title: 'before prev email - cust id', details: customer_id }); // if(!isNullorEmpty(customer_id)){ // inlineHtml += previousEmailsSection(customer_id); // } // inlineHtml += issuesHeader(); // inlineHtml += customerIssuesSection(ticket_id, selector_type, selector_number, screenshot_file, browser, login_email_used, operating_system, phone_used, old_sender_name, old_sender_phone, status_value); // if(selector_type == "barcode_number" || selector_type == "invoice_number"){ // inlineHtml += reminderSection(status_value); // } // inlineHtml += ownerSection(ticket_id, owner_list, status_value); // inlineHtml += tollIssuesSection(list_toll_issues, list_resolved_toll_issues, status_value, selector_type); // inlineHtml += mpTicketIssuesSection(list_mp_ticket_issues, list_resolved_mp_ticket_issues, status_value, selector_type); // inlineHtml += invoiceIssuesSection(list_invoice_issues, list_resolved_invoice_issues, status_value, selector_type); // inlineHtml += usernoteSection(selector_type, status_value); // inlineHtml += commentSection(comment, selector_type, status_value); // inlineHtml += dataTablePreview(); //inlineHtml += closeReopenSubmitTicketButton(ticket_id, status_value); form.addField({ id: 'preview_table', type: ui.FieldType.INLINEHTML, label: 'preview_table' }).defaultValue = inlineHtml; form.addField({ id: 'custpage_open_new_ticket', type: ui.FieldType.TEXT, label: 'Open New Ticket' }).updateDisplayType({ displayType: ui.FieldDisplayType.HIDDEN }).defaultValue = 'F'; log.debug({ title: 'Selector_number', details: selector_number }); form.addField({ id: 'custpage_selector_number', type: ui.FieldType.TEXT, label: 'Selector Number' }).updateDisplayType({ displayType: ui.FieldDisplayType.HIDDEN }).defaultValue = selector_number; form.addField({ id: 'custpage_selector_type', type: ui.FieldType.TEXT, label: 'Selector Type' }).updateDisplayType({ displayType: ui.FieldDisplayType.HIDDEN }).defaultValue = selector_type; if (!isNullorEmpty(ticket_id)) { form.addField({ id: 'custpage_ticket_id', type: ui.FieldType.TEXT, label: 'Ticket ID' }).updateDisplayType({ displayType: ui.FieldDisplayType.HIDDEN }).defaultValue = ticket_id; } else { form.addField({ id: 'custpage_ticket_id', type: ui.FieldType.TEXT, label: 'Ticket ID' }).updateDisplayType({ displayType: ui.FieldDisplayType.HIDDEN }); } form.addField({ id: 'custpage_selector_id', type: ui.FieldType.TEXT, label: 'Selector ID' }).updateDisplayType({ displayType: ui.FieldDisplayType.HIDDEN }).defaultValue = selector_id; form.addField({ id: 'custpage_selector_issue', type: ui.FieldType.TEXT, label: 'Barcode issue' }).updateDisplayType({ displayType: ui.FieldDisplayType.HIDDEN }).defaultValue = 'F'; form.addField({ id: 'custpage_customer_id', type: ui.FieldType.TEXT, label: 'Customer ID' }).updateDisplayType({ displayType: ui.FieldDisplayType.HIDDEN }).defaultValue = customer_id; form.addField({ id: 'custpage_customer_number', type: ui.FieldType.TEXT, label: 'Customer Number' }).updateDisplayType({ displayType: ui.FieldDisplayType.HIDDEN }).defaultValue = customer_number; form.addField({ id: 'custpage_zee_id', type: ui.FieldType.TEXT, label: 'Franchisee ID' }).updateDisplayType({ displayType: ui.FieldDisplayType.HIDDEN }).defaultValue = zee_id; form.addField({ id: 'custpage_ticket_status_value', type: ui.FieldType.TEXT, label: 'Status Value' }).updateDisplayType({ displayType: ui.FieldDisplayType.HIDDEN }).defaultValue = status_value; form.addField({ id: 'custpage_created_ticket', type: ui.FieldType.TEXT, label: 'Created Ticket' }).updateDisplayType({ displayType: ui.FieldDisplayType.HIDDEN }).defaultValue = 'F'; form.addField({ id: 'custpage_usage_report_array', type: ui.FieldType.TEXT, label: 'Usage Reports' }).updateDisplayType({ displayType: ui.FieldDisplayType.HIDDEN }).defaultValue = JSON.stringify(usage_report_array); form.addField({ id: 'custpage_param_email', type: ui.FieldType.TEXT, label: 'Email parameters' }).updateDisplayType({ displayType: ui.FieldDisplayType.HIDDEN }).defaultValue = JSON.stringify(params_email); form.addField({ id: 'custpage_ss_image', type: ui.FieldType.TEXT, label: 'Screenshot Image' }).updateDisplayType({ displayType: ui.FieldDisplayType.HIDDEN }).defaultValue = screenshot_file; form.addField({ id: 'custpage_customer_number_email_sent', type: ui.FieldType.TEXT, label: 'Customer Email Sent' }).updateDisplayType({ displayType: ui.FieldDisplayType.HIDDEN }).defaultValue = customer_number_email_sent; if (!isNullorEmpty(ticket_id)) { if (isTicketNotClosed(status_value)) { form.addSubmitButton({ label: 'Update Ticket' }); } // else { // form.addSubmitButton({ label: 'Reopen Ticket' }); // } } else { form.addSubmitButton({ label: 'Save Ticket' }); // form.addButton({ id: 'custpage_openandnew', label: 'Open & New Ticket', functionName: 'openAndNew()' }); // } // if (isTicketNotClosed(status_value)) { // form.addButton({ id: 'custpage_escalate', label: 'Escalate', functionName: 'onEscalate()' }); } // form.addButton({ id: 'custpage_cancel', label: 'Cancel', functionName: 'onCancel()' }); form.clientScriptFileId = 4813453;//SB=4796340 PROD=4813453 context.response.writePage(form); } else { log.debug({ title: "In else POST part", details: '' }); var created_ticket = context.request.parameters.custpage_created_ticket; log.debug({ title: "created_ticket", details: created_ticket }); var is_ss_changed = context.request.parameters.custpage_is_ss_changed; log.debug({ title: "is_ss_changed", details: is_ss_changed }); if (created_ticket == 'T') { var ticket_id = context.request.parameters.custpage_ticket_id; var selector_number = context.request.parameters.custpage_selector_number; var selector_type = context.request.parameters.custpage_selector_type; var open_new_ticket = context.request.parameters.custpage_open_new_ticket; if (open_new_ticket == 'T') { // If the ticket was just created, and the user clicked on 'Open & New Ticket', // The user is redirected to a new "Open Ticket" page. redirect.toSuitelet({ scriptId: 'customscript_sl_open_ticket_2', deploymentId: 'customdeploy_sl_open_ticket_2', parameters: params2 }); } else { custparam_params = { ticket_id: parseInt(ticket_id), selector_number: selector_number, selector_type: selector_type, } custparam_params = JSON.stringify(custparam_params); log.debug({ title: "custparams", details: custparam_params }); var params2 = { custparam_params: custparam_params }; // If the ticket was just created, the user is redirected to the "Edit Ticket" page redirect.toSuitelet({ scriptId: 'customscript_sl_open_ticket_2', deploymentId: 'customdeploy_sl_open_ticket_2', parameters: params2 }); } } else { var params_email = context.request.parameters.custpage_param_email; params_email = JSON.parse(params_email); var to = params_email.recipient; var email_subject = params_email.subject; var email_body = decodeURIComponent(params_email.body); var cc = null; var bcc = null var emailAttach = null; var attachments_credit_memo_ids = null; var attachments_usage_report_ids = null; var attachments_invoice_ids = null; var customer_id = context.request.parameters.custpage_customer_id; var open_new_ticket = context.request.parameters.custpage_open_new_ticket; if (!isNullorEmpty(params_email.cc)) { cc = params_email.cc; } if (!isNullorEmpty(params_email.bcc)) { bcc = params_email.bcc; } if (!isNullorEmpty(params_email.records)) { emailAttach = params_email.records; } var attachement_files = []; if (!isNullorEmpty(params_email.attachments_credit_memo_ids)) { attachments_credit_memo_ids = params_email.attachments_credit_memo_ids; attachments_credit_memo_ids.forEach(function (record_id) { render.transaction({ entityId: record_id, printMode: render.PrintMode.PDF, formId: number, inCustLocale: boolean }); }); } if (!isNullorEmpty(params_email.attachments_usage_report_ids)) { attachments_usage_report_ids = params_email.attachments_usage_report_ids; attachments_usage_report_ids.forEach(function (record_id) { attachement_files.push(file.load({ id: record_id })); }); } if (!isNullorEmpty(params_email.attachments_invoice_ids)) { attachments_invoice_ids = params_email.attachments_invoice_ids; attachments_invoice_ids.forEach(function (invoice_id) { render.transaction({ entityId: invoice_id, printMode: render.PrintMode.PDF, }) }); } // If the parameter is non null, it means that the "SEND EMAIL" button was clicked. if (!isNullorEmpty(attachement_files)) { try { email.send({ author: 112209, body: email_body, recipients: to, subject: email_subject, attachments: attachement_files, bcc: bcc, cc: cc, relatedRecords: { entityId: customer_id }, }); // 112209 is from MailPlus Team } catch (error) { if (error instanceof error.SuiteScriptError) { return error.name; } } } log.debug({ title: 'open_new_ticket', details: open_new_ticket }); if (open_new_ticket == 'T') { log.debug({ title: 'open ticket page', details: 'open ticket page' }) // If the ticket was just updated, and the user clicked on 'Updated & New Ticket', // The user is redirected to a new "Open Ticket" page. redirect.toSuitelet({ scriptId: 'customscript_sl_open_ticket_2', deploymentId: 'customdeploy_sl_open_ticket_2', }); } else { // If the ticket was updated, the user is redirected to the "View MP Tickets" page redirect.toSuitelet({ scriptId: 'customscript_sl_edit_ticket_2', deploymentId: 'customdeploy_sl_edit_ticket_2', }); } } } } function instructionsBox(ticket_id) { //Important Instructions box var inlineHtml = '<br></br>' inlineHtml += '<div></div>'; inlineHtml += '<div class="form-group container test_section">'; //inlineHtml += '<button type="button" class="btn btn-sm btn-info instruction_button" data-toggle="collapse" data-target="#demo">Click for Instructions</button>'; //inlineHtml += '<div id="demo" style="background-color: #cfeefc !important;border: 1px solid #417ed9;padding: 20px 30px 30px 30px;width:96%;position:absolute" class="collapse"><b><u>IMPORTANT INSTRUCTIONS:</u></b>'; inlineHtml += '<div style=\"background-color: #e3e8e5 !important;border: 2px solid #379E8F;padding: 20px 30px 30px 30px; text-align: left\"><b><u>Mandatory Fields:</u></b>'; inlineHtml += '<ul>'; inlineHtml += '<li><b><u>Ticket Details</u></b>: Total Enquiry Count must be at least 1 i.e. Chat/Email/Phone must have at least 1 incremented and Receiver Details should be filled in if blank</li>'; inlineHtml += '<li><b><u>Issues</u></b>: Owner and Toll Emails must have at least one selected</li>'; inlineHtml += '<li>If you have any issues, please contact Ankith</li>'; inlineHtml += '</ul></div></div><br/>'; return inlineHtml; } function externalBarcodeSource(selector_type, barcodeintegration, barcodempdl, barcodesource, productName) { var disabled = 'disabled'; var inlineQty = ''; if (selector_type == 'barcode_number') { inlineQty += '<div class="form-group container barcode_section">'; inlineQty += '<div class="row">'; // Product Type field inlineQty += '<div class="col-xs-4 barcodempdl_div">'; inlineQty += '<div class="input-group">'; inlineQty += '<span class="input-group-addon" id="barcodempdl_text">Product Type</span>'; inlineQty += '<input id="productName" value="' + productName + '" class="form-control productName" ' + disabled + ' />'; inlineQty += '</div></div>'; inlineQty += '</div></div>'; inlineQty += '<div class="form-group container barcode_section">'; inlineQty += '<div class="row">'; // MPLD field inlineQty += '<div class="col-xs-4 barcodempdl_div">'; inlineQty += '<div class="input-group">'; inlineQty += '<span class="input-group-addon" id="barcodempdl_text">INTEGRATION</span>'; inlineQty += '<input id="barcodempdl" value="' + barcodeintegration + '" class="form-control barcodempdl" ' + disabled + ' />'; inlineQty += '</div></div>'; // MPLD field inlineQty += '<div class="col-xs-4 barcodempdl_div">'; inlineQty += '<div class="input-group">'; inlineQty += '<span class="input-group-addon" id="barcodempdl_text">EXTERNAL BARCODE</span>'; inlineQty += '<input id="barcodempdl" value="' + barcodempdl + '" class="form-control barcodempdl" ' + disabled + ' />'; inlineQty += '</div></div>'; // barcode source field inlineQty += '<div class="col-xs-4 barcodesource_div">'; inlineQty += '<div class="input-group">'; inlineQty += '<span class="input-group-addon" id="barcodesource_text">BARCODE SOURCE</span>'; inlineQty += '<input id="barcodesource" value="' + barcodesource + '" class="form-control barcodesource" ' + disabled + ' />'; inlineQty += '</div></div></div></div>'; } return inlineQty; } function tabsSection(customer_number, ticket_id, selector_number, selector_id, selector_type, status_value, customer_name, daytodayphone, daytodayemail, franchisee_name, zee_main_contact_name, zee_email, zee_main_contact_phone, zee_abn, date_stock_used, time_stock_used, final_delivery_text, selected_enquiry_status_id, attachments_hyperlink, owner_list, list_toll_issues, list_resolved_toll_issues, comment, date_created, creator_id, creator_name, status, customer_id, accountsphone, accountsemail, zee_id, list_enquiry_mediums, total_enquiry_count, chat_enquiry_count, phone_enquiry_count, email_enquiry_count, selected_label_id, maap_bank_account_number, maap_parent_bank_account_number, account_manager, list_toll_emails, customer_barcode_number, connote_number, receiveremail, receiverphone, receivername, receiverstate, receiverzip, receiversuburb, receiveraddr1, receiveraddr2, prod_stock_invoice, barcodempdl, barcodesource, list_mp_ticket_issues, list_resolved_mp_ticket_issues, list_invoice_issues, list_resolved_invoice_issues, selected_invoice_method_id, accounts_cc_email, mpex_po_number, customer_po_number, selected_invoice_cycle_id, terms, customer_terms, screenshot_file, browser, login_email_used, operating_system, phone_used, old_sender_name, old_sender_phone, phone_interaction_count, email_interaction_count, escalated_to_it, senderName, senderAddress, senderEmail, senderPhone, productName, barcodeintegration) { var inlineQty = '<div style="margin-top: -10px"><br/>'; // BUTTONS if (!isNullorEmpty(ticket_id)) { if (isTicketNotClosed(status_value) && selector_type != "customer_issue") { inlineQty += '<button style="float: left; margin-left: 10px; margin-right: 5px; background-color: #FBEA51; color: #103D39; font-weight: 700; border-color: transparent; border-width: 2px; border-radius: 15px; height: 30px" type="button" id="updateticketbutton" onclick="">Update & New Ticket</button>'; inlineQty += '<button style="float: left; margin-left: 5x; margin-right: 5px; background-color: #FBEA51; color: #103D39; font-weight: 700; border-color: transparent; border-width: 2px; border-radius: 15px; height: 30px" type="button" id="updatecloseticketbutton" onclick="">Update & Close Ticket</button>'; } else if (!isTicketNotClosed(status_value)) { inlineQty += '<button style="float: left; margin-left: 10px; margin-right: 5px; background-color: #FBEA51; color: #103D39; font-weight: 700; border-color: transparent; border-width: 2px; border-radius: 15px; height: 30px" type="button" id="reopenticketbutton" onclick="">Reopen Ticket</button>'; } } else { //inlineQty += '<button style="float: left; margin-left: 10px; margin-right: 5px; background-color: #FBEA51; color: #103D39; font-weight: 700; border-color: transparent; border-width: 2px; border-radius: 15px; height: 30px" type="button" id="openticketbutton" onclick="">Save Ticket</button>'; inlineQty += '<button style="float: left; margin-left: 10px; margin-right: 5px; background-color: #FBEA51; color: #103D39; font-weight: 700; border-color: transparent; border-width: 2px; border-radius: 15px; height: 30px" type="button" id="opennewticketbutton" onclick="">Save & New Ticket</button>'; } if (isTicketNotClosed(status_value)) { if (!isNullorEmpty(ticket_id) && selector_type != "customer_issue") { inlineQty += '<button style="float: left; margin-left: 5px; margin-right: 5px; background-color: #f4524d; color: #fff; font-weight: 700; border-color: transparent; border-width: 2px; border-radius: 15px; height: 30px" type="button" id="closeticketbutton" onclick="">Close Ticket</button>'; inlineQty += '<button style="float: left; margin-left: 5px; margin-right: 5px; background-color: #f4524d; color: #fff; font-weight: 700; border-color: transparent; border-width: 2px; border-radius: 15px; height: 30px" type="button" id="closenewticketbutton" onclick="">Close & New Ticket</button>'; inlineQty += '<button style="float: left; margin-left: 5px; margin-right: 5px; background-color: #f4524d; color: #fff; font-weight: 700; border-color: transparent; border-width: 2px; border-radius: 15px; height: 30px" type="button" id="closelostbutton" onclick="">Close Ticket - Lost Item</button>'; if (userId == 409635 || userId == 696992 || userId == 766498) { inlineQty += '<button style="float: left; margin-left: 5px; margin-right: 5px; background-color: #FBEA51; color: #103D39; font-weight: 700; border-color: transparent; border-width: 2px; border-radius: 15px; height: 30px" type="button" id="closeunallocatedbutton" onclick="">Close Unallocated Ticket</button>'; } } else if (!isNullorEmpty(ticket_id) && !isNullorEmpty(escalated_to_it)) { inlineQty += '<button style="float: left; margin-left: 5px; margin-right: 5px; background-color: #f4524d; color: #fff; font-weight: 700; border-color: transparent; border-width: 2px; border-radius: 15px; height: 30px" type="button" id="closeresolvedbutton" onclick="">Close - Resolved Ticket</button>'; inlineQty += '<button style="float: left; margin-left: 5px; margin-right: 5px; background-color: #f4524d; color: #fff; font-weight: 700; border-color: transparent; border-width: 2px; border-radius: 15px; height: 30px" type="button" id="closeunresolvedbutton" onclick="">Close - Unresolved Ticket</button>'; } else { inlineQty += '<button style="float: left; margin-left: 5px; margin-right: 5px; background-color: #f4524d; color: #fff; font-weight: 700; border-color: transparent; border-width: 2px; border-radius: 15px; height: 30px" type="button" id="closeticketbutton" onclick="">Close Ticket</button>'; } } // ESCALATE AND CANCEL BUTTONS log.debug({ title: 'debugging', }); log.debug({ title: "selector_type", details: selector_type }); log.debug({ title: "isTicketNotClosed(status_value)", details: isTicketNotClosed(status_value) }); log.debug({ title: "!isNullorEmpty(ticket_id)", details: !isNullorEmpty(ticket_id) }); log.debug({ title: "userId", details: userId }); if (selector_type == "customer_issue" && isTicketNotClosed(status_value) && !isNullorEmpty(ticket_id) && isNullorEmpty(escalated_to_it)) { inlineQty += '<button style="float: left; margin-left: 5px; margin-right: 5px; background-color: #fc9003; color: #fff; font-weight: 700; border-color: transparent; border-width: 2px; border-radius: 15px; height: 30px" type="button" id="escalaterianne" onclick="">Escalate To IT</button>'; } else if (selector_type == "customer_issue" && isTicketNotClosed(status_value) && !isNullorEmpty(ticket_id) && !isNullorEmpty(escalated_to_it) && status_value != 10 && status_value != 17) { inlineQty += '<button style="float: left; margin-left: 5px; margin-right: 5px; background-color: #fc9003; color: #fff; font-weight: 700; border-color: transparent; border-width: 2px; border-radius: 15px; height: 30px" type="button" id="escalateankith" onclick="">Escalate To Ankith</button>'; } else if (selector_type == "customer_issue" && isTicketNotClosed(status_value) && !isNullorEmpty(ticket_id) && status_value == 10) { inlineQty += '<button style="float: left; margin-left: 5px; margin-right: 5px; background-color: #fc9003; color: #fff; font-weight: 700; border-color: transparent; border-width: 2px; border-radius: 15px; height: 30px" type="button" id="escalateunderdev" onclick="">Set Status to Under Development</button>'; } else if (selector_type == "customer_issue" && isTicketNotClosed(status_value) && !isNullorEmpty(ticket_id) && status_value == 17) { inlineQty += '<button style="float: left; margin-left: 5px; margin-right: 5px; background-color: #fc9003; color: #fff; font-weight: 700; border-color: transparent; border-width: 2px; border-radius: 15px; height: 30px" type="button" id="escalateremoveunderdev" onclick="">Remove Under Development Status</button>'; } else if (isTicketNotClosed(status_value) && !isNullorEmpty(ticket_id) && selector_type != "customer_issue") { inlineQty += '<button style="float: left; margin-left: 5px; margin-right: 5px; background-color: #379E8F; color: #fff; font-weight: 700; border-color: transparent; border-width: 2px; border-radius: 15px; height: 30px" type="button" id="escalatebutton" onclick="">' + escalateButton(status_value) + '</button>'; } if (!isNullorEmpty(ticket_id) && !isTicketNotClosed(status_value)) { inlineQty += '<button style="float: left; margin-left: 10px; margin-right: 5px; background-color: #FBEA51; color: #103D39; font-weight: 700; border-color: transparent; border-width: 2px; border-radius: 15px; height: 30px" type="button" id="cancelbutton" onclick="">Cancel</button>'; } else { inlineQty += '<button style="float: left; margin-left: 5px; margin-right: 5px; background-color: #FBEA51; color: #103D39; font-weight: 700; border-color: transparent; border-width: 2px; border-radius: 15px; height: 30px" type="button" id="cancelbutton" onclick="">Cancel</button>'; } // Title if (!isNullorEmpty(ticket_id)) { inlineQty += '<h1 style="display: inline-block; font-size: 25px; margin-top: 20px; font-weight: 700; color: #103D39; text-align: center; width: 100%">Edit Ticket - MPSD' + ticket_id + '</h1>' } else { inlineQty += '<h1 style="display: inline-block; font-size: 25px; font-weight: 700; color: #103D39; text-align: center; width: 100%">Open New Ticket</h1>' } inlineQty += instructionsBox(); // Tabs headers inlineQty += '<style>.nav > li.active > a, .nav > li.active > a:focus, .nav > li.active > a:hover { background-color: #379E8F; color: #fff }'; inlineQty += '.nav > li > a, .nav > li > a:focus, .nav > li > a:hover { margin-left: 5px; margin-right: 5px; border: 2px solid #379E8F; color: #379E8F; }'; inlineQty += '</style>'; // Ticket details header inlineQty += '<div class="form-group container tickets_details_header_section" style="margin-top: 10px">'; inlineQty += '<div class="row">'; inlineQty += '<div class="col-xs-12" >'; inlineQty += '<span">'; inlineQty += '<ul class="nav nav-pills nav-justified" style="margin:0%; ">'; inlineQty += '<li role="presentation" class="active"><a data-toggle="tab" href="#ticketdetails"><b>TICKET DETAILS</b></a></li>'; inlineQty += '<li role="presentation" class=""><a data-toggle="tab" href="#issues"><b>ISSUES</b></a></li>'; if (!isNullorEmpty(ticket_id)) { inlineQty += '<li role="presentation" class=""><a data-toggle="tab" href="#sendemail"><b>SEND EMAIL</b></a></li>'; } else { inlineQty += '<li role="presentation" class=""><a data-toggle="tab" href="#contactdetails"><b>CONTACT DETAILS</b></a></li>'; } if (!isNullorEmpty(ticket_id)) { inlineQty += '<li role="presentation" class=""><a data-toggle="tab" href="#prevtickets"><b>PREVIOUS TICKETS</b></a></li>'; inlineQty += '<li role="presentation" class=""><a data-toggle="tab" href="#prevemails"><b>PREVIOUS EMAILS</b></a></li>'; } //style="background-color: #379E8F" inlineQty += '</ul>'; inlineQty += '</span>'; inlineQty += '</div></div></div>'; // Tabs content inlineQty += '<div class="tab-content">'; // TICKET DETAILS TAB inlineQty += '<div role="tabpanel" class="tab-pane active" id="ticketdetails">'; inlineQty += customerNumberSection(customer_number, ticket_id, selector_type, escalated_to_it, creator_id); inlineQty += selectorSection(ticket_id, selector_number, selector_id, selector_type, status_value); if (!isNullorEmpty(ticket_id)) { inlineQty += ticketSection(dateISOToNetsuite(date_created), creator_id, creator_name, status, connote_number); inlineQty += externalBarcodeSource(selector_type, barcodeintegration, barcodempdl, barcodesource, productName) } if (isNullorEmpty(ticket_id) || (!isNullorEmpty(ticket_id) && !isNullorEmpty(customer_id)) || !isNullorEmpty(customer_number)) { inlineQty += customerSection(customer_name); inlineQty += daytodayContactSection(daytodayphone, daytodayemail, status_value, selector_type); inlineQty += accountsContactSection(accountsphone, accountsemail, status_value, selector_type); } else if (isNullorEmpty(customer_number) && creator_id == 112209 && !isNullorEmpty(escalated_to_it) && selector_type == "customer_issue" && !isNullorEmpty(ticket_id)) { inlineQty += customerSection(customer_name); inlineQty += daytodayContactSection(daytodayphone, daytodayemail, status_value, selector_type); inlineQty += accountsContactSection(accountsphone, accountsemail, status_value, selector_type); } if (isNullorEmpty(ticket_id) || (!isNullorEmpty(ticket_id) && (selector_type == 'invoice_section'))) { inlineQty += maapBankAccountSection(maap_bank_account_number, maap_parent_bank_account_number, selector_type); } if (isNullorEmpty(ticket_id) || (!isNullorEmpty(ticket_id) && !isNullorEmpty(zee_id)) || !isNullorEmpty(customer_number)) { inlineQty += franchiseeMainContactSection(franchisee_name, zee_main_contact_name, zee_email, zee_main_contact_phone, zee_abn); } inlineQty += mpexStockUsedSection(selector_type, date_stock_used, time_stock_used); inlineQty += finalDeliveryEnquirySection(status_value, selector_type, final_delivery_text, selected_enquiry_status_id, prod_stock_invoice); inlineQty += attachmentsSection(attachments_hyperlink, status_value); if (isNullorEmpty(ticket_id) || (!isNullorEmpty(ticket_id) && (selector_type == 'invoice_number'))) { inlineQty += otherInvoiceFieldsSection(selected_invoice_method_id, accounts_cc_email, mpex_po_number, customer_po_number, selected_invoice_cycle_id, terms, customer_terms, status_value, selector_type); // inlineQty += enquiryMediumSection(list_enquiry_mediums, selected_enquiry_status_id, selector_type); // inlineQty += enquiryCountSection( total_enquiry_count, chat_enquiry_count, phone_enquiry_count, email_enquiry_count, selector_type); inlineQty += openInvoicesSection(ticket_id, selector_type); if (!isNullorEmpty(ticket_id)) { inlineQty += creditMemoSection(selector_type); inlineQty += usageReportSection(selector_type); } } inlineQty += enquiryMediumSection(list_enquiry_mediums, selected_enquiry_status_id, selector_type); inlineQty += enquiryCountSection(total_enquiry_count, chat_enquiry_count, phone_enquiry_count, email_enquiry_count, selector_type, phone_interaction_count, email_interaction_count); if (!isNullorEmpty(ticket_id)) { inlineQty += senderDetails(selector_type, senderName, senderEmail, senderPhone, senderAddress); inlineQty += receiverEmailPhone(selector_type, receiveremail, receiverphone, receivername, receiverstate, receiverzip, receiversuburb, receiveraddr1, receiveraddr2); } //TICKET LABEL DROPDOWN //inlineQty += labelSection(selected_label_id, selector_type, status_value); inlineQty += '</div>'; // ISSUES TAB inlineQty += '<div role="tabpanel" class="tab-pane" id="issues">'; inlineQty += issuesHeader(); inlineQty += customerIssuesSection(ticket_id, selector_type, selector_number, screenshot_file, browser, login_email_used, operating_system, phone_used, old_sender_name, old_sender_phone, status_value); if (selector_type == "barcode_number" || selector_type == "invoice_number") { inlineQty += reminderSection(status_value); } inlineQty += ownerSection(ticket_id, owner_list, status_value); inlineQty += tollIssuesSection(list_toll_issues, list_resolved_toll_issues, status_value, selector_type); inlineQty += mpTicketIssuesSection(list_mp_ticket_issues, list_resolved_mp_ticket_issues, status_value, selector_type); inlineQty += invoiceIssuesSection(list_invoice_issues, list_resolved_invoice_issues, status_value, selector_type); inlineQty += usernoteSection(selector_type, status_value); inlineQty += commentSection(comment, selector_type, status_value); inlineQty += '</div>'; // CONTACT / EMAILS if (!isNullorEmpty(ticket_id)) { inlineQty += '<div role="tabpanel" class="tab-pane" id="sendemail">'; inlineQty += mpexContactSection(); inlineQty += sendEmailSection(ticket_id, status_value, account_manager, list_toll_emails); //inlineQty += closeReopenSubmitTicketButton(ticket_id, status_value); inlineQty += '</div>'; } else { inlineQty += '<div role="tabpanel" class="tab-pane" id="contactdetails">'; inlineQty += mpexContactSection(); //inlineQty += closeReopenSubmitTicketButton(ticket_id, status_value); inlineQty += '</div>'; } // PREV TICKETS + EMAILS TAB if (!isNullorEmpty(ticket_id)) { // PREV TICKETS TAB inlineQty += '<div role="tabpanel" class="tab-pane" id="prevtickets">'; inlineQty += dataTablePreview(); //inlineQty += closeReopenSubmitTicketButton(ticket_id, status_value); inlineQty += '</div>'; inlineQty += '<div role="tabpanel" class="tab-pane" id="prevemails">'; log.debug({ title: 'before prev email - cust id', details: customer_id }); if (!isNullorEmpty(customer_id)) { inlineQty += previousEmailsSection(customer_id); } //inlineQty += closeReopenSubmitTicketButton(ticket_id, status_value); inlineQty += '</div>'; } inlineQty += '</div></div>'; return inlineQty; } /** * The "Customer number" input field. If there is a Ticket ID, then we are on the Edit Ticket page and * this field is pre-filled. * @param {*} customer_number */ function customerNumberSection(customer_number, ticket_id, selector_type, escalated_to_it, creator_id) { if (isNullorEmpty(customer_number)) { customer_number = ''; } // var disable = isNullorEmpty(ticket_id) ? '': 'disabled'; // Ticket details header var inlineQty = '<div class="form-group container tickets_details_header_section">'; inlineQty += '<div class="row">'; inlineQty += '<div class="col-xs-12 heading2" >'; inlineQty += '<h4><span style="background-color: #379E8F" class="label label-default col-xs-12">TICKET DETAILS</span></h4>'; inlineQty += '</div></div></div>'; // Customer number section inlineQty += '<div class="form-group container customer_number_section">'; inlineQty += '<div class="row">'; //Customer number field inlineQty += '<div class="col-xs-12 customer_number">'; inlineQty += '<div class="input-group">'; inlineQty += '<span class="input-group-addon" id="customer_number_text">CUSTOMER NUMBER</span>'; if (customer_number == '' && isNullorEmpty(ticket_id)) { inlineQty += '<input id="customer_number_value" value=" ' + customer_number + ' " class="form-control customer_number">'; } else if (customer_number == '' && creator_id == 112209 && !isNullorEmpty(escalated_to_it) && selector_type == "customer_issue" && !isNullorEmpty(ticket_id)) { inlineQty += '<input id="customer_number_value" value=" ' + customer_number + ' " class="form-control customer_number">'; } else { inlineQty += '<input id="customer_number_value" value=" ' + customer_number + ' " class="form-control customer_number" disabled>'; } inlineQty += '</div></div></div></div>'; //Datatable for all tickets asscoiated to current customer number inlineQty += '<div class="row">'; inlineQty += '<div class="form-group container customer_number_tickets">'; inlineQty += '<style> table {font-size: 12px;text-align: center;border: none;} {font-size: 14px;} table th{text-align: center;} .dataTables_wrapper{width:78%; margin-bottom:40px; margin-left: auto; margin-right: auto; margin-top: auto;} </style>'; inlineQty += '<table cellpadding="15" id="customer_number_tickets_preview" class="table table-responsive table-striped customer tablesorter" cellspacing="0" style="width: 100%;">'; inlineQty += '<thead style="color: white;background-color: #379E8F;">'; inlineQty += '<tr class="text-center">'; inlineQty += '</tr>'; inlineQty += '</thead></table>'; inlineQty += '</div></div>'; return inlineQty; } /** * The "Barcode number" OR "Invoice Number" input field. * If there is a TICKET ID, we are in the "Edit Ticket", so we display the Ticket ID field and the selector field is disabled. * @param {Number} ticket_id * @param {String} selector_number * @param {Number} selector_id * @param {String} selector_type * @param {Number} status_value * @return {String} inlineQty */ function selectorSection(ticket_id, selector_number, selector_id, selector_type, status_value) { if (isNullorEmpty(selector_number)) { selector_number = ''; } var inlineQty = '<div class="form-group container selector_section">'; inlineQty += '<div class="row">'; if (!isNullorEmpty(ticket_id)) { // Ticket ID field inlineQty += '<div class="col-xs-6 ticket_id">'; inlineQty += '<div class="input-group">'; inlineQty += '<span class="input-group-addon" id="ticket_id_text">TICKET ID</span>'; inlineQty += '<input id="ticket_id" value="MPSD' + ticket_id + '" class="form-control ticket_id" disabled />'; inlineQty += '</div></div>'; // Selector Number field inlineQty += '<div class="col-xs-6 selector_number">'; inlineQty += '<div class="input-group">'; switch (selector_type) { case 'barcode_number': inlineQty += '<span class="input-group-addon" id="selector_text">BARCODE NUMBER</span>'; break; case 'invoice_number': inlineQty += '<span class="input-group-addon" id="selector_text">INVOICE NUMBER</span>'; break; } inlineQty += '<input id="selector_value" value="' + selector_number + '" class="form-control selector_value" disabled>'; if (selector_type == 'invoice_number') { // Open Invoice record inlineQty += '<div class="input-group-btn">'; inlineQty += '<button id="open_inv" type="button" class="btn btn-default link_inv" data-inv-id="' + selector_id + '" data-toggle="tooltip" data-placement="top" title="Open Invoice">'; inlineQty += '<span class="glyphicon glyphicon-link"></span>'; inlineQty += '</button>'; inlineQty += '</div>'; // Attach Invoice to email if (isTicketNotClosed(status_value)) { inlineQty += '<div class="input-group-btn"><button style="background-color: #379E8F" id="add_inv" type="button" class="btn btn-success add_inv" data-inv-id="' + selector_id + '" data-toggle="tooltip" data-placement="right" title="Attach to email">'; inlineQty += '<span class="glyphicon glyphicon-plus"></span>'; inlineQty += '</button></div>'; } } inlineQty += '</div></div></div></div>'; } else { inlineQty += '<div class="col-xs-12 selector_number">'; inlineQty += '<div class="input-group">'; //Input group addon text switch (selector_type) { case 'barcode_number': inlineQty += '<span class="input-group-addon" id="selector_text">BARCODE NUMBER</span>'; break; case 'invoice_number': inlineQty += '<span class="input-group-addon" id="selector_text">INVOICE NUMBER</span>'; break; case 'customer_issue': inlineQty += '<span class="input-group-addon" id="selector_text">CUSTOMER ISSUE</span>'; break; } inlineQty += '<div class="input-group-btn">'; inlineQty += '<button tabindex="-1" data-toggle="dropdown" class="btn btn-default dropdown-toggle" type="button">'; inlineQty += '<span class="caret"></span>'; inlineQty += '<span class="sr-only">Toggle Dropdown</span>'; inlineQty += '</button>'; inlineQty += '<ul class="dropdown-menu hide" style="list-style:none;margin: 2px 0 0;">'; inlineQty += '<li><a href="#">BARCODE NUMBER</a></li>'; inlineQty += '<li><a href="#">INVOICE NUMBER</a></li>'; //inlineQty += '<li><a href="#">CUSTOMER APP</a></li>'; inlineQty += '<li><a href="#">CUSTOMER PORTAL</a></li>'; // inlineQty += '<li><a href="#">UPDATE LABEL</a></li>'; inlineQty += '</ul>'; inlineQty += '</div>'; //Input text switch (selector_type) { case 'barcode_number': inlineQty += '<input id="selector_value" class="form-control selector_value" placeholder="MPEN123456">'; break; case 'invoice_number': inlineQty += '<input id="selector_value" class="form-control selector_value" placeholder="INV123456">'; break; case 'customer_app': inlineQty += '<input id="selector_value" class="form-control selector_value" placeholder="Customer App" disabled value="Customer App">'; break; case 'customer_portal': inlineQty += '<input id="selector_value" class="form-control selector_value" placeholder="Customer Portal" disabled value="Customer Portal">'; break; case 'update_label': inlineQty += '<input id="selector_value" class="form-control selector_value" placeholder="Update Label" disabled value="Update Label">'; break; } inlineQty += '</div></div></div></div>'; } return inlineQty; } /** * The informations regarding the ticket being edited. * @param {String} date_created * @param {Number} creator_id * @param {String} creator_name * @param {String} status * @return {String} inlineQty */ function ticketSection(date_created, creator_id, creator_name, status, connote_number) { if (isNullorEmpty(date_created)) { date_created = ''; } if (isNullorEmpty(creator_name)) { creator_name = ''; } if (isNullorEmpty(status)) { status = ''; } var inlineQty = '<div class="form-group container created_status_section">'; inlineQty += '<div class="row">'; // Date created field inlineQty += '<div class="col-xs-6 date_created">'; inlineQty += '<div class="input-group">'; inlineQty += '<span class="input-group-addon" id="date_created_text">DATE CREATED</span>'; inlineQty += '<input id="date_created" value="' + date_created + '" class="form-control date_created" disabled />'; inlineQty += '</div></div>'; // Creator field inlineQty += '<div class="col-xs-6 creator">'; inlineQty += '<div class="input-group">'; inlineQty += '<span class="input-group-addon" id="creator_text">CREATOR</span>'; inlineQty += '<input id="creator" value="' + creator_name + '" data-creator-id="' + creator_id + '" class="form-control creator" disabled />'; inlineQty += '</div></div></div></div>'; // Status Section inlineQty += '<div class="form-group container status_section">'; inlineQty += '<div class="row">'; // Status field inlineQty += '<div class="col-xs-6 status">'; inlineQty += '<div class="input-group">'; inlineQty += '<span class="input-group-addon" id="status_text">STATUS</span>'; inlineQty += '<input id="status" value="' + status + '" class="form-control status" disabled />'; inlineQty += '</div></div>'; // Customer Status field inlineQty += '<div class="col-xs-6 status">'; inlineQty += '<div class="input-group">'; inlineQty += '<span class="input-group-addon" id="status_text">CONNOTE NUMBER</span>'; inlineQty += '<input id="status" value="' + connote_number + '" class="form-control status" disabled />'; inlineQty += '</div></div></div></div>'; return inlineQty; } /** * The Customer name field. * The customer name field should be automatically filled based on the Selector number value. * @param {String} customer_name * @return {String} inlineQty */ function customerSection(customer_name) { if (isNullorEmpty(customer_name)) { customer_name = ''; } // Customer Section var inlineQty = '<div class="form-group container customer_section">'; inlineQty += '<div class="row">'; // Customer name field inlineQty += '<div class="col-xs-12 customer_name">'; inlineQty += '<div class="input-group">'; inlineQty += '<span class="input-group-addon" id="customer_name_text">CUSTOMER NAME</span>'; inlineQty += '<input id="customer_name" value="' + customer_name + '" class="form-control customer_name" disabled>'; inlineQty += '</div></div></div></div>'; return inlineQty; } /** * The day to day phone and email fields of the customer. * These fields should be automatically filled based on the Selector number value. * @param {String} daytodayphone * @param {String} daytodayemail * @param {Number} status_value * @param {String} selector_type * @return {String} inlineQty */ function daytodayContactSection(daytodayphone, daytodayemail, status_value, selector_type) { if (isNullorEmpty(daytodayphone)) { daytodayphone = ''; } if (isNullorEmpty(daytodayemail)) { daytodayemail = ''; } var disabled = 'disabled'; if ((isFinanceRole(userRole)) && isTicketNotClosed(status_value) && selector_type == 'invoice_number') { disabled = ''; } var inlineQty = '<div class="form-group container daytodaycontact_section">'; inlineQty += '<div class="row">'; // Day to day email field inlineQty += '<div class="col-xs-6 daytodayemail_div">'; inlineQty += '<div class="input-group">'; inlineQty += '<span class="input-group-addon" id="daytodayemail_text">DAY-TO-DAY EMAIL</span>'; inlineQty += '<input id="daytodayemail" type="email" value="' + daytodayemail + '" class="form-control daytodayemail" ' + disabled + ' />'; inlineQty += '<div class="input-group-btn">'; inlineQty += '<button type="button" style="background-color: #379E8F" class="btn btn-success add_as_recipient" data-email="' + daytodayemail + '" data-contact-id="" data-firstname="" data-toggle="tooltip" data-placement="right" title="Add as recipient">'; inlineQty += '<span class="glyphicon glyphicon-envelope"></span>'; inlineQty += '</button>'; inlineQty += '</div>'; inlineQty += '</div></div>'; // Day to day phone field inlineQty += '<div class="col-xs-6 daytodayphone_div">'; inlineQty += '<div class="input-group">'; inlineQty += '<span class="input-group-addon" id="daytodayphone_text">DAY-TO-DAY PHONE</span>'; inlineQty += '<input id="daytodayphone" type="tel" value="' + daytodayphone + '" class="form-control daytodayphone" ' + disabled + ' />'; inlineQty += '<div class="input-group-btn"><button type="button" style="background-color: #379E8F" class="btn btn-success" id="call_daytoday_phone"><span class="glyphicon glyphicon-earphone"></span></button></div>'; inlineQty += '</div></div></div></div>'; return inlineQty; } /** * The receiver phone and email fields. * These fields should be automatically filled based on the Selector number value. * @param {String} daytodayphone * @param {String} daytodayemail * @param {Number} status_value * @param {String} selector_type * @return {String} inlineQty */ function senderDetails(selector_type, senderName, senderEmail, senderPhone, senderAddress) { var disabled = 'disabled'; if (isNullorEmpty(senderName) && isNullorEmpty(senderEmail) && isNullorEmpty(senderPhone) && isNullorEmpty(senderAddress)) { disabled = ''; } var inlineQty = ''; if (selector_type == 'barcode_number') { // Sender details header var inlineQty = '<div class="form-group container tickets_details_header_section">'; inlineQty += '<div class="row">'; inlineQty += '<div class="col-xs-12 heading2" >'; inlineQty += '<h4><span style="background-color: #379E8F" class="label label-default col-xs-12">SENDER DETAILS</span></h4>'; inlineQty += '</div></div></div>'; //First Row inlineQty += '<div class="form-group container sendercontact_section">'; inlineQty += '<div class="row">'; // name field inlineQty += '<div class="col-xs-4 sendername_div">'; inlineQty += '<div class="input-group">'; inlineQty += '<span class="input-group-addon" id="sendername_text">NAME</span>'; inlineQty += '<input id="sendername" value="' + senderName + '" class="form-control sendername" ' + disabled + ' />'; inlineQty += '</div></div>'; // Day to day phone field inlineQty += '<div class="col-xs-4 senderphone_div">'; inlineQty += '<div class="input-group">'; inlineQty += '<span class="input-group-addon" id="senderphone_text">PHONE</span>'; inlineQty += '<input id="senderphone" type="tel" value="' + senderPhone + '" class="form-control senderphone" ' + disabled + ' />'; inlineQty += '<div class="input-group-btn"><button type="button" style="background-color: #379E8F" class="btn btn-success" id="call_sender_phone"><span class="glyphicon glyphicon-earphone"></span></button></div>'; inlineQty += '</div></div>'; // Day to day email field inlineQty += '<div class="col-xs-4 senderemail_div">'; inlineQty += '<div class="input-group">'; inlineQty += '<span class="input-group-addon" id="senderemail_text">EMAIL</span>'; inlineQty += '<input id="senderemail" type="email" value="' + senderEmail + '" class="form-control senderemail" ' + disabled + ' />'; inlineQty += '<div class="input-group-btn">'; inlineQty += '<button type="button" style="background-color: #379E8F" class="btn btn-success add_as_recipient" data-email="' + senderEmail + '" data-contact-id="" data-firstname="" data-toggle="tooltip" data-placement="right" title="Add as recipient">'; inlineQty += '<span class="glyphicon glyphicon-envelope"></span>'; inlineQty += '</button>'; inlineQty += '</div>'; inlineQty += '</div></div>'; inlineQty += '</div></div>'; //2nd Row inlineQty += '<div class="form-group container receivercontact2_section">'; inlineQty += '<div class="row">'; // address1 field inlineQty += '<div class="col-xs-12 senderaddress_div">'; inlineQty += '<div class="input-group">'; inlineQty += '<span class="input-group-addon" id="senderaddress_text">ADDRESS</span>'; inlineQty += '<input id="senderaddress" value="' + senderAddress + '" class="form-control senderaddress" ' + disabled + ' />'; inlineQty += '</div></div>'; inlineQty += '</div></div>'; } return inlineQty; } /** * The receiver phone and email fields. * These fields should be automatically filled based on the Selector number value. * @param {String} daytodayphone * @param {String} daytodayemail * @param {Number} status_value * @param {String} selector_type * @return {String} inlineQty */ function receiverEmailPhone(selector_type, receiveremail, receiverphone, receivername, receiverstate, receiverzip, receiversuburb, receiveraddr1, receiveraddr2) { var disabled = 'disabled'; if (isNullorEmpty(receiveremail) && isNullorEmpty(receiveraddr1) && isNullorEmpty(receiveraddr2) && isNullorEmpty(receivername) && isNullorEmpty(receiverphone) && isNullorEmpty(receiverstate) && isNullorEmpty(receiverzip) && isNullorEmpty(receiversuburb)) { disabled = ''; } var inlineQty = ''; if (selector_type == 'barcode_number') { // Receiver details header var inlineQty = '<div class="form-group container tickets_details_header_section">'; inlineQty += '<div class="row">'; inlineQty += '<div class="col-xs-12 heading2" >'; inlineQty += '<h4><span style="background-color: #379E8F" class="label label-default col-xs-12">RECEIVER DETAILS</span></h4>'; inlineQty += '</div></div></div>'; //First Row inlineQty += '<div class="form-group container receivercontact_section">'; inlineQty += '<div class="row">'; // name field inlineQty += '<div class="col-xs-4 receivername_div">'; inlineQty += '<div class="input-group">'; inlineQty += '<span class="input-group-addon" id="receivername_text">NAME</span>'; inlineQty += '<input id="receivername" value="' + receivername + '" class="form-control receivername" ' + disabled + ' />'; inlineQty += '</div></div>'; // Day to day phone field inlineQty += '<div class="col-xs-4 receiverphone_div">'; inlineQty += '<div class="input-group">'; inlineQty += '<span class="input-group-addon" id="receiverphone_text">PHONE</span>'; inlineQty += '<input id="receiverphone" type="tel" value="' + receiverphone + '" class="form-control receiverphone" ' + disabled + ' />'; inlineQty += '<div class="input-group-btn"><button type="button" style="background-color: #379E8F" class="btn btn-success" id="call_receiver_phone"><span class="glyphicon glyphicon-earphone"></span></button></div>'; inlineQty += '</div></div>'; // Day to day email field inlineQty += '<div class="col-xs-4 receiveremail_div">'; inlineQty += '<div class="input-group">'; inlineQty += '<span class="input-group-addon" id="receiveremail_text">EMAIL</span>'; inlineQty += '<input id="receiveremail" type="email" value="' + receiveremail + '" class="form-control receiveremail" ' + disabled + ' />'; inlineQty += '<div class="input-group-btn">'; inlineQty += '<button type="button" style="background-color: #379E8F" class="btn btn-success add_as_recipient" data-email="' + receiveremail + '" data-contact-id="" data-firstname="" data-toggle="tooltip" data-placement="right" title="Add as recipient">'; inlineQty += '<span class="glyphicon glyphicon-envelope"></span>'; inlineQty += '</button>'; inlineQty += '</div>'; inlineQty += '</div></div>'; inlineQty += '</div></div>'; //2nd Row inlineQty += '<div class="form-group container receivercontact2_section">'; inlineQty += '<div class="row">'; // address1 field inlineQty += '<div class="col-xs-6 receiveraddr1_div">'; inlineQty += '<div class="input-group">'; inlineQty += '<span class="input-group-addon" id="receiveraddr1_text">ADDRESS1</span>'; inlineQty += '<input id="receiveraddr1" value="' + receiveraddr1 + '" class="form-control receiveraddr1" ' + disabled + ' />'; inlineQty += '</div></div>'; // address2 field inlineQty += '<div class="col-xs-6 receiveraddr2_div">'; inlineQty += '<div class="input-group">'; inlineQty += '<span class="input-group-addon" id="receiveraddr2_text">ADDRESS2</span>'; inlineQty += '<input id="receiveraddr2" value="' + receiveraddr2 + '" class="form-control receiveraddr2" ' + disabled + ' />'; inlineQty += '</div></div>'; inlineQty += '</div></div>'; //3rd Row inlineQty += '<div class="form-group container receivercontact3_section">'; inlineQty += '<div class="row">'; // suburb field inlineQty += '<div class="col-xs-4 receiversuburb_div">'; inlineQty += '<div class="input-group">'; inlineQty += '<span class="input-group-addon" id="receiversuburb_text">SUBURB</span>'; inlineQty += '<input id="receiversuburb" value="' + receiversuburb + '" class="form-control receiversuburb" ' + disabled + ' />'; inlineQty += '</div></div>'; // postcode field inlineQty += '<div class="col-xs-4 receiverzip_div">'; inlineQty += '<div class="input-group">'; inlineQty += '<span class="input-group-addon" id="receiverzip_text">POSTCODE</span>'; inlineQty += '<input id="receiverzip" value="' + receiverzip + '" class="form-control receiverzip" ' + disabled + ' />'; inlineQty += '</div></div>'; // state field inlineQty += '<div class="col-xs-4 receiverstate_div">'; inlineQty += '<div class="input-group">'; inlineQty += '<span class="input-group-addon" id="receiverstate_text">STATE</span>'; inlineQty += '<input id="receiverstate" value="' + receiverstate + '" class="form-control receiverstate" ' + disabled + ' />'; inlineQty += '</div></div>'; inlineQty += '</div></div>'; } return inlineQty; } /** * The accounts phone and email fields of the customer. * These fields should be automatically filled based on the Invoice number value. * @param {String} accountsphone * @param {String} accountsemail * @param {Number} status_value * @param {String} selector_type * @return {String} inlineQty */ function accountsContactSection(accountsphone, accountsemail, status_value, selector_type) { if (isNullorEmpty(accountsphone)) { accountsphone = ''; } if (isNullorEmpty(accountsemail)) { accountsemail = ''; } if (selector_type == 'invoice_number') { var inlineQty = '<div class="form-group container accountscontact_section">'; if (isFinanceRole(userRole) && isTicketNotClosed(status_value)) { var disabled = ''; } else { var disabled = 'disabled'; } } else { var inlineQty = '<div class="form-group container accountscontact_section hide">'; var disabled = 'disabled'; } inlineQty += '<div class="row">'; // Accounts email field inlineQty += '<div class="col-xs-6 accountsemail_div">'; inlineQty += '<div class="input-group">'; inlineQty += '<span class="input-group-addon" id="accountsemail_text">ACCOUNTS EMAIL</span>'; inlineQty += '<input id="accountsemail" type="email" value="' + accountsemail + '" class="form-control accountsemail" ' + disabled + ' />'; inlineQty += '<div class="input-group-btn">'; inlineQty += '<button type="button" style="background-color: #379E8F" class="btn btn-success add_as_recipient" data-email="' + accountsemail + '" data-contact-id="" data-firstname="" data-toggle="tooltip" data-placement="right" title="Add as recipient">'; inlineQty += '<span class="glyphicon glyphicon-envelope"></span>'; inlineQty += '</button>'; inlineQty += '</div>'; inlineQty += '</div></div>'; // Accounts phone field inlineQty += '<div class="col-xs-6 accountsphone_div">'; inlineQty += '<div class="input-group">'; inlineQty += '<span class="input-group-addon" id="accountsphone_text">ACCOUNTS PHONE</span>'; inlineQty += '<input id="accountsphone" type="tel" value="' + accountsphone + '" class="form-control accountsphone" ' + disabled + ' />'; inlineQty += '<div class="input-group-btn"><button type="button" style="background-color: #379E8F" class="btn btn-success" id="call_accounts_phone"><span class="glyphicon glyphicon-earphone"></span></button></div>'; inlineQty += '</div></div></div></div>'; return inlineQty; } /** * * @param {Number} maap_bank_account_number * @param {Number} maap_parent_bank_account_number * @param {String} selector_type * @returns {String} inlineQty */ function maapBankAccountSection(maap_bank_account_number, maap_parent_bank_account_number, selector_type) { switch (selector_type) { case 'barcode_number': var inlineQty = '<div class="form-group container accounts_number_section hide">'; break; case 'invoice_number': var inlineQty = '<div class="form-group container accounts_number_section">'; break; } inlineQty += '<div class="row">'; // MAAP Bank Account # field inlineQty += '<div class="col-xs-6 account_number_div">'; inlineQty += '<div class="input-group">'; inlineQty += '<span class="input-group-addon" id="account_number_text">MAAP BANK ACCOUNT #</span>'; inlineQty += '<input id="account_number" type="number" value="' + maap_bank_account_number + '" class="form-control account_number" disabled />'; inlineQty += '</div></div>'; // MAAP Parent Bank Account # field inlineQty += '<div class="col-xs-6 parent_account_number_div">'; inlineQty += '<div class="input-group">'; inlineQty += '<span class="input-group-addon" id="parent_account_number_text">MAAP PARENT BANK ACCOUNT #</span>'; inlineQty += '<input id="parent_account_number" type="number" value="' + maap_parent_bank_account_number + '" class="form-control parent_account_number" disabled />'; inlineQty += '</div></div></div></div>'; return inlineQty; } /** * The Franchisee name, and its main contact name and phone number fields. * These fields should be automatically filled based on the Selector number value. * @param {String} franchisee_name * @param {String} zee_main_contact_name * @param {String} zee_email * @param {String} zee_main_contact_phone * @param {String} zee_abn * @return {String} inlineQty */ function franchiseeMainContactSection(franchisee_name, zee_main_contact_name, zee_email, zee_main_contact_phone, zee_abn) { if (isNullorEmpty(franchisee_name)) { franchisee_name = ''; } if (isNullorEmpty(zee_main_contact_name)) { zee_main_contact_name = ''; } if (isNullorEmpty(zee_email)) { zee_email = ''; } if (isNullorEmpty(zee_main_contact_phone)) { zee_main_contact_phone = ''; } if (isNullorEmpty(zee_abn)) { zee_abn = ''; } var inlineQty = '<div class="form-group container zee_main_contact_section">'; inlineQty += '<div class="row">'; // Franchisee name field inlineQty += '<div class="col-xs-6 franchisee_name">'; inlineQty += '<div class="input-group">'; inlineQty += '<span class="input-group-addon" id="franchisee_name_text">FRANCHISEE NAME</span>'; inlineQty += '<input id="franchisee_name" value="' + franchisee_name + '" class="form-control franchisee_name" disabled>'; inlineQty += '</div></div>'; // Franchisee main contact name field inlineQty += '<div class="col-xs-6 zee_main_contact_name">'; inlineQty += '<div class="input-group">'; inlineQty += '<span class="input-group-addon" id="zee_main_contact_name_text">MAIN CONTACT</span>'; inlineQty += '<input id="zee_main_contact_name" value="' + zee_main_contact_name + '" class="form-control zee_main_contact_name" disabled>'; inlineQty += '</div></div></div></div>'; // Franchisee contact details inlineQty += '<div class="form-group container zee_main_contact_section">'; inlineQty += '<div class="row">'; // Franchisee email field inlineQty += '<div class="col-xs-12 zee_email">'; inlineQty += '<div class="input-group">'; inlineQty += '<span class="input-group-addon" id="zee_email_text">FRANCHISEE EMAIL</span>'; inlineQty += '<input id="zee_email" type="email" value="' + zee_email + '" class="form-control accountsemail" disabled />'; inlineQty += '<div class="input-group-btn">'; var zee_contact_id = '0'; inlineQty += '<button type="button" style="background-color: #379E8F" class="btn btn-success add_as_recipient" data-email="' + zee_email + '" data-contact-id="' + zee_contact_id + '" data-firstname="' + franchisee_name + '" data-toggle="tooltip" data-placement="right" title="Add as recipient">'; inlineQty += '<span class="glyphicon glyphicon-envelope"></span>'; inlineQty += '</button>'; inlineQty += '</div>'; inlineQty += '</div></div></div></div>'; // Franchisee phone and ABN details inlineQty += '<div class="form-group container zee_main_contact_section">'; inlineQty += '<div class="row">'; // Franchisee main contact phone field inlineQty += '<div class="col-xs-6 zee_main_contact_phone">' inlineQty += '<div class="input-group">' inlineQty += '<span class="input-group-addon" id="zee_main_contact_phone_text">FRANCHISEE PHONE</span>'; inlineQty += '<input id="zee_main_contact_phone" type="tel" value="' + zee_main_contact_phone + '" class="form-control zee_main_contact_phone" disabled />'; inlineQty += '<div class="input-group-btn"><button style="background-color: #379E8F" type="button" class="btn btn-success" id="call_zee_main_contact_phone"><span class="glyphicon glyphicon-earphone"></span></button>'; inlineQty += '</div>'; inlineQty += '</div></div>'; // Franchisee ABN number inlineQty += '<div class="col-xs-6 zee_abn">' inlineQty += '<div class="input-group">' inlineQty += '<span class="input-group-addon" id="zee_abn_text">FRANCHISEE ABN</span>' inlineQty += '<input id="zee_abn" class="form-control zee_abn" value="' + zee_abn + '" disabled>' inlineQty += '</div></div></div></div>'; return inlineQty; } /** * The MPEX Date and Time Stock used fields. * Visible only for the barcode records. * @param {String} selector_type * @param {String} date_stock_used * @param {String} time_stock_used * @return {String} inlineQty */ function mpexStockUsedSection(selector_type, date_stock_used, time_stock_used) { if (isNullorEmpty(date_stock_used)) { date_stock_used = '' } if (isNullorEmpty(time_stock_used)) { time_stock_used = '' } var hide_class = (selector_type == 'barcode_number') ? '' : 'hide'; // MPEX Stock Used Section var inlineQty = '<div class="form-group container mpex_stock_used_section ' + hide_class + '">'; inlineQty += '<div class="row">'; // Date Stock Used inlineQty += ' <div class="col-xs-6 date_stock_used">'; inlineQty += '<div class="input-group">'; inlineQty += '<span class="input-group-addon" id="date_stock_used_text">DATE STOCK USED</span>'; inlineQty += '<input id="date_stock_used" class="form-control date_stock_used" value="' + date_stock_used + '" disabled>'; inlineQty += '</div></div>'; // Time Stock Used inlineQty += '<div class="col-xs-6 time_stock_used">'; inlineQty += '<div class="input-group">'; inlineQty += '<span class="input-group-addon" id="time_stock_used_text">TIME STOCK USED</span>'; inlineQty += '<input id="time_stock_used" class="form-control time_stock_used" value="' + time_stock_used + '" disabled>'; inlineQty += '</div></div></div></div>'; return inlineQty; } /** * The MPEX Final Delivery field is visible only for the barcode records. * The Enquiry Status field is not disabled only for the ticket that have not yet been opened. * @param {Number} status_value * @param {String} selector_type * @param {String} final_delivery_text * @param {Number} selected_enquiry_status_id * @return {String} inlineQty */ function finalDeliveryEnquirySection(status_value, selector_type, final_delivery_text, selected_enquiry_status_id, prod_stock_invoice) { if (isNullorEmpty(final_delivery_text)) { final_delivery_text = '' } if (isNullorEmpty(selected_enquiry_status_id)) { selected_enquiry_status_id = '' } var barcode_hide_class = (selector_type == 'barcode_number') ? '' : 'hide'; var nb_col_enquiry_section = (selector_type == 'barcode_number') ? '6' : '12'; var enquiry_disabled = (isTicketNotClosed(status_value)) ? '' : 'disabled'; // Final Delivery + Enquiry Status Section var inlineQty = '<div class="form-group container final_delivery_enquiry_status_section">'; inlineQty += '<div class="row">'; // Final Delivery inlineQty += '<div class="col-xs-6 final_delivery ' + barcode_hide_class + '">'; inlineQty += '<div class="input-group">'; inlineQty += '<span class="input-group-addon" id="final_delivery_text">FINAL DELIVERY</span>'; inlineQty += '<input id="final_delivery" class="form-control final_delivery" value="' + final_delivery_text + '" disabled>'; inlineQty += '</div></div>'; // Final Delivery inlineQty += '<div class="col-xs-6 invoice ' + barcode_hide_class + '">'; inlineQty += '<div class="input-group">'; inlineQty += '<span class="input-group-addon" id="invoice_text">INVOICE</span>'; inlineQty += '<input id="invoice" class="form-control invoice" value="' + prod_stock_invoice + '" disabled>'; inlineQty += '</div></div>'; inlineQty += '</div></div>'; return inlineQty; } /** * Ticket Label Section for if label on mpex was Printed or Handwritten * @param {Number} selected_label_id * @return {String} inlineQty */ function labelSection(selected_label_id, selector_type, status_value) { if (isNullorEmpty(selected_label_id)) { selected_label_id = ''; } var barcodeHideClass = (selector_type == 'barcode_number') ? '' : 'hide'; var labeldisabled = (isTicketNotClosed(status_value)) ? '' : 'disabled'; var inlineQty = '<div class="form-group container label_section ' + barcodeHideClass + '">'; inlineQty += '<div class="row">'; inlineQty += '<div class="col-xs-6 label_div">'; inlineQty += '<div class="input-group">'; inlineQty += '<span class="input-group-addon" id="label_text">TICKET LABEL</span>'; inlineQty += '<select id="label_status" class="form-control label_status" ' + labeldisabled + '>'; inlineQty += '<option></option>'; var labelColumns = new Array(); labelColumns[0] = search.createColumn({ name: 'name' }); labelColumns[1] = search.createColumn({ name: 'internalId' }); var labelResultSet = search.create({ type: 'customlist_mp_ticket_label', columns: labelColumns, }); labelResultSet.run().each(function (labelResult) { var labelName = labelResult.getValue('name'); var labelId = labelResult.getValue('internalId'); if (selected_label_id == labelId) { inlineQty += '<option value="' + labelId + '"selected>' + labelName + '</option>'; } else { inlineQty += '<option value="' + labelId + '">' + labelName + '</option>'; } return inlineQty; }); inlineQty += '</select>'; inlineQty += '</div></div></div></div>'; return inlineQty; } /** * Section containing enquiry medium type and the enquiry status of the ticket enquiry * @param list_enquiry_mediums {String}atus and * @param total_enquiry_count {Number} * @param selector_type {String} * @param status_value {Number} * @returns {string} */ function enquiryMediumSection(list_enquiry_mediums, selected_enquiry_status_id, selector_type) { //Search for enquiry mediums var hasEnquiryMediums = (!isNullorEmpty(list_enquiry_mediums)); var enquiryMediumColumns = new Array(); enquiryMediumColumns[0] = search.createColumn({ name: 'name' }); enquiryMediumColumns[1] = search.createColumn({ name: 'internalId' }); var enquiryMediumResultSet = search.create({ type: 'customlist_ticket_enquiry_mediums', columns: enquiryMediumColumns, }); //Ticket Enquiry Header // var inlineQty = '<div class="form-group container ticket_enquiry_header_section">'; // inlineQty += '<div class="row">'; // inlineQty += '<div class="col-xs-12 heading2">'; // inlineQty += '<h4><span style="background-color: #379E8F" class="label label-default col-xs-12">TICKET ENQUIRY DETAILS</span></h4>'; // inlineQty += '</div></div></div>'; //Enquiry Medium HTML var inlineQty = '<div class="form-group container enquiry_medium_section">'; inlineQty += '<div class="row">'; // inlineQty += '<div class="col-xs-6 enquiry_medium_div">'; // inlineQty += '<div class="input-group">'; // inlineQty += '<span class="input-group-addon" id="enquiry_medium_text">ENQUIRY MEDIUM</span>'; // inlineQty += '<select multiple id="enquiry_medium_status" class="form-control enquiry_medium_status" size="'+ enquiryMediumResultSet.length + '" disabled>'; // enquiryMediumResultSet.run().each(function (enquiryMediumResult) { // var enquiryMediumName = enquiryMediumResult.getValue('name'); // var enquiryMediumId = enquiryMediumResult.getValue('internalId'); // var selected = false; // if(hasEnquiryMediums){ // selected = (list_enquiry_mediums.indexOf(enquiryMediumId) !== -1); // } // if(selected) { // inlineQty += '<option value="' + enquiryMediumId + '"selected>' + enquiryMediumName + '</option>'; // }else{ // inlineQty += '<option value="' + enquiryMediumId + '">' + enquiryMediumName + '</option>'; // } // return true; // }); // inlineQty += '</select>'; // inlineQty += '</div></div>'; // Enquiry Status var enquiry_status_columns = new Array(); enquiry_status_columns[0] = search.createColumn({ name: 'name' }); enquiry_status_columns[1] = search.createColumn({ name: 'internalId' }); var enquiryStatusResultSet = search.create({ type: 'customlist_mp_ticket_enquiry', columns: enquiry_status_columns, }); inlineQty += '<div class="col-xs-6 enquiry_status_div">'; inlineQty += '<div class="input-group">'; inlineQty += '<span class="input-group-addon" id="enquiry_status_text">ENQUIRY STATUS</span>'; inlineQty += '<select id="enquiry_status" class="form-control enquiry_status">'; inlineQty += '<option></option>'; enquiryStatusResultSet.run().each(function (enquiryStatusResult) { var enquiry_status_name = enquiryStatusResult.getValue('name'); var enquiry_status_id = enquiryStatusResult.getValue('internalId'); if (enquiry_status_id == selected_enquiry_status_id) { inlineQty += '<option value="' + enquiry_status_id + '" selected>' + enquiry_status_name + '</option>'; } else { inlineQty += '<option value="' + enquiry_status_id + '">' + enquiry_status_name + '</option>'; } return true; }); inlineQty += '</select>'; inlineQty += '</div></div></div></div>'; return inlineQty; } /** * Section containing the total enquiry count and its breakdwn counts of chat, phone and email * @param total_enquiry_count * @param chat_enquiry_count * @param phone_enquiry_count * @param email_enquiry_count * @param selector_type * @returns {string} */ function enquiryCountSection(total_enquiry_count, chat_enquiry_count, phone_enquiry_count, email_enquiry_count, selector_type, phone_interaction_count, email_interaction_count) { if (isNullorEmpty(total_enquiry_count)) { total_enquiry_count = 0; } if (isNullorEmpty(chat_enquiry_count)) { chat_enquiry_count = 0; } if (isNullorEmpty(phone_enquiry_count)) { phone_enquiry_count = 0; } if (isNullorEmpty(email_enquiry_count)) { email_enquiry_count = 0; } if (isNullorEmpty(phone_interaction_count)) { phone_interaction_count = 0; } if (isNullorEmpty(email_interaction_count)) { email_interaction_count = 0; } //Total Enquiry Count HTML // var inlineQty = '<div class="form-group container enquiry_count_section">'; // inlineQty += '<div class="row">'; // inlineQty += '<div class="col-xs-12 total_enquiry_count_div">'; // inlineQty += '<div class="input-group">'; // inlineQty += '<span class="input-group-addon" id="total_enquiry_count_text">ENQUIRY COUNT</span>'; // inlineQty += '<input id="total_enquiry_count" class="form-control enquiry_count" value="' + total_enquiry_count + '" disabled />'; // inlineQty += '</div></div></div></div>'; //Enquiries by chat count var inlineQty = '<div class="form-group container enquiry_count_breakdown_section">'; inlineQty += '<div class="row">'; inlineQty += '<div class="col-xs-4 enquiry_count_by_chat">'; inlineQty += '<div class="input-group">'; inlineQty += '<span class="input-group-addon" id="enquiry_count_by_chat_text"> WEBSITE ENQUIRY </span>'; inlineQty += '<input id="enquiry_count_by_chat" value="' + chat_enquiry_count + '" class="form-control enquiry_count_by_chat" disabled>'; inlineQty += '<div class="input-group-btn">'; inlineQty += '<button type="button" style="background-color: #379E8F" class="btn btn-success increment_enquiry_count_by_chat" data-firstname="" data-toggle="tooltip" data-placement="right" title="Increment Chat Enquiry Count">'; inlineQty += '<span class="glyphicon glyphicon-plus"></span>'; inlineQty += '</button>'; inlineQty += '<button type="button" class="btn btn-danger decrement_enquiry_count_by_chat" data-firstname="" data-toggle="tooltip" data-placement="right" title="Decrement Chat Enquiry Count">'; inlineQty += '<span class="glyphicon glyphicon-minus"></span>'; inlineQty += '</button>'; inlineQty += '</div></div></div>'; inlineQty += '<div class="col-xs-4 enquiry_count_by_phone">'; inlineQty += '<div class="input-group">'; inlineQty += '<span class="input-group-addon" id="enquiry_count_by_phone_text"> PHONE ENQUIRY </span>'; inlineQty += '<input id="enquiry_count_by_phone" value="' + phone_enquiry_count + '" class="form-control enquiry_count_by_phone" disabled>'; inlineQty += '<div class="input-group-btn">'; inlineQty += '<button type="button" style="background-color: #379E8F" class="btn btn-success increment_enquiry_count_by_phone" data-firstname="" data-toggle="tooltip" data-placement="right" title="Increment Phone Enquiry Count">'; inlineQty += '<span class="glyphicon glyphicon-plus"></span>'; inlineQty += '</button>'; inlineQty += '<button type="button" class="btn btn-danger decrement_enquiry_count_by_phone" data-firstname="" data-toggle="tooltip" data-placement="right" title="Decrement Phone Enquiry Count">'; inlineQty += '<span class="glyphicon glyphicon-minus"></span>'; inlineQty += '</button>'; inlineQty += '</div></div></div>'; inlineQty += '<div class="col-xs-4 enquiry_count_by_email">'; inlineQty += '<div class="input-group">'; inlineQty += '<span class="input-group-addon" id="enquiry_count_by_email_text"> EMAIL ENQUIRY </span>'; inlineQty += '<input id="enquiry_count_by_email" value="' + email_enquiry_count + '" class="form-control enquiry_count_by_email" disabled>'; inlineQty += '<div class="input-group-btn">'; inlineQty += '<button type="button" style="background-color: #379E8F" class="btn btn-success increment_enquiry_count_by_email" data-firstname="" data-toggle="tooltip" data-placement="right" title="Increment Email Enquiry Count">'; inlineQty += '<span class="glyphicon glyphicon-plus"></span>'; inlineQty += '</button>'; inlineQty += '<button type="button" class="btn btn-danger decrement_enquiry_count_by_email" data-firstname="" data-toggle="tooltip" data-placement="right" title="Decrement Email Enquiry Count">'; inlineQty += '<span class="glyphicon glyphicon-minus"></span>'; inlineQty += '</button>'; inlineQty += '</div></div></div></div></div>'; if (selector_type == "customer_issue") { inlineQty += '<div class="form-group container interaction_count_breakdown_section">'; inlineQty += '<div class="row">'; inlineQty += '<div class="col-xs-6 interaction_count_by_phone">'; inlineQty += '<div class="input-group">'; inlineQty += '<span class="input-group-addon" id="interaction_count_by_phone_text"> PHONE INTERACTION </span>'; inlineQty += '<input id="interaction_count_by_phone" value="' + phone_interaction_count + '" class="form-control interaction_count_by_phone" disabled>'; inlineQty += '<div class="input-group-btn">'; inlineQty += '<button type="button" style="background-color: #379E8F" class="btn btn-success increment_interaction_count_by_phone" data-firstname="" data-toggle="tooltip" data-placement="right" title="Increment Phone Interaction Count">'; inlineQty += '<span class="glyphicon glyphicon-plus"></span>'; inlineQty += '</button>'; inlineQty += '<button type="button" class="btn btn-danger decrement_interaction_count_by_phone" data-firstname="" data-toggle="tooltip" data-placement="right" title="Decrement Phone interaction Count">'; inlineQty += '<span class="glyphicon glyphicon-minus"></span>'; inlineQty += '</button>'; inlineQty += '</div></div></div>'; inlineQty += '<div class="col-xs-6 interaction_count_by_email">'; inlineQty += '<div class="input-group">'; inlineQty += '<span class="input-group-addon" id="interaction_count_by_email_text"> EMAIL INTERACTION </span>'; inlineQty += '<input id="interaction_count_by_email" value="' + email_interaction_count + '" class="form-control interaction_count_by_email" disabled>'; inlineQty += '<div class="input-group-btn">'; inlineQty += '<button type="button" style="background-color: #379E8F" class="btn btn-success increment_interaction_count_by_email" data-firstname="" data-toggle="tooltip" data-placement="right" title="Increment Email Interaction Count">'; inlineQty += '<span class="glyphicon glyphicon-plus"></span>'; inlineQty += '</button>'; inlineQty += '<button type="button" class="btn btn-danger decrement_interaction_count_by_email" data-firstname="" data-toggle="tooltip" data-placement="right" title="Decrement Email Interaction Count">'; inlineQty += '<span class="glyphicon glyphicon-minus"></span>'; inlineQty += '</button>'; inlineQty += '</div></div></div></div></div>'; } return inlineQty; } /** * These fields should be displayed only for an Invoice ticket, and be edited only by the finance team. * - Invoice Method field * - Accounts cc email field * - MPEX PO # field * - Customer PO # field * - MPEX Invoicing Cycle field * @param {Number} selected_invoice_method_id * @param {String} accounts_cc_email * @param {String} mpex_po_number * @param {String} customer_po_number * @param {Number} selected_invoice_cycle_id * @param {Number} terms * @param {String} customer_terms * @param {Number} status_value * @param {String} selector_type * @return {String} inlineQty */ function otherInvoiceFieldsSection(selected_invoice_method_id, accounts_cc_email, mpex_po_number, customer_po_number, selected_invoice_cycle_id, terms, customer_terms, status_value, selector_type) { if (isNullorEmpty(accounts_cc_email)) { accounts_cc_email = '' } if (isNullorEmpty(mpex_po_number)) { mpex_po_number = '' } if (isNullorEmpty(customer_po_number)) { customer_po_number = '' } if (isNullorEmpty(customer_terms)) { customer_terms = '' } var invoice_method_columns = new Array(); invoice_method_columns[0] = search.createColumn({ name: 'name' }); invoice_method_columns[1] = search.createColumn({ name: 'internalId' }); var invoiceMethodResultSet = search.create({ type: 'customlist_invoice_method', columns: invoice_method_columns, }); switch (selector_type) { case 'barcode_number': var inlineQty = '<div class="form-group container invoice_method_accounts_cc_email_section hide">'; var disabled = 'disabled'; break; case 'invoice_number': var inlineQty = '<div class="form-group container invoice_method_accounts_cc_email_section">'; if (isFinanceRole(userRole) && isTicketNotClosed(status_value)) { var disabled = ''; } else { var disabled = 'disabled'; } break; } inlineQty += '<div class="row">'; // Invoice Method field inlineQty += '<div class="col-xs-6 invoice_method_div">'; inlineQty += '<div class="input-group">'; inlineQty += '<span class="input-group-addon" id="invoice_method_text">INVOICE METHOD</span>'; inlineQty += '<select id="invoice_method" class="form-control" ' + disabled + '>'; inlineQty += '<option></option>'; invoiceMethodResultSet.run().each(function (invoiceMethodResult) { var invoice_method_name = invoiceMethodResult.getValue('name'); var invoice_method_id = invoiceMethodResult.getValue('internalId'); if (invoice_method_id == selected_invoice_method_id) { inlineQty += '<option value="' + invoice_method_id + '" selected>' + invoice_method_name + '</option>'; } else { inlineQty += '<option value="' + invoice_method_id + '">' + invoice_method_name + '</option>'; } return true; }); inlineQty += '</select>'; inlineQty += '</div></div>'; // Accounts cc email field --> inlineQty += '<div class="col-xs-6 accounts_cc_email_div">'; inlineQty += '<div class="input-group">'; inlineQty += '<span class="input-group-addon" id="accounts_cc_email_text">ACCOUNTS CC EMAIL</span>'; inlineQty += '<input id="accounts_cc_email" type="email" value="' + accounts_cc_email + '" class="form-control accounts_cc_email" ' + disabled + '/>'; inlineQty += '<div class="input-group-btn">'; inlineQty += '<button type="button" style="background-color: #379E8F" class="btn btn-success add_as_recipient" data-email="' + accounts_cc_email + '" data-contact-id="" data-firstname="" data-toggle="tooltip" data-placement="right" title="Add as recipient">'; inlineQty += '<span class="glyphicon glyphicon-envelope"></span>'; inlineQty += '</button>'; inlineQty += '</div>'; inlineQty += '</div></div></div></div>'; switch (selector_type) { case 'barcode_number': inlineQty += '<div class="form-group container mpex_customer_po_number_section hide">'; break; case 'invoice_number': inlineQty += '<div class="form-group container mpex_customer_po_number_section">'; break; } inlineQty += '<div class="row">'; // MPEX PO # inlineQty += '<div class="col-xs-6 mpex_po_number_div">'; inlineQty += '<div class="input-group">'; inlineQty += '<span class="input-group-addon" id="mpex_po_number_text">MPEX PO #</span>'; inlineQty += '<input id="mpex_po_number" value="' + mpex_po_number + '" class="form-control mpex_po_number" ' + disabled + '/>'; inlineQty += '</div></div>'; // Customer PO # inlineQty += '<div class="col-xs-6 customer_po_number_div">'; inlineQty += '<div class="input-group">'; inlineQty += '<span class="input-group-addon" id="customer_po_number_text">CUSTOMER PO #</span>'; inlineQty += '<input id="customer_po_number" value="' + customer_po_number + '" class="form-control customer_po_number" ' + disabled + '/>'; inlineQty += '</div></div></div></div>'; // Terms fields switch (selector_type) { case 'barcode_number': inlineQty += '<div class="form-group container terms_section hide">'; break; case 'invoice_number': inlineQty += '<div class="form-group container terms_section">'; break; } inlineQty += '<div class="row">'; // Terms inlineQty += '<div class="col-xs-6 terms_div">'; inlineQty += '<div class="input-group">'; inlineQty += '<span class="input-group-addon" id="terms_text">TERMS</span>'; // Find the text related to the terms value. var terms_options = [{ "value": "", "text": "" }, { "value": "5", "text": "1% 10 Net 30" }, { "value": "6", "text": "2% 10 Net 30" }, { "value": "4", "text": "Due on receipt" }, { "value": "1", "text": "Net 15 Days" }, { "value": "2", "text": "Net 30 Days" }, { "value": "8", "text": "Net 45 Days" }, { "value": "3", "text": "Net 60 Days" }, { "value": "7", "text": "Net 7 Days" }, { "value": "9", "text": "Net 90 Days" }]; var terms_option = findObjectByKey(terms_options, "value", terms); var terms_text = isNullorEmpty(terms_option) ? '' : terms_option.text; inlineQty += '<input id="terms" class="form-control terms" value="' + terms_text + '" disabled/>'; inlineQty += '</div></div>'; // Customer's terms inlineQty += '<div class="col-xs-6 customers_terms_div">'; inlineQty += '<div class="input-group">'; inlineQty += '<span class="input-group-addon" id="customers_terms_text">' + "CUSTOMER'S TERMS</span>"; inlineQty += '<input id="customers_terms" class="form-control customers_terms" value="' + customer_terms + '" ' + disabled + '/>'; inlineQty += '</div></div></div></div>'; // MPEX Invoicing Cycle var invoice_cycle_columns = new Array(); invoice_cycle_columns[0] = search.createColumn({ name: 'name' }); invoice_cycle_columns[1] = search.createColumn({ name: 'internalId' }); var invoiceCycleResultSet = search.create({ type: 'customlist_invoicing_cyle', columns: invoice_cycle_columns, }) switch (selector_type) { case 'barcode_number': inlineQty += '<div class="form-group container mpex_invoicing_cycle_section hide">'; break; case 'invoice_number': inlineQty += '<div class="form-group container mpex_invoicing_cycle_section">'; break; } inlineQty += '<div class="row">'; inlineQty += '<div class="col-xs-12 mpex_invoicing_cycle_div">'; inlineQty += '<div class="input-group">'; inlineQty += '<span class="input-group-addon" id="mpex_invoicing_cycle_text">MPEX INVOICING CYCLE</span>'; inlineQty += '<select id="mpex_invoicing_cycle" class="form-control mpex_invoicing_cycle" ' + disabled + '>'; inlineQty += '<option></option>'; invoiceCycleResultSet.run().each(function (invoiceCycleResult) { var invoice_cycle_name = invoiceCycleResult.getValue('name'); var invoice_cycle_id = invoiceCycleResult.getValue('internalId'); if (invoice_cycle_id == selected_invoice_cycle_id) { inlineQty += '<option value="' + invoice_cycle_id + '" selected>' + invoice_cycle_name + '</option>'; } else { inlineQty += '<option value="' + invoice_cycle_id + '">' + invoice_cycle_name + '</option>'; } return true; }); inlineQty += '</select>'; inlineQty += '</div></div></div></div>'; return inlineQty; } /** * The Attachments field (an editable hyperlink) * @param {String} attachments_hyperlink * @param {Number} status_value * @returns {String} inlineQty */ function attachmentsSection(attachments_hyperlink, status_value) { if (isNullorEmpty(attachments_hyperlink)) { attachments_hyperlink = '' } var disabled = (isTicketNotClosed(status_value)) ? '' : 'disabled'; var inlineQty = '<div class="form-group container attachments_section">'; inlineQty += '<div class="row">'; inlineQty += '<div class="col-xs-12 attachments_div">'; inlineQty += '<div class="input-group">'; inlineQty += '<span class="input-group-addon" id="attachments_text">ATTACHMENTS</span>' inlineQty += '<input id="attachments" class="form-control attachments" type="url" value="' + attachments_hyperlink + '" ' + disabled + '/>'; inlineQty += '</div></div></div></div>'; return inlineQty; } /** * The customer contact details section. * Possibility for the user to add / edit the contacts. * @return {String} inlineQty */ function mpexContactSection() { // Contact details header var inlineQty = '<div class="form-group container mpex_contact_section">'; inlineQty += '<div class="row">'; inlineQty += '<div class="col-xs-12 heading2">'; inlineQty += '<h4><span style="background-color: #379E8F" class="label label-default col-xs-12">CONTACT DETAILS</span></h4>'; inlineQty += '</div>'; inlineQty += '</div></div>'; // Contact table inlineQty += '<div class="form-group container contacts_section" style="font-size: small;">'; inlineQty += '<div class="row">'; inlineQty += '<div class="col-xs-12 contacts_div">'; // Since the table is not displayed correctly when added through suitelet, // It is added with jQuery in the pageInit() function in the client script 'mp_cl_open_ticket.js'. inlineQty += '</div>'; inlineQty += '</div>'; inlineQty += '</div>'; // Add/edit contacts button inlineQty += '<div class="form-group container reviewcontacts_section">'; inlineQty += '<div class="row">'; inlineQty += '<div class="col-xs-4 col-xs-offset-4 reviewcontacts">'; inlineQty += '<input type="button" style="background-color: #379E8F; border-color: #379E8F; font-weight: 700" value="ADD/EDIT CONTACTS" class="form-control btn btn-primary" id="reviewcontacts" />'; inlineQty += '</div></div></div>'; return inlineQty; }; /** * A Datatable displaying the open invoices of the customer * @param {Number} ticket_id * @param {String} selector_type * @return {String} inlineQty */ function openInvoicesSection(ticket_id, selector_type) { if (isNullorEmpty(ticket_id)) { ticket_id = '' } var hide_class_section = (isNullorEmpty(ticket_id) || selector_type != 'invoice_number') ? 'hide' : ''; // Open invoices header var inlineQty = '<div class="form-group container open_invoices open_invoices_header ' + hide_class_section + '">'; inlineQty += '<div class="row">'; inlineQty += '<div class="col-xs-12 heading2">'; inlineQty += '<h4><span style="background-color: #379E8F" class="label label-default col-xs-12">OPEN INVOICES</span></h4>'; inlineQty += '</div></div></div>'; // Open invoices dropdown field inlineQty += '<div class="form-group container open_invoices invoices_dropdown ' + hide_class_section + '">'; inlineQty += '<div class="row">'; inlineQty += '<div class="col-xs-12 invoices_dropdown_div">'; inlineQty += '<div class="input-group">'; inlineQty += '<span class="input-group-addon" id="invoices_dropdown_text">INVOICE STATUS</span>'; inlineQty += '<select id="invoices_dropdown" class="form-control">'; inlineQty += '<option value="open" selected>Open</option>'; inlineQty += '<option value="paidInFull">Paid In Full (last 3 months)</option>'; inlineQty += '</select>'; inlineQty += '</div></div></div></div>'; // Open Invoices Datatable //inlineQty += '<div class="form-group container open_invoices open_invoices_datatable>'; //inlineQty += '</div>'; inlineQty += '<div class="form-group open_invoices open_invoices_table ' + hide_class_section + '">'; inlineQty += dataTable(); // inlineQty += '<div class="row">'; // inlineQty += '<div class="col-xs-18" id="open_invoice_dt_div">'; // // It is inserted as inline html in the script mp_cl_open_ticket // inlineQty += '</div></div></div>'; inlineQty += '</div>' return inlineQty; } function dataTable() { var inlineQty = '<style>table#invoices-preview {font-size: 12px;text-align: center;border: none;}.dataTables_wrapper {font-size: 14px;}table#invoices-preview th{text-align: center;} .bolded{font-weight: bold;}</style>'; inlineQty += '<table id="invoices-preview" class="table table-responsive table-striped customer tablesorter" style="width: 100%; table-layout: fixed">'; inlineQty += '<thead style="color: white;background-color: #379E8F;">'; inlineQty += '<tr class="text-center">'; inlineQty += '</tr>'; inlineQty += '</thead>'; inlineQty += '<tbody id="result_invoices"></tbody>'; inlineQty += '</table>'; return inlineQty; } /** * The Credit Memo Section. * Displays a table of the credit memos linked to the invoice. * Possibility to attach the credit memo PDF to the email. * @param {String} selector_type * @return {String} inlineQty */ function creditMemoSection(selector_type) { var inlineQty = ''; if (selector_type == 'invoice_number') { // Credit Memo Header inlineQty += '<div class="form-group container credit_memo credit_memo_header">'; inlineQty += '<div class="row">'; inlineQty += '<div class="col-xs-12 heading2">'; inlineQty += '<h4><span style="background-color: #379E8F" class="label label-default col-xs-12">CREDIT MEMO</span></h4>'; inlineQty += '</div></div></div>'; // Credit Memo table inlineQty += '<div class="form-group container credit_memo credit_memo_section" style="font-size: small;">'; inlineQty += '<div class="row">'; inlineQty += '<div class="col-xs-12 credit_memo_div">'; // Since the table is not displayed correctly when added through suitelet, // It is added with jQuery in the pageInit() function in the client script 'mp_cl_open_ticket.js'. inlineQty += '</div></div></div>'; } return inlineQty; } function usageReportSection(selector_type) { var inlineQty = ''; if (selector_type == 'invoice_number') { // Usage Report Header inlineQty += '<div class="form-group container usage_report usage_report_header">'; inlineQty += '<div class="row">'; inlineQty += '<div class="col-xs-12 heading2">'; inlineQty += '<h4><span style="background-color: #379E8F" class="label label-default col-xs-12">USAGE REPORT</span></h4>'; inlineQty += '</div></div></div>'; // Usage Report table inlineQty += '<div class="form-group container usage_report usage_report_section" style="font-size: small;">'; inlineQty += '<div class="row">'; inlineQty += '<div class="col-xs-12 usage_report_div">'; // Since the table is not displayed correctly when added through suitelet, // It is added with jQuery in the pageInit() function in the client script 'mp_cl_open_ticket.js'. inlineQty += '</div></div></div>'; } return inlineQty; } /** * The "Send Email" section. * Possibility for the user to send an email to the customer, based on selected templates. * @param {Number} ticket_id * @param {Number} status_value * @param {Object} account_manager * @returns {String} inlineQty */ function sendEmailSection(ticket_id, status_value, account_manager, list_toll_emails) { var has_toll_emails = (!isNullorEmpty(list_toll_emails)); if (isNullorEmpty(ticket_id) || !isTicketNotClosed(status_value)) { // The section is hidden here rather than in the openTicket function, // because we use the section to send an acknoledgement email when a ticket is opened. var inlineQty = '<div id="send_email_container" class="send_email hide">'; } else { var inlineQty = '<div id="send_email_container" class="send_email">'; } // inlineQty += '<div class="form-group container send_email header_section">'; // // Send email header // inlineQty += '<div class="row">'; // inlineQty += '<div class="col-xs-12 heading2">'; // inlineQty += '<h4><span style="background-color: #379E8F" class="label label-default col-xs-12">SEND EMAILS</span></h4>'; // inlineQty += '</div></div></div>'; inlineQty += '<br></br>' // Row addressees inlineQty += '<div class="form-group container send_email adressees_section">'; inlineQty += '<div class="row">'; inlineQty += '<div class="col-xs-12 to_section">'; inlineQty += '<div class="input-group">'; inlineQty += '<span class="input-group-addon">TO<span class="mandatory">*</span></span>'; inlineQty += '<input id="send_to" class="form-control" data-contact-id="" data-firstname=""/>'; inlineQty += '</div></div></div></div>'; // Toll addresses var toll_emails_columns = new Array(); toll_emails_columns[0] = search.createColumn({ name: 'name' }); toll_emails_columns[1] = search.createColumn({ name: 'internalId' }); var tollEmailsResultSet = search.create({ type: 'customlist_toll_emails', columns: toll_emails_columns, }) inlineQty += '<div class="form-group container send_email toll_adressees_section">'; inlineQty += '<div class="row">'; inlineQty += '<div class="col-xs-12 toll_section">'; inlineQty += '<div class="input-group">'; inlineQty += '<span class="input-group-addon">TOLL EMAILS</span>'; inlineQty += '<select multiple id="send_toll" class="form-control" size="' + tollEmailsResultSet.length + '"/>'; tollEmailsResultSet.run().each(function (tollEmailsResultSet) { var tollEmailName = tollEmailsResultSet.getValue('name'); var tollEmailId = tollEmailsResultSet.getValue('internalId'); var selected = false; if (has_toll_emails) { selected = (list_toll_emails.indexOf(tollEmailId) !== -1); } if (selected) { inlineQty += '<option value="' + tollEmailId + '" selected>' + tollEmailName + '</option>'; } else { inlineQty += '<option value="' + tollEmailId + '">' + tollEmailName + '</option>'; } return true; }); inlineQty += '</select>'; inlineQty += '</div></div></div></div>'; // Row ccs addresses inlineQty += '<div class="form-group container send_email cc_adressees_section">'; inlineQty += '<div class="row">'; inlineQty += '<div class="col-xs-6 cc_section">'; inlineQty += '<div class="input-group">'; inlineQty += '<span class="input-group-addon">CC</span>'; inlineQty += '<input id="send_cc" class="form-control"/>'; inlineQty += '</div></div>'; inlineQty += '<div class="col-xs-6 bcc_section">'; inlineQty += '<div class="input-group">'; inlineQty += '<span class="input-group-addon">BCC</span>'; inlineQty += '<input id="send_bcc" class="form-control"/>'; inlineQty += '</div></div></div></div>'; // Row account manager if (isNullorEmpty(account_manager.name)) { account_manager.name = '' } if (isNullorEmpty(account_manager.email)) { account_manager.email = '' } if (!isNullorEmpty(account_manager.email.email)) { inlineQty += '<div class="form-group container send_email acc_manager_section">'; inlineQty += '<div class="row">'; inlineQty += '<div class="col-xs-10 acc_manager_name_section">'; inlineQty += '<div class="input-group">'; inlineQty += '<span class="input-group-addon">ACCOUNT MANAGER</span>'; inlineQty += '<input id="acc_manager" class="form-control" data-email="' + account_manager.email.email + '" value="' + account_manager.name + ' - ' + account_manager.email.email + '" disabled/>'; inlineQty += '</div></div>'; inlineQty += '<div class="col-xs-2 acc_manager_button_section">'; inlineQty += '<button id="acc_manager_button" style="background-color: #379E8F; border-color: #379E8F" type="button" class="btn btn-success btn-block">ADD TO CC</button>'; inlineQty += '</div></div></div>'; } // Row Template inlineQty += '<div class="form-group container send_email template_section">'; inlineQty += '<div class="row">'; inlineQty += '<div class="col-xs-12 template_section">'; inlineQty += '<div class="input-group">'; inlineQty += '<span class="input-group-addon">TEMPLATE<span class="mandatory">*</span></span>'; inlineQty += '<select id="template" class="form-control">'; inlineQty += '<option></option>'; // Load the template options var templatesSearch = search.load({ id: 'customsearch_cctemplate_mp_ticket', type: 'customrecord_camp_comm_template' }); var templatesSearchResults = templatesSearch.run(); templatesSearchResults.each(function (templatesSearchResult) { // var tempId = templatesSearchResult.getValue('internalid'); var tempId = templatesSearchResult["id"]; var tempName = templatesSearchResult.getValue('name'); inlineQty += '<option value="' + tempId + '">' + tempName + '</option>'; return true; }); inlineQty += '</select>'; inlineQty += '</div></div></div></div>'; // Row Subject inlineQty += '<div class="form-group container send_email subject_section">'; inlineQty += '<div class="row">'; inlineQty += '<div class="col-xs-12 subject_section">'; inlineQty += '<div class="input-group">'; inlineQty += '<span class="input-group-addon">SUBJECT<span class="mandatory">*</span></span>'; inlineQty += '<input id="subject" class="form-control" />'; inlineQty += '</div></div></div></div>'; // Row Body inlineQty += '<div class="form-group container send_email body_section">'; inlineQty += '<div class="row">'; inlineQty += '<div class="col-xs-12 body_section">'; inlineQty += '<div id="email_body"></div>'; inlineQty += '</div></div></div>'; // SEND EMAIL button inlineQty += '<div class="form-group container send_email button_section">'; inlineQty += '<div class="row">'; inlineQty += '<div class="col-xs-4 col-xs-offset-4 send_email_btn">'; inlineQty += '<input type="button" style="background-color: #379E8F; border-color: #379E8F; font-weight: 700" value="SEND EMAIL" class="form-control btn btn-primary" id="send_email" />'; inlineQty += '</div></div></div></div>'; return inlineQty; }; /** * Section for the previous emails datatable * @param customer_id * @returns {string} */ function previousEmailsSection(customer_id) { var customerRecord = record.load({ type: record.Type.CUSTOMER, id: customer_id, }); var customer_internal_id = customerRecord.getValue({ fieldId: 'id' }); // Previous Emails header var inlineQty = '<div class="form-group container previous_emails_header">'; inlineQty += '<div class="row">'; inlineQty += '<div class="col-xs-12 heading2">'; inlineQty += '<h4><span style="background-color: #379E8F" class="label label-default col-xs-12">PREVIOUS EMAILS</span></h4>'; inlineQty += '</div></div></div>'; //Searching emails filtered by - internal customer id and dated before the lastmonthonefiscalquarterago (i.e. the past three months) var emailSearch = search.load({ type: 'message', id: 'customsearch_all_messages' }); var emailSearchFilter = [["customer.internalid", "anyof", customer_internal_id], "AND", ["messagedate", "after", "lastmonthonefiscalquarterago"]]; //670041, 313070 emailSearch.filterExpression = emailSearchFilter; var resultEmailSet = emailSearch.run(); var allEmails = resultEmailSet.getRange({ start: 0, end: 1000 }); //Previous Emails table setup // inlineQty += '<style> table {font-size: 12px;text-align: center;border: none;} {font-size: 14px;} table th{text-align: center;} .dataTables_wrapper{width:78%; margin:auto;} </style>'; // inlineQty += '<div class="form-group container previous_emails_section">'; // inlineQty += '<table cellpadding="15" id="emails-preview" class="table table-responsive table-striped customer tablesorter" cellspacing="0" style="width: 100%;">'; // inlineQty += '<thead style="color: white;background-color: #CFE0CE;">'; // inlineQty += '<tr class="text-center">'; // inlineQty += '<th scope="col">Message Date</th>'; // inlineQty += '<th scope="col">Author</th>'; // inlineQty += '<th scope="col">Receipients</th>'; // inlineQty += '<th scope="col">Subject</th>'; // inlineQty += '<th scope="col">More</th>'; // inlineQty += '</tr>'; // inlineQty += '</thead>'; // inlineQty += '<tbody>'; inlineQty += '<style>table#emails-preview {font-size: 12px;text-align: center;border: none; background-color: #379E8F}.dataTables_wrapper {font-size: 12px;}table#emails-preview th{background-color: #379E8F; text-align: center;}</style>'; inlineQty += '<table cellpadding="15" id="emails-preview" class="table table-responsive table-striped customer tablesorter" cellspacing="0" style="width: 100%;">'; inlineQty += '<thead style="color: white;background-color: #379E8F;">'; inlineQty += '<tr class="text-center">'; inlineQty += '<th scope="col">Message Date</th>'; inlineQty += '<th scope="col">Author</th>'; inlineQty += '<th scope="col">Receipients</th>'; inlineQty += '<th scope="col">Subject</th>'; inlineQty += '<th scope="col">More</th>'; inlineQty += '</tr>'; inlineQty += '</thead>'; inlineQty += '<tbody>'; allEmails.forEach(function (email) { var messageid = email.searchId; var date = email.getValue('messagedate'); var author = email.getValue('authoremail'); var recipients = email.getText('recipients'); var subject = email.getValue('subject'); var url = "https://1048144-sb3.app.netsuite.com/app/crm/common/crmmessage.nl?id=" + messageid; //Table row data inlineQty += '<tr>'; inlineQty += '<td> ' + date + ' </td>'; inlineQty += '<td> ' + author + ' </td>'; inlineQty += '<td> ' + recipients + ' </td>'; inlineQty += '<td> ' + subject + '</td>'; inlineQty += '<td> <a href=' + url + '> View More </a> </td>'; inlineQty += '</tr>'; }); inlineQty += '</tbody>'; inlineQty += '</table>'; //inlineQty += '</div>'; return inlineQty; } /** * @return {String} inlineQty */ function issuesHeader() { var inlineQty = '<div class="form-group container toll_issues_header_section">'; inlineQty += '<div class="row">'; inlineQty += '<div class="col-xs-12 heading1">'; inlineQty += '<h4><span style="background-color: #379E8F" class="form-group label label-default col-xs-12">ISSUES</span></h4>'; inlineQty += '</div></div></div>'; return inlineQty; } /** * @param {Number} status_value * @return {String} inlineQty */ function reminderSection(status_value) { var hide_class = (!isTicketNotClosed(status_value)) ? 'hide' : ''; var inlineQty = '<div class="form-group container reminder_section ' + hide_class + '">'; inlineQty += '<div class="row">'; // Reminder field inlineQty += '<div class="col-xs-12 reminder">'; inlineQty += '<div class="input-group">'; inlineQty += '<span class="input-group-addon" id="reminder_text">REMINDER</span>'; inlineQty += '<input id="reminder" class="form-control reminder" type="date" />'; inlineQty += '</div></div></div></div>'; return inlineQty; } /** * Based on the selected MP Issue, an Owner is allocated to the ticket. * IT issues have priority over the other issues. * Populated with selectOwner() in the pageInit function on the client script. * @param {Number} ticket_id * @param {Array} owner_list * @param {Number} status_value * @return {String} inlineQty */ function ownerSection(ticket_id, owner_list, status_value) { if (isNullorEmpty(ticket_id)) { // If ticket_id is null, owner_list as well. // In that case, only the creator of the ticket is pre-selected as the owner. var userId = runtime.getCurrentUser().id; log.debug({ title: 'userId', details: userId }) owner_list = [userId]; } var disabled = (!isTicketNotClosed(status_value)) ? 'disabled' : ''; log.debug({ title: 'owner_list', details: owner_list }) var inlineQty = '<div class="form-group container owner_section">'; inlineQty += '<div class="row">'; inlineQty += '<div class="col-xs-12 owner">'; inlineQty += '<div class="input-group">'; inlineQty += '<span class="input-group-addon" id="owner_text">OWNER<span class="mandatory">*</span></span>'; inlineQty += '<select multiple id="owner" class="form-control owner" ' + disabled + '>'; var employeeSearch = search.load({ type: 'employee', id: 'customsearch_active_employees' }); var employeeResultSet = employeeSearch.run(); employeeResultSet.each(function (employeeResult) { var employee_id = employeeResult.id; var employee_firstname = employeeResult.getValue('firstname'); var employee_lastname = employeeResult.getValue('lastname'); var employee_email = employeeResult.getValue('email'); if (owner_list.indexOf(parseInt(employee_id)) != -1) { inlineQty += '<option value="' + employee_id + '" data-email="' + employee_email + '" selected>' + employee_firstname + ' ' + employee_lastname + '</option>'; } else { inlineQty += '<option value="' + employee_id + '" data-email="' + employee_email + '">' + employee_firstname + ' ' + employee_lastname + '</option>'; } return true; }); inlineQty += '</select>'; inlineQty += '</div></div></div></div>'; return inlineQty; } function customerIssueDropdown() { //Load the customer issue list var col = new Array(); col[0] = search.createColumn({ name: 'name' }); col[1] = search.createColumn({ name: 'internalId' }); var results = search.create({ type: 'customlist_customer_ticket_issues', columns: col, }) var inlineQty = '<div class="form-group container customer_issues_dropdown_section">'; inlineQty += '<div class="row">'; inlineQty += '<div class="col-xs-12">'; inlineQty += '<div class="input-group"><span class="input-group-addon">CUSTOMER ISSUE</span>'; inlineQty += '<select id="customer_issue_dropdown" class="form-control">'; inlineQty += '<option></option>'; for (var i = 0; results != null && i < results.length; i++) { var res = results[i]; var listValue = res.getValue('name'); var listID = res.getValue('internalId'); inlineQty += '<option value="' + listID + '">' + listValue + '</option>'; // if (selected) { // inlineQty += '<option value="' + listID + '" selected>' + listValue + '</option>'; // } else { // inlineQty += '<option value="' + listID + '">' + listValue + '</option>'; // } } inlineQty += '</select>'; inlineQty += '</div></div></div></div>'; return inlineQty; } function customerIssuesSection(ticket_id, selector_type, selector_number, screenshot_file, selected_browser, login_email_used, selected_operating_system, phone_used, old_sender_name, old_sender_phone, status_value) { if (isNullorEmpty(screenshot_file)) { screenshot_file = ''; } if (isNullorEmpty(selected_browser)) { selected_browser = ''; } if (isNullorEmpty(login_email_used)) { login_email_used = ''; } if (isNullorEmpty(selected_operating_system)) { operating_system = ''; } if (isNullorEmpty(phone_used)) { phone_used = ''; } if (isNullorEmpty(old_sender_name)) { old_sender_name = ''; } if (isNullorEmpty(old_sender_phone)) { old_sender_phone = ''; } var hide_class_section_mp_app = ((selector_type == "customer_issue") && (selector_number == 'Customer App')) ? '' : 'hide'; var hide_class_section_mp_label = ((selector_type == "customer_issue") && (selector_number == 'Update Label')) ? '' : 'hide'; var is_customer_issue_hide = (selector_type != "customer_issue") ? 'hide' : ''; var hide_class_section_mp_portal = ((selector_type == "customer_issue") && (selector_number == 'Customer Portal')) ? '' : 'hide'; var inlineQty = ''; //Screenshot section if (selector_type == "customer_issue" && (selector_number == "Customer App" || selector_number == "Customer Portal") && !isNullorEmpty(ticket_id)) { inlineQty += '<div class="form-group container ss_section">'; inlineQty += '<div class="row">'; inlineQty += '<div class="col-xs-12 screenshot_div">'; inlineQty += '<div class="input-group"><span class="input-group-addon" id="screenshot_text">SCREENSHOT</span>'; inlineQty += '<input type="file" class="form-control" id="screenshot_image" value="' + screenshot_file + '">'; inlineQty += '</div></div></div></div>'; } // Browser and OS Section inlineQty += '<div class="form-group container browser_os_section ' + hide_class_section_mp_portal + ' ' + is_customer_issue_hide + '">'; inlineQty += '<div class="row">'; inlineQty += '<div class="col-xs-6 browser_div">'; inlineQty += '<div class="input-group"><span class="input-group-addon" id="browser_text">BROWSER</span>'; inlineQty += '<select id="browser_value" class="form-control label_status">'; inlineQty += '<option></option>' var browserColumns = new Array(); browserColumns[0] = search.createColumn({ name: 'name' }); browserColumns[1] = search.createColumn({ name: 'internalId' }); var browserResultSet = search.create({ type: 'customlist_common_browsers', columns: browserColumns }); browserResultSet.run().each(function (browserResult) { var browserName = browserResult.getValue('name'); var browserId = browserResult.getValue('internalId'); if (selected_browser == browserId) { inlineQty += '<option value="' + browserId + '"selected>' + browserName + '</option>'; } else { inlineQty += '<option value="' + browserId + '">' + browserName + '</option>'; } return inlineQty; }); inlineQty += '</select></div></div>'; inlineQty += '<div class="col-xs-6 os_div">'; inlineQty += '<div class="input-group"><span class="input-group-addon" id="os_text">OPERATING SYSTEM</span>'; inlineQty += '<select id="os_value" class="form-control">'; inlineQty += '<option></option>' var osColumns = new Array(); osColumns[0] = search.createColumn({ name: 'name' }); osColumns[1] = search.createColumn({ name: 'internalId' }); var osResultSet = search.create({ type: 'customlist_common_os', columns: osColumns }); osResultSet.run().each(function (osResult) { var osName = osResult.getValue('name'); var osId = osResult.getValue('internalId'); if (selected_browser == osId) { inlineQty += '<option value="' + osId + '"selected>' + osName + '</option>'; } else { inlineQty += '<option value="' + osId + '">' + osName + '</option>'; } return inlineQty; }); inlineQty += '</select>'; inlineQty += '</div></div></div></div>'; //Customer App issues - Phone section inlineQty += '<div class="form-group container ' + is_customer_issue_hide + ' phone_section ' + hide_class_section_mp_app + '">'; inlineQty += '<div class="row">'; inlineQty += '<div class="col-xs-12 phone_div">'; inlineQty += '<div class="input-group"><span class="input-group-addon" id="screenshot_text">PHONE</span>'; inlineQty += '<input type="text" class="form-control" id="phone_used" placeholder=" Google Pixel 3" value="' + phone_used + '">'; inlineQty += '</div></div></div></div>'; //Login email used section inlineQty += '<div class="form-group container login_email_used_section ' + is_customer_issue_hide + '">'; inlineQty += '<div class="row">'; inlineQty += '<div class="col-xs-12 login_email_div">'; inlineQty += '<div class="input-group">'; inlineQty += '<span class="input-group-addon" id="login_email">LOGIN EMAIL</span>'; inlineQty += '<input id="login_email_text" class="form-control" value="' + login_email_used + '"/>'; inlineQty += '</div></div></div></div>'; //Sender details name and phone number inlineQty += '<div class="form-group container ' + is_customer_issue_hide + ' sender_details_section ' + hide_class_section_mp_label + '">'; inlineQty += '<div class="row">'; inlineQty += '<div class="col-xs-6 sender_name_div">'; inlineQty += '<div class="input-group">'; inlineQty += '<span class="input-group-addon" id="sender_name">SENDER NAME</span>'; inlineQty += '<input id="sender_name_text" class="form-control" value="' + old_sender_name + '"/>'; inlineQty += '</div></div>'; inlineQty += '<div class="col-xs-6 sender_phone_div">'; inlineQty += '<div class="input-group">'; inlineQty += '<span class="input-group-addon" id="sender_phone">SENDER PHONE</span>'; inlineQty += '<input id="sender_phone_text" class="form-control" value="' + old_sender_phone + '"/>'; inlineQty += '</div></div></div></div>'; return inlineQty; } /** * The multiselect TOLL issues dropdown * @param {Array} list_toll_issues * @param {Array} list_resolved_toll_issues * @param {Number} status_value * @param {String} selector_type * @return {String} inlineQty */ function tollIssuesSection(list_toll_issues, list_resolved_toll_issues, status_value, selector_type) { // TOLL Issues var has_toll_issues = (!isNullorEmpty(list_toll_issues)); var toll_issues_columns = new Array(); toll_issues_columns[0] = search.createColumn({ name: 'name' }); toll_issues_columns[1] = search.createColumn({ name: 'internalId' }); var tollIssuesResultSet = search.create({ type: 'customlist_cust_prod_stock_toll_issues', columns: toll_issues_columns }); if (!isTicketNotClosed(status_value) || selector_type != 'barcode_number') { var inlineQty = '<div class="form-group container toll_issues_section hide">'; } else { var inlineQty = '<div class="form-group container toll_issues_section">'; } inlineQty += '<div class="row">'; inlineQty += '<div class="col-xs-12 toll_issues">'; inlineQty += '<div class="input-group"><span class="input-group-addon" id="toll_issues_text">TOLL ISSUES<span class="mandatory">*</span></span>'; inlineQty += '<select multiple id="toll_issues" class="form-control toll_issues" size="' + tollIssuesResultSet.length + '">'; tollIssuesResultSet.run().each(function (tollIssueResult) { var issue_name = tollIssueResult.getValue('name'); var issue_id = tollIssueResult.getValue('internalId'); var selected = false; if (has_toll_issues) { selected = (list_toll_issues.indexOf(issue_id) !== -1); } if (selected) { inlineQty += '<option value="' + issue_id + '" selected>' + issue_name + '</option>'; } else { inlineQty += '<option value="' + issue_id + '">' + issue_name + '</option>'; } return true; }); inlineQty += '</select>'; inlineQty += '</div></div></div></div>'; // Resolved TOLL Issues log.debug({ title: 'list_resolved_toll_issues : ', details: list_resolved_toll_issues }); var has_resolved_toll_issues = (!isNullorEmpty(list_resolved_toll_issues)); if (has_resolved_toll_issues) { var text_resolved_toll_issues = ''; tollIssuesResultSet.run().each(function (tollIssueResult) { var issue_name = tollIssueResult.getValue('name'); var issue_id = tollIssueResult.getValue('internalId'); if (list_resolved_toll_issues.indexOf(issue_id) !== -1) { text_resolved_toll_issues += issue_name + '\n'; } return true; }); log.debug({ title: 'text_resolved_toll_issues : ', details: text_resolved_toll_issues }); inlineQty += '<div class="form-group container resolved_toll_issues_section">'; inlineQty += '<div class="row">'; inlineQty += '<div class="col-xs-12 resolved_toll_issues">'; inlineQty += '<div class="input-group">'; inlineQty += '<span class="input-group-addon" id="resolved_toll_issues_text">RESOLVED TOLL ISSUES</span>'; inlineQty += '<textarea id="resolved_toll_issues" class="form-control resolved_toll_issues" rows="' + list_resolved_toll_issues.length + '" disabled>' + text_resolved_toll_issues.trim() + '</textarea>'; inlineQty += '</div></div></div></div>'; } return inlineQty; }; /** * The multiselect MP Ticket issues dropdown * @param {Array} list_mp_ticket_issues * @param {Array} list_resolved_mp_ticket_issues * @param {Number} status_value * @param {String} selector_type * @return {String} inlineQty */ function mpTicketIssuesSection(list_mp_ticket_issues, list_resolved_mp_ticket_issues, status_value, selector_type) { // MP Ticket Issues var has_mp_ticket_issues = !isNullorEmpty(list_mp_ticket_issues); var disabled_mp_issue_field = (isTicketNotClosed(status_value)) ? '' : 'disabled'; log.debug({ title: 'has_mp_ticket_issues : ', details: has_mp_ticket_issues }); if (has_mp_ticket_issues && status_value != 3) { // The MP Ticket issue section is displayed if the status is 'Closed - Unallocated' (status_value == 8) var inlineQty = '<div class="form-group container mp_issues_section">'; } else { var inlineQty = '<div class="form-group container mp_issues_section hide">'; } inlineQty += '<div class="row">'; inlineQty += '<div class="col-xs-12 mp_issues">'; var mp_ticket_issues_columns = new Array(); mp_ticket_issues_columns[0] = search.createColumn({ name: 'name' }); mp_ticket_issues_columns[1] = search.createColumn({ name: 'internalId' }); var mpTicketIssuesResultSet = search.create({ type: 'customlist_mp_ticket_issues', columns: mp_ticket_issues_columns }); inlineQty += '<div class="input-group">' inlineQty += '<span class="input-group-addon" id="mp_issues_text">MP ISSUES<span class="mandatory hide">*</span></span>'; inlineQty += '<select multiple id="mp_issues" class="form-control mp_issues" size="' + mpTicketIssuesResultSet.length + '" ' + disabled_mp_issue_field + '>'; mpTicketIssuesResultSet.run().each(function (mpTicketIssueResult) { var mp_issue_name = mpTicketIssueResult.getValue('name'); var mp_issue_id = mpTicketIssueResult.getValue('internalId'); var selected = false; if (has_mp_ticket_issues) { selected = (list_mp_ticket_issues.indexOf(mp_issue_id) !== -1); } var show_option = (selector_type == 'barcode_number' || (selector_type == 'invoice_number' && mp_issue_id == 4) || (selector_type == "customer_issue")); var selected_option = (selected) ? 'selected' : ''; if (show_option) { inlineQty += '<option value="' + mp_issue_id + '" ' + selected_option + '> ' + mp_issue_name + '</option > '; } return true; }); inlineQty += '</select>'; inlineQty += '</div></div></div></div>'; // Resolved MP Ticket Issues var has_resolved_mp_ticket_issues = !isNullorEmpty(list_resolved_mp_ticket_issues); if (has_resolved_mp_ticket_issues && selector_type != "customer_issue") { var text_resolved_mp_ticket_issues = ''; mpTicketIssuesResultSet.run().each(function (mpTicketIssueResult) { var mp_issue_name = mpTicketIssueResult.getValue('name'); var mp_issue_id = mpTicketIssueResult.getValue('internalId'); if (list_resolved_mp_ticket_issues.indexOf(mp_issue_id) !== -1) { text_resolved_mp_ticket_issues += mp_issue_name + '\n'; } return true; }); inlineQty += '<div class="form-group container resolved_mp_issues_section">'; inlineQty += '<div class="row">'; inlineQty += '<div class="col-xs-12 resolved_mp_issues">'; inlineQty += '<div class="input-group">'; inlineQty += '<span class="input-group-addon" id="resolved_mp_issues_text">RESOLVED MP ISSUES</span>'; inlineQty += '<textarea id="resolved_mp_issues" class="form-control resolved_mp_issues" rows="' + list_resolved_mp_ticket_issues.length + '" disabled>' + text_resolved_mp_ticket_issues.trim() + '</textarea>'; inlineQty += '</div></div></div></div>'; } return inlineQty; } /** * The multiselect Invoice issues dropdown * @param {Array} list_invoice_issues * @param {Array} list_resolved_invoice_issues * @param {Number} status_value * @param {String} selector_type * @return {String} inlineQty */ function invoiceIssuesSection(list_invoice_issues, list_resolved_invoice_issues, status_value, selector_type) { var has_invoice_issues = (!isNullorEmpty(list_invoice_issues)); var invoice_issues_columns = new Array(); invoice_issues_columns[0] = search.createColumn({ name: 'name' }); // Might need to be changed invoice_issues_columns[1] = search.createColumn({ name: 'internalId' }); // Might need to be changed var invoiceIssuesResultSet = search.create({ type: 'customlist_invoice_issues', columns: invoice_issues_columns }); if (!isTicketNotClosed(status_value) || selector_type != 'invoice_number') { var inlineQty = '<div class="form-group container invoice_issues_section hide">'; } else { var inlineQty = '<div class="form-group container invoice_issues_section">'; } inlineQty += '<div class="row">'; inlineQty += '<div class="col-xs-12 invoice_issues">'; inlineQty += '<div class="input-group"><span class="input-group-addon" id="invoice_issues_text">INVOICE ISSUES<span class="mandatory">*</span></span>'; inlineQty += '<select multiple id="invoice_issues" class="form-control invoice_issues">'; invoiceIssuesResultSet.run().each(function (invoiceIssueResult) { var issue_name = invoiceIssueResult.getValue('name'); // Might need to be changed var issue_id = invoiceIssueResult.getValue('internalId'); // Might need to be changed var selected = false; if (has_invoice_issues) { selected = (list_invoice_issues.indexOf(issue_id) != -1); } if (selected) { inlineQty += '<option value="' + issue_id + '" selected>' + issue_name + '</option>'; } else { inlineQty += '<option value="' + issue_id + '">' + issue_name + '</option>'; } return true; }); inlineQty += '</select>'; inlineQty += '</div></div></div></div>'; // Resolved invoice Issues log.debug({ title: 'list_resolved_invoice_issues : ', details: list_resolved_invoice_issues }); var has_resolved_invoice_issues = (!isNullorEmpty(list_resolved_invoice_issues)); if (has_resolved_invoice_issues) { var text_resolved_invoice_issues = ''; invoiceIssuesResultSet.run().each(function (invoiceIssueResult) { var issue_name = invoiceIssueResult.getValue('name'); // Might need to be changed var issue_id = invoiceIssueResult.getValue('internalId'); // Might need to be changed if (list_resolved_invoice_issues.indexOf(issue_id) !== -1) { text_resolved_invoice_issues += issue_name + '\n'; } }); log.debug({ title: 'text_resolved_invoice_issues : ', details: text_resolved_invoice_issues }); inlineQty += '<div class="form-group container resolved_invoice_issues_section">'; inlineQty += '<div class="row">'; inlineQty += '<div class="col-xs-12 resolved_invoice_issues">'; inlineQty += '<div class="input-group">'; inlineQty += '<span class="input-group-addon" id="resolved_invoice_issues_text">RESOLVED INVOICE ISSUES</span>'; inlineQty += '<textarea id="resolved_invoice_issues" class="form-control resolved_invoice_issues" rows="' + list_resolved_invoice_issues.length + '" disabled>' + text_resolved_invoice_issues.trim() + '</textarea>'; inlineQty += '</div></div></div></div>'; } return inlineQty; } /** * @param {String} selector_type * @param {Number} status_value * @return {String} inlineQty */ function usernoteSection(selector_type, status_value) { var usernote_titles_columns = new Array(); usernote_titles_columns[0] = search.createColumn({ name: 'name' }); usernote_titles_columns[1] = search.createColumn({ name: 'internalId' }); var usernoteTitlesResultSet = search.create({ type: 'customlist_user_note_title', columns: usernote_titles_columns }); // Row Title if (selector_type == 'invoice_number' && isTicketNotClosed(status_value)) { var inlineQty = '<div class="form-group container user_note user_note_title_section">'; } else { var inlineQty = '<div class="form-group container user_note user_note_title_section hide">'; } inlineQty += '<div class="row">'; inlineQty += '<div class="col-xs-12 user_note_title_section">'; inlineQty += '<div class="input-group">'; inlineQty += '<span class="input-group-addon">TITLE<span class="mandatory">*</span></span>'; inlineQty += '<select id="user_note_title" class="form-control">'; usernoteTitlesResultSet.run().each(function (usernoteTitleResult) { var title_name = usernoteTitleResult.getValue('name'); var title_id = usernoteTitleResult.getValue('internalId'); if (title_id == 3) { inlineQty += '<option value="' + title_id + '" selected>' + title_name + '</option>'; } else { inlineQty += '<option value="' + title_id + '">' + title_name + '</option>'; } return true; }); inlineQty += '</select>'; inlineQty += '</div></div></div></div>'; // Row User Note Textarea if (selector_type == 'invoice_number' && isTicketNotClosed(status_value)) { inlineQty += '<div class="form-group container user_note user_note_textarea_section">'; } else { inlineQty += '<div class="form-group container user_note user_note_textarea_section hide">'; } inlineQty += '<div class="row">'; inlineQty += '<div class="col-xs-12 user_note_textarea">'; inlineQty += '<div class="input-group">'; inlineQty += '<span class="input-group-addon" id="user_note_textarea_text">USER NOTE<span class="mandatory hide">*</span></span>'; inlineQty += '<textarea id="user_note_textarea" class="form-control user_note_textarea" rows="3"></textarea>'; inlineQty += '</div></div></div></div>'; // User Note table if (selector_type == 'invoice_number') { inlineQty += '<div class="form-group container user_note user_note_section" style="font-size: small;">'; } else { inlineQty += '<div class="form-group container user_note user_note_section hide" style="font-size: small;">'; } inlineQty += '<div class="row">'; inlineQty += '<div class="col-xs-12 user_note_div">'; // Since the table is not displayed correctly when added through suitelet, // It is added with jQuery in the pageInit() function in the client script 'mp_cl_open_ticket.js'. inlineQty += '</div>'; inlineQty += '</div>'; inlineQty += '</div>'; return inlineQty; } /** * Used to pass the values of `date_from` and `date_to` between the scripts and to Netsuite for the records and the search. * @param {String} date_iso "2020-06-01" * @returns {String} date_netsuite "1/6/2020" */ function dateISOToNetsuite(date_iso) { var date_netsuite = ''; if (!isNullorEmpty(date_iso)) { var date_netsuite = format.format({ value: date_iso, type: format.Type.DATETIME }); } return date_netsuite; } /** * The free-from text area for comments. * @param {String} comment * @param {String} selector_type * @param {Number} status_value * @return {String} inlineQty */ function commentSection(comment, selector_type, status_value) { if (isNullorEmpty(comment)) { comment = ''; } else { comment += '\n'; } switch (selector_type) { case 'barcode_number': var inlineQty = '<div class="form-group container comment_section">'; break; case 'invoice_number': var inlineQty = '<div class="form-group container comment_section hide">'; break; case 'customer_issue': var inlineQty = '<div class="form-group container comment_section">'; break; } inlineQty += '<div class="row">'; inlineQty += '<div class="col-xs-12 comment">'; inlineQty += '<div class="input-group">'; inlineQty += '<span class="input-group-addon" id="comment_text">COMMENT<span class="mandatory hide">*</span></span>'; if (isTicketNotClosed(status_value)) { inlineQty += '<textarea id="comment" class="form-control comment" rows="9">' + comment + '</textarea>'; } else { inlineQty += '<textarea id="comment" class="form-control comment" rows="9" readonly>' + comment + '</textarea>'; } inlineQty += '</div></div></div></div>'; return inlineQty; } /** * The table that will display the differents tickets linked to the customer. * @return {String} inlineQty */ function dataTablePreview() { var inlineQty = '<div class="form-group container tickets_datatable_section">'; inlineQty += '<div class="row">'; inlineQty += '<div class="col-xs-12 heading2">'; inlineQty += '<h4><span style="background-color: #379E8F" class="label label-default col-xs-12">PREVIOUS TICKETS</span></h4>'; inlineQty += '</div></div></div>'; inlineQty += '<style>table#tickets-preview {font-size: 12px;text-align: center;border: none; background-color: #379E8F}.dataTables_wrapper {font-size: 12px;}table#tickets-preview th{background-color: #379E8F; text-align: center;}</style>'; inlineQty += '<table cellpadding="15" id="tickets-preview" class="table table-responsive table-striped customer tablesorter" cellspacing="0" style="width: 100%;">'; inlineQty += '<thead style="color: white;background-color: #379E8F;">'; inlineQty += '<tr class="text-center">'; inlineQty += '</tr>'; inlineQty += '</thead>'; inlineQty += '<tbody id="result_tickets"></tbody>'; inlineQty += '</table>'; return inlineQty; } /** * The inline HTML for the close ticket button or the reopen button, * and the submitter button at the bottom of the page. * @param {Number} ticket_id * @param {Number} status_value * @return {String} inlineQty */ function closeReopenSubmitTicketButton(ticket_id, status_value) { var inlineQty = '<div class="form-group container close_reopen_submit_ticket_section">'; inlineQty += '<div class="row">'; log.debug({ title: 'status_value', details: status_value }); log.debug({ title: 'ticket_id', details: ticket_id }); if (isTicketNotClosed(status_value)) { if (!isNullorEmpty(ticket_id)) { inlineQty += '<div class="col-xs-2 close_ticket">'; inlineQty += '<input type="button" value="CLOSE TICKET" style="background-color: #FBEA51; border: 3px solid #379E8F; color: #379E8F; font-weight: 700" class="form-control btn btn-default" id="close_ticket" onclick="closeTicket()"/>'; inlineQty += '</div>'; inlineQty += '<div class="col-xs-3 close_ticket_lost">'; inlineQty += '<input type="button" value="CLOSE TICKET - LOST ITEM" style="background-color: #FBEA51; border: 3px solid #379E8F; color: #379E8F; font-weight: 700" class="form-control btn btn-default" id="close_ticket_lost" onclick="closeTicketLost()"/>'; inlineQty += '</div>'; if (userId == 409635 || userId == 696992 || userId == 766498) { inlineQty += '<div class="col-xs-3 close_unallocated_ticket hide">'; inlineQty += '<input type="button" value="CLOSE UNALLOCATED TICKET" style="background-color: #FBEA51; border: 3px solid #379E8F; color: #379E8F; font-weight: 700" class="form-control btn btn-default" id="close_unallocated_ticket" onclick="closeUnallocatedTicket()" />'; inlineQty += '</div>'; } } inlineQty += '<div class="col-xs-2 submitter">'; inlineQty += '<input type="button" style="background-color: #FBEA51; border: 3px solid #379E8F; color: #379E8F; font-weight: 700" value="UPDATE TICKET" class="form-control btn btn-primary" id="submit_ticket" />'; inlineQty += '</div>'; if (isNullorEmpty(ticket_id)) { inlineQty += '<div class="col-xs-3 open_and_new_ticket_btn">'; inlineQty += '<input type="button" style="background-color: #FBEA51; border: 3px solid #379E8F; color: #379E8F; font-weight: 700" value="OPEN AND NEW TICKET" class="form-control btn btn-primary" id="open_and_new_ticket_btn" />'; inlineQty += '</div>'; } inlineQty += '<style>.escalate:hover {box-shadow: 0 12px 16px 0 rgba(0,0,0,0.24), 0 17px 50px 0 rgba(0,0,0,0.19)}</style>'; inlineQty += '<div class="col-xs-2 escalate">'; inlineQty += '<input type="button" style="background-color: #FBEA51; border: 3px solid #379E8F; color: #379E8F; font-weight: 700" value="ESCALATE" class="form-control btn btn-default" id="escalate" onclick="onEscalate()"/>'; inlineQty += '</div>'; } else { inlineQty += '<div class="col-xs-2 col-xs-offset-2 reopen_ticket">'; inlineQty += '<input type="button" style="background-color: #FBEA51; border: 3px solid #379E8F; color: #379E8F; font-weight: 700" value="REOPEN TICKET" class="form-control btn btn-primary" id="reopen_ticket" />'; inlineQty += '</div>'; } inlineQty += '<div class="col-xs-2 cancel">'; inlineQty += '<input type="button" style="background-color: #FBEA51; border: 3px solid #379E8F; color: #379E8F; font-weight: 700" value="CANCEL" class="form-control btn btn-default" id="cancel" onclick="onCancel()"/>'; inlineQty += '</div>'; inlineQty += '</div></div>'; return inlineQty; } function Ownerjava2jsArray(javaArray) { var jsArray = new Array; if (!isNullorEmpty(javaArray)) { javaArray.forEach(function (javaValue) { var jsValue = parseInt(javaValue); jsArray.push(jsValue); }) } return jsArray; } /** * The output of .getFieldValues is a java String Array. * We want to convert it to a javaScript Array in order to read its values. * @param {Ljava.lang.String} javaArray * @return {Array} jsArray */ function java2jsArray(javaArray) { var jsArray = new Array; if (!isNullorEmpty(javaArray)) { javaArray.forEach(function (javaValue) { var jsValue = javaValue.toString(); jsArray.push(jsValue); }) } return jsArray; } /** * Parse the objects in an array, and returns an object based on the value of one of its keys. * With ES6, this function would simply be `array.find(obj => obj[key] == value)` * @param {Array} array * @param {String} key * @param {*} value * @returns {Object} */ function findObjectByKey(array, key, value) { for (var i = 0; i < array.length; i++) { if (array[i][key] === value) { return array[i]; } } return null; } /** * Returns whether a ticket is closed or not based on its status value. * @param {Number} status_value * @returns {Boolean} is_ticket_closed */ function isTicketNotClosed(status_value) { var is_ticket_not_closed = ((status_value != 3) && (status_value != 8) && (status_value != 15)) ? true : false; return is_ticket_not_closed; } function escalateButton(status) { if (status < 11) { return 'Escalate to 1st Escalation'; } else if (status == 11) { return 'Escalate to 2nd Escalation'; } else if (status == 12) { return 'Escalate to 3rd Escalation'; } else if (status == 13) { return 'Escalate to Final Escalation'; } else { return 'Escalate'; } } /** * Whether the user is from the finance team, * or a Data Systems Co-ordinator, MailPlus Administration or Administrator user. * @param {Number} userRole * @returns {Boolean} */ function isFinanceRole(userRole) { // 1001, 1031 and 1023 are finance roles // 1032 is the Data Systems Co-ordinator role (to be deleted in prod) // 1006 is the Mail Plus Administration role. // 3 is the Administrator role. return ((userRole == 1001 || userRole == 1031 || userRole == 1023) || ((userRole == 1032) || (userRole == 1006) || (userRole == 3))); } function isNullorEmpty(strVal) { return (strVal == null || strVal == '' || strVal == 'null' || strVal == undefined || strVal == 'undefined' || strVal == '- None -'); } return { onRequest: onRequest }; });
true
/** * * @NApiVersion 2.0 * @NScriptType Suitelet * * Description: A ticketing system for the Customer Service. * @Last Modified by: Sruti Desai * */ define(['N/ui/serverWidget', 'N/email', 'N/runtime', 'N/search', 'N/record', 'N/http', 'N/log', 'N/redirect', 'N/format', 'N/file'], function (ui, email, runtime, search, record, http, log, redirect, format, file) { var baseURL = 'https://1048144.app.netsuite.com'; if (runtime.EnvType == "SANDBOX") { baseURL = 'https://1048144-sb3.app.netsuite.com'; } var zee = 0; var role = runtime.getCurrentUser().role; var userRole = runtime.getCurrentUser().role; var ctx = runtime.getCurrentScript(); var userId = runtime.getCurrentUser().id; if (role == 1000) { //Franchisee zee = runtime.getCurrentUser(); } function onRequest(context) { if (context.request.method === 'GET') { var ticket_id = null; var customer_id = null; var customer_number = null; var selector_id = null; var selector_number = ''; var selector_type = 'barcode_number'; var connote_number = ''; var date_created = ''; var creator_name = ''; var creator_id = null; var status_value = null; var escalated_to_it = ''; var status = ''; var customer_name = ''; var daytodayphone = ''; var daytodayemail = ''; var accountsphone = ''; var accountsemail = ''; var zee_id = null; var franchisee_name = ''; var zee_main_contact_name = ''; var zee_email = ''; var zee_main_contact_phone = ''; var zee_abn = ''; var date_stock_used = ''; var time_stock_used = ''; var final_delivery_text = ''; var selected_enquiry_status_id = null; var attachments_hyperlink = ''; var maap_bank_account_number = null; var maap_parent_bank_account_number = null; var selected_invoice_method_id = null; var accounts_cc_email = ''; var mpex_po_number = ''; var customer_po_number = ''; var terms = null; var customer_terms = ''; var account_manager = {}; var selected_invoice_cycle_id = null; var usage_report_id_1 = ''; var usage_report_id_2 = ''; var usage_report_id_3 = ''; var usage_report_id_4 = ''; var usage_report_array = []; var list_toll_issues = ''; var list_resolved_toll_issues = ''; var list_mp_ticket_issues = ''; var list_resolved_mp_ticket_issues = ''; var list_invoice_issues = ''; var list_resolved_invoice_issues = ''; var owner_list = ''; var comment = ''; var selected_label_id = null; var list_enquiry_mediums = ''; var total_enquiry_count = 0; var chat_enquiry_count = 0; var phone_enquiry_count = 0; var email_enquiry_count = 0; var phone_interaction_count = 0; var email_interaction_count = 0; var list_toll_emails = ''; var params_email = { recipient: '', subject: '', body: '', cc: '', bcc: '', records: {}, attachments_credit_memo_ids: [], attachments_usage_report_ids: [], attachments_invoice_ids: [] }; var customer_barcode_number = ''; var customer_issue = ''; var screenshot_file = ''; var browser = ''; var login_email_used = ''; var operating_system = ''; var phone_used = ''; var old_sender_name = ''; var old_sender_phone = ''; var customer_number_email_sent = 'F'; var customer_ticket_status = ''; var receiveremail = ''; var receiverphone = ''; var receivername = ''; var receiverstate = ''; var receiverzip = ''; var receiversuburb = ''; var receiveraddr1 = ''; var receiveraddr2 = ''; var prod_stock_invoice = ''; var barcodempdl = ''; var barcodesource = ''; var barcodeintegration = ''; var senderName = ''; var senderEmail = ''; var senderPhone = ''; var senderAddress = ''; var productName = '' // Load params var params = context.request.parameters.custparam_params; log.debug({ title: 'Params', details: params }) if (!isNullorEmpty(params)) { params = JSON.parse(params); log.debug({ title: 'Params not empty', details: params }); // Coming from the ticket_contact page or the edit_ticket page if (!isNullorEmpty(params.selector_number) && !isNullorEmpty(params.selector_type)) { selector_number = params.selector_number; selector_type = params.selector_type; //Coming from the ticket_contact page if (!isNullorEmpty(params.custid)) { customer_id = params.custid; } log.debug({ title: 'customer_id after ticket_contact_page : ', details: customer_id }); // Coming from the edit_ticket page if (!isNullorEmpty(params.ticket_id)) { ticket_id = parseInt(params.ticket_id); log.debug({ title: 'ticket id ISS', details: ticket_id }); // Load ticket data var ticketRecord = record.load({ type: 'customrecord_mp_ticket', id: ticket_id }); date_created = ticketRecord.getValue({ fieldId: 'created' }); creator_name = ticketRecord.getText({ fieldId: 'custrecord_creator' }); creator_id = ticketRecord.getValue({ fieldId: 'custrecord_creator' }); status_value = ticketRecord.getValue({ fieldId: 'custrecord_ticket_status' }); escalated_to_it = ticketRecord.getValue({ fieldId: 'custrecord_date_escalated_it' }); status = ticketRecord.getText({ fieldId: 'custrecord_ticket_status' }); customer_id = ticketRecord.getValue({ fieldId: 'custrecord_customer1' }); customer_name = ticketRecord.getText({ fieldId: 'custrecord_customer1' }); zee_id = ticketRecord.getValue({ fieldId: 'custrecord_zee' }); selected_enquiry_status_id = ticketRecord.getValue({ fieldId: 'custrecord_enquiry_status' }); attachments_hyperlink = ticketRecord.getValue({ fieldId: 'custrecord_mp_ticket_attachments' }); selected_label_id = ticketRecord.getValue({ fieldId: 'custrecord_ticket_label' }); list_enquiry_mediums = ticketRecord.getValue({ fieldId: 'custrecord_enquiry_medium' }); list_enquiry_mediums = java2jsArray(list_enquiry_mediums); total_enquiry_count = ticketRecord.getValue({ fieldId: 'custrecord_enquiry_count' }); chat_enquiry_count = ticketRecord.getValue({ fieldId: 'custrecord_chat_enquiry_count' }); phone_enquiry_count = ticketRecord.getValue({ fieldId: 'custrecord_phone_enquiry_count' }); phone_interaction_count = ticketRecord.getValue({ fieldId: 'custrecord_phone_interaction_count' }); email_interaction_count = ticketRecord.getValue({ fieldId: 'custrecord_email_interaction_count' }); email_enquiry_count = ticketRecord.getValue({ fieldId: 'custrecord_email_enquiry_count' }); customer_issue = ticketRecord.getValue({ fieldId: 'custrecord_customer_issue' }); screenshot_file = ticketRecord.getValue({ fieldId: 'custrecord_screenshot' }); browser = ticketRecord.getValue({ fieldId: 'custrecord_browser' }); login_email_used = ticketRecord.getValue({ fieldId: 'custrecord_login_email' }); operating_system = ticketRecord.getValue({ fieldId: 'custrecord_operating_system' }); phone_used = ticketRecord.getValue({ fieldId: 'custrecord_phone_used' }); customer_number = ticketRecord.getValue({ fieldId: 'custrecord_cust_number' }); old_sender_name = ticketRecord.getValue({ fieldId: 'custrecord_sender_name' }); old_sender_phone = ticketRecord.getValue({ fieldId: 'custrecord_sender_phone' }); customer_number_email_sent = ticketRecord.getValue({ fieldId: 'custrecord_customer_number_email_sent' }); customer_barcode_number = ticketRecord.getValue({ fieldId: 'custrecord_barcode_number' }); customer_ticket_status = ticketRecord.getText({ fieldId: 'custrecord_mp_ticket_customer_status' }); if (!isNullorEmpty(customer_barcode_number)) { var rec = record.load({ type: 'customrecord_customer_product_stock', id: customer_barcode_number, }); receiveremail = rec.getValue({ fieldId: 'custrecord_receiver_email' }); receiverphone = rec.getValue({ fieldId: 'custrecord_receiver_phone' }); receivername = rec.getValue({ fieldId: 'custrecord_receiver_name' }); receiverstate = rec.getValue({ fieldId: 'custrecord_receiver_state' }); receiverzip = rec.getValue({ fieldId: 'custrecord_receiver_postcode' }); receiversuburb = rec.getValue({ fieldId: 'custrecord_receiver_suburb' }); receiveraddr1 = rec.getValue({ fieldId: 'custrecord_receiver_addr1' }); receiveraddr2 = rec.getValue({ fieldId: 'custrecord_receiver_addr2' }); senderName = rec.getValue({ fieldId: 'custrecord_senders_name' }); senderEmail = rec.getValue({ fieldId: 'custrecord_sender_email' }); senderPhone = rec.getValue({ fieldId: 'custrecord_senders_phone' }); senderAddress = rec.getValue({ fieldId: 'custrecord_sender_address_1' }); productName = rec.getText({ fieldId: 'custrecord_cust_prod_stock_single_name' }); if (isNullorEmpty(productName)) { productName = rec.getText({ fieldId: 'custrecord_cust_stock_prod_name' }) } prod_stock_invoice = rec.getText({ fieldId: 'custrecord_prod_stock_invoice' }); barcodempdl = rec.getValue({ fieldId: 'custrecord_mpdl_number' }); barcodeintegration = rec.getValue({ fieldId: 'custrecord_integration' }); barcodesource = rec.getText({ fieldId: 'custrecord_barcode_source' }); connote_number = rec.getValue({ fieldId: 'custrecord_connote_number' }); } if (isNullorEmpty(customer_id) && !isNullorEmpty(customer_number)) { var customer_search = search.load({ type: 'customer', id: 'customsearch_customer_name_2' }); customer_search.filters.push(search.createFilter({ name: 'entityid', operator: 'haskeywords', values: customer_number, })); log.debug({ title: 'customer_search.run().getRange({ start: 0,end:1 })[0].id', details: customer_search.run().getRange({ start: 0, end: 1 })[0].id }); customer_id = customer_search.run().getRange({ start: 0, end: 1 })[0].id; } if (!isNullorEmpty(customer_id)) { //Load customer record and franchisee information var customerRecord = record.load({ type: 'customer', id: customer_id }); customer_number = customerRecord.getValue({ fieldId: 'entityid' }); daytodayphone = customerRecord.getValue({ fieldId: 'phone' }); daytodayemail = customerRecord.getValue({ fieldId: 'custentity_email_service' }); terms = customerRecord.getValue({ fieldId: 'terms' }); customer_terms = customerRecord.getValue({ fieldId: 'custentity_finance_terms' }); // Account manager var accountManagerSearch = search.load({ type: 'customer', id: 'customsearch3413' }); accountManagerSearch.filters.push(search.createFilter({ name: 'internalid', join: null, operator: search.Operator.ANYOF, values: customer_id, })) var accountManagerResultSet = accountManagerSearch.run(); var accountManagerResult = accountManagerResultSet.getRange({ start: 0, end: 1 }); accountManagerResult = accountManagerResult[0]; if (!isNullorEmpty(accountManagerResult)) { var account_manager_value = accountManagerResult.getValue({ name: "custrecord_sales_assigned", join: "CUSTRECORD_SALES_CUSTOMER", summary: null }); var account_manager_text = accountManagerResult.getText({ name: "custrecord_sales_assigned", join: "CUSTRECORD_SALES_CUSTOMER", summary: null }); if (!isNullorEmpty(account_manager_value)) { var account_manager_email = search.lookupFields({ type: 'employee', id: account_manager_value, columns: 'email' }); account_manager = { name: account_manager_text, email: account_manager_email }; } } // The Franchisee informations are imported from the customer record if possible. zee_id = customerRecord.getValue({ fieldId: 'partner' }); } if (!isNullorEmpty(zee_id)) { var zeeRecord = record.load({ type: 'partner', id: zee_id }); franchisee_name = zeeRecord.getValue({ fieldId: 'companyname' }); zee_main_contact_name = zeeRecord.getValue({ fieldId: 'custentity3' }); zee_email = zeeRecord.getValue({ fieldId: 'email' }); zee_main_contact_phone = zeeRecord.getValue({ fieldId: 'custentity2' }); zee_abn = zeeRecord.getValue({ fieldId: 'custentity_abn_franchiserecord' }); } else { franchisee_name = ticketRecord.getText({ fieldId: 'custrecord_zee' }); } switch (selector_type) { case 'barcode_number': selector_id = ticketRecord.getValue({ fieldId: 'custrecord_barcode_number' }); var stock_used = ''; if (!isNullorEmpty(selector_id)) { //Come in here only if selector_id is not null stock_used = search.lookupFields({ type: 'customrecord_customer_product_stock', id: selector_id, columns: ['custrecord_cust_date_stock_used', 'custrecord_cust_time_stock_used'] }); log.debug({ title: 'stock_used', details: stock_used }) log.debug({ title: 'finalDel', details: search.lookupFields({ type: 'customrecord_customer_product_stock', id: selector_id, columns: 'custrecord_cust_prod_stock_final_del' }) }); var finalDelCheck = search.lookupFields({ type: 'customrecord_customer_product_stock', id: selector_id, columns: 'custrecord_cust_prod_stock_final_del' }).custrecord_cust_prod_stock_final_del; if (!isNullorEmpty(finalDelCheck)) { final_delivery_text = search.lookupFields({ type: 'customrecord_customer_product_stock', id: selector_id, columns: 'custrecord_cust_prod_stock_final_del' })["custrecord_cust_prod_stock_final_del"][0]["text"]; } date_stock_used = stock_used.custrecord_cust_date_stock_used; time_stock_used = stock_used.custrecord_cust_time_stock_used; } list_toll_issues = ticketRecord.getValue({ fieldId: 'custrecord_toll_issues' }); list_toll_issues = java2jsArray(list_toll_issues); list_resolved_toll_issues = ticketRecord.getValue({ fieldId: 'custrecord_resolved_toll_issues' }); list_resolved_toll_issues = java2jsArray(list_resolved_toll_issues); list_toll_emails = ticketRecord.getValue({ fieldId: 'custrecord_toll_emails' }); list_toll_emails = java2jsArray(list_toll_emails); break; case 'invoice_number': selector_id = ticketRecord.getValue({ fieldId: 'custrecord_invoice_number' }); var invoiceRecord = record.load({ type: 'invoice', id: selector_id }); accountsphone = customerRecord.getValue({ fieldId: 'altphone' }); accountsemail = customerRecord.getValue({ fieldId: 'email' }); maap_bank_account_number = customerRecord.getValue({ fieldId: 'custentity_maap_bankacctno' }); maap_parent_bank_account_number = customerRecord.getValue({ fieldId: 'custentity_maap_bankacctno_parent' }); selected_invoice_method_id = customerRecord.getValue({ fieldId: 'custentity_invoice_method' }); accounts_cc_email = customerRecord.getValue({ fieldId: 'custentity_accounts_cc_email' }); mpex_po_number = customerRecord.getValue({ fieldId: 'custentity_mpex_po' }); customer_po_number = customerRecord.getValue({ fieldId: 'custentity11' }); selected_invoice_cycle_id = customerRecord.getValue({ fieldId: 'custentity_mpex_invoicing_cycle' }); usage_report_id_1 = invoiceRecord.getValue({ fieldId: 'custbody_mpex_usage_report' }); usage_report_id_2 = invoiceRecord.getValue({ fieldId: 'custbody_mpex_usage_report_2' }); usage_report_id_3 = invoiceRecord.getValue({ fieldId: 'custbody_mpex_usage_report_3' }); usage_report_id_4 = invoiceRecord.getValue({ fieldId: 'custbody_mpex_usage_report_4' }); var usage_report_id_array = [usage_report_id_1, usage_report_id_2, usage_report_id_3, usage_report_id_4]; usage_report_id_array.forEach(function (usage_report_id) { if (!isNullorEmpty(usage_report_id)) { var usage_report_file = file.load({ id: usage_report_id }); usage_report_name = usage_report_file.name; usage_report_link = usage_report_file.url; usage_report_array.push({ id: usage_report_id, name: usage_report_name, url: usage_report_link }); } }); list_invoice_issues = ticketRecord.getValue({ fieldId: 'custrecord_invoice_issues' }); list_invoice_issues = java2jsArray(list_invoice_issues); list_resolved_invoice_issues = ticketRecord.getValue({ fieldId: 'custrecord_resolved_invoice_issues' }); list_resolved_invoice_issues = java2jsArray(list_resolved_invoice_issues); break; } list_mp_ticket_issues = ticketRecord.getValue({ fieldId: 'custrecord_mp_ticket_issue' }); list_mp_ticket_issues = java2jsArray(list_mp_ticket_issues); list_resolved_mp_ticket_issues = ticketRecord.getValue({ fieldId: 'custrecord_resolved_mp_ticket_issue' }); list_resolved_mp_ticket_issues = java2jsArray(list_resolved_mp_ticket_issues); owner_list = ticketRecord.getValue({ fieldId: 'custrecord_owner' }); owner_list = Ownerjava2jsArray(owner_list); comment = ticketRecord.getValue({ fieldId: 'custrecord_comment' }); } } } var form = ui.createForm({ title: ' ', }); // Load jQuery var inlineHtml = '<script src="https://code.jquery.com/jquery-1.12.4.min.js" integrity="PI:KEY:949d1u22cbffbrarjh182eig55721odjEND_PI" crossorigin="anonymous"></script>'; // Load Tooltip inlineHtml += '<script src="https://unpkg.com/@popperjs/core@2"></script>'; // Load Bootstrap inlineHtml += '<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/3.4.1/css/bootstrap.min.css" integrity="PI:KEY:ax5kh6jaqkcd2tiexxs8v6xjo8yv8a6bEND_PI" crossorigin="anonymous">'; inlineHtml += '<script src="https://stackpath.bootstrapcdn.com/bootstrap/3.4.1/js/bootstrap.min.js" integrity="PI:KEY:9jnerlff23u8ed01np9g6ysbhsh0dvcsEND_PI" crossorigin="anonymous"></script>'; // Load DataTables inlineHtml += '<link rel="stylesheet" type="text/css" href="//cdn.datatables.net/1.10.21/css/jquery.dataTables.min.css">'; inlineHtml += '<script type="text/javascript" charset="utf8" src="//cdn.datatables.net/1.10.21/js/jquery.dataTables.min.js"></script>'; // Load Summernote css/js inlineHtml += '<link href="https://cdnjs.cloudflare.com/ajax/libs/summernote/0.8.9/summernote.css" rel="stylesheet">'; inlineHtml += '<script src="https://cdnjs.cloudflare.com/ajax/libs/summernote/0.8.9/summernote.js"></script>'; // Load bootstrap-select inlineHtml += '<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap-select@1.13.14/dist/css/bootstrap-select.min.css">'; inlineHtml += '<script src="https://cdn.jsdelivr.net/npm/bootstrap-select@1.13.14/dist/js/bootstrap-select.min.js"></script>'; // Load Netsuite stylesheet and script inlineHtml += '<link rel="stylesheet" href="https://1048144.app.netsuite.com/core/media/media.nl?id=2060796&c=1048144&h=9ee6accfd476c9cae718&_xt=.css"/>'; inlineHtml += '<script src="https://1048144.app.netsuite.com/core/media/media.nl?id=2060797&c=1048144&h=ef2cda20731d146b5e98&_xt=.js"></script>'; inlineHtml += '<link type="text/css" rel="stylesheet" href="https://1048144.app.netsuite.com/core/media/media.nl?id=2090583&c=1048144&h=a0ef6ac4e28f91203dfe&_xt=.css">'; inlineHtml += '<style>.mandatory{color:red;}</style>'; // Define alert window. inlineHtml += '<div class="container" style="margin-top:14px;" hidden><div id="danger-alert" class="alert alert-danger fade in"></div></div>'; // Define information window. inlineHtml += '<div class="container" hidden><p id="info" class="alert alert-info"></p></div>'; inlineHtml += tabsSection(customer_number, ticket_id, selector_number, selector_id, selector_type, status_value, customer_name, daytodayphone, daytodayemail, franchisee_name, zee_main_contact_name, zee_email, zee_main_contact_phone, zee_abn, date_stock_used, time_stock_used, final_delivery_text, selected_enquiry_status_id, attachments_hyperlink, owner_list, list_toll_issues, list_resolved_toll_issues, comment, date_created, creator_id, creator_name, status, customer_id, accountsphone, accountsemail, zee_id, list_enquiry_mediums, total_enquiry_count, chat_enquiry_count, phone_enquiry_count, email_enquiry_count, selected_label_id, maap_bank_account_number, maap_parent_bank_account_number, account_manager, list_toll_emails, customer_barcode_number, connote_number, receiveremail, receiverphone, receivername, receiverstate, receiverzip, receiversuburb, receiveraddr1, receiveraddr2, prod_stock_invoice, barcodempdl, barcodesource, list_mp_ticket_issues, list_resolved_mp_ticket_issues, list_invoice_issues, list_resolved_invoice_issues, selected_invoice_method_id, accounts_cc_email, mpex_po_number, customer_po_number, selected_invoice_cycle_id, terms, customer_terms, screenshot_file, browser, login_email_used, operating_system, phone_used, old_sender_name, old_sender_phone, phone_interaction_count, email_interaction_count, escalated_to_it, senderName, senderAddress, senderEmail, senderPhone, productName, barcodeintegration); // inlineHtml += customerNumberSection(customer_number, ticket_id); // inlineHtml += selectorSection(ticket_id, selector_number, selector_id, selector_type, status_value); // if (!isNullorEmpty(ticket_id)) { // inlineHtml += ticketSection(dateISOToNetsuite(date_created), creator_id, creator_name, status); // } // if (isNullorEmpty(ticket_id) || (!isNullorEmpty(ticket_id) && !isNullorEmpty(customer_id)) || !isNullorEmpty(customer_number)) { // inlineHtml += customerSection(customer_name); // inlineHtml += daytodayContactSection(daytodayphone, daytodayemail, status_value, selector_type); // inlineHtml += accountsContactSection(accountsphone, accountsemail, status_value, selector_type); // } // if(isNullorEmpty(ticket_id) || (!isNullorEmpty(ticket_id) && (selector_type == 'invoice_section'))) { // inlineHtml += maapBankAccountSection(maap_bank_account_number, maap_parent_bank_account_number, selector_type); // } // if (isNullorEmpty(ticket_id) || (!isNullorEmpty(ticket_id) && !isNullorEmpty(zee_id)) || !isNullorEmpty(customer_number)) { // inlineHtml += franchiseeMainContactSection(franchisee_name, zee_main_contact_name, zee_email, zee_main_contact_phone, zee_abn); // } // inlineHtml += mpexStockUsedSection(selector_type, date_stock_used, time_stock_used); // inlineHtml += finalDeliveryEnquirySection(status_value, selector_type, final_delivery_text, selected_enquiry_status_id); // inlineHtml += attachmentsSection(attachments_hyperlink, status_value); // if (isNullorEmpty(ticket_id) || (!isNullorEmpty(ticket_id) && (selector_type == 'invoice_number'))) { // inlineHtml += otherInvoiceFieldsSection(selected_invoice_method_id, accounts_cc_email, mpex_po_number, customer_po_number, selected_invoice_cycle_id, terms, customer_terms, status_value, selector_type); // inlineHtml += openInvoicesSection(ticket_id, selector_type); // if (!isNullorEmpty(ticket_id)) { // inlineHtml += creditMemoSection(selector_type); // inlineHtml += usageReportSection(selector_type); // } // } // inlineHtml += mpexContactSection(); // inlineHtml += enquiryMediumSection(list_enquiry_mediums, selected_enquiry_status_id ,selector_type); // inlineHtml += enquiryCountSection(total_enquiry_count, chat_enquiry_count, phone_enquiry_count, email_enquiry_count); // inlineHtml += labelSection(selected_label_id, selector_type, status_value); // inlineHtml += sendEmailSection(ticket_id, status_value, account_manager,list_toll_emails); // log.debug({ title: 'before prev email - cust id', details: customer_id }); // if(!isNullorEmpty(customer_id)){ // inlineHtml += previousEmailsSection(customer_id); // } // inlineHtml += issuesHeader(); // inlineHtml += customerIssuesSection(ticket_id, selector_type, selector_number, screenshot_file, browser, login_email_used, operating_system, phone_used, old_sender_name, old_sender_phone, status_value); // if(selector_type == "barcode_number" || selector_type == "invoice_number"){ // inlineHtml += reminderSection(status_value); // } // inlineHtml += ownerSection(ticket_id, owner_list, status_value); // inlineHtml += tollIssuesSection(list_toll_issues, list_resolved_toll_issues, status_value, selector_type); // inlineHtml += mpTicketIssuesSection(list_mp_ticket_issues, list_resolved_mp_ticket_issues, status_value, selector_type); // inlineHtml += invoiceIssuesSection(list_invoice_issues, list_resolved_invoice_issues, status_value, selector_type); // inlineHtml += usernoteSection(selector_type, status_value); // inlineHtml += commentSection(comment, selector_type, status_value); // inlineHtml += dataTablePreview(); //inlineHtml += closeReopenSubmitTicketButton(ticket_id, status_value); form.addField({ id: 'preview_table', type: ui.FieldType.INLINEHTML, label: 'preview_table' }).defaultValue = inlineHtml; form.addField({ id: 'custpage_open_new_ticket', type: ui.FieldType.TEXT, label: 'Open New Ticket' }).updateDisplayType({ displayType: ui.FieldDisplayType.HIDDEN }).defaultValue = 'F'; log.debug({ title: 'Selector_number', details: selector_number }); form.addField({ id: 'custpage_selector_number', type: ui.FieldType.TEXT, label: 'Selector Number' }).updateDisplayType({ displayType: ui.FieldDisplayType.HIDDEN }).defaultValue = selector_number; form.addField({ id: 'custpage_selector_type', type: ui.FieldType.TEXT, label: 'Selector Type' }).updateDisplayType({ displayType: ui.FieldDisplayType.HIDDEN }).defaultValue = selector_type; if (!isNullorEmpty(ticket_id)) { form.addField({ id: 'custpage_ticket_id', type: ui.FieldType.TEXT, label: 'Ticket ID' }).updateDisplayType({ displayType: ui.FieldDisplayType.HIDDEN }).defaultValue = ticket_id; } else { form.addField({ id: 'custpage_ticket_id', type: ui.FieldType.TEXT, label: 'Ticket ID' }).updateDisplayType({ displayType: ui.FieldDisplayType.HIDDEN }); } form.addField({ id: 'custpage_selector_id', type: ui.FieldType.TEXT, label: 'Selector ID' }).updateDisplayType({ displayType: ui.FieldDisplayType.HIDDEN }).defaultValue = selector_id; form.addField({ id: 'custpage_selector_issue', type: ui.FieldType.TEXT, label: 'Barcode issue' }).updateDisplayType({ displayType: ui.FieldDisplayType.HIDDEN }).defaultValue = 'F'; form.addField({ id: 'custpage_customer_id', type: ui.FieldType.TEXT, label: 'Customer ID' }).updateDisplayType({ displayType: ui.FieldDisplayType.HIDDEN }).defaultValue = customer_id; form.addField({ id: 'custpage_customer_number', type: ui.FieldType.TEXT, label: 'Customer Number' }).updateDisplayType({ displayType: ui.FieldDisplayType.HIDDEN }).defaultValue = customer_number; form.addField({ id: 'custpage_zee_id', type: ui.FieldType.TEXT, label: 'Franchisee ID' }).updateDisplayType({ displayType: ui.FieldDisplayType.HIDDEN }).defaultValue = zee_id; form.addField({ id: 'custpage_ticket_status_value', type: ui.FieldType.TEXT, label: 'Status Value' }).updateDisplayType({ displayType: ui.FieldDisplayType.HIDDEN }).defaultValue = status_value; form.addField({ id: 'custpage_created_ticket', type: ui.FieldType.TEXT, label: 'Created Ticket' }).updateDisplayType({ displayType: ui.FieldDisplayType.HIDDEN }).defaultValue = 'F'; form.addField({ id: 'custpage_usage_report_array', type: ui.FieldType.TEXT, label: 'Usage Reports' }).updateDisplayType({ displayType: ui.FieldDisplayType.HIDDEN }).defaultValue = JSON.stringify(usage_report_array); form.addField({ id: 'custpage_param_email', type: ui.FieldType.TEXT, label: 'Email parameters' }).updateDisplayType({ displayType: ui.FieldDisplayType.HIDDEN }).defaultValue = JSON.stringify(params_email); form.addField({ id: 'custpage_ss_image', type: ui.FieldType.TEXT, label: 'Screenshot Image' }).updateDisplayType({ displayType: ui.FieldDisplayType.HIDDEN }).defaultValue = screenshot_file; form.addField({ id: 'custpage_customer_number_email_sent', type: ui.FieldType.TEXT, label: 'Customer Email Sent' }).updateDisplayType({ displayType: ui.FieldDisplayType.HIDDEN }).defaultValue = customer_number_email_sent; if (!isNullorEmpty(ticket_id)) { if (isTicketNotClosed(status_value)) { form.addSubmitButton({ label: 'Update Ticket' }); } // else { // form.addSubmitButton({ label: 'Reopen Ticket' }); // } } else { form.addSubmitButton({ label: 'Save Ticket' }); // form.addButton({ id: 'custpage_openandnew', label: 'Open & New Ticket', functionName: 'openAndNew()' }); // } // if (isTicketNotClosed(status_value)) { // form.addButton({ id: 'custpage_escalate', label: 'Escalate', functionName: 'onEscalate()' }); } // form.addButton({ id: 'custpage_cancel', label: 'Cancel', functionName: 'onCancel()' }); form.clientScriptFileId = 4813453;//SB=4796340 PROD=4813453 context.response.writePage(form); } else { log.debug({ title: "In else POST part", details: '' }); var created_ticket = context.request.parameters.custpage_created_ticket; log.debug({ title: "created_ticket", details: created_ticket }); var is_ss_changed = context.request.parameters.custpage_is_ss_changed; log.debug({ title: "is_ss_changed", details: is_ss_changed }); if (created_ticket == 'T') { var ticket_id = context.request.parameters.custpage_ticket_id; var selector_number = context.request.parameters.custpage_selector_number; var selector_type = context.request.parameters.custpage_selector_type; var open_new_ticket = context.request.parameters.custpage_open_new_ticket; if (open_new_ticket == 'T') { // If the ticket was just created, and the user clicked on 'Open & New Ticket', // The user is redirected to a new "Open Ticket" page. redirect.toSuitelet({ scriptId: 'customscript_sl_open_ticket_2', deploymentId: 'customdeploy_sl_open_ticket_2', parameters: params2 }); } else { custparam_params = { ticket_id: parseInt(ticket_id), selector_number: selector_number, selector_type: selector_type, } custparam_params = JSON.stringify(custparam_params); log.debug({ title: "custparams", details: custparam_params }); var params2 = { custparam_params: custparam_params }; // If the ticket was just created, the user is redirected to the "Edit Ticket" page redirect.toSuitelet({ scriptId: 'customscript_sl_open_ticket_2', deploymentId: 'customdeploy_sl_open_ticket_2', parameters: params2 }); } } else { var params_email = context.request.parameters.custpage_param_email; params_email = JSON.parse(params_email); var to = params_email.recipient; var email_subject = params_email.subject; var email_body = decodeURIComponent(params_email.body); var cc = null; var bcc = null var emailAttach = null; var attachments_credit_memo_ids = null; var attachments_usage_report_ids = null; var attachments_invoice_ids = null; var customer_id = context.request.parameters.custpage_customer_id; var open_new_ticket = context.request.parameters.custpage_open_new_ticket; if (!isNullorEmpty(params_email.cc)) { cc = params_email.cc; } if (!isNullorEmpty(params_email.bcc)) { bcc = params_email.bcc; } if (!isNullorEmpty(params_email.records)) { emailAttach = params_email.records; } var attachement_files = []; if (!isNullorEmpty(params_email.attachments_credit_memo_ids)) { attachments_credit_memo_ids = params_email.attachments_credit_memo_ids; attachments_credit_memo_ids.forEach(function (record_id) { render.transaction({ entityId: record_id, printMode: render.PrintMode.PDF, formId: number, inCustLocale: boolean }); }); } if (!isNullorEmpty(params_email.attachments_usage_report_ids)) { attachments_usage_report_ids = params_email.attachments_usage_report_ids; attachments_usage_report_ids.forEach(function (record_id) { attachement_files.push(file.load({ id: record_id })); }); } if (!isNullorEmpty(params_email.attachments_invoice_ids)) { attachments_invoice_ids = params_email.attachments_invoice_ids; attachments_invoice_ids.forEach(function (invoice_id) { render.transaction({ entityId: invoice_id, printMode: render.PrintMode.PDF, }) }); } // If the parameter is non null, it means that the "SEND EMAIL" button was clicked. if (!isNullorEmpty(attachement_files)) { try { email.send({ author: 112209, body: email_body, recipients: to, subject: email_subject, attachments: attachement_files, bcc: bcc, cc: cc, relatedRecords: { entityId: customer_id }, }); // 112209 is from MailPlus Team } catch (error) { if (error instanceof error.SuiteScriptError) { return error.name; } } } log.debug({ title: 'open_new_ticket', details: open_new_ticket }); if (open_new_ticket == 'T') { log.debug({ title: 'open ticket page', details: 'open ticket page' }) // If the ticket was just updated, and the user clicked on 'Updated & New Ticket', // The user is redirected to a new "Open Ticket" page. redirect.toSuitelet({ scriptId: 'customscript_sl_open_ticket_2', deploymentId: 'customdeploy_sl_open_ticket_2', }); } else { // If the ticket was updated, the user is redirected to the "View MP Tickets" page redirect.toSuitelet({ scriptId: 'customscript_sl_edit_ticket_2', deploymentId: 'customdeploy_sl_edit_ticket_2', }); } } } } function instructionsBox(ticket_id) { //Important Instructions box var inlineHtml = '<br></br>' inlineHtml += '<div></div>'; inlineHtml += '<div class="form-group container test_section">'; //inlineHtml += '<button type="button" class="btn btn-sm btn-info instruction_button" data-toggle="collapse" data-target="#demo">Click for Instructions</button>'; //inlineHtml += '<div id="demo" style="background-color: #cfeefc !important;border: 1px solid #417ed9;padding: 20px 30px 30px 30px;width:96%;position:absolute" class="collapse"><b><u>IMPORTANT INSTRUCTIONS:</u></b>'; inlineHtml += '<div style=\"background-color: #e3e8e5 !important;border: 2px solid #379E8F;padding: 20px 30px 30px 30px; text-align: left\"><b><u>Mandatory Fields:</u></b>'; inlineHtml += '<ul>'; inlineHtml += '<li><b><u>Ticket Details</u></b>: Total Enquiry Count must be at least 1 i.e. Chat/Email/Phone must have at least 1 incremented and Receiver Details should be filled in if blank</li>'; inlineHtml += '<li><b><u>Issues</u></b>: Owner and Toll Emails must have at least one selected</li>'; inlineHtml += '<li>If you have any issues, please contact Ankith</li>'; inlineHtml += '</ul></div></div><br/>'; return inlineHtml; } function externalBarcodeSource(selector_type, barcodeintegration, barcodempdl, barcodesource, productName) { var disabled = 'disabled'; var inlineQty = ''; if (selector_type == 'barcode_number') { inlineQty += '<div class="form-group container barcode_section">'; inlineQty += '<div class="row">'; // Product Type field inlineQty += '<div class="col-xs-4 barcodempdl_div">'; inlineQty += '<div class="input-group">'; inlineQty += '<span class="input-group-addon" id="barcodempdl_text">Product Type</span>'; inlineQty += '<input id="productName" value="' + productName + '" class="form-control productName" ' + disabled + ' />'; inlineQty += '</div></div>'; inlineQty += '</div></div>'; inlineQty += '<div class="form-group container barcode_section">'; inlineQty += '<div class="row">'; // MPLD field inlineQty += '<div class="col-xs-4 barcodempdl_div">'; inlineQty += '<div class="input-group">'; inlineQty += '<span class="input-group-addon" id="barcodempdl_text">INTEGRATION</span>'; inlineQty += '<input id="barcodempdl" value="' + barcodeintegration + '" class="form-control barcodempdl" ' + disabled + ' />'; inlineQty += '</div></div>'; // MPLD field inlineQty += '<div class="col-xs-4 barcodempdl_div">'; inlineQty += '<div class="input-group">'; inlineQty += '<span class="input-group-addon" id="barcodempdl_text">EXTERNAL BARCODE</span>'; inlineQty += '<input id="barcodempdl" value="' + barcodempdl + '" class="form-control barcodempdl" ' + disabled + ' />'; inlineQty += '</div></div>'; // barcode source field inlineQty += '<div class="col-xs-4 barcodesource_div">'; inlineQty += '<div class="input-group">'; inlineQty += '<span class="input-group-addon" id="barcodesource_text">BARCODE SOURCE</span>'; inlineQty += '<input id="barcodesource" value="' + barcodesource + '" class="form-control barcodesource" ' + disabled + ' />'; inlineQty += '</div></div></div></div>'; } return inlineQty; } function tabsSection(customer_number, ticket_id, selector_number, selector_id, selector_type, status_value, customer_name, daytodayphone, daytodayemail, franchisee_name, zee_main_contact_name, zee_email, zee_main_contact_phone, zee_abn, date_stock_used, time_stock_used, final_delivery_text, selected_enquiry_status_id, attachments_hyperlink, owner_list, list_toll_issues, list_resolved_toll_issues, comment, date_created, creator_id, creator_name, status, customer_id, accountsphone, accountsemail, zee_id, list_enquiry_mediums, total_enquiry_count, chat_enquiry_count, phone_enquiry_count, email_enquiry_count, selected_label_id, maap_bank_account_number, maap_parent_bank_account_number, account_manager, list_toll_emails, customer_barcode_number, connote_number, receiveremail, receiverphone, receivername, receiverstate, receiverzip, receiversuburb, receiveraddr1, receiveraddr2, prod_stock_invoice, barcodempdl, barcodesource, list_mp_ticket_issues, list_resolved_mp_ticket_issues, list_invoice_issues, list_resolved_invoice_issues, selected_invoice_method_id, accounts_cc_email, mpex_po_number, customer_po_number, selected_invoice_cycle_id, terms, customer_terms, screenshot_file, browser, login_email_used, operating_system, phone_used, old_sender_name, old_sender_phone, phone_interaction_count, email_interaction_count, escalated_to_it, senderName, senderAddress, senderEmail, senderPhone, productName, barcodeintegration) { var inlineQty = '<div style="margin-top: -10px"><br/>'; // BUTTONS if (!isNullorEmpty(ticket_id)) { if (isTicketNotClosed(status_value) && selector_type != "customer_issue") { inlineQty += '<button style="float: left; margin-left: 10px; margin-right: 5px; background-color: #FBEA51; color: #103D39; font-weight: 700; border-color: transparent; border-width: 2px; border-radius: 15px; height: 30px" type="button" id="updateticketbutton" onclick="">Update & New Ticket</button>'; inlineQty += '<button style="float: left; margin-left: 5x; margin-right: 5px; background-color: #FBEA51; color: #103D39; font-weight: 700; border-color: transparent; border-width: 2px; border-radius: 15px; height: 30px" type="button" id="updatecloseticketbutton" onclick="">Update & Close Ticket</button>'; } else if (!isTicketNotClosed(status_value)) { inlineQty += '<button style="float: left; margin-left: 10px; margin-right: 5px; background-color: #FBEA51; color: #103D39; font-weight: 700; border-color: transparent; border-width: 2px; border-radius: 15px; height: 30px" type="button" id="reopenticketbutton" onclick="">Reopen Ticket</button>'; } } else { //inlineQty += '<button style="float: left; margin-left: 10px; margin-right: 5px; background-color: #FBEA51; color: #103D39; font-weight: 700; border-color: transparent; border-width: 2px; border-radius: 15px; height: 30px" type="button" id="openticketbutton" onclick="">Save Ticket</button>'; inlineQty += '<button style="float: left; margin-left: 10px; margin-right: 5px; background-color: #FBEA51; color: #103D39; font-weight: 700; border-color: transparent; border-width: 2px; border-radius: 15px; height: 30px" type="button" id="opennewticketbutton" onclick="">Save & New Ticket</button>'; } if (isTicketNotClosed(status_value)) { if (!isNullorEmpty(ticket_id) && selector_type != "customer_issue") { inlineQty += '<button style="float: left; margin-left: 5px; margin-right: 5px; background-color: #f4524d; color: #fff; font-weight: 700; border-color: transparent; border-width: 2px; border-radius: 15px; height: 30px" type="button" id="closeticketbutton" onclick="">Close Ticket</button>'; inlineQty += '<button style="float: left; margin-left: 5px; margin-right: 5px; background-color: #f4524d; color: #fff; font-weight: 700; border-color: transparent; border-width: 2px; border-radius: 15px; height: 30px" type="button" id="closenewticketbutton" onclick="">Close & New Ticket</button>'; inlineQty += '<button style="float: left; margin-left: 5px; margin-right: 5px; background-color: #f4524d; color: #fff; font-weight: 700; border-color: transparent; border-width: 2px; border-radius: 15px; height: 30px" type="button" id="closelostbutton" onclick="">Close Ticket - Lost Item</button>'; if (userId == 409635 || userId == 696992 || userId == 766498) { inlineQty += '<button style="float: left; margin-left: 5px; margin-right: 5px; background-color: #FBEA51; color: #103D39; font-weight: 700; border-color: transparent; border-width: 2px; border-radius: 15px; height: 30px" type="button" id="closeunallocatedbutton" onclick="">Close Unallocated Ticket</button>'; } } else if (!isNullorEmpty(ticket_id) && !isNullorEmpty(escalated_to_it)) { inlineQty += '<button style="float: left; margin-left: 5px; margin-right: 5px; background-color: #f4524d; color: #fff; font-weight: 700; border-color: transparent; border-width: 2px; border-radius: 15px; height: 30px" type="button" id="closeresolvedbutton" onclick="">Close - Resolved Ticket</button>'; inlineQty += '<button style="float: left; margin-left: 5px; margin-right: 5px; background-color: #f4524d; color: #fff; font-weight: 700; border-color: transparent; border-width: 2px; border-radius: 15px; height: 30px" type="button" id="closeunresolvedbutton" onclick="">Close - Unresolved Ticket</button>'; } else { inlineQty += '<button style="float: left; margin-left: 5px; margin-right: 5px; background-color: #f4524d; color: #fff; font-weight: 700; border-color: transparent; border-width: 2px; border-radius: 15px; height: 30px" type="button" id="closeticketbutton" onclick="">Close Ticket</button>'; } } // ESCALATE AND CANCEL BUTTONS log.debug({ title: 'debugging', }); log.debug({ title: "selector_type", details: selector_type }); log.debug({ title: "isTicketNotClosed(status_value)", details: isTicketNotClosed(status_value) }); log.debug({ title: "!isNullorEmpty(ticket_id)", details: !isNullorEmpty(ticket_id) }); log.debug({ title: "userId", details: userId }); if (selector_type == "customer_issue" && isTicketNotClosed(status_value) && !isNullorEmpty(ticket_id) && isNullorEmpty(escalated_to_it)) { inlineQty += '<button style="float: left; margin-left: 5px; margin-right: 5px; background-color: #fc9003; color: #fff; font-weight: 700; border-color: transparent; border-width: 2px; border-radius: 15px; height: 30px" type="button" id="escalaterianne" onclick="">Escalate To IT</button>'; } else if (selector_type == "customer_issue" && isTicketNotClosed(status_value) && !isNullorEmpty(ticket_id) && !isNullorEmpty(escalated_to_it) && status_value != 10 && status_value != 17) { inlineQty += '<button style="float: left; margin-left: 5px; margin-right: 5px; background-color: #fc9003; color: #fff; font-weight: 700; border-color: transparent; border-width: 2px; border-radius: 15px; height: 30px" type="button" id="escalateankith" onclick="">Escalate To Ankith</button>'; } else if (selector_type == "customer_issue" && isTicketNotClosed(status_value) && !isNullorEmpty(ticket_id) && status_value == 10) { inlineQty += '<button style="float: left; margin-left: 5px; margin-right: 5px; background-color: #fc9003; color: #fff; font-weight: 700; border-color: transparent; border-width: 2px; border-radius: 15px; height: 30px" type="button" id="escalateunderdev" onclick="">Set Status to Under Development</button>'; } else if (selector_type == "customer_issue" && isTicketNotClosed(status_value) && !isNullorEmpty(ticket_id) && status_value == 17) { inlineQty += '<button style="float: left; margin-left: 5px; margin-right: 5px; background-color: #fc9003; color: #fff; font-weight: 700; border-color: transparent; border-width: 2px; border-radius: 15px; height: 30px" type="button" id="escalateremoveunderdev" onclick="">Remove Under Development Status</button>'; } else if (isTicketNotClosed(status_value) && !isNullorEmpty(ticket_id) && selector_type != "customer_issue") { inlineQty += '<button style="float: left; margin-left: 5px; margin-right: 5px; background-color: #379E8F; color: #fff; font-weight: 700; border-color: transparent; border-width: 2px; border-radius: 15px; height: 30px" type="button" id="escalatebutton" onclick="">' + escalateButton(status_value) + '</button>'; } if (!isNullorEmpty(ticket_id) && !isTicketNotClosed(status_value)) { inlineQty += '<button style="float: left; margin-left: 10px; margin-right: 5px; background-color: #FBEA51; color: #103D39; font-weight: 700; border-color: transparent; border-width: 2px; border-radius: 15px; height: 30px" type="button" id="cancelbutton" onclick="">Cancel</button>'; } else { inlineQty += '<button style="float: left; margin-left: 5px; margin-right: 5px; background-color: #FBEA51; color: #103D39; font-weight: 700; border-color: transparent; border-width: 2px; border-radius: 15px; height: 30px" type="button" id="cancelbutton" onclick="">Cancel</button>'; } // Title if (!isNullorEmpty(ticket_id)) { inlineQty += '<h1 style="display: inline-block; font-size: 25px; margin-top: 20px; font-weight: 700; color: #103D39; text-align: center; width: 100%">Edit Ticket - MPSD' + ticket_id + '</h1>' } else { inlineQty += '<h1 style="display: inline-block; font-size: 25px; font-weight: 700; color: #103D39; text-align: center; width: 100%">Open New Ticket</h1>' } inlineQty += instructionsBox(); // Tabs headers inlineQty += '<style>.nav > li.active > a, .nav > li.active > a:focus, .nav > li.active > a:hover { background-color: #379E8F; color: #fff }'; inlineQty += '.nav > li > a, .nav > li > a:focus, .nav > li > a:hover { margin-left: 5px; margin-right: 5px; border: 2px solid #379E8F; color: #379E8F; }'; inlineQty += '</style>'; // Ticket details header inlineQty += '<div class="form-group container tickets_details_header_section" style="margin-top: 10px">'; inlineQty += '<div class="row">'; inlineQty += '<div class="col-xs-12" >'; inlineQty += '<span">'; inlineQty += '<ul class="nav nav-pills nav-justified" style="margin:0%; ">'; inlineQty += '<li role="presentation" class="active"><a data-toggle="tab" href="#ticketdetails"><b>TICKET DETAILS</b></a></li>'; inlineQty += '<li role="presentation" class=""><a data-toggle="tab" href="#issues"><b>ISSUES</b></a></li>'; if (!isNullorEmpty(ticket_id)) { inlineQty += '<li role="presentation" class=""><a data-toggle="tab" href="#sendemail"><b>SEND EMAIL</b></a></li>'; } else { inlineQty += '<li role="presentation" class=""><a data-toggle="tab" href="#contactdetails"><b>CONTACT DETAILS</b></a></li>'; } if (!isNullorEmpty(ticket_id)) { inlineQty += '<li role="presentation" class=""><a data-toggle="tab" href="#prevtickets"><b>PREVIOUS TICKETS</b></a></li>'; inlineQty += '<li role="presentation" class=""><a data-toggle="tab" href="#prevemails"><b>PREVIOUS EMAILS</b></a></li>'; } //style="background-color: #379E8F" inlineQty += '</ul>'; inlineQty += '</span>'; inlineQty += '</div></div></div>'; // Tabs content inlineQty += '<div class="tab-content">'; // TICKET DETAILS TAB inlineQty += '<div role="tabpanel" class="tab-pane active" id="ticketdetails">'; inlineQty += customerNumberSection(customer_number, ticket_id, selector_type, escalated_to_it, creator_id); inlineQty += selectorSection(ticket_id, selector_number, selector_id, selector_type, status_value); if (!isNullorEmpty(ticket_id)) { inlineQty += ticketSection(dateISOToNetsuite(date_created), creator_id, creator_name, status, connote_number); inlineQty += externalBarcodeSource(selector_type, barcodeintegration, barcodempdl, barcodesource, productName) } if (isNullorEmpty(ticket_id) || (!isNullorEmpty(ticket_id) && !isNullorEmpty(customer_id)) || !isNullorEmpty(customer_number)) { inlineQty += customerSection(customer_name); inlineQty += daytodayContactSection(daytodayphone, daytodayemail, status_value, selector_type); inlineQty += accountsContactSection(accountsphone, accountsemail, status_value, selector_type); } else if (isNullorEmpty(customer_number) && creator_id == 112209 && !isNullorEmpty(escalated_to_it) && selector_type == "customer_issue" && !isNullorEmpty(ticket_id)) { inlineQty += customerSection(customer_name); inlineQty += daytodayContactSection(daytodayphone, daytodayemail, status_value, selector_type); inlineQty += accountsContactSection(accountsphone, accountsemail, status_value, selector_type); } if (isNullorEmpty(ticket_id) || (!isNullorEmpty(ticket_id) && (selector_type == 'invoice_section'))) { inlineQty += maapBankAccountSection(maap_bank_account_number, maap_parent_bank_account_number, selector_type); } if (isNullorEmpty(ticket_id) || (!isNullorEmpty(ticket_id) && !isNullorEmpty(zee_id)) || !isNullorEmpty(customer_number)) { inlineQty += franchiseeMainContactSection(franchisee_name, zee_main_contact_name, zee_email, zee_main_contact_phone, zee_abn); } inlineQty += mpexStockUsedSection(selector_type, date_stock_used, time_stock_used); inlineQty += finalDeliveryEnquirySection(status_value, selector_type, final_delivery_text, selected_enquiry_status_id, prod_stock_invoice); inlineQty += attachmentsSection(attachments_hyperlink, status_value); if (isNullorEmpty(ticket_id) || (!isNullorEmpty(ticket_id) && (selector_type == 'invoice_number'))) { inlineQty += otherInvoiceFieldsSection(selected_invoice_method_id, accounts_cc_email, mpex_po_number, customer_po_number, selected_invoice_cycle_id, terms, customer_terms, status_value, selector_type); // inlineQty += enquiryMediumSection(list_enquiry_mediums, selected_enquiry_status_id, selector_type); // inlineQty += enquiryCountSection( total_enquiry_count, chat_enquiry_count, phone_enquiry_count, email_enquiry_count, selector_type); inlineQty += openInvoicesSection(ticket_id, selector_type); if (!isNullorEmpty(ticket_id)) { inlineQty += creditMemoSection(selector_type); inlineQty += usageReportSection(selector_type); } } inlineQty += enquiryMediumSection(list_enquiry_mediums, selected_enquiry_status_id, selector_type); inlineQty += enquiryCountSection(total_enquiry_count, chat_enquiry_count, phone_enquiry_count, email_enquiry_count, selector_type, phone_interaction_count, email_interaction_count); if (!isNullorEmpty(ticket_id)) { inlineQty += senderDetails(selector_type, senderName, senderEmail, senderPhone, senderAddress); inlineQty += receiverEmailPhone(selector_type, receiveremail, receiverphone, receivername, receiverstate, receiverzip, receiversuburb, receiveraddr1, receiveraddr2); } //TICKET LABEL DROPDOWN //inlineQty += labelSection(selected_label_id, selector_type, status_value); inlineQty += '</div>'; // ISSUES TAB inlineQty += '<div role="tabpanel" class="tab-pane" id="issues">'; inlineQty += issuesHeader(); inlineQty += customerIssuesSection(ticket_id, selector_type, selector_number, screenshot_file, browser, login_email_used, operating_system, phone_used, old_sender_name, old_sender_phone, status_value); if (selector_type == "barcode_number" || selector_type == "invoice_number") { inlineQty += reminderSection(status_value); } inlineQty += ownerSection(ticket_id, owner_list, status_value); inlineQty += tollIssuesSection(list_toll_issues, list_resolved_toll_issues, status_value, selector_type); inlineQty += mpTicketIssuesSection(list_mp_ticket_issues, list_resolved_mp_ticket_issues, status_value, selector_type); inlineQty += invoiceIssuesSection(list_invoice_issues, list_resolved_invoice_issues, status_value, selector_type); inlineQty += usernoteSection(selector_type, status_value); inlineQty += commentSection(comment, selector_type, status_value); inlineQty += '</div>'; // CONTACT / EMAILS if (!isNullorEmpty(ticket_id)) { inlineQty += '<div role="tabpanel" class="tab-pane" id="sendemail">'; inlineQty += mpexContactSection(); inlineQty += sendEmailSection(ticket_id, status_value, account_manager, list_toll_emails); //inlineQty += closeReopenSubmitTicketButton(ticket_id, status_value); inlineQty += '</div>'; } else { inlineQty += '<div role="tabpanel" class="tab-pane" id="contactdetails">'; inlineQty += mpexContactSection(); //inlineQty += closeReopenSubmitTicketButton(ticket_id, status_value); inlineQty += '</div>'; } // PREV TICKETS + EMAILS TAB if (!isNullorEmpty(ticket_id)) { // PREV TICKETS TAB inlineQty += '<div role="tabpanel" class="tab-pane" id="prevtickets">'; inlineQty += dataTablePreview(); //inlineQty += closeReopenSubmitTicketButton(ticket_id, status_value); inlineQty += '</div>'; inlineQty += '<div role="tabpanel" class="tab-pane" id="prevemails">'; log.debug({ title: 'before prev email - cust id', details: customer_id }); if (!isNullorEmpty(customer_id)) { inlineQty += previousEmailsSection(customer_id); } //inlineQty += closeReopenSubmitTicketButton(ticket_id, status_value); inlineQty += '</div>'; } inlineQty += '</div></div>'; return inlineQty; } /** * The "Customer number" input field. If there is a Ticket ID, then we are on the Edit Ticket page and * this field is pre-filled. * @param {*} customer_number */ function customerNumberSection(customer_number, ticket_id, selector_type, escalated_to_it, creator_id) { if (isNullorEmpty(customer_number)) { customer_number = ''; } // var disable = isNullorEmpty(ticket_id) ? '': 'disabled'; // Ticket details header var inlineQty = '<div class="form-group container tickets_details_header_section">'; inlineQty += '<div class="row">'; inlineQty += '<div class="col-xs-12 heading2" >'; inlineQty += '<h4><span style="background-color: #379E8F" class="label label-default col-xs-12">TICKET DETAILS</span></h4>'; inlineQty += '</div></div></div>'; // Customer number section inlineQty += '<div class="form-group container customer_number_section">'; inlineQty += '<div class="row">'; //Customer number field inlineQty += '<div class="col-xs-12 customer_number">'; inlineQty += '<div class="input-group">'; inlineQty += '<span class="input-group-addon" id="customer_number_text">CUSTOMER NUMBER</span>'; if (customer_number == '' && isNullorEmpty(ticket_id)) { inlineQty += '<input id="customer_number_value" value=" ' + customer_number + ' " class="form-control customer_number">'; } else if (customer_number == '' && creator_id == 112209 && !isNullorEmpty(escalated_to_it) && selector_type == "customer_issue" && !isNullorEmpty(ticket_id)) { inlineQty += '<input id="customer_number_value" value=" ' + customer_number + ' " class="form-control customer_number">'; } else { inlineQty += '<input id="customer_number_value" value=" ' + customer_number + ' " class="form-control customer_number" disabled>'; } inlineQty += '</div></div></div></div>'; //Datatable for all tickets asscoiated to current customer number inlineQty += '<div class="row">'; inlineQty += '<div class="form-group container customer_number_tickets">'; inlineQty += '<style> table {font-size: 12px;text-align: center;border: none;} {font-size: 14px;} table th{text-align: center;} .dataTables_wrapper{width:78%; margin-bottom:40px; margin-left: auto; margin-right: auto; margin-top: auto;} </style>'; inlineQty += '<table cellpadding="15" id="customer_number_tickets_preview" class="table table-responsive table-striped customer tablesorter" cellspacing="0" style="width: 100%;">'; inlineQty += '<thead style="color: white;background-color: #379E8F;">'; inlineQty += '<tr class="text-center">'; inlineQty += '</tr>'; inlineQty += '</thead></table>'; inlineQty += '</div></div>'; return inlineQty; } /** * The "Barcode number" OR "Invoice Number" input field. * If there is a TICKET ID, we are in the "Edit Ticket", so we display the Ticket ID field and the selector field is disabled. * @param {Number} ticket_id * @param {String} selector_number * @param {Number} selector_id * @param {String} selector_type * @param {Number} status_value * @return {String} inlineQty */ function selectorSection(ticket_id, selector_number, selector_id, selector_type, status_value) { if (isNullorEmpty(selector_number)) { selector_number = ''; } var inlineQty = '<div class="form-group container selector_section">'; inlineQty += '<div class="row">'; if (!isNullorEmpty(ticket_id)) { // Ticket ID field inlineQty += '<div class="col-xs-6 ticket_id">'; inlineQty += '<div class="input-group">'; inlineQty += '<span class="input-group-addon" id="ticket_id_text">TICKET ID</span>'; inlineQty += '<input id="ticket_id" value="MPSD' + ticket_id + '" class="form-control ticket_id" disabled />'; inlineQty += '</div></div>'; // Selector Number field inlineQty += '<div class="col-xs-6 selector_number">'; inlineQty += '<div class="input-group">'; switch (selector_type) { case 'barcode_number': inlineQty += '<span class="input-group-addon" id="selector_text">BARCODE NUMBER</span>'; break; case 'invoice_number': inlineQty += '<span class="input-group-addon" id="selector_text">INVOICE NUMBER</span>'; break; } inlineQty += '<input id="selector_value" value="' + selector_number + '" class="form-control selector_value" disabled>'; if (selector_type == 'invoice_number') { // Open Invoice record inlineQty += '<div class="input-group-btn">'; inlineQty += '<button id="open_inv" type="button" class="btn btn-default link_inv" data-inv-id="' + selector_id + '" data-toggle="tooltip" data-placement="top" title="Open Invoice">'; inlineQty += '<span class="glyphicon glyphicon-link"></span>'; inlineQty += '</button>'; inlineQty += '</div>'; // Attach Invoice to email if (isTicketNotClosed(status_value)) { inlineQty += '<div class="input-group-btn"><button style="background-color: #379E8F" id="add_inv" type="button" class="btn btn-success add_inv" data-inv-id="' + selector_id + '" data-toggle="tooltip" data-placement="right" title="Attach to email">'; inlineQty += '<span class="glyphicon glyphicon-plus"></span>'; inlineQty += '</button></div>'; } } inlineQty += '</div></div></div></div>'; } else { inlineQty += '<div class="col-xs-12 selector_number">'; inlineQty += '<div class="input-group">'; //Input group addon text switch (selector_type) { case 'barcode_number': inlineQty += '<span class="input-group-addon" id="selector_text">BARCODE NUMBER</span>'; break; case 'invoice_number': inlineQty += '<span class="input-group-addon" id="selector_text">INVOICE NUMBER</span>'; break; case 'customer_issue': inlineQty += '<span class="input-group-addon" id="selector_text">CUSTOMER ISSUE</span>'; break; } inlineQty += '<div class="input-group-btn">'; inlineQty += '<button tabindex="-1" data-toggle="dropdown" class="btn btn-default dropdown-toggle" type="button">'; inlineQty += '<span class="caret"></span>'; inlineQty += '<span class="sr-only">Toggle Dropdown</span>'; inlineQty += '</button>'; inlineQty += '<ul class="dropdown-menu hide" style="list-style:none;margin: 2px 0 0;">'; inlineQty += '<li><a href="#">BARCODE NUMBER</a></li>'; inlineQty += '<li><a href="#">INVOICE NUMBER</a></li>'; //inlineQty += '<li><a href="#">CUSTOMER APP</a></li>'; inlineQty += '<li><a href="#">CUSTOMER PORTAL</a></li>'; // inlineQty += '<li><a href="#">UPDATE LABEL</a></li>'; inlineQty += '</ul>'; inlineQty += '</div>'; //Input text switch (selector_type) { case 'barcode_number': inlineQty += '<input id="selector_value" class="form-control selector_value" placeholder="MPEN123456">'; break; case 'invoice_number': inlineQty += '<input id="selector_value" class="form-control selector_value" placeholder="INV123456">'; break; case 'customer_app': inlineQty += '<input id="selector_value" class="form-control selector_value" placeholder="Customer App" disabled value="Customer App">'; break; case 'customer_portal': inlineQty += '<input id="selector_value" class="form-control selector_value" placeholder="Customer Portal" disabled value="Customer Portal">'; break; case 'update_label': inlineQty += '<input id="selector_value" class="form-control selector_value" placeholder="Update Label" disabled value="Update Label">'; break; } inlineQty += '</div></div></div></div>'; } return inlineQty; } /** * The informations regarding the ticket being edited. * @param {String} date_created * @param {Number} creator_id * @param {String} creator_name * @param {String} status * @return {String} inlineQty */ function ticketSection(date_created, creator_id, creator_name, status, connote_number) { if (isNullorEmpty(date_created)) { date_created = ''; } if (isNullorEmpty(creator_name)) { creator_name = ''; } if (isNullorEmpty(status)) { status = ''; } var inlineQty = '<div class="form-group container created_status_section">'; inlineQty += '<div class="row">'; // Date created field inlineQty += '<div class="col-xs-6 date_created">'; inlineQty += '<div class="input-group">'; inlineQty += '<span class="input-group-addon" id="date_created_text">DATE CREATED</span>'; inlineQty += '<input id="date_created" value="' + date_created + '" class="form-control date_created" disabled />'; inlineQty += '</div></div>'; // Creator field inlineQty += '<div class="col-xs-6 creator">'; inlineQty += '<div class="input-group">'; inlineQty += '<span class="input-group-addon" id="creator_text">CREATOR</span>'; inlineQty += '<input id="creator" value="' + creator_name + '" data-creator-id="' + creator_id + '" class="form-control creator" disabled />'; inlineQty += '</div></div></div></div>'; // Status Section inlineQty += '<div class="form-group container status_section">'; inlineQty += '<div class="row">'; // Status field inlineQty += '<div class="col-xs-6 status">'; inlineQty += '<div class="input-group">'; inlineQty += '<span class="input-group-addon" id="status_text">STATUS</span>'; inlineQty += '<input id="status" value="' + status + '" class="form-control status" disabled />'; inlineQty += '</div></div>'; // Customer Status field inlineQty += '<div class="col-xs-6 status">'; inlineQty += '<div class="input-group">'; inlineQty += '<span class="input-group-addon" id="status_text">CONNOTE NUMBER</span>'; inlineQty += '<input id="status" value="' + connote_number + '" class="form-control status" disabled />'; inlineQty += '</div></div></div></div>'; return inlineQty; } /** * The Customer name field. * The customer name field should be automatically filled based on the Selector number value. * @param {String} customer_name * @return {String} inlineQty */ function customerSection(customer_name) { if (isNullorEmpty(customer_name)) { customer_name = ''; } // Customer Section var inlineQty = '<div class="form-group container customer_section">'; inlineQty += '<div class="row">'; // Customer name field inlineQty += '<div class="col-xs-12 customer_name">'; inlineQty += '<div class="input-group">'; inlineQty += '<span class="input-group-addon" id="customer_name_text">CUSTOMER NAME</span>'; inlineQty += '<input id="customer_name" value="' + customer_name + '" class="form-control customer_name" disabled>'; inlineQty += '</div></div></div></div>'; return inlineQty; } /** * The day to day phone and email fields of the customer. * These fields should be automatically filled based on the Selector number value. * @param {String} daytodayphone * @param {String} daytodayemail * @param {Number} status_value * @param {String} selector_type * @return {String} inlineQty */ function daytodayContactSection(daytodayphone, daytodayemail, status_value, selector_type) { if (isNullorEmpty(daytodayphone)) { daytodayphone = ''; } if (isNullorEmpty(daytodayemail)) { daytodayemail = ''; } var disabled = 'disabled'; if ((isFinanceRole(userRole)) && isTicketNotClosed(status_value) && selector_type == 'invoice_number') { disabled = ''; } var inlineQty = '<div class="form-group container daytodaycontact_section">'; inlineQty += '<div class="row">'; // Day to day email field inlineQty += '<div class="col-xs-6 daytodayemail_div">'; inlineQty += '<div class="input-group">'; inlineQty += '<span class="input-group-addon" id="daytodayemail_text">DAY-TO-DAY EMAIL</span>'; inlineQty += '<input id="daytodayemail" type="email" value="' + daytodayemail + '" class="form-control daytodayemail" ' + disabled + ' />'; inlineQty += '<div class="input-group-btn">'; inlineQty += '<button type="button" style="background-color: #379E8F" class="btn btn-success add_as_recipient" data-email="' + daytodayemail + '" data-contact-id="" data-firstname="" data-toggle="tooltip" data-placement="right" title="Add as recipient">'; inlineQty += '<span class="glyphicon glyphicon-envelope"></span>'; inlineQty += '</button>'; inlineQty += '</div>'; inlineQty += '</div></div>'; // Day to day phone field inlineQty += '<div class="col-xs-6 daytodayphone_div">'; inlineQty += '<div class="input-group">'; inlineQty += '<span class="input-group-addon" id="daytodayphone_text">DAY-TO-DAY PHONE</span>'; inlineQty += '<input id="daytodayphone" type="tel" value="' + daytodayphone + '" class="form-control daytodayphone" ' + disabled + ' />'; inlineQty += '<div class="input-group-btn"><button type="button" style="background-color: #379E8F" class="btn btn-success" id="call_daytoday_phone"><span class="glyphicon glyphicon-earphone"></span></button></div>'; inlineQty += '</div></div></div></div>'; return inlineQty; } /** * The receiver phone and email fields. * These fields should be automatically filled based on the Selector number value. * @param {String} daytodayphone * @param {String} daytodayemail * @param {Number} status_value * @param {String} selector_type * @return {String} inlineQty */ function senderDetails(selector_type, senderName, senderEmail, senderPhone, senderAddress) { var disabled = 'disabled'; if (isNullorEmpty(senderName) && isNullorEmpty(senderEmail) && isNullorEmpty(senderPhone) && isNullorEmpty(senderAddress)) { disabled = ''; } var inlineQty = ''; if (selector_type == 'barcode_number') { // Sender details header var inlineQty = '<div class="form-group container tickets_details_header_section">'; inlineQty += '<div class="row">'; inlineQty += '<div class="col-xs-12 heading2" >'; inlineQty += '<h4><span style="background-color: #379E8F" class="label label-default col-xs-12">SENDER DETAILS</span></h4>'; inlineQty += '</div></div></div>'; //First Row inlineQty += '<div class="form-group container sendercontact_section">'; inlineQty += '<div class="row">'; // name field inlineQty += '<div class="col-xs-4 sendername_div">'; inlineQty += '<div class="input-group">'; inlineQty += '<span class="input-group-addon" id="sendername_text">NAME</span>'; inlineQty += '<input id="sendername" value="' + senderName + '" class="form-control sendername" ' + disabled + ' />'; inlineQty += '</div></div>'; // Day to day phone field inlineQty += '<div class="col-xs-4 senderphone_div">'; inlineQty += '<div class="input-group">'; inlineQty += '<span class="input-group-addon" id="senderphone_text">PHONE</span>'; inlineQty += '<input id="senderphone" type="tel" value="' + senderPhone + '" class="form-control senderphone" ' + disabled + ' />'; inlineQty += '<div class="input-group-btn"><button type="button" style="background-color: #379E8F" class="btn btn-success" id="call_sender_phone"><span class="glyphicon glyphicon-earphone"></span></button></div>'; inlineQty += '</div></div>'; // Day to day email field inlineQty += '<div class="col-xs-4 senderemail_div">'; inlineQty += '<div class="input-group">'; inlineQty += '<span class="input-group-addon" id="senderemail_text">EMAIL</span>'; inlineQty += '<input id="senderemail" type="email" value="' + senderEmail + '" class="form-control senderemail" ' + disabled + ' />'; inlineQty += '<div class="input-group-btn">'; inlineQty += '<button type="button" style="background-color: #379E8F" class="btn btn-success add_as_recipient" data-email="' + senderEmail + '" data-contact-id="" data-firstname="" data-toggle="tooltip" data-placement="right" title="Add as recipient">'; inlineQty += '<span class="glyphicon glyphicon-envelope"></span>'; inlineQty += '</button>'; inlineQty += '</div>'; inlineQty += '</div></div>'; inlineQty += '</div></div>'; //2nd Row inlineQty += '<div class="form-group container receivercontact2_section">'; inlineQty += '<div class="row">'; // address1 field inlineQty += '<div class="col-xs-12 senderaddress_div">'; inlineQty += '<div class="input-group">'; inlineQty += '<span class="input-group-addon" id="senderaddress_text">ADDRESS</span>'; inlineQty += '<input id="senderaddress" value="' + senderAddress + '" class="form-control senderaddress" ' + disabled + ' />'; inlineQty += '</div></div>'; inlineQty += '</div></div>'; } return inlineQty; } /** * The receiver phone and email fields. * These fields should be automatically filled based on the Selector number value. * @param {String} daytodayphone * @param {String} daytodayemail * @param {Number} status_value * @param {String} selector_type * @return {String} inlineQty */ function receiverEmailPhone(selector_type, receiveremail, receiverphone, receivername, receiverstate, receiverzip, receiversuburb, receiveraddr1, receiveraddr2) { var disabled = 'disabled'; if (isNullorEmpty(receiveremail) && isNullorEmpty(receiveraddr1) && isNullorEmpty(receiveraddr2) && isNullorEmpty(receivername) && isNullorEmpty(receiverphone) && isNullorEmpty(receiverstate) && isNullorEmpty(receiverzip) && isNullorEmpty(receiversuburb)) { disabled = ''; } var inlineQty = ''; if (selector_type == 'barcode_number') { // Receiver details header var inlineQty = '<div class="form-group container tickets_details_header_section">'; inlineQty += '<div class="row">'; inlineQty += '<div class="col-xs-12 heading2" >'; inlineQty += '<h4><span style="background-color: #379E8F" class="label label-default col-xs-12">RECEIVER DETAILS</span></h4>'; inlineQty += '</div></div></div>'; //First Row inlineQty += '<div class="form-group container receivercontact_section">'; inlineQty += '<div class="row">'; // name field inlineQty += '<div class="col-xs-4 receivername_div">'; inlineQty += '<div class="input-group">'; inlineQty += '<span class="input-group-addon" id="receivername_text">NAME</span>'; inlineQty += '<input id="receivername" value="' + receivername + '" class="form-control receivername" ' + disabled + ' />'; inlineQty += '</div></div>'; // Day to day phone field inlineQty += '<div class="col-xs-4 receiverphone_div">'; inlineQty += '<div class="input-group">'; inlineQty += '<span class="input-group-addon" id="receiverphone_text">PHONE</span>'; inlineQty += '<input id="receiverphone" type="tel" value="' + receiverphone + '" class="form-control receiverphone" ' + disabled + ' />'; inlineQty += '<div class="input-group-btn"><button type="button" style="background-color: #379E8F" class="btn btn-success" id="call_receiver_phone"><span class="glyphicon glyphicon-earphone"></span></button></div>'; inlineQty += '</div></div>'; // Day to day email field inlineQty += '<div class="col-xs-4 receiveremail_div">'; inlineQty += '<div class="input-group">'; inlineQty += '<span class="input-group-addon" id="receiveremail_text">EMAIL</span>'; inlineQty += '<input id="receiveremail" type="email" value="' + receiveremail + '" class="form-control receiveremail" ' + disabled + ' />'; inlineQty += '<div class="input-group-btn">'; inlineQty += '<button type="button" style="background-color: #379E8F" class="btn btn-success add_as_recipient" data-email="' + receiveremail + '" data-contact-id="" data-firstname="" data-toggle="tooltip" data-placement="right" title="Add as recipient">'; inlineQty += '<span class="glyphicon glyphicon-envelope"></span>'; inlineQty += '</button>'; inlineQty += '</div>'; inlineQty += '</div></div>'; inlineQty += '</div></div>'; //2nd Row inlineQty += '<div class="form-group container receivercontact2_section">'; inlineQty += '<div class="row">'; // address1 field inlineQty += '<div class="col-xs-6 receiveraddr1_div">'; inlineQty += '<div class="input-group">'; inlineQty += '<span class="input-group-addon" id="receiveraddr1_text">ADDRESS1</span>'; inlineQty += '<input id="receiveraddr1" value="' + receiveraddr1 + '" class="form-control receiveraddr1" ' + disabled + ' />'; inlineQty += '</div></div>'; // address2 field inlineQty += '<div class="col-xs-6 receiveraddr2_div">'; inlineQty += '<div class="input-group">'; inlineQty += '<span class="input-group-addon" id="receiveraddr2_text">ADDRESS2</span>'; inlineQty += '<input id="receiveraddr2" value="' + receiveraddr2 + '" class="form-control receiveraddr2" ' + disabled + ' />'; inlineQty += '</div></div>'; inlineQty += '</div></div>'; //3rd Row inlineQty += '<div class="form-group container receivercontact3_section">'; inlineQty += '<div class="row">'; // suburb field inlineQty += '<div class="col-xs-4 receiversuburb_div">'; inlineQty += '<div class="input-group">'; inlineQty += '<span class="input-group-addon" id="receiversuburb_text">SUBURB</span>'; inlineQty += '<input id="receiversuburb" value="' + receiversuburb + '" class="form-control receiversuburb" ' + disabled + ' />'; inlineQty += '</div></div>'; // postcode field inlineQty += '<div class="col-xs-4 receiverzip_div">'; inlineQty += '<div class="input-group">'; inlineQty += '<span class="input-group-addon" id="receiverzip_text">POSTCODE</span>'; inlineQty += '<input id="receiverzip" value="' + receiverzip + '" class="form-control receiverzip" ' + disabled + ' />'; inlineQty += '</div></div>'; // state field inlineQty += '<div class="col-xs-4 receiverstate_div">'; inlineQty += '<div class="input-group">'; inlineQty += '<span class="input-group-addon" id="receiverstate_text">STATE</span>'; inlineQty += '<input id="receiverstate" value="' + receiverstate + '" class="form-control receiverstate" ' + disabled + ' />'; inlineQty += '</div></div>'; inlineQty += '</div></div>'; } return inlineQty; } /** * The accounts phone and email fields of the customer. * These fields should be automatically filled based on the Invoice number value. * @param {String} accountsphone * @param {String} accountsemail * @param {Number} status_value * @param {String} selector_type * @return {String} inlineQty */ function accountsContactSection(accountsphone, accountsemail, status_value, selector_type) { if (isNullorEmpty(accountsphone)) { accountsphone = ''; } if (isNullorEmpty(accountsemail)) { accountsemail = ''; } if (selector_type == 'invoice_number') { var inlineQty = '<div class="form-group container accountscontact_section">'; if (isFinanceRole(userRole) && isTicketNotClosed(status_value)) { var disabled = ''; } else { var disabled = 'disabled'; } } else { var inlineQty = '<div class="form-group container accountscontact_section hide">'; var disabled = 'disabled'; } inlineQty += '<div class="row">'; // Accounts email field inlineQty += '<div class="col-xs-6 accountsemail_div">'; inlineQty += '<div class="input-group">'; inlineQty += '<span class="input-group-addon" id="accountsemail_text">ACCOUNTS EMAIL</span>'; inlineQty += '<input id="accountsemail" type="email" value="' + accountsemail + '" class="form-control accountsemail" ' + disabled + ' />'; inlineQty += '<div class="input-group-btn">'; inlineQty += '<button type="button" style="background-color: #379E8F" class="btn btn-success add_as_recipient" data-email="' + accountsemail + '" data-contact-id="" data-firstname="" data-toggle="tooltip" data-placement="right" title="Add as recipient">'; inlineQty += '<span class="glyphicon glyphicon-envelope"></span>'; inlineQty += '</button>'; inlineQty += '</div>'; inlineQty += '</div></div>'; // Accounts phone field inlineQty += '<div class="col-xs-6 accountsphone_div">'; inlineQty += '<div class="input-group">'; inlineQty += '<span class="input-group-addon" id="accountsphone_text">ACCOUNTS PHONE</span>'; inlineQty += '<input id="accountsphone" type="tel" value="' + accountsphone + '" class="form-control accountsphone" ' + disabled + ' />'; inlineQty += '<div class="input-group-btn"><button type="button" style="background-color: #379E8F" class="btn btn-success" id="call_accounts_phone"><span class="glyphicon glyphicon-earphone"></span></button></div>'; inlineQty += '</div></div></div></div>'; return inlineQty; } /** * * @param {Number} maap_bank_account_number * @param {Number} maap_parent_bank_account_number * @param {String} selector_type * @returns {String} inlineQty */ function maapBankAccountSection(maap_bank_account_number, maap_parent_bank_account_number, selector_type) { switch (selector_type) { case 'barcode_number': var inlineQty = '<div class="form-group container accounts_number_section hide">'; break; case 'invoice_number': var inlineQty = '<div class="form-group container accounts_number_section">'; break; } inlineQty += '<div class="row">'; // MAAP Bank Account # field inlineQty += '<div class="col-xs-6 account_number_div">'; inlineQty += '<div class="input-group">'; inlineQty += '<span class="input-group-addon" id="account_number_text">MAAP BANK ACCOUNT #</span>'; inlineQty += '<input id="account_number" type="number" value="' + maap_bank_account_number + '" class="form-control account_number" disabled />'; inlineQty += '</div></div>'; // MAAP Parent Bank Account # field inlineQty += '<div class="col-xs-6 parent_account_number_div">'; inlineQty += '<div class="input-group">'; inlineQty += '<span class="input-group-addon" id="parent_account_number_text">MAAP PARENT BANK ACCOUNT #</span>'; inlineQty += '<input id="parent_account_number" type="number" value="' + maap_parent_bank_account_number + '" class="form-control parent_account_number" disabled />'; inlineQty += '</div></div></div></div>'; return inlineQty; } /** * The Franchisee name, and its main contact name and phone number fields. * These fields should be automatically filled based on the Selector number value. * @param {String} franchisee_name * @param {String} zee_main_contact_name * @param {String} zee_email * @param {String} zee_main_contact_phone * @param {String} zee_abn * @return {String} inlineQty */ function franchiseeMainContactSection(franchisee_name, zee_main_contact_name, zee_email, zee_main_contact_phone, zee_abn) { if (isNullorEmpty(franchisee_name)) { franchisee_name = ''; } if (isNullorEmpty(zee_main_contact_name)) { zee_main_contact_name = ''; } if (isNullorEmpty(zee_email)) { zee_email = ''; } if (isNullorEmpty(zee_main_contact_phone)) { zee_main_contact_phone = ''; } if (isNullorEmpty(zee_abn)) { zee_abn = ''; } var inlineQty = '<div class="form-group container zee_main_contact_section">'; inlineQty += '<div class="row">'; // Franchisee name field inlineQty += '<div class="col-xs-6 franchisee_name">'; inlineQty += '<div class="input-group">'; inlineQty += '<span class="input-group-addon" id="franchisee_name_text">FRANCHISEE NAME</span>'; inlineQty += '<input id="franchisee_name" value="' + franchisee_name + '" class="form-control franchisee_name" disabled>'; inlineQty += '</div></div>'; // Franchisee main contact name field inlineQty += '<div class="col-xs-6 zee_main_contact_name">'; inlineQty += '<div class="input-group">'; inlineQty += '<span class="input-group-addon" id="zee_main_contact_name_text">MAIN CONTACT</span>'; inlineQty += '<input id="zee_main_contact_name" value="' + zee_main_contact_name + '" class="form-control zee_main_contact_name" disabled>'; inlineQty += '</div></div></div></div>'; // Franchisee contact details inlineQty += '<div class="form-group container zee_main_contact_section">'; inlineQty += '<div class="row">'; // Franchisee email field inlineQty += '<div class="col-xs-12 zee_email">'; inlineQty += '<div class="input-group">'; inlineQty += '<span class="input-group-addon" id="zee_email_text">FRANCHISEE EMAIL</span>'; inlineQty += '<input id="zee_email" type="email" value="' + zee_email + '" class="form-control accountsemail" disabled />'; inlineQty += '<div class="input-group-btn">'; var zee_contact_id = '0'; inlineQty += '<button type="button" style="background-color: #379E8F" class="btn btn-success add_as_recipient" data-email="' + zee_email + '" data-contact-id="' + zee_contact_id + '" data-firstname="' + franchisee_name + '" data-toggle="tooltip" data-placement="right" title="Add as recipient">'; inlineQty += '<span class="glyphicon glyphicon-envelope"></span>'; inlineQty += '</button>'; inlineQty += '</div>'; inlineQty += '</div></div></div></div>'; // Franchisee phone and ABN details inlineQty += '<div class="form-group container zee_main_contact_section">'; inlineQty += '<div class="row">'; // Franchisee main contact phone field inlineQty += '<div class="col-xs-6 zee_main_contact_phone">' inlineQty += '<div class="input-group">' inlineQty += '<span class="input-group-addon" id="zee_main_contact_phone_text">FRANCHISEE PHONE</span>'; inlineQty += '<input id="zee_main_contact_phone" type="tel" value="' + zee_main_contact_phone + '" class="form-control zee_main_contact_phone" disabled />'; inlineQty += '<div class="input-group-btn"><button style="background-color: #379E8F" type="button" class="btn btn-success" id="call_zee_main_contact_phone"><span class="glyphicon glyphicon-earphone"></span></button>'; inlineQty += '</div>'; inlineQty += '</div></div>'; // Franchisee ABN number inlineQty += '<div class="col-xs-6 zee_abn">' inlineQty += '<div class="input-group">' inlineQty += '<span class="input-group-addon" id="zee_abn_text">FRANCHISEE ABN</span>' inlineQty += '<input id="zee_abn" class="form-control zee_abn" value="' + zee_abn + '" disabled>' inlineQty += '</div></div></div></div>'; return inlineQty; } /** * The MPEX Date and Time Stock used fields. * Visible only for the barcode records. * @param {String} selector_type * @param {String} date_stock_used * @param {String} time_stock_used * @return {String} inlineQty */ function mpexStockUsedSection(selector_type, date_stock_used, time_stock_used) { if (isNullorEmpty(date_stock_used)) { date_stock_used = '' } if (isNullorEmpty(time_stock_used)) { time_stock_used = '' } var hide_class = (selector_type == 'barcode_number') ? '' : 'hide'; // MPEX Stock Used Section var inlineQty = '<div class="form-group container mpex_stock_used_section ' + hide_class + '">'; inlineQty += '<div class="row">'; // Date Stock Used inlineQty += ' <div class="col-xs-6 date_stock_used">'; inlineQty += '<div class="input-group">'; inlineQty += '<span class="input-group-addon" id="date_stock_used_text">DATE STOCK USED</span>'; inlineQty += '<input id="date_stock_used" class="form-control date_stock_used" value="' + date_stock_used + '" disabled>'; inlineQty += '</div></div>'; // Time Stock Used inlineQty += '<div class="col-xs-6 time_stock_used">'; inlineQty += '<div class="input-group">'; inlineQty += '<span class="input-group-addon" id="time_stock_used_text">TIME STOCK USED</span>'; inlineQty += '<input id="time_stock_used" class="form-control time_stock_used" value="' + time_stock_used + '" disabled>'; inlineQty += '</div></div></div></div>'; return inlineQty; } /** * The MPEX Final Delivery field is visible only for the barcode records. * The Enquiry Status field is not disabled only for the ticket that have not yet been opened. * @param {Number} status_value * @param {String} selector_type * @param {String} final_delivery_text * @param {Number} selected_enquiry_status_id * @return {String} inlineQty */ function finalDeliveryEnquirySection(status_value, selector_type, final_delivery_text, selected_enquiry_status_id, prod_stock_invoice) { if (isNullorEmpty(final_delivery_text)) { final_delivery_text = '' } if (isNullorEmpty(selected_enquiry_status_id)) { selected_enquiry_status_id = '' } var barcode_hide_class = (selector_type == 'barcode_number') ? '' : 'hide'; var nb_col_enquiry_section = (selector_type == 'barcode_number') ? '6' : '12'; var enquiry_disabled = (isTicketNotClosed(status_value)) ? '' : 'disabled'; // Final Delivery + Enquiry Status Section var inlineQty = '<div class="form-group container final_delivery_enquiry_status_section">'; inlineQty += '<div class="row">'; // Final Delivery inlineQty += '<div class="col-xs-6 final_delivery ' + barcode_hide_class + '">'; inlineQty += '<div class="input-group">'; inlineQty += '<span class="input-group-addon" id="final_delivery_text">FINAL DELIVERY</span>'; inlineQty += '<input id="final_delivery" class="form-control final_delivery" value="' + final_delivery_text + '" disabled>'; inlineQty += '</div></div>'; // Final Delivery inlineQty += '<div class="col-xs-6 invoice ' + barcode_hide_class + '">'; inlineQty += '<div class="input-group">'; inlineQty += '<span class="input-group-addon" id="invoice_text">INVOICE</span>'; inlineQty += '<input id="invoice" class="form-control invoice" value="' + prod_stock_invoice + '" disabled>'; inlineQty += '</div></div>'; inlineQty += '</div></div>'; return inlineQty; } /** * Ticket Label Section for if label on mpex was Printed or Handwritten * @param {Number} selected_label_id * @return {String} inlineQty */ function labelSection(selected_label_id, selector_type, status_value) { if (isNullorEmpty(selected_label_id)) { selected_label_id = ''; } var barcodeHideClass = (selector_type == 'barcode_number') ? '' : 'hide'; var labeldisabled = (isTicketNotClosed(status_value)) ? '' : 'disabled'; var inlineQty = '<div class="form-group container label_section ' + barcodeHideClass + '">'; inlineQty += '<div class="row">'; inlineQty += '<div class="col-xs-6 label_div">'; inlineQty += '<div class="input-group">'; inlineQty += '<span class="input-group-addon" id="label_text">TICKET LABEL</span>'; inlineQty += '<select id="label_status" class="form-control label_status" ' + labeldisabled + '>'; inlineQty += '<option></option>'; var labelColumns = new Array(); labelColumns[0] = search.createColumn({ name: 'name' }); labelColumns[1] = search.createColumn({ name: 'internalId' }); var labelResultSet = search.create({ type: 'customlist_mp_ticket_label', columns: labelColumns, }); labelResultSet.run().each(function (labelResult) { var labelName = labelResult.getValue('name'); var labelId = labelResult.getValue('internalId'); if (selected_label_id == labelId) { inlineQty += '<option value="' + labelId + '"selected>' + labelName + '</option>'; } else { inlineQty += '<option value="' + labelId + '">' + labelName + '</option>'; } return inlineQty; }); inlineQty += '</select>'; inlineQty += '</div></div></div></div>'; return inlineQty; } /** * Section containing enquiry medium type and the enquiry status of the ticket enquiry * @param list_enquiry_mediums {String}atus and * @param total_enquiry_count {Number} * @param selector_type {String} * @param status_value {Number} * @returns {string} */ function enquiryMediumSection(list_enquiry_mediums, selected_enquiry_status_id, selector_type) { //Search for enquiry mediums var hasEnquiryMediums = (!isNullorEmpty(list_enquiry_mediums)); var enquiryMediumColumns = new Array(); enquiryMediumColumns[0] = search.createColumn({ name: 'name' }); enquiryMediumColumns[1] = search.createColumn({ name: 'internalId' }); var enquiryMediumResultSet = search.create({ type: 'customlist_ticket_enquiry_mediums', columns: enquiryMediumColumns, }); //Ticket Enquiry Header // var inlineQty = '<div class="form-group container ticket_enquiry_header_section">'; // inlineQty += '<div class="row">'; // inlineQty += '<div class="col-xs-12 heading2">'; // inlineQty += '<h4><span style="background-color: #379E8F" class="label label-default col-xs-12">TICKET ENQUIRY DETAILS</span></h4>'; // inlineQty += '</div></div></div>'; //Enquiry Medium HTML var inlineQty = '<div class="form-group container enquiry_medium_section">'; inlineQty += '<div class="row">'; // inlineQty += '<div class="col-xs-6 enquiry_medium_div">'; // inlineQty += '<div class="input-group">'; // inlineQty += '<span class="input-group-addon" id="enquiry_medium_text">ENQUIRY MEDIUM</span>'; // inlineQty += '<select multiple id="enquiry_medium_status" class="form-control enquiry_medium_status" size="'+ enquiryMediumResultSet.length + '" disabled>'; // enquiryMediumResultSet.run().each(function (enquiryMediumResult) { // var enquiryMediumName = enquiryMediumResult.getValue('name'); // var enquiryMediumId = enquiryMediumResult.getValue('internalId'); // var selected = false; // if(hasEnquiryMediums){ // selected = (list_enquiry_mediums.indexOf(enquiryMediumId) !== -1); // } // if(selected) { // inlineQty += '<option value="' + enquiryMediumId + '"selected>' + enquiryMediumName + '</option>'; // }else{ // inlineQty += '<option value="' + enquiryMediumId + '">' + enquiryMediumName + '</option>'; // } // return true; // }); // inlineQty += '</select>'; // inlineQty += '</div></div>'; // Enquiry Status var enquiry_status_columns = new Array(); enquiry_status_columns[0] = search.createColumn({ name: 'name' }); enquiry_status_columns[1] = search.createColumn({ name: 'internalId' }); var enquiryStatusResultSet = search.create({ type: 'customlist_mp_ticket_enquiry', columns: enquiry_status_columns, }); inlineQty += '<div class="col-xs-6 enquiry_status_div">'; inlineQty += '<div class="input-group">'; inlineQty += '<span class="input-group-addon" id="enquiry_status_text">ENQUIRY STATUS</span>'; inlineQty += '<select id="enquiry_status" class="form-control enquiry_status">'; inlineQty += '<option></option>'; enquiryStatusResultSet.run().each(function (enquiryStatusResult) { var enquiry_status_name = enquiryStatusResult.getValue('name'); var enquiry_status_id = enquiryStatusResult.getValue('internalId'); if (enquiry_status_id == selected_enquiry_status_id) { inlineQty += '<option value="' + enquiry_status_id + '" selected>' + enquiry_status_name + '</option>'; } else { inlineQty += '<option value="' + enquiry_status_id + '">' + enquiry_status_name + '</option>'; } return true; }); inlineQty += '</select>'; inlineQty += '</div></div></div></div>'; return inlineQty; } /** * Section containing the total enquiry count and its breakdwn counts of chat, phone and email * @param total_enquiry_count * @param chat_enquiry_count * @param phone_enquiry_count * @param email_enquiry_count * @param selector_type * @returns {string} */ function enquiryCountSection(total_enquiry_count, chat_enquiry_count, phone_enquiry_count, email_enquiry_count, selector_type, phone_interaction_count, email_interaction_count) { if (isNullorEmpty(total_enquiry_count)) { total_enquiry_count = 0; } if (isNullorEmpty(chat_enquiry_count)) { chat_enquiry_count = 0; } if (isNullorEmpty(phone_enquiry_count)) { phone_enquiry_count = 0; } if (isNullorEmpty(email_enquiry_count)) { email_enquiry_count = 0; } if (isNullorEmpty(phone_interaction_count)) { phone_interaction_count = 0; } if (isNullorEmpty(email_interaction_count)) { email_interaction_count = 0; } //Total Enquiry Count HTML // var inlineQty = '<div class="form-group container enquiry_count_section">'; // inlineQty += '<div class="row">'; // inlineQty += '<div class="col-xs-12 total_enquiry_count_div">'; // inlineQty += '<div class="input-group">'; // inlineQty += '<span class="input-group-addon" id="total_enquiry_count_text">ENQUIRY COUNT</span>'; // inlineQty += '<input id="total_enquiry_count" class="form-control enquiry_count" value="' + total_enquiry_count + '" disabled />'; // inlineQty += '</div></div></div></div>'; //Enquiries by chat count var inlineQty = '<div class="form-group container enquiry_count_breakdown_section">'; inlineQty += '<div class="row">'; inlineQty += '<div class="col-xs-4 enquiry_count_by_chat">'; inlineQty += '<div class="input-group">'; inlineQty += '<span class="input-group-addon" id="enquiry_count_by_chat_text"> WEBSITE ENQUIRY </span>'; inlineQty += '<input id="enquiry_count_by_chat" value="' + chat_enquiry_count + '" class="form-control enquiry_count_by_chat" disabled>'; inlineQty += '<div class="input-group-btn">'; inlineQty += '<button type="button" style="background-color: #379E8F" class="btn btn-success increment_enquiry_count_by_chat" data-firstname="" data-toggle="tooltip" data-placement="right" title="Increment Chat Enquiry Count">'; inlineQty += '<span class="glyphicon glyphicon-plus"></span>'; inlineQty += '</button>'; inlineQty += '<button type="button" class="btn btn-danger decrement_enquiry_count_by_chat" data-firstname="" data-toggle="tooltip" data-placement="right" title="Decrement Chat Enquiry Count">'; inlineQty += '<span class="glyphicon glyphicon-minus"></span>'; inlineQty += '</button>'; inlineQty += '</div></div></div>'; inlineQty += '<div class="col-xs-4 enquiry_count_by_phone">'; inlineQty += '<div class="input-group">'; inlineQty += '<span class="input-group-addon" id="enquiry_count_by_phone_text"> PHONE ENQUIRY </span>'; inlineQty += '<input id="enquiry_count_by_phone" value="' + phone_enquiry_count + '" class="form-control enquiry_count_by_phone" disabled>'; inlineQty += '<div class="input-group-btn">'; inlineQty += '<button type="button" style="background-color: #379E8F" class="btn btn-success increment_enquiry_count_by_phone" data-firstname="" data-toggle="tooltip" data-placement="right" title="Increment Phone Enquiry Count">'; inlineQty += '<span class="glyphicon glyphicon-plus"></span>'; inlineQty += '</button>'; inlineQty += '<button type="button" class="btn btn-danger decrement_enquiry_count_by_phone" data-firstname="" data-toggle="tooltip" data-placement="right" title="Decrement Phone Enquiry Count">'; inlineQty += '<span class="glyphicon glyphicon-minus"></span>'; inlineQty += '</button>'; inlineQty += '</div></div></div>'; inlineQty += '<div class="col-xs-4 enquiry_count_by_email">'; inlineQty += '<div class="input-group">'; inlineQty += '<span class="input-group-addon" id="enquiry_count_by_email_text"> EMAIL ENQUIRY </span>'; inlineQty += '<input id="enquiry_count_by_email" value="' + email_enquiry_count + '" class="form-control enquiry_count_by_email" disabled>'; inlineQty += '<div class="input-group-btn">'; inlineQty += '<button type="button" style="background-color: #379E8F" class="btn btn-success increment_enquiry_count_by_email" data-firstname="" data-toggle="tooltip" data-placement="right" title="Increment Email Enquiry Count">'; inlineQty += '<span class="glyphicon glyphicon-plus"></span>'; inlineQty += '</button>'; inlineQty += '<button type="button" class="btn btn-danger decrement_enquiry_count_by_email" data-firstname="" data-toggle="tooltip" data-placement="right" title="Decrement Email Enquiry Count">'; inlineQty += '<span class="glyphicon glyphicon-minus"></span>'; inlineQty += '</button>'; inlineQty += '</div></div></div></div></div>'; if (selector_type == "customer_issue") { inlineQty += '<div class="form-group container interaction_count_breakdown_section">'; inlineQty += '<div class="row">'; inlineQty += '<div class="col-xs-6 interaction_count_by_phone">'; inlineQty += '<div class="input-group">'; inlineQty += '<span class="input-group-addon" id="interaction_count_by_phone_text"> PHONE INTERACTION </span>'; inlineQty += '<input id="interaction_count_by_phone" value="' + phone_interaction_count + '" class="form-control interaction_count_by_phone" disabled>'; inlineQty += '<div class="input-group-btn">'; inlineQty += '<button type="button" style="background-color: #379E8F" class="btn btn-success increment_interaction_count_by_phone" data-firstname="" data-toggle="tooltip" data-placement="right" title="Increment Phone Interaction Count">'; inlineQty += '<span class="glyphicon glyphicon-plus"></span>'; inlineQty += '</button>'; inlineQty += '<button type="button" class="btn btn-danger decrement_interaction_count_by_phone" data-firstname="" data-toggle="tooltip" data-placement="right" title="Decrement Phone interaction Count">'; inlineQty += '<span class="glyphicon glyphicon-minus"></span>'; inlineQty += '</button>'; inlineQty += '</div></div></div>'; inlineQty += '<div class="col-xs-6 interaction_count_by_email">'; inlineQty += '<div class="input-group">'; inlineQty += '<span class="input-group-addon" id="interaction_count_by_email_text"> EMAIL INTERACTION </span>'; inlineQty += '<input id="interaction_count_by_email" value="' + email_interaction_count + '" class="form-control interaction_count_by_email" disabled>'; inlineQty += '<div class="input-group-btn">'; inlineQty += '<button type="button" style="background-color: #379E8F" class="btn btn-success increment_interaction_count_by_email" data-firstname="" data-toggle="tooltip" data-placement="right" title="Increment Email Interaction Count">'; inlineQty += '<span class="glyphicon glyphicon-plus"></span>'; inlineQty += '</button>'; inlineQty += '<button type="button" class="btn btn-danger decrement_interaction_count_by_email" data-firstname="" data-toggle="tooltip" data-placement="right" title="Decrement Email Interaction Count">'; inlineQty += '<span class="glyphicon glyphicon-minus"></span>'; inlineQty += '</button>'; inlineQty += '</div></div></div></div></div>'; } return inlineQty; } /** * These fields should be displayed only for an Invoice ticket, and be edited only by the finance team. * - Invoice Method field * - Accounts cc email field * - MPEX PO # field * - Customer PO # field * - MPEX Invoicing Cycle field * @param {Number} selected_invoice_method_id * @param {String} accounts_cc_email * @param {String} mpex_po_number * @param {String} customer_po_number * @param {Number} selected_invoice_cycle_id * @param {Number} terms * @param {String} customer_terms * @param {Number} status_value * @param {String} selector_type * @return {String} inlineQty */ function otherInvoiceFieldsSection(selected_invoice_method_id, accounts_cc_email, mpex_po_number, customer_po_number, selected_invoice_cycle_id, terms, customer_terms, status_value, selector_type) { if (isNullorEmpty(accounts_cc_email)) { accounts_cc_email = '' } if (isNullorEmpty(mpex_po_number)) { mpex_po_number = '' } if (isNullorEmpty(customer_po_number)) { customer_po_number = '' } if (isNullorEmpty(customer_terms)) { customer_terms = '' } var invoice_method_columns = new Array(); invoice_method_columns[0] = search.createColumn({ name: 'name' }); invoice_method_columns[1] = search.createColumn({ name: 'internalId' }); var invoiceMethodResultSet = search.create({ type: 'customlist_invoice_method', columns: invoice_method_columns, }); switch (selector_type) { case 'barcode_number': var inlineQty = '<div class="form-group container invoice_method_accounts_cc_email_section hide">'; var disabled = 'disabled'; break; case 'invoice_number': var inlineQty = '<div class="form-group container invoice_method_accounts_cc_email_section">'; if (isFinanceRole(userRole) && isTicketNotClosed(status_value)) { var disabled = ''; } else { var disabled = 'disabled'; } break; } inlineQty += '<div class="row">'; // Invoice Method field inlineQty += '<div class="col-xs-6 invoice_method_div">'; inlineQty += '<div class="input-group">'; inlineQty += '<span class="input-group-addon" id="invoice_method_text">INVOICE METHOD</span>'; inlineQty += '<select id="invoice_method" class="form-control" ' + disabled + '>'; inlineQty += '<option></option>'; invoiceMethodResultSet.run().each(function (invoiceMethodResult) { var invoice_method_name = invoiceMethodResult.getValue('name'); var invoice_method_id = invoiceMethodResult.getValue('internalId'); if (invoice_method_id == selected_invoice_method_id) { inlineQty += '<option value="' + invoice_method_id + '" selected>' + invoice_method_name + '</option>'; } else { inlineQty += '<option value="' + invoice_method_id + '">' + invoice_method_name + '</option>'; } return true; }); inlineQty += '</select>'; inlineQty += '</div></div>'; // Accounts cc email field --> inlineQty += '<div class="col-xs-6 accounts_cc_email_div">'; inlineQty += '<div class="input-group">'; inlineQty += '<span class="input-group-addon" id="accounts_cc_email_text">ACCOUNTS CC EMAIL</span>'; inlineQty += '<input id="accounts_cc_email" type="email" value="' + accounts_cc_email + '" class="form-control accounts_cc_email" ' + disabled + '/>'; inlineQty += '<div class="input-group-btn">'; inlineQty += '<button type="button" style="background-color: #379E8F" class="btn btn-success add_as_recipient" data-email="' + accounts_cc_email + '" data-contact-id="" data-firstname="" data-toggle="tooltip" data-placement="right" title="Add as recipient">'; inlineQty += '<span class="glyphicon glyphicon-envelope"></span>'; inlineQty += '</button>'; inlineQty += '</div>'; inlineQty += '</div></div></div></div>'; switch (selector_type) { case 'barcode_number': inlineQty += '<div class="form-group container mpex_customer_po_number_section hide">'; break; case 'invoice_number': inlineQty += '<div class="form-group container mpex_customer_po_number_section">'; break; } inlineQty += '<div class="row">'; // MPEX PO # inlineQty += '<div class="col-xs-6 mpex_po_number_div">'; inlineQty += '<div class="input-group">'; inlineQty += '<span class="input-group-addon" id="mpex_po_number_text">MPEX PO #</span>'; inlineQty += '<input id="mpex_po_number" value="' + mpex_po_number + '" class="form-control mpex_po_number" ' + disabled + '/>'; inlineQty += '</div></div>'; // Customer PO # inlineQty += '<div class="col-xs-6 customer_po_number_div">'; inlineQty += '<div class="input-group">'; inlineQty += '<span class="input-group-addon" id="customer_po_number_text">CUSTOMER PO #</span>'; inlineQty += '<input id="customer_po_number" value="' + customer_po_number + '" class="form-control customer_po_number" ' + disabled + '/>'; inlineQty += '</div></div></div></div>'; // Terms fields switch (selector_type) { case 'barcode_number': inlineQty += '<div class="form-group container terms_section hide">'; break; case 'invoice_number': inlineQty += '<div class="form-group container terms_section">'; break; } inlineQty += '<div class="row">'; // Terms inlineQty += '<div class="col-xs-6 terms_div">'; inlineQty += '<div class="input-group">'; inlineQty += '<span class="input-group-addon" id="terms_text">TERMS</span>'; // Find the text related to the terms value. var terms_options = [{ "value": "", "text": "" }, { "value": "5", "text": "1% 10 Net 30" }, { "value": "6", "text": "2% 10 Net 30" }, { "value": "4", "text": "Due on receipt" }, { "value": "1", "text": "Net 15 Days" }, { "value": "2", "text": "Net 30 Days" }, { "value": "8", "text": "Net 45 Days" }, { "value": "3", "text": "Net 60 Days" }, { "value": "7", "text": "Net 7 Days" }, { "value": "9", "text": "Net 90 Days" }]; var terms_option = findObjectByKey(terms_options, "value", terms); var terms_text = isNullorEmpty(terms_option) ? '' : terms_option.text; inlineQty += '<input id="terms" class="form-control terms" value="' + terms_text + '" disabled/>'; inlineQty += '</div></div>'; // Customer's terms inlineQty += '<div class="col-xs-6 customers_terms_div">'; inlineQty += '<div class="input-group">'; inlineQty += '<span class="input-group-addon" id="customers_terms_text">' + "CUSTOMER'S TERMS</span>"; inlineQty += '<input id="customers_terms" class="form-control customers_terms" value="' + customer_terms + '" ' + disabled + '/>'; inlineQty += '</div></div></div></div>'; // MPEX Invoicing Cycle var invoice_cycle_columns = new Array(); invoice_cycle_columns[0] = search.createColumn({ name: 'name' }); invoice_cycle_columns[1] = search.createColumn({ name: 'internalId' }); var invoiceCycleResultSet = search.create({ type: 'customlist_invoicing_cyle', columns: invoice_cycle_columns, }) switch (selector_type) { case 'barcode_number': inlineQty += '<div class="form-group container mpex_invoicing_cycle_section hide">'; break; case 'invoice_number': inlineQty += '<div class="form-group container mpex_invoicing_cycle_section">'; break; } inlineQty += '<div class="row">'; inlineQty += '<div class="col-xs-12 mpex_invoicing_cycle_div">'; inlineQty += '<div class="input-group">'; inlineQty += '<span class="input-group-addon" id="mpex_invoicing_cycle_text">MPEX INVOICING CYCLE</span>'; inlineQty += '<select id="mpex_invoicing_cycle" class="form-control mpex_invoicing_cycle" ' + disabled + '>'; inlineQty += '<option></option>'; invoiceCycleResultSet.run().each(function (invoiceCycleResult) { var invoice_cycle_name = invoiceCycleResult.getValue('name'); var invoice_cycle_id = invoiceCycleResult.getValue('internalId'); if (invoice_cycle_id == selected_invoice_cycle_id) { inlineQty += '<option value="' + invoice_cycle_id + '" selected>' + invoice_cycle_name + '</option>'; } else { inlineQty += '<option value="' + invoice_cycle_id + '">' + invoice_cycle_name + '</option>'; } return true; }); inlineQty += '</select>'; inlineQty += '</div></div></div></div>'; return inlineQty; } /** * The Attachments field (an editable hyperlink) * @param {String} attachments_hyperlink * @param {Number} status_value * @returns {String} inlineQty */ function attachmentsSection(attachments_hyperlink, status_value) { if (isNullorEmpty(attachments_hyperlink)) { attachments_hyperlink = '' } var disabled = (isTicketNotClosed(status_value)) ? '' : 'disabled'; var inlineQty = '<div class="form-group container attachments_section">'; inlineQty += '<div class="row">'; inlineQty += '<div class="col-xs-12 attachments_div">'; inlineQty += '<div class="input-group">'; inlineQty += '<span class="input-group-addon" id="attachments_text">ATTACHMENTS</span>' inlineQty += '<input id="attachments" class="form-control attachments" type="url" value="' + attachments_hyperlink + '" ' + disabled + '/>'; inlineQty += '</div></div></div></div>'; return inlineQty; } /** * The customer contact details section. * Possibility for the user to add / edit the contacts. * @return {String} inlineQty */ function mpexContactSection() { // Contact details header var inlineQty = '<div class="form-group container mpex_contact_section">'; inlineQty += '<div class="row">'; inlineQty += '<div class="col-xs-12 heading2">'; inlineQty += '<h4><span style="background-color: #379E8F" class="label label-default col-xs-12">CONTACT DETAILS</span></h4>'; inlineQty += '</div>'; inlineQty += '</div></div>'; // Contact table inlineQty += '<div class="form-group container contacts_section" style="font-size: small;">'; inlineQty += '<div class="row">'; inlineQty += '<div class="col-xs-12 contacts_div">'; // Since the table is not displayed correctly when added through suitelet, // It is added with jQuery in the pageInit() function in the client script 'mp_cl_open_ticket.js'. inlineQty += '</div>'; inlineQty += '</div>'; inlineQty += '</div>'; // Add/edit contacts button inlineQty += '<div class="form-group container reviewcontacts_section">'; inlineQty += '<div class="row">'; inlineQty += '<div class="col-xs-4 col-xs-offset-4 reviewcontacts">'; inlineQty += '<input type="button" style="background-color: #379E8F; border-color: #379E8F; font-weight: 700" value="ADD/EDIT CONTACTS" class="form-control btn btn-primary" id="reviewcontacts" />'; inlineQty += '</div></div></div>'; return inlineQty; }; /** * A Datatable displaying the open invoices of the customer * @param {Number} ticket_id * @param {String} selector_type * @return {String} inlineQty */ function openInvoicesSection(ticket_id, selector_type) { if (isNullorEmpty(ticket_id)) { ticket_id = '' } var hide_class_section = (isNullorEmpty(ticket_id) || selector_type != 'invoice_number') ? 'hide' : ''; // Open invoices header var inlineQty = '<div class="form-group container open_invoices open_invoices_header ' + hide_class_section + '">'; inlineQty += '<div class="row">'; inlineQty += '<div class="col-xs-12 heading2">'; inlineQty += '<h4><span style="background-color: #379E8F" class="label label-default col-xs-12">OPEN INVOICES</span></h4>'; inlineQty += '</div></div></div>'; // Open invoices dropdown field inlineQty += '<div class="form-group container open_invoices invoices_dropdown ' + hide_class_section + '">'; inlineQty += '<div class="row">'; inlineQty += '<div class="col-xs-12 invoices_dropdown_div">'; inlineQty += '<div class="input-group">'; inlineQty += '<span class="input-group-addon" id="invoices_dropdown_text">INVOICE STATUS</span>'; inlineQty += '<select id="invoices_dropdown" class="form-control">'; inlineQty += '<option value="open" selected>Open</option>'; inlineQty += '<option value="paidInFull">Paid In Full (last 3 months)</option>'; inlineQty += '</select>'; inlineQty += '</div></div></div></div>'; // Open Invoices Datatable //inlineQty += '<div class="form-group container open_invoices open_invoices_datatable>'; //inlineQty += '</div>'; inlineQty += '<div class="form-group open_invoices open_invoices_table ' + hide_class_section + '">'; inlineQty += dataTable(); // inlineQty += '<div class="row">'; // inlineQty += '<div class="col-xs-18" id="open_invoice_dt_div">'; // // It is inserted as inline html in the script mp_cl_open_ticket // inlineQty += '</div></div></div>'; inlineQty += '</div>' return inlineQty; } function dataTable() { var inlineQty = '<style>table#invoices-preview {font-size: 12px;text-align: center;border: none;}.dataTables_wrapper {font-size: 14px;}table#invoices-preview th{text-align: center;} .bolded{font-weight: bold;}</style>'; inlineQty += '<table id="invoices-preview" class="table table-responsive table-striped customer tablesorter" style="width: 100%; table-layout: fixed">'; inlineQty += '<thead style="color: white;background-color: #379E8F;">'; inlineQty += '<tr class="text-center">'; inlineQty += '</tr>'; inlineQty += '</thead>'; inlineQty += '<tbody id="result_invoices"></tbody>'; inlineQty += '</table>'; return inlineQty; } /** * The Credit Memo Section. * Displays a table of the credit memos linked to the invoice. * Possibility to attach the credit memo PDF to the email. * @param {String} selector_type * @return {String} inlineQty */ function creditMemoSection(selector_type) { var inlineQty = ''; if (selector_type == 'invoice_number') { // Credit Memo Header inlineQty += '<div class="form-group container credit_memo credit_memo_header">'; inlineQty += '<div class="row">'; inlineQty += '<div class="col-xs-12 heading2">'; inlineQty += '<h4><span style="background-color: #379E8F" class="label label-default col-xs-12">CREDIT MEMO</span></h4>'; inlineQty += '</div></div></div>'; // Credit Memo table inlineQty += '<div class="form-group container credit_memo credit_memo_section" style="font-size: small;">'; inlineQty += '<div class="row">'; inlineQty += '<div class="col-xs-12 credit_memo_div">'; // Since the table is not displayed correctly when added through suitelet, // It is added with jQuery in the pageInit() function in the client script 'mp_cl_open_ticket.js'. inlineQty += '</div></div></div>'; } return inlineQty; } function usageReportSection(selector_type) { var inlineQty = ''; if (selector_type == 'invoice_number') { // Usage Report Header inlineQty += '<div class="form-group container usage_report usage_report_header">'; inlineQty += '<div class="row">'; inlineQty += '<div class="col-xs-12 heading2">'; inlineQty += '<h4><span style="background-color: #379E8F" class="label label-default col-xs-12">USAGE REPORT</span></h4>'; inlineQty += '</div></div></div>'; // Usage Report table inlineQty += '<div class="form-group container usage_report usage_report_section" style="font-size: small;">'; inlineQty += '<div class="row">'; inlineQty += '<div class="col-xs-12 usage_report_div">'; // Since the table is not displayed correctly when added through suitelet, // It is added with jQuery in the pageInit() function in the client script 'mp_cl_open_ticket.js'. inlineQty += '</div></div></div>'; } return inlineQty; } /** * The "Send Email" section. * Possibility for the user to send an email to the customer, based on selected templates. * @param {Number} ticket_id * @param {Number} status_value * @param {Object} account_manager * @returns {String} inlineQty */ function sendEmailSection(ticket_id, status_value, account_manager, list_toll_emails) { var has_toll_emails = (!isNullorEmpty(list_toll_emails)); if (isNullorEmpty(ticket_id) || !isTicketNotClosed(status_value)) { // The section is hidden here rather than in the openTicket function, // because we use the section to send an acknoledgement email when a ticket is opened. var inlineQty = '<div id="send_email_container" class="send_email hide">'; } else { var inlineQty = '<div id="send_email_container" class="send_email">'; } // inlineQty += '<div class="form-group container send_email header_section">'; // // Send email header // inlineQty += '<div class="row">'; // inlineQty += '<div class="col-xs-12 heading2">'; // inlineQty += '<h4><span style="background-color: #379E8F" class="label label-default col-xs-12">SEND EMAILS</span></h4>'; // inlineQty += '</div></div></div>'; inlineQty += '<br></br>' // Row addressees inlineQty += '<div class="form-group container send_email adressees_section">'; inlineQty += '<div class="row">'; inlineQty += '<div class="col-xs-12 to_section">'; inlineQty += '<div class="input-group">'; inlineQty += '<span class="input-group-addon">TO<span class="mandatory">*</span></span>'; inlineQty += '<input id="send_to" class="form-control" data-contact-id="" data-firstname=""/>'; inlineQty += '</div></div></div></div>'; // Toll addresses var toll_emails_columns = new Array(); toll_emails_columns[0] = search.createColumn({ name: 'name' }); toll_emails_columns[1] = search.createColumn({ name: 'internalId' }); var tollEmailsResultSet = search.create({ type: 'customlist_toll_emails', columns: toll_emails_columns, }) inlineQty += '<div class="form-group container send_email toll_adressees_section">'; inlineQty += '<div class="row">'; inlineQty += '<div class="col-xs-12 toll_section">'; inlineQty += '<div class="input-group">'; inlineQty += '<span class="input-group-addon">TOLL EMAILS</span>'; inlineQty += '<select multiple id="send_toll" class="form-control" size="' + tollEmailsResultSet.length + '"/>'; tollEmailsResultSet.run().each(function (tollEmailsResultSet) { var tollEmailName = tollEmailsResultSet.getValue('name'); var tollEmailId = tollEmailsResultSet.getValue('internalId'); var selected = false; if (has_toll_emails) { selected = (list_toll_emails.indexOf(tollEmailId) !== -1); } if (selected) { inlineQty += '<option value="' + tollEmailId + '" selected>' + tollEmailName + '</option>'; } else { inlineQty += '<option value="' + tollEmailId + '">' + tollEmailName + '</option>'; } return true; }); inlineQty += '</select>'; inlineQty += '</div></div></div></div>'; // Row ccs addresses inlineQty += '<div class="form-group container send_email cc_adressees_section">'; inlineQty += '<div class="row">'; inlineQty += '<div class="col-xs-6 cc_section">'; inlineQty += '<div class="input-group">'; inlineQty += '<span class="input-group-addon">CC</span>'; inlineQty += '<input id="send_cc" class="form-control"/>'; inlineQty += '</div></div>'; inlineQty += '<div class="col-xs-6 bcc_section">'; inlineQty += '<div class="input-group">'; inlineQty += '<span class="input-group-addon">BCC</span>'; inlineQty += '<input id="send_bcc" class="form-control"/>'; inlineQty += '</div></div></div></div>'; // Row account manager if (isNullorEmpty(account_manager.name)) { account_manager.name = '' } if (isNullorEmpty(account_manager.email)) { account_manager.email = '' } if (!isNullorEmpty(account_manager.email.email)) { inlineQty += '<div class="form-group container send_email acc_manager_section">'; inlineQty += '<div class="row">'; inlineQty += '<div class="col-xs-10 acc_manager_name_section">'; inlineQty += '<div class="input-group">'; inlineQty += '<span class="input-group-addon">ACCOUNT MANAGER</span>'; inlineQty += '<input id="acc_manager" class="form-control" data-email="' + account_manager.email.email + '" value="' + account_manager.name + ' - ' + account_manager.email.email + '" disabled/>'; inlineQty += '</div></div>'; inlineQty += '<div class="col-xs-2 acc_manager_button_section">'; inlineQty += '<button id="acc_manager_button" style="background-color: #379E8F; border-color: #379E8F" type="button" class="btn btn-success btn-block">ADD TO CC</button>'; inlineQty += '</div></div></div>'; } // Row Template inlineQty += '<div class="form-group container send_email template_section">'; inlineQty += '<div class="row">'; inlineQty += '<div class="col-xs-12 template_section">'; inlineQty += '<div class="input-group">'; inlineQty += '<span class="input-group-addon">TEMPLATE<span class="mandatory">*</span></span>'; inlineQty += '<select id="template" class="form-control">'; inlineQty += '<option></option>'; // Load the template options var templatesSearch = search.load({ id: 'customsearch_cctemplate_mp_ticket', type: 'customrecord_camp_comm_template' }); var templatesSearchResults = templatesSearch.run(); templatesSearchResults.each(function (templatesSearchResult) { // var tempId = templatesSearchResult.getValue('internalid'); var tempId = templatesSearchResult["id"]; var tempName = templatesSearchResult.getValue('name'); inlineQty += '<option value="' + tempId + '">' + tempName + '</option>'; return true; }); inlineQty += '</select>'; inlineQty += '</div></div></div></div>'; // Row Subject inlineQty += '<div class="form-group container send_email subject_section">'; inlineQty += '<div class="row">'; inlineQty += '<div class="col-xs-12 subject_section">'; inlineQty += '<div class="input-group">'; inlineQty += '<span class="input-group-addon">SUBJECT<span class="mandatory">*</span></span>'; inlineQty += '<input id="subject" class="form-control" />'; inlineQty += '</div></div></div></div>'; // Row Body inlineQty += '<div class="form-group container send_email body_section">'; inlineQty += '<div class="row">'; inlineQty += '<div class="col-xs-12 body_section">'; inlineQty += '<div id="email_body"></div>'; inlineQty += '</div></div></div>'; // SEND EMAIL button inlineQty += '<div class="form-group container send_email button_section">'; inlineQty += '<div class="row">'; inlineQty += '<div class="col-xs-4 col-xs-offset-4 send_email_btn">'; inlineQty += '<input type="button" style="background-color: #379E8F; border-color: #379E8F; font-weight: 700" value="SEND EMAIL" class="form-control btn btn-primary" id="send_email" />'; inlineQty += '</div></div></div></div>'; return inlineQty; }; /** * Section for the previous emails datatable * @param customer_id * @returns {string} */ function previousEmailsSection(customer_id) { var customerRecord = record.load({ type: record.Type.CUSTOMER, id: customer_id, }); var customer_internal_id = customerRecord.getValue({ fieldId: 'id' }); // Previous Emails header var inlineQty = '<div class="form-group container previous_emails_header">'; inlineQty += '<div class="row">'; inlineQty += '<div class="col-xs-12 heading2">'; inlineQty += '<h4><span style="background-color: #379E8F" class="label label-default col-xs-12">PREVIOUS EMAILS</span></h4>'; inlineQty += '</div></div></div>'; //Searching emails filtered by - internal customer id and dated before the lastmonthonefiscalquarterago (i.e. the past three months) var emailSearch = search.load({ type: 'message', id: 'customsearch_all_messages' }); var emailSearchFilter = [["customer.internalid", "anyof", customer_internal_id], "AND", ["messagedate", "after", "lastmonthonefiscalquarterago"]]; //670041, 313070 emailSearch.filterExpression = emailSearchFilter; var resultEmailSet = emailSearch.run(); var allEmails = resultEmailSet.getRange({ start: 0, end: 1000 }); //Previous Emails table setup // inlineQty += '<style> table {font-size: 12px;text-align: center;border: none;} {font-size: 14px;} table th{text-align: center;} .dataTables_wrapper{width:78%; margin:auto;} </style>'; // inlineQty += '<div class="form-group container previous_emails_section">'; // inlineQty += '<table cellpadding="15" id="emails-preview" class="table table-responsive table-striped customer tablesorter" cellspacing="0" style="width: 100%;">'; // inlineQty += '<thead style="color: white;background-color: #CFE0CE;">'; // inlineQty += '<tr class="text-center">'; // inlineQty += '<th scope="col">Message Date</th>'; // inlineQty += '<th scope="col">Author</th>'; // inlineQty += '<th scope="col">Receipients</th>'; // inlineQty += '<th scope="col">Subject</th>'; // inlineQty += '<th scope="col">More</th>'; // inlineQty += '</tr>'; // inlineQty += '</thead>'; // inlineQty += '<tbody>'; inlineQty += '<style>table#emails-preview {font-size: 12px;text-align: center;border: none; background-color: #379E8F}.dataTables_wrapper {font-size: 12px;}table#emails-preview th{background-color: #379E8F; text-align: center;}</style>'; inlineQty += '<table cellpadding="15" id="emails-preview" class="table table-responsive table-striped customer tablesorter" cellspacing="0" style="width: 100%;">'; inlineQty += '<thead style="color: white;background-color: #379E8F;">'; inlineQty += '<tr class="text-center">'; inlineQty += '<th scope="col">Message Date</th>'; inlineQty += '<th scope="col">Author</th>'; inlineQty += '<th scope="col">Receipients</th>'; inlineQty += '<th scope="col">Subject</th>'; inlineQty += '<th scope="col">More</th>'; inlineQty += '</tr>'; inlineQty += '</thead>'; inlineQty += '<tbody>'; allEmails.forEach(function (email) { var messageid = email.searchId; var date = email.getValue('messagedate'); var author = email.getValue('authoremail'); var recipients = email.getText('recipients'); var subject = email.getValue('subject'); var url = "https://1048144-sb3.app.netsuite.com/app/crm/common/crmmessage.nl?id=" + messageid; //Table row data inlineQty += '<tr>'; inlineQty += '<td> ' + date + ' </td>'; inlineQty += '<td> ' + author + ' </td>'; inlineQty += '<td> ' + recipients + ' </td>'; inlineQty += '<td> ' + subject + '</td>'; inlineQty += '<td> <a href=' + url + '> View More </a> </td>'; inlineQty += '</tr>'; }); inlineQty += '</tbody>'; inlineQty += '</table>'; //inlineQty += '</div>'; return inlineQty; } /** * @return {String} inlineQty */ function issuesHeader() { var inlineQty = '<div class="form-group container toll_issues_header_section">'; inlineQty += '<div class="row">'; inlineQty += '<div class="col-xs-12 heading1">'; inlineQty += '<h4><span style="background-color: #379E8F" class="form-group label label-default col-xs-12">ISSUES</span></h4>'; inlineQty += '</div></div></div>'; return inlineQty; } /** * @param {Number} status_value * @return {String} inlineQty */ function reminderSection(status_value) { var hide_class = (!isTicketNotClosed(status_value)) ? 'hide' : ''; var inlineQty = '<div class="form-group container reminder_section ' + hide_class + '">'; inlineQty += '<div class="row">'; // Reminder field inlineQty += '<div class="col-xs-12 reminder">'; inlineQty += '<div class="input-group">'; inlineQty += '<span class="input-group-addon" id="reminder_text">REMINDER</span>'; inlineQty += '<input id="reminder" class="form-control reminder" type="date" />'; inlineQty += '</div></div></div></div>'; return inlineQty; } /** * Based on the selected MP Issue, an Owner is allocated to the ticket. * IT issues have priority over the other issues. * Populated with selectOwner() in the pageInit function on the client script. * @param {Number} ticket_id * @param {Array} owner_list * @param {Number} status_value * @return {String} inlineQty */ function ownerSection(ticket_id, owner_list, status_value) { if (isNullorEmpty(ticket_id)) { // If ticket_id is null, owner_list as well. // In that case, only the creator of the ticket is pre-selected as the owner. var userId = runtime.getCurrentUser().id; log.debug({ title: 'userId', details: userId }) owner_list = [userId]; } var disabled = (!isTicketNotClosed(status_value)) ? 'disabled' : ''; log.debug({ title: 'owner_list', details: owner_list }) var inlineQty = '<div class="form-group container owner_section">'; inlineQty += '<div class="row">'; inlineQty += '<div class="col-xs-12 owner">'; inlineQty += '<div class="input-group">'; inlineQty += '<span class="input-group-addon" id="owner_text">OWNER<span class="mandatory">*</span></span>'; inlineQty += '<select multiple id="owner" class="form-control owner" ' + disabled + '>'; var employeeSearch = search.load({ type: 'employee', id: 'customsearch_active_employees' }); var employeeResultSet = employeeSearch.run(); employeeResultSet.each(function (employeeResult) { var employee_id = employeeResult.id; var employee_firstname = employeeResult.getValue('firstname'); var employee_lastname = employeeResult.getValue('lastname'); var employee_email = employeeResult.getValue('email'); if (owner_list.indexOf(parseInt(employee_id)) != -1) { inlineQty += '<option value="' + employee_id + '" data-email="' + employee_email + '" selected>' + employee_firstname + ' ' + employee_lastname + '</option>'; } else { inlineQty += '<option value="' + employee_id + '" data-email="' + employee_email + '">' + employee_firstname + ' ' + employee_lastname + '</option>'; } return true; }); inlineQty += '</select>'; inlineQty += '</div></div></div></div>'; return inlineQty; } function customerIssueDropdown() { //Load the customer issue list var col = new Array(); col[0] = search.createColumn({ name: 'name' }); col[1] = search.createColumn({ name: 'internalId' }); var results = search.create({ type: 'customlist_customer_ticket_issues', columns: col, }) var inlineQty = '<div class="form-group container customer_issues_dropdown_section">'; inlineQty += '<div class="row">'; inlineQty += '<div class="col-xs-12">'; inlineQty += '<div class="input-group"><span class="input-group-addon">CUSTOMER ISSUE</span>'; inlineQty += '<select id="customer_issue_dropdown" class="form-control">'; inlineQty += '<option></option>'; for (var i = 0; results != null && i < results.length; i++) { var res = results[i]; var listValue = res.getValue('name'); var listID = res.getValue('internalId'); inlineQty += '<option value="' + listID + '">' + listValue + '</option>'; // if (selected) { // inlineQty += '<option value="' + listID + '" selected>' + listValue + '</option>'; // } else { // inlineQty += '<option value="' + listID + '">' + listValue + '</option>'; // } } inlineQty += '</select>'; inlineQty += '</div></div></div></div>'; return inlineQty; } function customerIssuesSection(ticket_id, selector_type, selector_number, screenshot_file, selected_browser, login_email_used, selected_operating_system, phone_used, old_sender_name, old_sender_phone, status_value) { if (isNullorEmpty(screenshot_file)) { screenshot_file = ''; } if (isNullorEmpty(selected_browser)) { selected_browser = ''; } if (isNullorEmpty(login_email_used)) { login_email_used = ''; } if (isNullorEmpty(selected_operating_system)) { operating_system = ''; } if (isNullorEmpty(phone_used)) { phone_used = ''; } if (isNullorEmpty(old_sender_name)) { old_sender_name = ''; } if (isNullorEmpty(old_sender_phone)) { old_sender_phone = ''; } var hide_class_section_mp_app = ((selector_type == "customer_issue") && (selector_number == 'Customer App')) ? '' : 'hide'; var hide_class_section_mp_label = ((selector_type == "customer_issue") && (selector_number == 'Update Label')) ? '' : 'hide'; var is_customer_issue_hide = (selector_type != "customer_issue") ? 'hide' : ''; var hide_class_section_mp_portal = ((selector_type == "customer_issue") && (selector_number == 'Customer Portal')) ? '' : 'hide'; var inlineQty = ''; //Screenshot section if (selector_type == "customer_issue" && (selector_number == "Customer App" || selector_number == "Customer Portal") && !isNullorEmpty(ticket_id)) { inlineQty += '<div class="form-group container ss_section">'; inlineQty += '<div class="row">'; inlineQty += '<div class="col-xs-12 screenshot_div">'; inlineQty += '<div class="input-group"><span class="input-group-addon" id="screenshot_text">SCREENSHOT</span>'; inlineQty += '<input type="file" class="form-control" id="screenshot_image" value="' + screenshot_file + '">'; inlineQty += '</div></div></div></div>'; } // Browser and OS Section inlineQty += '<div class="form-group container browser_os_section ' + hide_class_section_mp_portal + ' ' + is_customer_issue_hide + '">'; inlineQty += '<div class="row">'; inlineQty += '<div class="col-xs-6 browser_div">'; inlineQty += '<div class="input-group"><span class="input-group-addon" id="browser_text">BROWSER</span>'; inlineQty += '<select id="browser_value" class="form-control label_status">'; inlineQty += '<option></option>' var browserColumns = new Array(); browserColumns[0] = search.createColumn({ name: 'name' }); browserColumns[1] = search.createColumn({ name: 'internalId' }); var browserResultSet = search.create({ type: 'customlist_common_browsers', columns: browserColumns }); browserResultSet.run().each(function (browserResult) { var browserName = browserResult.getValue('name'); var browserId = browserResult.getValue('internalId'); if (selected_browser == browserId) { inlineQty += '<option value="' + browserId + '"selected>' + browserName + '</option>'; } else { inlineQty += '<option value="' + browserId + '">' + browserName + '</option>'; } return inlineQty; }); inlineQty += '</select></div></div>'; inlineQty += '<div class="col-xs-6 os_div">'; inlineQty += '<div class="input-group"><span class="input-group-addon" id="os_text">OPERATING SYSTEM</span>'; inlineQty += '<select id="os_value" class="form-control">'; inlineQty += '<option></option>' var osColumns = new Array(); osColumns[0] = search.createColumn({ name: 'name' }); osColumns[1] = search.createColumn({ name: 'internalId' }); var osResultSet = search.create({ type: 'customlist_common_os', columns: osColumns }); osResultSet.run().each(function (osResult) { var osName = osResult.getValue('name'); var osId = osResult.getValue('internalId'); if (selected_browser == osId) { inlineQty += '<option value="' + osId + '"selected>' + osName + '</option>'; } else { inlineQty += '<option value="' + osId + '">' + osName + '</option>'; } return inlineQty; }); inlineQty += '</select>'; inlineQty += '</div></div></div></div>'; //Customer App issues - Phone section inlineQty += '<div class="form-group container ' + is_customer_issue_hide + ' phone_section ' + hide_class_section_mp_app + '">'; inlineQty += '<div class="row">'; inlineQty += '<div class="col-xs-12 phone_div">'; inlineQty += '<div class="input-group"><span class="input-group-addon" id="screenshot_text">PHONE</span>'; inlineQty += '<input type="text" class="form-control" id="phone_used" placeholder=" Google Pixel 3" value="' + phone_used + '">'; inlineQty += '</div></div></div></div>'; //Login email used section inlineQty += '<div class="form-group container login_email_used_section ' + is_customer_issue_hide + '">'; inlineQty += '<div class="row">'; inlineQty += '<div class="col-xs-12 login_email_div">'; inlineQty += '<div class="input-group">'; inlineQty += '<span class="input-group-addon" id="login_email">LOGIN EMAIL</span>'; inlineQty += '<input id="login_email_text" class="form-control" value="' + login_email_used + '"/>'; inlineQty += '</div></div></div></div>'; //Sender details name and phone number inlineQty += '<div class="form-group container ' + is_customer_issue_hide + ' sender_details_section ' + hide_class_section_mp_label + '">'; inlineQty += '<div class="row">'; inlineQty += '<div class="col-xs-6 sender_name_div">'; inlineQty += '<div class="input-group">'; inlineQty += '<span class="input-group-addon" id="sender_name">SENDER NAME</span>'; inlineQty += '<input id="sender_name_text" class="form-control" value="' + old_sender_name + '"/>'; inlineQty += '</div></div>'; inlineQty += '<div class="col-xs-6 sender_phone_div">'; inlineQty += '<div class="input-group">'; inlineQty += '<span class="input-group-addon" id="sender_phone">SENDER PHONE</span>'; inlineQty += '<input id="sender_phone_text" class="form-control" value="' + old_sender_phone + '"/>'; inlineQty += '</div></div></div></div>'; return inlineQty; } /** * The multiselect TOLL issues dropdown * @param {Array} list_toll_issues * @param {Array} list_resolved_toll_issues * @param {Number} status_value * @param {String} selector_type * @return {String} inlineQty */ function tollIssuesSection(list_toll_issues, list_resolved_toll_issues, status_value, selector_type) { // TOLL Issues var has_toll_issues = (!isNullorEmpty(list_toll_issues)); var toll_issues_columns = new Array(); toll_issues_columns[0] = search.createColumn({ name: 'name' }); toll_issues_columns[1] = search.createColumn({ name: 'internalId' }); var tollIssuesResultSet = search.create({ type: 'customlist_cust_prod_stock_toll_issues', columns: toll_issues_columns }); if (!isTicketNotClosed(status_value) || selector_type != 'barcode_number') { var inlineQty = '<div class="form-group container toll_issues_section hide">'; } else { var inlineQty = '<div class="form-group container toll_issues_section">'; } inlineQty += '<div class="row">'; inlineQty += '<div class="col-xs-12 toll_issues">'; inlineQty += '<div class="input-group"><span class="input-group-addon" id="toll_issues_text">TOLL ISSUES<span class="mandatory">*</span></span>'; inlineQty += '<select multiple id="toll_issues" class="form-control toll_issues" size="' + tollIssuesResultSet.length + '">'; tollIssuesResultSet.run().each(function (tollIssueResult) { var issue_name = tollIssueResult.getValue('name'); var issue_id = tollIssueResult.getValue('internalId'); var selected = false; if (has_toll_issues) { selected = (list_toll_issues.indexOf(issue_id) !== -1); } if (selected) { inlineQty += '<option value="' + issue_id + '" selected>' + issue_name + '</option>'; } else { inlineQty += '<option value="' + issue_id + '">' + issue_name + '</option>'; } return true; }); inlineQty += '</select>'; inlineQty += '</div></div></div></div>'; // Resolved TOLL Issues log.debug({ title: 'list_resolved_toll_issues : ', details: list_resolved_toll_issues }); var has_resolved_toll_issues = (!isNullorEmpty(list_resolved_toll_issues)); if (has_resolved_toll_issues) { var text_resolved_toll_issues = ''; tollIssuesResultSet.run().each(function (tollIssueResult) { var issue_name = tollIssueResult.getValue('name'); var issue_id = tollIssueResult.getValue('internalId'); if (list_resolved_toll_issues.indexOf(issue_id) !== -1) { text_resolved_toll_issues += issue_name + '\n'; } return true; }); log.debug({ title: 'text_resolved_toll_issues : ', details: text_resolved_toll_issues }); inlineQty += '<div class="form-group container resolved_toll_issues_section">'; inlineQty += '<div class="row">'; inlineQty += '<div class="col-xs-12 resolved_toll_issues">'; inlineQty += '<div class="input-group">'; inlineQty += '<span class="input-group-addon" id="resolved_toll_issues_text">RESOLVED TOLL ISSUES</span>'; inlineQty += '<textarea id="resolved_toll_issues" class="form-control resolved_toll_issues" rows="' + list_resolved_toll_issues.length + '" disabled>' + text_resolved_toll_issues.trim() + '</textarea>'; inlineQty += '</div></div></div></div>'; } return inlineQty; }; /** * The multiselect MP Ticket issues dropdown * @param {Array} list_mp_ticket_issues * @param {Array} list_resolved_mp_ticket_issues * @param {Number} status_value * @param {String} selector_type * @return {String} inlineQty */ function mpTicketIssuesSection(list_mp_ticket_issues, list_resolved_mp_ticket_issues, status_value, selector_type) { // MP Ticket Issues var has_mp_ticket_issues = !isNullorEmpty(list_mp_ticket_issues); var disabled_mp_issue_field = (isTicketNotClosed(status_value)) ? '' : 'disabled'; log.debug({ title: 'has_mp_ticket_issues : ', details: has_mp_ticket_issues }); if (has_mp_ticket_issues && status_value != 3) { // The MP Ticket issue section is displayed if the status is 'Closed - Unallocated' (status_value == 8) var inlineQty = '<div class="form-group container mp_issues_section">'; } else { var inlineQty = '<div class="form-group container mp_issues_section hide">'; } inlineQty += '<div class="row">'; inlineQty += '<div class="col-xs-12 mp_issues">'; var mp_ticket_issues_columns = new Array(); mp_ticket_issues_columns[0] = search.createColumn({ name: 'name' }); mp_ticket_issues_columns[1] = search.createColumn({ name: 'internalId' }); var mpTicketIssuesResultSet = search.create({ type: 'customlist_mp_ticket_issues', columns: mp_ticket_issues_columns }); inlineQty += '<div class="input-group">' inlineQty += '<span class="input-group-addon" id="mp_issues_text">MP ISSUES<span class="mandatory hide">*</span></span>'; inlineQty += '<select multiple id="mp_issues" class="form-control mp_issues" size="' + mpTicketIssuesResultSet.length + '" ' + disabled_mp_issue_field + '>'; mpTicketIssuesResultSet.run().each(function (mpTicketIssueResult) { var mp_issue_name = mpTicketIssueResult.getValue('name'); var mp_issue_id = mpTicketIssueResult.getValue('internalId'); var selected = false; if (has_mp_ticket_issues) { selected = (list_mp_ticket_issues.indexOf(mp_issue_id) !== -1); } var show_option = (selector_type == 'barcode_number' || (selector_type == 'invoice_number' && mp_issue_id == 4) || (selector_type == "customer_issue")); var selected_option = (selected) ? 'selected' : ''; if (show_option) { inlineQty += '<option value="' + mp_issue_id + '" ' + selected_option + '> ' + mp_issue_name + '</option > '; } return true; }); inlineQty += '</select>'; inlineQty += '</div></div></div></div>'; // Resolved MP Ticket Issues var has_resolved_mp_ticket_issues = !isNullorEmpty(list_resolved_mp_ticket_issues); if (has_resolved_mp_ticket_issues && selector_type != "customer_issue") { var text_resolved_mp_ticket_issues = ''; mpTicketIssuesResultSet.run().each(function (mpTicketIssueResult) { var mp_issue_name = mpTicketIssueResult.getValue('name'); var mp_issue_id = mpTicketIssueResult.getValue('internalId'); if (list_resolved_mp_ticket_issues.indexOf(mp_issue_id) !== -1) { text_resolved_mp_ticket_issues += mp_issue_name + '\n'; } return true; }); inlineQty += '<div class="form-group container resolved_mp_issues_section">'; inlineQty += '<div class="row">'; inlineQty += '<div class="col-xs-12 resolved_mp_issues">'; inlineQty += '<div class="input-group">'; inlineQty += '<span class="input-group-addon" id="resolved_mp_issues_text">RESOLVED MP ISSUES</span>'; inlineQty += '<textarea id="resolved_mp_issues" class="form-control resolved_mp_issues" rows="' + list_resolved_mp_ticket_issues.length + '" disabled>' + text_resolved_mp_ticket_issues.trim() + '</textarea>'; inlineQty += '</div></div></div></div>'; } return inlineQty; } /** * The multiselect Invoice issues dropdown * @param {Array} list_invoice_issues * @param {Array} list_resolved_invoice_issues * @param {Number} status_value * @param {String} selector_type * @return {String} inlineQty */ function invoiceIssuesSection(list_invoice_issues, list_resolved_invoice_issues, status_value, selector_type) { var has_invoice_issues = (!isNullorEmpty(list_invoice_issues)); var invoice_issues_columns = new Array(); invoice_issues_columns[0] = search.createColumn({ name: 'name' }); // Might need to be changed invoice_issues_columns[1] = search.createColumn({ name: 'internalId' }); // Might need to be changed var invoiceIssuesResultSet = search.create({ type: 'customlist_invoice_issues', columns: invoice_issues_columns }); if (!isTicketNotClosed(status_value) || selector_type != 'invoice_number') { var inlineQty = '<div class="form-group container invoice_issues_section hide">'; } else { var inlineQty = '<div class="form-group container invoice_issues_section">'; } inlineQty += '<div class="row">'; inlineQty += '<div class="col-xs-12 invoice_issues">'; inlineQty += '<div class="input-group"><span class="input-group-addon" id="invoice_issues_text">INVOICE ISSUES<span class="mandatory">*</span></span>'; inlineQty += '<select multiple id="invoice_issues" class="form-control invoice_issues">'; invoiceIssuesResultSet.run().each(function (invoiceIssueResult) { var issue_name = invoiceIssueResult.getValue('name'); // Might need to be changed var issue_id = invoiceIssueResult.getValue('internalId'); // Might need to be changed var selected = false; if (has_invoice_issues) { selected = (list_invoice_issues.indexOf(issue_id) != -1); } if (selected) { inlineQty += '<option value="' + issue_id + '" selected>' + issue_name + '</option>'; } else { inlineQty += '<option value="' + issue_id + '">' + issue_name + '</option>'; } return true; }); inlineQty += '</select>'; inlineQty += '</div></div></div></div>'; // Resolved invoice Issues log.debug({ title: 'list_resolved_invoice_issues : ', details: list_resolved_invoice_issues }); var has_resolved_invoice_issues = (!isNullorEmpty(list_resolved_invoice_issues)); if (has_resolved_invoice_issues) { var text_resolved_invoice_issues = ''; invoiceIssuesResultSet.run().each(function (invoiceIssueResult) { var issue_name = invoiceIssueResult.getValue('name'); // Might need to be changed var issue_id = invoiceIssueResult.getValue('internalId'); // Might need to be changed if (list_resolved_invoice_issues.indexOf(issue_id) !== -1) { text_resolved_invoice_issues += issue_name + '\n'; } }); log.debug({ title: 'text_resolved_invoice_issues : ', details: text_resolved_invoice_issues }); inlineQty += '<div class="form-group container resolved_invoice_issues_section">'; inlineQty += '<div class="row">'; inlineQty += '<div class="col-xs-12 resolved_invoice_issues">'; inlineQty += '<div class="input-group">'; inlineQty += '<span class="input-group-addon" id="resolved_invoice_issues_text">RESOLVED INVOICE ISSUES</span>'; inlineQty += '<textarea id="resolved_invoice_issues" class="form-control resolved_invoice_issues" rows="' + list_resolved_invoice_issues.length + '" disabled>' + text_resolved_invoice_issues.trim() + '</textarea>'; inlineQty += '</div></div></div></div>'; } return inlineQty; } /** * @param {String} selector_type * @param {Number} status_value * @return {String} inlineQty */ function usernoteSection(selector_type, status_value) { var usernote_titles_columns = new Array(); usernote_titles_columns[0] = search.createColumn({ name: 'name' }); usernote_titles_columns[1] = search.createColumn({ name: 'internalId' }); var usernoteTitlesResultSet = search.create({ type: 'customlist_user_note_title', columns: usernote_titles_columns }); // Row Title if (selector_type == 'invoice_number' && isTicketNotClosed(status_value)) { var inlineQty = '<div class="form-group container user_note user_note_title_section">'; } else { var inlineQty = '<div class="form-group container user_note user_note_title_section hide">'; } inlineQty += '<div class="row">'; inlineQty += '<div class="col-xs-12 user_note_title_section">'; inlineQty += '<div class="input-group">'; inlineQty += '<span class="input-group-addon">TITLE<span class="mandatory">*</span></span>'; inlineQty += '<select id="user_note_title" class="form-control">'; usernoteTitlesResultSet.run().each(function (usernoteTitleResult) { var title_name = usernoteTitleResult.getValue('name'); var title_id = usernoteTitleResult.getValue('internalId'); if (title_id == 3) { inlineQty += '<option value="' + title_id + '" selected>' + title_name + '</option>'; } else { inlineQty += '<option value="' + title_id + '">' + title_name + '</option>'; } return true; }); inlineQty += '</select>'; inlineQty += '</div></div></div></div>'; // Row User Note Textarea if (selector_type == 'invoice_number' && isTicketNotClosed(status_value)) { inlineQty += '<div class="form-group container user_note user_note_textarea_section">'; } else { inlineQty += '<div class="form-group container user_note user_note_textarea_section hide">'; } inlineQty += '<div class="row">'; inlineQty += '<div class="col-xs-12 user_note_textarea">'; inlineQty += '<div class="input-group">'; inlineQty += '<span class="input-group-addon" id="user_note_textarea_text">USER NOTE<span class="mandatory hide">*</span></span>'; inlineQty += '<textarea id="user_note_textarea" class="form-control user_note_textarea" rows="3"></textarea>'; inlineQty += '</div></div></div></div>'; // User Note table if (selector_type == 'invoice_number') { inlineQty += '<div class="form-group container user_note user_note_section" style="font-size: small;">'; } else { inlineQty += '<div class="form-group container user_note user_note_section hide" style="font-size: small;">'; } inlineQty += '<div class="row">'; inlineQty += '<div class="col-xs-12 user_note_div">'; // Since the table is not displayed correctly when added through suitelet, // It is added with jQuery in the pageInit() function in the client script 'mp_cl_open_ticket.js'. inlineQty += '</div>'; inlineQty += '</div>'; inlineQty += '</div>'; return inlineQty; } /** * Used to pass the values of `date_from` and `date_to` between the scripts and to Netsuite for the records and the search. * @param {String} date_iso "2020-06-01" * @returns {String} date_netsuite "1/6/2020" */ function dateISOToNetsuite(date_iso) { var date_netsuite = ''; if (!isNullorEmpty(date_iso)) { var date_netsuite = format.format({ value: date_iso, type: format.Type.DATETIME }); } return date_netsuite; } /** * The free-from text area for comments. * @param {String} comment * @param {String} selector_type * @param {Number} status_value * @return {String} inlineQty */ function commentSection(comment, selector_type, status_value) { if (isNullorEmpty(comment)) { comment = ''; } else { comment += '\n'; } switch (selector_type) { case 'barcode_number': var inlineQty = '<div class="form-group container comment_section">'; break; case 'invoice_number': var inlineQty = '<div class="form-group container comment_section hide">'; break; case 'customer_issue': var inlineQty = '<div class="form-group container comment_section">'; break; } inlineQty += '<div class="row">'; inlineQty += '<div class="col-xs-12 comment">'; inlineQty += '<div class="input-group">'; inlineQty += '<span class="input-group-addon" id="comment_text">COMMENT<span class="mandatory hide">*</span></span>'; if (isTicketNotClosed(status_value)) { inlineQty += '<textarea id="comment" class="form-control comment" rows="9">' + comment + '</textarea>'; } else { inlineQty += '<textarea id="comment" class="form-control comment" rows="9" readonly>' + comment + '</textarea>'; } inlineQty += '</div></div></div></div>'; return inlineQty; } /** * The table that will display the differents tickets linked to the customer. * @return {String} inlineQty */ function dataTablePreview() { var inlineQty = '<div class="form-group container tickets_datatable_section">'; inlineQty += '<div class="row">'; inlineQty += '<div class="col-xs-12 heading2">'; inlineQty += '<h4><span style="background-color: #379E8F" class="label label-default col-xs-12">PREVIOUS TICKETS</span></h4>'; inlineQty += '</div></div></div>'; inlineQty += '<style>table#tickets-preview {font-size: 12px;text-align: center;border: none; background-color: #379E8F}.dataTables_wrapper {font-size: 12px;}table#tickets-preview th{background-color: #379E8F; text-align: center;}</style>'; inlineQty += '<table cellpadding="15" id="tickets-preview" class="table table-responsive table-striped customer tablesorter" cellspacing="0" style="width: 100%;">'; inlineQty += '<thead style="color: white;background-color: #379E8F;">'; inlineQty += '<tr class="text-center">'; inlineQty += '</tr>'; inlineQty += '</thead>'; inlineQty += '<tbody id="result_tickets"></tbody>'; inlineQty += '</table>'; return inlineQty; } /** * The inline HTML for the close ticket button or the reopen button, * and the submitter button at the bottom of the page. * @param {Number} ticket_id * @param {Number} status_value * @return {String} inlineQty */ function closeReopenSubmitTicketButton(ticket_id, status_value) { var inlineQty = '<div class="form-group container close_reopen_submit_ticket_section">'; inlineQty += '<div class="row">'; log.debug({ title: 'status_value', details: status_value }); log.debug({ title: 'ticket_id', details: ticket_id }); if (isTicketNotClosed(status_value)) { if (!isNullorEmpty(ticket_id)) { inlineQty += '<div class="col-xs-2 close_ticket">'; inlineQty += '<input type="button" value="CLOSE TICKET" style="background-color: #FBEA51; border: 3px solid #379E8F; color: #379E8F; font-weight: 700" class="form-control btn btn-default" id="close_ticket" onclick="closeTicket()"/>'; inlineQty += '</div>'; inlineQty += '<div class="col-xs-3 close_ticket_lost">'; inlineQty += '<input type="button" value="CLOSE TICKET - LOST ITEM" style="background-color: #FBEA51; border: 3px solid #379E8F; color: #379E8F; font-weight: 700" class="form-control btn btn-default" id="close_ticket_lost" onclick="closeTicketLost()"/>'; inlineQty += '</div>'; if (userId == 409635 || userId == 696992 || userId == 766498) { inlineQty += '<div class="col-xs-3 close_unallocated_ticket hide">'; inlineQty += '<input type="button" value="CLOSE UNALLOCATED TICKET" style="background-color: #FBEA51; border: 3px solid #379E8F; color: #379E8F; font-weight: 700" class="form-control btn btn-default" id="close_unallocated_ticket" onclick="closeUnallocatedTicket()" />'; inlineQty += '</div>'; } } inlineQty += '<div class="col-xs-2 submitter">'; inlineQty += '<input type="button" style="background-color: #FBEA51; border: 3px solid #379E8F; color: #379E8F; font-weight: 700" value="UPDATE TICKET" class="form-control btn btn-primary" id="submit_ticket" />'; inlineQty += '</div>'; if (isNullorEmpty(ticket_id)) { inlineQty += '<div class="col-xs-3 open_and_new_ticket_btn">'; inlineQty += '<input type="button" style="background-color: #FBEA51; border: 3px solid #379E8F; color: #379E8F; font-weight: 700" value="OPEN AND NEW TICKET" class="form-control btn btn-primary" id="open_and_new_ticket_btn" />'; inlineQty += '</div>'; } inlineQty += '<style>.escalate:hover {box-shadow: 0 12px 16px 0 rgba(0,0,0,0.24), 0 17px 50px 0 rgba(0,0,0,0.19)}</style>'; inlineQty += '<div class="col-xs-2 escalate">'; inlineQty += '<input type="button" style="background-color: #FBEA51; border: 3px solid #379E8F; color: #379E8F; font-weight: 700" value="ESCALATE" class="form-control btn btn-default" id="escalate" onclick="onEscalate()"/>'; inlineQty += '</div>'; } else { inlineQty += '<div class="col-xs-2 col-xs-offset-2 reopen_ticket">'; inlineQty += '<input type="button" style="background-color: #FBEA51; border: 3px solid #379E8F; color: #379E8F; font-weight: 700" value="REOPEN TICKET" class="form-control btn btn-primary" id="reopen_ticket" />'; inlineQty += '</div>'; } inlineQty += '<div class="col-xs-2 cancel">'; inlineQty += '<input type="button" style="background-color: #FBEA51; border: 3px solid #379E8F; color: #379E8F; font-weight: 700" value="CANCEL" class="form-control btn btn-default" id="cancel" onclick="onCancel()"/>'; inlineQty += '</div>'; inlineQty += '</div></div>'; return inlineQty; } function Ownerjava2jsArray(javaArray) { var jsArray = new Array; if (!isNullorEmpty(javaArray)) { javaArray.forEach(function (javaValue) { var jsValue = parseInt(javaValue); jsArray.push(jsValue); }) } return jsArray; } /** * The output of .getFieldValues is a java String Array. * We want to convert it to a javaScript Array in order to read its values. * @param {Ljava.lang.String} javaArray * @return {Array} jsArray */ function java2jsArray(javaArray) { var jsArray = new Array; if (!isNullorEmpty(javaArray)) { javaArray.forEach(function (javaValue) { var jsValue = javaValue.toString(); jsArray.push(jsValue); }) } return jsArray; } /** * Parse the objects in an array, and returns an object based on the value of one of its keys. * With ES6, this function would simply be `array.find(obj => obj[key] == value)` * @param {Array} array * @param {String} key * @param {*} value * @returns {Object} */ function findObjectByKey(array, key, value) { for (var i = 0; i < array.length; i++) { if (array[i][key] === value) { return array[i]; } } return null; } /** * Returns whether a ticket is closed or not based on its status value. * @param {Number} status_value * @returns {Boolean} is_ticket_closed */ function isTicketNotClosed(status_value) { var is_ticket_not_closed = ((status_value != 3) && (status_value != 8) && (status_value != 15)) ? true : false; return is_ticket_not_closed; } function escalateButton(status) { if (status < 11) { return 'Escalate to 1st Escalation'; } else if (status == 11) { return 'Escalate to 2nd Escalation'; } else if (status == 12) { return 'Escalate to 3rd Escalation'; } else if (status == 13) { return 'Escalate to Final Escalation'; } else { return 'Escalate'; } } /** * Whether the user is from the finance team, * or a Data Systems Co-ordinator, MailPlus Administration or Administrator user. * @param {Number} userRole * @returns {Boolean} */ function isFinanceRole(userRole) { // 1001, 1031 and 1023 are finance roles // 1032 is the Data Systems Co-ordinator role (to be deleted in prod) // 1006 is the Mail Plus Administration role. // 3 is the Administrator role. return ((userRole == 1001 || userRole == 1031 || userRole == 1023) || ((userRole == 1032) || (userRole == 1006) || (userRole == 3))); } function isNullorEmpty(strVal) { return (strVal == null || strVal == '' || strVal == 'null' || strVal == undefined || strVal == 'undefined' || strVal == '- None -'); } return { onRequest: onRequest }; });
/** * Quotes Scheduled Script * * @NApiVersion 2.x * @NScriptType ScheduledScript * @author trungpv <trung@lexor.com> */ define(['N/search', '/SuiteScripts/Module/SalesFlow/Main'], function(search, salesFlow) { /* VARS */ /** * execute * @param {*} context */ function execute(context) { try { var listLeads = search.create({ type: search.Type.ESTIMATE, // filters: [ // { // name: 'entitystatus', // operator: search.Operator.ISNOT, // values: [14, 16] // } // ], columns: ['internalid', 'custbody_expiration_date', 'entity', 'entitystatus'] }); listLeads.run().each(function(item) { var expirationDate = item.getValue('custbody_expiration_date'); var entity = item.getValue('entity'); var opportunity = item.getValue('opportunity'); var entitystatus = item.getValue('entitystatus'); if (entitystatus != '14' && entitystatus != '13') { var isExpired = isToday(new Date(expirationDate)); if (isExpired) { salesFlow.Q.changeStatusToClosedLostById(item.id); if (opportunity) { salesFlow.O.changeStatusToClosedLostById(opportunity); } salesFlow.LPC.changeStatusLeadUnqualifiedById(entity); } } return true; }); } catch (error) { log.error({ title: 'ScheduledScript', details: error }); } } /** * Is Today * @param {*} date */ function isToday(date) { const today = new Date(); return ( date.getDate() == today.getDate() && date.getMonth() == today.getMonth() && date.getFullYear() == today.getFullYear() ); } return { execute: execute }; });
481
[{"tag": "EMAIL", "value": "trung@lexor.com", "start": 106, "end": 121}]
true
1
/** * Quotes Scheduled Script * * @NApiVersion 2.x * @NScriptType ScheduledScript * @author trungpv <kenaa@example.com> */ define(['N/search', '/SuiteScripts/Module/SalesFlow/Main'], function(search, salesFlow) { /* VARS */ /** * execute * @param {*} context */ function execute(context) { try { var listLeads = search.create({ type: search.Type.ESTIMATE, // filters: [ // { // name: 'entitystatus', // operator: search.Operator.ISNOT, // values: [14, 16] // } // ], columns: ['internalid', 'custbody_expiration_date', 'entity', 'entitystatus'] }); listLeads.run().each(function(item) { var expirationDate = item.getValue('custbody_expiration_date'); var entity = item.getValue('entity'); var opportunity = item.getValue('opportunity'); var entitystatus = item.getValue('entitystatus'); if (entitystatus != '14' && entitystatus != '13') { var isExpired = isToday(new Date(expirationDate)); if (isExpired) { salesFlow.Q.changeStatusToClosedLostById(item.id); if (opportunity) { salesFlow.O.changeStatusToClosedLostById(opportunity); } salesFlow.LPC.changeStatusLeadUnqualifiedById(entity); } } return true; }); } catch (error) { log.error({ title: 'ScheduledScript', details: error }); } } /** * Is Today * @param {*} date */ function isToday(date) { const today = new Date(); return ( date.getDate() == today.getDate() && date.getMonth() == today.getMonth() && date.getFullYear() == today.getFullYear() ); } return { execute: execute }; });
true
/** * Quotes Scheduled Script * * @NApiVersion 2.x * @NScriptType ScheduledScript * @author trungpv <PI:EMAIL:kenaa@example.comEND_PI> */ define(['N/search', '/SuiteScripts/Module/SalesFlow/Main'], function(search, salesFlow) { /* VARS */ /** * execute * @param {*} context */ function execute(context) { try { var listLeads = search.create({ type: search.Type.ESTIMATE, // filters: [ // { // name: 'entitystatus', // operator: search.Operator.ISNOT, // values: [14, 16] // } // ], columns: ['internalid', 'custbody_expiration_date', 'entity', 'entitystatus'] }); listLeads.run().each(function(item) { var expirationDate = item.getValue('custbody_expiration_date'); var entity = item.getValue('entity'); var opportunity = item.getValue('opportunity'); var entitystatus = item.getValue('entitystatus'); if (entitystatus != '14' && entitystatus != '13') { var isExpired = isToday(new Date(expirationDate)); if (isExpired) { salesFlow.Q.changeStatusToClosedLostById(item.id); if (opportunity) { salesFlow.O.changeStatusToClosedLostById(opportunity); } salesFlow.LPC.changeStatusLeadUnqualifiedById(entity); } } return true; }); } catch (error) { log.error({ title: 'ScheduledScript', details: error }); } } /** * Is Today * @param {*} date */ function isToday(date) { const today = new Date(); return ( date.getDate() == today.getDate() && date.getMonth() == today.getMonth() && date.getFullYear() == today.getFullYear() ); } return { execute: execute }; });
/** * * @NApiVersion 2.0 * @NScriptType Suitelet * * Description: * @Last Modified by: Sruti Desai * */ define(['N/ui/serverWidget', 'N/email', 'N/runtime', 'N/search', 'N/record', 'N/https', 'N/log', 'N/redirect', 'N/format', 'N/url'], function (ui, email, runtime, search, record, https, log, redirect, format, url) { var baseURL = 'https://1048144.app.netsuite.com'; if (runtime.envType == "SANDBOX") { baseURL = 'https://1048144-sb3.app.netsuite.com'; } var zee = 0; var role = runtime.getCurrentUser().role; if (role == 1000) { //Franchisee zee = runtime.getCurrentUser(); } function onRequest(context) { log.debug({ title: "context.request.method", details: context.request.method }); log.debug({ title: "context.request", details: context.request }); log.debug({ title: "context.request.parameters", details: context.request.parameters }); var first_name = context.request.parameters.first_name; var last_name = context.request.parameters.last_name; var form_email = context.request.parameters.email; var phone = context.request.parameters.phone_number; var company_name = context.request.parameters.company_name; var comments = context.request.parameters.comments; var ticketRecord = record.create({ type: 'customrecord_mp_ticket', }); //Mandatory Fields ticketRecord.setValue({ fieldId: 'custrecord_login_email', value: form_email }); //Enquiry Medium var medium_list = []; medium_list.push("3"); ticketRecord.setValue({ fieldId: 'custrecord_chat_enquiry_count', value: 1 }); ticketRecord.setValue({ fieldId: 'custrecord_enquiry_count', value: 1 }); ticketRecord.setValue({ fieldId: 'custrecord_enquiry_medium', value: medium_list }); ticketRecord.setValue({ fieldId: 'custrecord_enquiry_status', value: 1 }); //Status ticketRecord.setValue({ fieldId: 'custrecord_ticket_status', value: 1 }); //Owner ticketRecord.setValue({ fieldId: 'custrecord_creator', value: 112209 }); ticketRecord.setValue({ fieldId: 'custrecord_owner', value: [1706027] }); //Other fields ticketRecord.setValue({ fieldId: 'custrecord_email_sent', value: false }); ticketRecord.setValue({ fieldId: 'custrecord_date_escalated_it', value: new Date() }); ticketRecord.setValue({ fieldId: 'altname', value: 'Customer Portal' }); ticketRecord.setValue({ fieldId: 'custrecord_mp_ticket_issue', value: 9 }); ticketRecord.setValue({ fieldId: 'custrecord_customer_issue', value: "Customer Portal" }); //Comments if (!isNullorEmpty(comments)) { ticketRecord.setValue({ fieldId: 'custrecord_comment', value: comments }); } //Save Ticket var ticket_id = ticketRecord.save({ enableSourcing: true, ignoreMandatoryFields: true }); log.debug({ title: 'ticket_id', details: ticket_id }); //User Note var ticketRecord = record.load({ type: 'customrecord_mp_ticket', id: ticket_id, }); //Usernote of information user provides var userNote = record.create({ type: record.Type.NOTE, isDynamic: true, }); var custparam_params = new Object(); custparam_params['ticket_id'] = parseInt(ticket_id); custparam_params['selector_number'] = 'Customer Portal'; custparam_params['selector_type'] = "customer_issue"; var url = "https://1048144.app.netsuite.com/app/site/hosting/scriptlet.nl?script=1243&deploy=1&compid=1048144&"; var ticket_url = url + "&custparam_params=" + encodeURIComponent(JSON.stringify(custparam_params)); var note = 'Ticket number: MPSD' + ticket_id; note += '\nCompany Name: ' + company_name; note += '\nFirst Name: ' + first_name; note += '\nLast Name: ' + last_name; note += '\nLogin Email: ' + form_email; note += '\nPhone: ' + phone; note += '\nDescription: ' + comments; // Record Type i.e MP Ticket userNote.setValue({ fieldId: 'recordtype', value: 1042 }); // Record ID userNote.setValue({ fieldId: 'record', value: ticket_id }); //Title userNote.setValue({ fieldId: 'title', value: 'MailPlus Customer - New Portal Ticket Information' }); //Memo userNote.setValue({ fieldId: 'note', value: note }); userNote.save({ enableSourcing: true, ignoreMandatoryFields: true }); log.debug({ title: 'User note created', }) //Send Acknowledgement Email sendCustomerTicketEmail('MailPlus [MPSD' + ticket_id + '] - Thank you for your IT request - Customer Portal', [form_email], 119, ''); //Send Email to Rianne/Ankith // email.send({ // author: 112209, // body: note, // recipients: ["rianne.mansell@mailplus.com.au"], // subject: 'MPSD' + ticket_id + ' - New Customer Issue Ticket', // cc: ["ankith.ravindran@mailplus.com.au"], // }); var body = 'Ticket number: ' + '<a href="' + ticket_url + '"> MPSD' + ticket_id + '</a><br>'; body += 'Company Name: ' + company_name + '<br>'; body += 'First Name: ' + first_name + '<br>'; body += 'Last Name: ' + last_name + '<br>'; body += 'Login Email: ' + form_email + '<br>'; body += 'Phone: ' + phone + '<br>'; body += 'Description: ' + comments + '<br>'; // email.send({ // author: 112209, // body: body, // recipients: ["rianne.mansell@mailplus.com.au", "ankith.ravindran@mailplus.com.au", "sruti.desai@mailplus.com.au"], // subject: 'MPSD' + ticket_id + ' - New Customer Issue Ticket', // }); // // Send Email to Rianne/Ankith email.send({ author: 112209, body: note, recipients: ["laura.busse@mailplus.com.au"], subject: 'MPSD' + ticket_id + ' - New Customer Issue Ticket', cc: ["ankith.ravindran@mailplus.com.au"] }); log.debug({ title: 'Sent acknowledgement email && email to IT' }); } /** * Function to sent emails when a customer associated ticket is opened */ function sendCustomerTicketEmail(subject, recipients, template, customer_id) { var sales_rep = encodeURIComponent(runtime.getCurrentUser().name); var userid = encodeURIComponent(runtime.getCurrentUser().id); var suiteletUrl = url.resolveScript({ scriptId: 'customscript_merge_email', deploymentId: 'customdeploy_merge_email', returnExternalUrl: true }); suiteletUrl += '&rectype=customer&template='; suiteletUrl += template + '&recid=' + customer_id + '&salesrep=' + sales_rep + '&dear=' + '' + '&contactid=' + null + '&userid=' + userid; log.debug({ title: 'suiteletUrl', details: suiteletUrl }); var response = https.get({ url: suiteletUrl }); var emailHtml = response.body; if (!isNullorEmpty(customer_id)) { email.send({ author: 112209, body: emailHtml, recipients: recipients, subject: subject, relatedRecords: { entityId: customer_id } }); } else { email.send({ author: 112209, body: emailHtml, recipients: recipients, subject: subject, }); } } function isNullorEmpty(strVal) { return (strVal == null || strVal == '' || strVal == 'null' || strVal == undefined || strVal == 'undefined' || strVal == '- None -'); } return { onRequest: onRequest }; });
998
[{"tag": "EMAIL", "value": "rianne.mansell@mailplus.com.au", "start": 5671, "end": 5701}, {"tag": "EMAIL", "value": "ankith.ravindran@mailplus.com.au", "start": 5811, "end": 5843}, {"tag": "EMAIL", "value": "rianne.mansell@mailplus.com.au", "start": 6440, "end": 6470}, {"tag": "EMAIL", "value": "ankith.ravindran@mailplus.com.au", "start": 6474, "end": 6506}, {"tag": "EMAIL", "value": "sruti.desai@mailplus.com.au", "start": 6510, "end": 6537}, {"tag": "EMAIL", "value": "laura.busse@mailplus.com.au", "start": 6815, "end": 6842}, {"tag": "EMAIL", "value": "ankith.ravindran@mailplus.com.au", "start": 6946, "end": 6978}]
true
7
/** * * @NApiVersion 2.0 * @NScriptType Suitelet * * Description: * @Last Modified by: Sruti Desai * */ define(['N/ui/serverWidget', 'N/email', 'N/runtime', 'N/search', 'N/record', 'N/https', 'N/log', 'N/redirect', 'N/format', 'N/url'], function (ui, email, runtime, search, record, https, log, redirect, format, url) { var baseURL = 'https://1048144.app.netsuite.com'; if (runtime.envType == "SANDBOX") { baseURL = 'https://1048144-sb3.app.netsuite.com'; } var zee = 0; var role = runtime.getCurrentUser().role; if (role == 1000) { //Franchisee zee = runtime.getCurrentUser(); } function onRequest(context) { log.debug({ title: "context.request.method", details: context.request.method }); log.debug({ title: "context.request", details: context.request }); log.debug({ title: "context.request.parameters", details: context.request.parameters }); var first_name = context.request.parameters.first_name; var last_name = context.request.parameters.last_name; var form_email = context.request.parameters.email; var phone = context.request.parameters.phone_number; var company_name = context.request.parameters.company_name; var comments = context.request.parameters.comments; var ticketRecord = record.create({ type: 'customrecord_mp_ticket', }); //Mandatory Fields ticketRecord.setValue({ fieldId: 'custrecord_login_email', value: form_email }); //Enquiry Medium var medium_list = []; medium_list.push("3"); ticketRecord.setValue({ fieldId: 'custrecord_chat_enquiry_count', value: 1 }); ticketRecord.setValue({ fieldId: 'custrecord_enquiry_count', value: 1 }); ticketRecord.setValue({ fieldId: 'custrecord_enquiry_medium', value: medium_list }); ticketRecord.setValue({ fieldId: 'custrecord_enquiry_status', value: 1 }); //Status ticketRecord.setValue({ fieldId: 'custrecord_ticket_status', value: 1 }); //Owner ticketRecord.setValue({ fieldId: 'custrecord_creator', value: 112209 }); ticketRecord.setValue({ fieldId: 'custrecord_owner', value: [1706027] }); //Other fields ticketRecord.setValue({ fieldId: 'custrecord_email_sent', value: false }); ticketRecord.setValue({ fieldId: 'custrecord_date_escalated_it', value: new Date() }); ticketRecord.setValue({ fieldId: 'altname', value: 'Customer Portal' }); ticketRecord.setValue({ fieldId: 'custrecord_mp_ticket_issue', value: 9 }); ticketRecord.setValue({ fieldId: 'custrecord_customer_issue', value: "Customer Portal" }); //Comments if (!isNullorEmpty(comments)) { ticketRecord.setValue({ fieldId: 'custrecord_comment', value: comments }); } //Save Ticket var ticket_id = ticketRecord.save({ enableSourcing: true, ignoreMandatoryFields: true }); log.debug({ title: 'ticket_id', details: ticket_id }); //User Note var ticketRecord = record.load({ type: 'customrecord_mp_ticket', id: ticket_id, }); //Usernote of information user provides var userNote = record.create({ type: record.Type.NOTE, isDynamic: true, }); var custparam_params = new Object(); custparam_params['ticket_id'] = parseInt(ticket_id); custparam_params['selector_number'] = 'Customer Portal'; custparam_params['selector_type'] = "customer_issue"; var url = "https://1048144.app.netsuite.com/app/site/hosting/scriptlet.nl?script=1243&deploy=1&compid=1048144&"; var ticket_url = url + "&custparam_params=" + encodeURIComponent(JSON.stringify(custparam_params)); var note = 'Ticket number: MPSD' + ticket_id; note += '\nCompany Name: ' + company_name; note += '\nFirst Name: ' + first_name; note += '\nLast Name: ' + last_name; note += '\nLogin Email: ' + form_email; note += '\nPhone: ' + phone; note += '\nDescription: ' + comments; // Record Type i.e MP Ticket userNote.setValue({ fieldId: 'recordtype', value: 1042 }); // Record ID userNote.setValue({ fieldId: 'record', value: ticket_id }); //Title userNote.setValue({ fieldId: 'title', value: 'MailPlus Customer - New Portal Ticket Information' }); //Memo userNote.setValue({ fieldId: 'note', value: note }); userNote.save({ enableSourcing: true, ignoreMandatoryFields: true }); log.debug({ title: 'User note created', }) //Send Acknowledgement Email sendCustomerTicketEmail('MailPlus [MPSD' + ticket_id + '] - Thank you for your IT request - Customer Portal', [form_email], 119, ''); //Send Email to Rianne/Ankith // email.send({ // author: 112209, // body: note, // recipients: ["envkt@example.com"], // subject: 'MPSD' + ticket_id + ' - New Customer Issue Ticket', // cc: ["envkt@example.com"], // }); var body = 'Ticket number: ' + '<a href="' + ticket_url + '"> MPSD' + ticket_id + '</a><br>'; body += 'Company Name: ' + company_name + '<br>'; body += 'First Name: ' + first_name + '<br>'; body += 'Last Name: ' + last_name + '<br>'; body += 'Login Email: ' + form_email + '<br>'; body += 'Phone: ' + phone + '<br>'; body += 'Description: ' + comments + '<br>'; // email.send({ // author: 112209, // body: body, // recipients: ["envkt@example.com", "envkt@example.com", "ychag@example.com"], // subject: 'MPSD' + ticket_id + ' - New Customer Issue Ticket', // }); // // Send Email to Rianne/Ankith email.send({ author: 112209, body: note, recipients: ["hzdkv@example.com"], subject: 'MPSD' + ticket_id + ' - New Customer Issue Ticket', cc: ["envkt@example.com"] }); log.debug({ title: 'Sent acknowledgement email && email to IT' }); } /** * Function to sent emails when a customer associated ticket is opened */ function sendCustomerTicketEmail(subject, recipients, template, customer_id) { var sales_rep = encodeURIComponent(runtime.getCurrentUser().name); var userid = encodeURIComponent(runtime.getCurrentUser().id); var suiteletUrl = url.resolveScript({ scriptId: 'customscript_merge_email', deploymentId: 'customdeploy_merge_email', returnExternalUrl: true }); suiteletUrl += '&rectype=customer&template='; suiteletUrl += template + '&recid=' + customer_id + '&salesrep=' + sales_rep + '&dear=' + '' + '&contactid=' + null + '&userid=' + userid; log.debug({ title: 'suiteletUrl', details: suiteletUrl }); var response = https.get({ url: suiteletUrl }); var emailHtml = response.body; if (!isNullorEmpty(customer_id)) { email.send({ author: 112209, body: emailHtml, recipients: recipients, subject: subject, relatedRecords: { entityId: customer_id } }); } else { email.send({ author: 112209, body: emailHtml, recipients: recipients, subject: subject, }); } } function isNullorEmpty(strVal) { return (strVal == null || strVal == '' || strVal == 'null' || strVal == undefined || strVal == 'undefined' || strVal == '- None -'); } return { onRequest: onRequest }; });
true
/** * * @NApiVersion 2.0 * @NScriptType Suitelet * * Description: * @Last Modified by: Sruti Desai * */ define(['N/ui/serverWidget', 'N/email', 'N/runtime', 'N/search', 'N/record', 'N/https', 'N/log', 'N/redirect', 'N/format', 'N/url'], function (ui, email, runtime, search, record, https, log, redirect, format, url) { var baseURL = 'https://1048144.app.netsuite.com'; if (runtime.envType == "SANDBOX") { baseURL = 'https://1048144-sb3.app.netsuite.com'; } var zee = 0; var role = runtime.getCurrentUser().role; if (role == 1000) { //Franchisee zee = runtime.getCurrentUser(); } function onRequest(context) { log.debug({ title: "context.request.method", details: context.request.method }); log.debug({ title: "context.request", details: context.request }); log.debug({ title: "context.request.parameters", details: context.request.parameters }); var first_name = context.request.parameters.first_name; var last_name = context.request.parameters.last_name; var form_email = context.request.parameters.email; var phone = context.request.parameters.phone_number; var company_name = context.request.parameters.company_name; var comments = context.request.parameters.comments; var ticketRecord = record.create({ type: 'customrecord_mp_ticket', }); //Mandatory Fields ticketRecord.setValue({ fieldId: 'custrecord_login_email', value: form_email }); //Enquiry Medium var medium_list = []; medium_list.push("3"); ticketRecord.setValue({ fieldId: 'custrecord_chat_enquiry_count', value: 1 }); ticketRecord.setValue({ fieldId: 'custrecord_enquiry_count', value: 1 }); ticketRecord.setValue({ fieldId: 'custrecord_enquiry_medium', value: medium_list }); ticketRecord.setValue({ fieldId: 'custrecord_enquiry_status', value: 1 }); //Status ticketRecord.setValue({ fieldId: 'custrecord_ticket_status', value: 1 }); //Owner ticketRecord.setValue({ fieldId: 'custrecord_creator', value: 112209 }); ticketRecord.setValue({ fieldId: 'custrecord_owner', value: [1706027] }); //Other fields ticketRecord.setValue({ fieldId: 'custrecord_email_sent', value: false }); ticketRecord.setValue({ fieldId: 'custrecord_date_escalated_it', value: new Date() }); ticketRecord.setValue({ fieldId: 'altname', value: 'Customer Portal' }); ticketRecord.setValue({ fieldId: 'custrecord_mp_ticket_issue', value: 9 }); ticketRecord.setValue({ fieldId: 'custrecord_customer_issue', value: "Customer Portal" }); //Comments if (!isNullorEmpty(comments)) { ticketRecord.setValue({ fieldId: 'custrecord_comment', value: comments }); } //Save Ticket var ticket_id = ticketRecord.save({ enableSourcing: true, ignoreMandatoryFields: true }); log.debug({ title: 'ticket_id', details: ticket_id }); //User Note var ticketRecord = record.load({ type: 'customrecord_mp_ticket', id: ticket_id, }); //Usernote of information user provides var userNote = record.create({ type: record.Type.NOTE, isDynamic: true, }); var custparam_params = new Object(); custparam_params['ticket_id'] = parseInt(ticket_id); custparam_params['selector_number'] = 'Customer Portal'; custparam_params['selector_type'] = "customer_issue"; var url = "https://1048144.app.netsuite.com/app/site/hosting/scriptlet.nl?script=1243&deploy=1&compid=1048144&"; var ticket_url = url + "&custparam_params=" + encodeURIComponent(JSON.stringify(custparam_params)); var note = 'Ticket number: MPSD' + ticket_id; note += '\nCompany Name: ' + company_name; note += '\nFirst Name: ' + first_name; note += '\nLast Name: ' + last_name; note += '\nLogin Email: ' + form_email; note += '\nPhone: ' + phone; note += '\nDescription: ' + comments; // Record Type i.e MP Ticket userNote.setValue({ fieldId: 'recordtype', value: 1042 }); // Record ID userNote.setValue({ fieldId: 'record', value: ticket_id }); //Title userNote.setValue({ fieldId: 'title', value: 'MailPlus Customer - New Portal Ticket Information' }); //Memo userNote.setValue({ fieldId: 'note', value: note }); userNote.save({ enableSourcing: true, ignoreMandatoryFields: true }); log.debug({ title: 'User note created', }) //Send Acknowledgement Email sendCustomerTicketEmail('MailPlus [MPSD' + ticket_id + '] - Thank you for your IT request - Customer Portal', [form_email], 119, ''); //Send Email to Rianne/Ankith // email.send({ // author: 112209, // body: note, // recipients: ["PI:EMAIL:envkt@example.comEND_PI"], // subject: 'MPSD' + ticket_id + ' - New Customer Issue Ticket', // cc: ["PI:EMAIL:envkt@example.comEND_PI"], // }); var body = 'Ticket number: ' + '<a href="' + ticket_url + '"> MPSD' + ticket_id + '</a><br>'; body += 'Company Name: ' + company_name + '<br>'; body += 'First Name: ' + first_name + '<br>'; body += 'Last Name: ' + last_name + '<br>'; body += 'Login Email: ' + form_email + '<br>'; body += 'Phone: ' + phone + '<br>'; body += 'Description: ' + comments + '<br>'; // email.send({ // author: 112209, // body: body, // recipients: ["PI:EMAIL:envkt@example.comEND_PI", "PI:EMAIL:envkt@example.comEND_PI", "PI:EMAIL:ychag@example.comEND_PI"], // subject: 'MPSD' + ticket_id + ' - New Customer Issue Ticket', // }); // // Send Email to Rianne/Ankith email.send({ author: 112209, body: note, recipients: ["PI:EMAIL:hzdkv@example.comEND_PI"], subject: 'MPSD' + ticket_id + ' - New Customer Issue Ticket', cc: ["PI:EMAIL:envkt@example.comEND_PI"] }); log.debug({ title: 'Sent acknowledgement email && email to IT' }); } /** * Function to sent emails when a customer associated ticket is opened */ function sendCustomerTicketEmail(subject, recipients, template, customer_id) { var sales_rep = encodeURIComponent(runtime.getCurrentUser().name); var userid = encodeURIComponent(runtime.getCurrentUser().id); var suiteletUrl = url.resolveScript({ scriptId: 'customscript_merge_email', deploymentId: 'customdeploy_merge_email', returnExternalUrl: true }); suiteletUrl += '&rectype=customer&template='; suiteletUrl += template + '&recid=' + customer_id + '&salesrep=' + sales_rep + '&dear=' + '' + '&contactid=' + null + '&userid=' + userid; log.debug({ title: 'suiteletUrl', details: suiteletUrl }); var response = https.get({ url: suiteletUrl }); var emailHtml = response.body; if (!isNullorEmpty(customer_id)) { email.send({ author: 112209, body: emailHtml, recipients: recipients, subject: subject, relatedRecords: { entityId: customer_id } }); } else { email.send({ author: 112209, body: emailHtml, recipients: recipients, subject: subject, }); } } function isNullorEmpty(strVal) { return (strVal == null || strVal == '' || strVal == 'null' || strVal == undefined || strVal == 'undefined' || strVal == '- None -'); } return { onRequest: onRequest }; });
/** * @NApiVersion 2.0 * @NScriptType MapReduceScript */ define(['N/record', 'N/search', 'N/email', 'N/runtime'], /** * @param{record} record * @param{search} search */ function(record, search, email, runtime){ /** * Defines the function that is executed at the beginning of the map/reduce process and generates the input data. * @param {Object} inputContext * @param {boolean} inputContext.isRestarted - Indicates whether the current invocation of this function is the first * invocation (if true, the current invocation is not the first invocation and this function has been restarted) * @param {Object} inputContext.ObjectRef - Object that references the input data * @typedef {Object} ObjectRef * @property {string|number} ObjectRef.id - Internal ID of the record instance that contains the input data * @property {string} ObjectRef.type - Type of the record instance that contains the input data * @returns {Array|Object|Search|ObjectRef|File|Query} The input data to use in the map/reduce process * @since 2015.2 */ /*Global Variables*/ var departmentD; var classD; var locationD; function getInputData(inputContext){ var loadSearch = search.load({ id: 'customsearch_time_entry_to_post' }); return loadSearch; } /** * Defines the function that is executed when the map entry point is triggered. This entry point is triggered automatically * when the associated getInputData stage is complete. This function is applied to each key-value pair in the provided * context. * @param {Object} mapContext - Data collection containing the key-value pairs to process in the map stage. This parameter * is provided automatically based on the results of the getInputData stage. * @param {Iterator} mapContext.errors - Serialized errors that were thrown during previous attempts to execute the map * function on the current key-value pair * @param {number} mapContext.executionNo - Number of times the map function has been executed on the current key-value * pair * @param {boolean} mapContext.isRestarted - Indicates whether the current invocation of this function is the first * invocation (if true, the current invocation is not the first invocation and this function has been restarted) * @param {string} mapContext.key - Key to be processed during the map stage * @param {string} mapContext.value - Value to be processed during the map stage * @since 2015.2 */ function map(mapContext) { try { var accountCr = runtime.getCurrentScript().getParameter("custscript_proj_var_acct"); var currentUser = 239241; var currentUserEmail = 'rubykumari413@gmail.com' var data = JSON.parse(mapContext.value); //log.debug('data',data) var id = data.id; var empName = data.values.employee.value; var custName = data.values.customer.value; var jrnalMemo = data.values.memo; var hours = data.values.hours; log.debug('Time sheet enterted for - ',id) hours = ''+hours.split(':')[0]+'.'+hours.split(':')[1]+''; var timebillCheck = search.lookupFields({ type:'timebill', id: id, columns: ['isbillable'] }); var billCbk = timebillCheck['isbillable']; var transactionCheck = search.lookupFields({ type:'employee', id: empName, columns: ['subsidiary','department','class','location','custentity_laborcost_usd'] }); var subsidaryD = transactionCheck['subsidiary'][0].value; var subsidaryText = transactionCheck['subsidiary'][0].text; try{ departmentD = transactionCheck['department'][0].value; classD = transactionCheck['class'][0].value; locationD = transactionCheck['location'][0].value; }catch(e){ log.debug('e',e) } var labourCost = transactionCheck['custentity_laborcost_usd']; var finalAmount = (Number(Number(hours)*Number(labourCost))).toFixed(2); var finalLineMemo = 'Time Entry for '+subsidaryText+'; memo:'+jrnalMemo+''; var jobCheck = search.lookupFields({ type:'job', id: custName, columns: ['currency','projectexpensetype'] }); var lvCurrency = jobCheck['currency'][0].value; var accountDr = jobCheck['projectexpensetype'][0].value; if(accountDr == '1'){accountDr = 913;}else if(accountDr == '2'){accountDr = 914;}else if(accountDr == -3){accountDr = 885;}else{accountDr = 884;} /* //// @@@@@@@@@@@@ Account Map @@@@@@@@@@@ //// Direct Salary == 61190 Project Direct Salary (895/913) Indirect Salary == Project Indirect Salary (896/914) Overhead == Indirect Labor (885) Regular == Direct Labor (884) //// @@@@@@@@@@@@ Account Map END @@@@@@@@@@@ ////*/ //creating journal record journalRecordCreate = record.create({ type: 'journalentry', isDynamic: true }); journalRecordCreate.setValue({ fieldId : 'subsidiary', value : subsidaryD }); journalRecordCreate.setValue({ fieldId : 'currency', value : lvCurrency }); journalRecordCreate.setValue({ fieldId : 'trandate', value : new Date() }); journalRecordCreate.setValue({ fieldId : 'approved', value : true }); journalRecordCreate.setValue({ fieldId : 'timebillflag', value : 'T' }); journalRecordCreate.setValue({ fieldId : 'custbody_sr_time_track_link', value : id }); var type = 'debit'; addLineDataOnJournalRecord(finalLineMemo,accountDr,finalAmount,type); var type = 'credit'; addLineDataOnJournalRecord(finalLineMemo,accountCr,finalAmount,type); try{ if(billCbk == false || billCbk == 'F' || billCbk == ''){ var journalRecordId = journalRecordCreate.save({ enableSourcing: true, ignoreMandatoryFields: true }); log.debug('journalRecordId',journalRecordId) /*var rec = record.load({type:'timebill',id:id}); rec.setValue({fieldId:'transactionid',value:Number(journalRecordId)}); rec.setValue({fieldId:'posted',value:true}); var recordSubmit = rec.save()*/ var recordSubmit = record.submitFields({ type: 'timebill', id: id, values: { 'posted': 'T', 'transactionid':Number(journalRecordId) }, options: { enableSourcing: true, ignoreMandatoryFields : true } }); log.debug('recordSubmit',recordSubmit) }else{ log.debug('its charges') } }catch(journalRecordSubmitError){ record.submitFields({ type: 'timebill', id: id, values: { 'posted': 'F' } }); log.error({title:'Error in journal Creation: ', details:journalRecordSubmitError}); email.send({author: currentUser, recipients: currentUserEmail, subject: 'Error while submitting journal for Time sheet: '+id+'', body: 'Hi,\n Error is:\n '+journalRecordSubmitError+'' }); } }catch(e){ log.debug('Error', e); } } function addLineDataOnJournalRecord(memo,account,ammount,type){ if(ammount != '' && ammount != undefined || ammount != null){ if(account != '' && account != undefined){ if(type == 'credit'){ var line = journalRecordCreate.getLineCount({ sublistId: 'line' }); journalRecordCreate.selectLine({ sublistId: 'line', line: line }); journalRecordCreate.setCurrentSublistValue({ sublistId: 'line', fieldId: 'account', value: account }); journalRecordCreate.setCurrentSublistValue({ sublistId: 'line', fieldId: 'credit', value: ammount }); journalRecordCreate.setCurrentSublistValue({ sublistId: 'line', fieldId: 'memo', value: memo }); try{ journalRecordCreate.setCurrentSublistValue({ sublistId: 'line', fieldId: 'department', value: departmentD }); journalRecordCreate.setCurrentSublistValue({ sublistId: 'line', fieldId: 'class', value: classD }); journalRecordCreate.setCurrentSublistValue({ sublistId: 'line', fieldId: 'location', value: locationD }); }catch(e){ log.debug("issue with department") } journalRecordCreate.commitLine({ sublistId: 'line'}); }else if(type == 'debit'){ var line = journalRecordCreate.getLineCount({ sublistId: 'line' }); journalRecordCreate.selectLine({ sublistId: 'line', line: line }); journalRecordCreate.setCurrentSublistValue({ sublistId: 'line', fieldId: 'account', value: account }); journalRecordCreate.setCurrentSublistValue({ sublistId: 'line', fieldId: 'debit', value: ammount }); journalRecordCreate.setCurrentSublistValue({ sublistId: 'line', fieldId: 'memo', value: memo }); try{ journalRecordCreate.setCurrentSublistValue({ sublistId: 'line', fieldId: 'department', value: departmentD }); journalRecordCreate.setCurrentSublistValue({ sublistId: 'line', fieldId: 'class', value: classD }); journalRecordCreate.setCurrentSublistValue({ sublistId: 'line', fieldId: 'location', value: locationD }); }catch(e){ log.debug("issue with department") } journalRecordCreate.commitLine({sublistId: 'line'}); } } } } /** * Defines the function that is executed when the reduce entry point is triggered. This entry point is triggered * automatically when the associated map stage is complete. This function is applied to each group in the provided context. * @param {Object} reduceContext - Data collection containing the groups to process in the reduce stage. This parameter is * provided automatically based on the results of the map stage. * @param {Iterator} reduceContext.errors - Serialized errors that were thrown during previous attempts to execute the * reduce function on the current group * @param {number} reduceContext.executionNo - Number of times the reduce function has been executed on the current group * @param {boolean} reduceContext.isRestarted - Indicates whether the current invocation of this function is the first * invocation (if true, the current invocation is not the first invocation and this function has been restarted) * @param {string} reduceContext.key - Key to be processed during the reduce stage * @param {List<String>} reduceContext.values - All values associated with a unique key that was passed to the reduce stage * for processing * @since 2015.2 */ function reduce (reduceContext) { } /** * Defines the function that is executed when the summarize entry point is triggered. This entry point is triggered * automatically when the associated reduce stage is complete. This function is applied to the entire result set. * @param {Object} summaryContext - Statistics about the execution of a map/reduce script * @param {number} summaryContext.concurrency - Maximum concurrency number when executing parallel tasks for the map/reduce * script * @param {Date} summaryContext.dateCreated - The date and time when the map/reduce script began running * @param {boolean} summaryContext.isRestarted - Indicates whether the current invocation of this function is the first * invocation (if true, the current invocation is not the first invocation and this function has been restarted) * @param {Iterator} summaryContext.output - Serialized keys and values that were saved as output during the reduce stage * @param {number} summaryContext.seconds - Total seconds elapsed when running the map/reduce script * @param {number} summaryContext.usage - Total number of governance usage units consumed when running the map/reduce * script * @param {number} summaryContext.yields - Total number of yields when running the map/reduce script * @param {Object} summaryContext.inputSummary - Statistics about the input stage * @param {Object} summaryContext.mapSummary - Statistics about the map stage * @param {Object} summaryContext.reduceSummary - Statistics about the reduce stage * @since 2015.2 */ function summarize (summaryContext) { } return { getInputData:getInputData, map:map, summarize:summarize } });
1,012
[{"tag": "EMAIL", "value": "rubykumari413@gmail.com", "start": 2993, "end": 3016}]
true
1
/** * @NApiVersion 2.0 * @NScriptType MapReduceScript */ define(['N/record', 'N/search', 'N/email', 'N/runtime'], /** * @param{record} record * @param{search} search */ function(record, search, email, runtime){ /** * Defines the function that is executed at the beginning of the map/reduce process and generates the input data. * @param {Object} inputContext * @param {boolean} inputContext.isRestarted - Indicates whether the current invocation of this function is the first * invocation (if true, the current invocation is not the first invocation and this function has been restarted) * @param {Object} inputContext.ObjectRef - Object that references the input data * @typedef {Object} ObjectRef * @property {string|number} ObjectRef.id - Internal ID of the record instance that contains the input data * @property {string} ObjectRef.type - Type of the record instance that contains the input data * @returns {Array|Object|Search|ObjectRef|File|Query} The input data to use in the map/reduce process * @since 2015.2 */ /*Global Variables*/ var departmentD; var classD; var locationD; function getInputData(inputContext){ var loadSearch = search.load({ id: 'customsearch_time_entry_to_post' }); return loadSearch; } /** * Defines the function that is executed when the map entry point is triggered. This entry point is triggered automatically * when the associated getInputData stage is complete. This function is applied to each key-value pair in the provided * context. * @param {Object} mapContext - Data collection containing the key-value pairs to process in the map stage. This parameter * is provided automatically based on the results of the getInputData stage. * @param {Iterator} mapContext.errors - Serialized errors that were thrown during previous attempts to execute the map * function on the current key-value pair * @param {number} mapContext.executionNo - Number of times the map function has been executed on the current key-value * pair * @param {boolean} mapContext.isRestarted - Indicates whether the current invocation of this function is the first * invocation (if true, the current invocation is not the first invocation and this function has been restarted) * @param {string} mapContext.key - Key to be processed during the map stage * @param {string} mapContext.value - Value to be processed during the map stage * @since 2015.2 */ function map(mapContext) { try { var accountCr = runtime.getCurrentScript().getParameter("custscript_proj_var_acct"); var currentUser = 239241; var currentUserEmail = 'hzdkv@example.com' var data = JSON.parse(mapContext.value); //log.debug('data',data) var id = data.id; var empName = data.values.employee.value; var custName = data.values.customer.value; var jrnalMemo = data.values.memo; var hours = data.values.hours; log.debug('Time sheet enterted for - ',id) hours = ''+hours.split(':')[0]+'.'+hours.split(':')[1]+''; var timebillCheck = search.lookupFields({ type:'timebill', id: id, columns: ['isbillable'] }); var billCbk = timebillCheck['isbillable']; var transactionCheck = search.lookupFields({ type:'employee', id: empName, columns: ['subsidiary','department','class','location','custentity_laborcost_usd'] }); var subsidaryD = transactionCheck['subsidiary'][0].value; var subsidaryText = transactionCheck['subsidiary'][0].text; try{ departmentD = transactionCheck['department'][0].value; classD = transactionCheck['class'][0].value; locationD = transactionCheck['location'][0].value; }catch(e){ log.debug('e',e) } var labourCost = transactionCheck['custentity_laborcost_usd']; var finalAmount = (Number(Number(hours)*Number(labourCost))).toFixed(2); var finalLineMemo = 'Time Entry for '+subsidaryText+'; memo:'+jrnalMemo+''; var jobCheck = search.lookupFields({ type:'job', id: custName, columns: ['currency','projectexpensetype'] }); var lvCurrency = jobCheck['currency'][0].value; var accountDr = jobCheck['projectexpensetype'][0].value; if(accountDr == '1'){accountDr = 913;}else if(accountDr == '2'){accountDr = 914;}else if(accountDr == -3){accountDr = 885;}else{accountDr = 884;} /* //// @@@@@@@@@@@@ Account Map @@@@@@@@@@@ //// Direct Salary == 61190 Project Direct Salary (895/913) Indirect Salary == Project Indirect Salary (896/914) Overhead == Indirect Labor (885) Regular == Direct Labor (884) //// @@@@@@@@@@@@ Account Map END @@@@@@@@@@@ ////*/ //creating journal record journalRecordCreate = record.create({ type: 'journalentry', isDynamic: true }); journalRecordCreate.setValue({ fieldId : 'subsidiary', value : subsidaryD }); journalRecordCreate.setValue({ fieldId : 'currency', value : lvCurrency }); journalRecordCreate.setValue({ fieldId : 'trandate', value : new Date() }); journalRecordCreate.setValue({ fieldId : 'approved', value : true }); journalRecordCreate.setValue({ fieldId : 'timebillflag', value : 'T' }); journalRecordCreate.setValue({ fieldId : 'custbody_sr_time_track_link', value : id }); var type = 'debit'; addLineDataOnJournalRecord(finalLineMemo,accountDr,finalAmount,type); var type = 'credit'; addLineDataOnJournalRecord(finalLineMemo,accountCr,finalAmount,type); try{ if(billCbk == false || billCbk == 'F' || billCbk == ''){ var journalRecordId = journalRecordCreate.save({ enableSourcing: true, ignoreMandatoryFields: true }); log.debug('journalRecordId',journalRecordId) /*var rec = record.load({type:'timebill',id:id}); rec.setValue({fieldId:'transactionid',value:Number(journalRecordId)}); rec.setValue({fieldId:'posted',value:true}); var recordSubmit = rec.save()*/ var recordSubmit = record.submitFields({ type: 'timebill', id: id, values: { 'posted': 'T', 'transactionid':Number(journalRecordId) }, options: { enableSourcing: true, ignoreMandatoryFields : true } }); log.debug('recordSubmit',recordSubmit) }else{ log.debug('its charges') } }catch(journalRecordSubmitError){ record.submitFields({ type: 'timebill', id: id, values: { 'posted': 'F' } }); log.error({title:'Error in journal Creation: ', details:journalRecordSubmitError}); email.send({author: currentUser, recipients: currentUserEmail, subject: 'Error while submitting journal for Time sheet: '+id+'', body: 'Hi,\n Error is:\n '+journalRecordSubmitError+'' }); } }catch(e){ log.debug('Error', e); } } function addLineDataOnJournalRecord(memo,account,ammount,type){ if(ammount != '' && ammount != undefined || ammount != null){ if(account != '' && account != undefined){ if(type == 'credit'){ var line = journalRecordCreate.getLineCount({ sublistId: 'line' }); journalRecordCreate.selectLine({ sublistId: 'line', line: line }); journalRecordCreate.setCurrentSublistValue({ sublistId: 'line', fieldId: 'account', value: account }); journalRecordCreate.setCurrentSublistValue({ sublistId: 'line', fieldId: 'credit', value: ammount }); journalRecordCreate.setCurrentSublistValue({ sublistId: 'line', fieldId: 'memo', value: memo }); try{ journalRecordCreate.setCurrentSublistValue({ sublistId: 'line', fieldId: 'department', value: departmentD }); journalRecordCreate.setCurrentSublistValue({ sublistId: 'line', fieldId: 'class', value: classD }); journalRecordCreate.setCurrentSublistValue({ sublistId: 'line', fieldId: 'location', value: locationD }); }catch(e){ log.debug("issue with department") } journalRecordCreate.commitLine({ sublistId: 'line'}); }else if(type == 'debit'){ var line = journalRecordCreate.getLineCount({ sublistId: 'line' }); journalRecordCreate.selectLine({ sublistId: 'line', line: line }); journalRecordCreate.setCurrentSublistValue({ sublistId: 'line', fieldId: 'account', value: account }); journalRecordCreate.setCurrentSublistValue({ sublistId: 'line', fieldId: 'debit', value: ammount }); journalRecordCreate.setCurrentSublistValue({ sublistId: 'line', fieldId: 'memo', value: memo }); try{ journalRecordCreate.setCurrentSublistValue({ sublistId: 'line', fieldId: 'department', value: departmentD }); journalRecordCreate.setCurrentSublistValue({ sublistId: 'line', fieldId: 'class', value: classD }); journalRecordCreate.setCurrentSublistValue({ sublistId: 'line', fieldId: 'location', value: locationD }); }catch(e){ log.debug("issue with department") } journalRecordCreate.commitLine({sublistId: 'line'}); } } } } /** * Defines the function that is executed when the reduce entry point is triggered. This entry point is triggered * automatically when the associated map stage is complete. This function is applied to each group in the provided context. * @param {Object} reduceContext - Data collection containing the groups to process in the reduce stage. This parameter is * provided automatically based on the results of the map stage. * @param {Iterator} reduceContext.errors - Serialized errors that were thrown during previous attempts to execute the * reduce function on the current group * @param {number} reduceContext.executionNo - Number of times the reduce function has been executed on the current group * @param {boolean} reduceContext.isRestarted - Indicates whether the current invocation of this function is the first * invocation (if true, the current invocation is not the first invocation and this function has been restarted) * @param {string} reduceContext.key - Key to be processed during the reduce stage * @param {List<String>} reduceContext.values - All values associated with a unique key that was passed to the reduce stage * for processing * @since 2015.2 */ function reduce (reduceContext) { } /** * Defines the function that is executed when the summarize entry point is triggered. This entry point is triggered * automatically when the associated reduce stage is complete. This function is applied to the entire result set. * @param {Object} summaryContext - Statistics about the execution of a map/reduce script * @param {number} summaryContext.concurrency - Maximum concurrency number when executing parallel tasks for the map/reduce * script * @param {Date} summaryContext.dateCreated - The date and time when the map/reduce script began running * @param {boolean} summaryContext.isRestarted - Indicates whether the current invocation of this function is the first * invocation (if true, the current invocation is not the first invocation and this function has been restarted) * @param {Iterator} summaryContext.output - Serialized keys and values that were saved as output during the reduce stage * @param {number} summaryContext.seconds - Total seconds elapsed when running the map/reduce script * @param {number} summaryContext.usage - Total number of governance usage units consumed when running the map/reduce * script * @param {number} summaryContext.yields - Total number of yields when running the map/reduce script * @param {Object} summaryContext.inputSummary - Statistics about the input stage * @param {Object} summaryContext.mapSummary - Statistics about the map stage * @param {Object} summaryContext.reduceSummary - Statistics about the reduce stage * @since 2015.2 */ function summarize (summaryContext) { } return { getInputData:getInputData, map:map, summarize:summarize } });
true
/** * @NApiVersion 2.0 * @NScriptType MapReduceScript */ define(['N/record', 'N/search', 'N/email', 'N/runtime'], /** * @param{record} record * @param{search} search */ function(record, search, email, runtime){ /** * Defines the function that is executed at the beginning of the map/reduce process and generates the input data. * @param {Object} inputContext * @param {boolean} inputContext.isRestarted - Indicates whether the current invocation of this function is the first * invocation (if true, the current invocation is not the first invocation and this function has been restarted) * @param {Object} inputContext.ObjectRef - Object that references the input data * @typedef {Object} ObjectRef * @property {string|number} ObjectRef.id - Internal ID of the record instance that contains the input data * @property {string} ObjectRef.type - Type of the record instance that contains the input data * @returns {Array|Object|Search|ObjectRef|File|Query} The input data to use in the map/reduce process * @since 2015.2 */ /*Global Variables*/ var departmentD; var classD; var locationD; function getInputData(inputContext){ var loadSearch = search.load({ id: 'customsearch_time_entry_to_post' }); return loadSearch; } /** * Defines the function that is executed when the map entry point is triggered. This entry point is triggered automatically * when the associated getInputData stage is complete. This function is applied to each key-value pair in the provided * context. * @param {Object} mapContext - Data collection containing the key-value pairs to process in the map stage. This parameter * is provided automatically based on the results of the getInputData stage. * @param {Iterator} mapContext.errors - Serialized errors that were thrown during previous attempts to execute the map * function on the current key-value pair * @param {number} mapContext.executionNo - Number of times the map function has been executed on the current key-value * pair * @param {boolean} mapContext.isRestarted - Indicates whether the current invocation of this function is the first * invocation (if true, the current invocation is not the first invocation and this function has been restarted) * @param {string} mapContext.key - Key to be processed during the map stage * @param {string} mapContext.value - Value to be processed during the map stage * @since 2015.2 */ function map(mapContext) { try { var accountCr = runtime.getCurrentScript().getParameter("custscript_proj_var_acct"); var currentUser = 239241; var currentUserEmail = 'PI:EMAIL:hzdkv@example.comEND_PI' var data = JSON.parse(mapContext.value); //log.debug('data',data) var id = data.id; var empName = data.values.employee.value; var custName = data.values.customer.value; var jrnalMemo = data.values.memo; var hours = data.values.hours; log.debug('Time sheet enterted for - ',id) hours = ''+hours.split(':')[0]+'.'+hours.split(':')[1]+''; var timebillCheck = search.lookupFields({ type:'timebill', id: id, columns: ['isbillable'] }); var billCbk = timebillCheck['isbillable']; var transactionCheck = search.lookupFields({ type:'employee', id: empName, columns: ['subsidiary','department','class','location','custentity_laborcost_usd'] }); var subsidaryD = transactionCheck['subsidiary'][0].value; var subsidaryText = transactionCheck['subsidiary'][0].text; try{ departmentD = transactionCheck['department'][0].value; classD = transactionCheck['class'][0].value; locationD = transactionCheck['location'][0].value; }catch(e){ log.debug('e',e) } var labourCost = transactionCheck['custentity_laborcost_usd']; var finalAmount = (Number(Number(hours)*Number(labourCost))).toFixed(2); var finalLineMemo = 'Time Entry for '+subsidaryText+'; memo:'+jrnalMemo+''; var jobCheck = search.lookupFields({ type:'job', id: custName, columns: ['currency','projectexpensetype'] }); var lvCurrency = jobCheck['currency'][0].value; var accountDr = jobCheck['projectexpensetype'][0].value; if(accountDr == '1'){accountDr = 913;}else if(accountDr == '2'){accountDr = 914;}else if(accountDr == -3){accountDr = 885;}else{accountDr = 884;} /* //// @@@@@@@@@@@@ Account Map @@@@@@@@@@@ //// Direct Salary == 61190 Project Direct Salary (895/913) Indirect Salary == Project Indirect Salary (896/914) Overhead == Indirect Labor (885) Regular == Direct Labor (884) //// @@@@@@@@@@@@ Account Map END @@@@@@@@@@@ ////*/ //creating journal record journalRecordCreate = record.create({ type: 'journalentry', isDynamic: true }); journalRecordCreate.setValue({ fieldId : 'subsidiary', value : subsidaryD }); journalRecordCreate.setValue({ fieldId : 'currency', value : lvCurrency }); journalRecordCreate.setValue({ fieldId : 'trandate', value : new Date() }); journalRecordCreate.setValue({ fieldId : 'approved', value : true }); journalRecordCreate.setValue({ fieldId : 'timebillflag', value : 'T' }); journalRecordCreate.setValue({ fieldId : 'custbody_sr_time_track_link', value : id }); var type = 'debit'; addLineDataOnJournalRecord(finalLineMemo,accountDr,finalAmount,type); var type = 'credit'; addLineDataOnJournalRecord(finalLineMemo,accountCr,finalAmount,type); try{ if(billCbk == false || billCbk == 'F' || billCbk == ''){ var journalRecordId = journalRecordCreate.save({ enableSourcing: true, ignoreMandatoryFields: true }); log.debug('journalRecordId',journalRecordId) /*var rec = record.load({type:'timebill',id:id}); rec.setValue({fieldId:'transactionid',value:Number(journalRecordId)}); rec.setValue({fieldId:'posted',value:true}); var recordSubmit = rec.save()*/ var recordSubmit = record.submitFields({ type: 'timebill', id: id, values: { 'posted': 'T', 'transactionid':Number(journalRecordId) }, options: { enableSourcing: true, ignoreMandatoryFields : true } }); log.debug('recordSubmit',recordSubmit) }else{ log.debug('its charges') } }catch(journalRecordSubmitError){ record.submitFields({ type: 'timebill', id: id, values: { 'posted': 'F' } }); log.error({title:'Error in journal Creation: ', details:journalRecordSubmitError}); email.send({author: currentUser, recipients: currentUserEmail, subject: 'Error while submitting journal for Time sheet: '+id+'', body: 'Hi,\n Error is:\n '+journalRecordSubmitError+'' }); } }catch(e){ log.debug('Error', e); } } function addLineDataOnJournalRecord(memo,account,ammount,type){ if(ammount != '' && ammount != undefined || ammount != null){ if(account != '' && account != undefined){ if(type == 'credit'){ var line = journalRecordCreate.getLineCount({ sublistId: 'line' }); journalRecordCreate.selectLine({ sublistId: 'line', line: line }); journalRecordCreate.setCurrentSublistValue({ sublistId: 'line', fieldId: 'account', value: account }); journalRecordCreate.setCurrentSublistValue({ sublistId: 'line', fieldId: 'credit', value: ammount }); journalRecordCreate.setCurrentSublistValue({ sublistId: 'line', fieldId: 'memo', value: memo }); try{ journalRecordCreate.setCurrentSublistValue({ sublistId: 'line', fieldId: 'department', value: departmentD }); journalRecordCreate.setCurrentSublistValue({ sublistId: 'line', fieldId: 'class', value: classD }); journalRecordCreate.setCurrentSublistValue({ sublistId: 'line', fieldId: 'location', value: locationD }); }catch(e){ log.debug("issue with department") } journalRecordCreate.commitLine({ sublistId: 'line'}); }else if(type == 'debit'){ var line = journalRecordCreate.getLineCount({ sublistId: 'line' }); journalRecordCreate.selectLine({ sublistId: 'line', line: line }); journalRecordCreate.setCurrentSublistValue({ sublistId: 'line', fieldId: 'account', value: account }); journalRecordCreate.setCurrentSublistValue({ sublistId: 'line', fieldId: 'debit', value: ammount }); journalRecordCreate.setCurrentSublistValue({ sublistId: 'line', fieldId: 'memo', value: memo }); try{ journalRecordCreate.setCurrentSublistValue({ sublistId: 'line', fieldId: 'department', value: departmentD }); journalRecordCreate.setCurrentSublistValue({ sublistId: 'line', fieldId: 'class', value: classD }); journalRecordCreate.setCurrentSublistValue({ sublistId: 'line', fieldId: 'location', value: locationD }); }catch(e){ log.debug("issue with department") } journalRecordCreate.commitLine({sublistId: 'line'}); } } } } /** * Defines the function that is executed when the reduce entry point is triggered. This entry point is triggered * automatically when the associated map stage is complete. This function is applied to each group in the provided context. * @param {Object} reduceContext - Data collection containing the groups to process in the reduce stage. This parameter is * provided automatically based on the results of the map stage. * @param {Iterator} reduceContext.errors - Serialized errors that were thrown during previous attempts to execute the * reduce function on the current group * @param {number} reduceContext.executionNo - Number of times the reduce function has been executed on the current group * @param {boolean} reduceContext.isRestarted - Indicates whether the current invocation of this function is the first * invocation (if true, the current invocation is not the first invocation and this function has been restarted) * @param {string} reduceContext.key - Key to be processed during the reduce stage * @param {List<String>} reduceContext.values - All values associated with a unique key that was passed to the reduce stage * for processing * @since 2015.2 */ function reduce (reduceContext) { } /** * Defines the function that is executed when the summarize entry point is triggered. This entry point is triggered * automatically when the associated reduce stage is complete. This function is applied to the entire result set. * @param {Object} summaryContext - Statistics about the execution of a map/reduce script * @param {number} summaryContext.concurrency - Maximum concurrency number when executing parallel tasks for the map/reduce * script * @param {Date} summaryContext.dateCreated - The date and time when the map/reduce script began running * @param {boolean} summaryContext.isRestarted - Indicates whether the current invocation of this function is the first * invocation (if true, the current invocation is not the first invocation and this function has been restarted) * @param {Iterator} summaryContext.output - Serialized keys and values that were saved as output during the reduce stage * @param {number} summaryContext.seconds - Total seconds elapsed when running the map/reduce script * @param {number} summaryContext.usage - Total number of governance usage units consumed when running the map/reduce * script * @param {number} summaryContext.yields - Total number of yields when running the map/reduce script * @param {Object} summaryContext.inputSummary - Statistics about the input stage * @param {Object} summaryContext.mapSummary - Statistics about the map stage * @param {Object} summaryContext.reduceSummary - Statistics about the reduce stage * @since 2015.2 */ function summarize (summaryContext) { } return { getInputData:getInputData, map:map, summarize:summarize } });
/** * @NApiVersion 2.1 */ require(['N/task', 'N/runtime', 'N/email'], (task, runtime, email) => { // Store the script ID of the script to submit // // Update the following statement so it uses the script ID // of the map/reduce script record you want to submit const mapReduceScriptId = 'customscript_test_mapreduce_script'; // Create a map/reduce task // // Update the deploymentId parameter to use the script ID of // the deployment record for your map/reduce script let mrTask = task.create({ taskType: task.TaskType.MAP_REDUCE, scriptId: mapReduceScriptId, deploymentId: 'customdeploy_test_mapreduce_script' }); // Submit the map/reduce task let mrTaskId = mrTask.submit(); // Check the status of the task, and send an email if the // task has a status of FAILED // // Update the authorId value with the internal ID of the user // who is the email sender. Update the recipientEmail value // with the email address of the recipient. let taskStatus = task.checkStatus(mrTaskId); if (taskStatus.status === 'FAILED') { const authorId = -5; const recipientEmail = 'notify@myCompany.com'; email.send({ author: authorId, recipients: recipientEmail, subject: 'Failure executing map/reduce job!', body: 'Map reduce task: ' + mapReduceScriptId + ' has failed.' }); } });
984
[{"tag": "EMAIL", "value": "notify@myCompany.com", "start": 1196, "end": 1216}]
true
1
/** * @NApiVersion 2.1 */ require(['N/task', 'N/runtime', 'N/email'], (task, runtime, email) => { // Store the script ID of the script to submit // // Update the following statement so it uses the script ID // of the map/reduce script record you want to submit const mapReduceScriptId = 'customscript_test_mapreduce_script'; // Create a map/reduce task // // Update the deploymentId parameter to use the script ID of // the deployment record for your map/reduce script let mrTask = task.create({ taskType: task.TaskType.MAP_REDUCE, scriptId: mapReduceScriptId, deploymentId: 'customdeploy_test_mapreduce_script' }); // Submit the map/reduce task let mrTaskId = mrTask.submit(); // Check the status of the task, and send an email if the // task has a status of FAILED // // Update the authorId value with the internal ID of the user // who is the email sender. Update the recipientEmail value // with the email address of the recipient. let taskStatus = task.checkStatus(mrTaskId); if (taskStatus.status === 'FAILED') { const authorId = -5; const recipientEmail = 'upchh@example.com'; email.send({ author: authorId, recipients: recipientEmail, subject: 'Failure executing map/reduce job!', body: 'Map reduce task: ' + mapReduceScriptId + ' has failed.' }); } });
true
/** * @NApiVersion 2.1 */ require(['N/task', 'N/runtime', 'N/email'], (task, runtime, email) => { // Store the script ID of the script to submit // // Update the following statement so it uses the script ID // of the map/reduce script record you want to submit const mapReduceScriptId = 'customscript_test_mapreduce_script'; // Create a map/reduce task // // Update the deploymentId parameter to use the script ID of // the deployment record for your map/reduce script let mrTask = task.create({ taskType: task.TaskType.MAP_REDUCE, scriptId: mapReduceScriptId, deploymentId: 'customdeploy_test_mapreduce_script' }); // Submit the map/reduce task let mrTaskId = mrTask.submit(); // Check the status of the task, and send an email if the // task has a status of FAILED // // Update the authorId value with the internal ID of the user // who is the email sender. Update the recipientEmail value // with the email address of the recipient. let taskStatus = task.checkStatus(mrTaskId); if (taskStatus.status === 'FAILED') { const authorId = -5; const recipientEmail = 'PI:EMAIL:upchh@example.comEND_PI'; email.send({ author: authorId, recipients: recipientEmail, subject: 'Failure executing map/reduce job!', body: 'Map reduce task: ' + mapReduceScriptId + ' has failed.' }); } });
/** * @NApiVersion 2.0 * @NScriptType Suitelet * * Module Description * * NSVersion Date Author * 2.00 2021-09-20 09:33:08 Anesu * * Description: xxxxxxxx * * @Last Modified by: Anesu * @Last Modified time: 2021-09-20 09:33:08 * */ define(["N/ui/serverWidget","N/email","N/runtime","N/search","N/record","N/http","N/log","N/redirect","N/task","N/format",], function(ui,email,runtime,search,record,http,log,redirect,task,format) { var zee = 0; var role = 0; var baseURL = "https://1048144.app.netsuite.com"; if (runtime.EnvType == "SANDBOX") { baseURL = "https://1048144-sb3.app.netsuite.com"; } role = runtime.getCurrentUser().role; if (role == 1000) { zee = runtime.getCurrentUser().id; } else if (role == 3) { //Administrator zee = 6; //test } else if (role == 1032) { // System Support zee = 425904; //test-AR } function onRequest(context) { if (context.request.method === "GET") { type = context.request.parameters.type; var params_params = context.request.parameters; if (!isNullorEmpty(params_params.custparam_params)) { var params = JSON.parse(context.request.parameters.custparam_params); } var zee_id; var commReg; if (!isNullorEmpty(params)) { zee_id = parseInt(params.zeeid); commReg = parseInt(params.commreg); } var form = ui.createForm({ title: " " }); // Load jQuery // var inlineHtml = '<script src="https://code.jquery.com/jquery-1.12.4.min.js" integrity="sha384-nvAa0+6Qg9clwYCGGPpDQLVpLNn0fRaROjHqs13t4Ggj3Ez50XnGQqc/r8MhnRDZ" crossorigin="anonymous"></script>'; var inlineHtml = '<script src="https://code.jquery.com/jquery-3.5.0.js" crossorigin="anonymous"></script>'; // Load Tooltip inlineHtml += '<script src="https://unpkg.com/@popperjs/core@2"></script>'; // Load Bootstrap inlineHtml += '<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/3.4.1/css/bootstrap.min.css" integrity="sha384-HSMxcRTRxnN+Bdg0JdbxYKrThecOKuH5zCYotlSAcp1+c8xmyTe9GYg1l9a69psu" crossorigin="anonymous">'; inlineHtml += '<script src="https://stackpath.bootstrapcdn.com/bootstrap/3.4.1/js/bootstrap.min.js" integrity="sha384-aJ21OjlMXNL5UyIl/XNwTMqvzeRMZH2w8c5cRVpzpU8Y5bApTppSuUkhZXN0VxHd" crossorigin="anonymous"></script>'; // Load DataTables inlineHtml += '<link rel="stylesheet" type="text/css" href="//cdn.datatables.net/1.10.21/css/jquery.dataTables.min.css">'; inlineHtml += '<script type="text/javascript" charset="utf8" src="//cdn.datatables.net/1.10.21/js/jquery.dataTables.min.js"></script>'; inlineHtml += '<script type="text/javascript" charset="utf8" src="//cdn.datatables.net/rowgroup/1.1.3/js/dataTables.rowGroup.min.js"></script> '; inlineHtml += '<script type="text/javascript" charset="utf8" src="//cdn.datatables.net/buttons/2.0.0/js/dataTables.buttons.min.js"></script> '; inlineHtml += '<script type="text/javascript" charset="utf8" src="//cdnjs.cloudflare.com/ajax/libs/jszip/3.1.3/jszip.min.js"></script> '; inlineHtml += '<script type="text/javascript" charset="utf8" src="//cdnjs.cloudflare.com/ajax/libs/pdfmake/0.1.53/pdfmake.min.js"></script> '; inlineHtml += '<script type="text/javascript" charset="utf8" src="//cdnjs.cloudflare.com/ajax/libs/pdfmake/0.1.53/vfs_fonts.js"></script> '; inlineHtml += '<script type="text/javascript" charset="utf8" src="//cdn.datatables.net/buttons/2.0.0/js/buttons.html5.min.js"></script> '; inlineHtml += '<script type="text/javascript" charset="utf8" src="//cdn.datatables.net/buttons/2.0.0/js/buttons.print.min.js"></script> '; // Load Netsuite stylesheet and script inlineHtml += '<link rel="stylesheet" href="https://1048144.app.netsuite.com/core/media/media.nl?id=2060796&c=1048144&h=9ee6accfd476c9cae718&_xt=.css"/>'; inlineHtml += '<script src="https://1048144.app.netsuite.com/core/media/media.nl?id=2060797&c=1048144&h=ef2cda20731d146b5e98&_xt=.js"></script>'; inlineHtml += '<link type="text/css" rel="stylesheet" href="https://1048144.app.netsuite.com/core/media/media.nl?id=2090583&c=1048144&h=a0ef6ac4e28f91203dfe&_xt=.css">'; inlineHtml += "<style>.mandatory{color:red;}</style>"; // Load Bootstrap-Select inlineHtml += '<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap-select@1.13.14/dist/css/bootstrap-select.min.css">'; inlineHtml += '<script src="https://cdn.jsdelivr.net/npm/bootstrap-select@1.13.14/dist/js/bootstrap-select.min.js"></script>'; // Semantic Select inlineHtml += '<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/semantic-ui/2.2.13/semantic.min.css">'; inlineHtml += '<script src="https://cdnjs.cloudflare.com/ajax/libs/semantic-ui/2.2.13/semantic.min.js"></script>'; // Load Search In Dropdown // inlineHtml += '<link href="https://cdnjs.cloudflare.com/ajax/libs/select2/4.0.6-rc.0/css/select2.min.css" rel="stylesheet" />'; // inlineHtml += '<script src="https://cdnjs.cloudflare.com/ajax/libs/select2/4.0.6-rc.0/js/select2.min.js"></script>'; // New Website Color Schemes // Main Color: #379E8F // Background Color: #CFE0CE // Button Color: #FBEA51 // Text Color: #103D39 inlineHtml += '<div class="a" style="width: 100%; background-color: #CFE0CE; padding: 20px; min-height: 100%; height: 100%;">'; // inlineHtml += '<h1 style="text-align: center; color: #103D39; display: inline-block; font-size: 22px; font-weight: bold; line-height: 33px; vertical-align: top; margin-bottom: 4px;">Consolidation Invoice</h1>'; inlineHtml += "<style>.nav > li.active > a, .nav > li.active > a:focus, .nav > li.active > a:hover { background-color: #379E8F; color: #fff }"; inlineHtml += ".nav > li > a, .nav > li > a:focus, .nav > li > a:hover { margin-left: 5px; margin-right: 5px; border: 2px solid #379E8F; color: #379E8F; }"; inlineHtml += "</style>"; // Define alert window. inlineHtml += '<div class="container" style="margin-top:14px;" hidden><div id="alert" class="alert alert-danger fade in"></div></div>'; // Define information window. inlineHtml += '<div class="container" hidden><p id="info" class="alert alert-info"></p></div>'; inlineHtml += '<div style="margin-top: -40px"><br/>'; // Buttons inlineHtml += '<button style="margin-left: 10px; margin-right: 5px; background-color: #FBEA51; color: #103D39; font-weight: 700; border-color: transparent; border-width: 2px; border-radius: 15px; height: 30px" type="button" id="smc" onclick="">Service Management Console</button>'; inlineHtml += '<h1 style="font-size: 25px; font-weight: 700; color: #103D39; text-align: center">Scheduled Price Change</h1>'; // Click for Instructions // inlineHtml += '<button type="button" class="btn btn-sm btn-info instruction_button" data-toggle="collapse" data-target="#demo" style="background-color: #FBEA51; color: #103D39;">Click for Instructions</button><div id="demo" style="background-color: #cfeefc !important;border: 1px solid #417ed9;padding: 10px 10px 10px 20px;width:96%;position:absolute" class="collapse"><b><u>IMPORTANT INSTRUCTIONS:</u></b>'; // inlineHtml += '<ul><li><input type="button" class="btn-xs" style="background-color: #fff; color: black;" disabled value="Submit Search" /> - <ul><li>Click "Submit Search" to load Datatable using current parameters</li></ul></li>' // inlineHtml += '<li>Functionalities available on the Table Collections Table:<ul><li><b>Sort</b><ul><li>Click on column headers to sort collections invoices according to the values in the columns. This is default to "Days Overdue".</li><li>Hold "Shift" and click another column to sort according to multiple columns.</li></ul></li><li><b>Search</b><ul><li>You can search for specific Customer or Invoice by typing into the "Search" field</li></ul></li></ul></li>'; // inlineHtml += '<li>Table Filters:<ul><li><b>Matching MAAP Allocation</b><ul><li><button type="button" class="btn-xs btn-success " disabled><span class="glyphicon glyphicon-plus"></span></button> - Click to apply MAAP Allocation filters search filters on table. ONLY click once. </li><li><button type="button" class="btn-xs btn-danger " disabled><span class="glyphicon glyphicon-minus"></span></button> - Click to remove MAAP Allocation search filter from table. This is set default to "Days Overdue".</li></ul></li> <li><b>MP Ticket Column</b><ul><button type="button" class="btn-xs btn-success" disabled><span class="glyphicon glyphicon-plus"></span></button> - Click to apply MAAP Allocation filters search filters on table. ONLY click once. </li></ul></li></ul></li><li>Clickable Actions Available Per Invoice in DataTable:</li>'; // inlineHtml += '<ul><li><button type="button" class="btn-xs" disabled><span class="span_class glyphicon glyphicon-pencil"></span></button> - Click to open Notes Section for Selected Invoice. (Notes Section is seperate from User Notes)</li>'; // inlineHtml += '<li><button type="button" class="btn-xs btn-secondary" disabled><span class="glyphicon glyphicon-eye-open"></span></button> - Click to Set Invoice has "Viewed" by a member of the Finance Team.</li>'; // inlineHtml += '<li><button type="button" class="btn-xs btn-info" disabled><span class="glyphicon glyphicon-time"></span></button> - Click to view Snooze Timers</li><li><button type="button" class="timer-1day form=control btn-xs btn-info" disabled><span class="span_class">1 Day</span></button> - Click to select Snooze duration of invoice from Table Collections Page.</li>'; // inlineHtml += '</li></ul></div>'; // inlineHtml += '<div class="se-pre-con"></div>' // inlineHtml += '<button type="button" class="btn btn-sm btn-info instruction_button" data-toggle="collapse" data-target="#demo">Click for Instructions</button><div id="demo" style="background-color: #cfeefc !important;border: 1px solid #417ed9;padding: 10px 10px 10px 20px;width:96%;position:absolute" class="collapse"><b><u>IMPORTANT INSTRUCTIONS:</u></b><ul><li>Functionalities available on the Customer listing/table:<ul><li><b>Sort</b><ul><li>Click on column headers to sort customer list according to the values in the columns. This is default to "Customer Name".</li><li>Hold "Shift" and click another column to sort according to multiple columns.</li></ul></li><li><b>Search</b><ul><li>You can search for specific customer by typing into the "Search" field</li></ul></li></ul></li><li>Clickable Actions available per customer:</li><ul><li><button class="btn-xs btn-default" disabled>UPLOAD SCF</button> - <ul><li>Available for customers with missing Service Commencement Forms (SCF) in the system. You will need to upload the latest signed SCF for each relevant customers which outlines the service commencement date along with the Service(s) and Price(s).</li></ul></li><li><button class="btn-xs btn-warning" disabled>REVIEW</button> / <button class="btn-xs btn-primary" disabled>EDIT</button> - <ul><li>Review or Edit customer details (eg. Addresses, Service and Pricing, Packages) to set them up for Run Digitalisation.</li></ul></li><li><button class="btn-xs btn-danger" disabled>CANCEL</button> - <ul><li>You may Cancel non-active customers providing details and reasons around the Cancellation.</li><li>You <b><u>DO NOT NEED</u></b> to cancel customers with <b><u>Adhoc</u></b> arrangements.</li></ul></li><li><button class="btn-xs btn-default" disabled>Duplicate COMMREG</button> - <ul><li>Please contact <b><u>Head Office</u></b> if you see this Action against any customer</li></ul></li></ul></li></ul></ul></div>'; // inlineHtml = '<div class="form-group container loading_section"></div>'; // inlineHtml += '<style> .loading_section { border: 14px solid #f3f3f3; border-radius: 50%; border-top: 14px solid #379E8F; width: 90px; height: 90px; -webkit-animation: spin 2s linear infinite; /* Safari */ animation: spin 2s linear infinite;'; // inlineHtml += 'left: 50%; }' //position: fixed; z-index: 1000; // /* Safari */ // inlineHtml += '@-webkit-keyframes spin {0% { -webkit-transform: rotate(0deg); } 100% { -webkit-transform: rotate(360deg); } }'; // inlineHtml += '@keyframes spin { 0% { transform: rotate(0deg); } 100% { transform: rotate(360deg); } }'; // inlineHtml += '</style>'; inlineHtml += zeeDropdownSection(zee_id); // Customer List inlineHtml += dataTable_custlist(); inlineHtml += "</div></div>"; form.addField({ id: "preview_table", label: "inlinehtml", type: "inlinehtml", }).updateLayoutType({ layoutType: ui.FieldLayoutType.STARTROW, }).defaultValue = inlineHtml; form.addField({ id: "custpage_price_change_zee_id", label: "Zee ID", type: ui.FieldType.TEXT, }).updateDisplayType({ displayType: ui.FieldDisplayType.HIDDEN, }).defaultValue = zee_id; form.clientScriptFileId = 5500819; // 5500819 context.response.writePage(form); } else {} } function zeeDropdownSection(zeeid) { var inlineQty = '<div class="form-group container zeeDropdown">'; inlineQty += '<div class="row col-xs-6" style="left: 25%; margin-top: 20px;">'; //col-xs-6 d-flex justify-content-center inlineQty += '<div class="input-group">'; inlineQty += '<span style="background-color: #379E8F; color: white;" class="input-group-addon">Franchisee</span>'; inlineQty += '<select id="zee_filter_dropdown" class="form-control" required>'; inlineQty += "<option></option>"; var zeesSearch = search.load({ type: "partner", id: "customsearch_smc_franchisee", }); // zeesSearch.filters.push(search.createFilter({ // name: 'entityid', // operator: search.Operator.DOESNOTSTARTWITH, // values: 'Test' // })) var zeesSearchResults = zeesSearch.run(); log.audit({ title: "JSON Stringify - zeesSearchResults", details: JSON.stringify(zeesSearchResults), }); zeesSearchResults.each(function(zeesSearchResult) { var zee_id = zeesSearchResult.getValue({ name: "internalid", summmary: search.Summary.GROUP, }); var zee_name = zeesSearchResult.getValue({ name: "companyname", summmary: search.Summary.GROUP, }); var zee_state = zeesSearchResult.getText({ name: "location" }); if (zee_id == zeeid) { inlineQty += '<option value="' + zee_id + '" state="' + zee_state + '" selected>' + zee_name + "</option>"; } else { inlineQty += '<option value="' + zee_id + '" state="' + zee_state + '">' + zee_name + "</option>"; } return true; }); inlineQty += "</select>"; inlineQty += "</div>"; inlineQty += "</div></div>"; return inlineQty; } /** * The table that will display the differents invoices linked to the franchisee and the time period. * @return {String} inlineQty */ function dataTable_custlist() { var inlineQty = "<style>table#table_preview {font-size: 12px;text-align: center;border: none;}.dataTables_wrapper {font-size: 14px;}table#table_preview th{text-align: center;} .bolded{font-weight: bold;}</style>"; inlineQty += '<table id="table_preview" class="table table-responsive table-striped customer tablesorter hide" style="width: 100%;">'; inlineQty += '<thead style="color: white; background-color: #379E8F;">'; inlineQty += '<tr class="text-center">'; inlineQty += "</tr>"; inlineQty += "</thead>"; inlineQty += '<tbody id="result_Table" class="result-Table"></tbody>'; inlineQty += "</table>"; return inlineQty; } function tabsSection() { // var inlineQty = '<div>'; // Tabs headersasdasda var inlineQty = "<style>.nav > li.active > a, .nav > li.active > a:focus, .nav > li.active > a:hover { background-color: #379E8F; color: #fff }"; inlineQty += ".nav > li > a, .nav > li > a:focus, .nav > li > a:hover { margin-left: 5px; margin-right: 5px; border: 2px solid #379E8F; color: #379E8F; }"; inlineQty += "</style>"; inlineQty += '<div class="tabSection" style="width: 95%; margin:auto; margin-bottom: 30px; margin-top: 30px;",><ul class="nav nav-pills nav-justified" style="margin:0%; ">'; inlineQty += '<li role="presentation" class="active"><a data-toggle="tab" href="#edit"><b>Edit</b></a></li>'; inlineQty += '<li role="presentation" class=""><a data-toggle="tab" href="#review"><b>Review</b></a></li>'; inlineQty += '<li role="presentation" class=""><a data-toggle="tab" href="#upload_scf"><b>Upload SCF</b></a></li>'; inlineQty += "</ul></div>"; // Tabs content inlineQty += '<div class="tab-content">'; // if (!isFinanceRole(userRole)) { inlineQty += '<div role="tabpanel" class="tab-pane active" id="edit">'; // inlineQty += dataTablePreview('reassign'); inlineQty += editTab("edit"); inlineQty += "</div>"; inlineQty += '<div role="tabpanel" class="tab-pane" id="review">'; inlineQty += reviewTab("review"); inlineQty += "</div>"; inlineQty += '<div role="tabpanel" class="tab-pane" id="upload_scf">'; inlineQty += uploadSCF(); inlineQty += "</div>"; // inlineQty += '</div>'; //</div> return inlineQty; } function commRegSection(commReg) { var inlineQty = "<style>table#comm_reg_preview {font-size: 12px;text-align: center;border: none;}.dataTables_wrapper {font-size: 14px;}table#comm_reg_preview th{text-align: center;} .bolded{font-weight: bold;}</style>"; /** * Comm Reg Header */ inlineQty += '<div class="form-group container comm_header_section">'; inlineQty += '<div class="row">'; inlineQty += '<div class="col-xs-12 heading1">'; inlineQty += '<h4><span style="background-color: #379E8F" class="form-group label label-default col-xs-12">Commencement Register</span></h4>'; inlineQty += "</div></div></div>"; inlineQty += '<table id="comm_reg_preview" class="table table-responsive table-striped customer tablesorter" style="width: 100%;">'; inlineQty += '<thead style="color: white; background-color: #379E8F;">'; inlineQty += '<tr class="text-center">'; // inlineQty += '<th>Commencement Register</th>'; inlineQty += "</tr>"; inlineQty += "</thead>"; inlineQty += '<tbody id="result_data" class="result-data">'; inlineQty += "</tbody>"; inlineQty += "</table>"; inlineQty += '<div class="form-row container comm_reg_section">'; inlineQty += '<div class="row">'; inlineQty += '<div class="col-xs-2"></div>'; // Blank Placeholder inlineQty += '<div class="col-xs-4 schedule_change_section"><input type="button" id="create_new" class="form-control btn btn-success btn-xs create_new" value="New Scheduled Change" data-toggle="tooltip" data-placement="right" title="NEW SCHEDULED CHANGE" /></div>'; inlineQty += '<div class="col-xs-4 cancel_service_section"><input type="button" id="cancel_service" class="form-control btn btn-danger btn-xs cancel_service" value="Cancel Service" data-toggle="tooltip" data-placement="right" title="CANCEL SERVICE" /></div>'; inlineQty += '<div class="col-xs-2"></div>'; // Blank Placeholder inlineQty += "</div>"; inlineQty += "</div>"; return inlineQty; } /** * The table that will display the differents invoices linked to the franchisee and the time period. * @return {String} inlineQty */ function editTab(selector) { var inlineQty = "<style>table#data_preview_" + selector + " {font-size: 12px;text-align: center;border: none;}.dataTables_wrapper {font-size: 14px;}table#data_preview_" + selector + " th{text-align: center;} .bolded{font-weight: bold;}</style>"; /** * Edit Header */ inlineQty += '<div class="form-group container edit_header_section">'; inlineQty += '<div class="row">'; inlineQty += '<div class="col-xs-12 heading1">'; inlineQty += '<h4><span style="background-color: #379E8F" class="form-group label label-default col-xs-12">Edit</span></h4>'; inlineQty += "</div></div></div>"; /** * Date Effective */ inlineQty += '<div class="form-group container date_effective_section">'; inlineQty += '<div class="row">'; // if (isNullorEmpty(dateEffective)) { inlineQty += '<div class="col-xs-6"><div class="input-group"><span style="background-color: #379E8F; color: white;" class="input-group-addon">Date Effective <span class="mandatory">*</span></span><input type="date" id="date_effective" value="" class="form-control date_effective"/></div></div>'; // } else { // start_date = GetFormattedDate(dateEffective); // inlineQty += '<div class="col-xs-7 "><div class="input-group"><span class="input-group-addon">DATE EFFECTIVE <span class="mandatory">*</span></span><input type="date" id="date_effective" value="' + start_date + '" data-olddate="' + dateEffective + '" class="form-control date_effective"/></div></div>'; // } /** * Sales Type */ inlineQty += '<div class="col-xs-6 commencementtype"><div class="input-group"><span style="background-color: #379E8F; color: white;" class="input-group-addon" id="commencementtype_text">Sale Type <span class="mandatory">*</span></span><select id="commencementtype" class="form-control commencementtype"><option></option>'; var col = new Array(); col[0] = search.createColumn({ name: "name", }); col[1] = search.createColumn({ name: "internalId", }); var results = search.create({ type: "customlist_sale_type", columns: col }); results.run().each(function(res) { var listValue = res.getValue({ name: "name" }); var listID = res.getValue({ name: "internalId" }); // if (!isNullorEmpty(sale_type) && sale_type == listID) { // inlineQty += '<option value="' + listID + '" selected>' + listValue + '</option>'; // } else { inlineQty += '<option value="' + listID + '">' + listValue + "</option>"; // } return true; }); inlineQty += "</select></div></div>"; inlineQty += "</div>"; inlineQty += "</div>"; /** * DataTable */ inlineQty += '<table id="data_preview_' + selector + '" class="table table-responsive table-striped customer tablesorter" style="width: 100%;">'; inlineQty += '<thead style="color: white; background-color: #379E8F;">'; inlineQty += '<tr class="text-center">'; inlineQty += "</tr>"; inlineQty += "</thead>"; inlineQty += '<tbody id="result_data" class="result-data"></tbody>'; // inlineQty += '' inlineQty += "</table>"; inlineQty += '<div class="form-row container edit_submit_section">'; inlineQty += '<div class="row">'; inlineQty += '<div class="col-xs-2"></div>'; // Blank Placeholder inlineQty += '<div class="col-xs-4 schedule_change_section"><input type="button" id="sumbit_edit" style="color: #103D39;" class="form-control btn btn-warning btn-xs sumbit_edit" value="Submit" data-toggle="tooltip" data-placement="right" title="Submit" /></div>'; // <button style="margin-left: 10px; margin-right: 5px; background-color: #FBEA51; color: #103D39; font-weight: 700; border-color: transparent; border-width: 2px; border-radius: 15px; height: 30px" type="button" id="smc" class="">Service Management Console</button>'; inlineQty += '<div class="col-xs-4 cancel_service_section"><input type="button" id="next_customer" style="color: #103D39;" class="form-control btn btn-warning btn-xs next_customer" value="Next Customer" data-toggle="tooltip" data-placement="right" title="Next Customer" /></div>'; inlineQty += '<div class="col-xs-2"></div>'; // Blank Placeholder inlineQty += "</div>"; inlineQty += "</div>"; return inlineQty; } /** * The table that will display the differents invoices linked to the franchisee and the time period. * @return {String} inlineQty */ function reviewTab(selector) { var inlineQty = "<style>table#data_preview_" + selector + " {font-size: 12px;text-align: center;border: none;}.dataTables_wrapper {font-size: 14px;}table#data_preview_" + selector + " th{text-align: center;} .bolded{font-weight: bold;}</style>"; /** * Review Header */ inlineQty += '<div class="form-group container review_header_section">'; inlineQty += '<div class="row">'; inlineQty += '<div class="col-xs-12 heading1">'; inlineQty += '<h4><span style="background-color: #379E8F" class="form-group label label-default col-xs-12">REVIEW</span></h4>'; inlineQty += "</div></div></div>"; inlineQty += '<table id="data_preview_' + selector + '" class="table table-responsive table-striped customer tablesorter" style="width: 100%;">'; inlineQty += '<thead style="color: white; background-color: #379E8F;">'; inlineQty += '<tr class="text-center">'; inlineQty += "</tr>"; inlineQty += "</thead>"; inlineQty += '<tbody id="result_data" class="result-data"></tbody>'; inlineQty += "</table>"; return inlineQty; } function uploadSCF() { var inlineQty = ""; // inlineQty += '<h4 id="primary_table_title" class="primary_table_title_a" style="font-size: 25px; font-weight: 700; color: #103D39; text-align: center">Upload SCF</h4>'; /** * Upload SCF Header */ inlineQty += '<div class="form-group container scf_header_section">'; inlineQty += '<div class="row">'; inlineQty += '<div class="col-xs-12 heading1">'; inlineQty += '<h4><span style="background-color: #379E8F" class="form-group label label-default col-xs-12">Upload SCF</span></h4>'; inlineQty += "</div></div></div>"; inlineQty += "<br>"; inlineQty += '<div class="form-group container scf_header_section">'; inlineQty += '<div class="row">'; inlineQty += '<div class="mb-3">'; inlineQty += '<label for="formFileSm" class="form-label">Upload SCF</label>'; inlineQty += '<input class="form-control form-control-sm" id="upload_scf_file" type="file" name="scf">'; inlineQty += "</div>"; inlineQty += "</div></div>"; return inlineQty; } /** * The period dropdown field. * @param {String} date_from * @param {String} date_to * @return {String} `inlineQty` */ function periodDropdownSection(date_from, date_to) { var selected_option = isNullorEmpty(date_from) && isNullorEmpty(date_to) ? "selected" : ""; var inlineQty = '<div class="form-group container period_dropdown_section">'; inlineQty += '<div class="row">'; // Period dropdown field inlineQty += '<div class="col-xs-12 period_dropdown_div">'; inlineQty += '<div class="input-group">'; inlineQty += '<span class="input-group-addon" id="period_dropdown_text">Period</span>'; inlineQty += '<select id="period_dropdown" class="form-control">'; inlineQty += "<option " + selected_option + "></option>"; inlineQty += '<option value="this_week">This Week</option>'; inlineQty += '<option value="last_week">Last Week</option>'; inlineQty += '<option value="this_month">This Month</option>'; inlineQty += '<option value="last_month">Last Month</option>'; inlineQty += '<option value="full_year">Full Year (1 Jan -)</option>'; inlineQty += '<option value="financial_year">Financial Year (1 Jul -)</option>'; inlineQty += "</select>"; inlineQty += "</div></div></div></div>"; return inlineQty; } /** * Used to pass the values of `date_from` and `date_to` between the scripts and to Netsuite for the records and the search. * @param {String} date_iso "2020-06-01" * @returns {String} date_netsuite "1/6/2020" */ function dateISOToNetsuite(date_iso) { var date_netsuite = ""; if (!isNullorEmpty(date_iso)) { var date_utc = new Date(date_iso); // var date_netsuite = nlapiDateToString(date_utc); var date_netsuite = format.format({ value: date_utc, type: format.Type.DATE, }); } return date_netsuite; } function isNullorEmpty(strVal) { return ( strVal == null || strVal == "" || strVal == "null" || strVal == undefined || strVal == "undefined" || strVal == "- None -" ); } return { onRequest: onRequest, }; });
961
[{"tag": "KEY", "value": "sha384-HSMxcRTRxnN+Bdg0JdbxYKrThecOKuH5zCYotlSAcp1+c8xmyTe9GYg1l9a69psu", "start": 2451, "end": 2522}, {"tag": "KEY", "value": "sha384-nvAa0+6Qg9clwYCGGPpDQLVpLNn0fRaROjHqs13t4Ggj3Ez50XnGQqc/r8MhnRDZ", "start": 1853, "end": 1924}, {"tag": "KEY", "value": "sha384-aJ21OjlMXNL5UyIl/XNwTMqvzeRMZH2w8c5cRVpzpU8Y5bApTppSuUkhZXN0VxHd", "start": 2698, "end": 2769}]
true
3
/** * @NApiVersion 2.0 * @NScriptType Suitelet * * Module Description * * NSVersion Date Author * 2.00 2021-09-20 09:33:08 Anesu * * Description: xxxxxxxx * * @Last Modified by: Anesu * @Last Modified time: 2021-09-20 09:33:08 * */ define(["N/ui/serverWidget","N/email","N/runtime","N/search","N/record","N/http","N/log","N/redirect","N/task","N/format",], function(ui,email,runtime,search,record,http,log,redirect,task,format) { var zee = 0; var role = 0; var baseURL = "https://1048144.app.netsuite.com"; if (runtime.EnvType == "SANDBOX") { baseURL = "https://1048144-sb3.app.netsuite.com"; } role = runtime.getCurrentUser().role; if (role == 1000) { zee = runtime.getCurrentUser().id; } else if (role == 3) { //Administrator zee = 6; //test } else if (role == 1032) { // System Support zee = 425904; //test-AR } function onRequest(context) { if (context.request.method === "GET") { type = context.request.parameters.type; var params_params = context.request.parameters; if (!isNullorEmpty(params_params.custparam_params)) { var params = JSON.parse(context.request.parameters.custparam_params); } var zee_id; var commReg; if (!isNullorEmpty(params)) { zee_id = parseInt(params.zeeid); commReg = parseInt(params.commreg); } var form = ui.createForm({ title: " " }); // Load jQuery // var inlineHtml = '<script src="https://code.jquery.com/jquery-1.12.4.min.js" integrity="ax5kh6jaqkcd2tiexxs8v6xjo8yv8a6b" crossorigin="anonymous"></script>'; var inlineHtml = '<script src="https://code.jquery.com/jquery-3.5.0.js" crossorigin="anonymous"></script>'; // Load Tooltip inlineHtml += '<script src="https://unpkg.com/@popperjs/core@2"></script>'; // Load Bootstrap inlineHtml += '<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/3.4.1/css/bootstrap.min.css" integrity="949d1u22cbffbrarjh182eig55721odj" crossorigin="anonymous">'; inlineHtml += '<script src="https://stackpath.bootstrapcdn.com/bootstrap/3.4.1/js/bootstrap.min.js" integrity="kgfhvu9qnh3mr6eel97y6fq2hezzol8z" crossorigin="anonymous"></script>'; // Load DataTables inlineHtml += '<link rel="stylesheet" type="text/css" href="//cdn.datatables.net/1.10.21/css/jquery.dataTables.min.css">'; inlineHtml += '<script type="text/javascript" charset="utf8" src="//cdn.datatables.net/1.10.21/js/jquery.dataTables.min.js"></script>'; inlineHtml += '<script type="text/javascript" charset="utf8" src="//cdn.datatables.net/rowgroup/1.1.3/js/dataTables.rowGroup.min.js"></script> '; inlineHtml += '<script type="text/javascript" charset="utf8" src="//cdn.datatables.net/buttons/2.0.0/js/dataTables.buttons.min.js"></script> '; inlineHtml += '<script type="text/javascript" charset="utf8" src="//cdnjs.cloudflare.com/ajax/libs/jszip/3.1.3/jszip.min.js"></script> '; inlineHtml += '<script type="text/javascript" charset="utf8" src="//cdnjs.cloudflare.com/ajax/libs/pdfmake/0.1.53/pdfmake.min.js"></script> '; inlineHtml += '<script type="text/javascript" charset="utf8" src="//cdnjs.cloudflare.com/ajax/libs/pdfmake/0.1.53/vfs_fonts.js"></script> '; inlineHtml += '<script type="text/javascript" charset="utf8" src="//cdn.datatables.net/buttons/2.0.0/js/buttons.html5.min.js"></script> '; inlineHtml += '<script type="text/javascript" charset="utf8" src="//cdn.datatables.net/buttons/2.0.0/js/buttons.print.min.js"></script> '; // Load Netsuite stylesheet and script inlineHtml += '<link rel="stylesheet" href="https://1048144.app.netsuite.com/core/media/media.nl?id=2060796&c=1048144&h=9ee6accfd476c9cae718&_xt=.css"/>'; inlineHtml += '<script src="https://1048144.app.netsuite.com/core/media/media.nl?id=2060797&c=1048144&h=ef2cda20731d146b5e98&_xt=.js"></script>'; inlineHtml += '<link type="text/css" rel="stylesheet" href="https://1048144.app.netsuite.com/core/media/media.nl?id=2090583&c=1048144&h=a0ef6ac4e28f91203dfe&_xt=.css">'; inlineHtml += "<style>.mandatory{color:red;}</style>"; // Load Bootstrap-Select inlineHtml += '<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap-select@1.13.14/dist/css/bootstrap-select.min.css">'; inlineHtml += '<script src="https://cdn.jsdelivr.net/npm/bootstrap-select@1.13.14/dist/js/bootstrap-select.min.js"></script>'; // Semantic Select inlineHtml += '<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/semantic-ui/2.2.13/semantic.min.css">'; inlineHtml += '<script src="https://cdnjs.cloudflare.com/ajax/libs/semantic-ui/2.2.13/semantic.min.js"></script>'; // Load Search In Dropdown // inlineHtml += '<link href="https://cdnjs.cloudflare.com/ajax/libs/select2/4.0.6-rc.0/css/select2.min.css" rel="stylesheet" />'; // inlineHtml += '<script src="https://cdnjs.cloudflare.com/ajax/libs/select2/4.0.6-rc.0/js/select2.min.js"></script>'; // New Website Color Schemes // Main Color: #379E8F // Background Color: #CFE0CE // Button Color: #FBEA51 // Text Color: #103D39 inlineHtml += '<div class="a" style="width: 100%; background-color: #CFE0CE; padding: 20px; min-height: 100%; height: 100%;">'; // inlineHtml += '<h1 style="text-align: center; color: #103D39; display: inline-block; font-size: 22px; font-weight: bold; line-height: 33px; vertical-align: top; margin-bottom: 4px;">Consolidation Invoice</h1>'; inlineHtml += "<style>.nav > li.active > a, .nav > li.active > a:focus, .nav > li.active > a:hover { background-color: #379E8F; color: #fff }"; inlineHtml += ".nav > li > a, .nav > li > a:focus, .nav > li > a:hover { margin-left: 5px; margin-right: 5px; border: 2px solid #379E8F; color: #379E8F; }"; inlineHtml += "</style>"; // Define alert window. inlineHtml += '<div class="container" style="margin-top:14px;" hidden><div id="alert" class="alert alert-danger fade in"></div></div>'; // Define information window. inlineHtml += '<div class="container" hidden><p id="info" class="alert alert-info"></p></div>'; inlineHtml += '<div style="margin-top: -40px"><br/>'; // Buttons inlineHtml += '<button style="margin-left: 10px; margin-right: 5px; background-color: #FBEA51; color: #103D39; font-weight: 700; border-color: transparent; border-width: 2px; border-radius: 15px; height: 30px" type="button" id="smc" onclick="">Service Management Console</button>'; inlineHtml += '<h1 style="font-size: 25px; font-weight: 700; color: #103D39; text-align: center">Scheduled Price Change</h1>'; // Click for Instructions // inlineHtml += '<button type="button" class="btn btn-sm btn-info instruction_button" data-toggle="collapse" data-target="#demo" style="background-color: #FBEA51; color: #103D39;">Click for Instructions</button><div id="demo" style="background-color: #cfeefc !important;border: 1px solid #417ed9;padding: 10px 10px 10px 20px;width:96%;position:absolute" class="collapse"><b><u>IMPORTANT INSTRUCTIONS:</u></b>'; // inlineHtml += '<ul><li><input type="button" class="btn-xs" style="background-color: #fff; color: black;" disabled value="Submit Search" /> - <ul><li>Click "Submit Search" to load Datatable using current parameters</li></ul></li>' // inlineHtml += '<li>Functionalities available on the Table Collections Table:<ul><li><b>Sort</b><ul><li>Click on column headers to sort collections invoices according to the values in the columns. This is default to "Days Overdue".</li><li>Hold "Shift" and click another column to sort according to multiple columns.</li></ul></li><li><b>Search</b><ul><li>You can search for specific Customer or Invoice by typing into the "Search" field</li></ul></li></ul></li>'; // inlineHtml += '<li>Table Filters:<ul><li><b>Matching MAAP Allocation</b><ul><li><button type="button" class="btn-xs btn-success " disabled><span class="glyphicon glyphicon-plus"></span></button> - Click to apply MAAP Allocation filters search filters on table. ONLY click once. </li><li><button type="button" class="btn-xs btn-danger " disabled><span class="glyphicon glyphicon-minus"></span></button> - Click to remove MAAP Allocation search filter from table. This is set default to "Days Overdue".</li></ul></li> <li><b>MP Ticket Column</b><ul><button type="button" class="btn-xs btn-success" disabled><span class="glyphicon glyphicon-plus"></span></button> - Click to apply MAAP Allocation filters search filters on table. ONLY click once. </li></ul></li></ul></li><li>Clickable Actions Available Per Invoice in DataTable:</li>'; // inlineHtml += '<ul><li><button type="button" class="btn-xs" disabled><span class="span_class glyphicon glyphicon-pencil"></span></button> - Click to open Notes Section for Selected Invoice. (Notes Section is seperate from User Notes)</li>'; // inlineHtml += '<li><button type="button" class="btn-xs btn-secondary" disabled><span class="glyphicon glyphicon-eye-open"></span></button> - Click to Set Invoice has "Viewed" by a member of the Finance Team.</li>'; // inlineHtml += '<li><button type="button" class="btn-xs btn-info" disabled><span class="glyphicon glyphicon-time"></span></button> - Click to view Snooze Timers</li><li><button type="button" class="timer-1day form=control btn-xs btn-info" disabled><span class="span_class">1 Day</span></button> - Click to select Snooze duration of invoice from Table Collections Page.</li>'; // inlineHtml += '</li></ul></div>'; // inlineHtml += '<div class="se-pre-con"></div>' // inlineHtml += '<button type="button" class="btn btn-sm btn-info instruction_button" data-toggle="collapse" data-target="#demo">Click for Instructions</button><div id="demo" style="background-color: #cfeefc !important;border: 1px solid #417ed9;padding: 10px 10px 10px 20px;width:96%;position:absolute" class="collapse"><b><u>IMPORTANT INSTRUCTIONS:</u></b><ul><li>Functionalities available on the Customer listing/table:<ul><li><b>Sort</b><ul><li>Click on column headers to sort customer list according to the values in the columns. This is default to "Customer Name".</li><li>Hold "Shift" and click another column to sort according to multiple columns.</li></ul></li><li><b>Search</b><ul><li>You can search for specific customer by typing into the "Search" field</li></ul></li></ul></li><li>Clickable Actions available per customer:</li><ul><li><button class="btn-xs btn-default" disabled>UPLOAD SCF</button> - <ul><li>Available for customers with missing Service Commencement Forms (SCF) in the system. You will need to upload the latest signed SCF for each relevant customers which outlines the service commencement date along with the Service(s) and Price(s).</li></ul></li><li><button class="btn-xs btn-warning" disabled>REVIEW</button> / <button class="btn-xs btn-primary" disabled>EDIT</button> - <ul><li>Review or Edit customer details (eg. Addresses, Service and Pricing, Packages) to set them up for Run Digitalisation.</li></ul></li><li><button class="btn-xs btn-danger" disabled>CANCEL</button> - <ul><li>You may Cancel non-active customers providing details and reasons around the Cancellation.</li><li>You <b><u>DO NOT NEED</u></b> to cancel customers with <b><u>Adhoc</u></b> arrangements.</li></ul></li><li><button class="btn-xs btn-default" disabled>Duplicate COMMREG</button> - <ul><li>Please contact <b><u>Head Office</u></b> if you see this Action against any customer</li></ul></li></ul></li></ul></ul></div>'; // inlineHtml = '<div class="form-group container loading_section"></div>'; // inlineHtml += '<style> .loading_section { border: 14px solid #f3f3f3; border-radius: 50%; border-top: 14px solid #379E8F; width: 90px; height: 90px; -webkit-animation: spin 2s linear infinite; /* Safari */ animation: spin 2s linear infinite;'; // inlineHtml += 'left: 50%; }' //position: fixed; z-index: 1000; // /* Safari */ // inlineHtml += '@-webkit-keyframes spin {0% { -webkit-transform: rotate(0deg); } 100% { -webkit-transform: rotate(360deg); } }'; // inlineHtml += '@keyframes spin { 0% { transform: rotate(0deg); } 100% { transform: rotate(360deg); } }'; // inlineHtml += '</style>'; inlineHtml += zeeDropdownSection(zee_id); // Customer List inlineHtml += dataTable_custlist(); inlineHtml += "</div></div>"; form.addField({ id: "preview_table", label: "inlinehtml", type: "inlinehtml", }).updateLayoutType({ layoutType: ui.FieldLayoutType.STARTROW, }).defaultValue = inlineHtml; form.addField({ id: "custpage_price_change_zee_id", label: "Zee ID", type: ui.FieldType.TEXT, }).updateDisplayType({ displayType: ui.FieldDisplayType.HIDDEN, }).defaultValue = zee_id; form.clientScriptFileId = 5500819; // 5500819 context.response.writePage(form); } else {} } function zeeDropdownSection(zeeid) { var inlineQty = '<div class="form-group container zeeDropdown">'; inlineQty += '<div class="row col-xs-6" style="left: 25%; margin-top: 20px;">'; //col-xs-6 d-flex justify-content-center inlineQty += '<div class="input-group">'; inlineQty += '<span style="background-color: #379E8F; color: white;" class="input-group-addon">Franchisee</span>'; inlineQty += '<select id="zee_filter_dropdown" class="form-control" required>'; inlineQty += "<option></option>"; var zeesSearch = search.load({ type: "partner", id: "customsearch_smc_franchisee", }); // zeesSearch.filters.push(search.createFilter({ // name: 'entityid', // operator: search.Operator.DOESNOTSTARTWITH, // values: 'Test' // })) var zeesSearchResults = zeesSearch.run(); log.audit({ title: "JSON Stringify - zeesSearchResults", details: JSON.stringify(zeesSearchResults), }); zeesSearchResults.each(function(zeesSearchResult) { var zee_id = zeesSearchResult.getValue({ name: "internalid", summmary: search.Summary.GROUP, }); var zee_name = zeesSearchResult.getValue({ name: "companyname", summmary: search.Summary.GROUP, }); var zee_state = zeesSearchResult.getText({ name: "location" }); if (zee_id == zeeid) { inlineQty += '<option value="' + zee_id + '" state="' + zee_state + '" selected>' + zee_name + "</option>"; } else { inlineQty += '<option value="' + zee_id + '" state="' + zee_state + '">' + zee_name + "</option>"; } return true; }); inlineQty += "</select>"; inlineQty += "</div>"; inlineQty += "</div></div>"; return inlineQty; } /** * The table that will display the differents invoices linked to the franchisee and the time period. * @return {String} inlineQty */ function dataTable_custlist() { var inlineQty = "<style>table#table_preview {font-size: 12px;text-align: center;border: none;}.dataTables_wrapper {font-size: 14px;}table#table_preview th{text-align: center;} .bolded{font-weight: bold;}</style>"; inlineQty += '<table id="table_preview" class="table table-responsive table-striped customer tablesorter hide" style="width: 100%;">'; inlineQty += '<thead style="color: white; background-color: #379E8F;">'; inlineQty += '<tr class="text-center">'; inlineQty += "</tr>"; inlineQty += "</thead>"; inlineQty += '<tbody id="result_Table" class="result-Table"></tbody>'; inlineQty += "</table>"; return inlineQty; } function tabsSection() { // var inlineQty = '<div>'; // Tabs headersasdasda var inlineQty = "<style>.nav > li.active > a, .nav > li.active > a:focus, .nav > li.active > a:hover { background-color: #379E8F; color: #fff }"; inlineQty += ".nav > li > a, .nav > li > a:focus, .nav > li > a:hover { margin-left: 5px; margin-right: 5px; border: 2px solid #379E8F; color: #379E8F; }"; inlineQty += "</style>"; inlineQty += '<div class="tabSection" style="width: 95%; margin:auto; margin-bottom: 30px; margin-top: 30px;",><ul class="nav nav-pills nav-justified" style="margin:0%; ">'; inlineQty += '<li role="presentation" class="active"><a data-toggle="tab" href="#edit"><b>Edit</b></a></li>'; inlineQty += '<li role="presentation" class=""><a data-toggle="tab" href="#review"><b>Review</b></a></li>'; inlineQty += '<li role="presentation" class=""><a data-toggle="tab" href="#upload_scf"><b>Upload SCF</b></a></li>'; inlineQty += "</ul></div>"; // Tabs content inlineQty += '<div class="tab-content">'; // if (!isFinanceRole(userRole)) { inlineQty += '<div role="tabpanel" class="tab-pane active" id="edit">'; // inlineQty += dataTablePreview('reassign'); inlineQty += editTab("edit"); inlineQty += "</div>"; inlineQty += '<div role="tabpanel" class="tab-pane" id="review">'; inlineQty += reviewTab("review"); inlineQty += "</div>"; inlineQty += '<div role="tabpanel" class="tab-pane" id="upload_scf">'; inlineQty += uploadSCF(); inlineQty += "</div>"; // inlineQty += '</div>'; //</div> return inlineQty; } function commRegSection(commReg) { var inlineQty = "<style>table#comm_reg_preview {font-size: 12px;text-align: center;border: none;}.dataTables_wrapper {font-size: 14px;}table#comm_reg_preview th{text-align: center;} .bolded{font-weight: bold;}</style>"; /** * Comm Reg Header */ inlineQty += '<div class="form-group container comm_header_section">'; inlineQty += '<div class="row">'; inlineQty += '<div class="col-xs-12 heading1">'; inlineQty += '<h4><span style="background-color: #379E8F" class="form-group label label-default col-xs-12">Commencement Register</span></h4>'; inlineQty += "</div></div></div>"; inlineQty += '<table id="comm_reg_preview" class="table table-responsive table-striped customer tablesorter" style="width: 100%;">'; inlineQty += '<thead style="color: white; background-color: #379E8F;">'; inlineQty += '<tr class="text-center">'; // inlineQty += '<th>Commencement Register</th>'; inlineQty += "</tr>"; inlineQty += "</thead>"; inlineQty += '<tbody id="result_data" class="result-data">'; inlineQty += "</tbody>"; inlineQty += "</table>"; inlineQty += '<div class="form-row container comm_reg_section">'; inlineQty += '<div class="row">'; inlineQty += '<div class="col-xs-2"></div>'; // Blank Placeholder inlineQty += '<div class="col-xs-4 schedule_change_section"><input type="button" id="create_new" class="form-control btn btn-success btn-xs create_new" value="New Scheduled Change" data-toggle="tooltip" data-placement="right" title="NEW SCHEDULED CHANGE" /></div>'; inlineQty += '<div class="col-xs-4 cancel_service_section"><input type="button" id="cancel_service" class="form-control btn btn-danger btn-xs cancel_service" value="Cancel Service" data-toggle="tooltip" data-placement="right" title="CANCEL SERVICE" /></div>'; inlineQty += '<div class="col-xs-2"></div>'; // Blank Placeholder inlineQty += "</div>"; inlineQty += "</div>"; return inlineQty; } /** * The table that will display the differents invoices linked to the franchisee and the time period. * @return {String} inlineQty */ function editTab(selector) { var inlineQty = "<style>table#data_preview_" + selector + " {font-size: 12px;text-align: center;border: none;}.dataTables_wrapper {font-size: 14px;}table#data_preview_" + selector + " th{text-align: center;} .bolded{font-weight: bold;}</style>"; /** * Edit Header */ inlineQty += '<div class="form-group container edit_header_section">'; inlineQty += '<div class="row">'; inlineQty += '<div class="col-xs-12 heading1">'; inlineQty += '<h4><span style="background-color: #379E8F" class="form-group label label-default col-xs-12">Edit</span></h4>'; inlineQty += "</div></div></div>"; /** * Date Effective */ inlineQty += '<div class="form-group container date_effective_section">'; inlineQty += '<div class="row">'; // if (isNullorEmpty(dateEffective)) { inlineQty += '<div class="col-xs-6"><div class="input-group"><span style="background-color: #379E8F; color: white;" class="input-group-addon">Date Effective <span class="mandatory">*</span></span><input type="date" id="date_effective" value="" class="form-control date_effective"/></div></div>'; // } else { // start_date = GetFormattedDate(dateEffective); // inlineQty += '<div class="col-xs-7 "><div class="input-group"><span class="input-group-addon">DATE EFFECTIVE <span class="mandatory">*</span></span><input type="date" id="date_effective" value="' + start_date + '" data-olddate="' + dateEffective + '" class="form-control date_effective"/></div></div>'; // } /** * Sales Type */ inlineQty += '<div class="col-xs-6 commencementtype"><div class="input-group"><span style="background-color: #379E8F; color: white;" class="input-group-addon" id="commencementtype_text">Sale Type <span class="mandatory">*</span></span><select id="commencementtype" class="form-control commencementtype"><option></option>'; var col = new Array(); col[0] = search.createColumn({ name: "name", }); col[1] = search.createColumn({ name: "internalId", }); var results = search.create({ type: "customlist_sale_type", columns: col }); results.run().each(function(res) { var listValue = res.getValue({ name: "name" }); var listID = res.getValue({ name: "internalId" }); // if (!isNullorEmpty(sale_type) && sale_type == listID) { // inlineQty += '<option value="' + listID + '" selected>' + listValue + '</option>'; // } else { inlineQty += '<option value="' + listID + '">' + listValue + "</option>"; // } return true; }); inlineQty += "</select></div></div>"; inlineQty += "</div>"; inlineQty += "</div>"; /** * DataTable */ inlineQty += '<table id="data_preview_' + selector + '" class="table table-responsive table-striped customer tablesorter" style="width: 100%;">'; inlineQty += '<thead style="color: white; background-color: #379E8F;">'; inlineQty += '<tr class="text-center">'; inlineQty += "</tr>"; inlineQty += "</thead>"; inlineQty += '<tbody id="result_data" class="result-data"></tbody>'; // inlineQty += '' inlineQty += "</table>"; inlineQty += '<div class="form-row container edit_submit_section">'; inlineQty += '<div class="row">'; inlineQty += '<div class="col-xs-2"></div>'; // Blank Placeholder inlineQty += '<div class="col-xs-4 schedule_change_section"><input type="button" id="sumbit_edit" style="color: #103D39;" class="form-control btn btn-warning btn-xs sumbit_edit" value="Submit" data-toggle="tooltip" data-placement="right" title="Submit" /></div>'; // <button style="margin-left: 10px; margin-right: 5px; background-color: #FBEA51; color: #103D39; font-weight: 700; border-color: transparent; border-width: 2px; border-radius: 15px; height: 30px" type="button" id="smc" class="">Service Management Console</button>'; inlineQty += '<div class="col-xs-4 cancel_service_section"><input type="button" id="next_customer" style="color: #103D39;" class="form-control btn btn-warning btn-xs next_customer" value="Next Customer" data-toggle="tooltip" data-placement="right" title="Next Customer" /></div>'; inlineQty += '<div class="col-xs-2"></div>'; // Blank Placeholder inlineQty += "</div>"; inlineQty += "</div>"; return inlineQty; } /** * The table that will display the differents invoices linked to the franchisee and the time period. * @return {String} inlineQty */ function reviewTab(selector) { var inlineQty = "<style>table#data_preview_" + selector + " {font-size: 12px;text-align: center;border: none;}.dataTables_wrapper {font-size: 14px;}table#data_preview_" + selector + " th{text-align: center;} .bolded{font-weight: bold;}</style>"; /** * Review Header */ inlineQty += '<div class="form-group container review_header_section">'; inlineQty += '<div class="row">'; inlineQty += '<div class="col-xs-12 heading1">'; inlineQty += '<h4><span style="background-color: #379E8F" class="form-group label label-default col-xs-12">REVIEW</span></h4>'; inlineQty += "</div></div></div>"; inlineQty += '<table id="data_preview_' + selector + '" class="table table-responsive table-striped customer tablesorter" style="width: 100%;">'; inlineQty += '<thead style="color: white; background-color: #379E8F;">'; inlineQty += '<tr class="text-center">'; inlineQty += "</tr>"; inlineQty += "</thead>"; inlineQty += '<tbody id="result_data" class="result-data"></tbody>'; inlineQty += "</table>"; return inlineQty; } function uploadSCF() { var inlineQty = ""; // inlineQty += '<h4 id="primary_table_title" class="primary_table_title_a" style="font-size: 25px; font-weight: 700; color: #103D39; text-align: center">Upload SCF</h4>'; /** * Upload SCF Header */ inlineQty += '<div class="form-group container scf_header_section">'; inlineQty += '<div class="row">'; inlineQty += '<div class="col-xs-12 heading1">'; inlineQty += '<h4><span style="background-color: #379E8F" class="form-group label label-default col-xs-12">Upload SCF</span></h4>'; inlineQty += "</div></div></div>"; inlineQty += "<br>"; inlineQty += '<div class="form-group container scf_header_section">'; inlineQty += '<div class="row">'; inlineQty += '<div class="mb-3">'; inlineQty += '<label for="formFileSm" class="form-label">Upload SCF</label>'; inlineQty += '<input class="form-control form-control-sm" id="upload_scf_file" type="file" name="scf">'; inlineQty += "</div>"; inlineQty += "</div></div>"; return inlineQty; } /** * The period dropdown field. * @param {String} date_from * @param {String} date_to * @return {String} `inlineQty` */ function periodDropdownSection(date_from, date_to) { var selected_option = isNullorEmpty(date_from) && isNullorEmpty(date_to) ? "selected" : ""; var inlineQty = '<div class="form-group container period_dropdown_section">'; inlineQty += '<div class="row">'; // Period dropdown field inlineQty += '<div class="col-xs-12 period_dropdown_div">'; inlineQty += '<div class="input-group">'; inlineQty += '<span class="input-group-addon" id="period_dropdown_text">Period</span>'; inlineQty += '<select id="period_dropdown" class="form-control">'; inlineQty += "<option " + selected_option + "></option>"; inlineQty += '<option value="this_week">This Week</option>'; inlineQty += '<option value="last_week">Last Week</option>'; inlineQty += '<option value="this_month">This Month</option>'; inlineQty += '<option value="last_month">Last Month</option>'; inlineQty += '<option value="full_year">Full Year (1 Jan -)</option>'; inlineQty += '<option value="financial_year">Financial Year (1 Jul -)</option>'; inlineQty += "</select>"; inlineQty += "</div></div></div></div>"; return inlineQty; } /** * Used to pass the values of `date_from` and `date_to` between the scripts and to Netsuite for the records and the search. * @param {String} date_iso "2020-06-01" * @returns {String} date_netsuite "1/6/2020" */ function dateISOToNetsuite(date_iso) { var date_netsuite = ""; if (!isNullorEmpty(date_iso)) { var date_utc = new Date(date_iso); // var date_netsuite = nlapiDateToString(date_utc); var date_netsuite = format.format({ value: date_utc, type: format.Type.DATE, }); } return date_netsuite; } function isNullorEmpty(strVal) { return ( strVal == null || strVal == "" || strVal == "null" || strVal == undefined || strVal == "undefined" || strVal == "- None -" ); } return { onRequest: onRequest, }; });
true
/** * @NApiVersion 2.0 * @NScriptType Suitelet * * Module Description * * NSVersion Date Author * 2.00 2021-09-20 09:33:08 Anesu * * Description: xxxxxxxx * * @Last Modified by: Anesu * @Last Modified time: 2021-09-20 09:33:08 * */ define(["N/ui/serverWidget","N/email","N/runtime","N/search","N/record","N/http","N/log","N/redirect","N/task","N/format",], function(ui,email,runtime,search,record,http,log,redirect,task,format) { var zee = 0; var role = 0; var baseURL = "https://1048144.app.netsuite.com"; if (runtime.EnvType == "SANDBOX") { baseURL = "https://1048144-sb3.app.netsuite.com"; } role = runtime.getCurrentUser().role; if (role == 1000) { zee = runtime.getCurrentUser().id; } else if (role == 3) { //Administrator zee = 6; //test } else if (role == 1032) { // System Support zee = 425904; //test-AR } function onRequest(context) { if (context.request.method === "GET") { type = context.request.parameters.type; var params_params = context.request.parameters; if (!isNullorEmpty(params_params.custparam_params)) { var params = JSON.parse(context.request.parameters.custparam_params); } var zee_id; var commReg; if (!isNullorEmpty(params)) { zee_id = parseInt(params.zeeid); commReg = parseInt(params.commreg); } var form = ui.createForm({ title: " " }); // Load jQuery // var inlineHtml = '<script src="https://code.jquery.com/jquery-1.12.4.min.js" integrity="PI:KEY:ax5kh6jaqkcd2tiexxs8v6xjo8yv8a6bEND_PI" crossorigin="anonymous"></script>'; var inlineHtml = '<script src="https://code.jquery.com/jquery-3.5.0.js" crossorigin="anonymous"></script>'; // Load Tooltip inlineHtml += '<script src="https://unpkg.com/@popperjs/core@2"></script>'; // Load Bootstrap inlineHtml += '<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/3.4.1/css/bootstrap.min.css" integrity="PI:KEY:949d1u22cbffbrarjh182eig55721odjEND_PI" crossorigin="anonymous">'; inlineHtml += '<script src="https://stackpath.bootstrapcdn.com/bootstrap/3.4.1/js/bootstrap.min.js" integrity="PI:KEY:kgfhvu9qnh3mr6eel97y6fq2hezzol8zEND_PI" crossorigin="anonymous"></script>'; // Load DataTables inlineHtml += '<link rel="stylesheet" type="text/css" href="//cdn.datatables.net/1.10.21/css/jquery.dataTables.min.css">'; inlineHtml += '<script type="text/javascript" charset="utf8" src="//cdn.datatables.net/1.10.21/js/jquery.dataTables.min.js"></script>'; inlineHtml += '<script type="text/javascript" charset="utf8" src="//cdn.datatables.net/rowgroup/1.1.3/js/dataTables.rowGroup.min.js"></script> '; inlineHtml += '<script type="text/javascript" charset="utf8" src="//cdn.datatables.net/buttons/2.0.0/js/dataTables.buttons.min.js"></script> '; inlineHtml += '<script type="text/javascript" charset="utf8" src="//cdnjs.cloudflare.com/ajax/libs/jszip/3.1.3/jszip.min.js"></script> '; inlineHtml += '<script type="text/javascript" charset="utf8" src="//cdnjs.cloudflare.com/ajax/libs/pdfmake/0.1.53/pdfmake.min.js"></script> '; inlineHtml += '<script type="text/javascript" charset="utf8" src="//cdnjs.cloudflare.com/ajax/libs/pdfmake/0.1.53/vfs_fonts.js"></script> '; inlineHtml += '<script type="text/javascript" charset="utf8" src="//cdn.datatables.net/buttons/2.0.0/js/buttons.html5.min.js"></script> '; inlineHtml += '<script type="text/javascript" charset="utf8" src="//cdn.datatables.net/buttons/2.0.0/js/buttons.print.min.js"></script> '; // Load Netsuite stylesheet and script inlineHtml += '<link rel="stylesheet" href="https://1048144.app.netsuite.com/core/media/media.nl?id=2060796&c=1048144&h=9ee6accfd476c9cae718&_xt=.css"/>'; inlineHtml += '<script src="https://1048144.app.netsuite.com/core/media/media.nl?id=2060797&c=1048144&h=ef2cda20731d146b5e98&_xt=.js"></script>'; inlineHtml += '<link type="text/css" rel="stylesheet" href="https://1048144.app.netsuite.com/core/media/media.nl?id=2090583&c=1048144&h=a0ef6ac4e28f91203dfe&_xt=.css">'; inlineHtml += "<style>.mandatory{color:red;}</style>"; // Load Bootstrap-Select inlineHtml += '<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap-select@1.13.14/dist/css/bootstrap-select.min.css">'; inlineHtml += '<script src="https://cdn.jsdelivr.net/npm/bootstrap-select@1.13.14/dist/js/bootstrap-select.min.js"></script>'; // Semantic Select inlineHtml += '<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/semantic-ui/2.2.13/semantic.min.css">'; inlineHtml += '<script src="https://cdnjs.cloudflare.com/ajax/libs/semantic-ui/2.2.13/semantic.min.js"></script>'; // Load Search In Dropdown // inlineHtml += '<link href="https://cdnjs.cloudflare.com/ajax/libs/select2/4.0.6-rc.0/css/select2.min.css" rel="stylesheet" />'; // inlineHtml += '<script src="https://cdnjs.cloudflare.com/ajax/libs/select2/4.0.6-rc.0/js/select2.min.js"></script>'; // New Website Color Schemes // Main Color: #379E8F // Background Color: #CFE0CE // Button Color: #FBEA51 // Text Color: #103D39 inlineHtml += '<div class="a" style="width: 100%; background-color: #CFE0CE; padding: 20px; min-height: 100%; height: 100%;">'; // inlineHtml += '<h1 style="text-align: center; color: #103D39; display: inline-block; font-size: 22px; font-weight: bold; line-height: 33px; vertical-align: top; margin-bottom: 4px;">Consolidation Invoice</h1>'; inlineHtml += "<style>.nav > li.active > a, .nav > li.active > a:focus, .nav > li.active > a:hover { background-color: #379E8F; color: #fff }"; inlineHtml += ".nav > li > a, .nav > li > a:focus, .nav > li > a:hover { margin-left: 5px; margin-right: 5px; border: 2px solid #379E8F; color: #379E8F; }"; inlineHtml += "</style>"; // Define alert window. inlineHtml += '<div class="container" style="margin-top:14px;" hidden><div id="alert" class="alert alert-danger fade in"></div></div>'; // Define information window. inlineHtml += '<div class="container" hidden><p id="info" class="alert alert-info"></p></div>'; inlineHtml += '<div style="margin-top: -40px"><br/>'; // Buttons inlineHtml += '<button style="margin-left: 10px; margin-right: 5px; background-color: #FBEA51; color: #103D39; font-weight: 700; border-color: transparent; border-width: 2px; border-radius: 15px; height: 30px" type="button" id="smc" onclick="">Service Management Console</button>'; inlineHtml += '<h1 style="font-size: 25px; font-weight: 700; color: #103D39; text-align: center">Scheduled Price Change</h1>'; // Click for Instructions // inlineHtml += '<button type="button" class="btn btn-sm btn-info instruction_button" data-toggle="collapse" data-target="#demo" style="background-color: #FBEA51; color: #103D39;">Click for Instructions</button><div id="demo" style="background-color: #cfeefc !important;border: 1px solid #417ed9;padding: 10px 10px 10px 20px;width:96%;position:absolute" class="collapse"><b><u>IMPORTANT INSTRUCTIONS:</u></b>'; // inlineHtml += '<ul><li><input type="button" class="btn-xs" style="background-color: #fff; color: black;" disabled value="Submit Search" /> - <ul><li>Click "Submit Search" to load Datatable using current parameters</li></ul></li>' // inlineHtml += '<li>Functionalities available on the Table Collections Table:<ul><li><b>Sort</b><ul><li>Click on column headers to sort collections invoices according to the values in the columns. This is default to "Days Overdue".</li><li>Hold "Shift" and click another column to sort according to multiple columns.</li></ul></li><li><b>Search</b><ul><li>You can search for specific Customer or Invoice by typing into the "Search" field</li></ul></li></ul></li>'; // inlineHtml += '<li>Table Filters:<ul><li><b>Matching MAAP Allocation</b><ul><li><button type="button" class="btn-xs btn-success " disabled><span class="glyphicon glyphicon-plus"></span></button> - Click to apply MAAP Allocation filters search filters on table. ONLY click once. </li><li><button type="button" class="btn-xs btn-danger " disabled><span class="glyphicon glyphicon-minus"></span></button> - Click to remove MAAP Allocation search filter from table. This is set default to "Days Overdue".</li></ul></li> <li><b>MP Ticket Column</b><ul><button type="button" class="btn-xs btn-success" disabled><span class="glyphicon glyphicon-plus"></span></button> - Click to apply MAAP Allocation filters search filters on table. ONLY click once. </li></ul></li></ul></li><li>Clickable Actions Available Per Invoice in DataTable:</li>'; // inlineHtml += '<ul><li><button type="button" class="btn-xs" disabled><span class="span_class glyphicon glyphicon-pencil"></span></button> - Click to open Notes Section for Selected Invoice. (Notes Section is seperate from User Notes)</li>'; // inlineHtml += '<li><button type="button" class="btn-xs btn-secondary" disabled><span class="glyphicon glyphicon-eye-open"></span></button> - Click to Set Invoice has "Viewed" by a member of the Finance Team.</li>'; // inlineHtml += '<li><button type="button" class="btn-xs btn-info" disabled><span class="glyphicon glyphicon-time"></span></button> - Click to view Snooze Timers</li><li><button type="button" class="timer-1day form=control btn-xs btn-info" disabled><span class="span_class">1 Day</span></button> - Click to select Snooze duration of invoice from Table Collections Page.</li>'; // inlineHtml += '</li></ul></div>'; // inlineHtml += '<div class="se-pre-con"></div>' // inlineHtml += '<button type="button" class="btn btn-sm btn-info instruction_button" data-toggle="collapse" data-target="#demo">Click for Instructions</button><div id="demo" style="background-color: #cfeefc !important;border: 1px solid #417ed9;padding: 10px 10px 10px 20px;width:96%;position:absolute" class="collapse"><b><u>IMPORTANT INSTRUCTIONS:</u></b><ul><li>Functionalities available on the Customer listing/table:<ul><li><b>Sort</b><ul><li>Click on column headers to sort customer list according to the values in the columns. This is default to "Customer Name".</li><li>Hold "Shift" and click another column to sort according to multiple columns.</li></ul></li><li><b>Search</b><ul><li>You can search for specific customer by typing into the "Search" field</li></ul></li></ul></li><li>Clickable Actions available per customer:</li><ul><li><button class="btn-xs btn-default" disabled>UPLOAD SCF</button> - <ul><li>Available for customers with missing Service Commencement Forms (SCF) in the system. You will need to upload the latest signed SCF for each relevant customers which outlines the service commencement date along with the Service(s) and Price(s).</li></ul></li><li><button class="btn-xs btn-warning" disabled>REVIEW</button> / <button class="btn-xs btn-primary" disabled>EDIT</button> - <ul><li>Review or Edit customer details (eg. Addresses, Service and Pricing, Packages) to set them up for Run Digitalisation.</li></ul></li><li><button class="btn-xs btn-danger" disabled>CANCEL</button> - <ul><li>You may Cancel non-active customers providing details and reasons around the Cancellation.</li><li>You <b><u>DO NOT NEED</u></b> to cancel customers with <b><u>Adhoc</u></b> arrangements.</li></ul></li><li><button class="btn-xs btn-default" disabled>Duplicate COMMREG</button> - <ul><li>Please contact <b><u>Head Office</u></b> if you see this Action against any customer</li></ul></li></ul></li></ul></ul></div>'; // inlineHtml = '<div class="form-group container loading_section"></div>'; // inlineHtml += '<style> .loading_section { border: 14px solid #f3f3f3; border-radius: 50%; border-top: 14px solid #379E8F; width: 90px; height: 90px; -webkit-animation: spin 2s linear infinite; /* Safari */ animation: spin 2s linear infinite;'; // inlineHtml += 'left: 50%; }' //position: fixed; z-index: 1000; // /* Safari */ // inlineHtml += '@-webkit-keyframes spin {0% { -webkit-transform: rotate(0deg); } 100% { -webkit-transform: rotate(360deg); } }'; // inlineHtml += '@keyframes spin { 0% { transform: rotate(0deg); } 100% { transform: rotate(360deg); } }'; // inlineHtml += '</style>'; inlineHtml += zeeDropdownSection(zee_id); // Customer List inlineHtml += dataTable_custlist(); inlineHtml += "</div></div>"; form.addField({ id: "preview_table", label: "inlinehtml", type: "inlinehtml", }).updateLayoutType({ layoutType: ui.FieldLayoutType.STARTROW, }).defaultValue = inlineHtml; form.addField({ id: "custpage_price_change_zee_id", label: "Zee ID", type: ui.FieldType.TEXT, }).updateDisplayType({ displayType: ui.FieldDisplayType.HIDDEN, }).defaultValue = zee_id; form.clientScriptFileId = 5500819; // 5500819 context.response.writePage(form); } else {} } function zeeDropdownSection(zeeid) { var inlineQty = '<div class="form-group container zeeDropdown">'; inlineQty += '<div class="row col-xs-6" style="left: 25%; margin-top: 20px;">'; //col-xs-6 d-flex justify-content-center inlineQty += '<div class="input-group">'; inlineQty += '<span style="background-color: #379E8F; color: white;" class="input-group-addon">Franchisee</span>'; inlineQty += '<select id="zee_filter_dropdown" class="form-control" required>'; inlineQty += "<option></option>"; var zeesSearch = search.load({ type: "partner", id: "customsearch_smc_franchisee", }); // zeesSearch.filters.push(search.createFilter({ // name: 'entityid', // operator: search.Operator.DOESNOTSTARTWITH, // values: 'Test' // })) var zeesSearchResults = zeesSearch.run(); log.audit({ title: "JSON Stringify - zeesSearchResults", details: JSON.stringify(zeesSearchResults), }); zeesSearchResults.each(function(zeesSearchResult) { var zee_id = zeesSearchResult.getValue({ name: "internalid", summmary: search.Summary.GROUP, }); var zee_name = zeesSearchResult.getValue({ name: "companyname", summmary: search.Summary.GROUP, }); var zee_state = zeesSearchResult.getText({ name: "location" }); if (zee_id == zeeid) { inlineQty += '<option value="' + zee_id + '" state="' + zee_state + '" selected>' + zee_name + "</option>"; } else { inlineQty += '<option value="' + zee_id + '" state="' + zee_state + '">' + zee_name + "</option>"; } return true; }); inlineQty += "</select>"; inlineQty += "</div>"; inlineQty += "</div></div>"; return inlineQty; } /** * The table that will display the differents invoices linked to the franchisee and the time period. * @return {String} inlineQty */ function dataTable_custlist() { var inlineQty = "<style>table#table_preview {font-size: 12px;text-align: center;border: none;}.dataTables_wrapper {font-size: 14px;}table#table_preview th{text-align: center;} .bolded{font-weight: bold;}</style>"; inlineQty += '<table id="table_preview" class="table table-responsive table-striped customer tablesorter hide" style="width: 100%;">'; inlineQty += '<thead style="color: white; background-color: #379E8F;">'; inlineQty += '<tr class="text-center">'; inlineQty += "</tr>"; inlineQty += "</thead>"; inlineQty += '<tbody id="result_Table" class="result-Table"></tbody>'; inlineQty += "</table>"; return inlineQty; } function tabsSection() { // var inlineQty = '<div>'; // Tabs headersasdasda var inlineQty = "<style>.nav > li.active > a, .nav > li.active > a:focus, .nav > li.active > a:hover { background-color: #379E8F; color: #fff }"; inlineQty += ".nav > li > a, .nav > li > a:focus, .nav > li > a:hover { margin-left: 5px; margin-right: 5px; border: 2px solid #379E8F; color: #379E8F; }"; inlineQty += "</style>"; inlineQty += '<div class="tabSection" style="width: 95%; margin:auto; margin-bottom: 30px; margin-top: 30px;",><ul class="nav nav-pills nav-justified" style="margin:0%; ">'; inlineQty += '<li role="presentation" class="active"><a data-toggle="tab" href="#edit"><b>Edit</b></a></li>'; inlineQty += '<li role="presentation" class=""><a data-toggle="tab" href="#review"><b>Review</b></a></li>'; inlineQty += '<li role="presentation" class=""><a data-toggle="tab" href="#upload_scf"><b>Upload SCF</b></a></li>'; inlineQty += "</ul></div>"; // Tabs content inlineQty += '<div class="tab-content">'; // if (!isFinanceRole(userRole)) { inlineQty += '<div role="tabpanel" class="tab-pane active" id="edit">'; // inlineQty += dataTablePreview('reassign'); inlineQty += editTab("edit"); inlineQty += "</div>"; inlineQty += '<div role="tabpanel" class="tab-pane" id="review">'; inlineQty += reviewTab("review"); inlineQty += "</div>"; inlineQty += '<div role="tabpanel" class="tab-pane" id="upload_scf">'; inlineQty += uploadSCF(); inlineQty += "</div>"; // inlineQty += '</div>'; //</div> return inlineQty; } function commRegSection(commReg) { var inlineQty = "<style>table#comm_reg_preview {font-size: 12px;text-align: center;border: none;}.dataTables_wrapper {font-size: 14px;}table#comm_reg_preview th{text-align: center;} .bolded{font-weight: bold;}</style>"; /** * Comm Reg Header */ inlineQty += '<div class="form-group container comm_header_section">'; inlineQty += '<div class="row">'; inlineQty += '<div class="col-xs-12 heading1">'; inlineQty += '<h4><span style="background-color: #379E8F" class="form-group label label-default col-xs-12">Commencement Register</span></h4>'; inlineQty += "</div></div></div>"; inlineQty += '<table id="comm_reg_preview" class="table table-responsive table-striped customer tablesorter" style="width: 100%;">'; inlineQty += '<thead style="color: white; background-color: #379E8F;">'; inlineQty += '<tr class="text-center">'; // inlineQty += '<th>Commencement Register</th>'; inlineQty += "</tr>"; inlineQty += "</thead>"; inlineQty += '<tbody id="result_data" class="result-data">'; inlineQty += "</tbody>"; inlineQty += "</table>"; inlineQty += '<div class="form-row container comm_reg_section">'; inlineQty += '<div class="row">'; inlineQty += '<div class="col-xs-2"></div>'; // Blank Placeholder inlineQty += '<div class="col-xs-4 schedule_change_section"><input type="button" id="create_new" class="form-control btn btn-success btn-xs create_new" value="New Scheduled Change" data-toggle="tooltip" data-placement="right" title="NEW SCHEDULED CHANGE" /></div>'; inlineQty += '<div class="col-xs-4 cancel_service_section"><input type="button" id="cancel_service" class="form-control btn btn-danger btn-xs cancel_service" value="Cancel Service" data-toggle="tooltip" data-placement="right" title="CANCEL SERVICE" /></div>'; inlineQty += '<div class="col-xs-2"></div>'; // Blank Placeholder inlineQty += "</div>"; inlineQty += "</div>"; return inlineQty; } /** * The table that will display the differents invoices linked to the franchisee and the time period. * @return {String} inlineQty */ function editTab(selector) { var inlineQty = "<style>table#data_preview_" + selector + " {font-size: 12px;text-align: center;border: none;}.dataTables_wrapper {font-size: 14px;}table#data_preview_" + selector + " th{text-align: center;} .bolded{font-weight: bold;}</style>"; /** * Edit Header */ inlineQty += '<div class="form-group container edit_header_section">'; inlineQty += '<div class="row">'; inlineQty += '<div class="col-xs-12 heading1">'; inlineQty += '<h4><span style="background-color: #379E8F" class="form-group label label-default col-xs-12">Edit</span></h4>'; inlineQty += "</div></div></div>"; /** * Date Effective */ inlineQty += '<div class="form-group container date_effective_section">'; inlineQty += '<div class="row">'; // if (isNullorEmpty(dateEffective)) { inlineQty += '<div class="col-xs-6"><div class="input-group"><span style="background-color: #379E8F; color: white;" class="input-group-addon">Date Effective <span class="mandatory">*</span></span><input type="date" id="date_effective" value="" class="form-control date_effective"/></div></div>'; // } else { // start_date = GetFormattedDate(dateEffective); // inlineQty += '<div class="col-xs-7 "><div class="input-group"><span class="input-group-addon">DATE EFFECTIVE <span class="mandatory">*</span></span><input type="date" id="date_effective" value="' + start_date + '" data-olddate="' + dateEffective + '" class="form-control date_effective"/></div></div>'; // } /** * Sales Type */ inlineQty += '<div class="col-xs-6 commencementtype"><div class="input-group"><span style="background-color: #379E8F; color: white;" class="input-group-addon" id="commencementtype_text">Sale Type <span class="mandatory">*</span></span><select id="commencementtype" class="form-control commencementtype"><option></option>'; var col = new Array(); col[0] = search.createColumn({ name: "name", }); col[1] = search.createColumn({ name: "internalId", }); var results = search.create({ type: "customlist_sale_type", columns: col }); results.run().each(function(res) { var listValue = res.getValue({ name: "name" }); var listID = res.getValue({ name: "internalId" }); // if (!isNullorEmpty(sale_type) && sale_type == listID) { // inlineQty += '<option value="' + listID + '" selected>' + listValue + '</option>'; // } else { inlineQty += '<option value="' + listID + '">' + listValue + "</option>"; // } return true; }); inlineQty += "</select></div></div>"; inlineQty += "</div>"; inlineQty += "</div>"; /** * DataTable */ inlineQty += '<table id="data_preview_' + selector + '" class="table table-responsive table-striped customer tablesorter" style="width: 100%;">'; inlineQty += '<thead style="color: white; background-color: #379E8F;">'; inlineQty += '<tr class="text-center">'; inlineQty += "</tr>"; inlineQty += "</thead>"; inlineQty += '<tbody id="result_data" class="result-data"></tbody>'; // inlineQty += '' inlineQty += "</table>"; inlineQty += '<div class="form-row container edit_submit_section">'; inlineQty += '<div class="row">'; inlineQty += '<div class="col-xs-2"></div>'; // Blank Placeholder inlineQty += '<div class="col-xs-4 schedule_change_section"><input type="button" id="sumbit_edit" style="color: #103D39;" class="form-control btn btn-warning btn-xs sumbit_edit" value="Submit" data-toggle="tooltip" data-placement="right" title="Submit" /></div>'; // <button style="margin-left: 10px; margin-right: 5px; background-color: #FBEA51; color: #103D39; font-weight: 700; border-color: transparent; border-width: 2px; border-radius: 15px; height: 30px" type="button" id="smc" class="">Service Management Console</button>'; inlineQty += '<div class="col-xs-4 cancel_service_section"><input type="button" id="next_customer" style="color: #103D39;" class="form-control btn btn-warning btn-xs next_customer" value="Next Customer" data-toggle="tooltip" data-placement="right" title="Next Customer" /></div>'; inlineQty += '<div class="col-xs-2"></div>'; // Blank Placeholder inlineQty += "</div>"; inlineQty += "</div>"; return inlineQty; } /** * The table that will display the differents invoices linked to the franchisee and the time period. * @return {String} inlineQty */ function reviewTab(selector) { var inlineQty = "<style>table#data_preview_" + selector + " {font-size: 12px;text-align: center;border: none;}.dataTables_wrapper {font-size: 14px;}table#data_preview_" + selector + " th{text-align: center;} .bolded{font-weight: bold;}</style>"; /** * Review Header */ inlineQty += '<div class="form-group container review_header_section">'; inlineQty += '<div class="row">'; inlineQty += '<div class="col-xs-12 heading1">'; inlineQty += '<h4><span style="background-color: #379E8F" class="form-group label label-default col-xs-12">REVIEW</span></h4>'; inlineQty += "</div></div></div>"; inlineQty += '<table id="data_preview_' + selector + '" class="table table-responsive table-striped customer tablesorter" style="width: 100%;">'; inlineQty += '<thead style="color: white; background-color: #379E8F;">'; inlineQty += '<tr class="text-center">'; inlineQty += "</tr>"; inlineQty += "</thead>"; inlineQty += '<tbody id="result_data" class="result-data"></tbody>'; inlineQty += "</table>"; return inlineQty; } function uploadSCF() { var inlineQty = ""; // inlineQty += '<h4 id="primary_table_title" class="primary_table_title_a" style="font-size: 25px; font-weight: 700; color: #103D39; text-align: center">Upload SCF</h4>'; /** * Upload SCF Header */ inlineQty += '<div class="form-group container scf_header_section">'; inlineQty += '<div class="row">'; inlineQty += '<div class="col-xs-12 heading1">'; inlineQty += '<h4><span style="background-color: #379E8F" class="form-group label label-default col-xs-12">Upload SCF</span></h4>'; inlineQty += "</div></div></div>"; inlineQty += "<br>"; inlineQty += '<div class="form-group container scf_header_section">'; inlineQty += '<div class="row">'; inlineQty += '<div class="mb-3">'; inlineQty += '<label for="formFileSm" class="form-label">Upload SCF</label>'; inlineQty += '<input class="form-control form-control-sm" id="upload_scf_file" type="file" name="scf">'; inlineQty += "</div>"; inlineQty += "</div></div>"; return inlineQty; } /** * The period dropdown field. * @param {String} date_from * @param {String} date_to * @return {String} `inlineQty` */ function periodDropdownSection(date_from, date_to) { var selected_option = isNullorEmpty(date_from) && isNullorEmpty(date_to) ? "selected" : ""; var inlineQty = '<div class="form-group container period_dropdown_section">'; inlineQty += '<div class="row">'; // Period dropdown field inlineQty += '<div class="col-xs-12 period_dropdown_div">'; inlineQty += '<div class="input-group">'; inlineQty += '<span class="input-group-addon" id="period_dropdown_text">Period</span>'; inlineQty += '<select id="period_dropdown" class="form-control">'; inlineQty += "<option " + selected_option + "></option>"; inlineQty += '<option value="this_week">This Week</option>'; inlineQty += '<option value="last_week">Last Week</option>'; inlineQty += '<option value="this_month">This Month</option>'; inlineQty += '<option value="last_month">Last Month</option>'; inlineQty += '<option value="full_year">Full Year (1 Jan -)</option>'; inlineQty += '<option value="financial_year">Financial Year (1 Jul -)</option>'; inlineQty += "</select>"; inlineQty += "</div></div></div></div>"; return inlineQty; } /** * Used to pass the values of `date_from` and `date_to` between the scripts and to Netsuite for the records and the search. * @param {String} date_iso "2020-06-01" * @returns {String} date_netsuite "1/6/2020" */ function dateISOToNetsuite(date_iso) { var date_netsuite = ""; if (!isNullorEmpty(date_iso)) { var date_utc = new Date(date_iso); // var date_netsuite = nlapiDateToString(date_utc); var date_netsuite = format.format({ value: date_utc, type: format.Type.DATE, }); } return date_netsuite; } function isNullorEmpty(strVal) { return ( strVal == null || strVal == "" || strVal == "null" || strVal == undefined || strVal == "undefined" || strVal == "- None -" ); } return { onRequest: onRequest, }; });
/** *@NApiVersion 2.x *@NScriptType ScheduledScript */ define(['N/task', 'N/email', 'N/runtime', 'N/search', 'N/record', 'N/format', 'N/https'], function(task, email, runtime, search, record, format, https) { function execute(context) { var todayDate = new Date(); log.audit({ title: 'todayDate', details: todayDate }); //To get todays date var today = format.format({ value: todayDate, type: format.Type.DATE }); log.audit({ title: 'today', details: today }); var tempTodayDate = today.split('/'); // var temp = tempTodayDate.split('-'); // var today = tempTodayDate[0] + '/' + tempTodayDate[1] + '/' + tempTodayDate[2]; var today = '02-05-2021'; log.audit({ title: 'today', details: today }); var scanJSONSearch = search.load({ id: 'customsearch_scan_json' }); scanJSONSearch.filters.push(search.createFilter({ name: 'name', join: null, operator: search.Operator.STARTSWITH, values: '02-05-2021_Part_2' })); scanJSONSearch.filters.push(search.createFilter({ name: 'custrecord_scan_josn_sync', join: null, operator: search.Operator.IS, values: 2 })); scanJSONSearch.filters.push(search.createFilter({ name: 'isinactive', join: null, operator: search.Operator.IS, values: "F" })); var scan_json_record_id; scanJSONSearch.run().each(function(searchResult) { var scriptObj = runtime.getCurrentScript() var usage_loopstart_cust = scriptObj.getRemainingUsage(); log.audit({ title: 'Start of SCAN JSON Loop', details: usage_loopstart_cust }); var scan_json_record_id = searchResult.getValue({ name: 'internalid' }); var scan_json_record_name = searchResult.getValue({ name: "name" }); log.audit({ title: 'Scan JSON Record Name ', details: scan_json_record_name }); var scan_json_record = record.load({ type: 'customrecord_scan_json', id: scan_json_record_id }); var body = scan_json_record.getValue({ fieldId: 'custrecord_json' }); var body_2 = scan_json_record.getValue({ fieldId: 'custrecord_scan_json_2' }); if (body_2 == "") { var todays_scans = JSON.parse(body); var barcodes = todays_scans.scans; //No. of barcodes } else { var todays_scans = JSON.parse(body_2); var barcodes = todays_scans.scans; //No. of barcodes } log.audit({ title: 'barcodes', details: barcodes }); log.audit({ title: 'barcodes length', details: barcodes.length }); if (barcodes.length > 0) { //Iterate through each barcode do { var x = barcodes.length - 1; var scriptObj = runtime.getCurrentScript() var usage_loopstart_cust = scriptObj.getRemainingUsage(); //Usage at the start of each barcode log.audit({ title: 'Start of Barcode Loop', details: scriptObj.getRemainingUsage() }); log.audit({ title: 'Scans for barcode: ' + barcodes[x].code, details: barcodes[x].scans }); var scans = barcodes[x].scans; log.audit({ title: 'Scans Length for barcode: ' + barcodes[x].code, details: scans.length }); //Only one scan history for the barcode if (scans.length == 1) { log.audit({ title: 'Inside Scan Length = 1', details: barcodes[x].code }); var y = 0; var scriptObj = runtime.getCurrentScript() var usage_loopstart_cust = scriptObj.getRemainingUsage(); //Usage at the start of each scan type log.audit({ title: 'Start of Scans Loop per barcode', details: scriptObj.getRemainingUsage() }); log.audit({ title: 'Scans for barcode: ' + barcodes[x].code, details: scans[y] }); log.audit({ title: 'Scans for barcode: ' + barcodes[x].code, details: scans[y].scan_type }); var barcode = scans[y].barcode.toUpperCase(); var customer_id = scans[y].customer_ns_id; var zee_id = scans[y].zee_ns_id; var rta_id = scans[y].id; var invoiceable = scans[y].invoiceable; var scan_type = scans[y].scan_type.toLowerCase(); var operator_id = scans[y].operator_ns_id; var updated_at = scans[y].updated_at; var deleted = scans[y].deleted; var external_barcode = scans[y].external_barcode; var source = scans[y].source; var receiver_suburb = scans[y].receiver_suburb; var receiver_postcode = scans[y].post_code; var receiver_state = scans[y].state; var receiver_addr1 = scans[y].address1; var receiver_addr2 = scans[y].address2; var receiver_name = scans[y].receiver_name; var receiver_email = scans[y].email; var receiver_phone = scans[y].phone; updated_at = updated_at.split("T"); var time_updated_at = updated_at[1]; time_updated_at = time_updated_at.split("."); time_updated_at = onTimeChange(time_updated_at[0]); time_updated_at = format.parse({ value: time_updated_at, type: format.Type.TIMEOFDAY }); log.audit({ title: 'TIME OF DAY', details: time_updated_at }); var updated_at = updated_at[0]; var save_barcode = true; var barcode_beg = barcode.slice(0, 4); updated_at = updated_at.split("-"); updated_at = format.parse({ value: updated_at[2] + '/' + updated_at[1] + '/' + updated_at[0], type: format.Type.DATE }); log.audit({ title: 'DATE', details: updated_at }); // updated_at = nlapiStringToDate(updated_at[2] + '/' + updated_at[1] + '/' + updated_at[0]); //Load Search: RTA - Product Stock var productStockSearch = search.load({ id: 'customsearch_rta_product_stock' }); productStockSearch.filters.push(search.createFilter({ name: 'name', join: null, operator: search.Operator.IS, values: barcode })); productStockSearch.filters.push(search.createFilter({ name: 'isinactive', join: null, operator: search.Operator.IS, values: "F" })); var count = 0; var prod_id; productStockSearch.run().each(function(searchResult) { log.audit({ title: 'Barcode does exist', details: scans[y].scan_type.toLowerCase() }); var customer_prod_stock_id = searchResult.getValue({ name: 'internalid' }); //Load the customer product stock record var customerProdStockRecord = record.load({ type: 'customrecord_customer_product_stock', id: customer_prod_stock_id }); //Get the current status of the record. var stock_status = customerProdStockRecord.getValue({ fieldId: 'custrecord_cust_prod_stock_status' }); //Status is Product Order Created or Invoiced if (stock_status != 6 && stock_status != 7) { if (scan_type == 'stockzee') { if (!isNullorEmpty(zee_id)) { //Set status as Zee stock customerProdStockRecord.setValue({ fieldId: 'custrecord_cust_prod_stock_status', value: 8 }); customerProdStockRecord.setText({ fieldId: 'custrecord_cust_date_stock_given', value: updated_at }); customerProdStockRecord.setText({ fieldId: 'custrecord_cust_time_stock_given', value: time_updated_at }); customerProdStockRecord.setValue({ fieldId: 'custrecord_cust_prod_stock_customer', value: null }); customerProdStockRecord.setValue({ fieldId: 'custrecord_cust_prod_stock_zee', value: zee_id }); } else { //Send email if no Zee ID email.send({ author: 409635, recipients: 'ankith.ravindran@mailplus.comau', subject: 'MPEX Scan Sync - Error', body: 'Barcode: ' + barcode + ' has empty Zee ID' }); save_barcode = false; } } else if (scan_type == 'allocate') { if (!isNullorEmpty(customer_id)) { //Invoiceable field is set to false if (invoiceable === false || invoiceable == 'false' || invoiceable === 'false' || invoiceable == false) { //Set invoiceable as NO customerProdStockRecord.setValue({ fieldId: 'custrecord_cust_prod_stock_invoiceable', value: 2 }); //Set Prepaid as YES customerProdStockRecord.setValue({ fieldId: 'custrecord_cust_prod_stock_prepaid', value: 1 }); } customerProdStockRecord.setValue({ fieldId: 'custrecord_cust_prod_stock_customer', value: customer_id }); customerProdStockRecord.setValue({ fieldId: 'custrecord_cust_prod_stock_status', value: 1 }); customerProdStockRecord.setText({ fieldId: 'custrecord_cust_date_stock_given', value: updated_at }); customerProdStockRecord.setText({ fieldId: 'custrecord_cust_time_stock_given', value: time_updated_at }); } else { email.send({ author: 409635, recipients: 'ankith.ravindran@mailplus.comau', subject: 'MPEX Scan Sync - Error', body: 'Barcode: ' + barcode + ' has empty Customer ID' }); save_barcode = false; } } else if (scan_type == 'pickup') { if (!isNullorEmpty(customer_id)) { //Invoiceable field is set to false if (invoiceable === false || invoiceable == 'false' || invoiceable === 'false' || invoiceable == false) { //Set invoiceable as NO customerProdStockRecord.setValue({ fieldId: 'custrecord_cust_prod_stock_invoiceable', value: 2 }); //Set Prepaid as YES customerProdStockRecord.setValue({ fieldId: 'custrecord_cust_prod_stock_prepaid', value: 1 }); } customerProdStockRecord.setValue({ fieldId: 'custrecord_cust_prod_stock_customer', value: customer_id }); customerProdStockRecord.setValue({ fieldId: 'custrecord_cust_prod_stock_status', value: 2 }); customerProdStockRecord.setText({ fieldId: 'custrecord_cust_date_stock_given', value: updated_at }); customerProdStockRecord.setText({ fieldId: 'custrecord_cust_time_stock_given', value: time_updated_at }); } else { email.send({ author: 409635, recipients: 'ankith.ravindran@mailplus.comau', subject: 'MPEX Scan Sync - Error', body: 'Barcode: ' + barcode + ' has empty Customer ID' }); save_barcode = false; } } else if (scan_type == "delivery") { if (!isNullorEmpty(customer_id)) { //Invoiceable field is set to false if (invoiceable === false || invoiceable == 'false' || invoiceable === 'false' || invoiceable == false) { //Set invoiceable as NO customerProdStockRecord.setValue({ fieldId: 'custrecord_cust_prod_stock_invoiceable', value: 2 }); //Set Prepaid as YES customerProdStockRecord.setValue({ fieldId: 'custrecord_cust_prod_stock_prepaid', value: 1 }); } customerProdStockRecord.setValue({ fieldId: 'custrecord_cust_prod_stock_customer', value: customer_id }); customerProdStockRecord.setValue({ fieldId: 'custrecord_cust_prod_stock_status', value: 4 }); customerProdStockRecord.setValue({ fieldId: 'custrecord_cust_prod_stock_final_del', value: 4 }); customerProdStockRecord.setText({ fieldId: 'custrecord_cust_date_stock_given', value: updated_at }); customerProdStockRecord.setText({ fieldId: 'custrecord_cust_time_stock_given', value: time_updated_at }); } else { email.send({ author: 409635, recipients: 'ankith.ravindran@mailplus.comau', subject: 'MPEX Scan Sync - Error', body: 'Barcode: ' + barcode + ' has empty Customer ID' }); save_barcode = false; } } else if (scan_type == "lodgement") { if (!isNullorEmpty(customer_id)) { //Invoiceable field is set to false if (invoiceable === false || invoiceable == 'false' || invoiceable === 'false' || invoiceable == false) { //Set invoiceable as NO customerProdStockRecord.setValue({ fieldId: 'custrecord_cust_prod_stock_invoiceable', value: 2 }); //Set Prepaid as YES customerProdStockRecord.setValue({ fieldId: 'custrecord_cust_prod_stock_prepaid', value: 1 }); } customerProdStockRecord.setValue({ fieldId: 'custrecord_cust_prod_stock_customer', value: customer_id }); customerProdStockRecord.setValue({ fieldId: 'custrecord_cust_prod_stock_status', value: 5 }); customerProdStockRecord.setValue({ fieldId: 'custrecord_cust_prod_stock_final_del', value: 5 }); customerProdStockRecord.setText({ fieldId: 'custrecord_cust_date_stock_given', value: updated_at }); customerProdStockRecord.setText({ fieldId: 'custrecord_cust_time_stock_given', value: time_updated_at }); } else { email.send({ author: 409635, recipients: 'ankith.ravindran@mailplus.comau', subject: 'MPEX Scan Sync - Error', body: 'Barcode: ' + barcode + ' has empty Customer ID' }); save_barcode = false; } } if (save_barcode == true) { customerProdStockRecord.setValue({ fieldId: 'custrecord_cust_prod_stock_source', value: 6 }); customerProdStockRecord.setValue({ fieldId: 'custrecord_cust_prod_stock_operator', value: operator_id }); customerProdStockRecord.setValue({ fieldId: 'custrecord_mpdl_number', value: external_barcode }); var sourceId = getSourceID(source); if (sourceId != null) { customerProdStockRecord.setValue({ fieldId: 'custrecord_barcode_source', value: sourceId }); } customerProdStockRecord.setValue({ fieldId: 'custrecord_receiver_suburb', value: receiver_suburb }); customerProdStockRecord.setValue({ fieldId: 'custrecord_receiver_postcode', value: receiver_postcode }); customerProdStockRecord.setValue({ fieldId: 'custrecord_receiver_state', value: receiver_state }); customerProdStockRecord.setValue({ fieldId: 'custrecord_receiver_addr1', value: receiver_addr1 }); customerProdStockRecord.setValue({ fieldId: 'custrecord_receiver_addr2', value: receiver_addr2 }); customerProdStockRecord.setValue({ fieldId: 'custrecord_receiver_name', value: receiver_name }); customerProdStockRecord.setValue({ fieldId: 'custrecord_receiver_email', value: receiver_email }); customerProdStockRecord.setValue({ fieldId: 'custrecord_receiver_phone', value: receiver_phone }); //Invoiceable field is set to false if (invoiceable === false || invoiceable == 'false' || invoiceable === 'false' || invoiceable == false) { //Set invoiceable as NO customerProdStockRecord.setValue({ fieldId: 'custrecord_cust_prod_stock_invoiceable', value: 2 }); //Set Prepaid as YES customerProdStockRecord.setValue({ fieldId: 'custrecord_cust_prod_stock_prepaid', value: 1 }); } log.audit({ title: 'barcode_beg', details: barcode_beg }); if (barcode_beg == 'MPEN' || barcode_beg == 'MPET' || barcode_beg == 'MPEF' || barcode_beg == 'MPEB' || barcode_beg == 'MPEC' || barcode_beg == 'MPED' || barcode_beg == 'MPEG') { if (barcode_beg == 'MPEN') { prod_id = 552; } else if (barcode_beg == 'MPET') { prod_id = 553; } else if (barcode_beg == 'MPEF') { prod_id = 554; } else if (barcode_beg == 'MPEB') { prod_id = 550; } else if (barcode_beg == 'MPEC') { prod_id = 551; } else if (barcode_beg == 'MPED') { prod_id = 549; } else if (barcode_beg == 'MPEG') { prod_id = 638; } log.audit({ title: 'prod_id', details: prod_id }); customerProdStockRecord.setValue({ fieldId: 'custrecord_cust_stock_prod_name', value: prod_id }); } customer_prod_stock_id = customerProdStockRecord.save(); } } count++; return true; }); if (count == 0) { log.audit({ title: 'Barcode does not exist', details: scans[y].scan_type }); var save_barcode = true; if (isNullorEmpty(deleted)) { var customerProdStockRecord = record.create({ type: 'customrecord_customer_product_stock', isDynamic: true }); customerProdStockRecord.setText({ fieldId: 'custrecord_cust_date_stock_given', value: updated_at }); customerProdStockRecord.setText({ fieldId: 'custrecord_cust_time_stock_given', value: time_updated_at }); //Invoiceable field is set to false if (invoiceable === false || invoiceable == 'false' || invoiceable === 'false' || invoiceable == false) { //Set invoiceable as NO customerProdStockRecord.setValue({ fieldId: 'custrecord_cust_prod_stock_invoiceable', value: 2 }); //Set Prepaid as YES customerProdStockRecord.setValue({ fieldId: 'custrecord_cust_prod_stock_prepaid', value: 1 }); } customerProdStockRecord.setValue({ fieldId: 'name', value: barcode }); if (scan_type == 'stockzee') { if (!isNullorEmpty(zee_id)) { //Set status as Zee stock customerProdStockRecord.setValue({ fieldId: 'custrecord_cust_prod_stock_status', value: 8 }); customerProdStockRecord.setText({ fieldId: 'custrecord_cust_date_stock_given', value: updated_at }); customerProdStockRecord.setText({ fieldId: 'custrecord_cust_time_stock_given', value: time_updated_at }); customerProdStockRecord.setValue({ fieldId: 'custrecord_cust_prod_stock_customer', value: null }); customerProdStockRecord.setValue({ fieldId: 'custrecord_cust_prod_stock_zee', value: zee_id }); } else { //Send email if no Zee ID email.send({ author: 409635, recipients: 'ankith.ravindran@mailplus.comau', subject: 'MPEX Scan Sync - Error', body: 'Barcode: ' + barcode + ' has empty Zee ID' }); save_barcode = false; } } else if (scan_type == 'allocate') { if (!isNullorEmpty(customer_id)) { //Invoiceable field is set to false if (invoiceable === false || invoiceable == 'false' || invoiceable === 'false' || invoiceable == false) { //Set invoiceable as NO customerProdStockRecord.setValue({ fieldId: 'custrecord_cust_prod_stock_invoiceable', value: 2 }); //Set Prepaid as YES customerProdStockRecord.setValue({ fieldId: 'custrecord_cust_prod_stock_prepaid', value: 1 }); } customerProdStockRecord.setValue({ fieldId: 'custrecord_cust_prod_stock_customer', value: customer_id }); customerProdStockRecord.setValue({ fieldId: 'custrecord_cust_prod_stock_status', value: 1 }); customerProdStockRecord.setText({ fieldId: 'custrecord_cust_date_stock_given', value: updated_at }); customerProdStockRecord.setText({ fieldId: 'custrecord_cust_time_stock_given', value: time_updated_at }); } else { email.send({ author: 409635, recipients: 'ankith.ravindran@mailplus.comau', subject: 'MPEX Scan Sync - Error', body: 'Barcode: ' + barcode + ' has empty Customer ID' }); save_barcode = false; } } else if (scan_type == 'pickup') { if (!isNullorEmpty(customer_id)) { //Invoiceable field is set to false if (invoiceable === false || invoiceable == 'false' || invoiceable === 'false' || invoiceable == false) { //Set invoiceable as NO customerProdStockRecord.setValue({ fieldId: 'custrecord_cust_prod_stock_invoiceable', value: 2 }); //Set Prepaid as YES customerProdStockRecord.setValue({ fieldId: 'custrecord_cust_prod_stock_prepaid', value: 1 }); } customerProdStockRecord.setValue({ fieldId: 'custrecord_cust_prod_stock_customer', value: customer_id }); customerProdStockRecord.setValue({ fieldId: 'custrecord_cust_prod_stock_status', value: 2 }); customerProdStockRecord.setText({ fieldId: 'custrecord_cust_date_stock_given', value: updated_at }); customerProdStockRecord.setText({ fieldId: 'custrecord_cust_time_stock_given', value: time_updated_at }); } else { email.send({ author: 409635, recipients: 'ankith.ravindran@mailplus.comau', subject: 'MPEX Scan Sync - Error', body: 'Barcode: ' + barcode + ' has empty Customer ID' }); save_barcode = false; } } else if (scan_type == "delivery") { if (!isNullorEmpty(customer_id)) { //Invoiceable field is set to false if (invoiceable === false || invoiceable == 'false' || invoiceable === 'false' || invoiceable == false) { //Set invoiceable as NO customerProdStockRecord.setValue({ fieldId: 'custrecord_cust_prod_stock_invoiceable', value: 2 }); //Set Prepaid as YES customerProdStockRecord.setValue({ fieldId: 'custrecord_cust_prod_stock_prepaid', value: 1 }); } customerProdStockRecord.setValue({ fieldId: 'custrecord_cust_prod_stock_customer', value: customer_id }); customerProdStockRecord.setValue({ fieldId: 'custrecord_cust_prod_stock_status', value: 4 }); customerProdStockRecord.setValue({ fieldId: 'custrecord_cust_prod_stock_final_del', value: 4 }); customerProdStockRecord.setText({ fieldId: 'custrecord_cust_date_stock_given', value: updated_at }); customerProdStockRecord.setText({ fieldId: 'custrecord_cust_time_stock_given', value: time_updated_at }); } else { email.send({ author: 409635, recipients: 'ankith.ravindran@mailplus.comau', subject: 'MPEX Scan Sync - Error', body: 'Barcode: ' + barcode + ' has empty Customer ID' }); save_barcode = false; } } else if (scan_type == "lodgement") { if (!isNullorEmpty(customer_id)) { //Invoiceable field is set to false if (invoiceable === false || invoiceable == 'false' || invoiceable === 'false' || invoiceable == false) { //Set invoiceable as NO customerProdStockRecord.setValue({ fieldId: 'custrecord_cust_prod_stock_invoiceable', value: 2 }); //Set Prepaid as YES customerProdStockRecord.setValue({ fieldId: 'custrecord_cust_prod_stock_prepaid', value: 1 }); } customerProdStockRecord.setValue({ fieldId: 'custrecord_cust_prod_stock_customer', value: customer_id }); customerProdStockRecord.setValue({ fieldId: 'custrecord_cust_prod_stock_status', value: 5 }); customerProdStockRecord.setValue({ fieldId: 'custrecord_cust_prod_stock_final_del', value: 5 }); customerProdStockRecord.setText({ fieldId: 'custrecord_cust_date_stock_given', value: updated_at }); customerProdStockRecord.setText({ fieldId: 'custrecord_cust_time_stock_given', value: time_updated_at }); } else { email.send({ author: 409635, recipients: 'ankith.ravindran@mailplus.comau', subject: 'MPEX Scan Sync - Error', body: 'Barcode: ' + barcode + ' has empty Customer ID' }); save_barcode = false; } } if (save_barcode == true) { customerProdStockRecord.setValue({ fieldId: 'custrecord_cust_prod_stock_source', value: 6 }); customerProdStockRecord.setValue({ fieldId: 'custrecord_cust_prod_stock_operator', value: operator_id }); customerProdStockRecord.setValue({ fieldId: 'custrecord_mpdl_number', value: external_barcode }); var sourceId = getSourceID(source); if (sourceId != null) { customerProdStockRecord.setValue({ fieldId: 'custrecord_barcode_source', value: sourceId }); } customerProdStockRecord.setValue({ fieldId: 'custrecord_receiver_suburb', value: receiver_suburb }); customerProdStockRecord.setValue({ fieldId: 'custrecord_receiver_postcode', value: receiver_postcode }); customerProdStockRecord.setValue({ fieldId: 'custrecord_receiver_state', value: receiver_state }); customerProdStockRecord.setValue({ fieldId: 'custrecord_receiver_addr1', value: receiver_addr1 }); customerProdStockRecord.setValue({ fieldId: 'custrecord_receiver_addr2', value: receiver_addr2 }); customerProdStockRecord.setValue({ fieldId: 'custrecord_receiver_name', value: receiver_name }); customerProdStockRecord.setValue({ fieldId: 'custrecord_receiver_email', value: receiver_email }); customerProdStockRecord.setValue({ fieldId: 'custrecord_receiver_phone', value: receiver_phone }); //Invoiceable field is set to false if (invoiceable === false || invoiceable == 'false' || invoiceable === 'false' || invoiceable == false) { //Set invoiceable as NO customerProdStockRecord.setValue({ fieldId: 'custrecord_cust_prod_stock_invoiceable', value: 2 }); //Set Prepaid as YES customerProdStockRecord.setValue({ fieldId: 'custrecord_cust_prod_stock_prepaid', value: 1 }); } if (barcode_beg == 'MPEN' || barcode_beg == 'MPET' || barcode_beg == 'MPEF' || barcode_beg == 'MPEB' || barcode_beg == 'MPEC' || barcode_beg == 'MPED' || barcode_beg == 'MPEG') { if (barcode_beg == 'MPEN') { prod_id = 552; } else if (barcode_beg == 'MPET') { prod_id = 553; } else if (barcode_beg == 'MPEF') { prod_id = 554; } else if (barcode_beg == 'MPEB') { prod_id = 550; } else if (barcode_beg == 'MPEC') { prod_id = 551; } else if (barcode_beg == 'MPED') { prod_id = 549; } else if (barcode_beg == 'MPEG') { prod_id = 638; } customerProdStockRecord.setValue({ fieldId: 'custrecord_cust_stock_prod_name', value: prod_id }); } customer_prod_stock_id = customerProdStockRecord.save(); } } } } else { //Iterate through the differenct scans for each barcode for (var y = 0; y < scans.length; y++) { var scriptObj = runtime.getCurrentScript() var usage_loopstart_cust = scriptObj.getRemainingUsage(); //Usage at the start of each scan type log.debug({ title: 'Start of Scans Loop per barcode', details: scriptObj.getRemainingUsage() }); log.debug({ title: 'Scans for barcode: ' + barcodes[x].code, details: scans[y] }); log.debug({ title: 'Scans for barcode: ' + barcodes[x].code, details: scans[y].scan_type }); var barcode = scans[y].barcode.toUpperCase(); var customer_id = scans[y].customer_ns_id; var zee_id = scans[y].zee_ns_id; var rta_id = scans[y].id; var invoiceable = scans[y].invoiceable; var scan_type = scans[y].scan_type.toLowerCase(); var operator_id = scans[y].operator_ns_id; var updated_at = scans[y].updated_at; var deleted = scans[y].deleted; var external_barcode = scans[y].external_barcode; var source = scans[y].source; var receiver_suburb = scans[y].receiver_suburb; var receiver_postcode = scans[y].post_code; var receiver_state = scans[y].state; var receiver_addr1 = scans[y].address1; var receiver_addr2 = scans[y].address2; var receiver_name = scans[y].receiver_name; var receiver_email = scans[y].email; var receiver_phone = scans[y].phone; updated_at = updated_at.split("T"); var time_updated_at = updated_at[1]; time_updated_at = time_updated_at.split("."); time_updated_at = onTimeChange(time_updated_at[0]); time_updated_at = format.parse({ value: time_updated_at, type: format.Type.TIMEOFDAY }); log.debug({ title: 'TIME OF DAY more than 1 scan', details: time_updated_at }); var updated_at = updated_at[0]; var save_barcode = true; var barcode_beg = barcode.slice(0, 4); updated_at = updated_at.split("-"); updated_at = format.parse({ value: updated_at[2] + '/' + updated_at[1] + '/' + updated_at[0], type: format.Type.DATE }) log.debug({ title: 'DATE more than 1 scan', details: updated_at }); // updated_at = nlapiStringToDate(updated_at[2] + '/' + updated_at[1] + '/' + updated_at[0]); // updated_at = nlapiStringToDate(updated_at[2] + '/' + updated_at[1] + '/' + updated_at[0]); //Load Search: RTA - Product Stock var productStockSearch = search.load({ id: 'customsearch_rta_product_stock' }); productStockSearch.filters.push(search.createFilter({ name: 'name', join: null, operator: search.Operator.IS, values: barcode })); productStockSearch.filters.push(search.createFilter({ name: 'isinactive', join: null, operator: search.Operator.IS, values: "F" })); var count = 0; var prod_id; productStockSearch.run().each(function(searchResult) { log.debug({ title: 'Barcode does exist', details: scans[y].scan_type }); var customer_prod_stock_id = searchResult.getValue({ name: 'internalid' }); //Load the customer product stock record var customerProdStockRecord = record.load({ type: 'customrecord_customer_product_stock', id: customer_prod_stock_id }); //Get the current status of the record. var stock_status = customerProdStockRecord.getValue({ fieldId: 'custrecord_cust_prod_stock_status' }); //Status is Product Order Created or Invoiced if (stock_status != 6 && stock_status != 7) { //If the scan has the deleted field if (!isNullorEmpty(deleted)) { //Status is Allocated to custoemer if (stock_status == 1) { customerProdStockRecord.setValue({ fieldId: 'custrecord_cust_prod_stock_customer', value: null }); customerProdStockRecord.setValue({ fieldId: 'custrecord_cust_date_stock_used', value: null }); customerProdStockRecord.setValue({ fieldId: 'custrecord_cust_time_stock_used', value: null }); //Change status to Zee Stock customerProdStockRecord.setValue({ fieldId: 'custrecord_cust_prod_stock_status', value: 8 }); customerProdStockRecord.setValue({ fieldId: 'custrecord_cust_prod_stock_zee', value: zee_id }); } else if (stock_status == 8) { // Status is Zee Stock //Inactivate the record customerProdStockRecord.setValue({ fieldId: 'isinactive', value: true }); customerProdStockRecord.setValue({ fieldId: 'custrecord_cust_time_deleted', value: time_updated_at }); } else if (stock_status == 4 || stock_status == 5) { // Status is Delivered to receiver / Lodged at TOLL //Change status to Allocated to customer customerProdStockRecord.setValue({ fieldId: 'custrecord_cust_prod_stock_status', value: 1 }); } } else if (scan_type == 'stockzee') { if (!isNullorEmpty(zee_id)) { //Set status as Zee stock customerProdStockRecord.setValue({ fieldId: 'custrecord_cust_prod_stock_status', value: 8 }); customerProdStockRecord.setText({ fieldId: 'custrecord_cust_date_stock_given', value: updated_at }); customerProdStockRecord.setText({ fieldId: 'custrecord_cust_time_stock_given', value: time_updated_at }); customerProdStockRecord.setValue({ fieldId: 'custrecord_cust_prod_stock_customer', value: null }); customerProdStockRecord.setValue({ fieldId: 'custrecord_cust_prod_stock_zee', value: zee_id }); customerProdStockRecord.setText({ fieldId: 'custrecord_history_zee_stock_date', value: updated_at }); customerProdStockRecord.setText({ fieldId: 'custrecord_history_zee_stock_time', value: time_updated_at }); } else { //Send email if no Zee ID email.send({ author: 409635, recipients: 'ankith.ravindran@mailplus.comau', subject: 'MPEX Scan Sync - Error', body: 'Barcode: ' + barcode + ' has empty Zee ID' }); save_barcode = false; } } else if (scan_type == 'allocate') { if (!isNullorEmpty(customer_id)) { //Invoiceable field is set to false if (invoiceable === false || invoiceable == 'false' || invoiceable === 'false' || invoiceable == false) { //Set invoiceable as NO customerProdStockRecord.setValue({ fieldId: 'custrecord_cust_prod_stock_invoiceable', value: 2 }); //Set Prepaid as YES customerProdStockRecord.setValue({ fieldId: 'custrecord_cust_prod_stock_prepaid', value: 1 }); } customerProdStockRecord.setValue({ fieldId: 'custrecord_cust_prod_stock_customer', value: customer_id }); customerProdStockRecord.setValue({ fieldId: 'custrecord_cust_prod_stock_status', value: 1 }); customerProdStockRecord.setText({ fieldId: 'custrecord_cust_date_stock_given', value: updated_at }); customerProdStockRecord.setText({ fieldId: 'custrecord_cust_time_stock_given', value: time_updated_at }); customerProdStockRecord.setText({ fieldId: 'custrecord_history_allocate_date', value: updated_at }); customerProdStockRecord.setText({ fieldId: 'custrecord_history_allocate_time', value: time_updated_at }); } else { email.send({ author: 409635, recipients: 'ankith.ravindran@mailplus.comau', subject: 'MPEX Scan Sync - Error', body: 'Barcode: ' + barcode + ' has empty Customer ID' }); save_barcode = false; } } else if (scan_type == 'pickup') { if (!isNullorEmpty(customer_id)) { //Invoiceable field is set to false if (invoiceable === false || invoiceable == 'false' || invoiceable === 'false' || invoiceable == false) { //Set invoiceable as NO customerProdStockRecord.setValue({ fieldId: 'custrecord_cust_prod_stock_invoiceable', value: 2 }); //Set Prepaid as YES customerProdStockRecord.setValue({ fieldId: 'custrecord_cust_prod_stock_prepaid', value: 1 }); } customerProdStockRecord.setValue({ fieldId: 'custrecord_cust_prod_stock_customer', value: customer_id }); customerProdStockRecord.setValue({ fieldId: 'custrecord_cust_prod_stock_status', value: 2 }); customerProdStockRecord.setText({ fieldId: 'custrecord_cust_date_stock_given', value: updated_at }); customerProdStockRecord.setText({ fieldId: 'custrecord_cust_time_stock_given', value: time_updated_at }); customerProdStockRecord.setText({ fieldId: 'custrecord_history_pickup_date', value: updated_at }); customerProdStockRecord.setText({ fieldId: 'custrecord_history_pickup_time', value: time_updated_at }); } else { email.send({ author: 409635, recipients: 'ankith.ravindran@mailplus.comau', subject: 'MPEX Scan Sync - Error', body: 'Barcode: ' + barcode + ' has empty Customer ID' }); save_barcode = false; } } else if (scan_type == "delivery") { if (!isNullorEmpty(customer_id)) { //Invoiceable field is set to false if (invoiceable === false || invoiceable == 'false' || invoiceable === 'false' || invoiceable == false) { //Set invoiceable as NO customerProdStockRecord.setValue({ fieldId: 'custrecord_cust_prod_stock_invoiceable', value: 2 }); //Set Prepaid as YES customerProdStockRecord.setValue({ fieldId: 'custrecord_cust_prod_stock_prepaid', value: 1 }); } customerProdStockRecord.setValue({ fieldId: 'custrecord_cust_prod_stock_customer', value: customer_id }); customerProdStockRecord.setValue({ fieldId: 'custrecord_cust_prod_stock_status', value: 4 }); customerProdStockRecord.setValue({ fieldId: 'custrecord_cust_prod_stock_final_del', value: 4 }); customerProdStockRecord.setText({ fieldId: 'custrecord_cust_date_stock_given', value: updated_at }); customerProdStockRecord.setText({ fieldId: 'custrecord_cust_time_stock_given', value: time_updated_at }); customerProdStockRecord.setText({ fieldId: 'custrecord_history_delivery_date', value: updated_at }); customerProdStockRecord.setText({ fieldId: 'custrecord_history_delivery_time', value: time_updated_at }); } else { email.send({ author: 409635, recipients: 'ankith.ravindran@mailplus.comau', subject: 'MPEX Scan Sync - Error', body: 'Barcode: ' + barcode + ' has empty Customer ID' }); save_barcode = false; } } else if (scan_type == "lodgement") { if (!isNullorEmpty(customer_id)) { //Invoiceable field is set to false if (invoiceable === false || invoiceable == 'false' || invoiceable === 'false' || invoiceable == false) { //Set invoiceable as NO customerProdStockRecord.setValue({ fieldId: 'custrecord_cust_prod_stock_invoiceable', value: 2 }); //Set Prepaid as YES customerProdStockRecord.setValue({ fieldId: 'custrecord_cust_prod_stock_prepaid', value: 1 }); } customerProdStockRecord.setValue({ fieldId: 'custrecord_cust_prod_stock_customer', value: customer_id }); customerProdStockRecord.setValue({ fieldId: 'custrecord_cust_prod_stock_status', value: 5 }); customerProdStockRecord.setValue({ fieldId: 'custrecord_cust_prod_stock_final_del', value: 5 }); customerProdStockRecord.setText({ fieldId: 'custrecord_cust_date_stock_given', value: updated_at }); customerProdStockRecord.setText({ fieldId: 'custrecord_cust_time_stock_given', value: time_updated_at }); customerProdStockRecord.setText({ fieldId: 'custrecord_history_lodge_date', value: updated_at }); customerProdStockRecord.setText({ fieldId: 'custrecord_history_lodge_time', value: time_updated_at }); } else { email.send({ author: 409635, recipients: 'ankith.ravindran@mailplus.comau', subject: 'MPEX Scan Sync - Error', body: 'Barcode: ' + barcode + ' has empty Customer ID' }); save_barcode = false; } } if (save_barcode == true) { customerProdStockRecord.setValue({ fieldId: 'custrecord_cust_prod_stock_source', value: 6 }); customerProdStockRecord.setValue({ fieldId: 'custrecord_cust_prod_stock_operator', value: operator_id }); customerProdStockRecord.setValue({ fieldId: 'custrecord_mpdl_number', value: external_barcode }); var sourceId = getSourceID(source); if (sourceId != null) { customerProdStockRecord.setValue({ fieldId: 'custrecord_barcode_source', value: sourceId }); } customerProdStockRecord.setValue({ fieldId: 'custrecord_receiver_suburb', value: receiver_suburb }); customerProdStockRecord.setValue({ fieldId: 'custrecord_receiver_postcode', value: receiver_postcode }); customerProdStockRecord.setValue({ fieldId: 'custrecord_receiver_state', value: receiver_state }); customerProdStockRecord.setValue({ fieldId: 'custrecord_receiver_addr1', value: receiver_addr1 }); customerProdStockRecord.setValue({ fieldId: 'custrecord_receiver_addr2', value: receiver_addr2 }); customerProdStockRecord.setValue({ fieldId: 'custrecord_receiver_name', value: receiver_name }); customerProdStockRecord.setValue({ fieldId: 'custrecord_receiver_email', value: receiver_email }); customerProdStockRecord.setValue({ fieldId: 'custrecord_receiver_phone', value: receiver_phone }); //Invoiceable field is set to false if (invoiceable === false || invoiceable == 'false' || invoiceable === 'false' || invoiceable == false) { //Set invoiceable as NO customerProdStockRecord.setValue({ fieldId: 'custrecord_cust_prod_stock_invoiceable', value: 2 }); //Set Prepaid as YES customerProdStockRecord.setValue({ fieldId: 'custrecord_cust_prod_stock_prepaid', value: 1 }); } if (barcode_beg == 'MPEN' || barcode_beg == 'MPET' || barcode_beg == 'MPEF' || barcode_beg == 'MPEB' || barcode_beg == 'MPEC' || barcode_beg == 'MPED' || barcode_beg == 'MPEG') { if (barcode_beg == 'MPEN') { prod_id = 552; } else if (barcode_beg == 'MPET') { prod_id = 553; } else if (barcode_beg == 'MPEF') { prod_id = 554; } else if (barcode_beg == 'MPEB') { prod_id = 550; } else if (barcode_beg == 'MPEC') { prod_id = 551; } else if (barcode_beg == 'MPED') { prod_id = 549; } else if (barcode_beg == 'MPEG') { prod_id = 638; } customerProdStockRecord.setValue({ fieldId: 'custrecord_cust_stock_prod_name', value: prod_id }); } customer_prod_stock_id = customerProdStockRecord.save(); } } count++; return true; }); //Barcode does not exist in NetSuite if (count == 0) { log.debug({ title: 'Barcode does not exist', details: scans[y].scan_type }); var save_barcode = true; if (isNullorEmpty(deleted)) { var customerProdStockRecord = record.create({ type: 'customrecord_customer_product_stock' }); log.debug({ title: 'EDIT - updated_at', details: updated_at }); customerProdStockRecord.setText({ fieldId: 'custrecord_cust_date_stock_given', value: updated_at }); log.debug({ title: 'EDIT - time_updated_at', details: time_updated_at }); customerProdStockRecord.setText({ fieldId: 'custrecord_cust_time_stock_given', value: time_updated_at }); //Invoiceable field is set to false if (invoiceable === false || invoiceable == 'false' || invoiceable === 'false' || invoiceable == false) { //Set invoiceable as NO customerProdStockRecord.setValue({ fieldId: 'custrecord_cust_prod_stock_invoiceable', value: 2 }); //Set Prepaid as YES customerProdStockRecord.setValue({ fieldId: 'custrecord_cust_prod_stock_prepaid', value: 1 }); } customerProdStockRecord.setValue({ fieldId: 'name', value: barcode }); if (scan_type == 'stockzee') { if (!isNullorEmpty(zee_id)) { //Set status as Zee stock customerProdStockRecord.setValue({ fieldId: 'custrecord_cust_prod_stock_status', value: 8 }); customerProdStockRecord.setText({ fieldId: 'custrecord_cust_date_stock_given', value: updated_at }); customerProdStockRecord.setText({ fieldId: 'custrecord_cust_time_stock_given', value: time_updated_at }); customerProdStockRecord.setValue({ fieldId: 'custrecord_cust_prod_stock_customer', value: null }); customerProdStockRecord.setValue({ fieldId: 'custrecord_cust_prod_stock_zee', value: zee_id }); customerProdStockRecord.setText({ fieldId: 'custrecord_history_zee_stock_date', value: updated_at }); customerProdStockRecord.setText({ fieldId: 'custrecord_history_zee_stock_time', value: time_updated_at }); } else { //Send email if no Zee ID email.send({ author: 409635, recipients: 'ankith.ravindran@mailplus.comau', subject: 'MPEX Scan Sync - Error', body: 'Barcode: ' + barcode + ' has empty Zee ID' }); save_barcode = false; } } else if (scan_type == 'allocate') { if (!isNullorEmpty(customer_id)) { //Invoiceable field is set to false if (invoiceable === false || invoiceable == 'false' || invoiceable === 'false' || invoiceable == false) { //Set invoiceable as NO customerProdStockRecord.setValue({ fieldId: 'custrecord_cust_prod_stock_invoiceable', value: 2 }); //Set Prepaid as YES customerProdStockRecord.setValue({ fieldId: 'custrecord_cust_prod_stock_prepaid', value: 1 }); } customerProdStockRecord.setValue({ fieldId: 'custrecord_cust_prod_stock_customer', value: customer_id }); customerProdStockRecord.setValue({ fieldId: 'custrecord_cust_prod_stock_status', value: 1 }); customerProdStockRecord.setText({ fieldId: 'custrecord_cust_date_stock_given', value: updated_at }); customerProdStockRecord.setText({ fieldId: 'custrecord_cust_time_stock_given', value: time_updated_at }); customerProdStockRecord.setText({ fieldId: 'custrecord_history_allocate_date', value: updated_at }); customerProdStockRecord.setText({ fieldId: 'custrecord_history_allocate_time', value: time_updated_at }); } else { email.send({ author: 409635, recipients: 'ankith.ravindran@mailplus.comau', subject: 'MPEX Scan Sync - Error', body: 'Barcode: ' + barcode + ' has empty Customer ID' }); save_barcode = false; } } else if (scan_type == 'pickup') { if (!isNullorEmpty(customer_id)) { //Invoiceable field is set to false if (invoiceable === false || invoiceable == 'false' || invoiceable === 'false' || invoiceable == false) { //Set invoiceable as NO customerProdStockRecord.setValue({ fieldId: 'custrecord_cust_prod_stock_invoiceable', value: 2 }); //Set Prepaid as YES customerProdStockRecord.setValue({ fieldId: 'custrecord_cust_prod_stock_prepaid', value: 1 }); } customerProdStockRecord.setValue({ fieldId: 'custrecord_cust_prod_stock_customer', value: customer_id }); customerProdStockRecord.setValue({ fieldId: 'custrecord_cust_prod_stock_status', value: 2 }); customerProdStockRecord.setText({ fieldId: 'custrecord_cust_date_stock_given', value: updated_at }); customerProdStockRecord.setText({ fieldId: 'custrecord_cust_time_stock_given', value: time_updated_at }); customerProdStockRecord.setText({ fieldId: 'custrecord_history_pickup_date', value: updated_at }); customerProdStockRecord.setText({ fieldId: 'custrecord_history_pickup_time', value: time_updated_at }); } else { email.send({ author: 409635, recipients: 'ankith.ravindran@mailplus.comau', subject: 'MPEX Scan Sync - Error', body: 'Barcode: ' + barcode + ' has empty Customer ID' }); save_barcode = false; } } else if (scan_type == "delivery") { if (!isNullorEmpty(customer_id)) { //Invoiceable field is set to false if (invoiceable === false || invoiceable == 'false' || invoiceable === 'false' || invoiceable == false) { //Set invoiceable as NO customerProdStockRecord.setValue({ fieldId: 'custrecord_cust_prod_stock_invoiceable', value: 2 }); //Set Prepaid as YES customerProdStockRecord.setValue({ fieldId: 'custrecord_cust_prod_stock_prepaid', value: 1 }); } customerProdStockRecord.setValue({ fieldId: 'custrecord_cust_prod_stock_customer', value: customer_id }); customerProdStockRecord.setValue({ fieldId: 'custrecord_cust_prod_stock_status', value: 4 }); customerProdStockRecord.setValue({ fieldId: 'custrecord_cust_prod_stock_final_del', value: 4 }); customerProdStockRecord.setText({ fieldId: 'custrecord_cust_date_stock_given', value: updated_at }); customerProdStockRecord.setText({ fieldId: 'custrecord_cust_time_stock_given', value: time_updated_at }); customerProdStockRecord.setText({ fieldId: 'custrecord_history_delivery_date', value: updated_at }); customerProdStockRecord.setText({ fieldId: 'custrecord_history_delivery_time', value: time_updated_at }); } else { email.send({ author: 409635, recipients: 'ankith.ravindran@mailplus.comau', subject: 'MPEX Scan Sync - Error', body: 'Barcode: ' + barcode + ' has empty Customer ID' }); save_barcode = false; } } else if (scan_type == "lodgement") { if (!isNullorEmpty(customer_id)) { //Invoiceable field is set to false if (invoiceable === false || invoiceable == 'false' || invoiceable === 'false' || invoiceable == false) { //Set invoiceable as NO customerProdStockRecord.setValue({ fieldId: 'custrecord_cust_prod_stock_invoiceable', value: 2 }); //Set Prepaid as YES customerProdStockRecord.setValue({ fieldId: 'custrecord_cust_prod_stock_prepaid', value: 1 }); } customerProdStockRecord.setValue({ fieldId: 'custrecord_cust_prod_stock_customer', value: customer_id }); customerProdStockRecord.setValue({ fieldId: 'custrecord_cust_prod_stock_status', value: 5 }); customerProdStockRecord.setValue({ fieldId: 'custrecord_cust_prod_stock_final_del', value: 5 }); customerProdStockRecord.setText({ fieldId: 'custrecord_cust_date_stock_given', value: updated_at }); customerProdStockRecord.setText({ fieldId: 'custrecord_cust_time_stock_given', value: time_updated_at }); customerProdStockRecord.setText({ fieldId: 'custrecord_history_lodge_date', value: updated_at }); customerProdStockRecord.setText({ fieldId: 'custrecord_history_lodge_time', value: time_updated_at }); } else { email.send({ author: 409635, recipients: 'ankith.ravindran@mailplus.comau', subject: 'MPEX Scan Sync - Error', body: 'Barcode: ' + barcode + ' has empty Customer ID' }); save_barcode = false; } } if (save_barcode == true) { customerProdStockRecord.setValue({ fieldId: 'custrecord_cust_prod_stock_source', value: 6 }); customerProdStockRecord.setValue({ fieldId: 'custrecord_cust_prod_stock_operator', value: operator_id }); customerProdStockRecord.setValue({ fieldId: 'custrecord_mpdl_number', value: external_barcode }); var sourceId = getSourceID(source); if (sourceId != null) { customerProdStockRecord.setValue({ fieldId: 'custrecord_barcode_source', value: sourceId }); } customerProdStockRecord.setValue({ fieldId: 'custrecord_receiver_suburb', value: receiver_suburb }); customerProdStockRecord.setValue({ fieldId: 'custrecord_receiver_postcode', value: receiver_postcode }); customerProdStockRecord.setValue({ fieldId: 'custrecord_receiver_state', value: receiver_state }); customerProdStockRecord.setValue({ fieldId: 'custrecord_receiver_addr1', value: receiver_addr1 }); customerProdStockRecord.setValue({ fieldId: 'custrecord_receiver_addr2', value: receiver_addr2 }); customerProdStockRecord.setValue({ fieldId: 'custrecord_receiver_name', value: receiver_name }); customerProdStockRecord.setValue({ fieldId: 'custrecord_receiver_email', value: receiver_email }); customerProdStockRecord.setValue({ fieldId: 'custrecord_receiver_phone', value: receiver_phone }); //Invoiceable field is set to false if (invoiceable === false || invoiceable == 'false' || invoiceable === 'false' || invoiceable == false) { //Set invoiceable as NO customerProdStockRecord.setValue({ fieldId: 'custrecord_cust_prod_stock_invoiceable', value: 2 }); //Set Prepaid as YES customerProdStockRecord.setValue({ fieldId: 'custrecord_cust_prod_stock_prepaid', value: 1 }); } if (barcode_beg == 'MPEN' || barcode_beg == 'MPET' || barcode_beg == 'MPEF' || barcode_beg == 'MPEB' || barcode_beg == 'MPEC' || barcode_beg == 'MPED' || barcode_beg == 'MPEG') { if (barcode_beg == 'MPEN') { prod_id = 552; } else if (barcode_beg == 'MPET') { prod_id = 553; } else if (barcode_beg == 'MPEF') { prod_id = 554; } else if (barcode_beg == 'MPEB') { prod_id = 550; } else if (barcode_beg == 'MPEC') { prod_id = 551; } else if (barcode_beg == 'MPED') { prod_id = 549; } else if (barcode_beg == 'MPEG') { prod_id = 638; } customerProdStockRecord.setValue({ fieldId: 'custrecord_cust_stock_prod_name', value: prod_id }); } customer_prod_stock_id = customerProdStockRecord.save(); } } } } } // // log.audit({ title: 'barcodes Length before splice', details: barcodes.length }); log.audit({ title: 'barcodes before splice', details: barcodes }); barcodes.splice(x, 1); log.audit({ title: 'barcodes Length after splice', details: barcodes.length }); log.audit({ title: 'barcodes after splice', details: barcodes }); var scan_json_2 = '{ "scans": ' + JSON.stringify(barcodes) + '}'; var body_2 = scan_json_record.setValue({ fieldId: 'custrecord_json', value: scan_json_2 }); scan_json_record.save(); var scriptTask = task.create({ taskType: task.TaskType.SCHEDULED_SCRIPT, scriptId: 'customscript_ss2_rta_scan_sync_v2', deploymentId: 'customdeploy2', params: null }); var scriptTaskId = scriptTask.submit(); return false; x++; } while (barcodes.length > 0); } else if (barcodes.length == 0) { var body_2 = scan_json_record.setValue({ fieldId: 'custrecord_scan_josn_sync', value: 1 }); } return true; }); } return { execute: execute }; } ); function getSourceID(source) { switch (source) { case 'shopify': return 2; break; case 'manual': return 1; break; case 'bulk': return 4; break; case 'portal': return 3; break; default: return null; break; } } function onTimeChange(value) { if (value != "") { var timeSplit = value.split(':'), hours, minutes, meridian; hours = timeSplit[0]; minutes = timeSplit[1]; if (hours > 12) { meridian = 'PM'; hours -= 12; } else if (hours < 12) { meridian = 'AM'; if (hours == 0) { hours = 12; } } else { meridian = 'PM'; } return (hours + ':' + minutes + ' ' + meridian); } } function convertTo24Hour(time) { var hours_string = (time.substr(0, 2)); var hours = parseInt(time.substr(0, 2)); if (time.indexOf('AM') != -1 && hours == 12) { time = time.replace('12', '0'); } // if (time.indexOf('AM') != -1 && hours < 10) { // time = time.replace(hours, ('0' + hours)); // } if (time.indexOf('PM') != -1 && hours < 12) { console.log(hours + 12) time = time.replace(hours_string, (hours + 12)); } return time.replace(/( AM| PM)/, ''); } /** * Is Null or Empty. * * @param {Object} strVal */ function isNullorEmpty(strVal) { return (strVal == null || strVal == '' || strVal == 'null' || strVal == undefined || strVal == 'undefined' || strVal == '- None -'); }
631
[{"tag": "EMAIL", "value": "ankith.ravindran@mailplus.comau", "start": 8106, "end": 8137}, {"tag": "EMAIL", "value": "ankith.ravindran@mailplus.comau", "start": 9628, "end": 9659}, {"tag": "EMAIL", "value": "ankith.ravindran@mailplus.comau", "start": 11154, "end": 11185}, {"tag": "EMAIL", "value": "ankith.ravindran@mailplus.comau", "start": 12824, "end": 12855}, {"tag": "EMAIL", "value": "ankith.ravindran@mailplus.comau", "start": 14495, "end": 14526}, {"tag": "EMAIL", "value": "ankith.ravindran@mailplus.comau", "start": 20594, "end": 20625}, {"tag": "EMAIL", "value": "ankith.ravindran@mailplus.comau", "start": 22116, "end": 22147}, {"tag": "EMAIL", "value": "ankith.ravindran@mailplus.comau", "start": 23642, "end": 23673}, {"tag": "EMAIL", "value": "ankith.ravindran@mailplus.comau", "start": 25312, "end": 25343}, {"tag": "EMAIL", "value": "ankith.ravindran@mailplus.comau", "start": 26983, "end": 27014}, {"tag": "EMAIL", "value": "ankith.ravindran@mailplus.comau", "start": 37568, "end": 37599}, {"tag": "EMAIL", "value": "ankith.ravindran@mailplus.comau", "start": 39438, "end": 39469}, {"tag": "EMAIL", "value": "ankith.ravindran@mailplus.comau", "start": 41307, "end": 41338}, {"tag": "EMAIL", "value": "ankith.ravindran@mailplus.comau", "start": 43328, "end": 43359}, {"tag": "EMAIL", "value": "ankith.ravindran@mailplus.comau", "start": 45344, "end": 45375}, {"tag": "EMAIL", "value": "ankith.ravindran@mailplus.comau", "start": 51958, "end": 51989}, {"tag": "EMAIL", "value": "ankith.ravindran@mailplus.comau", "start": 53828, "end": 53859}, {"tag": "EMAIL", "value": "ankith.ravindran@mailplus.comau", "start": 55697, "end": 55728}, {"tag": "EMAIL", "value": "ankith.ravindran@mailplus.comau", "start": 57718, "end": 57749}, {"tag": "EMAIL", "value": "ankith.ravindran@mailplus.comau", "start": 59734, "end": 59765}]
true
20
/** *@NApiVersion 2.x *@NScriptType ScheduledScript */ define(['N/task', 'N/email', 'N/runtime', 'N/search', 'N/record', 'N/format', 'N/https'], function(task, email, runtime, search, record, format, https) { function execute(context) { var todayDate = new Date(); log.audit({ title: 'todayDate', details: todayDate }); //To get todays date var today = format.format({ value: todayDate, type: format.Type.DATE }); log.audit({ title: 'today', details: today }); var tempTodayDate = today.split('/'); // var temp = tempTodayDate.split('-'); // var today = tempTodayDate[0] + '/' + tempTodayDate[1] + '/' + tempTodayDate[2]; var today = '02-05-2021'; log.audit({ title: 'today', details: today }); var scanJSONSearch = search.load({ id: 'customsearch_scan_json' }); scanJSONSearch.filters.push(search.createFilter({ name: 'name', join: null, operator: search.Operator.STARTSWITH, values: '02-05-2021_Part_2' })); scanJSONSearch.filters.push(search.createFilter({ name: 'custrecord_scan_josn_sync', join: null, operator: search.Operator.IS, values: 2 })); scanJSONSearch.filters.push(search.createFilter({ name: 'isinactive', join: null, operator: search.Operator.IS, values: "F" })); var scan_json_record_id; scanJSONSearch.run().each(function(searchResult) { var scriptObj = runtime.getCurrentScript() var usage_loopstart_cust = scriptObj.getRemainingUsage(); log.audit({ title: 'Start of SCAN JSON Loop', details: usage_loopstart_cust }); var scan_json_record_id = searchResult.getValue({ name: 'internalid' }); var scan_json_record_name = searchResult.getValue({ name: "name" }); log.audit({ title: 'Scan JSON Record Name ', details: scan_json_record_name }); var scan_json_record = record.load({ type: 'customrecord_scan_json', id: scan_json_record_id }); var body = scan_json_record.getValue({ fieldId: 'custrecord_json' }); var body_2 = scan_json_record.getValue({ fieldId: 'custrecord_scan_json_2' }); if (body_2 == "") { var todays_scans = JSON.parse(body); var barcodes = todays_scans.scans; //No. of barcodes } else { var todays_scans = JSON.parse(body_2); var barcodes = todays_scans.scans; //No. of barcodes } log.audit({ title: 'barcodes', details: barcodes }); log.audit({ title: 'barcodes length', details: barcodes.length }); if (barcodes.length > 0) { //Iterate through each barcode do { var x = barcodes.length - 1; var scriptObj = runtime.getCurrentScript() var usage_loopstart_cust = scriptObj.getRemainingUsage(); //Usage at the start of each barcode log.audit({ title: 'Start of Barcode Loop', details: scriptObj.getRemainingUsage() }); log.audit({ title: 'Scans for barcode: ' + barcodes[x].code, details: barcodes[x].scans }); var scans = barcodes[x].scans; log.audit({ title: 'Scans Length for barcode: ' + barcodes[x].code, details: scans.length }); //Only one scan history for the barcode if (scans.length == 1) { log.audit({ title: 'Inside Scan Length = 1', details: barcodes[x].code }); var y = 0; var scriptObj = runtime.getCurrentScript() var usage_loopstart_cust = scriptObj.getRemainingUsage(); //Usage at the start of each scan type log.audit({ title: 'Start of Scans Loop per barcode', details: scriptObj.getRemainingUsage() }); log.audit({ title: 'Scans for barcode: ' + barcodes[x].code, details: scans[y] }); log.audit({ title: 'Scans for barcode: ' + barcodes[x].code, details: scans[y].scan_type }); var barcode = scans[y].barcode.toUpperCase(); var customer_id = scans[y].customer_ns_id; var zee_id = scans[y].zee_ns_id; var rta_id = scans[y].id; var invoiceable = scans[y].invoiceable; var scan_type = scans[y].scan_type.toLowerCase(); var operator_id = scans[y].operator_ns_id; var updated_at = scans[y].updated_at; var deleted = scans[y].deleted; var external_barcode = scans[y].external_barcode; var source = scans[y].source; var receiver_suburb = scans[y].receiver_suburb; var receiver_postcode = scans[y].post_code; var receiver_state = scans[y].state; var receiver_addr1 = scans[y].address1; var receiver_addr2 = scans[y].address2; var receiver_name = scans[y].receiver_name; var receiver_email = scans[y].email; var receiver_phone = scans[y].phone; updated_at = updated_at.split("T"); var time_updated_at = updated_at[1]; time_updated_at = time_updated_at.split("."); time_updated_at = onTimeChange(time_updated_at[0]); time_updated_at = format.parse({ value: time_updated_at, type: format.Type.TIMEOFDAY }); log.audit({ title: 'TIME OF DAY', details: time_updated_at }); var updated_at = updated_at[0]; var save_barcode = true; var barcode_beg = barcode.slice(0, 4); updated_at = updated_at.split("-"); updated_at = format.parse({ value: updated_at[2] + '/' + updated_at[1] + '/' + updated_at[0], type: format.Type.DATE }); log.audit({ title: 'DATE', details: updated_at }); // updated_at = nlapiStringToDate(updated_at[2] + '/' + updated_at[1] + '/' + updated_at[0]); //Load Search: RTA - Product Stock var productStockSearch = search.load({ id: 'customsearch_rta_product_stock' }); productStockSearch.filters.push(search.createFilter({ name: 'name', join: null, operator: search.Operator.IS, values: barcode })); productStockSearch.filters.push(search.createFilter({ name: 'isinactive', join: null, operator: search.Operator.IS, values: "F" })); var count = 0; var prod_id; productStockSearch.run().each(function(searchResult) { log.audit({ title: 'Barcode does exist', details: scans[y].scan_type.toLowerCase() }); var customer_prod_stock_id = searchResult.getValue({ name: 'internalid' }); //Load the customer product stock record var customerProdStockRecord = record.load({ type: 'customrecord_customer_product_stock', id: customer_prod_stock_id }); //Get the current status of the record. var stock_status = customerProdStockRecord.getValue({ fieldId: 'custrecord_cust_prod_stock_status' }); //Status is Product Order Created or Invoiced if (stock_status != 6 && stock_status != 7) { if (scan_type == 'stockzee') { if (!isNullorEmpty(zee_id)) { //Set status as Zee stock customerProdStockRecord.setValue({ fieldId: 'custrecord_cust_prod_stock_status', value: 8 }); customerProdStockRecord.setText({ fieldId: 'custrecord_cust_date_stock_given', value: updated_at }); customerProdStockRecord.setText({ fieldId: 'custrecord_cust_time_stock_given', value: time_updated_at }); customerProdStockRecord.setValue({ fieldId: 'custrecord_cust_prod_stock_customer', value: null }); customerProdStockRecord.setValue({ fieldId: 'custrecord_cust_prod_stock_zee', value: zee_id }); } else { //Send email if no Zee ID email.send({ author: 409635, recipients: 'hzdkv@example.com', subject: 'MPEX Scan Sync - Error', body: 'Barcode: ' + barcode + ' has empty Zee ID' }); save_barcode = false; } } else if (scan_type == 'allocate') { if (!isNullorEmpty(customer_id)) { //Invoiceable field is set to false if (invoiceable === false || invoiceable == 'false' || invoiceable === 'false' || invoiceable == false) { //Set invoiceable as NO customerProdStockRecord.setValue({ fieldId: 'custrecord_cust_prod_stock_invoiceable', value: 2 }); //Set Prepaid as YES customerProdStockRecord.setValue({ fieldId: 'custrecord_cust_prod_stock_prepaid', value: 1 }); } customerProdStockRecord.setValue({ fieldId: 'custrecord_cust_prod_stock_customer', value: customer_id }); customerProdStockRecord.setValue({ fieldId: 'custrecord_cust_prod_stock_status', value: 1 }); customerProdStockRecord.setText({ fieldId: 'custrecord_cust_date_stock_given', value: updated_at }); customerProdStockRecord.setText({ fieldId: 'custrecord_cust_time_stock_given', value: time_updated_at }); } else { email.send({ author: 409635, recipients: 'hzdkv@example.com', subject: 'MPEX Scan Sync - Error', body: 'Barcode: ' + barcode + ' has empty Customer ID' }); save_barcode = false; } } else if (scan_type == 'pickup') { if (!isNullorEmpty(customer_id)) { //Invoiceable field is set to false if (invoiceable === false || invoiceable == 'false' || invoiceable === 'false' || invoiceable == false) { //Set invoiceable as NO customerProdStockRecord.setValue({ fieldId: 'custrecord_cust_prod_stock_invoiceable', value: 2 }); //Set Prepaid as YES customerProdStockRecord.setValue({ fieldId: 'custrecord_cust_prod_stock_prepaid', value: 1 }); } customerProdStockRecord.setValue({ fieldId: 'custrecord_cust_prod_stock_customer', value: customer_id }); customerProdStockRecord.setValue({ fieldId: 'custrecord_cust_prod_stock_status', value: 2 }); customerProdStockRecord.setText({ fieldId: 'custrecord_cust_date_stock_given', value: updated_at }); customerProdStockRecord.setText({ fieldId: 'custrecord_cust_time_stock_given', value: time_updated_at }); } else { email.send({ author: 409635, recipients: 'hzdkv@example.com', subject: 'MPEX Scan Sync - Error', body: 'Barcode: ' + barcode + ' has empty Customer ID' }); save_barcode = false; } } else if (scan_type == "delivery") { if (!isNullorEmpty(customer_id)) { //Invoiceable field is set to false if (invoiceable === false || invoiceable == 'false' || invoiceable === 'false' || invoiceable == false) { //Set invoiceable as NO customerProdStockRecord.setValue({ fieldId: 'custrecord_cust_prod_stock_invoiceable', value: 2 }); //Set Prepaid as YES customerProdStockRecord.setValue({ fieldId: 'custrecord_cust_prod_stock_prepaid', value: 1 }); } customerProdStockRecord.setValue({ fieldId: 'custrecord_cust_prod_stock_customer', value: customer_id }); customerProdStockRecord.setValue({ fieldId: 'custrecord_cust_prod_stock_status', value: 4 }); customerProdStockRecord.setValue({ fieldId: 'custrecord_cust_prod_stock_final_del', value: 4 }); customerProdStockRecord.setText({ fieldId: 'custrecord_cust_date_stock_given', value: updated_at }); customerProdStockRecord.setText({ fieldId: 'custrecord_cust_time_stock_given', value: time_updated_at }); } else { email.send({ author: 409635, recipients: 'hzdkv@example.com', subject: 'MPEX Scan Sync - Error', body: 'Barcode: ' + barcode + ' has empty Customer ID' }); save_barcode = false; } } else if (scan_type == "lodgement") { if (!isNullorEmpty(customer_id)) { //Invoiceable field is set to false if (invoiceable === false || invoiceable == 'false' || invoiceable === 'false' || invoiceable == false) { //Set invoiceable as NO customerProdStockRecord.setValue({ fieldId: 'custrecord_cust_prod_stock_invoiceable', value: 2 }); //Set Prepaid as YES customerProdStockRecord.setValue({ fieldId: 'custrecord_cust_prod_stock_prepaid', value: 1 }); } customerProdStockRecord.setValue({ fieldId: 'custrecord_cust_prod_stock_customer', value: customer_id }); customerProdStockRecord.setValue({ fieldId: 'custrecord_cust_prod_stock_status', value: 5 }); customerProdStockRecord.setValue({ fieldId: 'custrecord_cust_prod_stock_final_del', value: 5 }); customerProdStockRecord.setText({ fieldId: 'custrecord_cust_date_stock_given', value: updated_at }); customerProdStockRecord.setText({ fieldId: 'custrecord_cust_time_stock_given', value: time_updated_at }); } else { email.send({ author: 409635, recipients: 'hzdkv@example.com', subject: 'MPEX Scan Sync - Error', body: 'Barcode: ' + barcode + ' has empty Customer ID' }); save_barcode = false; } } if (save_barcode == true) { customerProdStockRecord.setValue({ fieldId: 'custrecord_cust_prod_stock_source', value: 6 }); customerProdStockRecord.setValue({ fieldId: 'custrecord_cust_prod_stock_operator', value: operator_id }); customerProdStockRecord.setValue({ fieldId: 'custrecord_mpdl_number', value: external_barcode }); var sourceId = getSourceID(source); if (sourceId != null) { customerProdStockRecord.setValue({ fieldId: 'custrecord_barcode_source', value: sourceId }); } customerProdStockRecord.setValue({ fieldId: 'custrecord_receiver_suburb', value: receiver_suburb }); customerProdStockRecord.setValue({ fieldId: 'custrecord_receiver_postcode', value: receiver_postcode }); customerProdStockRecord.setValue({ fieldId: 'custrecord_receiver_state', value: receiver_state }); customerProdStockRecord.setValue({ fieldId: 'custrecord_receiver_addr1', value: receiver_addr1 }); customerProdStockRecord.setValue({ fieldId: 'custrecord_receiver_addr2', value: receiver_addr2 }); customerProdStockRecord.setValue({ fieldId: 'custrecord_receiver_name', value: receiver_name }); customerProdStockRecord.setValue({ fieldId: 'custrecord_receiver_email', value: receiver_email }); customerProdStockRecord.setValue({ fieldId: 'custrecord_receiver_phone', value: receiver_phone }); //Invoiceable field is set to false if (invoiceable === false || invoiceable == 'false' || invoiceable === 'false' || invoiceable == false) { //Set invoiceable as NO customerProdStockRecord.setValue({ fieldId: 'custrecord_cust_prod_stock_invoiceable', value: 2 }); //Set Prepaid as YES customerProdStockRecord.setValue({ fieldId: 'custrecord_cust_prod_stock_prepaid', value: 1 }); } log.audit({ title: 'barcode_beg', details: barcode_beg }); if (barcode_beg == 'MPEN' || barcode_beg == 'MPET' || barcode_beg == 'MPEF' || barcode_beg == 'MPEB' || barcode_beg == 'MPEC' || barcode_beg == 'MPED' || barcode_beg == 'MPEG') { if (barcode_beg == 'MPEN') { prod_id = 552; } else if (barcode_beg == 'MPET') { prod_id = 553; } else if (barcode_beg == 'MPEF') { prod_id = 554; } else if (barcode_beg == 'MPEB') { prod_id = 550; } else if (barcode_beg == 'MPEC') { prod_id = 551; } else if (barcode_beg == 'MPED') { prod_id = 549; } else if (barcode_beg == 'MPEG') { prod_id = 638; } log.audit({ title: 'prod_id', details: prod_id }); customerProdStockRecord.setValue({ fieldId: 'custrecord_cust_stock_prod_name', value: prod_id }); } customer_prod_stock_id = customerProdStockRecord.save(); } } count++; return true; }); if (count == 0) { log.audit({ title: 'Barcode does not exist', details: scans[y].scan_type }); var save_barcode = true; if (isNullorEmpty(deleted)) { var customerProdStockRecord = record.create({ type: 'customrecord_customer_product_stock', isDynamic: true }); customerProdStockRecord.setText({ fieldId: 'custrecord_cust_date_stock_given', value: updated_at }); customerProdStockRecord.setText({ fieldId: 'custrecord_cust_time_stock_given', value: time_updated_at }); //Invoiceable field is set to false if (invoiceable === false || invoiceable == 'false' || invoiceable === 'false' || invoiceable == false) { //Set invoiceable as NO customerProdStockRecord.setValue({ fieldId: 'custrecord_cust_prod_stock_invoiceable', value: 2 }); //Set Prepaid as YES customerProdStockRecord.setValue({ fieldId: 'custrecord_cust_prod_stock_prepaid', value: 1 }); } customerProdStockRecord.setValue({ fieldId: 'name', value: barcode }); if (scan_type == 'stockzee') { if (!isNullorEmpty(zee_id)) { //Set status as Zee stock customerProdStockRecord.setValue({ fieldId: 'custrecord_cust_prod_stock_status', value: 8 }); customerProdStockRecord.setText({ fieldId: 'custrecord_cust_date_stock_given', value: updated_at }); customerProdStockRecord.setText({ fieldId: 'custrecord_cust_time_stock_given', value: time_updated_at }); customerProdStockRecord.setValue({ fieldId: 'custrecord_cust_prod_stock_customer', value: null }); customerProdStockRecord.setValue({ fieldId: 'custrecord_cust_prod_stock_zee', value: zee_id }); } else { //Send email if no Zee ID email.send({ author: 409635, recipients: 'hzdkv@example.com', subject: 'MPEX Scan Sync - Error', body: 'Barcode: ' + barcode + ' has empty Zee ID' }); save_barcode = false; } } else if (scan_type == 'allocate') { if (!isNullorEmpty(customer_id)) { //Invoiceable field is set to false if (invoiceable === false || invoiceable == 'false' || invoiceable === 'false' || invoiceable == false) { //Set invoiceable as NO customerProdStockRecord.setValue({ fieldId: 'custrecord_cust_prod_stock_invoiceable', value: 2 }); //Set Prepaid as YES customerProdStockRecord.setValue({ fieldId: 'custrecord_cust_prod_stock_prepaid', value: 1 }); } customerProdStockRecord.setValue({ fieldId: 'custrecord_cust_prod_stock_customer', value: customer_id }); customerProdStockRecord.setValue({ fieldId: 'custrecord_cust_prod_stock_status', value: 1 }); customerProdStockRecord.setText({ fieldId: 'custrecord_cust_date_stock_given', value: updated_at }); customerProdStockRecord.setText({ fieldId: 'custrecord_cust_time_stock_given', value: time_updated_at }); } else { email.send({ author: 409635, recipients: 'hzdkv@example.com', subject: 'MPEX Scan Sync - Error', body: 'Barcode: ' + barcode + ' has empty Customer ID' }); save_barcode = false; } } else if (scan_type == 'pickup') { if (!isNullorEmpty(customer_id)) { //Invoiceable field is set to false if (invoiceable === false || invoiceable == 'false' || invoiceable === 'false' || invoiceable == false) { //Set invoiceable as NO customerProdStockRecord.setValue({ fieldId: 'custrecord_cust_prod_stock_invoiceable', value: 2 }); //Set Prepaid as YES customerProdStockRecord.setValue({ fieldId: 'custrecord_cust_prod_stock_prepaid', value: 1 }); } customerProdStockRecord.setValue({ fieldId: 'custrecord_cust_prod_stock_customer', value: customer_id }); customerProdStockRecord.setValue({ fieldId: 'custrecord_cust_prod_stock_status', value: 2 }); customerProdStockRecord.setText({ fieldId: 'custrecord_cust_date_stock_given', value: updated_at }); customerProdStockRecord.setText({ fieldId: 'custrecord_cust_time_stock_given', value: time_updated_at }); } else { email.send({ author: 409635, recipients: 'hzdkv@example.com', subject: 'MPEX Scan Sync - Error', body: 'Barcode: ' + barcode + ' has empty Customer ID' }); save_barcode = false; } } else if (scan_type == "delivery") { if (!isNullorEmpty(customer_id)) { //Invoiceable field is set to false if (invoiceable === false || invoiceable == 'false' || invoiceable === 'false' || invoiceable == false) { //Set invoiceable as NO customerProdStockRecord.setValue({ fieldId: 'custrecord_cust_prod_stock_invoiceable', value: 2 }); //Set Prepaid as YES customerProdStockRecord.setValue({ fieldId: 'custrecord_cust_prod_stock_prepaid', value: 1 }); } customerProdStockRecord.setValue({ fieldId: 'custrecord_cust_prod_stock_customer', value: customer_id }); customerProdStockRecord.setValue({ fieldId: 'custrecord_cust_prod_stock_status', value: 4 }); customerProdStockRecord.setValue({ fieldId: 'custrecord_cust_prod_stock_final_del', value: 4 }); customerProdStockRecord.setText({ fieldId: 'custrecord_cust_date_stock_given', value: updated_at }); customerProdStockRecord.setText({ fieldId: 'custrecord_cust_time_stock_given', value: time_updated_at }); } else { email.send({ author: 409635, recipients: 'hzdkv@example.com', subject: 'MPEX Scan Sync - Error', body: 'Barcode: ' + barcode + ' has empty Customer ID' }); save_barcode = false; } } else if (scan_type == "lodgement") { if (!isNullorEmpty(customer_id)) { //Invoiceable field is set to false if (invoiceable === false || invoiceable == 'false' || invoiceable === 'false' || invoiceable == false) { //Set invoiceable as NO customerProdStockRecord.setValue({ fieldId: 'custrecord_cust_prod_stock_invoiceable', value: 2 }); //Set Prepaid as YES customerProdStockRecord.setValue({ fieldId: 'custrecord_cust_prod_stock_prepaid', value: 1 }); } customerProdStockRecord.setValue({ fieldId: 'custrecord_cust_prod_stock_customer', value: customer_id }); customerProdStockRecord.setValue({ fieldId: 'custrecord_cust_prod_stock_status', value: 5 }); customerProdStockRecord.setValue({ fieldId: 'custrecord_cust_prod_stock_final_del', value: 5 }); customerProdStockRecord.setText({ fieldId: 'custrecord_cust_date_stock_given', value: updated_at }); customerProdStockRecord.setText({ fieldId: 'custrecord_cust_time_stock_given', value: time_updated_at }); } else { email.send({ author: 409635, recipients: 'hzdkv@example.com', subject: 'MPEX Scan Sync - Error', body: 'Barcode: ' + barcode + ' has empty Customer ID' }); save_barcode = false; } } if (save_barcode == true) { customerProdStockRecord.setValue({ fieldId: 'custrecord_cust_prod_stock_source', value: 6 }); customerProdStockRecord.setValue({ fieldId: 'custrecord_cust_prod_stock_operator', value: operator_id }); customerProdStockRecord.setValue({ fieldId: 'custrecord_mpdl_number', value: external_barcode }); var sourceId = getSourceID(source); if (sourceId != null) { customerProdStockRecord.setValue({ fieldId: 'custrecord_barcode_source', value: sourceId }); } customerProdStockRecord.setValue({ fieldId: 'custrecord_receiver_suburb', value: receiver_suburb }); customerProdStockRecord.setValue({ fieldId: 'custrecord_receiver_postcode', value: receiver_postcode }); customerProdStockRecord.setValue({ fieldId: 'custrecord_receiver_state', value: receiver_state }); customerProdStockRecord.setValue({ fieldId: 'custrecord_receiver_addr1', value: receiver_addr1 }); customerProdStockRecord.setValue({ fieldId: 'custrecord_receiver_addr2', value: receiver_addr2 }); customerProdStockRecord.setValue({ fieldId: 'custrecord_receiver_name', value: receiver_name }); customerProdStockRecord.setValue({ fieldId: 'custrecord_receiver_email', value: receiver_email }); customerProdStockRecord.setValue({ fieldId: 'custrecord_receiver_phone', value: receiver_phone }); //Invoiceable field is set to false if (invoiceable === false || invoiceable == 'false' || invoiceable === 'false' || invoiceable == false) { //Set invoiceable as NO customerProdStockRecord.setValue({ fieldId: 'custrecord_cust_prod_stock_invoiceable', value: 2 }); //Set Prepaid as YES customerProdStockRecord.setValue({ fieldId: 'custrecord_cust_prod_stock_prepaid', value: 1 }); } if (barcode_beg == 'MPEN' || barcode_beg == 'MPET' || barcode_beg == 'MPEF' || barcode_beg == 'MPEB' || barcode_beg == 'MPEC' || barcode_beg == 'MPED' || barcode_beg == 'MPEG') { if (barcode_beg == 'MPEN') { prod_id = 552; } else if (barcode_beg == 'MPET') { prod_id = 553; } else if (barcode_beg == 'MPEF') { prod_id = 554; } else if (barcode_beg == 'MPEB') { prod_id = 550; } else if (barcode_beg == 'MPEC') { prod_id = 551; } else if (barcode_beg == 'MPED') { prod_id = 549; } else if (barcode_beg == 'MPEG') { prod_id = 638; } customerProdStockRecord.setValue({ fieldId: 'custrecord_cust_stock_prod_name', value: prod_id }); } customer_prod_stock_id = customerProdStockRecord.save(); } } } } else { //Iterate through the differenct scans for each barcode for (var y = 0; y < scans.length; y++) { var scriptObj = runtime.getCurrentScript() var usage_loopstart_cust = scriptObj.getRemainingUsage(); //Usage at the start of each scan type log.debug({ title: 'Start of Scans Loop per barcode', details: scriptObj.getRemainingUsage() }); log.debug({ title: 'Scans for barcode: ' + barcodes[x].code, details: scans[y] }); log.debug({ title: 'Scans for barcode: ' + barcodes[x].code, details: scans[y].scan_type }); var barcode = scans[y].barcode.toUpperCase(); var customer_id = scans[y].customer_ns_id; var zee_id = scans[y].zee_ns_id; var rta_id = scans[y].id; var invoiceable = scans[y].invoiceable; var scan_type = scans[y].scan_type.toLowerCase(); var operator_id = scans[y].operator_ns_id; var updated_at = scans[y].updated_at; var deleted = scans[y].deleted; var external_barcode = scans[y].external_barcode; var source = scans[y].source; var receiver_suburb = scans[y].receiver_suburb; var receiver_postcode = scans[y].post_code; var receiver_state = scans[y].state; var receiver_addr1 = scans[y].address1; var receiver_addr2 = scans[y].address2; var receiver_name = scans[y].receiver_name; var receiver_email = scans[y].email; var receiver_phone = scans[y].phone; updated_at = updated_at.split("T"); var time_updated_at = updated_at[1]; time_updated_at = time_updated_at.split("."); time_updated_at = onTimeChange(time_updated_at[0]); time_updated_at = format.parse({ value: time_updated_at, type: format.Type.TIMEOFDAY }); log.debug({ title: 'TIME OF DAY more than 1 scan', details: time_updated_at }); var updated_at = updated_at[0]; var save_barcode = true; var barcode_beg = barcode.slice(0, 4); updated_at = updated_at.split("-"); updated_at = format.parse({ value: updated_at[2] + '/' + updated_at[1] + '/' + updated_at[0], type: format.Type.DATE }) log.debug({ title: 'DATE more than 1 scan', details: updated_at }); // updated_at = nlapiStringToDate(updated_at[2] + '/' + updated_at[1] + '/' + updated_at[0]); // updated_at = nlapiStringToDate(updated_at[2] + '/' + updated_at[1] + '/' + updated_at[0]); //Load Search: RTA - Product Stock var productStockSearch = search.load({ id: 'customsearch_rta_product_stock' }); productStockSearch.filters.push(search.createFilter({ name: 'name', join: null, operator: search.Operator.IS, values: barcode })); productStockSearch.filters.push(search.createFilter({ name: 'isinactive', join: null, operator: search.Operator.IS, values: "F" })); var count = 0; var prod_id; productStockSearch.run().each(function(searchResult) { log.debug({ title: 'Barcode does exist', details: scans[y].scan_type }); var customer_prod_stock_id = searchResult.getValue({ name: 'internalid' }); //Load the customer product stock record var customerProdStockRecord = record.load({ type: 'customrecord_customer_product_stock', id: customer_prod_stock_id }); //Get the current status of the record. var stock_status = customerProdStockRecord.getValue({ fieldId: 'custrecord_cust_prod_stock_status' }); //Status is Product Order Created or Invoiced if (stock_status != 6 && stock_status != 7) { //If the scan has the deleted field if (!isNullorEmpty(deleted)) { //Status is Allocated to custoemer if (stock_status == 1) { customerProdStockRecord.setValue({ fieldId: 'custrecord_cust_prod_stock_customer', value: null }); customerProdStockRecord.setValue({ fieldId: 'custrecord_cust_date_stock_used', value: null }); customerProdStockRecord.setValue({ fieldId: 'custrecord_cust_time_stock_used', value: null }); //Change status to Zee Stock customerProdStockRecord.setValue({ fieldId: 'custrecord_cust_prod_stock_status', value: 8 }); customerProdStockRecord.setValue({ fieldId: 'custrecord_cust_prod_stock_zee', value: zee_id }); } else if (stock_status == 8) { // Status is Zee Stock //Inactivate the record customerProdStockRecord.setValue({ fieldId: 'isinactive', value: true }); customerProdStockRecord.setValue({ fieldId: 'custrecord_cust_time_deleted', value: time_updated_at }); } else if (stock_status == 4 || stock_status == 5) { // Status is Delivered to receiver / Lodged at TOLL //Change status to Allocated to customer customerProdStockRecord.setValue({ fieldId: 'custrecord_cust_prod_stock_status', value: 1 }); } } else if (scan_type == 'stockzee') { if (!isNullorEmpty(zee_id)) { //Set status as Zee stock customerProdStockRecord.setValue({ fieldId: 'custrecord_cust_prod_stock_status', value: 8 }); customerProdStockRecord.setText({ fieldId: 'custrecord_cust_date_stock_given', value: updated_at }); customerProdStockRecord.setText({ fieldId: 'custrecord_cust_time_stock_given', value: time_updated_at }); customerProdStockRecord.setValue({ fieldId: 'custrecord_cust_prod_stock_customer', value: null }); customerProdStockRecord.setValue({ fieldId: 'custrecord_cust_prod_stock_zee', value: zee_id }); customerProdStockRecord.setText({ fieldId: 'custrecord_history_zee_stock_date', value: updated_at }); customerProdStockRecord.setText({ fieldId: 'custrecord_history_zee_stock_time', value: time_updated_at }); } else { //Send email if no Zee ID email.send({ author: 409635, recipients: 'hzdkv@example.com', subject: 'MPEX Scan Sync - Error', body: 'Barcode: ' + barcode + ' has empty Zee ID' }); save_barcode = false; } } else if (scan_type == 'allocate') { if (!isNullorEmpty(customer_id)) { //Invoiceable field is set to false if (invoiceable === false || invoiceable == 'false' || invoiceable === 'false' || invoiceable == false) { //Set invoiceable as NO customerProdStockRecord.setValue({ fieldId: 'custrecord_cust_prod_stock_invoiceable', value: 2 }); //Set Prepaid as YES customerProdStockRecord.setValue({ fieldId: 'custrecord_cust_prod_stock_prepaid', value: 1 }); } customerProdStockRecord.setValue({ fieldId: 'custrecord_cust_prod_stock_customer', value: customer_id }); customerProdStockRecord.setValue({ fieldId: 'custrecord_cust_prod_stock_status', value: 1 }); customerProdStockRecord.setText({ fieldId: 'custrecord_cust_date_stock_given', value: updated_at }); customerProdStockRecord.setText({ fieldId: 'custrecord_cust_time_stock_given', value: time_updated_at }); customerProdStockRecord.setText({ fieldId: 'custrecord_history_allocate_date', value: updated_at }); customerProdStockRecord.setText({ fieldId: 'custrecord_history_allocate_time', value: time_updated_at }); } else { email.send({ author: 409635, recipients: 'hzdkv@example.com', subject: 'MPEX Scan Sync - Error', body: 'Barcode: ' + barcode + ' has empty Customer ID' }); save_barcode = false; } } else if (scan_type == 'pickup') { if (!isNullorEmpty(customer_id)) { //Invoiceable field is set to false if (invoiceable === false || invoiceable == 'false' || invoiceable === 'false' || invoiceable == false) { //Set invoiceable as NO customerProdStockRecord.setValue({ fieldId: 'custrecord_cust_prod_stock_invoiceable', value: 2 }); //Set Prepaid as YES customerProdStockRecord.setValue({ fieldId: 'custrecord_cust_prod_stock_prepaid', value: 1 }); } customerProdStockRecord.setValue({ fieldId: 'custrecord_cust_prod_stock_customer', value: customer_id }); customerProdStockRecord.setValue({ fieldId: 'custrecord_cust_prod_stock_status', value: 2 }); customerProdStockRecord.setText({ fieldId: 'custrecord_cust_date_stock_given', value: updated_at }); customerProdStockRecord.setText({ fieldId: 'custrecord_cust_time_stock_given', value: time_updated_at }); customerProdStockRecord.setText({ fieldId: 'custrecord_history_pickup_date', value: updated_at }); customerProdStockRecord.setText({ fieldId: 'custrecord_history_pickup_time', value: time_updated_at }); } else { email.send({ author: 409635, recipients: 'hzdkv@example.com', subject: 'MPEX Scan Sync - Error', body: 'Barcode: ' + barcode + ' has empty Customer ID' }); save_barcode = false; } } else if (scan_type == "delivery") { if (!isNullorEmpty(customer_id)) { //Invoiceable field is set to false if (invoiceable === false || invoiceable == 'false' || invoiceable === 'false' || invoiceable == false) { //Set invoiceable as NO customerProdStockRecord.setValue({ fieldId: 'custrecord_cust_prod_stock_invoiceable', value: 2 }); //Set Prepaid as YES customerProdStockRecord.setValue({ fieldId: 'custrecord_cust_prod_stock_prepaid', value: 1 }); } customerProdStockRecord.setValue({ fieldId: 'custrecord_cust_prod_stock_customer', value: customer_id }); customerProdStockRecord.setValue({ fieldId: 'custrecord_cust_prod_stock_status', value: 4 }); customerProdStockRecord.setValue({ fieldId: 'custrecord_cust_prod_stock_final_del', value: 4 }); customerProdStockRecord.setText({ fieldId: 'custrecord_cust_date_stock_given', value: updated_at }); customerProdStockRecord.setText({ fieldId: 'custrecord_cust_time_stock_given', value: time_updated_at }); customerProdStockRecord.setText({ fieldId: 'custrecord_history_delivery_date', value: updated_at }); customerProdStockRecord.setText({ fieldId: 'custrecord_history_delivery_time', value: time_updated_at }); } else { email.send({ author: 409635, recipients: 'hzdkv@example.com', subject: 'MPEX Scan Sync - Error', body: 'Barcode: ' + barcode + ' has empty Customer ID' }); save_barcode = false; } } else if (scan_type == "lodgement") { if (!isNullorEmpty(customer_id)) { //Invoiceable field is set to false if (invoiceable === false || invoiceable == 'false' || invoiceable === 'false' || invoiceable == false) { //Set invoiceable as NO customerProdStockRecord.setValue({ fieldId: 'custrecord_cust_prod_stock_invoiceable', value: 2 }); //Set Prepaid as YES customerProdStockRecord.setValue({ fieldId: 'custrecord_cust_prod_stock_prepaid', value: 1 }); } customerProdStockRecord.setValue({ fieldId: 'custrecord_cust_prod_stock_customer', value: customer_id }); customerProdStockRecord.setValue({ fieldId: 'custrecord_cust_prod_stock_status', value: 5 }); customerProdStockRecord.setValue({ fieldId: 'custrecord_cust_prod_stock_final_del', value: 5 }); customerProdStockRecord.setText({ fieldId: 'custrecord_cust_date_stock_given', value: updated_at }); customerProdStockRecord.setText({ fieldId: 'custrecord_cust_time_stock_given', value: time_updated_at }); customerProdStockRecord.setText({ fieldId: 'custrecord_history_lodge_date', value: updated_at }); customerProdStockRecord.setText({ fieldId: 'custrecord_history_lodge_time', value: time_updated_at }); } else { email.send({ author: 409635, recipients: 'hzdkv@example.com', subject: 'MPEX Scan Sync - Error', body: 'Barcode: ' + barcode + ' has empty Customer ID' }); save_barcode = false; } } if (save_barcode == true) { customerProdStockRecord.setValue({ fieldId: 'custrecord_cust_prod_stock_source', value: 6 }); customerProdStockRecord.setValue({ fieldId: 'custrecord_cust_prod_stock_operator', value: operator_id }); customerProdStockRecord.setValue({ fieldId: 'custrecord_mpdl_number', value: external_barcode }); var sourceId = getSourceID(source); if (sourceId != null) { customerProdStockRecord.setValue({ fieldId: 'custrecord_barcode_source', value: sourceId }); } customerProdStockRecord.setValue({ fieldId: 'custrecord_receiver_suburb', value: receiver_suburb }); customerProdStockRecord.setValue({ fieldId: 'custrecord_receiver_postcode', value: receiver_postcode }); customerProdStockRecord.setValue({ fieldId: 'custrecord_receiver_state', value: receiver_state }); customerProdStockRecord.setValue({ fieldId: 'custrecord_receiver_addr1', value: receiver_addr1 }); customerProdStockRecord.setValue({ fieldId: 'custrecord_receiver_addr2', value: receiver_addr2 }); customerProdStockRecord.setValue({ fieldId: 'custrecord_receiver_name', value: receiver_name }); customerProdStockRecord.setValue({ fieldId: 'custrecord_receiver_email', value: receiver_email }); customerProdStockRecord.setValue({ fieldId: 'custrecord_receiver_phone', value: receiver_phone }); //Invoiceable field is set to false if (invoiceable === false || invoiceable == 'false' || invoiceable === 'false' || invoiceable == false) { //Set invoiceable as NO customerProdStockRecord.setValue({ fieldId: 'custrecord_cust_prod_stock_invoiceable', value: 2 }); //Set Prepaid as YES customerProdStockRecord.setValue({ fieldId: 'custrecord_cust_prod_stock_prepaid', value: 1 }); } if (barcode_beg == 'MPEN' || barcode_beg == 'MPET' || barcode_beg == 'MPEF' || barcode_beg == 'MPEB' || barcode_beg == 'MPEC' || barcode_beg == 'MPED' || barcode_beg == 'MPEG') { if (barcode_beg == 'MPEN') { prod_id = 552; } else if (barcode_beg == 'MPET') { prod_id = 553; } else if (barcode_beg == 'MPEF') { prod_id = 554; } else if (barcode_beg == 'MPEB') { prod_id = 550; } else if (barcode_beg == 'MPEC') { prod_id = 551; } else if (barcode_beg == 'MPED') { prod_id = 549; } else if (barcode_beg == 'MPEG') { prod_id = 638; } customerProdStockRecord.setValue({ fieldId: 'custrecord_cust_stock_prod_name', value: prod_id }); } customer_prod_stock_id = customerProdStockRecord.save(); } } count++; return true; }); //Barcode does not exist in NetSuite if (count == 0) { log.debug({ title: 'Barcode does not exist', details: scans[y].scan_type }); var save_barcode = true; if (isNullorEmpty(deleted)) { var customerProdStockRecord = record.create({ type: 'customrecord_customer_product_stock' }); log.debug({ title: 'EDIT - updated_at', details: updated_at }); customerProdStockRecord.setText({ fieldId: 'custrecord_cust_date_stock_given', value: updated_at }); log.debug({ title: 'EDIT - time_updated_at', details: time_updated_at }); customerProdStockRecord.setText({ fieldId: 'custrecord_cust_time_stock_given', value: time_updated_at }); //Invoiceable field is set to false if (invoiceable === false || invoiceable == 'false' || invoiceable === 'false' || invoiceable == false) { //Set invoiceable as NO customerProdStockRecord.setValue({ fieldId: 'custrecord_cust_prod_stock_invoiceable', value: 2 }); //Set Prepaid as YES customerProdStockRecord.setValue({ fieldId: 'custrecord_cust_prod_stock_prepaid', value: 1 }); } customerProdStockRecord.setValue({ fieldId: 'name', value: barcode }); if (scan_type == 'stockzee') { if (!isNullorEmpty(zee_id)) { //Set status as Zee stock customerProdStockRecord.setValue({ fieldId: 'custrecord_cust_prod_stock_status', value: 8 }); customerProdStockRecord.setText({ fieldId: 'custrecord_cust_date_stock_given', value: updated_at }); customerProdStockRecord.setText({ fieldId: 'custrecord_cust_time_stock_given', value: time_updated_at }); customerProdStockRecord.setValue({ fieldId: 'custrecord_cust_prod_stock_customer', value: null }); customerProdStockRecord.setValue({ fieldId: 'custrecord_cust_prod_stock_zee', value: zee_id }); customerProdStockRecord.setText({ fieldId: 'custrecord_history_zee_stock_date', value: updated_at }); customerProdStockRecord.setText({ fieldId: 'custrecord_history_zee_stock_time', value: time_updated_at }); } else { //Send email if no Zee ID email.send({ author: 409635, recipients: 'hzdkv@example.com', subject: 'MPEX Scan Sync - Error', body: 'Barcode: ' + barcode + ' has empty Zee ID' }); save_barcode = false; } } else if (scan_type == 'allocate') { if (!isNullorEmpty(customer_id)) { //Invoiceable field is set to false if (invoiceable === false || invoiceable == 'false' || invoiceable === 'false' || invoiceable == false) { //Set invoiceable as NO customerProdStockRecord.setValue({ fieldId: 'custrecord_cust_prod_stock_invoiceable', value: 2 }); //Set Prepaid as YES customerProdStockRecord.setValue({ fieldId: 'custrecord_cust_prod_stock_prepaid', value: 1 }); } customerProdStockRecord.setValue({ fieldId: 'custrecord_cust_prod_stock_customer', value: customer_id }); customerProdStockRecord.setValue({ fieldId: 'custrecord_cust_prod_stock_status', value: 1 }); customerProdStockRecord.setText({ fieldId: 'custrecord_cust_date_stock_given', value: updated_at }); customerProdStockRecord.setText({ fieldId: 'custrecord_cust_time_stock_given', value: time_updated_at }); customerProdStockRecord.setText({ fieldId: 'custrecord_history_allocate_date', value: updated_at }); customerProdStockRecord.setText({ fieldId: 'custrecord_history_allocate_time', value: time_updated_at }); } else { email.send({ author: 409635, recipients: 'hzdkv@example.com', subject: 'MPEX Scan Sync - Error', body: 'Barcode: ' + barcode + ' has empty Customer ID' }); save_barcode = false; } } else if (scan_type == 'pickup') { if (!isNullorEmpty(customer_id)) { //Invoiceable field is set to false if (invoiceable === false || invoiceable == 'false' || invoiceable === 'false' || invoiceable == false) { //Set invoiceable as NO customerProdStockRecord.setValue({ fieldId: 'custrecord_cust_prod_stock_invoiceable', value: 2 }); //Set Prepaid as YES customerProdStockRecord.setValue({ fieldId: 'custrecord_cust_prod_stock_prepaid', value: 1 }); } customerProdStockRecord.setValue({ fieldId: 'custrecord_cust_prod_stock_customer', value: customer_id }); customerProdStockRecord.setValue({ fieldId: 'custrecord_cust_prod_stock_status', value: 2 }); customerProdStockRecord.setText({ fieldId: 'custrecord_cust_date_stock_given', value: updated_at }); customerProdStockRecord.setText({ fieldId: 'custrecord_cust_time_stock_given', value: time_updated_at }); customerProdStockRecord.setText({ fieldId: 'custrecord_history_pickup_date', value: updated_at }); customerProdStockRecord.setText({ fieldId: 'custrecord_history_pickup_time', value: time_updated_at }); } else { email.send({ author: 409635, recipients: 'hzdkv@example.com', subject: 'MPEX Scan Sync - Error', body: 'Barcode: ' + barcode + ' has empty Customer ID' }); save_barcode = false; } } else if (scan_type == "delivery") { if (!isNullorEmpty(customer_id)) { //Invoiceable field is set to false if (invoiceable === false || invoiceable == 'false' || invoiceable === 'false' || invoiceable == false) { //Set invoiceable as NO customerProdStockRecord.setValue({ fieldId: 'custrecord_cust_prod_stock_invoiceable', value: 2 }); //Set Prepaid as YES customerProdStockRecord.setValue({ fieldId: 'custrecord_cust_prod_stock_prepaid', value: 1 }); } customerProdStockRecord.setValue({ fieldId: 'custrecord_cust_prod_stock_customer', value: customer_id }); customerProdStockRecord.setValue({ fieldId: 'custrecord_cust_prod_stock_status', value: 4 }); customerProdStockRecord.setValue({ fieldId: 'custrecord_cust_prod_stock_final_del', value: 4 }); customerProdStockRecord.setText({ fieldId: 'custrecord_cust_date_stock_given', value: updated_at }); customerProdStockRecord.setText({ fieldId: 'custrecord_cust_time_stock_given', value: time_updated_at }); customerProdStockRecord.setText({ fieldId: 'custrecord_history_delivery_date', value: updated_at }); customerProdStockRecord.setText({ fieldId: 'custrecord_history_delivery_time', value: time_updated_at }); } else { email.send({ author: 409635, recipients: 'hzdkv@example.com', subject: 'MPEX Scan Sync - Error', body: 'Barcode: ' + barcode + ' has empty Customer ID' }); save_barcode = false; } } else if (scan_type == "lodgement") { if (!isNullorEmpty(customer_id)) { //Invoiceable field is set to false if (invoiceable === false || invoiceable == 'false' || invoiceable === 'false' || invoiceable == false) { //Set invoiceable as NO customerProdStockRecord.setValue({ fieldId: 'custrecord_cust_prod_stock_invoiceable', value: 2 }); //Set Prepaid as YES customerProdStockRecord.setValue({ fieldId: 'custrecord_cust_prod_stock_prepaid', value: 1 }); } customerProdStockRecord.setValue({ fieldId: 'custrecord_cust_prod_stock_customer', value: customer_id }); customerProdStockRecord.setValue({ fieldId: 'custrecord_cust_prod_stock_status', value: 5 }); customerProdStockRecord.setValue({ fieldId: 'custrecord_cust_prod_stock_final_del', value: 5 }); customerProdStockRecord.setText({ fieldId: 'custrecord_cust_date_stock_given', value: updated_at }); customerProdStockRecord.setText({ fieldId: 'custrecord_cust_time_stock_given', value: time_updated_at }); customerProdStockRecord.setText({ fieldId: 'custrecord_history_lodge_date', value: updated_at }); customerProdStockRecord.setText({ fieldId: 'custrecord_history_lodge_time', value: time_updated_at }); } else { email.send({ author: 409635, recipients: 'hzdkv@example.com', subject: 'MPEX Scan Sync - Error', body: 'Barcode: ' + barcode + ' has empty Customer ID' }); save_barcode = false; } } if (save_barcode == true) { customerProdStockRecord.setValue({ fieldId: 'custrecord_cust_prod_stock_source', value: 6 }); customerProdStockRecord.setValue({ fieldId: 'custrecord_cust_prod_stock_operator', value: operator_id }); customerProdStockRecord.setValue({ fieldId: 'custrecord_mpdl_number', value: external_barcode }); var sourceId = getSourceID(source); if (sourceId != null) { customerProdStockRecord.setValue({ fieldId: 'custrecord_barcode_source', value: sourceId }); } customerProdStockRecord.setValue({ fieldId: 'custrecord_receiver_suburb', value: receiver_suburb }); customerProdStockRecord.setValue({ fieldId: 'custrecord_receiver_postcode', value: receiver_postcode }); customerProdStockRecord.setValue({ fieldId: 'custrecord_receiver_state', value: receiver_state }); customerProdStockRecord.setValue({ fieldId: 'custrecord_receiver_addr1', value: receiver_addr1 }); customerProdStockRecord.setValue({ fieldId: 'custrecord_receiver_addr2', value: receiver_addr2 }); customerProdStockRecord.setValue({ fieldId: 'custrecord_receiver_name', value: receiver_name }); customerProdStockRecord.setValue({ fieldId: 'custrecord_receiver_email', value: receiver_email }); customerProdStockRecord.setValue({ fieldId: 'custrecord_receiver_phone', value: receiver_phone }); //Invoiceable field is set to false if (invoiceable === false || invoiceable == 'false' || invoiceable === 'false' || invoiceable == false) { //Set invoiceable as NO customerProdStockRecord.setValue({ fieldId: 'custrecord_cust_prod_stock_invoiceable', value: 2 }); //Set Prepaid as YES customerProdStockRecord.setValue({ fieldId: 'custrecord_cust_prod_stock_prepaid', value: 1 }); } if (barcode_beg == 'MPEN' || barcode_beg == 'MPET' || barcode_beg == 'MPEF' || barcode_beg == 'MPEB' || barcode_beg == 'MPEC' || barcode_beg == 'MPED' || barcode_beg == 'MPEG') { if (barcode_beg == 'MPEN') { prod_id = 552; } else if (barcode_beg == 'MPET') { prod_id = 553; } else if (barcode_beg == 'MPEF') { prod_id = 554; } else if (barcode_beg == 'MPEB') { prod_id = 550; } else if (barcode_beg == 'MPEC') { prod_id = 551; } else if (barcode_beg == 'MPED') { prod_id = 549; } else if (barcode_beg == 'MPEG') { prod_id = 638; } customerProdStockRecord.setValue({ fieldId: 'custrecord_cust_stock_prod_name', value: prod_id }); } customer_prod_stock_id = customerProdStockRecord.save(); } } } } } // // log.audit({ title: 'barcodes Length before splice', details: barcodes.length }); log.audit({ title: 'barcodes before splice', details: barcodes }); barcodes.splice(x, 1); log.audit({ title: 'barcodes Length after splice', details: barcodes.length }); log.audit({ title: 'barcodes after splice', details: barcodes }); var scan_json_2 = '{ "scans": ' + JSON.stringify(barcodes) + '}'; var body_2 = scan_json_record.setValue({ fieldId: 'custrecord_json', value: scan_json_2 }); scan_json_record.save(); var scriptTask = task.create({ taskType: task.TaskType.SCHEDULED_SCRIPT, scriptId: 'customscript_ss2_rta_scan_sync_v2', deploymentId: 'customdeploy2', params: null }); var scriptTaskId = scriptTask.submit(); return false; x++; } while (barcodes.length > 0); } else if (barcodes.length == 0) { var body_2 = scan_json_record.setValue({ fieldId: 'custrecord_scan_josn_sync', value: 1 }); } return true; }); } return { execute: execute }; } ); function getSourceID(source) { switch (source) { case 'shopify': return 2; break; case 'manual': return 1; break; case 'bulk': return 4; break; case 'portal': return 3; break; default: return null; break; } } function onTimeChange(value) { if (value != "") { var timeSplit = value.split(':'), hours, minutes, meridian; hours = timeSplit[0]; minutes = timeSplit[1]; if (hours > 12) { meridian = 'PM'; hours -= 12; } else if (hours < 12) { meridian = 'AM'; if (hours == 0) { hours = 12; } } else { meridian = 'PM'; } return (hours + ':' + minutes + ' ' + meridian); } } function convertTo24Hour(time) { var hours_string = (time.substr(0, 2)); var hours = parseInt(time.substr(0, 2)); if (time.indexOf('AM') != -1 && hours == 12) { time = time.replace('12', '0'); } // if (time.indexOf('AM') != -1 && hours < 10) { // time = time.replace(hours, ('0' + hours)); // } if (time.indexOf('PM') != -1 && hours < 12) { console.log(hours + 12) time = time.replace(hours_string, (hours + 12)); } return time.replace(/( AM| PM)/, ''); } /** * Is Null or Empty. * * @param {Object} strVal */ function isNullorEmpty(strVal) { return (strVal == null || strVal == '' || strVal == 'null' || strVal == undefined || strVal == 'undefined' || strVal == '- None -'); }
true
/** *@NApiVersion 2.x *@NScriptType ScheduledScript */ define(['N/task', 'N/email', 'N/runtime', 'N/search', 'N/record', 'N/format', 'N/https'], function(task, email, runtime, search, record, format, https) { function execute(context) { var todayDate = new Date(); log.audit({ title: 'todayDate', details: todayDate }); //To get todays date var today = format.format({ value: todayDate, type: format.Type.DATE }); log.audit({ title: 'today', details: today }); var tempTodayDate = today.split('/'); // var temp = tempTodayDate.split('-'); // var today = tempTodayDate[0] + '/' + tempTodayDate[1] + '/' + tempTodayDate[2]; var today = '02-05-2021'; log.audit({ title: 'today', details: today }); var scanJSONSearch = search.load({ id: 'customsearch_scan_json' }); scanJSONSearch.filters.push(search.createFilter({ name: 'name', join: null, operator: search.Operator.STARTSWITH, values: '02-05-2021_Part_2' })); scanJSONSearch.filters.push(search.createFilter({ name: 'custrecord_scan_josn_sync', join: null, operator: search.Operator.IS, values: 2 })); scanJSONSearch.filters.push(search.createFilter({ name: 'isinactive', join: null, operator: search.Operator.IS, values: "F" })); var scan_json_record_id; scanJSONSearch.run().each(function(searchResult) { var scriptObj = runtime.getCurrentScript() var usage_loopstart_cust = scriptObj.getRemainingUsage(); log.audit({ title: 'Start of SCAN JSON Loop', details: usage_loopstart_cust }); var scan_json_record_id = searchResult.getValue({ name: 'internalid' }); var scan_json_record_name = searchResult.getValue({ name: "name" }); log.audit({ title: 'Scan JSON Record Name ', details: scan_json_record_name }); var scan_json_record = record.load({ type: 'customrecord_scan_json', id: scan_json_record_id }); var body = scan_json_record.getValue({ fieldId: 'custrecord_json' }); var body_2 = scan_json_record.getValue({ fieldId: 'custrecord_scan_json_2' }); if (body_2 == "") { var todays_scans = JSON.parse(body); var barcodes = todays_scans.scans; //No. of barcodes } else { var todays_scans = JSON.parse(body_2); var barcodes = todays_scans.scans; //No. of barcodes } log.audit({ title: 'barcodes', details: barcodes }); log.audit({ title: 'barcodes length', details: barcodes.length }); if (barcodes.length > 0) { //Iterate through each barcode do { var x = barcodes.length - 1; var scriptObj = runtime.getCurrentScript() var usage_loopstart_cust = scriptObj.getRemainingUsage(); //Usage at the start of each barcode log.audit({ title: 'Start of Barcode Loop', details: scriptObj.getRemainingUsage() }); log.audit({ title: 'Scans for barcode: ' + barcodes[x].code, details: barcodes[x].scans }); var scans = barcodes[x].scans; log.audit({ title: 'Scans Length for barcode: ' + barcodes[x].code, details: scans.length }); //Only one scan history for the barcode if (scans.length == 1) { log.audit({ title: 'Inside Scan Length = 1', details: barcodes[x].code }); var y = 0; var scriptObj = runtime.getCurrentScript() var usage_loopstart_cust = scriptObj.getRemainingUsage(); //Usage at the start of each scan type log.audit({ title: 'Start of Scans Loop per barcode', details: scriptObj.getRemainingUsage() }); log.audit({ title: 'Scans for barcode: ' + barcodes[x].code, details: scans[y] }); log.audit({ title: 'Scans for barcode: ' + barcodes[x].code, details: scans[y].scan_type }); var barcode = scans[y].barcode.toUpperCase(); var customer_id = scans[y].customer_ns_id; var zee_id = scans[y].zee_ns_id; var rta_id = scans[y].id; var invoiceable = scans[y].invoiceable; var scan_type = scans[y].scan_type.toLowerCase(); var operator_id = scans[y].operator_ns_id; var updated_at = scans[y].updated_at; var deleted = scans[y].deleted; var external_barcode = scans[y].external_barcode; var source = scans[y].source; var receiver_suburb = scans[y].receiver_suburb; var receiver_postcode = scans[y].post_code; var receiver_state = scans[y].state; var receiver_addr1 = scans[y].address1; var receiver_addr2 = scans[y].address2; var receiver_name = scans[y].receiver_name; var receiver_email = scans[y].email; var receiver_phone = scans[y].phone; updated_at = updated_at.split("T"); var time_updated_at = updated_at[1]; time_updated_at = time_updated_at.split("."); time_updated_at = onTimeChange(time_updated_at[0]); time_updated_at = format.parse({ value: time_updated_at, type: format.Type.TIMEOFDAY }); log.audit({ title: 'TIME OF DAY', details: time_updated_at }); var updated_at = updated_at[0]; var save_barcode = true; var barcode_beg = barcode.slice(0, 4); updated_at = updated_at.split("-"); updated_at = format.parse({ value: updated_at[2] + '/' + updated_at[1] + '/' + updated_at[0], type: format.Type.DATE }); log.audit({ title: 'DATE', details: updated_at }); // updated_at = nlapiStringToDate(updated_at[2] + '/' + updated_at[1] + '/' + updated_at[0]); //Load Search: RTA - Product Stock var productStockSearch = search.load({ id: 'customsearch_rta_product_stock' }); productStockSearch.filters.push(search.createFilter({ name: 'name', join: null, operator: search.Operator.IS, values: barcode })); productStockSearch.filters.push(search.createFilter({ name: 'isinactive', join: null, operator: search.Operator.IS, values: "F" })); var count = 0; var prod_id; productStockSearch.run().each(function(searchResult) { log.audit({ title: 'Barcode does exist', details: scans[y].scan_type.toLowerCase() }); var customer_prod_stock_id = searchResult.getValue({ name: 'internalid' }); //Load the customer product stock record var customerProdStockRecord = record.load({ type: 'customrecord_customer_product_stock', id: customer_prod_stock_id }); //Get the current status of the record. var stock_status = customerProdStockRecord.getValue({ fieldId: 'custrecord_cust_prod_stock_status' }); //Status is Product Order Created or Invoiced if (stock_status != 6 && stock_status != 7) { if (scan_type == 'stockzee') { if (!isNullorEmpty(zee_id)) { //Set status as Zee stock customerProdStockRecord.setValue({ fieldId: 'custrecord_cust_prod_stock_status', value: 8 }); customerProdStockRecord.setText({ fieldId: 'custrecord_cust_date_stock_given', value: updated_at }); customerProdStockRecord.setText({ fieldId: 'custrecord_cust_time_stock_given', value: time_updated_at }); customerProdStockRecord.setValue({ fieldId: 'custrecord_cust_prod_stock_customer', value: null }); customerProdStockRecord.setValue({ fieldId: 'custrecord_cust_prod_stock_zee', value: zee_id }); } else { //Send email if no Zee ID email.send({ author: 409635, recipients: 'PI:EMAIL:hzdkv@example.comEND_PI', subject: 'MPEX Scan Sync - Error', body: 'Barcode: ' + barcode + ' has empty Zee ID' }); save_barcode = false; } } else if (scan_type == 'allocate') { if (!isNullorEmpty(customer_id)) { //Invoiceable field is set to false if (invoiceable === false || invoiceable == 'false' || invoiceable === 'false' || invoiceable == false) { //Set invoiceable as NO customerProdStockRecord.setValue({ fieldId: 'custrecord_cust_prod_stock_invoiceable', value: 2 }); //Set Prepaid as YES customerProdStockRecord.setValue({ fieldId: 'custrecord_cust_prod_stock_prepaid', value: 1 }); } customerProdStockRecord.setValue({ fieldId: 'custrecord_cust_prod_stock_customer', value: customer_id }); customerProdStockRecord.setValue({ fieldId: 'custrecord_cust_prod_stock_status', value: 1 }); customerProdStockRecord.setText({ fieldId: 'custrecord_cust_date_stock_given', value: updated_at }); customerProdStockRecord.setText({ fieldId: 'custrecord_cust_time_stock_given', value: time_updated_at }); } else { email.send({ author: 409635, recipients: 'PI:EMAIL:hzdkv@example.comEND_PI', subject: 'MPEX Scan Sync - Error', body: 'Barcode: ' + barcode + ' has empty Customer ID' }); save_barcode = false; } } else if (scan_type == 'pickup') { if (!isNullorEmpty(customer_id)) { //Invoiceable field is set to false if (invoiceable === false || invoiceable == 'false' || invoiceable === 'false' || invoiceable == false) { //Set invoiceable as NO customerProdStockRecord.setValue({ fieldId: 'custrecord_cust_prod_stock_invoiceable', value: 2 }); //Set Prepaid as YES customerProdStockRecord.setValue({ fieldId: 'custrecord_cust_prod_stock_prepaid', value: 1 }); } customerProdStockRecord.setValue({ fieldId: 'custrecord_cust_prod_stock_customer', value: customer_id }); customerProdStockRecord.setValue({ fieldId: 'custrecord_cust_prod_stock_status', value: 2 }); customerProdStockRecord.setText({ fieldId: 'custrecord_cust_date_stock_given', value: updated_at }); customerProdStockRecord.setText({ fieldId: 'custrecord_cust_time_stock_given', value: time_updated_at }); } else { email.send({ author: 409635, recipients: 'PI:EMAIL:hzdkv@example.comEND_PI', subject: 'MPEX Scan Sync - Error', body: 'Barcode: ' + barcode + ' has empty Customer ID' }); save_barcode = false; } } else if (scan_type == "delivery") { if (!isNullorEmpty(customer_id)) { //Invoiceable field is set to false if (invoiceable === false || invoiceable == 'false' || invoiceable === 'false' || invoiceable == false) { //Set invoiceable as NO customerProdStockRecord.setValue({ fieldId: 'custrecord_cust_prod_stock_invoiceable', value: 2 }); //Set Prepaid as YES customerProdStockRecord.setValue({ fieldId: 'custrecord_cust_prod_stock_prepaid', value: 1 }); } customerProdStockRecord.setValue({ fieldId: 'custrecord_cust_prod_stock_customer', value: customer_id }); customerProdStockRecord.setValue({ fieldId: 'custrecord_cust_prod_stock_status', value: 4 }); customerProdStockRecord.setValue({ fieldId: 'custrecord_cust_prod_stock_final_del', value: 4 }); customerProdStockRecord.setText({ fieldId: 'custrecord_cust_date_stock_given', value: updated_at }); customerProdStockRecord.setText({ fieldId: 'custrecord_cust_time_stock_given', value: time_updated_at }); } else { email.send({ author: 409635, recipients: 'PI:EMAIL:hzdkv@example.comEND_PI', subject: 'MPEX Scan Sync - Error', body: 'Barcode: ' + barcode + ' has empty Customer ID' }); save_barcode = false; } } else if (scan_type == "lodgement") { if (!isNullorEmpty(customer_id)) { //Invoiceable field is set to false if (invoiceable === false || invoiceable == 'false' || invoiceable === 'false' || invoiceable == false) { //Set invoiceable as NO customerProdStockRecord.setValue({ fieldId: 'custrecord_cust_prod_stock_invoiceable', value: 2 }); //Set Prepaid as YES customerProdStockRecord.setValue({ fieldId: 'custrecord_cust_prod_stock_prepaid', value: 1 }); } customerProdStockRecord.setValue({ fieldId: 'custrecord_cust_prod_stock_customer', value: customer_id }); customerProdStockRecord.setValue({ fieldId: 'custrecord_cust_prod_stock_status', value: 5 }); customerProdStockRecord.setValue({ fieldId: 'custrecord_cust_prod_stock_final_del', value: 5 }); customerProdStockRecord.setText({ fieldId: 'custrecord_cust_date_stock_given', value: updated_at }); customerProdStockRecord.setText({ fieldId: 'custrecord_cust_time_stock_given', value: time_updated_at }); } else { email.send({ author: 409635, recipients: 'PI:EMAIL:hzdkv@example.comEND_PI', subject: 'MPEX Scan Sync - Error', body: 'Barcode: ' + barcode + ' has empty Customer ID' }); save_barcode = false; } } if (save_barcode == true) { customerProdStockRecord.setValue({ fieldId: 'custrecord_cust_prod_stock_source', value: 6 }); customerProdStockRecord.setValue({ fieldId: 'custrecord_cust_prod_stock_operator', value: operator_id }); customerProdStockRecord.setValue({ fieldId: 'custrecord_mpdl_number', value: external_barcode }); var sourceId = getSourceID(source); if (sourceId != null) { customerProdStockRecord.setValue({ fieldId: 'custrecord_barcode_source', value: sourceId }); } customerProdStockRecord.setValue({ fieldId: 'custrecord_receiver_suburb', value: receiver_suburb }); customerProdStockRecord.setValue({ fieldId: 'custrecord_receiver_postcode', value: receiver_postcode }); customerProdStockRecord.setValue({ fieldId: 'custrecord_receiver_state', value: receiver_state }); customerProdStockRecord.setValue({ fieldId: 'custrecord_receiver_addr1', value: receiver_addr1 }); customerProdStockRecord.setValue({ fieldId: 'custrecord_receiver_addr2', value: receiver_addr2 }); customerProdStockRecord.setValue({ fieldId: 'custrecord_receiver_name', value: receiver_name }); customerProdStockRecord.setValue({ fieldId: 'custrecord_receiver_email', value: receiver_email }); customerProdStockRecord.setValue({ fieldId: 'custrecord_receiver_phone', value: receiver_phone }); //Invoiceable field is set to false if (invoiceable === false || invoiceable == 'false' || invoiceable === 'false' || invoiceable == false) { //Set invoiceable as NO customerProdStockRecord.setValue({ fieldId: 'custrecord_cust_prod_stock_invoiceable', value: 2 }); //Set Prepaid as YES customerProdStockRecord.setValue({ fieldId: 'custrecord_cust_prod_stock_prepaid', value: 1 }); } log.audit({ title: 'barcode_beg', details: barcode_beg }); if (barcode_beg == 'MPEN' || barcode_beg == 'MPET' || barcode_beg == 'MPEF' || barcode_beg == 'MPEB' || barcode_beg == 'MPEC' || barcode_beg == 'MPED' || barcode_beg == 'MPEG') { if (barcode_beg == 'MPEN') { prod_id = 552; } else if (barcode_beg == 'MPET') { prod_id = 553; } else if (barcode_beg == 'MPEF') { prod_id = 554; } else if (barcode_beg == 'MPEB') { prod_id = 550; } else if (barcode_beg == 'MPEC') { prod_id = 551; } else if (barcode_beg == 'MPED') { prod_id = 549; } else if (barcode_beg == 'MPEG') { prod_id = 638; } log.audit({ title: 'prod_id', details: prod_id }); customerProdStockRecord.setValue({ fieldId: 'custrecord_cust_stock_prod_name', value: prod_id }); } customer_prod_stock_id = customerProdStockRecord.save(); } } count++; return true; }); if (count == 0) { log.audit({ title: 'Barcode does not exist', details: scans[y].scan_type }); var save_barcode = true; if (isNullorEmpty(deleted)) { var customerProdStockRecord = record.create({ type: 'customrecord_customer_product_stock', isDynamic: true }); customerProdStockRecord.setText({ fieldId: 'custrecord_cust_date_stock_given', value: updated_at }); customerProdStockRecord.setText({ fieldId: 'custrecord_cust_time_stock_given', value: time_updated_at }); //Invoiceable field is set to false if (invoiceable === false || invoiceable == 'false' || invoiceable === 'false' || invoiceable == false) { //Set invoiceable as NO customerProdStockRecord.setValue({ fieldId: 'custrecord_cust_prod_stock_invoiceable', value: 2 }); //Set Prepaid as YES customerProdStockRecord.setValue({ fieldId: 'custrecord_cust_prod_stock_prepaid', value: 1 }); } customerProdStockRecord.setValue({ fieldId: 'name', value: barcode }); if (scan_type == 'stockzee') { if (!isNullorEmpty(zee_id)) { //Set status as Zee stock customerProdStockRecord.setValue({ fieldId: 'custrecord_cust_prod_stock_status', value: 8 }); customerProdStockRecord.setText({ fieldId: 'custrecord_cust_date_stock_given', value: updated_at }); customerProdStockRecord.setText({ fieldId: 'custrecord_cust_time_stock_given', value: time_updated_at }); customerProdStockRecord.setValue({ fieldId: 'custrecord_cust_prod_stock_customer', value: null }); customerProdStockRecord.setValue({ fieldId: 'custrecord_cust_prod_stock_zee', value: zee_id }); } else { //Send email if no Zee ID email.send({ author: 409635, recipients: 'PI:EMAIL:hzdkv@example.comEND_PI', subject: 'MPEX Scan Sync - Error', body: 'Barcode: ' + barcode + ' has empty Zee ID' }); save_barcode = false; } } else if (scan_type == 'allocate') { if (!isNullorEmpty(customer_id)) { //Invoiceable field is set to false if (invoiceable === false || invoiceable == 'false' || invoiceable === 'false' || invoiceable == false) { //Set invoiceable as NO customerProdStockRecord.setValue({ fieldId: 'custrecord_cust_prod_stock_invoiceable', value: 2 }); //Set Prepaid as YES customerProdStockRecord.setValue({ fieldId: 'custrecord_cust_prod_stock_prepaid', value: 1 }); } customerProdStockRecord.setValue({ fieldId: 'custrecord_cust_prod_stock_customer', value: customer_id }); customerProdStockRecord.setValue({ fieldId: 'custrecord_cust_prod_stock_status', value: 1 }); customerProdStockRecord.setText({ fieldId: 'custrecord_cust_date_stock_given', value: updated_at }); customerProdStockRecord.setText({ fieldId: 'custrecord_cust_time_stock_given', value: time_updated_at }); } else { email.send({ author: 409635, recipients: 'PI:EMAIL:hzdkv@example.comEND_PI', subject: 'MPEX Scan Sync - Error', body: 'Barcode: ' + barcode + ' has empty Customer ID' }); save_barcode = false; } } else if (scan_type == 'pickup') { if (!isNullorEmpty(customer_id)) { //Invoiceable field is set to false if (invoiceable === false || invoiceable == 'false' || invoiceable === 'false' || invoiceable == false) { //Set invoiceable as NO customerProdStockRecord.setValue({ fieldId: 'custrecord_cust_prod_stock_invoiceable', value: 2 }); //Set Prepaid as YES customerProdStockRecord.setValue({ fieldId: 'custrecord_cust_prod_stock_prepaid', value: 1 }); } customerProdStockRecord.setValue({ fieldId: 'custrecord_cust_prod_stock_customer', value: customer_id }); customerProdStockRecord.setValue({ fieldId: 'custrecord_cust_prod_stock_status', value: 2 }); customerProdStockRecord.setText({ fieldId: 'custrecord_cust_date_stock_given', value: updated_at }); customerProdStockRecord.setText({ fieldId: 'custrecord_cust_time_stock_given', value: time_updated_at }); } else { email.send({ author: 409635, recipients: 'PI:EMAIL:hzdkv@example.comEND_PI', subject: 'MPEX Scan Sync - Error', body: 'Barcode: ' + barcode + ' has empty Customer ID' }); save_barcode = false; } } else if (scan_type == "delivery") { if (!isNullorEmpty(customer_id)) { //Invoiceable field is set to false if (invoiceable === false || invoiceable == 'false' || invoiceable === 'false' || invoiceable == false) { //Set invoiceable as NO customerProdStockRecord.setValue({ fieldId: 'custrecord_cust_prod_stock_invoiceable', value: 2 }); //Set Prepaid as YES customerProdStockRecord.setValue({ fieldId: 'custrecord_cust_prod_stock_prepaid', value: 1 }); } customerProdStockRecord.setValue({ fieldId: 'custrecord_cust_prod_stock_customer', value: customer_id }); customerProdStockRecord.setValue({ fieldId: 'custrecord_cust_prod_stock_status', value: 4 }); customerProdStockRecord.setValue({ fieldId: 'custrecord_cust_prod_stock_final_del', value: 4 }); customerProdStockRecord.setText({ fieldId: 'custrecord_cust_date_stock_given', value: updated_at }); customerProdStockRecord.setText({ fieldId: 'custrecord_cust_time_stock_given', value: time_updated_at }); } else { email.send({ author: 409635, recipients: 'PI:EMAIL:hzdkv@example.comEND_PI', subject: 'MPEX Scan Sync - Error', body: 'Barcode: ' + barcode + ' has empty Customer ID' }); save_barcode = false; } } else if (scan_type == "lodgement") { if (!isNullorEmpty(customer_id)) { //Invoiceable field is set to false if (invoiceable === false || invoiceable == 'false' || invoiceable === 'false' || invoiceable == false) { //Set invoiceable as NO customerProdStockRecord.setValue({ fieldId: 'custrecord_cust_prod_stock_invoiceable', value: 2 }); //Set Prepaid as YES customerProdStockRecord.setValue({ fieldId: 'custrecord_cust_prod_stock_prepaid', value: 1 }); } customerProdStockRecord.setValue({ fieldId: 'custrecord_cust_prod_stock_customer', value: customer_id }); customerProdStockRecord.setValue({ fieldId: 'custrecord_cust_prod_stock_status', value: 5 }); customerProdStockRecord.setValue({ fieldId: 'custrecord_cust_prod_stock_final_del', value: 5 }); customerProdStockRecord.setText({ fieldId: 'custrecord_cust_date_stock_given', value: updated_at }); customerProdStockRecord.setText({ fieldId: 'custrecord_cust_time_stock_given', value: time_updated_at }); } else { email.send({ author: 409635, recipients: 'PI:EMAIL:hzdkv@example.comEND_PI', subject: 'MPEX Scan Sync - Error', body: 'Barcode: ' + barcode + ' has empty Customer ID' }); save_barcode = false; } } if (save_barcode == true) { customerProdStockRecord.setValue({ fieldId: 'custrecord_cust_prod_stock_source', value: 6 }); customerProdStockRecord.setValue({ fieldId: 'custrecord_cust_prod_stock_operator', value: operator_id }); customerProdStockRecord.setValue({ fieldId: 'custrecord_mpdl_number', value: external_barcode }); var sourceId = getSourceID(source); if (sourceId != null) { customerProdStockRecord.setValue({ fieldId: 'custrecord_barcode_source', value: sourceId }); } customerProdStockRecord.setValue({ fieldId: 'custrecord_receiver_suburb', value: receiver_suburb }); customerProdStockRecord.setValue({ fieldId: 'custrecord_receiver_postcode', value: receiver_postcode }); customerProdStockRecord.setValue({ fieldId: 'custrecord_receiver_state', value: receiver_state }); customerProdStockRecord.setValue({ fieldId: 'custrecord_receiver_addr1', value: receiver_addr1 }); customerProdStockRecord.setValue({ fieldId: 'custrecord_receiver_addr2', value: receiver_addr2 }); customerProdStockRecord.setValue({ fieldId: 'custrecord_receiver_name', value: receiver_name }); customerProdStockRecord.setValue({ fieldId: 'custrecord_receiver_email', value: receiver_email }); customerProdStockRecord.setValue({ fieldId: 'custrecord_receiver_phone', value: receiver_phone }); //Invoiceable field is set to false if (invoiceable === false || invoiceable == 'false' || invoiceable === 'false' || invoiceable == false) { //Set invoiceable as NO customerProdStockRecord.setValue({ fieldId: 'custrecord_cust_prod_stock_invoiceable', value: 2 }); //Set Prepaid as YES customerProdStockRecord.setValue({ fieldId: 'custrecord_cust_prod_stock_prepaid', value: 1 }); } if (barcode_beg == 'MPEN' || barcode_beg == 'MPET' || barcode_beg == 'MPEF' || barcode_beg == 'MPEB' || barcode_beg == 'MPEC' || barcode_beg == 'MPED' || barcode_beg == 'MPEG') { if (barcode_beg == 'MPEN') { prod_id = 552; } else if (barcode_beg == 'MPET') { prod_id = 553; } else if (barcode_beg == 'MPEF') { prod_id = 554; } else if (barcode_beg == 'MPEB') { prod_id = 550; } else if (barcode_beg == 'MPEC') { prod_id = 551; } else if (barcode_beg == 'MPED') { prod_id = 549; } else if (barcode_beg == 'MPEG') { prod_id = 638; } customerProdStockRecord.setValue({ fieldId: 'custrecord_cust_stock_prod_name', value: prod_id }); } customer_prod_stock_id = customerProdStockRecord.save(); } } } } else { //Iterate through the differenct scans for each barcode for (var y = 0; y < scans.length; y++) { var scriptObj = runtime.getCurrentScript() var usage_loopstart_cust = scriptObj.getRemainingUsage(); //Usage at the start of each scan type log.debug({ title: 'Start of Scans Loop per barcode', details: scriptObj.getRemainingUsage() }); log.debug({ title: 'Scans for barcode: ' + barcodes[x].code, details: scans[y] }); log.debug({ title: 'Scans for barcode: ' + barcodes[x].code, details: scans[y].scan_type }); var barcode = scans[y].barcode.toUpperCase(); var customer_id = scans[y].customer_ns_id; var zee_id = scans[y].zee_ns_id; var rta_id = scans[y].id; var invoiceable = scans[y].invoiceable; var scan_type = scans[y].scan_type.toLowerCase(); var operator_id = scans[y].operator_ns_id; var updated_at = scans[y].updated_at; var deleted = scans[y].deleted; var external_barcode = scans[y].external_barcode; var source = scans[y].source; var receiver_suburb = scans[y].receiver_suburb; var receiver_postcode = scans[y].post_code; var receiver_state = scans[y].state; var receiver_addr1 = scans[y].address1; var receiver_addr2 = scans[y].address2; var receiver_name = scans[y].receiver_name; var receiver_email = scans[y].email; var receiver_phone = scans[y].phone; updated_at = updated_at.split("T"); var time_updated_at = updated_at[1]; time_updated_at = time_updated_at.split("."); time_updated_at = onTimeChange(time_updated_at[0]); time_updated_at = format.parse({ value: time_updated_at, type: format.Type.TIMEOFDAY }); log.debug({ title: 'TIME OF DAY more than 1 scan', details: time_updated_at }); var updated_at = updated_at[0]; var save_barcode = true; var barcode_beg = barcode.slice(0, 4); updated_at = updated_at.split("-"); updated_at = format.parse({ value: updated_at[2] + '/' + updated_at[1] + '/' + updated_at[0], type: format.Type.DATE }) log.debug({ title: 'DATE more than 1 scan', details: updated_at }); // updated_at = nlapiStringToDate(updated_at[2] + '/' + updated_at[1] + '/' + updated_at[0]); // updated_at = nlapiStringToDate(updated_at[2] + '/' + updated_at[1] + '/' + updated_at[0]); //Load Search: RTA - Product Stock var productStockSearch = search.load({ id: 'customsearch_rta_product_stock' }); productStockSearch.filters.push(search.createFilter({ name: 'name', join: null, operator: search.Operator.IS, values: barcode })); productStockSearch.filters.push(search.createFilter({ name: 'isinactive', join: null, operator: search.Operator.IS, values: "F" })); var count = 0; var prod_id; productStockSearch.run().each(function(searchResult) { log.debug({ title: 'Barcode does exist', details: scans[y].scan_type }); var customer_prod_stock_id = searchResult.getValue({ name: 'internalid' }); //Load the customer product stock record var customerProdStockRecord = record.load({ type: 'customrecord_customer_product_stock', id: customer_prod_stock_id }); //Get the current status of the record. var stock_status = customerProdStockRecord.getValue({ fieldId: 'custrecord_cust_prod_stock_status' }); //Status is Product Order Created or Invoiced if (stock_status != 6 && stock_status != 7) { //If the scan has the deleted field if (!isNullorEmpty(deleted)) { //Status is Allocated to custoemer if (stock_status == 1) { customerProdStockRecord.setValue({ fieldId: 'custrecord_cust_prod_stock_customer', value: null }); customerProdStockRecord.setValue({ fieldId: 'custrecord_cust_date_stock_used', value: null }); customerProdStockRecord.setValue({ fieldId: 'custrecord_cust_time_stock_used', value: null }); //Change status to Zee Stock customerProdStockRecord.setValue({ fieldId: 'custrecord_cust_prod_stock_status', value: 8 }); customerProdStockRecord.setValue({ fieldId: 'custrecord_cust_prod_stock_zee', value: zee_id }); } else if (stock_status == 8) { // Status is Zee Stock //Inactivate the record customerProdStockRecord.setValue({ fieldId: 'isinactive', value: true }); customerProdStockRecord.setValue({ fieldId: 'custrecord_cust_time_deleted', value: time_updated_at }); } else if (stock_status == 4 || stock_status == 5) { // Status is Delivered to receiver / Lodged at TOLL //Change status to Allocated to customer customerProdStockRecord.setValue({ fieldId: 'custrecord_cust_prod_stock_status', value: 1 }); } } else if (scan_type == 'stockzee') { if (!isNullorEmpty(zee_id)) { //Set status as Zee stock customerProdStockRecord.setValue({ fieldId: 'custrecord_cust_prod_stock_status', value: 8 }); customerProdStockRecord.setText({ fieldId: 'custrecord_cust_date_stock_given', value: updated_at }); customerProdStockRecord.setText({ fieldId: 'custrecord_cust_time_stock_given', value: time_updated_at }); customerProdStockRecord.setValue({ fieldId: 'custrecord_cust_prod_stock_customer', value: null }); customerProdStockRecord.setValue({ fieldId: 'custrecord_cust_prod_stock_zee', value: zee_id }); customerProdStockRecord.setText({ fieldId: 'custrecord_history_zee_stock_date', value: updated_at }); customerProdStockRecord.setText({ fieldId: 'custrecord_history_zee_stock_time', value: time_updated_at }); } else { //Send email if no Zee ID email.send({ author: 409635, recipients: 'PI:EMAIL:hzdkv@example.comEND_PI', subject: 'MPEX Scan Sync - Error', body: 'Barcode: ' + barcode + ' has empty Zee ID' }); save_barcode = false; } } else if (scan_type == 'allocate') { if (!isNullorEmpty(customer_id)) { //Invoiceable field is set to false if (invoiceable === false || invoiceable == 'false' || invoiceable === 'false' || invoiceable == false) { //Set invoiceable as NO customerProdStockRecord.setValue({ fieldId: 'custrecord_cust_prod_stock_invoiceable', value: 2 }); //Set Prepaid as YES customerProdStockRecord.setValue({ fieldId: 'custrecord_cust_prod_stock_prepaid', value: 1 }); } customerProdStockRecord.setValue({ fieldId: 'custrecord_cust_prod_stock_customer', value: customer_id }); customerProdStockRecord.setValue({ fieldId: 'custrecord_cust_prod_stock_status', value: 1 }); customerProdStockRecord.setText({ fieldId: 'custrecord_cust_date_stock_given', value: updated_at }); customerProdStockRecord.setText({ fieldId: 'custrecord_cust_time_stock_given', value: time_updated_at }); customerProdStockRecord.setText({ fieldId: 'custrecord_history_allocate_date', value: updated_at }); customerProdStockRecord.setText({ fieldId: 'custrecord_history_allocate_time', value: time_updated_at }); } else { email.send({ author: 409635, recipients: 'PI:EMAIL:hzdkv@example.comEND_PI', subject: 'MPEX Scan Sync - Error', body: 'Barcode: ' + barcode + ' has empty Customer ID' }); save_barcode = false; } } else if (scan_type == 'pickup') { if (!isNullorEmpty(customer_id)) { //Invoiceable field is set to false if (invoiceable === false || invoiceable == 'false' || invoiceable === 'false' || invoiceable == false) { //Set invoiceable as NO customerProdStockRecord.setValue({ fieldId: 'custrecord_cust_prod_stock_invoiceable', value: 2 }); //Set Prepaid as YES customerProdStockRecord.setValue({ fieldId: 'custrecord_cust_prod_stock_prepaid', value: 1 }); } customerProdStockRecord.setValue({ fieldId: 'custrecord_cust_prod_stock_customer', value: customer_id }); customerProdStockRecord.setValue({ fieldId: 'custrecord_cust_prod_stock_status', value: 2 }); customerProdStockRecord.setText({ fieldId: 'custrecord_cust_date_stock_given', value: updated_at }); customerProdStockRecord.setText({ fieldId: 'custrecord_cust_time_stock_given', value: time_updated_at }); customerProdStockRecord.setText({ fieldId: 'custrecord_history_pickup_date', value: updated_at }); customerProdStockRecord.setText({ fieldId: 'custrecord_history_pickup_time', value: time_updated_at }); } else { email.send({ author: 409635, recipients: 'PI:EMAIL:hzdkv@example.comEND_PI', subject: 'MPEX Scan Sync - Error', body: 'Barcode: ' + barcode + ' has empty Customer ID' }); save_barcode = false; } } else if (scan_type == "delivery") { if (!isNullorEmpty(customer_id)) { //Invoiceable field is set to false if (invoiceable === false || invoiceable == 'false' || invoiceable === 'false' || invoiceable == false) { //Set invoiceable as NO customerProdStockRecord.setValue({ fieldId: 'custrecord_cust_prod_stock_invoiceable', value: 2 }); //Set Prepaid as YES customerProdStockRecord.setValue({ fieldId: 'custrecord_cust_prod_stock_prepaid', value: 1 }); } customerProdStockRecord.setValue({ fieldId: 'custrecord_cust_prod_stock_customer', value: customer_id }); customerProdStockRecord.setValue({ fieldId: 'custrecord_cust_prod_stock_status', value: 4 }); customerProdStockRecord.setValue({ fieldId: 'custrecord_cust_prod_stock_final_del', value: 4 }); customerProdStockRecord.setText({ fieldId: 'custrecord_cust_date_stock_given', value: updated_at }); customerProdStockRecord.setText({ fieldId: 'custrecord_cust_time_stock_given', value: time_updated_at }); customerProdStockRecord.setText({ fieldId: 'custrecord_history_delivery_date', value: updated_at }); customerProdStockRecord.setText({ fieldId: 'custrecord_history_delivery_time', value: time_updated_at }); } else { email.send({ author: 409635, recipients: 'PI:EMAIL:hzdkv@example.comEND_PI', subject: 'MPEX Scan Sync - Error', body: 'Barcode: ' + barcode + ' has empty Customer ID' }); save_barcode = false; } } else if (scan_type == "lodgement") { if (!isNullorEmpty(customer_id)) { //Invoiceable field is set to false if (invoiceable === false || invoiceable == 'false' || invoiceable === 'false' || invoiceable == false) { //Set invoiceable as NO customerProdStockRecord.setValue({ fieldId: 'custrecord_cust_prod_stock_invoiceable', value: 2 }); //Set Prepaid as YES customerProdStockRecord.setValue({ fieldId: 'custrecord_cust_prod_stock_prepaid', value: 1 }); } customerProdStockRecord.setValue({ fieldId: 'custrecord_cust_prod_stock_customer', value: customer_id }); customerProdStockRecord.setValue({ fieldId: 'custrecord_cust_prod_stock_status', value: 5 }); customerProdStockRecord.setValue({ fieldId: 'custrecord_cust_prod_stock_final_del', value: 5 }); customerProdStockRecord.setText({ fieldId: 'custrecord_cust_date_stock_given', value: updated_at }); customerProdStockRecord.setText({ fieldId: 'custrecord_cust_time_stock_given', value: time_updated_at }); customerProdStockRecord.setText({ fieldId: 'custrecord_history_lodge_date', value: updated_at }); customerProdStockRecord.setText({ fieldId: 'custrecord_history_lodge_time', value: time_updated_at }); } else { email.send({ author: 409635, recipients: 'PI:EMAIL:hzdkv@example.comEND_PI', subject: 'MPEX Scan Sync - Error', body: 'Barcode: ' + barcode + ' has empty Customer ID' }); save_barcode = false; } } if (save_barcode == true) { customerProdStockRecord.setValue({ fieldId: 'custrecord_cust_prod_stock_source', value: 6 }); customerProdStockRecord.setValue({ fieldId: 'custrecord_cust_prod_stock_operator', value: operator_id }); customerProdStockRecord.setValue({ fieldId: 'custrecord_mpdl_number', value: external_barcode }); var sourceId = getSourceID(source); if (sourceId != null) { customerProdStockRecord.setValue({ fieldId: 'custrecord_barcode_source', value: sourceId }); } customerProdStockRecord.setValue({ fieldId: 'custrecord_receiver_suburb', value: receiver_suburb }); customerProdStockRecord.setValue({ fieldId: 'custrecord_receiver_postcode', value: receiver_postcode }); customerProdStockRecord.setValue({ fieldId: 'custrecord_receiver_state', value: receiver_state }); customerProdStockRecord.setValue({ fieldId: 'custrecord_receiver_addr1', value: receiver_addr1 }); customerProdStockRecord.setValue({ fieldId: 'custrecord_receiver_addr2', value: receiver_addr2 }); customerProdStockRecord.setValue({ fieldId: 'custrecord_receiver_name', value: receiver_name }); customerProdStockRecord.setValue({ fieldId: 'custrecord_receiver_email', value: receiver_email }); customerProdStockRecord.setValue({ fieldId: 'custrecord_receiver_phone', value: receiver_phone }); //Invoiceable field is set to false if (invoiceable === false || invoiceable == 'false' || invoiceable === 'false' || invoiceable == false) { //Set invoiceable as NO customerProdStockRecord.setValue({ fieldId: 'custrecord_cust_prod_stock_invoiceable', value: 2 }); //Set Prepaid as YES customerProdStockRecord.setValue({ fieldId: 'custrecord_cust_prod_stock_prepaid', value: 1 }); } if (barcode_beg == 'MPEN' || barcode_beg == 'MPET' || barcode_beg == 'MPEF' || barcode_beg == 'MPEB' || barcode_beg == 'MPEC' || barcode_beg == 'MPED' || barcode_beg == 'MPEG') { if (barcode_beg == 'MPEN') { prod_id = 552; } else if (barcode_beg == 'MPET') { prod_id = 553; } else if (barcode_beg == 'MPEF') { prod_id = 554; } else if (barcode_beg == 'MPEB') { prod_id = 550; } else if (barcode_beg == 'MPEC') { prod_id = 551; } else if (barcode_beg == 'MPED') { prod_id = 549; } else if (barcode_beg == 'MPEG') { prod_id = 638; } customerProdStockRecord.setValue({ fieldId: 'custrecord_cust_stock_prod_name', value: prod_id }); } customer_prod_stock_id = customerProdStockRecord.save(); } } count++; return true; }); //Barcode does not exist in NetSuite if (count == 0) { log.debug({ title: 'Barcode does not exist', details: scans[y].scan_type }); var save_barcode = true; if (isNullorEmpty(deleted)) { var customerProdStockRecord = record.create({ type: 'customrecord_customer_product_stock' }); log.debug({ title: 'EDIT - updated_at', details: updated_at }); customerProdStockRecord.setText({ fieldId: 'custrecord_cust_date_stock_given', value: updated_at }); log.debug({ title: 'EDIT - time_updated_at', details: time_updated_at }); customerProdStockRecord.setText({ fieldId: 'custrecord_cust_time_stock_given', value: time_updated_at }); //Invoiceable field is set to false if (invoiceable === false || invoiceable == 'false' || invoiceable === 'false' || invoiceable == false) { //Set invoiceable as NO customerProdStockRecord.setValue({ fieldId: 'custrecord_cust_prod_stock_invoiceable', value: 2 }); //Set Prepaid as YES customerProdStockRecord.setValue({ fieldId: 'custrecord_cust_prod_stock_prepaid', value: 1 }); } customerProdStockRecord.setValue({ fieldId: 'name', value: barcode }); if (scan_type == 'stockzee') { if (!isNullorEmpty(zee_id)) { //Set status as Zee stock customerProdStockRecord.setValue({ fieldId: 'custrecord_cust_prod_stock_status', value: 8 }); customerProdStockRecord.setText({ fieldId: 'custrecord_cust_date_stock_given', value: updated_at }); customerProdStockRecord.setText({ fieldId: 'custrecord_cust_time_stock_given', value: time_updated_at }); customerProdStockRecord.setValue({ fieldId: 'custrecord_cust_prod_stock_customer', value: null }); customerProdStockRecord.setValue({ fieldId: 'custrecord_cust_prod_stock_zee', value: zee_id }); customerProdStockRecord.setText({ fieldId: 'custrecord_history_zee_stock_date', value: updated_at }); customerProdStockRecord.setText({ fieldId: 'custrecord_history_zee_stock_time', value: time_updated_at }); } else { //Send email if no Zee ID email.send({ author: 409635, recipients: 'PI:EMAIL:hzdkv@example.comEND_PI', subject: 'MPEX Scan Sync - Error', body: 'Barcode: ' + barcode + ' has empty Zee ID' }); save_barcode = false; } } else if (scan_type == 'allocate') { if (!isNullorEmpty(customer_id)) { //Invoiceable field is set to false if (invoiceable === false || invoiceable == 'false' || invoiceable === 'false' || invoiceable == false) { //Set invoiceable as NO customerProdStockRecord.setValue({ fieldId: 'custrecord_cust_prod_stock_invoiceable', value: 2 }); //Set Prepaid as YES customerProdStockRecord.setValue({ fieldId: 'custrecord_cust_prod_stock_prepaid', value: 1 }); } customerProdStockRecord.setValue({ fieldId: 'custrecord_cust_prod_stock_customer', value: customer_id }); customerProdStockRecord.setValue({ fieldId: 'custrecord_cust_prod_stock_status', value: 1 }); customerProdStockRecord.setText({ fieldId: 'custrecord_cust_date_stock_given', value: updated_at }); customerProdStockRecord.setText({ fieldId: 'custrecord_cust_time_stock_given', value: time_updated_at }); customerProdStockRecord.setText({ fieldId: 'custrecord_history_allocate_date', value: updated_at }); customerProdStockRecord.setText({ fieldId: 'custrecord_history_allocate_time', value: time_updated_at }); } else { email.send({ author: 409635, recipients: 'PI:EMAIL:hzdkv@example.comEND_PI', subject: 'MPEX Scan Sync - Error', body: 'Barcode: ' + barcode + ' has empty Customer ID' }); save_barcode = false; } } else if (scan_type == 'pickup') { if (!isNullorEmpty(customer_id)) { //Invoiceable field is set to false if (invoiceable === false || invoiceable == 'false' || invoiceable === 'false' || invoiceable == false) { //Set invoiceable as NO customerProdStockRecord.setValue({ fieldId: 'custrecord_cust_prod_stock_invoiceable', value: 2 }); //Set Prepaid as YES customerProdStockRecord.setValue({ fieldId: 'custrecord_cust_prod_stock_prepaid', value: 1 }); } customerProdStockRecord.setValue({ fieldId: 'custrecord_cust_prod_stock_customer', value: customer_id }); customerProdStockRecord.setValue({ fieldId: 'custrecord_cust_prod_stock_status', value: 2 }); customerProdStockRecord.setText({ fieldId: 'custrecord_cust_date_stock_given', value: updated_at }); customerProdStockRecord.setText({ fieldId: 'custrecord_cust_time_stock_given', value: time_updated_at }); customerProdStockRecord.setText({ fieldId: 'custrecord_history_pickup_date', value: updated_at }); customerProdStockRecord.setText({ fieldId: 'custrecord_history_pickup_time', value: time_updated_at }); } else { email.send({ author: 409635, recipients: 'PI:EMAIL:hzdkv@example.comEND_PI', subject: 'MPEX Scan Sync - Error', body: 'Barcode: ' + barcode + ' has empty Customer ID' }); save_barcode = false; } } else if (scan_type == "delivery") { if (!isNullorEmpty(customer_id)) { //Invoiceable field is set to false if (invoiceable === false || invoiceable == 'false' || invoiceable === 'false' || invoiceable == false) { //Set invoiceable as NO customerProdStockRecord.setValue({ fieldId: 'custrecord_cust_prod_stock_invoiceable', value: 2 }); //Set Prepaid as YES customerProdStockRecord.setValue({ fieldId: 'custrecord_cust_prod_stock_prepaid', value: 1 }); } customerProdStockRecord.setValue({ fieldId: 'custrecord_cust_prod_stock_customer', value: customer_id }); customerProdStockRecord.setValue({ fieldId: 'custrecord_cust_prod_stock_status', value: 4 }); customerProdStockRecord.setValue({ fieldId: 'custrecord_cust_prod_stock_final_del', value: 4 }); customerProdStockRecord.setText({ fieldId: 'custrecord_cust_date_stock_given', value: updated_at }); customerProdStockRecord.setText({ fieldId: 'custrecord_cust_time_stock_given', value: time_updated_at }); customerProdStockRecord.setText({ fieldId: 'custrecord_history_delivery_date', value: updated_at }); customerProdStockRecord.setText({ fieldId: 'custrecord_history_delivery_time', value: time_updated_at }); } else { email.send({ author: 409635, recipients: 'PI:EMAIL:hzdkv@example.comEND_PI', subject: 'MPEX Scan Sync - Error', body: 'Barcode: ' + barcode + ' has empty Customer ID' }); save_barcode = false; } } else if (scan_type == "lodgement") { if (!isNullorEmpty(customer_id)) { //Invoiceable field is set to false if (invoiceable === false || invoiceable == 'false' || invoiceable === 'false' || invoiceable == false) { //Set invoiceable as NO customerProdStockRecord.setValue({ fieldId: 'custrecord_cust_prod_stock_invoiceable', value: 2 }); //Set Prepaid as YES customerProdStockRecord.setValue({ fieldId: 'custrecord_cust_prod_stock_prepaid', value: 1 }); } customerProdStockRecord.setValue({ fieldId: 'custrecord_cust_prod_stock_customer', value: customer_id }); customerProdStockRecord.setValue({ fieldId: 'custrecord_cust_prod_stock_status', value: 5 }); customerProdStockRecord.setValue({ fieldId: 'custrecord_cust_prod_stock_final_del', value: 5 }); customerProdStockRecord.setText({ fieldId: 'custrecord_cust_date_stock_given', value: updated_at }); customerProdStockRecord.setText({ fieldId: 'custrecord_cust_time_stock_given', value: time_updated_at }); customerProdStockRecord.setText({ fieldId: 'custrecord_history_lodge_date', value: updated_at }); customerProdStockRecord.setText({ fieldId: 'custrecord_history_lodge_time', value: time_updated_at }); } else { email.send({ author: 409635, recipients: 'PI:EMAIL:hzdkv@example.comEND_PI', subject: 'MPEX Scan Sync - Error', body: 'Barcode: ' + barcode + ' has empty Customer ID' }); save_barcode = false; } } if (save_barcode == true) { customerProdStockRecord.setValue({ fieldId: 'custrecord_cust_prod_stock_source', value: 6 }); customerProdStockRecord.setValue({ fieldId: 'custrecord_cust_prod_stock_operator', value: operator_id }); customerProdStockRecord.setValue({ fieldId: 'custrecord_mpdl_number', value: external_barcode }); var sourceId = getSourceID(source); if (sourceId != null) { customerProdStockRecord.setValue({ fieldId: 'custrecord_barcode_source', value: sourceId }); } customerProdStockRecord.setValue({ fieldId: 'custrecord_receiver_suburb', value: receiver_suburb }); customerProdStockRecord.setValue({ fieldId: 'custrecord_receiver_postcode', value: receiver_postcode }); customerProdStockRecord.setValue({ fieldId: 'custrecord_receiver_state', value: receiver_state }); customerProdStockRecord.setValue({ fieldId: 'custrecord_receiver_addr1', value: receiver_addr1 }); customerProdStockRecord.setValue({ fieldId: 'custrecord_receiver_addr2', value: receiver_addr2 }); customerProdStockRecord.setValue({ fieldId: 'custrecord_receiver_name', value: receiver_name }); customerProdStockRecord.setValue({ fieldId: 'custrecord_receiver_email', value: receiver_email }); customerProdStockRecord.setValue({ fieldId: 'custrecord_receiver_phone', value: receiver_phone }); //Invoiceable field is set to false if (invoiceable === false || invoiceable == 'false' || invoiceable === 'false' || invoiceable == false) { //Set invoiceable as NO customerProdStockRecord.setValue({ fieldId: 'custrecord_cust_prod_stock_invoiceable', value: 2 }); //Set Prepaid as YES customerProdStockRecord.setValue({ fieldId: 'custrecord_cust_prod_stock_prepaid', value: 1 }); } if (barcode_beg == 'MPEN' || barcode_beg == 'MPET' || barcode_beg == 'MPEF' || barcode_beg == 'MPEB' || barcode_beg == 'MPEC' || barcode_beg == 'MPED' || barcode_beg == 'MPEG') { if (barcode_beg == 'MPEN') { prod_id = 552; } else if (barcode_beg == 'MPET') { prod_id = 553; } else if (barcode_beg == 'MPEF') { prod_id = 554; } else if (barcode_beg == 'MPEB') { prod_id = 550; } else if (barcode_beg == 'MPEC') { prod_id = 551; } else if (barcode_beg == 'MPED') { prod_id = 549; } else if (barcode_beg == 'MPEG') { prod_id = 638; } customerProdStockRecord.setValue({ fieldId: 'custrecord_cust_stock_prod_name', value: prod_id }); } customer_prod_stock_id = customerProdStockRecord.save(); } } } } } // // log.audit({ title: 'barcodes Length before splice', details: barcodes.length }); log.audit({ title: 'barcodes before splice', details: barcodes }); barcodes.splice(x, 1); log.audit({ title: 'barcodes Length after splice', details: barcodes.length }); log.audit({ title: 'barcodes after splice', details: barcodes }); var scan_json_2 = '{ "scans": ' + JSON.stringify(barcodes) + '}'; var body_2 = scan_json_record.setValue({ fieldId: 'custrecord_json', value: scan_json_2 }); scan_json_record.save(); var scriptTask = task.create({ taskType: task.TaskType.SCHEDULED_SCRIPT, scriptId: 'customscript_ss2_rta_scan_sync_v2', deploymentId: 'customdeploy2', params: null }); var scriptTaskId = scriptTask.submit(); return false; x++; } while (barcodes.length > 0); } else if (barcodes.length == 0) { var body_2 = scan_json_record.setValue({ fieldId: 'custrecord_scan_josn_sync', value: 1 }); } return true; }); } return { execute: execute }; } ); function getSourceID(source) { switch (source) { case 'shopify': return 2; break; case 'manual': return 1; break; case 'bulk': return 4; break; case 'portal': return 3; break; default: return null; break; } } function onTimeChange(value) { if (value != "") { var timeSplit = value.split(':'), hours, minutes, meridian; hours = timeSplit[0]; minutes = timeSplit[1]; if (hours > 12) { meridian = 'PM'; hours -= 12; } else if (hours < 12) { meridian = 'AM'; if (hours == 0) { hours = 12; } } else { meridian = 'PM'; } return (hours + ':' + minutes + ' ' + meridian); } } function convertTo24Hour(time) { var hours_string = (time.substr(0, 2)); var hours = parseInt(time.substr(0, 2)); if (time.indexOf('AM') != -1 && hours == 12) { time = time.replace('12', '0'); } // if (time.indexOf('AM') != -1 && hours < 10) { // time = time.replace(hours, ('0' + hours)); // } if (time.indexOf('PM') != -1 && hours < 12) { console.log(hours + 12) time = time.replace(hours_string, (hours + 12)); } return time.replace(/( AM| PM)/, ''); } /** * Is Null or Empty. * * @param {Object} strVal */ function isNullorEmpty(strVal) { return (strVal == null || strVal == '' || strVal == 'null' || strVal == undefined || strVal == 'undefined' || strVal == '- None -'); }
/** * Quote Form * custform_145_4283482_879 * * @NApiVersion 2.x * @NModuleScope Public * @NScriptType ClientScript * @author trungpv <trung@lexor.com> */ define([], function() { /* === VARS === */ /* === EVENTS FUNCTIONS === */ /** * Page Init * @param {*} context */ function pageInit(context) { const currentRecord = context.currentRecord; try { buildTableTotalWeight(currentRecord); removeOptionsShipAndBill(); } catch (error) { console.log("pageInit Error: ", error); } return; } /** * Sublist Changed * @param {*} context */ function sublistChanged(context) { const currentRecord = context.currentRecord; const sublistId = context.sublistId; if (sublistId === "item") { try { buildTableTotalWeight(currentRecord); } catch (error) { console.log("pageInit Error: ", error); } } return; } /** * Validate Line * @param {*} context */ function validateLine(context) { try { const sublistId = context.sublistId; const currentRecord = context.currentRecord; if (sublistId === "item") { const quantity = currentRecord.getCurrentSublistValue({ sublistId: sublistId, fieldId: "quantity" }); const itemWeight = currentRecord.getCurrentSublistValue({ sublistId: sublistId, fieldId: "weightinlb" }); currentRecord.setCurrentSublistValue({ sublistId: sublistId, fieldId: "custcol_total_weight", value: quantity * itemWeight }); const location = currentRecord.getValue({ fieldId: "location" }); if (location) { currentRecord.setCurrentSublistValue({ sublistId: sublistId, fieldId: "location", value: location }); } } } catch (error) { console.log("validateLine Error: ", error); } return true; //Return true if the line is valid. } /** * Field Changed * @param {*} context */ function fieldChanged(context) { //shipaddresslist, billaddresslist const fieldId = context.fieldId; const sublistId = context.sublistId; if ( sublistId === null && (fieldId === "shipaddresslist" || fieldId === "billaddresslist") ) { removeOptionsShipAndBill(); } return; } /** HELPPER FUNCTIONS **/ /** * Build HTML Table Total Weight * @param {*} currentRecord */ function buildTableTotalWeight(currentRecord) { // Add Util Function Replace All String.prototype.replaceAll = function(search, replacement) { return this.split(search).join(replacement); }; const totalLine = currentRecord.getLineCount({ sublistId: "item" }); var tableTotalWeight = {}; var totalWeight = 0; document.querySelector("#tableTotalWeight tbody").innerHTML = ""; for (var index = 0; index < totalLine; index++) { const quantity = currentRecord.getSublistValue({ sublistId: "item", fieldId: "quantity", line: index }); const weightinlb = currentRecord.getSublistValue({ sublistId: "item", fieldId: "weightinlb", line: index }); const location = currentRecord.getSublistValue({ sublistId: "item", fieldId: "location_display", line: index }); if (location === "") { if (tableTotalWeight["None"] === undefined) { tableTotalWeight["None"] = 0; } tableTotalWeight["None"] = tableTotalWeight["None"] + quantity * weightinlb; } else { if (tableTotalWeight[location] === undefined) { tableTotalWeight[location] = 0; } tableTotalWeight[location] = tableTotalWeight[location] + quantity * weightinlb; } totalWeight += quantity * weightinlb; } // Set Total Weight currentRecord.setValue({ fieldId: "custbody_total_weight", value: totalWeight }); var htmlTableTotalWeight = ""; for (var key in tableTotalWeight) { var tplRow = document.getElementById("tplTableTotalWeight").innerHTML; htmlTableTotalWeight += tplRow .replaceAll("____LOCATIN___", key) .replaceAll("____TOTAL_WEIGHT___", tableTotalWeight[key]); } document.querySelector( "#tableTotalWeight tbody" ).innerHTML = htmlTableTotalWeight; } /** * remove Select Option * @param {*} fieldName * @param {*} value */ function removeSelectOption(fieldName, value) { var form = typeof ftabs != "undefined" && ftabs[getFieldName(fieldName)] != null ? document.forms[ftabs[getFieldName(fieldName)] + "_form"] : document.forms[0]; var fld = getFormElement(form, getFieldName(fieldName)); if (fld != null) { if (value != null) deleteOneSelectOption(fld, value); else deleteAllSelectOptions(fld, window); } } /** * Remove Options Ship and Bill */ function removeOptionsShipAndBill() { // Remove [New, Custom] options billaddresslist removeSelectOption("billaddresslist", "-1"); removeSelectOption("billaddresslist", "-2"); // Remove [New, Custom] options shipaddresslist removeSelectOption("shipaddresslist", "-1"); removeSelectOption("shipaddresslist", "-2"); // Hide Button document.getElementById('billaddresslist_popup_new').setAttribute('style', 'display:none !important'); document.getElementById('billaddresslist_popup_link').setAttribute('style', 'display:none !important'); document.getElementById('shipaddresslist_popup_new').setAttribute('style', 'display:none !important'); document.getElementById('shipaddresslist_popup_link').setAttribute('style', 'display:none !important'); } /** * Export Events */ var exports = {}; exports.pageInit = pageInit; exports.sublistChanged = sublistChanged; exports.validateLine = validateLine; exports.fieldChanged = fieldChanged; return exports; });
198
[{"tag": "EMAIL", "value": "trung@lexor.com", "start": 142, "end": 157}]
true
1
/** * Quote Form * custform_145_4283482_879 * * @NApiVersion 2.x * @NModuleScope Public * @NScriptType ClientScript * @author trungpv <anpch@example.com> */ define([], function() { /* === VARS === */ /* === EVENTS FUNCTIONS === */ /** * Page Init * @param {*} context */ function pageInit(context) { const currentRecord = context.currentRecord; try { buildTableTotalWeight(currentRecord); removeOptionsShipAndBill(); } catch (error) { console.log("pageInit Error: ", error); } return; } /** * Sublist Changed * @param {*} context */ function sublistChanged(context) { const currentRecord = context.currentRecord; const sublistId = context.sublistId; if (sublistId === "item") { try { buildTableTotalWeight(currentRecord); } catch (error) { console.log("pageInit Error: ", error); } } return; } /** * Validate Line * @param {*} context */ function validateLine(context) { try { const sublistId = context.sublistId; const currentRecord = context.currentRecord; if (sublistId === "item") { const quantity = currentRecord.getCurrentSublistValue({ sublistId: sublistId, fieldId: "quantity" }); const itemWeight = currentRecord.getCurrentSublistValue({ sublistId: sublistId, fieldId: "weightinlb" }); currentRecord.setCurrentSublistValue({ sublistId: sublistId, fieldId: "custcol_total_weight", value: quantity * itemWeight }); const location = currentRecord.getValue({ fieldId: "location" }); if (location) { currentRecord.setCurrentSublistValue({ sublistId: sublistId, fieldId: "location", value: location }); } } } catch (error) { console.log("validateLine Error: ", error); } return true; //Return true if the line is valid. } /** * Field Changed * @param {*} context */ function fieldChanged(context) { //shipaddresslist, billaddresslist const fieldId = context.fieldId; const sublistId = context.sublistId; if ( sublistId === null && (fieldId === "shipaddresslist" || fieldId === "billaddresslist") ) { removeOptionsShipAndBill(); } return; } /** HELPPER FUNCTIONS **/ /** * Build HTML Table Total Weight * @param {*} currentRecord */ function buildTableTotalWeight(currentRecord) { // Add Util Function Replace All String.prototype.replaceAll = function(search, replacement) { return this.split(search).join(replacement); }; const totalLine = currentRecord.getLineCount({ sublistId: "item" }); var tableTotalWeight = {}; var totalWeight = 0; document.querySelector("#tableTotalWeight tbody").innerHTML = ""; for (var index = 0; index < totalLine; index++) { const quantity = currentRecord.getSublistValue({ sublistId: "item", fieldId: "quantity", line: index }); const weightinlb = currentRecord.getSublistValue({ sublistId: "item", fieldId: "weightinlb", line: index }); const location = currentRecord.getSublistValue({ sublistId: "item", fieldId: "location_display", line: index }); if (location === "") { if (tableTotalWeight["None"] === undefined) { tableTotalWeight["None"] = 0; } tableTotalWeight["None"] = tableTotalWeight["None"] + quantity * weightinlb; } else { if (tableTotalWeight[location] === undefined) { tableTotalWeight[location] = 0; } tableTotalWeight[location] = tableTotalWeight[location] + quantity * weightinlb; } totalWeight += quantity * weightinlb; } // Set Total Weight currentRecord.setValue({ fieldId: "custbody_total_weight", value: totalWeight }); var htmlTableTotalWeight = ""; for (var key in tableTotalWeight) { var tplRow = document.getElementById("tplTableTotalWeight").innerHTML; htmlTableTotalWeight += tplRow .replaceAll("____LOCATIN___", key) .replaceAll("____TOTAL_WEIGHT___", tableTotalWeight[key]); } document.querySelector( "#tableTotalWeight tbody" ).innerHTML = htmlTableTotalWeight; } /** * remove Select Option * @param {*} fieldName * @param {*} value */ function removeSelectOption(fieldName, value) { var form = typeof ftabs != "undefined" && ftabs[getFieldName(fieldName)] != null ? document.forms[ftabs[getFieldName(fieldName)] + "_form"] : document.forms[0]; var fld = getFormElement(form, getFieldName(fieldName)); if (fld != null) { if (value != null) deleteOneSelectOption(fld, value); else deleteAllSelectOptions(fld, window); } } /** * Remove Options Ship and Bill */ function removeOptionsShipAndBill() { // Remove [New, Custom] options billaddresslist removeSelectOption("billaddresslist", "-1"); removeSelectOption("billaddresslist", "-2"); // Remove [New, Custom] options shipaddresslist removeSelectOption("shipaddresslist", "-1"); removeSelectOption("shipaddresslist", "-2"); // Hide Button document.getElementById('billaddresslist_popup_new').setAttribute('style', 'display:none !important'); document.getElementById('billaddresslist_popup_link').setAttribute('style', 'display:none !important'); document.getElementById('shipaddresslist_popup_new').setAttribute('style', 'display:none !important'); document.getElementById('shipaddresslist_popup_link').setAttribute('style', 'display:none !important'); } /** * Export Events */ var exports = {}; exports.pageInit = pageInit; exports.sublistChanged = sublistChanged; exports.validateLine = validateLine; exports.fieldChanged = fieldChanged; return exports; });
true
/** * Quote Form * custform_145_4283482_879 * * @NApiVersion 2.x * @NModuleScope Public * @NScriptType ClientScript * @author trungpv <PI:EMAIL:anpch@example.comEND_PI> */ define([], function() { /* === VARS === */ /* === EVENTS FUNCTIONS === */ /** * Page Init * @param {*} context */ function pageInit(context) { const currentRecord = context.currentRecord; try { buildTableTotalWeight(currentRecord); removeOptionsShipAndBill(); } catch (error) { console.log("pageInit Error: ", error); } return; } /** * Sublist Changed * @param {*} context */ function sublistChanged(context) { const currentRecord = context.currentRecord; const sublistId = context.sublistId; if (sublistId === "item") { try { buildTableTotalWeight(currentRecord); } catch (error) { console.log("pageInit Error: ", error); } } return; } /** * Validate Line * @param {*} context */ function validateLine(context) { try { const sublistId = context.sublistId; const currentRecord = context.currentRecord; if (sublistId === "item") { const quantity = currentRecord.getCurrentSublistValue({ sublistId: sublistId, fieldId: "quantity" }); const itemWeight = currentRecord.getCurrentSublistValue({ sublistId: sublistId, fieldId: "weightinlb" }); currentRecord.setCurrentSublistValue({ sublistId: sublistId, fieldId: "custcol_total_weight", value: quantity * itemWeight }); const location = currentRecord.getValue({ fieldId: "location" }); if (location) { currentRecord.setCurrentSublistValue({ sublistId: sublistId, fieldId: "location", value: location }); } } } catch (error) { console.log("validateLine Error: ", error); } return true; //Return true if the line is valid. } /** * Field Changed * @param {*} context */ function fieldChanged(context) { //shipaddresslist, billaddresslist const fieldId = context.fieldId; const sublistId = context.sublistId; if ( sublistId === null && (fieldId === "shipaddresslist" || fieldId === "billaddresslist") ) { removeOptionsShipAndBill(); } return; } /** HELPPER FUNCTIONS **/ /** * Build HTML Table Total Weight * @param {*} currentRecord */ function buildTableTotalWeight(currentRecord) { // Add Util Function Replace All String.prototype.replaceAll = function(search, replacement) { return this.split(search).join(replacement); }; const totalLine = currentRecord.getLineCount({ sublistId: "item" }); var tableTotalWeight = {}; var totalWeight = 0; document.querySelector("#tableTotalWeight tbody").innerHTML = ""; for (var index = 0; index < totalLine; index++) { const quantity = currentRecord.getSublistValue({ sublistId: "item", fieldId: "quantity", line: index }); const weightinlb = currentRecord.getSublistValue({ sublistId: "item", fieldId: "weightinlb", line: index }); const location = currentRecord.getSublistValue({ sublistId: "item", fieldId: "location_display", line: index }); if (location === "") { if (tableTotalWeight["None"] === undefined) { tableTotalWeight["None"] = 0; } tableTotalWeight["None"] = tableTotalWeight["None"] + quantity * weightinlb; } else { if (tableTotalWeight[location] === undefined) { tableTotalWeight[location] = 0; } tableTotalWeight[location] = tableTotalWeight[location] + quantity * weightinlb; } totalWeight += quantity * weightinlb; } // Set Total Weight currentRecord.setValue({ fieldId: "custbody_total_weight", value: totalWeight }); var htmlTableTotalWeight = ""; for (var key in tableTotalWeight) { var tplRow = document.getElementById("tplTableTotalWeight").innerHTML; htmlTableTotalWeight += tplRow .replaceAll("____LOCATIN___", key) .replaceAll("____TOTAL_WEIGHT___", tableTotalWeight[key]); } document.querySelector( "#tableTotalWeight tbody" ).innerHTML = htmlTableTotalWeight; } /** * remove Select Option * @param {*} fieldName * @param {*} value */ function removeSelectOption(fieldName, value) { var form = typeof ftabs != "undefined" && ftabs[getFieldName(fieldName)] != null ? document.forms[ftabs[getFieldName(fieldName)] + "_form"] : document.forms[0]; var fld = getFormElement(form, getFieldName(fieldName)); if (fld != null) { if (value != null) deleteOneSelectOption(fld, value); else deleteAllSelectOptions(fld, window); } } /** * Remove Options Ship and Bill */ function removeOptionsShipAndBill() { // Remove [New, Custom] options billaddresslist removeSelectOption("billaddresslist", "-1"); removeSelectOption("billaddresslist", "-2"); // Remove [New, Custom] options shipaddresslist removeSelectOption("shipaddresslist", "-1"); removeSelectOption("shipaddresslist", "-2"); // Hide Button document.getElementById('billaddresslist_popup_new').setAttribute('style', 'display:none !important'); document.getElementById('billaddresslist_popup_link').setAttribute('style', 'display:none !important'); document.getElementById('shipaddresslist_popup_new').setAttribute('style', 'display:none !important'); document.getElementById('shipaddresslist_popup_link').setAttribute('style', 'display:none !important'); } /** * Export Events */ var exports = {}; exports.pageInit = pageInit; exports.sublistChanged = sublistChanged; exports.validateLine = validateLine; exports.fieldChanged = fieldChanged; return exports; });
/** * @NApiVersion 2.x * @NScriptType Suitelet */ define(['N/https', 'N/url'], function(https, urlMod) { return { onRequest : function(options) { var url = urlMod.resolveScript({ scriptId: 'customscript196', deploymentId: 'customdeploy1', returnExternalUrl: true, params: {parametername: 'value'} }); var headers = {'Authorization': 'NLAuth nlauth_account=12345, nlauth_email=john@smith.com, nlauth_signature=Welcome123, nlauth_role=3'}; var response = https.get({url: url, headers: headers}); options.response.write(response.body); } }; });
1,135
[{"tag": "EMAIL", "value": "nlauth_email=john@smith.com", "start": 468, "end": 495}]
true
1
/** * @NApiVersion 2.x * @NScriptType Suitelet */ define(['N/https', 'N/url'], function(https, urlMod) { return { onRequest : function(options) { var url = urlMod.resolveScript({ scriptId: 'customscript196', deploymentId: 'customdeploy1', returnExternalUrl: true, params: {parametername: 'value'} }); var headers = {'Authorization': 'NLAuth nlauth_account=12345, nnheo@example.com, nlauth_signature=Welcome123, nlauth_role=3'}; var response = https.get({url: url, headers: headers}); options.response.write(response.body); } }; });
true
/** * @NApiVersion 2.x * @NScriptType Suitelet */ define(['N/https', 'N/url'], function(https, urlMod) { return { onRequest : function(options) { var url = urlMod.resolveScript({ scriptId: 'customscript196', deploymentId: 'customdeploy1', returnExternalUrl: true, params: {parametername: 'value'} }); var headers = {'Authorization': 'NLAuth nlauth_account=12345, PI:EMAIL:nnheo@example.comEND_PI, nlauth_signature=Welcome123, nlauth_role=3'}; var response = https.get({url: url, headers: headers}); options.response.write(response.body); } }; });
/** *@NApiVersion 2.x *@NScriptType ScheduledScript */ define(['N/email', 'N/runtime', 'N/search', 'N/record'], function(email, runtime, search, record) { function execute(context) { log.audit({ title: 'InvocationType', details: context.InvocationType }); log.audit({ title: 'context.type', details: context.type }); // if (context.type !== context.InvocationType.ON_DEMAND) // return; var customerLast6WeeksSearch = search.load({ id: 'customsearch_customer_last_6_weeks' }); customerLast6WeeksSearch.run().each(function(result) { var customerInternalId = result.getValue({ name: 'internalid' }); var customerId = result.getValue({ name: 'entityid' }); var customerName = result.getValue({ name: 'companyname' }); var customerZee = result.getValue({ name: 'partner' }); var customerState = result.getValue({ name: 'internalid', join: 'partner' }); var commDate = result.getValue({ name: 'internalid', join: 'CUSTRECORD_CUSTOMER' }); var signUpDate = result.getValue({ name: 'internalid', join: 'CUSTRECORD_CUSTOMER' }); var salesRep = result.getValue({ name: 'custrecord_salesrep', join: 'CUSTRECORD_CUSTOMER' }); var customerLink = 'https://1048144.app.netsuite.com/app/site/hosting/scriptlet.nl?script=858&deploy=1&compid=1048144&unlayered=T&custparam_params={%22custid%22%3A' + customerInternalId + '%2C%22scriptid%22%3A%22customscript_sl_customer_list%22%2C%22deployid%22%3A%22customdeploy_sl_customer_list%22}&sorts[weekused]=-1'; var subject = 'MailPlus Service Call & Referral Program' var emailBody = 'Dear Account Manager,\n\nPlease review customers 6 weeks MPEX usage. Place a customer service call, offer referral program and obtain a review if possible.\n'; emailBody += '<b><u>LINK</u></b>: ' + customerLink; emailBody += '\n\n<b><u>Note</u></b>: If above link not clickable, please copy and paste in browser.' log.audit({ title: 'Subject', details: subject }); log.audit({ title: 'Email Body', details: emailBody }); log.audit({ title: 'Customer Internal ID', details: customerInternalId }); log.audit({ title: 'Sales Rep', details: salesRep }); email.send({ author: 112209, recipients: salesRep, subject: subject, body: emailBody, cc: ['luke.forbes@mailplus.com.au'], relatedRecords: { entityId: customerInternalId, } }); var customerRecord = record.load({ type: record.Type.CUSTOMER, id: customerInternalId }); customerRecord.setValue({ fieldId: 'custentity_referral_program', value: 1 }); customerRecord.save(); return true; }); } return { execute: execute }; });
618
[{"tag": "EMAIL", "value": "luke.forbes@mailplus.com.au", "start": 3352, "end": 3379}]
true
1
/** *@NApiVersion 2.x *@NScriptType ScheduledScript */ define(['N/email', 'N/runtime', 'N/search', 'N/record'], function(email, runtime, search, record) { function execute(context) { log.audit({ title: 'InvocationType', details: context.InvocationType }); log.audit({ title: 'context.type', details: context.type }); // if (context.type !== context.InvocationType.ON_DEMAND) // return; var customerLast6WeeksSearch = search.load({ id: 'customsearch_customer_last_6_weeks' }); customerLast6WeeksSearch.run().each(function(result) { var customerInternalId = result.getValue({ name: 'internalid' }); var customerId = result.getValue({ name: 'entityid' }); var customerName = result.getValue({ name: 'companyname' }); var customerZee = result.getValue({ name: 'partner' }); var customerState = result.getValue({ name: 'internalid', join: 'partner' }); var commDate = result.getValue({ name: 'internalid', join: 'CUSTRECORD_CUSTOMER' }); var signUpDate = result.getValue({ name: 'internalid', join: 'CUSTRECORD_CUSTOMER' }); var salesRep = result.getValue({ name: 'custrecord_salesrep', join: 'CUSTRECORD_CUSTOMER' }); var customerLink = 'https://1048144.app.netsuite.com/app/site/hosting/scriptlet.nl?script=858&deploy=1&compid=1048144&unlayered=T&custparam_params={%22custid%22%3A' + customerInternalId + '%2C%22scriptid%22%3A%22customscript_sl_customer_list%22%2C%22deployid%22%3A%22customdeploy_sl_customer_list%22}&sorts[weekused]=-1'; var subject = 'MailPlus Service Call & Referral Program' var emailBody = 'Dear Account Manager,\n\nPlease review customers 6 weeks MPEX usage. Place a customer service call, offer referral program and obtain a review if possible.\n'; emailBody += '<b><u>LINK</u></b>: ' + customerLink; emailBody += '\n\n<b><u>Note</u></b>: If above link not clickable, please copy and paste in browser.' log.audit({ title: 'Subject', details: subject }); log.audit({ title: 'Email Body', details: emailBody }); log.audit({ title: 'Customer Internal ID', details: customerInternalId }); log.audit({ title: 'Sales Rep', details: salesRep }); email.send({ author: 112209, recipients: salesRep, subject: subject, body: emailBody, cc: ['kenaa@example.com'], relatedRecords: { entityId: customerInternalId, } }); var customerRecord = record.load({ type: record.Type.CUSTOMER, id: customerInternalId }); customerRecord.setValue({ fieldId: 'custentity_referral_program', value: 1 }); customerRecord.save(); return true; }); } return { execute: execute }; });
true
/** *@NApiVersion 2.x *@NScriptType ScheduledScript */ define(['N/email', 'N/runtime', 'N/search', 'N/record'], function(email, runtime, search, record) { function execute(context) { log.audit({ title: 'InvocationType', details: context.InvocationType }); log.audit({ title: 'context.type', details: context.type }); // if (context.type !== context.InvocationType.ON_DEMAND) // return; var customerLast6WeeksSearch = search.load({ id: 'customsearch_customer_last_6_weeks' }); customerLast6WeeksSearch.run().each(function(result) { var customerInternalId = result.getValue({ name: 'internalid' }); var customerId = result.getValue({ name: 'entityid' }); var customerName = result.getValue({ name: 'companyname' }); var customerZee = result.getValue({ name: 'partner' }); var customerState = result.getValue({ name: 'internalid', join: 'partner' }); var commDate = result.getValue({ name: 'internalid', join: 'CUSTRECORD_CUSTOMER' }); var signUpDate = result.getValue({ name: 'internalid', join: 'CUSTRECORD_CUSTOMER' }); var salesRep = result.getValue({ name: 'custrecord_salesrep', join: 'CUSTRECORD_CUSTOMER' }); var customerLink = 'https://1048144.app.netsuite.com/app/site/hosting/scriptlet.nl?script=858&deploy=1&compid=1048144&unlayered=T&custparam_params={%22custid%22%3A' + customerInternalId + '%2C%22scriptid%22%3A%22customscript_sl_customer_list%22%2C%22deployid%22%3A%22customdeploy_sl_customer_list%22}&sorts[weekused]=-1'; var subject = 'MailPlus Service Call & Referral Program' var emailBody = 'Dear Account Manager,\n\nPlease review customers 6 weeks MPEX usage. Place a customer service call, offer referral program and obtain a review if possible.\n'; emailBody += '<b><u>LINK</u></b>: ' + customerLink; emailBody += '\n\n<b><u>Note</u></b>: If above link not clickable, please copy and paste in browser.' log.audit({ title: 'Subject', details: subject }); log.audit({ title: 'Email Body', details: emailBody }); log.audit({ title: 'Customer Internal ID', details: customerInternalId }); log.audit({ title: 'Sales Rep', details: salesRep }); email.send({ author: 112209, recipients: salesRep, subject: subject, body: emailBody, cc: ['PI:EMAIL:kenaa@example.comEND_PI'], relatedRecords: { entityId: customerInternalId, } }); var customerRecord = record.load({ type: record.Type.CUSTOMER, id: customerInternalId }); customerRecord.setValue({ fieldId: 'custentity_referral_program', value: 1 }); customerRecord.save(); return true; }); } return { execute: execute }; });
/** * @NApiVersion 2.1 */ require(['N/task', 'N/runtime', 'N/email'], (task, runtime, email) => { // Store the script ID of the script to submit // // Update the following statement so it uses the script ID // of the map/reduce script record you want to submit const mapReduceScriptId = 'customscript_test_mapreduce_script'; // Create a map/reduce task // // Update the deploymentId parameter to use the script ID of // the deployment record for your map/reduce script let mrTask = task.create({ taskType: task.TaskType.MAP_REDUCE, scriptId: mapReduceScriptId, deploymentId: 'customdeploy_test_mapreduce_script' }); // Submit the map/reduce task let mrTaskId = mrTask.submit(); // Check the status of the task, and send an email if the // task has a status of FAILED // // Update the authorId value with the internal ID of the user // who is the email sender. Update the recipientEmail value // with the email address of the recipient. let taskStatus = task.checkStatus(mrTaskId); if (taskStatus.status === 'FAILED') { const authorId = -5; const recipientEmail = 'notify@myCompany.com'; email.send({ author: authorId, recipients: recipientEmail, subject: 'Failure executing map/reduce job!', body: 'Map reduce task: ' + mapReduceScriptId + ' has failed.' }); } });
12
[{"tag": "EMAIL", "value": "notify@myCompany.com", "start": 1196, "end": 1216}]
true
1
/** * @NApiVersion 2.1 */ require(['N/task', 'N/runtime', 'N/email'], (task, runtime, email) => { // Store the script ID of the script to submit // // Update the following statement so it uses the script ID // of the map/reduce script record you want to submit const mapReduceScriptId = 'customscript_test_mapreduce_script'; // Create a map/reduce task // // Update the deploymentId parameter to use the script ID of // the deployment record for your map/reduce script let mrTask = task.create({ taskType: task.TaskType.MAP_REDUCE, scriptId: mapReduceScriptId, deploymentId: 'customdeploy_test_mapreduce_script' }); // Submit the map/reduce task let mrTaskId = mrTask.submit(); // Check the status of the task, and send an email if the // task has a status of FAILED // // Update the authorId value with the internal ID of the user // who is the email sender. Update the recipientEmail value // with the email address of the recipient. let taskStatus = task.checkStatus(mrTaskId); if (taskStatus.status === 'FAILED') { const authorId = -5; const recipientEmail = 'ychag@example.com'; email.send({ author: authorId, recipients: recipientEmail, subject: 'Failure executing map/reduce job!', body: 'Map reduce task: ' + mapReduceScriptId + ' has failed.' }); } });
true
/** * @NApiVersion 2.1 */ require(['N/task', 'N/runtime', 'N/email'], (task, runtime, email) => { // Store the script ID of the script to submit // // Update the following statement so it uses the script ID // of the map/reduce script record you want to submit const mapReduceScriptId = 'customscript_test_mapreduce_script'; // Create a map/reduce task // // Update the deploymentId parameter to use the script ID of // the deployment record for your map/reduce script let mrTask = task.create({ taskType: task.TaskType.MAP_REDUCE, scriptId: mapReduceScriptId, deploymentId: 'customdeploy_test_mapreduce_script' }); // Submit the map/reduce task let mrTaskId = mrTask.submit(); // Check the status of the task, and send an email if the // task has a status of FAILED // // Update the authorId value with the internal ID of the user // who is the email sender. Update the recipientEmail value // with the email address of the recipient. let taskStatus = task.checkStatus(mrTaskId); if (taskStatus.status === 'FAILED') { const authorId = -5; const recipientEmail = 'PI:EMAIL:ychag@example.comEND_PI'; email.send({ author: authorId, recipients: recipientEmail, subject: 'Failure executing map/reduce job!', body: 'Map reduce task: ' + mapReduceScriptId + ' has failed.' }); } });
/** * Quote Form * * @NApiVersion 2.x * @NScriptType UserEventScript * @author trungpv <trung@lexor.com> */ define([ 'N/runtime', './Module/discountSoldPriceTaxModule', './Module/marginBalance', './Module/oneQuoteForOneCustomer', 'N/ui/serverWidget', './Module/SalesFlow/Main' ], function( runtime, discountSoldPriceTaxModule, marginBalance, oneQuoteForOneCustomer, serverWidget, salesFlow ) { const SHIPPING_METHODS = { RL_CARRIERS: 'LTL', WILL_CALL: 'Will Call', LEXOR_TRUCK: 'Lexor Truck', ODFL: 'LTL', UPS_PACKAGE: 'UPS Package', RFQ: 'RFQ (Requesting a Freight Quote)', OCEAN_SERVICE: 'Ocean Service', INTERNATIONAL: 'International' }; function beforeLoad(context) { try { // https://trello.com/c/cYmEKul4/211-one-open-quote-for-1-customer oneQuoteForOneCustomer.beforeLoad(context, serverWidget); salesFlow.Q.beforeLoad(context); var form = context.form; var newRecord = context.newRecord; var item = form.getSublist({ id: 'item' }); var currentUser = runtime.getCurrentUser(); const role = currentUser.role; if (item) { var amountCol = item.getField({ id: 'amount' }); if (amountCol) { amountCol.updateDisplayType({ displayType: 'disabled' }); } // 1036 Lexor | Sales Representative // https://trello.com/c/2hFT7AlH/188-disable-tax-rate-for-sale-rep if (role === 1036) { var taxrate1Col = item.getField({ id: 'taxrate1' }); if (taxrate1Col) { taxrate1Col.updateDisplayType({ displayType: 'hidden' }); } var taxcodeCol = item.getField({ id: 'taxcode' }); if (taxcodeCol) { taxcodeCol.updateDisplayType({ displayType: 'disabled' }); } } // Set Default Location var locationCol = item.getField({ id: 'location' }); if (locationCol) { var location = newRecord.getValue({ fieldId: 'location' }); locationCol.defaultValue = location; } } shippingDiscountByTheManager(context); // View Mode if (context.type === context.UserEventType.VIEW) { try { var obj = getTotalWeightByLocation(newRecord); buildTableTotalWeight(newRecord, obj); } catch (err) { log.error({ title: 'Error buildTableTotalWeight', details: err }); } if (isSalesOrder(newRecord)) { var createsalesord = form.getButton('createsalesord'); createsalesord.isHidden = true; } } discountSoldPriceTaxModule.beforeLoad(context); } catch (error) { log.error({ title: 'Error beforeLoad', details: error }); } } function beforeSubmit(context) { // https://trello.com/c/cYmEKul4/211-one-open-quote-for-1-customer oneQuoteForOneCustomer.beforeSubmit(context); salesFlow.Q.beforeSubmit(context); var newRecord = context.newRecord; try { const totalLine = newRecord.getLineCount({ sublistId: 'item' }); for (var index = 0; index < totalLine; index++) { var quantity = newRecord.getSublistValue({ sublistId: 'item', fieldId: 'quantity', line: index }); var weightinlb = newRecord.getSublistValue({ sublistId: 'item', fieldId: 'custcol45', // weightinlb line: index }); // Update Total Weight Each Line newRecord.setSublistValue({ sublistId: 'item', fieldId: 'custcol_total_weight', line: index, value: quantity * weightinlb }); } } catch (error) { log.error({ title: 'Error updateTotalWeightByLocation', details: error }); } discountSoldPriceTaxModule.beforeSubmit(newRecord); marginBalance.beforeSubmit(newRecord); } /** * afterSubmit * @param {*} context */ function afterSubmit(context) { try { salesFlow.Q.afterSubmit(context); } catch (error) { log.error({ title: 'Error afterSubmit', details: error }); } } /** HEPPER FUNCTIONS **/ /** * Build Table Total Weight for View Mode * @param {*} newRecord * @param {*} obj */ function buildTableTotalWeight(newRecord, obj) { const tableTotalWeight = obj.tableTotalWeight; // Add Util Function Replace All String.prototype.replaceAll = function(search, replacement) { return this.split(search).join(replacement); }; var dataObj = getTableWeightDataJSON(newRecord); var htmlTableTotalWeight = '<span class="smallgraytextnolink uir-label"><span class="smallgraytextnolink">Shipping Rates</span></span><table id="tableTotalWeight" class="lx-table"><thead><tr><th>Location</th><th>Total Weight</th><th>Shipping Method</th><th>Freight Rate</th><th>Discount</th></tr></thead><tbody>'; var totalWeight = 0; var totalFreightRate = dataObj ? dataObj.reduce(function(a, b) { return ( (!isNaN(typeof a === 'number' ? a : a.FREIGHT_RATE) ? parseFloat(typeof a === 'number' ? a : a.FREIGHT_RATE) : 0) + (!isNaN(typeof b === 'number' ? b : b.FREIGHT_RATE) ? parseFloat(typeof b === 'number' ? b : b.FREIGHT_RATE) : 0) ); }, 0) : 0; var totalDiscount = dataObj ? dataObj.reduce(function(a, b) { return ( (!isNaN(typeof a === 'number' ? a : a.DISCOUNT) ? parseFloat(typeof a === 'number' ? a : a.DISCOUNT) : 0) + (!isNaN(typeof b === 'number' ? b : b.DISCOUNT) ? parseFloat(typeof b === 'number' ? b : b.DISCOUNT) : 0) ); }, 0) : 0; for (var key in tableTotalWeight) { var tplRow = '<tr><td>____LOCATIN___</td><td style="text-align: center;">____TOTAL_WEIGHT___</td><td>____SHIPPING_METHOD___</td><td style="text-align: center;">____FREIGHT_RATE___</td><td style="text-align: center;">____SHIPPING_DISCOUNT___</td></tr>'; tplRow = tplRow .replaceAll('____LOCATIN___', key) .replaceAll('____TOTAL_WEIGHT___', tableTotalWeight[key]); if (dataObj) { var locationId = obj.mapLocation[key]; var row = dataObj.reduce(function(a, b) { return (a.LOCATION == locationId && a) || (b.LOCATION == locationId && b); }); if (row) { tplRow = tplRow .replaceAll('____SHIPPING_METHOD___', SHIPPING_METHODS[row.SHIPPING_METHOD]) .replaceAll( '____FREIGHT_RATE___', isNaN(row.FREIGHT_RATE) ? 0 : parseFloat(row.FREIGHT_RATE).toFixed(2) ) .replaceAll( '____SHIPPING_DISCOUNT___', isNaN(row.DISCOUNT) ? 0 : parseFloat(row.DISCOUNT).toFixed(2) ); } else { tplRow = tplRow .replaceAll('____SHIPPING_METHOD___', '') .replaceAll('____FREIGHT_RATE___', '') .replaceAll('____SHIPPING_DISCOUNT___', ''); } } else { tplRow = tplRow .replaceAll('____SHIPPING_METHOD___', '') .replaceAll('____FREIGHT_RATE___', '') .replaceAll('____SHIPPING_DISCOUNT___', ''); } htmlTableTotalWeight += tplRow; totalWeight += parseFloat(tableTotalWeight[key]); } htmlTableTotalWeight += '</tbody><tfoot><tr><td>Total</td><td style="text-align: center;">' + totalWeight + '</td><td></td><td style="text-align: center;">' + totalFreightRate + '</td><td style="text-align: center;">' + totalDiscount + '</td></tr></tfoot></table>'; htmlTableTotalWeight += '<style>.lx-table{border:solid 1px #dee;border-collapse:collapse;border-spacing:0;font-size:12px}.lx-table thead th{background-color:#607799;border:solid 1px #dee;color:#fff;padding:10px;text-align:left}.lx-table tbody td{border:solid 1px #dee;color:#000;padding:10px}.lx-table tfoot td{border:solid 1px #dee;color:#000;padding:10px}</style>'; newRecord.setValue({ fieldId: 'custbody_table_total_weight', value: htmlTableTotalWeight }); } /** * Get data JSON * @param {*} newRecord */ function getTableWeightDataJSON(newRecord) { const dataJSON = newRecord.getValue({ fieldId: 'custbody_table_total_weight_data' }); var dataObj = false; try { dataObj = JSON.parse(dataJSON); } catch (error) {} return dataObj; } /** * Get Total Weight By Location * @param {*} record */ function getTotalWeightByLocation(record) { const totalLine = record.getLineCount({ sublistId: 'item' }); var tableTotalWeight = {}; var mapLocation = {}; for (var index = 0; index < totalLine; index++) { var quantity = record.getSublistValue({ sublistId: 'item', fieldId: 'quantity', line: index }); var weightinlb = record.getSublistValue({ sublistId: 'item', fieldId: 'custcol45', // weightinlb line: index }); var location = record.getSublistValue({ sublistId: 'item', fieldId: 'location_display', line: index }); var locationId = record.getSublistValue({ sublistId: 'item', fieldId: 'location', line: index }); if (location === undefined || location === '') { if (tableTotalWeight['None'] === undefined) { tableTotalWeight['None'] = 0; } tableTotalWeight['None'] = tableTotalWeight['None'] + quantity * weightinlb; mapLocation['None'] = 0; } else { if (tableTotalWeight[location] === undefined) { tableTotalWeight[location] = 0; } tableTotalWeight[location] = tableTotalWeight[location] + quantity * weightinlb; mapLocation[location] = locationId; } } return { tableTotalWeight: tableTotalWeight, mapLocation: mapLocation }; } /** * Active feature Shipping Discount By The Manager * @param {*} context */ function shippingDiscountByTheManager(context) { try { var form = context.form; var newRecord = context.newRecord; var currentUser = runtime.getCurrentUser(); const role = currentUser.role; // https://trello.com/c/RvSjr3Is/180-shipping-discount-for-customer-service-team // set shipping discount by manager is 100% for all role // var custbodyshipping_discount_by_manager = form.getField({ // id: 'custbodyshipping_discount_by_manager' // }); // if (custbodyshipping_discount_by_manager) { // // 3 Administrator // // 1069 Lexor | Sales Director // // 1037 Lexor | Sales Manager // if (role === 3 || role === 1069 || role === 1037) { // custbodyshipping_discount_by_manager.updateDisplayType({ // displayType: 'NORMAL' // }); // } else { // custbodyshipping_discount_by_manager.updateDisplayType({ // displayType: 'disabled' // }); // } // } } catch (error) { log.error({ title: 'Error shippingDiscountByTheManager', details: error }); } } /** * Check exists Sales Order * @param {*} newRecord */ function isSalesOrder(newRecord) { var result = false; try { const totalLinks = newRecord.getLineCount({ sublistId: 'links' }); for (var index = 0; index < totalLinks; index++) { var typeValue = newRecord.getSublistText({ sublistId: 'links', fieldId: 'linkurl', line: index }); if (typeValue === '/app/accounting/transactions/salesord.nl?whence=') { result = true; break; } } } catch (error) { log.error({ title: 'Error isSalesOrder', details: error }); } return result; } return { beforeLoad: beforeLoad, beforeSubmit: beforeSubmit, afterSubmit: afterSubmit }; });
935
[{"tag": "EMAIL", "value": "trung@lexor.com", "start": 93, "end": 108}]
true
1
/** * Quote Form * * @NApiVersion 2.x * @NScriptType UserEventScript * @author trungpv <efpyi@example.com> */ define([ 'N/runtime', './Module/discountSoldPriceTaxModule', './Module/marginBalance', './Module/oneQuoteForOneCustomer', 'N/ui/serverWidget', './Module/SalesFlow/Main' ], function( runtime, discountSoldPriceTaxModule, marginBalance, oneQuoteForOneCustomer, serverWidget, salesFlow ) { const SHIPPING_METHODS = { RL_CARRIERS: 'LTL', WILL_CALL: 'Will Call', LEXOR_TRUCK: 'Lexor Truck', ODFL: 'LTL', UPS_PACKAGE: 'UPS Package', RFQ: 'RFQ (Requesting a Freight Quote)', OCEAN_SERVICE: 'Ocean Service', INTERNATIONAL: 'International' }; function beforeLoad(context) { try { // https://trello.com/c/cYmEKul4/211-one-open-quote-for-1-customer oneQuoteForOneCustomer.beforeLoad(context, serverWidget); salesFlow.Q.beforeLoad(context); var form = context.form; var newRecord = context.newRecord; var item = form.getSublist({ id: 'item' }); var currentUser = runtime.getCurrentUser(); const role = currentUser.role; if (item) { var amountCol = item.getField({ id: 'amount' }); if (amountCol) { amountCol.updateDisplayType({ displayType: 'disabled' }); } // 1036 Lexor | Sales Representative // https://trello.com/c/2hFT7AlH/188-disable-tax-rate-for-sale-rep if (role === 1036) { var taxrate1Col = item.getField({ id: 'taxrate1' }); if (taxrate1Col) { taxrate1Col.updateDisplayType({ displayType: 'hidden' }); } var taxcodeCol = item.getField({ id: 'taxcode' }); if (taxcodeCol) { taxcodeCol.updateDisplayType({ displayType: 'disabled' }); } } // Set Default Location var locationCol = item.getField({ id: 'location' }); if (locationCol) { var location = newRecord.getValue({ fieldId: 'location' }); locationCol.defaultValue = location; } } shippingDiscountByTheManager(context); // View Mode if (context.type === context.UserEventType.VIEW) { try { var obj = getTotalWeightByLocation(newRecord); buildTableTotalWeight(newRecord, obj); } catch (err) { log.error({ title: 'Error buildTableTotalWeight', details: err }); } if (isSalesOrder(newRecord)) { var createsalesord = form.getButton('createsalesord'); createsalesord.isHidden = true; } } discountSoldPriceTaxModule.beforeLoad(context); } catch (error) { log.error({ title: 'Error beforeLoad', details: error }); } } function beforeSubmit(context) { // https://trello.com/c/cYmEKul4/211-one-open-quote-for-1-customer oneQuoteForOneCustomer.beforeSubmit(context); salesFlow.Q.beforeSubmit(context); var newRecord = context.newRecord; try { const totalLine = newRecord.getLineCount({ sublistId: 'item' }); for (var index = 0; index < totalLine; index++) { var quantity = newRecord.getSublistValue({ sublistId: 'item', fieldId: 'quantity', line: index }); var weightinlb = newRecord.getSublistValue({ sublistId: 'item', fieldId: 'custcol45', // weightinlb line: index }); // Update Total Weight Each Line newRecord.setSublistValue({ sublistId: 'item', fieldId: 'custcol_total_weight', line: index, value: quantity * weightinlb }); } } catch (error) { log.error({ title: 'Error updateTotalWeightByLocation', details: error }); } discountSoldPriceTaxModule.beforeSubmit(newRecord); marginBalance.beforeSubmit(newRecord); } /** * afterSubmit * @param {*} context */ function afterSubmit(context) { try { salesFlow.Q.afterSubmit(context); } catch (error) { log.error({ title: 'Error afterSubmit', details: error }); } } /** HEPPER FUNCTIONS **/ /** * Build Table Total Weight for View Mode * @param {*} newRecord * @param {*} obj */ function buildTableTotalWeight(newRecord, obj) { const tableTotalWeight = obj.tableTotalWeight; // Add Util Function Replace All String.prototype.replaceAll = function(search, replacement) { return this.split(search).join(replacement); }; var dataObj = getTableWeightDataJSON(newRecord); var htmlTableTotalWeight = '<span class="smallgraytextnolink uir-label"><span class="smallgraytextnolink">Shipping Rates</span></span><table id="tableTotalWeight" class="lx-table"><thead><tr><th>Location</th><th>Total Weight</th><th>Shipping Method</th><th>Freight Rate</th><th>Discount</th></tr></thead><tbody>'; var totalWeight = 0; var totalFreightRate = dataObj ? dataObj.reduce(function(a, b) { return ( (!isNaN(typeof a === 'number' ? a : a.FREIGHT_RATE) ? parseFloat(typeof a === 'number' ? a : a.FREIGHT_RATE) : 0) + (!isNaN(typeof b === 'number' ? b : b.FREIGHT_RATE) ? parseFloat(typeof b === 'number' ? b : b.FREIGHT_RATE) : 0) ); }, 0) : 0; var totalDiscount = dataObj ? dataObj.reduce(function(a, b) { return ( (!isNaN(typeof a === 'number' ? a : a.DISCOUNT) ? parseFloat(typeof a === 'number' ? a : a.DISCOUNT) : 0) + (!isNaN(typeof b === 'number' ? b : b.DISCOUNT) ? parseFloat(typeof b === 'number' ? b : b.DISCOUNT) : 0) ); }, 0) : 0; for (var key in tableTotalWeight) { var tplRow = '<tr><td>____LOCATIN___</td><td style="text-align: center;">____TOTAL_WEIGHT___</td><td>____SHIPPING_METHOD___</td><td style="text-align: center;">____FREIGHT_RATE___</td><td style="text-align: center;">____SHIPPING_DISCOUNT___</td></tr>'; tplRow = tplRow .replaceAll('____LOCATIN___', key) .replaceAll('____TOTAL_WEIGHT___', tableTotalWeight[key]); if (dataObj) { var locationId = obj.mapLocation[key]; var row = dataObj.reduce(function(a, b) { return (a.LOCATION == locationId && a) || (b.LOCATION == locationId && b); }); if (row) { tplRow = tplRow .replaceAll('____SHIPPING_METHOD___', SHIPPING_METHODS[row.SHIPPING_METHOD]) .replaceAll( '____FREIGHT_RATE___', isNaN(row.FREIGHT_RATE) ? 0 : parseFloat(row.FREIGHT_RATE).toFixed(2) ) .replaceAll( '____SHIPPING_DISCOUNT___', isNaN(row.DISCOUNT) ? 0 : parseFloat(row.DISCOUNT).toFixed(2) ); } else { tplRow = tplRow .replaceAll('____SHIPPING_METHOD___', '') .replaceAll('____FREIGHT_RATE___', '') .replaceAll('____SHIPPING_DISCOUNT___', ''); } } else { tplRow = tplRow .replaceAll('____SHIPPING_METHOD___', '') .replaceAll('____FREIGHT_RATE___', '') .replaceAll('____SHIPPING_DISCOUNT___', ''); } htmlTableTotalWeight += tplRow; totalWeight += parseFloat(tableTotalWeight[key]); } htmlTableTotalWeight += '</tbody><tfoot><tr><td>Total</td><td style="text-align: center;">' + totalWeight + '</td><td></td><td style="text-align: center;">' + totalFreightRate + '</td><td style="text-align: center;">' + totalDiscount + '</td></tr></tfoot></table>'; htmlTableTotalWeight += '<style>.lx-table{border:solid 1px #dee;border-collapse:collapse;border-spacing:0;font-size:12px}.lx-table thead th{background-color:#607799;border:solid 1px #dee;color:#fff;padding:10px;text-align:left}.lx-table tbody td{border:solid 1px #dee;color:#000;padding:10px}.lx-table tfoot td{border:solid 1px #dee;color:#000;padding:10px}</style>'; newRecord.setValue({ fieldId: 'custbody_table_total_weight', value: htmlTableTotalWeight }); } /** * Get data JSON * @param {*} newRecord */ function getTableWeightDataJSON(newRecord) { const dataJSON = newRecord.getValue({ fieldId: 'custbody_table_total_weight_data' }); var dataObj = false; try { dataObj = JSON.parse(dataJSON); } catch (error) {} return dataObj; } /** * Get Total Weight By Location * @param {*} record */ function getTotalWeightByLocation(record) { const totalLine = record.getLineCount({ sublistId: 'item' }); var tableTotalWeight = {}; var mapLocation = {}; for (var index = 0; index < totalLine; index++) { var quantity = record.getSublistValue({ sublistId: 'item', fieldId: 'quantity', line: index }); var weightinlb = record.getSublistValue({ sublistId: 'item', fieldId: 'custcol45', // weightinlb line: index }); var location = record.getSublistValue({ sublistId: 'item', fieldId: 'location_display', line: index }); var locationId = record.getSublistValue({ sublistId: 'item', fieldId: 'location', line: index }); if (location === undefined || location === '') { if (tableTotalWeight['None'] === undefined) { tableTotalWeight['None'] = 0; } tableTotalWeight['None'] = tableTotalWeight['None'] + quantity * weightinlb; mapLocation['None'] = 0; } else { if (tableTotalWeight[location] === undefined) { tableTotalWeight[location] = 0; } tableTotalWeight[location] = tableTotalWeight[location] + quantity * weightinlb; mapLocation[location] = locationId; } } return { tableTotalWeight: tableTotalWeight, mapLocation: mapLocation }; } /** * Active feature Shipping Discount By The Manager * @param {*} context */ function shippingDiscountByTheManager(context) { try { var form = context.form; var newRecord = context.newRecord; var currentUser = runtime.getCurrentUser(); const role = currentUser.role; // https://trello.com/c/RvSjr3Is/180-shipping-discount-for-customer-service-team // set shipping discount by manager is 100% for all role // var custbodyshipping_discount_by_manager = form.getField({ // id: 'custbodyshipping_discount_by_manager' // }); // if (custbodyshipping_discount_by_manager) { // // 3 Administrator // // 1069 Lexor | Sales Director // // 1037 Lexor | Sales Manager // if (role === 3 || role === 1069 || role === 1037) { // custbodyshipping_discount_by_manager.updateDisplayType({ // displayType: 'NORMAL' // }); // } else { // custbodyshipping_discount_by_manager.updateDisplayType({ // displayType: 'disabled' // }); // } // } } catch (error) { log.error({ title: 'Error shippingDiscountByTheManager', details: error }); } } /** * Check exists Sales Order * @param {*} newRecord */ function isSalesOrder(newRecord) { var result = false; try { const totalLinks = newRecord.getLineCount({ sublistId: 'links' }); for (var index = 0; index < totalLinks; index++) { var typeValue = newRecord.getSublistText({ sublistId: 'links', fieldId: 'linkurl', line: index }); if (typeValue === '/app/accounting/transactions/salesord.nl?whence=') { result = true; break; } } } catch (error) { log.error({ title: 'Error isSalesOrder', details: error }); } return result; } return { beforeLoad: beforeLoad, beforeSubmit: beforeSubmit, afterSubmit: afterSubmit }; });
true
/** * Quote Form * * @NApiVersion 2.x * @NScriptType UserEventScript * @author trungpv <PI:EMAIL:efpyi@example.comEND_PI> */ define([ 'N/runtime', './Module/discountSoldPriceTaxModule', './Module/marginBalance', './Module/oneQuoteForOneCustomer', 'N/ui/serverWidget', './Module/SalesFlow/Main' ], function( runtime, discountSoldPriceTaxModule, marginBalance, oneQuoteForOneCustomer, serverWidget, salesFlow ) { const SHIPPING_METHODS = { RL_CARRIERS: 'LTL', WILL_CALL: 'Will Call', LEXOR_TRUCK: 'Lexor Truck', ODFL: 'LTL', UPS_PACKAGE: 'UPS Package', RFQ: 'RFQ (Requesting a Freight Quote)', OCEAN_SERVICE: 'Ocean Service', INTERNATIONAL: 'International' }; function beforeLoad(context) { try { // https://trello.com/c/cYmEKul4/211-one-open-quote-for-1-customer oneQuoteForOneCustomer.beforeLoad(context, serverWidget); salesFlow.Q.beforeLoad(context); var form = context.form; var newRecord = context.newRecord; var item = form.getSublist({ id: 'item' }); var currentUser = runtime.getCurrentUser(); const role = currentUser.role; if (item) { var amountCol = item.getField({ id: 'amount' }); if (amountCol) { amountCol.updateDisplayType({ displayType: 'disabled' }); } // 1036 Lexor | Sales Representative // https://trello.com/c/2hFT7AlH/188-disable-tax-rate-for-sale-rep if (role === 1036) { var taxrate1Col = item.getField({ id: 'taxrate1' }); if (taxrate1Col) { taxrate1Col.updateDisplayType({ displayType: 'hidden' }); } var taxcodeCol = item.getField({ id: 'taxcode' }); if (taxcodeCol) { taxcodeCol.updateDisplayType({ displayType: 'disabled' }); } } // Set Default Location var locationCol = item.getField({ id: 'location' }); if (locationCol) { var location = newRecord.getValue({ fieldId: 'location' }); locationCol.defaultValue = location; } } shippingDiscountByTheManager(context); // View Mode if (context.type === context.UserEventType.VIEW) { try { var obj = getTotalWeightByLocation(newRecord); buildTableTotalWeight(newRecord, obj); } catch (err) { log.error({ title: 'Error buildTableTotalWeight', details: err }); } if (isSalesOrder(newRecord)) { var createsalesord = form.getButton('createsalesord'); createsalesord.isHidden = true; } } discountSoldPriceTaxModule.beforeLoad(context); } catch (error) { log.error({ title: 'Error beforeLoad', details: error }); } } function beforeSubmit(context) { // https://trello.com/c/cYmEKul4/211-one-open-quote-for-1-customer oneQuoteForOneCustomer.beforeSubmit(context); salesFlow.Q.beforeSubmit(context); var newRecord = context.newRecord; try { const totalLine = newRecord.getLineCount({ sublistId: 'item' }); for (var index = 0; index < totalLine; index++) { var quantity = newRecord.getSublistValue({ sublistId: 'item', fieldId: 'quantity', line: index }); var weightinlb = newRecord.getSublistValue({ sublistId: 'item', fieldId: 'custcol45', // weightinlb line: index }); // Update Total Weight Each Line newRecord.setSublistValue({ sublistId: 'item', fieldId: 'custcol_total_weight', line: index, value: quantity * weightinlb }); } } catch (error) { log.error({ title: 'Error updateTotalWeightByLocation', details: error }); } discountSoldPriceTaxModule.beforeSubmit(newRecord); marginBalance.beforeSubmit(newRecord); } /** * afterSubmit * @param {*} context */ function afterSubmit(context) { try { salesFlow.Q.afterSubmit(context); } catch (error) { log.error({ title: 'Error afterSubmit', details: error }); } } /** HEPPER FUNCTIONS **/ /** * Build Table Total Weight for View Mode * @param {*} newRecord * @param {*} obj */ function buildTableTotalWeight(newRecord, obj) { const tableTotalWeight = obj.tableTotalWeight; // Add Util Function Replace All String.prototype.replaceAll = function(search, replacement) { return this.split(search).join(replacement); }; var dataObj = getTableWeightDataJSON(newRecord); var htmlTableTotalWeight = '<span class="smallgraytextnolink uir-label"><span class="smallgraytextnolink">Shipping Rates</span></span><table id="tableTotalWeight" class="lx-table"><thead><tr><th>Location</th><th>Total Weight</th><th>Shipping Method</th><th>Freight Rate</th><th>Discount</th></tr></thead><tbody>'; var totalWeight = 0; var totalFreightRate = dataObj ? dataObj.reduce(function(a, b) { return ( (!isNaN(typeof a === 'number' ? a : a.FREIGHT_RATE) ? parseFloat(typeof a === 'number' ? a : a.FREIGHT_RATE) : 0) + (!isNaN(typeof b === 'number' ? b : b.FREIGHT_RATE) ? parseFloat(typeof b === 'number' ? b : b.FREIGHT_RATE) : 0) ); }, 0) : 0; var totalDiscount = dataObj ? dataObj.reduce(function(a, b) { return ( (!isNaN(typeof a === 'number' ? a : a.DISCOUNT) ? parseFloat(typeof a === 'number' ? a : a.DISCOUNT) : 0) + (!isNaN(typeof b === 'number' ? b : b.DISCOUNT) ? parseFloat(typeof b === 'number' ? b : b.DISCOUNT) : 0) ); }, 0) : 0; for (var key in tableTotalWeight) { var tplRow = '<tr><td>____LOCATIN___</td><td style="text-align: center;">____TOTAL_WEIGHT___</td><td>____SHIPPING_METHOD___</td><td style="text-align: center;">____FREIGHT_RATE___</td><td style="text-align: center;">____SHIPPING_DISCOUNT___</td></tr>'; tplRow = tplRow .replaceAll('____LOCATIN___', key) .replaceAll('____TOTAL_WEIGHT___', tableTotalWeight[key]); if (dataObj) { var locationId = obj.mapLocation[key]; var row = dataObj.reduce(function(a, b) { return (a.LOCATION == locationId && a) || (b.LOCATION == locationId && b); }); if (row) { tplRow = tplRow .replaceAll('____SHIPPING_METHOD___', SHIPPING_METHODS[row.SHIPPING_METHOD]) .replaceAll( '____FREIGHT_RATE___', isNaN(row.FREIGHT_RATE) ? 0 : parseFloat(row.FREIGHT_RATE).toFixed(2) ) .replaceAll( '____SHIPPING_DISCOUNT___', isNaN(row.DISCOUNT) ? 0 : parseFloat(row.DISCOUNT).toFixed(2) ); } else { tplRow = tplRow .replaceAll('____SHIPPING_METHOD___', '') .replaceAll('____FREIGHT_RATE___', '') .replaceAll('____SHIPPING_DISCOUNT___', ''); } } else { tplRow = tplRow .replaceAll('____SHIPPING_METHOD___', '') .replaceAll('____FREIGHT_RATE___', '') .replaceAll('____SHIPPING_DISCOUNT___', ''); } htmlTableTotalWeight += tplRow; totalWeight += parseFloat(tableTotalWeight[key]); } htmlTableTotalWeight += '</tbody><tfoot><tr><td>Total</td><td style="text-align: center;">' + totalWeight + '</td><td></td><td style="text-align: center;">' + totalFreightRate + '</td><td style="text-align: center;">' + totalDiscount + '</td></tr></tfoot></table>'; htmlTableTotalWeight += '<style>.lx-table{border:solid 1px #dee;border-collapse:collapse;border-spacing:0;font-size:12px}.lx-table thead th{background-color:#607799;border:solid 1px #dee;color:#fff;padding:10px;text-align:left}.lx-table tbody td{border:solid 1px #dee;color:#000;padding:10px}.lx-table tfoot td{border:solid 1px #dee;color:#000;padding:10px}</style>'; newRecord.setValue({ fieldId: 'custbody_table_total_weight', value: htmlTableTotalWeight }); } /** * Get data JSON * @param {*} newRecord */ function getTableWeightDataJSON(newRecord) { const dataJSON = newRecord.getValue({ fieldId: 'custbody_table_total_weight_data' }); var dataObj = false; try { dataObj = JSON.parse(dataJSON); } catch (error) {} return dataObj; } /** * Get Total Weight By Location * @param {*} record */ function getTotalWeightByLocation(record) { const totalLine = record.getLineCount({ sublistId: 'item' }); var tableTotalWeight = {}; var mapLocation = {}; for (var index = 0; index < totalLine; index++) { var quantity = record.getSublistValue({ sublistId: 'item', fieldId: 'quantity', line: index }); var weightinlb = record.getSublistValue({ sublistId: 'item', fieldId: 'custcol45', // weightinlb line: index }); var location = record.getSublistValue({ sublistId: 'item', fieldId: 'location_display', line: index }); var locationId = record.getSublistValue({ sublistId: 'item', fieldId: 'location', line: index }); if (location === undefined || location === '') { if (tableTotalWeight['None'] === undefined) { tableTotalWeight['None'] = 0; } tableTotalWeight['None'] = tableTotalWeight['None'] + quantity * weightinlb; mapLocation['None'] = 0; } else { if (tableTotalWeight[location] === undefined) { tableTotalWeight[location] = 0; } tableTotalWeight[location] = tableTotalWeight[location] + quantity * weightinlb; mapLocation[location] = locationId; } } return { tableTotalWeight: tableTotalWeight, mapLocation: mapLocation }; } /** * Active feature Shipping Discount By The Manager * @param {*} context */ function shippingDiscountByTheManager(context) { try { var form = context.form; var newRecord = context.newRecord; var currentUser = runtime.getCurrentUser(); const role = currentUser.role; // https://trello.com/c/RvSjr3Is/180-shipping-discount-for-customer-service-team // set shipping discount by manager is 100% for all role // var custbodyshipping_discount_by_manager = form.getField({ // id: 'custbodyshipping_discount_by_manager' // }); // if (custbodyshipping_discount_by_manager) { // // 3 Administrator // // 1069 Lexor | Sales Director // // 1037 Lexor | Sales Manager // if (role === 3 || role === 1069 || role === 1037) { // custbodyshipping_discount_by_manager.updateDisplayType({ // displayType: 'NORMAL' // }); // } else { // custbodyshipping_discount_by_manager.updateDisplayType({ // displayType: 'disabled' // }); // } // } } catch (error) { log.error({ title: 'Error shippingDiscountByTheManager', details: error }); } } /** * Check exists Sales Order * @param {*} newRecord */ function isSalesOrder(newRecord) { var result = false; try { const totalLinks = newRecord.getLineCount({ sublistId: 'links' }); for (var index = 0; index < totalLinks; index++) { var typeValue = newRecord.getSublistText({ sublistId: 'links', fieldId: 'linkurl', line: index }); if (typeValue === '/app/accounting/transactions/salesord.nl?whence=') { result = true; break; } } } catch (error) { log.error({ title: 'Error isSalesOrder', details: error }); } return result; } return { beforeLoad: beforeLoad, beforeSubmit: beforeSubmit, afterSubmit: afterSubmit }; });
/** * @NApiVersion 2.1 * @NScriptType Suitelet * @NModuleScope Public */ /* ------------------------------------------------------------------------------------------ Script Information ------------------------------------------------------------------------------------------ Name: SQL Query Tool ID: _sql_query_tool Description A utility for running SuiteQL queries in a NetSuite instance. ------------------------------------------------------------------------------------------ MIT License ------------------------------------------------------------------------------------------ Copyright (c) 2021 Timothy Dietrich. Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. ------------------------------------------------------------------------------------------ Developer(s) ------------------------------------------------------------------------------------------ Tim Dietrich * timdietrich@me.com * https://timdietrich.me ------------------------------------------------------------------------------------------ History ------------------------------------------------------------------------------------------ 20210714 - Tim Dietrich * First public beta of v2021.2. 20210725 - Tim Dietrich * Second public beta of v2021.2. */ var datatablesEnabled = true, file, https, log, page, query, record, remoteLibraryEnabled = true, render, rowsReturnedDefault = 10, runtime, scriptURL, queryFolderID = null, toolLatestVersion, toolUpgradesEnabled = true, toolUpgradeMessage = '', url, version = '2021.2 Beta 2', workbooksEnabled = true; define( [ 'N/file', 'N/https', 'N/log', 'N/ui/message', 'N/query', 'N/record', 'N/render', 'N/runtime', 'N/ui/serverWidget', 'N/url' ], main ); function main( fileModule, httpsModule, logModule, messageModule, queryModule, recordModule, renderModule, runtimeModule, serverWidgetModule, urlModule ) { file = fileModule; https = httpsModule; log = logModule; message = messageModule; query= queryModule; record = recordModule; render = renderModule; runtime = runtimeModule; serverWidget = serverWidgetModule; url = urlModule; return { onRequest: function( context ) { scriptURL = url.resolveScript( { scriptId: runtime.getCurrentScript().id, deploymentId: runtime.getCurrentScript().deploymentId, returnExternalURL: false } ); if ( context.request.method == 'POST' ) { var requestPayload = JSON.parse( context.request.body ); context.response.setHeader( 'Content-Type', 'application/json' ); switch ( requestPayload['function'] ) { case 'documentSubmit': return documentSubmit( context, requestPayload ); break; case 'queryExecute': return queryExecute( context, requestPayload ); break; case 'sqlFileExists': return sqlFileExists( context, requestPayload ); break; case 'sqlFileLoad': return sqlFileLoad( context, requestPayload ); break; case 'sqlFileSave': return sqlFileSave( context, requestPayload ); break; case 'localLibraryFilesGet': return localLibraryFilesGet( context ); break; case 'workbookLoad': return workbookLoad( context, requestPayload ); break; case 'workbooksGet': return workbooksGet( context ); break; default: log.error( { title: 'Payload - Unsupported Function', details: requestPayload['function'] } ); } } else { if ( toolUpgradesEnabled === true ) { toolLatestVersion = toolLatestVersionGet(); } if ( context.request.parameters.hasOwnProperty( 'function' ) ) { if ( context.request.parameters['function'] == 'documentGenerate' ) { documentGenerate( context ); } if ( context.request.parameters['function'] == 'upgrade' ) { let upgradeSuccess = toolUpgrade( context ); if ( upgradeSuccess === true ) { context.response.write( `<meta http-equiv="refresh" content = "0; url = ${scriptURL}" />` ); } else { context.response.write( '<p>An error occurred during the upgrade process.</p><p>See the script execution log for details.</p><p><a href="javascript:history.go(-1);">Continue...</a></p>' ); } } } else { if ( toolUpgradesEnabled === true ) { if ( toolLatestVersion != null ) { if ( toolLatestVersion.version != version ) { toolUpgradeMessage = ` <p style="margin-top: 24px;"> <span style="padding: 9px; x-background-color: yellow; width: 30%; border: 1px solid #ccc;"> <a href="${toolLatestVersion.infoURL}" target="_info" style="color: #4d5f79;">Version ${toolLatestVersion.version}</a> is now available. <a href="${scriptURL}&function=upgrade" style="color: #4d5f79;">Click to install.</a> </span> </p> `; } } } var form = serverWidget.createForm( { title: 'SuiteQL Query Tool', hideNavBar: false } ); var htmlField = form.addField( { id: 'custpage_field_html', type: serverWidget.FieldType.INLINEHTML, label: 'HTML' } ); htmlField.defaultValue = htmlGenerate(); context.response.writePage( form ); } } } } } function documentGenerate( context ) { try { var sessionScope = runtime.getCurrentSession(); var docInfo = JSON.parse( sessionScope.get( { name: 'suiteQLDocumentInfo' } ) ); var moreRecords = true; var paginatedRowBegin = docInfo.rowBegin; var paginatedRowEnd = docInfo.rowEnd; var queryParams = new Array(); var records = new Array(); do { var paginatedSQL = 'SELECT * FROM ( SELECT ROWNUM AS ROWNUMBER, * FROM (' + docInfo.query + ' ) ) WHERE ( ROWNUMBER BETWEEN ' + paginatedRowBegin + ' AND ' + paginatedRowEnd + ')'; var queryResults = query.runSuiteQL( { query: paginatedSQL, params: queryParams } ).asMappedResults(); records = records.concat( queryResults ); if ( queryResults.length < 5000 ) { moreRecords = false; } paginatedRowBegin = paginatedRowBegin + 5000; } while ( moreRecords ); var recordsDataSource = { 'records': records }; var renderer = render.create(); renderer.addCustomDataSource( { alias: 'results', format: render.DataSource.OBJECT, data: recordsDataSource } ); renderer.templateContent = docInfo.template; if ( docInfo.docType == 'pdf' ) { let renderObj = renderer.renderAsPdf(); let pdfString = renderObj.getContents(); context.response.setHeader( 'Content-Type', 'application/pdf' ); context.response.write( pdfString ); } else { let htmlString = renderer.renderAsString(); context.response.setHeader( 'Content-Type', 'text/html' ); context.response.write( htmlString ); } } catch( e ) { log.error( { title: 'documentGenerate Error', details: e } ); context.response.write( 'Error: ' + e ); } } function documentSubmit( context, requestPayload ) { try { var responsePayload; var sessionScope = runtime.getCurrentSession(); sessionScope.set( { name: 'suiteQLDocumentInfo', value: JSON.stringify( requestPayload ) } ); responsePayload = { 'submitted': true } } catch( e ) { log.error( { title: 'queryExecute Error', details: e } ); responsePayload = { 'error': e } } context.response.write( JSON.stringify( responsePayload, null, 5 ) ); } function htmlDataTablesFormatOption() { if ( datatablesEnabled === true ) { return ` <div class="form-check-inline"> <label class="form-check-label" style="font-size: 10pt;"> <input type="radio" class="form-check-input" name="resultsFormat" value="datatable" onChange="responseGenerate();">DataTable </label> </div> ` } else { return `` } } function htmlGenerate() { return ` <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.5.2/css/bootstrap.min.css"> <script src="/ui/jquery/jquery-3.5.1.min.js"></script> <script src="https://maxcdn.bootstrapcdn.com/bootstrap/4.5.2/js/bootstrap.min.js"></script> ${jsFunctionDataTablesExternals()} <style type = "text/css"> input[type="text"], input[type="search"], textarea, button { outline: none; box-shadow:none !important; border: 1px solid #ccc !important; } p, pre { font-size: 10pt; } td, th { font-size: 10pt; border: 3px; } th { text-transform: lowercase; font-weight: bold; } </style> ${htmlLocalLoadModal()} ${htmlRemoteLoadModal()} ${htmlSaveModal()} ${htmlWorkbooksModal()} ${htmlQueryUI()} ${htmlTablesUI()} <script> var activeSQLFile = {}, queryResponsePayload, fileLoadResponsePayload; window.jQuery = window.$ = jQuery; $('#queryUI').show(); $('#templateHeaderRow').hide(); $('#templateFormRow').hide(); tableNamesGet(); ${jqueryKeydownHandler()} ${jqueryModalHandlers()} ${jsFunctionDefaultQuerySet()} ${jsFunctionDocumentGenerate()} ${jsFunctionFileInfoRefresh()} ${jsFunctionHideRowNumbersToggle()} ${jsFunctionLocalLibraryFilesGet()} ${jsFunctionLocalSQLFileLoad()} ${jsFunctionLocalSQLFileSave()} ${jsFunctionQueryFormRowToggle()} ${jsFunctionQuerySubmit()} ${jsFunctionQueryTextAreaResize()} ${jsFunctionRadioFieldValueGet()} ${jsFunctionRemoteLibraryIndexGet()} ${jsFunctionRemoteSQLFileLoad()} ${jsFunctionResponseDataCopy()} ${jsFunctionResponseGenerate()} ${jsFunctionResponseGenerateCSV()} ${jsFunctionResponseGenerateJSON()} ${jsFunctionResponseGenerateTable()} ${jsFunctionReturnAllToggle()} ${jsFunctionTableDetailsGet()} ${jsFunctionTableNamesGet()} ${jsFunctionTableQueryCopy()} ${jsFunctionTablesUIToggle()} ${jsFunctionWorkbookLoad()} ${jsFunctionWorkbooksListGet()} </script> ` } function htmlLocalLoadModal() { return ` <div class="modal fade" id="localLoadModal"> <div class="modal-dialog modal-lg"> <div class="modal-content"> <div class="modal-header"> <h4 class="modal-title">Local Query Library</h4> <button type="button" class="close" data-dismiss="modal">&times;</button> </div> <div class="modal-body" id="localSQLFilesList"> </div> </div> </div> </div> `; } function htmlQueryUI() { return ` <div class="collapse" id="queryUI" style="text-align: left;"> <table style="table-layout: fixed; width: 100%; border-spacing: 6px; border-collapse: separate;"> <tr> <td width="20%"> <h5 id="queryHeader" style="margin-bottom: 0px; color: #4d5f79; font-weight: 600;"><a href="#" onClick="javascript:defaultQuerySet();" title="Click to load a sample query." style="color: #4d5f79;">Query Editor</a></h5> </td> <td width="55%" style="text-align: right;"> <div id="buttonsDiv"> <button type="button" class="btn btn-sm btn-light" onClick="javascript:tablesUIToggle();">Tables Reference</button> ${jsFunctionWorkbooksButton()} ${jsFunctionRemoteLibraryButton()} ${jsFunctionLocalLibraryButtons()} <button type="button" class="btn btn-sm btn-success" onclick="querySubmit();" accesskey="r">Run Query</button> </div> </td> <td width="25%" style="text-align: right;"> <button id="btnQueryFormRowToggle" type="button" class="btn btn-sm btn-light" onclick="queryFormRowToggle();">Hide Query Editor</button> </td> </tr> <tr id="queryFormRow"> <td colspan="2" style="vertical-align: top;"> <textarea class="form-control small" id="query" style=" font-size: 10pt; background-color: #FFFFFF; x-font-family: 'Courier New', monospace; color: #000000; line-height: 1.3; padding: 12px; " rows="20" placeholder="Enter a SuiteQL query here. Click &quot;Query Editor&quot; (above) to load a sample query." autofocus ></textarea> <div id="fileInfo"></div> </td> <td style="vertical-align: top;"> <div style="margin-left: 6px; padding: 12px; border: 1px solid #ccc; border-radius: 5px; background-color: #FAFAFA;"> <div> <p style="font-size: 10pt; margin-bottom: 3px;">Return Rows:</p> <div class="form-inline" id="rowRangeDiv"> <input type="number" class="form-control-sm" name="rowBegin" id="rowBegin" style="max-width: 100px;" value="1" required> &nbsp;thru&nbsp; <input type="number" class="form-control-sm" name="rowEnd" id="rowEnd" style="max-width: 100px;" value="${rowsReturnedDefault}" required> </div> <div class="form-check" style="margin-top: 6px;"> <label class="form-check-label" style="font-size: 10pt;"> <input type="checkbox" class="form-check-input" id="returnAll" onChange="returnAllToggle();">Return all rows. </label> </div> </div> <div style="margin-top: 12px; border-top: 1px solid #eee; padding-top: 12px;"> <p style="font-size: 10pt; margin-bottom: 3px;">Format Results As:</p> <div class="form-check-inline"> <label class="form-check-label" style="font-size: 10pt;"> <input type="radio" class="form-check-input" name="resultsFormat" value="table" checked onChange="responseGenerate();">Table </label> </div> ${htmlDataTablesFormatOption()} <div class="form-check-inline"> <label class="form-check-label" style="font-size: 10pt;"> <input type="radio" class="form-check-input" name="resultsFormat" value="csv" onChange="responseGenerate();">CSV </label> </div> <div class="form-check-inline"> <label class="form-check-label" style="font-size: 10pt;"> <input type="radio" class="form-check-input" name="resultsFormat" value="json" onChange="responseGenerate();">JSON </label> </div> <div class="form-check-inline"> <label class="form-check-label" style="font-size: 10pt;"> <input type="radio" class="form-check-input" name="resultsFormat" value="pdf" onChange="responseGenerate();">PDF </label> </div> <div class="form-check-inline"> <label class="form-check-label" style="font-size: 10pt;"> <input type="radio" class="form-check-input" name="resultsFormat" value="html" onChange="responseGenerate();">HTML </label> </div> </div> <div style="margin-top: 12px; border-top: 1px solid #eee; padding-top: 12px;" id="nullFormatDiv"> <p style="font-size: 10pt; margin-bottom: 3px;">Display NULL Values As:</p> <div class="form-check-inline"> <label class="form-check-label" style="font-size: 10pt;"> <input type="radio" class="form-check-input" name="nullFormat" value="dimmed" checked onChange="responseGenerate();">Dimmed </label> </div> <div class="form-check-inline"> <label class="form-check-label" style="font-size: 10pt;"> <input type="radio" class="form-check-input" name="nullFormat" value="blank" onChange="responseGenerate();">Blank </label> </div> <div class="form-check-inline"> <label class="form-check-label" style="font-size: 10pt;"> <input type="radio" class="form-check-input" name="nullFormat" value="null" onChange="responseGenerate();">null </label> </div> </div> <div style="margin-top: 12px; border-top: 1px solid #eee; padding-top: 12px;" id="hideRowNumsDiv"> <div class="form-check" style="margin-top: 6px;"> <label class="form-check-label" style="font-size: 10pt;"> <input type="checkbox" class="form-check-input" id="hideRowNumbers" onChange="hideRowNumbersToggle();" checked>Hide Row Numbers. </label> </div> </div> </div> </td> </tr> <tr id="templateHeaderRow"> <td> <h5 style="margin-top: 12px; margin-bottom: 0px; color: #4d5f79; font-weight: 600;"><a href="#" onClick="javascript:defaultQuerySet();" title="Click to load a sample query." style="color: #4d5f79;">Template Editor</a></h5> </td> <td colspan="2" style="text-align: right; vertical-align: top;"> <div id="templateButtonsDiv"> <button type="button" class="btn btn-sm btn-light" onClick="window.open( 'https://bfo.com/products/report/docs/userguide.pdf' );">BFO Reference</button> <button type="button" class="btn btn-sm btn-light" onClick="window.open( 'https://freemarker.apache.org/docs/index.html' );">FreeMarker Reference</button> <button type="button" class="btn btn-sm btn-success" onclick="documentGenerate();" accesskey="g">Generate Document</button> </div> </td> </tr> <tr id="templateFormRow"> <td colspan="3" style="vertical-align: top;"> <textarea class="form-control small" id="template" style=" font-size: 10pt; background-color: #FFFFFF; x-font-family: 'Courier New', monospace; color: #000000; line-height: 1.3; padding: 12px; " rows="20" placeholder="Enter your template here." autofocus ></textarea> <div id="templateFileInfo"></div> </td> </tr> <tr> <td colspan="3"> <div id="resultsDiv" style="max-width: 100%; margin-top: 12px; display: none; overflow: auto; overflow-y: hidden;"> <!-- RESULTS --> </div> </td> </tr> <tr> <td colspan="3"> <div id="footerDiv" style="width: 100%; margin-top: 24px; margin-bottom: 24px; border-top: 1px solid #eee; padding-top: 24px; font-size: 10pt; color: #848484; display: inline-block; text-align: center;"> <p> SuiteQL Query Tool Version ${version}. Developed by <a href="https://timdietrich.me/" target="_tim" style="color: #4d5f79;">Tim Dietrich</a>. </p> ${toolUpgradeMessage} </div> </td> </tr> </table> </div> `; } function htmlRemoteLoadModal() { return ` <div class="modal fade" id="remoteLoadModal"> <div class="modal-dialog modal-lg"> <div class="modal-content"> <div class="modal-header"> <h4 class="modal-title">Remote Query Library</h4> <button type="button" class="close" data-dismiss="modal">&times;</button> </div> <div class="modal-body" id="remoteSQLFilesList"> </div> </div> </div> </div> `; } function htmlSaveModal() { return ` <div class="modal fade" id="saveModal"> <div class="modal-dialog modal-lg"> <div class="modal-content"> <div class="modal-header"> <h4 class="modal-title">Save Query</h4> <button type="button" class="close" data-dismiss="modal">&times;</button> </div> <div class="modal-body" id="saveQueryMessage" style="display: none;"> ERROR </div> <div class="modal-body" id="saveQueryForm" style="display: none;"> <form class="row" style="margin-bottom: 24px;"> <div class="col-12" style="margin-top: 12px;"> <p style="font-size: 10pt; margin-bottom: 3px;">File Name:</p> <input type="text" class="form-control" name="saveQueryFormFileName" id="saveQueryFormFileName" style="width: 200px; padding: 3px;" value=""> </div> <div class="col-12" style="margin-top: 12px;"> <p style="font-size: 10pt; margin-bottom: 3px;">Description:</p> <input type="text" class="form-control" name="saveQueryFormDescription" id="saveQueryFormDescription" style="width: 400px; padding: 3px;" value=""> </div> <div class="col-12" style="margin-top: 12px;"> <button type="button" class="btn btn-sm btn-success" onclick="javascript:localSQLFileSave();">Save The Query &gt;</button> </div> </form> </div> </div> </div> </div> `; } function htmlTablesUI() { return ` <div class="collapse" id="tablesUI"> <div class="container" style="max-width: 100%; margin-top: 24px;"> <form class="row g-3" method="POST" action="${scriptURL}"> <div class="col-md-4"> <h5 style="color: #4d5f79; font-weight: 600;">Tables Reference</h5> <p>Select a table to view its details.</p> </div> <div class="col-md-8" style="text-align: right;"> <button type="button" class="btn btn-sm btn-danger" onClick="javascript:tablesUIToggle();">Close Tables Reference</button> </div> <div class="col-md-4" style="margin-top: 3px;" id="tablesColumn">Loading Tables Index...</div> <div class="col-md-8" id="tableInfoColumn"> &nbsp; </div> </form> </div> </div> `; } function htmlWorkbooksModal() { return ` <div class="modal fade" id="workbooksModal"> <div class="modal-dialog modal-lg"> <div class="modal-content"> <div class="modal-header"> <h4 class="modal-title">Workbooks</h4> <button type="button" class="close" data-dismiss="modal">&times;</button> </div> <div class="modal-body" id="workbooksList"> </div> </div> </div> </div> `; } function jqueryKeydownHandler() { return ` $('textarea').keydown( function(e) { if ( e.keyCode === 9 ) { var start = this.selectionStart; var end = this.selectionEnd; var $this = $(this); var value = $this.val(); $this.val(value.substring(0, start) + "\t" + value.substring(end)); this.selectionStart = this.selectionEnd = start + 1; e.preventDefault(); return; } if ( e.keyCode === 190 ) { var queryField = document.getElementById('query'); var pos = queryField.selectionStart; if ( pos > 1 ) { if ( queryField.value.charAt( pos - 1 ) == '.' ) { var tableStart = -2; for ( i = pos - 2; i > 0; i--) { var c = queryField.value.charAt(i); if ( ( c == '\\t' ) || ( c == ' ' ) || ( c == '\\n' ) || ( c == '\\r' ) ) { i = i + 1; break; } } var tableName = queryField.value.substring( i, pos - 1 ); // alert( tableName ); tablesUIToggle(); tableDetailsGet( tableName ); return false; } } return; } fileInfoRefresh(); } ); ` } function jqueryModalHandlers() { return ` $('#localLoadModal').on('shown.bs.modal', function (e) { localLibraryFilesGet(); } ); $('#remoteLoadModal').on('shown.bs.modal', function (e) { remoteLibraryIndexGet(); } ); $('#saveModal').on('shown.bs.modal', function (e) { document.getElementById('saveQueryMessage').style.display = "none"; document.getElementById('saveQueryForm').style.display = "none"; if ( document.getElementById('query').value == '' ) { document.getElementById('saveQueryMessage').innerHTML = '<p>Please enter a query.</p>'; document.getElementById('saveQueryMessage').style.display = "block"; return; } else { document.getElementById('saveQueryForm').style.display = "block"; if ( activeSQLFile.hasOwnProperty( 'fileName' ) ) { document.getElementById('saveQueryFormFileName').value = activeSQLFile.fileName; } if ( activeSQLFile.hasOwnProperty( 'description' ) ) { document.getElementById('saveQueryFormDescription').value = activeSQLFile.description; } document.getElementById('saveQueryFormFileName').focus(); } } ); $('#workbooksModal').on('shown.bs.modal', function (e) { workbooksListGet(); } ); ` } function jsFunctionDataTablesExternals() { if ( datatablesEnabled === true ) { return ` <link rel="stylesheet" type="text/css" href="https://cdn.datatables.net/1.10.25/css/jquery.dataTables.css"> <script type="text/javascript" charset="utf8" src="https://cdn.datatables.net/1.10.25/js/jquery.dataTables.js"></script> ` } else { return `` } } function jsFunctionDefaultQuerySet() { return ` function defaultQuerySet() { document.getElementById('query').value = \`SELECT\n\tID,\n\tLastName,\n\tFirstName,\n\tPhone,\n\tEmail\nFROM\n\tEmployee\nWHERE\n\tEmail LIKE '%@test.com'\nORDER BY\n\tLastName,\n\tFirstName\`; return false; } ` } function jsFunctionDocumentGenerate() { return ` function documentGenerate() { if ( document.getElementById('query').value == '' ) { alert( 'Please enter a query.' ); return; } if ( document.getElementById('returnAll').checked ) { rowBegin = 1; rowEnd = 999999; } else { rowBegin = parseInt( document.getElementById('rowBegin').value ); if ( Number.isInteger( rowBegin ) === false ) { alert( 'Enter an integer for the beginning row.' ); document.getElementById('rowBegin').focus(); return; } rowEnd = parseInt( document.getElementById('rowEnd').value ); if ( Number.isInteger( rowEnd ) === false ) { alert( 'Enter an integer for the ending row.' ); document.getElementById('rowEnd').focus(); return; } } if ( document.getElementById('template').value == '' ) { alert( 'Please enter a template.' ); return; } var requestPayload = { 'function': 'documentSubmit', 'query': document.getElementById('query').value, 'rowBegin': rowBegin, 'rowEnd': rowEnd, 'template': document.getElementById('template').value, 'docType': radioFieldValueGet( 'resultsFormat' ) } var xhr = new XMLHttpRequest(); xhr.open( 'POST', '${scriptURL}', true ); xhr.setRequestHeader( 'Accept', 'application/json' ); xhr.send( JSON.stringify( requestPayload ) ); xhr.onload = function() { if( xhr.status === 200 ) { try { queryResponsePayload = JSON.parse( xhr.response ); } catch( e ) { alert( 'Unable to parse the response.' ); return; } if ( queryResponsePayload['error'] == undefined ) { window.open( '${scriptURL}&function=documentGenerate' ); } else { alert( 'Error: ' + queryResponsePayload.error.message ); } } else { alert( 'Error: ' + xhr.status ); } } } ` } function jsFunctionFileInfoRefresh() { return ` function fileInfoRefresh() { var content = ''; var status = ''; if ( activeSQLFile.source == undefined ) { if ( document.getElementById('query').value != '' ) { content = '<span class="text-danger">unsaved</span>'; } } else { status = 'Unchanged'; if ( document.getElementById('query').value != activeSQLFile.sql ) { status = 'Changed / Unsaved'; } else { status = 'Unchanged'; } var tooltip = 'Source: ' + activeSQLFile.source + '\\n'; tooltip += 'Status: ' + status; content = '<span title="' + tooltip + '">' + activeSQLFile.fileName + '</span>'; if ( document.getElementById('query').value != activeSQLFile.sql ) { content = '<span class="text-danger">' + content + '</span>'; } } content = '<p style="margin-top: 3px;">' + content + '</p>'; document.getElementById('fileInfo').innerHTML = content; } ` } function jsFunctionHideRowNumbersToggle() { return ` function hideRowNumbersToggle() { responseGenerateTable(); } ` } function jsFunctionLocalLibraryButtons() { if ( queryFolderID !== null ) { return `<button type="button" class="btn btn-sm btn-light" data-toggle="modal" data-target="#localLoadModal">Local Library</button> <button type="button" class="btn btn-sm btn-light" data-toggle="modal" data-target="#saveModal">Save Query</i></button>` } else { return `` } } function jsFunctionLocalLibraryFilesGet() { return ` function localLibraryFilesGet() { document.getElementById('localSQLFilesList').innerHTML = '<h5 style="color: green;">Getting the list of SQL files...</h5>'; var requestPayload = { 'function': 'localLibraryFilesGet' } var xhr = new XMLHttpRequest(); xhr.open( 'POST', '${scriptURL}', true ); xhr.send( JSON.stringify( requestPayload ) ); xhr.onload = function() { var content = ''; if( xhr.status === 200 ) { payload = JSON.parse( xhr.response ); if ( payload.error == undefined ) { content = '<div class="table-responsive">'; content += '<table id="localFilesTable" class="table table-sm table-bordered table-hover table-responsive-sm">'; content += '<thead class="thead-light">'; content += '<tr>'; content += '<th>Name</th>'; content += '<th>Description</th>'; content += '<th></th>'; content += '</tr>'; content += '</thead>'; content += '<tbody>'; for ( r = 0; r < payload.records.length; r++ ) { var description = payload.records[r].description; if( description === null ) { description = ''; } content += '<tr>'; content += '<td style="vertical-align: middle;">' + payload.records[r].name + '</td>'; content += '<td style="vertical-align: middle;">' + description + '</td>'; content += '<td style="text-align: center;"><button type="button" class="btn btn-sm btn-primary" onclick="localSQLFileLoad(' + payload.records[r].id + ');">Load</button></td>'; content += '</tr>'; } content += '</tbody>'; content += '</table>'; content += '</div>'; document.getElementById('localSQLFilesList').innerHTML = content; if ( ${datatablesEnabled} ) { $('#localFilesTable').DataTable(); } } else { if ( payload.error == 'No SQL Files' ) { content += '<p class="text-danger">No query files were found in the local folder.</p>'; document.getElementById('localSQLFilesList').innerHTML = content; } else { content = '<h5 class="text-danger">Error</h5>'; content += '<pre>'; content += payload.error; content += '</pre>'; document.getElementById('localSQLFilesList').innerHTML = content; } } } else { var content = '<h5 class="text-danger">Error</h5>'; content += '<pre>'; content += 'XHR Error: Status ' + xhr.status; document.getElementById('localSQLFilesList').innerHTML = content; } } } ` } function jsFunctionLocalSQLFileLoad() { return ` function localSQLFileLoad( fileID ) { var requestPayload = { 'function': 'sqlFileLoad', 'fileID': fileID } var xhr = new XMLHttpRequest(); xhr.open( 'POST', '${scriptURL}', true ); xhr.send( JSON.stringify( requestPayload ) ); xhr.onload = function() { if( xhr.status === 200 ) { fileLoadResponsePayload = JSON.parse( xhr.response ); if ( fileLoadResponsePayload.error == undefined ) { document.getElementById('query').value = fileLoadResponsePayload.sql; queryTextAreaResize(); $('#localLoadModal').modal('toggle'); document.getElementById('resultsDiv').style.display = "none"; activeSQLFile.source = 'Local SQL Library'; activeSQLFile.fileName = fileLoadResponsePayload.file.name; activeSQLFile.description = fileLoadResponsePayload.file.description; activeSQLFile.fileID = fileLoadResponsePayload.file.id; activeSQLFile.sql = fileLoadResponsePayload.sql; fileInfoRefresh(); } else { alert( 'Error: ' + payload.error ); } } else { alert( 'Error: ' + xhr.status ); } } } ` } function jsFunctionLocalSQLFileSave() { return ` function localSQLFileSave() { var filename = document.getElementById('saveQueryFormFileName').value; if ( filename == '' ) { alert( 'Please enter a name for the file.' ); return; } var requestPayload = { 'function': 'sqlFileExists', 'filename': filename } var xhr = new XMLHttpRequest(); xhr.open( 'POST', '${scriptURL}', false ); xhr.send( JSON.stringify( requestPayload ) ); if( xhr.status === 200 ) { fileExistsResponsePayload = JSON.parse( xhr.response ); if ( fileExistsResponsePayload.exists == true ) { var confirmResponse = confirm( "A file named \\"" + filename + "\\" already exists. Do you want to replace it?"); if ( confirmResponse == false ) { return; } } } else { alert( 'Error: ' + xhr.status ); return; } var requestPayload = { 'function': 'sqlFileSave', 'filename': filename, 'contents': document.getElementById('query').value, 'description': document.getElementById('saveQueryFormDescription').value } var xhr = new XMLHttpRequest(); xhr.open( 'POST', '${scriptURL}', true ); xhr.send( JSON.stringify( requestPayload ) ); xhr.onload = function() { if( xhr.status === 200 ) { fileSaveResponsePayload = JSON.parse( xhr.response ); if ( fileSaveResponsePayload.error == undefined ) { activeSQLFile.source = 'Local SQL Library'; activeSQLFile.fileName = filename; activeSQLFile.description = document.getElementById('saveQueryFormDescription').value; activeSQLFile.fileID = fileSaveResponsePayload.fileID; activeSQLFile.sql = document.getElementById('query').value; fileInfoRefresh(); alert( 'The file has been saved.' ); } else { alert( 'Error: ' + payload.error ); } } else { alert( 'Error: ' + xhr.status ); } } $('#saveModal').modal('toggle'); return; } ` } function jsFunctionQueryFormRowToggle() { return ` function queryFormRowToggle() { if ( $('#queryFormRow').is(":visible") ) { $('#queryFormRow').hide(); $('#queryHeader').hide(); $('#buttonsDiv').hide(); $('#btnQueryFormRowToggle').html('Show Query Editor'); } else { $('#queryFormRow').show(); $('#queryHeader').show(); $('#buttonsDiv').show(); $('#btnQueryFormRowToggle').html('Hide Query Editor'); } } ` } function jsFunctionQuerySubmit() { return ` function querySubmit() { if ( document.getElementById('query').value == '' ) { alert( 'Please enter a query.' ); return; } if ( document.getElementById('returnAll').checked ) { rowBegin = 1; rowEnd = 999999; } else { rowBegin = parseInt( document.getElementById('rowBegin').value ); if ( Number.isInteger( rowBegin ) === false ) { alert( 'Enter an integer for the beginning row.' ); document.getElementById('rowBegin').focus(); return; } rowEnd = parseInt( document.getElementById('rowEnd').value ); if ( Number.isInteger( rowEnd ) === false ) { alert( 'Enter an integer for the ending row.' ); document.getElementById('rowEnd').focus(); return; } } document.getElementById('resultsDiv').style.display = "block"; document.getElementById('resultsDiv').innerHTML = '<h5 style="color: green;">Running query...</h5>'; var requestPayload = { 'function': 'queryExecute', 'query': document.getElementById('query').value, 'rowBegin': rowBegin, 'rowEnd': rowEnd } var xhr = new XMLHttpRequest(); xhr.open( 'POST', '${scriptURL}', true ); xhr.setRequestHeader( 'Accept', 'application/json' ); xhr.send( JSON.stringify( requestPayload ) ); xhr.onload = function() { if( xhr.status === 200 ) { try { queryResponsePayload = JSON.parse( xhr.response ); } catch( e ) { alert( 'Unable to parse the response.' ); return; } if ( queryResponsePayload['error'] == undefined ) { responseGenerate(); } else { var content = '<h5 class="text-danger">Error</h5>'; content += '<pre>'; content += queryResponsePayload.error.message; content += '</pre>'; document.getElementById('resultsDiv').innerHTML = content; } } else { var content = '<h5 class="text-danger">Error</h5>'; content += '<pre>'; content += 'XHR Error: Status ' + xhr.status; content += '</pre>'; document.getElementById('resultsDiv').innerHTML = content; } } } ` } function jsFunctionQueryTextAreaResize() { return ` function queryTextAreaResize() { var lines = document.getElementById('query').value.split(/\\r*\\n/); var lineCount = lines.length + 1; if ( lineCount < 12 ) { lineCount = 12; } document.getElementById('query').rows = lineCount + 1; } ` } function jsFunctionRadioFieldValueGet() { return ` function radioFieldValueGet( fieldName ) { var radios = document.getElementsByName( fieldName ); for (var i = 0, length = radios.length; i < length; i++) { if (radios[i].checked) { return( radios[i].value ); } } return ''; } ` } function jsFunctionRemoteLibraryButton() { if ( remoteLibraryEnabled === true ) { return `<button type="button" class="btn btn-sm btn-light" data-toggle="modal" data-target="#remoteLoadModal">Remote Library</button>` } else { return `` } } function jsFunctionRemoteLibraryIndexGet() { return ` function remoteLibraryIndexGet() { document.getElementById('remoteSQLFilesList').innerHTML = '<h5 style="color: green;">Loading SuiteQL Query Library...</h5>'; var xhr = new XMLHttpRequest(); xhr.open( 'GET', 'https://suiteql.s3.us-east-1.amazonaws.com/queries/index.json?nonce=' + new Date().getTime(), true ); xhr.send(); xhr.onload = function() { var content = ''; if( xhr.status === 200 ) { payload = JSON.parse( xhr.response ); content = '<div class="table-responsive">'; content += '<table class="table table-sm table-bordered table-hover table-responsive-sm" id="remoteFilesTable">'; content += '<thead class="thead-light">'; content += '<tr>'; content += '<th>Name</th>'; content += '<th>Description</th>'; content += '<th></th>'; content += '</tr>'; content += '</thead>'; content += '<tbody>'; for ( r = 0; r < payload.length; r++ ) { content += '<tr>'; content += '<td style="vertical-align: middle;" width="40%">' + payload[r].name + '</td>'; content += '<td style="vertical-align: middle;">' + payload[r].description + '</td>'; content += '<td style="text-align: center;"><button type="button" class="btn btn-sm btn-primary" onclick="remoteSQLFileLoad(\\'' + payload[r].fileName + '\\');">Load</button></td>'; content += '</tr>'; } content += '</tbody>'; content += '</table>'; content += '</div>'; document.getElementById('remoteSQLFilesList').innerHTML = content; if ( ${datatablesEnabled} ) { $('#remoteFilesTable').DataTable(); } } else { var content = '<h5 class="text-danger">Error</h5>'; content += '<pre>'; content += 'XHR Error: Status ' + xhr.status; document.getElementById('remoteSQLFilesList').innerHTML = content; } } } ` } function jsFunctionRemoteSQLFileLoad() { return ` function remoteSQLFileLoad( filename ) { var xhr = new XMLHttpRequest(); xhr.open( 'GET', 'https://suiteql.s3.us-east-1.amazonaws.com/queries/' + filename+ '?nonce=' + new Date().getTime(), true ); xhr.send(); xhr.onload = function() { var content = ''; if( xhr.status === 200 ) { document.getElementById('query').value = xhr.response; queryTextAreaResize(); $('#remoteLoadModal').modal('toggle'); document.getElementById('resultsDiv').style.display = "none"; activeSQLFile.source = 'Remote SQL Library'; activeSQLFile.fileName = filename; activeSQLFile.sql = xhr.response; fileInfoRefresh(); } else { alert( 'XHR Error: Status ' + xhr.status ); } } } ` } function jsFunctionResponseDataCopy() { return ` function responseDataCopy() { var copyText = document.getElementById("responseData"); copyText.select(); document.execCommand("copy"); return false; } ` } function jsFunctionResponseGenerate() { return ` function responseGenerate() { $('#templateHeaderRow').hide(); $('#templateFormRow').hide(); switch ( radioFieldValueGet( 'resultsFormat' ) ) { case 'csv': responseGenerateCSV(); break; case 'json': responseGenerateJSON(); break; case 'pdf': $('#templateHeaderRow').show(); $('#templateFormRow').show(); responseGenerateTable(); break; case 'html': $('#templateHeaderRow').show(); $('#templateFormRow').show(); responseGenerateTable(); break; default: responseGenerateTable(); } } ` } function jsFunctionResponseGenerateCSV() { return ` function responseGenerateCSV() { document.getElementById('nullFormatDiv').style.display = "none"; document.getElementById('hideRowNumsDiv').style.display = "none"; var columnNames = Object.keys( queryResponsePayload.records[0] ); var row = '"' + columnNames.join( '","' ) + '"'; var csv = row + "\\r\\n"; for ( r = 0; r < queryResponsePayload.records.length; r++ ) { var record = queryResponsePayload.records[r]; var values = []; for ( c = 0; c < columnNames.length; c++ ) { var column = columnNames[c]; var value = record[column]; if ( value != null ) { value = value.toString(); } else { value = ''; } values.push( '"' + value + '"' ); } var row = values.join( ',' ); csv += row + "\\r\\n"; } var content = '<h5 style="margin-bottom: 3px; color: #4d5f79; font-weight: 600;">Results</h5>'; content += 'Retrieved ' + queryResponsePayload.records.length + ' of ' + queryResponsePayload.totalRecordCount + ' rows in ' + queryResponsePayload.elapsedTime + 'ms.<br>'; content += '<p>'; content += ' <a href="#" onclick="javascript:responseDataCopy();">Click here</a> to copy the data.'; content += '</p>'; content += '<textarea class="form-control small" id="responseData" name="responseData" rows="25" placeholder="Enter your query here." autofocus style="font-size: 10pt;">' + csv + '</textarea>'; content += '</div>'; document.getElementById('resultsDiv').innerHTML = content; } ` } function jsFunctionResponseGenerateJSON() { return ` function responseGenerateJSON() { document.getElementById('nullFormatDiv').style.display = "none"; document.getElementById('hideRowNumsDiv').style.display = "none"; var content = '<h5 style="margin-bottom: 3px; color: #4d5f79; font-weight: 600;">Results</h5>'; content += 'Retrieved ' + queryResponsePayload.records.length + ' of ' + queryResponsePayload.totalRecordCount + ' rows in ' + queryResponsePayload.elapsedTime + 'ms.<br>'; content += '<p>'; content += ' <a href="#" onclick="javascript:responseDataCopy();">Click here</a> to copy the data.'; content += '</p>'; content += '<textarea class="form-control small" id="responseData" name="responseData" rows="25" placeholder="Enter your query here." autofocus style="font-size: 10pt;">' + JSON.stringify( queryResponsePayload.records, null, 5 ) + '</textarea>'; content += '</div>'; document.getElementById('resultsDiv').innerHTML = content; } ` } function jsFunctionResponseGenerateTable() { return ` function responseGenerateTable() { document.getElementById('nullFormatDiv').style.display = "block"; document.getElementById('hideRowNumsDiv').style.display = "block"; if ( queryResponsePayload.records.length > 0 ) { var columnNames = Object.keys( queryResponsePayload.records[0] ); var startColumn = 0; if ( document.getElementById('hideRowNumbers').checked ) { startColumn = 1; } var thead = '<thead class="thead-light">'; thead += '<tr>'; if ( document.getElementById('hideRowNumbers').checked === false ) { thead += '<th style="text-align: center;">&nbsp;#&nbsp;</th>'; } for ( i = 1; i < columnNames.length; i++ ) { thead += '<th>' + columnNames[i] + '</th>'; } thead += '</tr>'; thead += '</thead>'; var tbody = '<tbody>'; for ( r = 0; r < queryResponsePayload.records.length; r++ ) { tbody += '<tr>'; for ( i = startColumn; i < columnNames.length; i++ ) { var value = queryResponsePayload.records[r][ columnNames[i] ]; if ( value === null ) { var nullFormat = radioFieldValueGet( 'nullFormat' ); if ( nullFormat == 'dimmed' ) { value = '<span style="color: #ccc;">' + value + '</span>'; } else if ( nullFormat == 'blank' ) { value = ''; } else { value = 'null'; } } if ( i > 0 ) { tbody += '<td>' + value + '</td>'; } else { tbody += '<td style="text-align: center;">' + value + '</td>'; } } tbody += '</tr>'; } tbody += '</tbody>'; var content = '<h5 style="margin-bottom: 3px; color: #4d5f79; font-weight: 600;">Results</h5>'; content += 'Retrieved ' + queryResponsePayload.records.length + ' of ' + queryResponsePayload.totalRecordCount + ' rows in ' + queryResponsePayload.elapsedTime + 'ms.<br>'; content += '<div class="table-responsive">'; content += '<table class="table table-sm table-bordered table-hover table-responsive-sm" id="resultsTable">'; content += thead; content += tbody; content += '</table>'; content += '</div>'; document.getElementById('resultsDiv').innerHTML = content; if ( radioFieldValueGet( 'resultsFormat' ) == 'datatable' ) { $('#resultsTable').DataTable(); } } else { document.getElementById('resultsDiv').innerHTML = '<h5 class="text-warning">No Records Were Found</h5>'; } } ` } function jsFunctionReturnAllToggle() { return ` function returnAllToggle() { if ( document.getElementById('returnAll').checked ) { document.getElementById('rowRangeDiv').style.display = "none"; } else { document.getElementById('rowRangeDiv').style.display = "block"; } } ` } function jsFunctionTableDetailsGet() { return ` function tableDetailsGet( tableName ) { document.getElementById('tableInfoColumn').innerHTML = '<h5 style="color: green;">Loading information for ' + tableName + ' table...</h5>'; var url = '/app/recordscatalog/rcendpoint.nl?action=\getRecordTypeDetail&data=' + encodeURI( JSON.stringify( { scriptId: tableName, detailType: 'SS_ANAL' } ) ); var xhr = new XMLHttpRequest(); xhr.open( 'GET', url, true ); xhr.send(); xhr.onload = function() { if( xhr.status === 200 ) { let recordDetail = JSON.parse( xhr.response ).data; content = '<h5 style="color: #000;">' + recordDetail.label + ' Table ("' + tableName + '") Information</h5>'; content += '<h5 style="margin-top: 18px; margin-bottom: 6px; color: #4d5f79; font-weight: 600;">Columns</h5>'; content += '<div class="table-responsive">'; content += '<table class="table table-sm table-bordered table-hover table-responsive-sm" id="tableColumnsTable">'; content += '<thead class="thead-light">'; content += '<tr>'; content += '<th>Label</th>'; content += '<th>Name</th>'; content += '<th>Type</th>'; content += '</tr>'; content += '</thead>'; content += '<tbody>'; for ( i = 0; i < recordDetail.fields.length; i++ ) { var field = recordDetail.fields[i]; if ( field.isColumn ) {; content += '<tr>'; content += '<td>' + field.label + '</td>'; content += '<td>' + field.id + '</td>'; content += '<td>' + field.dataType + '</td>'; content += '</tr>'; }; } content += '</tbody>'; content += '</table>'; content += '</div>'; if ( recordDetail.joins.length > 0 ) { content += '<h5 style="margin-top: 18px; margin-bottom: 6px; color: #4d5f79; font-weight: 600;">Joins</h5>'; content += '<div class="table-responsive">'; content += '<table class="table table-sm table-bordered table-hover table-responsive-sm" id="tableJoinsTable">'; content += '<thead class="thead-light">'; content += '<tr>'; content += '<th>Label</th>'; content += '<th>Table Name</th>'; content += '<th>Cardinality</th>'; content += '<th>Join Pairs</th>'; content += '</tr>'; content += '</thead>'; content += '<tbody>'; for ( i = 0; i < recordDetail.joins.length; i++ ) { var join = recordDetail.joins[i]; content += '<tr>'; content += '<td>' + join.label + '</td>'; content += '<td><a href="#" onclick="javascript:tableDetailsGet( \\'' + join.sourceTargetType.id + '\\' );">' + join.sourceTargetType.id + '</a></td>'; content += '<td>' + join.cardinality + '</td>'; var joinInfo = ""; for ( j = 0; j < join.sourceTargetType.joinPairs.length; j++ ) { var joinPair = join.sourceTargetType.joinPairs[j]; joinInfo += joinPair.label + '<br>'; } content += '<td>' + joinInfo + '</td>'; content += '</tr>'; } content += '</tbody>'; content += '</table>'; content += '</div>'; } let textareaRows = recordDetail.fields.length + 5; content += '<h5 style="margin-top: 18px; margin-bottom: 6px; color: #4d5f79; font-weight: 600;">Sample Query</h5>'; content += '<span style="font-size: 11pt;"><a href="#" onclick="javascript:tableQueryCopy();">Click here</a> to copy the query.</span>'; content += '<textarea class="form-control small" id="tableQuery" name="sampleQuery" rows="' + textareaRows + '" style="font-size: 10pt;">'; content += 'SELECT\\n'; for ( i = 0; i < recordDetail.fields.length; i++ ) { var field = recordDetail.fields[i]; if ( field.isColumn ) { content += '\\t' + tableName + '.' + field.id; if ( ( i + 1 ) < recordDetail.fields.length ) { content += ','; } content += '\\n'; } } content += 'FROM\\n'; content += '\\t' + tableName + '\\n'; content += '</textarea>'; document.getElementById('tableInfoColumn').innerHTML = content; if ( ${datatablesEnabled} ) { $('#tableColumnsTable').DataTable(); $('#tableJoinsTable').DataTable(); } } else { alert( 'Error: ' + xhr.status ); } } } ` } function jsFunctionTableNamesGet() { return ` function tableNamesGet() { var url = '/app/recordscatalog/rcendpoint.nl?action=\getRecordTypes&data=' + encodeURI( JSON.stringify( { structureType: 'FLAT' } ) ); var xhr = new XMLHttpRequest(); xhr.open( 'GET', url, true ); xhr.send(); xhr.onload = function() { if( xhr.status === 200 ) { let recordTypes = JSON.parse( xhr.response ).data; content = '<div class="table-responsive">'; content += '<table class="table table-sm table-bordered table-hover table-responsive-sm" id="tableNamesTable">'; content += '<thead class="thead-light">'; content += '<tr>'; content += '<th>Table</th>'; content += '</tr>'; content += '</thead>'; content += '<tbody>'; for ( i = 0; i < recordTypes.length; i++ ) { content += '<tr>'; content += '<td>'; content += '<a href="#" onclick="javascript:tableDetailsGet( \\'' + recordTypes[i].id + '\\' );" style="font-weight: bold;">' + recordTypes[i].label + '</a><br>'; content += recordTypes[i].id; content += '</td>'; content += '</tr>'; } content += '</tbody>'; content += '</table>'; content += '</div>'; document.getElementById('tablesColumn').innerHTML = content; if ( ${datatablesEnabled} ) { $('#tableNamesTable').DataTable(); } } else { alert( 'Error: ' + xhr.status ); } } } ` } function jsFunctionTableQueryCopy() { return ` function tableQueryCopy() { var copyText = document.getElementById("tableQuery"); copyText.select(); document.execCommand("copy"); return false; } ` } function jsFunctionTablesUIToggle() { return ` function tablesUIToggle() { $('#queryUI').toggle(); $('#tablesUI').toggle(); } ` } function jsFunctionWorkbooksButton() { if ( workbooksEnabled === true ) { return `<button type="button" class="btn btn-sm btn-light" data-toggle="modal" data-target="#workbooksModal">Workbooks</button>` } else { return `` } } function jsFunctionWorkbookLoad() { return ` function workbookLoad( scriptID ) { var requestPayload = { 'function': 'workbookLoad', 'scriptID': scriptID } var xhr = new XMLHttpRequest(); xhr.open( 'POST', '${scriptURL}', true ); xhr.send( JSON.stringify( requestPayload ) ); xhr.onload = function() { if( xhr.status === 200 ) { workbookLoadResponsePayload = JSON.parse( xhr.response ); if ( workbookLoadResponsePayload.error == undefined ) { document.getElementById('query').value = workbookLoadResponsePayload.sql; queryTextAreaResize(); $('#workbooksModal').modal('toggle'); document.getElementById('resultsDiv').style.display = "none"; activeSQLFile.source = 'Workbook ' + scriptID; activeSQLFile.fileName = ''; activeSQLFile.description = ''; activeSQLFile.fileID = ''; activeSQLFile.sql = workbookLoadResponsePayload.sql; fileInfoRefresh(); } else { alert( 'Error: ' + payload.error ); } } else { alert( 'Error: ' + xhr.status ); } } } ` } function jsFunctionWorkbooksListGet() { return ` function workbooksListGet() { document.getElementById('workbooksList').innerHTML = '<h5 style="color: green;">Getting the list of Workbooks...</h5>'; var requestPayload = { 'function': 'workbooksGet' } var xhr = new XMLHttpRequest(); xhr.open( 'POST', '${scriptURL}', true ); xhr.send( JSON.stringify( requestPayload ) ); xhr.onload = function() { var content = ''; if( xhr.status === 200 ) { payload = JSON.parse( xhr.response ); if ( payload.error == undefined ) { content = '<div class="table-responsive">'; content += '<table id="workbooksTable" class="table table-sm table-bordered table-hover table-responsive-sm">'; content += '<thead class="thead-light">'; content += '<tr>'; content += '<th>Name</th>'; content += '<th>Description</th>'; content += '<th>Owner</th>'; content += '<th></th>'; content += '</tr>'; content += '</thead>'; content += '<tbody>'; for ( r = 0; r < payload.records.length; r++ ) { var description = payload.records[r].description; if( description === null ) { description = ''; } content += '<tr>'; content += '<td style="vertical-align: middle;">' + payload.records[r].name + '</td>'; content += '<td style="vertical-align: middle;">' + description + '</td>'; content += '<td style="vertical-align: middle;">' + payload.records[r].owner + '</td>'; content += '<td style="text-align: center; vertical-align: middle;"><button type="button" class="btn btn-sm btn-primary" onclick="workbookLoad(\\'' + payload.records[r].scriptid + '\\');" >Load</button></td>'; content += '</tr>'; } content += '</tbody>'; content += '</table>'; content += '</div>'; document.getElementById('workbooksList').innerHTML = content; if ( ${datatablesEnabled} ) { $('#workbooksTable').DataTable(); } } else { if ( payload.error == 'No Workbooks' ) { content += '<p class="text-danger">No workbooks were found.</p>'; document.getElementById('workbooksList').innerHTML = content; } else { content = '<h5 class="text-danger">Error</h5>'; content += '<pre>'; content += payload.error; content += '</pre>'; document.getElementById('workbooksList').innerHTML = content; } } } else { var content = '<h5 class="text-danger">Error</h5>'; content += '<pre>'; content += 'XHR Error: Status ' + xhr.status; document.getElementById('workbooksList').innerHTML = content; } } } ` } function localLibraryFilesGet( context ) { var responsePayload; var sql = ` SELECT ID, Name, Description FROM File WHERE ( Folder = ? ) ORDER BY Name `; var queryResults = query.runSuiteQL( { query: sql, params: [ queryFolderID ] } ); var records = queryResults.asMappedResults(); if ( records.length > 0 ) { responsePayload = { 'records': records }; } else { responsePayload = { 'error': 'No SQL Files' }; } context.response.write( JSON.stringify( responsePayload, null, 5 ) ); } function queryExecute( context, requestPayload ) { try { var responsePayload; var moreRecords = true; var records = new Array(); var totalRecordCount = 0; var queryParams = new Array(); var paginatedRowBegin = requestPayload.rowBegin; var paginatedRowEnd = requestPayload.rowEnd; let beginTime = new Date().getTime(); do { var paginatedSQL = 'SELECT * FROM ( SELECT ROWNUM AS ROWNUMBER, * FROM (' + requestPayload.query + ' ) ) WHERE ( ROWNUMBER BETWEEN ' + paginatedRowBegin + ' AND ' + paginatedRowEnd + ')'; var queryResults = query.runSuiteQL( { query: paginatedSQL, params: queryParams } ).asMappedResults(); records = records.concat( queryResults ); if ( queryResults.length < 5000 ) { moreRecords = false; } paginatedRowBegin = paginatedRowBegin + 5000; } while ( moreRecords ); let elapsedTime = ( new Date().getTime() - beginTime ) ; if ( records.length > 0 ) { var paginatedSQL = 'SELECT COUNT(*) AS TotalRecordCount FROM ( ' + requestPayload.query + ' )'; var queryResults = query.runSuiteQL( { query: paginatedSQL, params: queryParams } ).asMappedResults(); var totalRecordCount = queryResults[0].totalrecordcount; } responsePayload = { 'records': records, 'totalRecordCount': totalRecordCount, 'elapsedTime': elapsedTime } } catch( e ) { log.error( { title: 'queryExecute Error', details: e } ); responsePayload = { 'error': e } } context.response.write( JSON.stringify( responsePayload, null, 5 ) ); } function sqlFileExists( context, requestPayload ) { var responsePayload; var sql = ` SELECT ID FROM File WHERE ( Folder = ? ) AND ( Name = ? ) `; var queryResults = query.runSuiteQL( { query: sql, params: [ queryFolderID, requestPayload.filename ] } ); var records = queryResults.asMappedResults(); if ( records.length > 0 ) { responsePayload = { 'exists': true }; } else { responsePayload = { 'exists': false }; } context.response.write( JSON.stringify( responsePayload, null, 5 ) ); } function sqlFileLoad( context, requestPayload ) { var responsePayload; try { var fileObj = file.load( { id: requestPayload.fileID } ); responsePayload = {} responsePayload.file = fileObj; responsePayload.sql = fileObj.getContents(); } catch( e ) { log.error( { title: 'sqlFileLoad Error', details: e } ); responsePayload = { 'error': e } } context.response.write( JSON.stringify( responsePayload, null, 5 ) ); } function sqlFileSave( context, requestPayload ) { var responsePayload; try { var fileObj = file.create( { name: requestPayload.filename, contents: requestPayload.contents, description: requestPayload.description, fileType: file.Type.PLAINTEXT, folder: queryFolderID, isOnline: false } ); var fileID = fileObj.save(); responsePayload = {} responsePayload.fileID = fileID; } catch( e ) { log.error( { title: 'sqlFileSave Error', details: e } ); responsePayload = { 'error': e } } context.response.write( JSON.stringify( responsePayload, null, 5 ) ); } function toolLatestVersionGet() { try { let httpsResponse = https.get( { url: 'https://suiteql.s3.us-east-1.amazonaws.com/query-tool/index.json' } ); let index = JSON.parse( httpsResponse.body ); return index[0]; } catch (e) { log.error( { title: 'toolLatestVersionGet - https error', details: e } ); return null; } } function toolUpgrade( context ) { try { let sql = ` SELECT SuiteLet.ID, SuiteLet.ScriptFile, File.Folder FROM SuiteLet INNER JOIN File ON ( File.ID = SuiteLet.ScriptFile ) WHERE ( SuiteLet.ScriptID = ? ) `; let queryResults = query.runSuiteQL( { query: sql, params: [ runtime.getCurrentScript().id ] } ); let records = queryResults.asMappedResults(); let scriptRecord = records[0]; let httpsResponse = https.get( { url: 'https://suiteql.s3.us-east-1.amazonaws.com/query-tool/' + toolLatestVersion.fileName } ); var fileObj = file.create( { name: toolLatestVersion.fileName, contents: httpsResponse.body, description: 'SuiteQL Query Tool v' + toolLatestVersion.version, fileType: file.Type.JAVASCRIPT, folder: scriptRecord.folder, isOnline: false } ); var fileID = fileObj.save(); var id = record.submitFields( { type: record.Type.SUITELET, id: scriptRecord.id, values: { scriptfile: fileID } } ); return true; } catch (e) { log.error( { title: 'toolUpgrade - error', details: e } ); return false; } } function workbookLoad( context, requestPayload ) { var responsePayload; try { var loadedQuery = query.load( { id: requestPayload.scriptID } ); responsePayload = {} responsePayload.sql = loadedQuery.toSuiteQL().query; } catch( e ) { log.error( { title: 'workbookLoad Error', details: e } ); responsePayload = { 'error': e } } context.response.write( JSON.stringify( responsePayload, null, 5 ) ); } function workbooksGet( context ) { var responsePayload; var sql = ` SELECT ScriptID, Name, Description, BUILTIN.DF( Owner ) AS Owner FROM UsrSavedSearch ORDER BY Name `; var queryResults = query.runSuiteQL( { query: sql, params: [] } ); var records = queryResults.asMappedResults(); if ( records.length > 0 ) { responsePayload = { 'records': records }; } else { responsePayload = { 'error': 'No Workbooks' }; } context.response.write( JSON.stringify( responsePayload, null, 5 ) ); }
310
[{"tag": "EMAIL", "value": "timdietrich@me.com", "start": 1869, "end": 1887}, {"tag": "EMAIL", "value": "%@test.com", "start": 26287, "end": 26297}]
true
2
/** * @NApiVersion 2.1 * @NScriptType Suitelet * @NModuleScope Public */ /* ------------------------------------------------------------------------------------------ Script Information ------------------------------------------------------------------------------------------ Name: SQL Query Tool ID: _sql_query_tool Description A utility for running SuiteQL queries in a NetSuite instance. ------------------------------------------------------------------------------------------ MIT License ------------------------------------------------------------------------------------------ Copyright (c) 2021 Timothy Dietrich. Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. ------------------------------------------------------------------------------------------ Developer(s) ------------------------------------------------------------------------------------------ Tim Dietrich * nnheo@example.com * https://timdietrich.me ------------------------------------------------------------------------------------------ History ------------------------------------------------------------------------------------------ 20210714 - Tim Dietrich * First public beta of v2021.2. 20210725 - Tim Dietrich * Second public beta of v2021.2. */ var datatablesEnabled = true, file, https, log, page, query, record, remoteLibraryEnabled = true, render, rowsReturnedDefault = 10, runtime, scriptURL, queryFolderID = null, toolLatestVersion, toolUpgradesEnabled = true, toolUpgradeMessage = '', url, version = '2021.2 Beta 2', workbooksEnabled = true; define( [ 'N/file', 'N/https', 'N/log', 'N/ui/message', 'N/query', 'N/record', 'N/render', 'N/runtime', 'N/ui/serverWidget', 'N/url' ], main ); function main( fileModule, httpsModule, logModule, messageModule, queryModule, recordModule, renderModule, runtimeModule, serverWidgetModule, urlModule ) { file = fileModule; https = httpsModule; log = logModule; message = messageModule; query= queryModule; record = recordModule; render = renderModule; runtime = runtimeModule; serverWidget = serverWidgetModule; url = urlModule; return { onRequest: function( context ) { scriptURL = url.resolveScript( { scriptId: runtime.getCurrentScript().id, deploymentId: runtime.getCurrentScript().deploymentId, returnExternalURL: false } ); if ( context.request.method == 'POST' ) { var requestPayload = JSON.parse( context.request.body ); context.response.setHeader( 'Content-Type', 'application/json' ); switch ( requestPayload['function'] ) { case 'documentSubmit': return documentSubmit( context, requestPayload ); break; case 'queryExecute': return queryExecute( context, requestPayload ); break; case 'sqlFileExists': return sqlFileExists( context, requestPayload ); break; case 'sqlFileLoad': return sqlFileLoad( context, requestPayload ); break; case 'sqlFileSave': return sqlFileSave( context, requestPayload ); break; case 'localLibraryFilesGet': return localLibraryFilesGet( context ); break; case 'workbookLoad': return workbookLoad( context, requestPayload ); break; case 'workbooksGet': return workbooksGet( context ); break; default: log.error( { title: 'Payload - Unsupported Function', details: requestPayload['function'] } ); } } else { if ( toolUpgradesEnabled === true ) { toolLatestVersion = toolLatestVersionGet(); } if ( context.request.parameters.hasOwnProperty( 'function' ) ) { if ( context.request.parameters['function'] == 'documentGenerate' ) { documentGenerate( context ); } if ( context.request.parameters['function'] == 'upgrade' ) { let upgradeSuccess = toolUpgrade( context ); if ( upgradeSuccess === true ) { context.response.write( `<meta http-equiv="refresh" content = "0; url = ${scriptURL}" />` ); } else { context.response.write( '<p>An error occurred during the upgrade process.</p><p>See the script execution log for details.</p><p><a href="javascript:history.go(-1);">Continue...</a></p>' ); } } } else { if ( toolUpgradesEnabled === true ) { if ( toolLatestVersion != null ) { if ( toolLatestVersion.version != version ) { toolUpgradeMessage = ` <p style="margin-top: 24px;"> <span style="padding: 9px; x-background-color: yellow; width: 30%; border: 1px solid #ccc;"> <a href="${toolLatestVersion.infoURL}" target="_info" style="color: #4d5f79;">Version ${toolLatestVersion.version}</a> is now available. <a href="${scriptURL}&function=upgrade" style="color: #4d5f79;">Click to install.</a> </span> </p> `; } } } var form = serverWidget.createForm( { title: 'SuiteQL Query Tool', hideNavBar: false } ); var htmlField = form.addField( { id: 'custpage_field_html', type: serverWidget.FieldType.INLINEHTML, label: 'HTML' } ); htmlField.defaultValue = htmlGenerate(); context.response.writePage( form ); } } } } } function documentGenerate( context ) { try { var sessionScope = runtime.getCurrentSession(); var docInfo = JSON.parse( sessionScope.get( { name: 'suiteQLDocumentInfo' } ) ); var moreRecords = true; var paginatedRowBegin = docInfo.rowBegin; var paginatedRowEnd = docInfo.rowEnd; var queryParams = new Array(); var records = new Array(); do { var paginatedSQL = 'SELECT * FROM ( SELECT ROWNUM AS ROWNUMBER, * FROM (' + docInfo.query + ' ) ) WHERE ( ROWNUMBER BETWEEN ' + paginatedRowBegin + ' AND ' + paginatedRowEnd + ')'; var queryResults = query.runSuiteQL( { query: paginatedSQL, params: queryParams } ).asMappedResults(); records = records.concat( queryResults ); if ( queryResults.length < 5000 ) { moreRecords = false; } paginatedRowBegin = paginatedRowBegin + 5000; } while ( moreRecords ); var recordsDataSource = { 'records': records }; var renderer = render.create(); renderer.addCustomDataSource( { alias: 'results', format: render.DataSource.OBJECT, data: recordsDataSource } ); renderer.templateContent = docInfo.template; if ( docInfo.docType == 'pdf' ) { let renderObj = renderer.renderAsPdf(); let pdfString = renderObj.getContents(); context.response.setHeader( 'Content-Type', 'application/pdf' ); context.response.write( pdfString ); } else { let htmlString = renderer.renderAsString(); context.response.setHeader( 'Content-Type', 'text/html' ); context.response.write( htmlString ); } } catch( e ) { log.error( { title: 'documentGenerate Error', details: e } ); context.response.write( 'Error: ' + e ); } } function documentSubmit( context, requestPayload ) { try { var responsePayload; var sessionScope = runtime.getCurrentSession(); sessionScope.set( { name: 'suiteQLDocumentInfo', value: JSON.stringify( requestPayload ) } ); responsePayload = { 'submitted': true } } catch( e ) { log.error( { title: 'queryExecute Error', details: e } ); responsePayload = { 'error': e } } context.response.write( JSON.stringify( responsePayload, null, 5 ) ); } function htmlDataTablesFormatOption() { if ( datatablesEnabled === true ) { return ` <div class="form-check-inline"> <label class="form-check-label" style="font-size: 10pt;"> <input type="radio" class="form-check-input" name="resultsFormat" value="datatable" onChange="responseGenerate();">DataTable </label> </div> ` } else { return `` } } function htmlGenerate() { return ` <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.5.2/css/bootstrap.min.css"> <script src="/ui/jquery/jquery-3.5.1.min.js"></script> <script src="https://maxcdn.bootstrapcdn.com/bootstrap/4.5.2/js/bootstrap.min.js"></script> ${jsFunctionDataTablesExternals()} <style type = "text/css"> input[type="text"], input[type="search"], textarea, button { outline: none; box-shadow:none !important; border: 1px solid #ccc !important; } p, pre { font-size: 10pt; } td, th { font-size: 10pt; border: 3px; } th { text-transform: lowercase; font-weight: bold; } </style> ${htmlLocalLoadModal()} ${htmlRemoteLoadModal()} ${htmlSaveModal()} ${htmlWorkbooksModal()} ${htmlQueryUI()} ${htmlTablesUI()} <script> var activeSQLFile = {}, queryResponsePayload, fileLoadResponsePayload; window.jQuery = window.$ = jQuery; $('#queryUI').show(); $('#templateHeaderRow').hide(); $('#templateFormRow').hide(); tableNamesGet(); ${jqueryKeydownHandler()} ${jqueryModalHandlers()} ${jsFunctionDefaultQuerySet()} ${jsFunctionDocumentGenerate()} ${jsFunctionFileInfoRefresh()} ${jsFunctionHideRowNumbersToggle()} ${jsFunctionLocalLibraryFilesGet()} ${jsFunctionLocalSQLFileLoad()} ${jsFunctionLocalSQLFileSave()} ${jsFunctionQueryFormRowToggle()} ${jsFunctionQuerySubmit()} ${jsFunctionQueryTextAreaResize()} ${jsFunctionRadioFieldValueGet()} ${jsFunctionRemoteLibraryIndexGet()} ${jsFunctionRemoteSQLFileLoad()} ${jsFunctionResponseDataCopy()} ${jsFunctionResponseGenerate()} ${jsFunctionResponseGenerateCSV()} ${jsFunctionResponseGenerateJSON()} ${jsFunctionResponseGenerateTable()} ${jsFunctionReturnAllToggle()} ${jsFunctionTableDetailsGet()} ${jsFunctionTableNamesGet()} ${jsFunctionTableQueryCopy()} ${jsFunctionTablesUIToggle()} ${jsFunctionWorkbookLoad()} ${jsFunctionWorkbooksListGet()} </script> ` } function htmlLocalLoadModal() { return ` <div class="modal fade" id="localLoadModal"> <div class="modal-dialog modal-lg"> <div class="modal-content"> <div class="modal-header"> <h4 class="modal-title">Local Query Library</h4> <button type="button" class="close" data-dismiss="modal">&times;</button> </div> <div class="modal-body" id="localSQLFilesList"> </div> </div> </div> </div> `; } function htmlQueryUI() { return ` <div class="collapse" id="queryUI" style="text-align: left;"> <table style="table-layout: fixed; width: 100%; border-spacing: 6px; border-collapse: separate;"> <tr> <td width="20%"> <h5 id="queryHeader" style="margin-bottom: 0px; color: #4d5f79; font-weight: 600;"><a href="#" onClick="javascript:defaultQuerySet();" title="Click to load a sample query." style="color: #4d5f79;">Query Editor</a></h5> </td> <td width="55%" style="text-align: right;"> <div id="buttonsDiv"> <button type="button" class="btn btn-sm btn-light" onClick="javascript:tablesUIToggle();">Tables Reference</button> ${jsFunctionWorkbooksButton()} ${jsFunctionRemoteLibraryButton()} ${jsFunctionLocalLibraryButtons()} <button type="button" class="btn btn-sm btn-success" onclick="querySubmit();" accesskey="r">Run Query</button> </div> </td> <td width="25%" style="text-align: right;"> <button id="btnQueryFormRowToggle" type="button" class="btn btn-sm btn-light" onclick="queryFormRowToggle();">Hide Query Editor</button> </td> </tr> <tr id="queryFormRow"> <td colspan="2" style="vertical-align: top;"> <textarea class="form-control small" id="query" style=" font-size: 10pt; background-color: #FFFFFF; x-font-family: 'Courier New', monospace; color: #000000; line-height: 1.3; padding: 12px; " rows="20" placeholder="Enter a SuiteQL query here. Click &quot;Query Editor&quot; (above) to load a sample query." autofocus ></textarea> <div id="fileInfo"></div> </td> <td style="vertical-align: top;"> <div style="margin-left: 6px; padding: 12px; border: 1px solid #ccc; border-radius: 5px; background-color: #FAFAFA;"> <div> <p style="font-size: 10pt; margin-bottom: 3px;">Return Rows:</p> <div class="form-inline" id="rowRangeDiv"> <input type="number" class="form-control-sm" name="rowBegin" id="rowBegin" style="max-width: 100px;" value="1" required> &nbsp;thru&nbsp; <input type="number" class="form-control-sm" name="rowEnd" id="rowEnd" style="max-width: 100px;" value="${rowsReturnedDefault}" required> </div> <div class="form-check" style="margin-top: 6px;"> <label class="form-check-label" style="font-size: 10pt;"> <input type="checkbox" class="form-check-input" id="returnAll" onChange="returnAllToggle();">Return all rows. </label> </div> </div> <div style="margin-top: 12px; border-top: 1px solid #eee; padding-top: 12px;"> <p style="font-size: 10pt; margin-bottom: 3px;">Format Results As:</p> <div class="form-check-inline"> <label class="form-check-label" style="font-size: 10pt;"> <input type="radio" class="form-check-input" name="resultsFormat" value="table" checked onChange="responseGenerate();">Table </label> </div> ${htmlDataTablesFormatOption()} <div class="form-check-inline"> <label class="form-check-label" style="font-size: 10pt;"> <input type="radio" class="form-check-input" name="resultsFormat" value="csv" onChange="responseGenerate();">CSV </label> </div> <div class="form-check-inline"> <label class="form-check-label" style="font-size: 10pt;"> <input type="radio" class="form-check-input" name="resultsFormat" value="json" onChange="responseGenerate();">JSON </label> </div> <div class="form-check-inline"> <label class="form-check-label" style="font-size: 10pt;"> <input type="radio" class="form-check-input" name="resultsFormat" value="pdf" onChange="responseGenerate();">PDF </label> </div> <div class="form-check-inline"> <label class="form-check-label" style="font-size: 10pt;"> <input type="radio" class="form-check-input" name="resultsFormat" value="html" onChange="responseGenerate();">HTML </label> </div> </div> <div style="margin-top: 12px; border-top: 1px solid #eee; padding-top: 12px;" id="nullFormatDiv"> <p style="font-size: 10pt; margin-bottom: 3px;">Display NULL Values As:</p> <div class="form-check-inline"> <label class="form-check-label" style="font-size: 10pt;"> <input type="radio" class="form-check-input" name="nullFormat" value="dimmed" checked onChange="responseGenerate();">Dimmed </label> </div> <div class="form-check-inline"> <label class="form-check-label" style="font-size: 10pt;"> <input type="radio" class="form-check-input" name="nullFormat" value="blank" onChange="responseGenerate();">Blank </label> </div> <div class="form-check-inline"> <label class="form-check-label" style="font-size: 10pt;"> <input type="radio" class="form-check-input" name="nullFormat" value="null" onChange="responseGenerate();">null </label> </div> </div> <div style="margin-top: 12px; border-top: 1px solid #eee; padding-top: 12px;" id="hideRowNumsDiv"> <div class="form-check" style="margin-top: 6px;"> <label class="form-check-label" style="font-size: 10pt;"> <input type="checkbox" class="form-check-input" id="hideRowNumbers" onChange="hideRowNumbersToggle();" checked>Hide Row Numbers. </label> </div> </div> </div> </td> </tr> <tr id="templateHeaderRow"> <td> <h5 style="margin-top: 12px; margin-bottom: 0px; color: #4d5f79; font-weight: 600;"><a href="#" onClick="javascript:defaultQuerySet();" title="Click to load a sample query." style="color: #4d5f79;">Template Editor</a></h5> </td> <td colspan="2" style="text-align: right; vertical-align: top;"> <div id="templateButtonsDiv"> <button type="button" class="btn btn-sm btn-light" onClick="window.open( 'https://bfo.com/products/report/docs/userguide.pdf' );">BFO Reference</button> <button type="button" class="btn btn-sm btn-light" onClick="window.open( 'https://freemarker.apache.org/docs/index.html' );">FreeMarker Reference</button> <button type="button" class="btn btn-sm btn-success" onclick="documentGenerate();" accesskey="g">Generate Document</button> </div> </td> </tr> <tr id="templateFormRow"> <td colspan="3" style="vertical-align: top;"> <textarea class="form-control small" id="template" style=" font-size: 10pt; background-color: #FFFFFF; x-font-family: 'Courier New', monospace; color: #000000; line-height: 1.3; padding: 12px; " rows="20" placeholder="Enter your template here." autofocus ></textarea> <div id="templateFileInfo"></div> </td> </tr> <tr> <td colspan="3"> <div id="resultsDiv" style="max-width: 100%; margin-top: 12px; display: none; overflow: auto; overflow-y: hidden;"> <!-- RESULTS --> </div> </td> </tr> <tr> <td colspan="3"> <div id="footerDiv" style="width: 100%; margin-top: 24px; margin-bottom: 24px; border-top: 1px solid #eee; padding-top: 24px; font-size: 10pt; color: #848484; display: inline-block; text-align: center;"> <p> SuiteQL Query Tool Version ${version}. Developed by <a href="https://timdietrich.me/" target="_tim" style="color: #4d5f79;">Tim Dietrich</a>. </p> ${toolUpgradeMessage} </div> </td> </tr> </table> </div> `; } function htmlRemoteLoadModal() { return ` <div class="modal fade" id="remoteLoadModal"> <div class="modal-dialog modal-lg"> <div class="modal-content"> <div class="modal-header"> <h4 class="modal-title">Remote Query Library</h4> <button type="button" class="close" data-dismiss="modal">&times;</button> </div> <div class="modal-body" id="remoteSQLFilesList"> </div> </div> </div> </div> `; } function htmlSaveModal() { return ` <div class="modal fade" id="saveModal"> <div class="modal-dialog modal-lg"> <div class="modal-content"> <div class="modal-header"> <h4 class="modal-title">Save Query</h4> <button type="button" class="close" data-dismiss="modal">&times;</button> </div> <div class="modal-body" id="saveQueryMessage" style="display: none;"> ERROR </div> <div class="modal-body" id="saveQueryForm" style="display: none;"> <form class="row" style="margin-bottom: 24px;"> <div class="col-12" style="margin-top: 12px;"> <p style="font-size: 10pt; margin-bottom: 3px;">File Name:</p> <input type="text" class="form-control" name="saveQueryFormFileName" id="saveQueryFormFileName" style="width: 200px; padding: 3px;" value=""> </div> <div class="col-12" style="margin-top: 12px;"> <p style="font-size: 10pt; margin-bottom: 3px;">Description:</p> <input type="text" class="form-control" name="saveQueryFormDescription" id="saveQueryFormDescription" style="width: 400px; padding: 3px;" value=""> </div> <div class="col-12" style="margin-top: 12px;"> <button type="button" class="btn btn-sm btn-success" onclick="javascript:localSQLFileSave();">Save The Query &gt;</button> </div> </form> </div> </div> </div> </div> `; } function htmlTablesUI() { return ` <div class="collapse" id="tablesUI"> <div class="container" style="max-width: 100%; margin-top: 24px;"> <form class="row g-3" method="POST" action="${scriptURL}"> <div class="col-md-4"> <h5 style="color: #4d5f79; font-weight: 600;">Tables Reference</h5> <p>Select a table to view its details.</p> </div> <div class="col-md-8" style="text-align: right;"> <button type="button" class="btn btn-sm btn-danger" onClick="javascript:tablesUIToggle();">Close Tables Reference</button> </div> <div class="col-md-4" style="margin-top: 3px;" id="tablesColumn">Loading Tables Index...</div> <div class="col-md-8" id="tableInfoColumn"> &nbsp; </div> </form> </div> </div> `; } function htmlWorkbooksModal() { return ` <div class="modal fade" id="workbooksModal"> <div class="modal-dialog modal-lg"> <div class="modal-content"> <div class="modal-header"> <h4 class="modal-title">Workbooks</h4> <button type="button" class="close" data-dismiss="modal">&times;</button> </div> <div class="modal-body" id="workbooksList"> </div> </div> </div> </div> `; } function jqueryKeydownHandler() { return ` $('textarea').keydown( function(e) { if ( e.keyCode === 9 ) { var start = this.selectionStart; var end = this.selectionEnd; var $this = $(this); var value = $this.val(); $this.val(value.substring(0, start) + "\t" + value.substring(end)); this.selectionStart = this.selectionEnd = start + 1; e.preventDefault(); return; } if ( e.keyCode === 190 ) { var queryField = document.getElementById('query'); var pos = queryField.selectionStart; if ( pos > 1 ) { if ( queryField.value.charAt( pos - 1 ) == '.' ) { var tableStart = -2; for ( i = pos - 2; i > 0; i--) { var c = queryField.value.charAt(i); if ( ( c == '\\t' ) || ( c == ' ' ) || ( c == '\\n' ) || ( c == '\\r' ) ) { i = i + 1; break; } } var tableName = queryField.value.substring( i, pos - 1 ); // alert( tableName ); tablesUIToggle(); tableDetailsGet( tableName ); return false; } } return; } fileInfoRefresh(); } ); ` } function jqueryModalHandlers() { return ` $('#localLoadModal').on('shown.bs.modal', function (e) { localLibraryFilesGet(); } ); $('#remoteLoadModal').on('shown.bs.modal', function (e) { remoteLibraryIndexGet(); } ); $('#saveModal').on('shown.bs.modal', function (e) { document.getElementById('saveQueryMessage').style.display = "none"; document.getElementById('saveQueryForm').style.display = "none"; if ( document.getElementById('query').value == '' ) { document.getElementById('saveQueryMessage').innerHTML = '<p>Please enter a query.</p>'; document.getElementById('saveQueryMessage').style.display = "block"; return; } else { document.getElementById('saveQueryForm').style.display = "block"; if ( activeSQLFile.hasOwnProperty( 'fileName' ) ) { document.getElementById('saveQueryFormFileName').value = activeSQLFile.fileName; } if ( activeSQLFile.hasOwnProperty( 'description' ) ) { document.getElementById('saveQueryFormDescription').value = activeSQLFile.description; } document.getElementById('saveQueryFormFileName').focus(); } } ); $('#workbooksModal').on('shown.bs.modal', function (e) { workbooksListGet(); } ); ` } function jsFunctionDataTablesExternals() { if ( datatablesEnabled === true ) { return ` <link rel="stylesheet" type="text/css" href="https://cdn.datatables.net/1.10.25/css/jquery.dataTables.css"> <script type="text/javascript" charset="utf8" src="https://cdn.datatables.net/1.10.25/js/jquery.dataTables.js"></script> ` } else { return `` } } function jsFunctionDefaultQuerySet() { return ` function defaultQuerySet() { document.getElementById('query').value = \`SELECT\n\tID,\n\tLastName,\n\tFirstName,\n\tPhone,\n\tEmail\nFROM\n\tEmployee\nWHERE\n\tEmail LIKE 'efpyi@example.com'\nORDER BY\n\tLastName,\n\tFirstName\`; return false; } ` } function jsFunctionDocumentGenerate() { return ` function documentGenerate() { if ( document.getElementById('query').value == '' ) { alert( 'Please enter a query.' ); return; } if ( document.getElementById('returnAll').checked ) { rowBegin = 1; rowEnd = 999999; } else { rowBegin = parseInt( document.getElementById('rowBegin').value ); if ( Number.isInteger( rowBegin ) === false ) { alert( 'Enter an integer for the beginning row.' ); document.getElementById('rowBegin').focus(); return; } rowEnd = parseInt( document.getElementById('rowEnd').value ); if ( Number.isInteger( rowEnd ) === false ) { alert( 'Enter an integer for the ending row.' ); document.getElementById('rowEnd').focus(); return; } } if ( document.getElementById('template').value == '' ) { alert( 'Please enter a template.' ); return; } var requestPayload = { 'function': 'documentSubmit', 'query': document.getElementById('query').value, 'rowBegin': rowBegin, 'rowEnd': rowEnd, 'template': document.getElementById('template').value, 'docType': radioFieldValueGet( 'resultsFormat' ) } var xhr = new XMLHttpRequest(); xhr.open( 'POST', '${scriptURL}', true ); xhr.setRequestHeader( 'Accept', 'application/json' ); xhr.send( JSON.stringify( requestPayload ) ); xhr.onload = function() { if( xhr.status === 200 ) { try { queryResponsePayload = JSON.parse( xhr.response ); } catch( e ) { alert( 'Unable to parse the response.' ); return; } if ( queryResponsePayload['error'] == undefined ) { window.open( '${scriptURL}&function=documentGenerate' ); } else { alert( 'Error: ' + queryResponsePayload.error.message ); } } else { alert( 'Error: ' + xhr.status ); } } } ` } function jsFunctionFileInfoRefresh() { return ` function fileInfoRefresh() { var content = ''; var status = ''; if ( activeSQLFile.source == undefined ) { if ( document.getElementById('query').value != '' ) { content = '<span class="text-danger">unsaved</span>'; } } else { status = 'Unchanged'; if ( document.getElementById('query').value != activeSQLFile.sql ) { status = 'Changed / Unsaved'; } else { status = 'Unchanged'; } var tooltip = 'Source: ' + activeSQLFile.source + '\\n'; tooltip += 'Status: ' + status; content = '<span title="' + tooltip + '">' + activeSQLFile.fileName + '</span>'; if ( document.getElementById('query').value != activeSQLFile.sql ) { content = '<span class="text-danger">' + content + '</span>'; } } content = '<p style="margin-top: 3px;">' + content + '</p>'; document.getElementById('fileInfo').innerHTML = content; } ` } function jsFunctionHideRowNumbersToggle() { return ` function hideRowNumbersToggle() { responseGenerateTable(); } ` } function jsFunctionLocalLibraryButtons() { if ( queryFolderID !== null ) { return `<button type="button" class="btn btn-sm btn-light" data-toggle="modal" data-target="#localLoadModal">Local Library</button> <button type="button" class="btn btn-sm btn-light" data-toggle="modal" data-target="#saveModal">Save Query</i></button>` } else { return `` } } function jsFunctionLocalLibraryFilesGet() { return ` function localLibraryFilesGet() { document.getElementById('localSQLFilesList').innerHTML = '<h5 style="color: green;">Getting the list of SQL files...</h5>'; var requestPayload = { 'function': 'localLibraryFilesGet' } var xhr = new XMLHttpRequest(); xhr.open( 'POST', '${scriptURL}', true ); xhr.send( JSON.stringify( requestPayload ) ); xhr.onload = function() { var content = ''; if( xhr.status === 200 ) { payload = JSON.parse( xhr.response ); if ( payload.error == undefined ) { content = '<div class="table-responsive">'; content += '<table id="localFilesTable" class="table table-sm table-bordered table-hover table-responsive-sm">'; content += '<thead class="thead-light">'; content += '<tr>'; content += '<th>Name</th>'; content += '<th>Description</th>'; content += '<th></th>'; content += '</tr>'; content += '</thead>'; content += '<tbody>'; for ( r = 0; r < payload.records.length; r++ ) { var description = payload.records[r].description; if( description === null ) { description = ''; } content += '<tr>'; content += '<td style="vertical-align: middle;">' + payload.records[r].name + '</td>'; content += '<td style="vertical-align: middle;">' + description + '</td>'; content += '<td style="text-align: center;"><button type="button" class="btn btn-sm btn-primary" onclick="localSQLFileLoad(' + payload.records[r].id + ');">Load</button></td>'; content += '</tr>'; } content += '</tbody>'; content += '</table>'; content += '</div>'; document.getElementById('localSQLFilesList').innerHTML = content; if ( ${datatablesEnabled} ) { $('#localFilesTable').DataTable(); } } else { if ( payload.error == 'No SQL Files' ) { content += '<p class="text-danger">No query files were found in the local folder.</p>'; document.getElementById('localSQLFilesList').innerHTML = content; } else { content = '<h5 class="text-danger">Error</h5>'; content += '<pre>'; content += payload.error; content += '</pre>'; document.getElementById('localSQLFilesList').innerHTML = content; } } } else { var content = '<h5 class="text-danger">Error</h5>'; content += '<pre>'; content += 'XHR Error: Status ' + xhr.status; document.getElementById('localSQLFilesList').innerHTML = content; } } } ` } function jsFunctionLocalSQLFileLoad() { return ` function localSQLFileLoad( fileID ) { var requestPayload = { 'function': 'sqlFileLoad', 'fileID': fileID } var xhr = new XMLHttpRequest(); xhr.open( 'POST', '${scriptURL}', true ); xhr.send( JSON.stringify( requestPayload ) ); xhr.onload = function() { if( xhr.status === 200 ) { fileLoadResponsePayload = JSON.parse( xhr.response ); if ( fileLoadResponsePayload.error == undefined ) { document.getElementById('query').value = fileLoadResponsePayload.sql; queryTextAreaResize(); $('#localLoadModal').modal('toggle'); document.getElementById('resultsDiv').style.display = "none"; activeSQLFile.source = 'Local SQL Library'; activeSQLFile.fileName = fileLoadResponsePayload.file.name; activeSQLFile.description = fileLoadResponsePayload.file.description; activeSQLFile.fileID = fileLoadResponsePayload.file.id; activeSQLFile.sql = fileLoadResponsePayload.sql; fileInfoRefresh(); } else { alert( 'Error: ' + payload.error ); } } else { alert( 'Error: ' + xhr.status ); } } } ` } function jsFunctionLocalSQLFileSave() { return ` function localSQLFileSave() { var filename = document.getElementById('saveQueryFormFileName').value; if ( filename == '' ) { alert( 'Please enter a name for the file.' ); return; } var requestPayload = { 'function': 'sqlFileExists', 'filename': filename } var xhr = new XMLHttpRequest(); xhr.open( 'POST', '${scriptURL}', false ); xhr.send( JSON.stringify( requestPayload ) ); if( xhr.status === 200 ) { fileExistsResponsePayload = JSON.parse( xhr.response ); if ( fileExistsResponsePayload.exists == true ) { var confirmResponse = confirm( "A file named \\"" + filename + "\\" already exists. Do you want to replace it?"); if ( confirmResponse == false ) { return; } } } else { alert( 'Error: ' + xhr.status ); return; } var requestPayload = { 'function': 'sqlFileSave', 'filename': filename, 'contents': document.getElementById('query').value, 'description': document.getElementById('saveQueryFormDescription').value } var xhr = new XMLHttpRequest(); xhr.open( 'POST', '${scriptURL}', true ); xhr.send( JSON.stringify( requestPayload ) ); xhr.onload = function() { if( xhr.status === 200 ) { fileSaveResponsePayload = JSON.parse( xhr.response ); if ( fileSaveResponsePayload.error == undefined ) { activeSQLFile.source = 'Local SQL Library'; activeSQLFile.fileName = filename; activeSQLFile.description = document.getElementById('saveQueryFormDescription').value; activeSQLFile.fileID = fileSaveResponsePayload.fileID; activeSQLFile.sql = document.getElementById('query').value; fileInfoRefresh(); alert( 'The file has been saved.' ); } else { alert( 'Error: ' + payload.error ); } } else { alert( 'Error: ' + xhr.status ); } } $('#saveModal').modal('toggle'); return; } ` } function jsFunctionQueryFormRowToggle() { return ` function queryFormRowToggle() { if ( $('#queryFormRow').is(":visible") ) { $('#queryFormRow').hide(); $('#queryHeader').hide(); $('#buttonsDiv').hide(); $('#btnQueryFormRowToggle').html('Show Query Editor'); } else { $('#queryFormRow').show(); $('#queryHeader').show(); $('#buttonsDiv').show(); $('#btnQueryFormRowToggle').html('Hide Query Editor'); } } ` } function jsFunctionQuerySubmit() { return ` function querySubmit() { if ( document.getElementById('query').value == '' ) { alert( 'Please enter a query.' ); return; } if ( document.getElementById('returnAll').checked ) { rowBegin = 1; rowEnd = 999999; } else { rowBegin = parseInt( document.getElementById('rowBegin').value ); if ( Number.isInteger( rowBegin ) === false ) { alert( 'Enter an integer for the beginning row.' ); document.getElementById('rowBegin').focus(); return; } rowEnd = parseInt( document.getElementById('rowEnd').value ); if ( Number.isInteger( rowEnd ) === false ) { alert( 'Enter an integer for the ending row.' ); document.getElementById('rowEnd').focus(); return; } } document.getElementById('resultsDiv').style.display = "block"; document.getElementById('resultsDiv').innerHTML = '<h5 style="color: green;">Running query...</h5>'; var requestPayload = { 'function': 'queryExecute', 'query': document.getElementById('query').value, 'rowBegin': rowBegin, 'rowEnd': rowEnd } var xhr = new XMLHttpRequest(); xhr.open( 'POST', '${scriptURL}', true ); xhr.setRequestHeader( 'Accept', 'application/json' ); xhr.send( JSON.stringify( requestPayload ) ); xhr.onload = function() { if( xhr.status === 200 ) { try { queryResponsePayload = JSON.parse( xhr.response ); } catch( e ) { alert( 'Unable to parse the response.' ); return; } if ( queryResponsePayload['error'] == undefined ) { responseGenerate(); } else { var content = '<h5 class="text-danger">Error</h5>'; content += '<pre>'; content += queryResponsePayload.error.message; content += '</pre>'; document.getElementById('resultsDiv').innerHTML = content; } } else { var content = '<h5 class="text-danger">Error</h5>'; content += '<pre>'; content += 'XHR Error: Status ' + xhr.status; content += '</pre>'; document.getElementById('resultsDiv').innerHTML = content; } } } ` } function jsFunctionQueryTextAreaResize() { return ` function queryTextAreaResize() { var lines = document.getElementById('query').value.split(/\\r*\\n/); var lineCount = lines.length + 1; if ( lineCount < 12 ) { lineCount = 12; } document.getElementById('query').rows = lineCount + 1; } ` } function jsFunctionRadioFieldValueGet() { return ` function radioFieldValueGet( fieldName ) { var radios = document.getElementsByName( fieldName ); for (var i = 0, length = radios.length; i < length; i++) { if (radios[i].checked) { return( radios[i].value ); } } return ''; } ` } function jsFunctionRemoteLibraryButton() { if ( remoteLibraryEnabled === true ) { return `<button type="button" class="btn btn-sm btn-light" data-toggle="modal" data-target="#remoteLoadModal">Remote Library</button>` } else { return `` } } function jsFunctionRemoteLibraryIndexGet() { return ` function remoteLibraryIndexGet() { document.getElementById('remoteSQLFilesList').innerHTML = '<h5 style="color: green;">Loading SuiteQL Query Library...</h5>'; var xhr = new XMLHttpRequest(); xhr.open( 'GET', 'https://suiteql.s3.us-east-1.amazonaws.com/queries/index.json?nonce=' + new Date().getTime(), true ); xhr.send(); xhr.onload = function() { var content = ''; if( xhr.status === 200 ) { payload = JSON.parse( xhr.response ); content = '<div class="table-responsive">'; content += '<table class="table table-sm table-bordered table-hover table-responsive-sm" id="remoteFilesTable">'; content += '<thead class="thead-light">'; content += '<tr>'; content += '<th>Name</th>'; content += '<th>Description</th>'; content += '<th></th>'; content += '</tr>'; content += '</thead>'; content += '<tbody>'; for ( r = 0; r < payload.length; r++ ) { content += '<tr>'; content += '<td style="vertical-align: middle;" width="40%">' + payload[r].name + '</td>'; content += '<td style="vertical-align: middle;">' + payload[r].description + '</td>'; content += '<td style="text-align: center;"><button type="button" class="btn btn-sm btn-primary" onclick="remoteSQLFileLoad(\\'' + payload[r].fileName + '\\');">Load</button></td>'; content += '</tr>'; } content += '</tbody>'; content += '</table>'; content += '</div>'; document.getElementById('remoteSQLFilesList').innerHTML = content; if ( ${datatablesEnabled} ) { $('#remoteFilesTable').DataTable(); } } else { var content = '<h5 class="text-danger">Error</h5>'; content += '<pre>'; content += 'XHR Error: Status ' + xhr.status; document.getElementById('remoteSQLFilesList').innerHTML = content; } } } ` } function jsFunctionRemoteSQLFileLoad() { return ` function remoteSQLFileLoad( filename ) { var xhr = new XMLHttpRequest(); xhr.open( 'GET', 'https://suiteql.s3.us-east-1.amazonaws.com/queries/' + filename+ '?nonce=' + new Date().getTime(), true ); xhr.send(); xhr.onload = function() { var content = ''; if( xhr.status === 200 ) { document.getElementById('query').value = xhr.response; queryTextAreaResize(); $('#remoteLoadModal').modal('toggle'); document.getElementById('resultsDiv').style.display = "none"; activeSQLFile.source = 'Remote SQL Library'; activeSQLFile.fileName = filename; activeSQLFile.sql = xhr.response; fileInfoRefresh(); } else { alert( 'XHR Error: Status ' + xhr.status ); } } } ` } function jsFunctionResponseDataCopy() { return ` function responseDataCopy() { var copyText = document.getElementById("responseData"); copyText.select(); document.execCommand("copy"); return false; } ` } function jsFunctionResponseGenerate() { return ` function responseGenerate() { $('#templateHeaderRow').hide(); $('#templateFormRow').hide(); switch ( radioFieldValueGet( 'resultsFormat' ) ) { case 'csv': responseGenerateCSV(); break; case 'json': responseGenerateJSON(); break; case 'pdf': $('#templateHeaderRow').show(); $('#templateFormRow').show(); responseGenerateTable(); break; case 'html': $('#templateHeaderRow').show(); $('#templateFormRow').show(); responseGenerateTable(); break; default: responseGenerateTable(); } } ` } function jsFunctionResponseGenerateCSV() { return ` function responseGenerateCSV() { document.getElementById('nullFormatDiv').style.display = "none"; document.getElementById('hideRowNumsDiv').style.display = "none"; var columnNames = Object.keys( queryResponsePayload.records[0] ); var row = '"' + columnNames.join( '","' ) + '"'; var csv = row + "\\r\\n"; for ( r = 0; r < queryResponsePayload.records.length; r++ ) { var record = queryResponsePayload.records[r]; var values = []; for ( c = 0; c < columnNames.length; c++ ) { var column = columnNames[c]; var value = record[column]; if ( value != null ) { value = value.toString(); } else { value = ''; } values.push( '"' + value + '"' ); } var row = values.join( ',' ); csv += row + "\\r\\n"; } var content = '<h5 style="margin-bottom: 3px; color: #4d5f79; font-weight: 600;">Results</h5>'; content += 'Retrieved ' + queryResponsePayload.records.length + ' of ' + queryResponsePayload.totalRecordCount + ' rows in ' + queryResponsePayload.elapsedTime + 'ms.<br>'; content += '<p>'; content += ' <a href="#" onclick="javascript:responseDataCopy();">Click here</a> to copy the data.'; content += '</p>'; content += '<textarea class="form-control small" id="responseData" name="responseData" rows="25" placeholder="Enter your query here." autofocus style="font-size: 10pt;">' + csv + '</textarea>'; content += '</div>'; document.getElementById('resultsDiv').innerHTML = content; } ` } function jsFunctionResponseGenerateJSON() { return ` function responseGenerateJSON() { document.getElementById('nullFormatDiv').style.display = "none"; document.getElementById('hideRowNumsDiv').style.display = "none"; var content = '<h5 style="margin-bottom: 3px; color: #4d5f79; font-weight: 600;">Results</h5>'; content += 'Retrieved ' + queryResponsePayload.records.length + ' of ' + queryResponsePayload.totalRecordCount + ' rows in ' + queryResponsePayload.elapsedTime + 'ms.<br>'; content += '<p>'; content += ' <a href="#" onclick="javascript:responseDataCopy();">Click here</a> to copy the data.'; content += '</p>'; content += '<textarea class="form-control small" id="responseData" name="responseData" rows="25" placeholder="Enter your query here." autofocus style="font-size: 10pt;">' + JSON.stringify( queryResponsePayload.records, null, 5 ) + '</textarea>'; content += '</div>'; document.getElementById('resultsDiv').innerHTML = content; } ` } function jsFunctionResponseGenerateTable() { return ` function responseGenerateTable() { document.getElementById('nullFormatDiv').style.display = "block"; document.getElementById('hideRowNumsDiv').style.display = "block"; if ( queryResponsePayload.records.length > 0 ) { var columnNames = Object.keys( queryResponsePayload.records[0] ); var startColumn = 0; if ( document.getElementById('hideRowNumbers').checked ) { startColumn = 1; } var thead = '<thead class="thead-light">'; thead += '<tr>'; if ( document.getElementById('hideRowNumbers').checked === false ) { thead += '<th style="text-align: center;">&nbsp;#&nbsp;</th>'; } for ( i = 1; i < columnNames.length; i++ ) { thead += '<th>' + columnNames[i] + '</th>'; } thead += '</tr>'; thead += '</thead>'; var tbody = '<tbody>'; for ( r = 0; r < queryResponsePayload.records.length; r++ ) { tbody += '<tr>'; for ( i = startColumn; i < columnNames.length; i++ ) { var value = queryResponsePayload.records[r][ columnNames[i] ]; if ( value === null ) { var nullFormat = radioFieldValueGet( 'nullFormat' ); if ( nullFormat == 'dimmed' ) { value = '<span style="color: #ccc;">' + value + '</span>'; } else if ( nullFormat == 'blank' ) { value = ''; } else { value = 'null'; } } if ( i > 0 ) { tbody += '<td>' + value + '</td>'; } else { tbody += '<td style="text-align: center;">' + value + '</td>'; } } tbody += '</tr>'; } tbody += '</tbody>'; var content = '<h5 style="margin-bottom: 3px; color: #4d5f79; font-weight: 600;">Results</h5>'; content += 'Retrieved ' + queryResponsePayload.records.length + ' of ' + queryResponsePayload.totalRecordCount + ' rows in ' + queryResponsePayload.elapsedTime + 'ms.<br>'; content += '<div class="table-responsive">'; content += '<table class="table table-sm table-bordered table-hover table-responsive-sm" id="resultsTable">'; content += thead; content += tbody; content += '</table>'; content += '</div>'; document.getElementById('resultsDiv').innerHTML = content; if ( radioFieldValueGet( 'resultsFormat' ) == 'datatable' ) { $('#resultsTable').DataTable(); } } else { document.getElementById('resultsDiv').innerHTML = '<h5 class="text-warning">No Records Were Found</h5>'; } } ` } function jsFunctionReturnAllToggle() { return ` function returnAllToggle() { if ( document.getElementById('returnAll').checked ) { document.getElementById('rowRangeDiv').style.display = "none"; } else { document.getElementById('rowRangeDiv').style.display = "block"; } } ` } function jsFunctionTableDetailsGet() { return ` function tableDetailsGet( tableName ) { document.getElementById('tableInfoColumn').innerHTML = '<h5 style="color: green;">Loading information for ' + tableName + ' table...</h5>'; var url = '/app/recordscatalog/rcendpoint.nl?action=\getRecordTypeDetail&data=' + encodeURI( JSON.stringify( { scriptId: tableName, detailType: 'SS_ANAL' } ) ); var xhr = new XMLHttpRequest(); xhr.open( 'GET', url, true ); xhr.send(); xhr.onload = function() { if( xhr.status === 200 ) { let recordDetail = JSON.parse( xhr.response ).data; content = '<h5 style="color: #000;">' + recordDetail.label + ' Table ("' + tableName + '") Information</h5>'; content += '<h5 style="margin-top: 18px; margin-bottom: 6px; color: #4d5f79; font-weight: 600;">Columns</h5>'; content += '<div class="table-responsive">'; content += '<table class="table table-sm table-bordered table-hover table-responsive-sm" id="tableColumnsTable">'; content += '<thead class="thead-light">'; content += '<tr>'; content += '<th>Label</th>'; content += '<th>Name</th>'; content += '<th>Type</th>'; content += '</tr>'; content += '</thead>'; content += '<tbody>'; for ( i = 0; i < recordDetail.fields.length; i++ ) { var field = recordDetail.fields[i]; if ( field.isColumn ) {; content += '<tr>'; content += '<td>' + field.label + '</td>'; content += '<td>' + field.id + '</td>'; content += '<td>' + field.dataType + '</td>'; content += '</tr>'; }; } content += '</tbody>'; content += '</table>'; content += '</div>'; if ( recordDetail.joins.length > 0 ) { content += '<h5 style="margin-top: 18px; margin-bottom: 6px; color: #4d5f79; font-weight: 600;">Joins</h5>'; content += '<div class="table-responsive">'; content += '<table class="table table-sm table-bordered table-hover table-responsive-sm" id="tableJoinsTable">'; content += '<thead class="thead-light">'; content += '<tr>'; content += '<th>Label</th>'; content += '<th>Table Name</th>'; content += '<th>Cardinality</th>'; content += '<th>Join Pairs</th>'; content += '</tr>'; content += '</thead>'; content += '<tbody>'; for ( i = 0; i < recordDetail.joins.length; i++ ) { var join = recordDetail.joins[i]; content += '<tr>'; content += '<td>' + join.label + '</td>'; content += '<td><a href="#" onclick="javascript:tableDetailsGet( \\'' + join.sourceTargetType.id + '\\' );">' + join.sourceTargetType.id + '</a></td>'; content += '<td>' + join.cardinality + '</td>'; var joinInfo = ""; for ( j = 0; j < join.sourceTargetType.joinPairs.length; j++ ) { var joinPair = join.sourceTargetType.joinPairs[j]; joinInfo += joinPair.label + '<br>'; } content += '<td>' + joinInfo + '</td>'; content += '</tr>'; } content += '</tbody>'; content += '</table>'; content += '</div>'; } let textareaRows = recordDetail.fields.length + 5; content += '<h5 style="margin-top: 18px; margin-bottom: 6px; color: #4d5f79; font-weight: 600;">Sample Query</h5>'; content += '<span style="font-size: 11pt;"><a href="#" onclick="javascript:tableQueryCopy();">Click here</a> to copy the query.</span>'; content += '<textarea class="form-control small" id="tableQuery" name="sampleQuery" rows="' + textareaRows + '" style="font-size: 10pt;">'; content += 'SELECT\\n'; for ( i = 0; i < recordDetail.fields.length; i++ ) { var field = recordDetail.fields[i]; if ( field.isColumn ) { content += '\\t' + tableName + '.' + field.id; if ( ( i + 1 ) < recordDetail.fields.length ) { content += ','; } content += '\\n'; } } content += 'FROM\\n'; content += '\\t' + tableName + '\\n'; content += '</textarea>'; document.getElementById('tableInfoColumn').innerHTML = content; if ( ${datatablesEnabled} ) { $('#tableColumnsTable').DataTable(); $('#tableJoinsTable').DataTable(); } } else { alert( 'Error: ' + xhr.status ); } } } ` } function jsFunctionTableNamesGet() { return ` function tableNamesGet() { var url = '/app/recordscatalog/rcendpoint.nl?action=\getRecordTypes&data=' + encodeURI( JSON.stringify( { structureType: 'FLAT' } ) ); var xhr = new XMLHttpRequest(); xhr.open( 'GET', url, true ); xhr.send(); xhr.onload = function() { if( xhr.status === 200 ) { let recordTypes = JSON.parse( xhr.response ).data; content = '<div class="table-responsive">'; content += '<table class="table table-sm table-bordered table-hover table-responsive-sm" id="tableNamesTable">'; content += '<thead class="thead-light">'; content += '<tr>'; content += '<th>Table</th>'; content += '</tr>'; content += '</thead>'; content += '<tbody>'; for ( i = 0; i < recordTypes.length; i++ ) { content += '<tr>'; content += '<td>'; content += '<a href="#" onclick="javascript:tableDetailsGet( \\'' + recordTypes[i].id + '\\' );" style="font-weight: bold;">' + recordTypes[i].label + '</a><br>'; content += recordTypes[i].id; content += '</td>'; content += '</tr>'; } content += '</tbody>'; content += '</table>'; content += '</div>'; document.getElementById('tablesColumn').innerHTML = content; if ( ${datatablesEnabled} ) { $('#tableNamesTable').DataTable(); } } else { alert( 'Error: ' + xhr.status ); } } } ` } function jsFunctionTableQueryCopy() { return ` function tableQueryCopy() { var copyText = document.getElementById("tableQuery"); copyText.select(); document.execCommand("copy"); return false; } ` } function jsFunctionTablesUIToggle() { return ` function tablesUIToggle() { $('#queryUI').toggle(); $('#tablesUI').toggle(); } ` } function jsFunctionWorkbooksButton() { if ( workbooksEnabled === true ) { return `<button type="button" class="btn btn-sm btn-light" data-toggle="modal" data-target="#workbooksModal">Workbooks</button>` } else { return `` } } function jsFunctionWorkbookLoad() { return ` function workbookLoad( scriptID ) { var requestPayload = { 'function': 'workbookLoad', 'scriptID': scriptID } var xhr = new XMLHttpRequest(); xhr.open( 'POST', '${scriptURL}', true ); xhr.send( JSON.stringify( requestPayload ) ); xhr.onload = function() { if( xhr.status === 200 ) { workbookLoadResponsePayload = JSON.parse( xhr.response ); if ( workbookLoadResponsePayload.error == undefined ) { document.getElementById('query').value = workbookLoadResponsePayload.sql; queryTextAreaResize(); $('#workbooksModal').modal('toggle'); document.getElementById('resultsDiv').style.display = "none"; activeSQLFile.source = 'Workbook ' + scriptID; activeSQLFile.fileName = ''; activeSQLFile.description = ''; activeSQLFile.fileID = ''; activeSQLFile.sql = workbookLoadResponsePayload.sql; fileInfoRefresh(); } else { alert( 'Error: ' + payload.error ); } } else { alert( 'Error: ' + xhr.status ); } } } ` } function jsFunctionWorkbooksListGet() { return ` function workbooksListGet() { document.getElementById('workbooksList').innerHTML = '<h5 style="color: green;">Getting the list of Workbooks...</h5>'; var requestPayload = { 'function': 'workbooksGet' } var xhr = new XMLHttpRequest(); xhr.open( 'POST', '${scriptURL}', true ); xhr.send( JSON.stringify( requestPayload ) ); xhr.onload = function() { var content = ''; if( xhr.status === 200 ) { payload = JSON.parse( xhr.response ); if ( payload.error == undefined ) { content = '<div class="table-responsive">'; content += '<table id="workbooksTable" class="table table-sm table-bordered table-hover table-responsive-sm">'; content += '<thead class="thead-light">'; content += '<tr>'; content += '<th>Name</th>'; content += '<th>Description</th>'; content += '<th>Owner</th>'; content += '<th></th>'; content += '</tr>'; content += '</thead>'; content += '<tbody>'; for ( r = 0; r < payload.records.length; r++ ) { var description = payload.records[r].description; if( description === null ) { description = ''; } content += '<tr>'; content += '<td style="vertical-align: middle;">' + payload.records[r].name + '</td>'; content += '<td style="vertical-align: middle;">' + description + '</td>'; content += '<td style="vertical-align: middle;">' + payload.records[r].owner + '</td>'; content += '<td style="text-align: center; vertical-align: middle;"><button type="button" class="btn btn-sm btn-primary" onclick="workbookLoad(\\'' + payload.records[r].scriptid + '\\');" >Load</button></td>'; content += '</tr>'; } content += '</tbody>'; content += '</table>'; content += '</div>'; document.getElementById('workbooksList').innerHTML = content; if ( ${datatablesEnabled} ) { $('#workbooksTable').DataTable(); } } else { if ( payload.error == 'No Workbooks' ) { content += '<p class="text-danger">No workbooks were found.</p>'; document.getElementById('workbooksList').innerHTML = content; } else { content = '<h5 class="text-danger">Error</h5>'; content += '<pre>'; content += payload.error; content += '</pre>'; document.getElementById('workbooksList').innerHTML = content; } } } else { var content = '<h5 class="text-danger">Error</h5>'; content += '<pre>'; content += 'XHR Error: Status ' + xhr.status; document.getElementById('workbooksList').innerHTML = content; } } } ` } function localLibraryFilesGet( context ) { var responsePayload; var sql = ` SELECT ID, Name, Description FROM File WHERE ( Folder = ? ) ORDER BY Name `; var queryResults = query.runSuiteQL( { query: sql, params: [ queryFolderID ] } ); var records = queryResults.asMappedResults(); if ( records.length > 0 ) { responsePayload = { 'records': records }; } else { responsePayload = { 'error': 'No SQL Files' }; } context.response.write( JSON.stringify( responsePayload, null, 5 ) ); } function queryExecute( context, requestPayload ) { try { var responsePayload; var moreRecords = true; var records = new Array(); var totalRecordCount = 0; var queryParams = new Array(); var paginatedRowBegin = requestPayload.rowBegin; var paginatedRowEnd = requestPayload.rowEnd; let beginTime = new Date().getTime(); do { var paginatedSQL = 'SELECT * FROM ( SELECT ROWNUM AS ROWNUMBER, * FROM (' + requestPayload.query + ' ) ) WHERE ( ROWNUMBER BETWEEN ' + paginatedRowBegin + ' AND ' + paginatedRowEnd + ')'; var queryResults = query.runSuiteQL( { query: paginatedSQL, params: queryParams } ).asMappedResults(); records = records.concat( queryResults ); if ( queryResults.length < 5000 ) { moreRecords = false; } paginatedRowBegin = paginatedRowBegin + 5000; } while ( moreRecords ); let elapsedTime = ( new Date().getTime() - beginTime ) ; if ( records.length > 0 ) { var paginatedSQL = 'SELECT COUNT(*) AS TotalRecordCount FROM ( ' + requestPayload.query + ' )'; var queryResults = query.runSuiteQL( { query: paginatedSQL, params: queryParams } ).asMappedResults(); var totalRecordCount = queryResults[0].totalrecordcount; } responsePayload = { 'records': records, 'totalRecordCount': totalRecordCount, 'elapsedTime': elapsedTime } } catch( e ) { log.error( { title: 'queryExecute Error', details: e } ); responsePayload = { 'error': e } } context.response.write( JSON.stringify( responsePayload, null, 5 ) ); } function sqlFileExists( context, requestPayload ) { var responsePayload; var sql = ` SELECT ID FROM File WHERE ( Folder = ? ) AND ( Name = ? ) `; var queryResults = query.runSuiteQL( { query: sql, params: [ queryFolderID, requestPayload.filename ] } ); var records = queryResults.asMappedResults(); if ( records.length > 0 ) { responsePayload = { 'exists': true }; } else { responsePayload = { 'exists': false }; } context.response.write( JSON.stringify( responsePayload, null, 5 ) ); } function sqlFileLoad( context, requestPayload ) { var responsePayload; try { var fileObj = file.load( { id: requestPayload.fileID } ); responsePayload = {} responsePayload.file = fileObj; responsePayload.sql = fileObj.getContents(); } catch( e ) { log.error( { title: 'sqlFileLoad Error', details: e } ); responsePayload = { 'error': e } } context.response.write( JSON.stringify( responsePayload, null, 5 ) ); } function sqlFileSave( context, requestPayload ) { var responsePayload; try { var fileObj = file.create( { name: requestPayload.filename, contents: requestPayload.contents, description: requestPayload.description, fileType: file.Type.PLAINTEXT, folder: queryFolderID, isOnline: false } ); var fileID = fileObj.save(); responsePayload = {} responsePayload.fileID = fileID; } catch( e ) { log.error( { title: 'sqlFileSave Error', details: e } ); responsePayload = { 'error': e } } context.response.write( JSON.stringify( responsePayload, null, 5 ) ); } function toolLatestVersionGet() { try { let httpsResponse = https.get( { url: 'https://suiteql.s3.us-east-1.amazonaws.com/query-tool/index.json' } ); let index = JSON.parse( httpsResponse.body ); return index[0]; } catch (e) { log.error( { title: 'toolLatestVersionGet - https error', details: e } ); return null; } } function toolUpgrade( context ) { try { let sql = ` SELECT SuiteLet.ID, SuiteLet.ScriptFile, File.Folder FROM SuiteLet INNER JOIN File ON ( File.ID = SuiteLet.ScriptFile ) WHERE ( SuiteLet.ScriptID = ? ) `; let queryResults = query.runSuiteQL( { query: sql, params: [ runtime.getCurrentScript().id ] } ); let records = queryResults.asMappedResults(); let scriptRecord = records[0]; let httpsResponse = https.get( { url: 'https://suiteql.s3.us-east-1.amazonaws.com/query-tool/' + toolLatestVersion.fileName } ); var fileObj = file.create( { name: toolLatestVersion.fileName, contents: httpsResponse.body, description: 'SuiteQL Query Tool v' + toolLatestVersion.version, fileType: file.Type.JAVASCRIPT, folder: scriptRecord.folder, isOnline: false } ); var fileID = fileObj.save(); var id = record.submitFields( { type: record.Type.SUITELET, id: scriptRecord.id, values: { scriptfile: fileID } } ); return true; } catch (e) { log.error( { title: 'toolUpgrade - error', details: e } ); return false; } } function workbookLoad( context, requestPayload ) { var responsePayload; try { var loadedQuery = query.load( { id: requestPayload.scriptID } ); responsePayload = {} responsePayload.sql = loadedQuery.toSuiteQL().query; } catch( e ) { log.error( { title: 'workbookLoad Error', details: e } ); responsePayload = { 'error': e } } context.response.write( JSON.stringify( responsePayload, null, 5 ) ); } function workbooksGet( context ) { var responsePayload; var sql = ` SELECT ScriptID, Name, Description, BUILTIN.DF( Owner ) AS Owner FROM UsrSavedSearch ORDER BY Name `; var queryResults = query.runSuiteQL( { query: sql, params: [] } ); var records = queryResults.asMappedResults(); if ( records.length > 0 ) { responsePayload = { 'records': records }; } else { responsePayload = { 'error': 'No Workbooks' }; } context.response.write( JSON.stringify( responsePayload, null, 5 ) ); }
true
/** * @NApiVersion 2.1 * @NScriptType Suitelet * @NModuleScope Public */ /* ------------------------------------------------------------------------------------------ Script Information ------------------------------------------------------------------------------------------ Name: SQL Query Tool ID: _sql_query_tool Description A utility for running SuiteQL queries in a NetSuite instance. ------------------------------------------------------------------------------------------ MIT License ------------------------------------------------------------------------------------------ Copyright (c) 2021 Timothy Dietrich. Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. ------------------------------------------------------------------------------------------ Developer(s) ------------------------------------------------------------------------------------------ Tim Dietrich * PI:EMAIL:nnheo@example.comEND_PI * https://timdietrich.me ------------------------------------------------------------------------------------------ History ------------------------------------------------------------------------------------------ 20210714 - Tim Dietrich * First public beta of v2021.2. 20210725 - Tim Dietrich * Second public beta of v2021.2. */ var datatablesEnabled = true, file, https, log, page, query, record, remoteLibraryEnabled = true, render, rowsReturnedDefault = 10, runtime, scriptURL, queryFolderID = null, toolLatestVersion, toolUpgradesEnabled = true, toolUpgradeMessage = '', url, version = '2021.2 Beta 2', workbooksEnabled = true; define( [ 'N/file', 'N/https', 'N/log', 'N/ui/message', 'N/query', 'N/record', 'N/render', 'N/runtime', 'N/ui/serverWidget', 'N/url' ], main ); function main( fileModule, httpsModule, logModule, messageModule, queryModule, recordModule, renderModule, runtimeModule, serverWidgetModule, urlModule ) { file = fileModule; https = httpsModule; log = logModule; message = messageModule; query= queryModule; record = recordModule; render = renderModule; runtime = runtimeModule; serverWidget = serverWidgetModule; url = urlModule; return { onRequest: function( context ) { scriptURL = url.resolveScript( { scriptId: runtime.getCurrentScript().id, deploymentId: runtime.getCurrentScript().deploymentId, returnExternalURL: false } ); if ( context.request.method == 'POST' ) { var requestPayload = JSON.parse( context.request.body ); context.response.setHeader( 'Content-Type', 'application/json' ); switch ( requestPayload['function'] ) { case 'documentSubmit': return documentSubmit( context, requestPayload ); break; case 'queryExecute': return queryExecute( context, requestPayload ); break; case 'sqlFileExists': return sqlFileExists( context, requestPayload ); break; case 'sqlFileLoad': return sqlFileLoad( context, requestPayload ); break; case 'sqlFileSave': return sqlFileSave( context, requestPayload ); break; case 'localLibraryFilesGet': return localLibraryFilesGet( context ); break; case 'workbookLoad': return workbookLoad( context, requestPayload ); break; case 'workbooksGet': return workbooksGet( context ); break; default: log.error( { title: 'Payload - Unsupported Function', details: requestPayload['function'] } ); } } else { if ( toolUpgradesEnabled === true ) { toolLatestVersion = toolLatestVersionGet(); } if ( context.request.parameters.hasOwnProperty( 'function' ) ) { if ( context.request.parameters['function'] == 'documentGenerate' ) { documentGenerate( context ); } if ( context.request.parameters['function'] == 'upgrade' ) { let upgradeSuccess = toolUpgrade( context ); if ( upgradeSuccess === true ) { context.response.write( `<meta http-equiv="refresh" content = "0; url = ${scriptURL}" />` ); } else { context.response.write( '<p>An error occurred during the upgrade process.</p><p>See the script execution log for details.</p><p><a href="javascript:history.go(-1);">Continue...</a></p>' ); } } } else { if ( toolUpgradesEnabled === true ) { if ( toolLatestVersion != null ) { if ( toolLatestVersion.version != version ) { toolUpgradeMessage = ` <p style="margin-top: 24px;"> <span style="padding: 9px; x-background-color: yellow; width: 30%; border: 1px solid #ccc;"> <a href="${toolLatestVersion.infoURL}" target="_info" style="color: #4d5f79;">Version ${toolLatestVersion.version}</a> is now available. <a href="${scriptURL}&function=upgrade" style="color: #4d5f79;">Click to install.</a> </span> </p> `; } } } var form = serverWidget.createForm( { title: 'SuiteQL Query Tool', hideNavBar: false } ); var htmlField = form.addField( { id: 'custpage_field_html', type: serverWidget.FieldType.INLINEHTML, label: 'HTML' } ); htmlField.defaultValue = htmlGenerate(); context.response.writePage( form ); } } } } } function documentGenerate( context ) { try { var sessionScope = runtime.getCurrentSession(); var docInfo = JSON.parse( sessionScope.get( { name: 'suiteQLDocumentInfo' } ) ); var moreRecords = true; var paginatedRowBegin = docInfo.rowBegin; var paginatedRowEnd = docInfo.rowEnd; var queryParams = new Array(); var records = new Array(); do { var paginatedSQL = 'SELECT * FROM ( SELECT ROWNUM AS ROWNUMBER, * FROM (' + docInfo.query + ' ) ) WHERE ( ROWNUMBER BETWEEN ' + paginatedRowBegin + ' AND ' + paginatedRowEnd + ')'; var queryResults = query.runSuiteQL( { query: paginatedSQL, params: queryParams } ).asMappedResults(); records = records.concat( queryResults ); if ( queryResults.length < 5000 ) { moreRecords = false; } paginatedRowBegin = paginatedRowBegin + 5000; } while ( moreRecords ); var recordsDataSource = { 'records': records }; var renderer = render.create(); renderer.addCustomDataSource( { alias: 'results', format: render.DataSource.OBJECT, data: recordsDataSource } ); renderer.templateContent = docInfo.template; if ( docInfo.docType == 'pdf' ) { let renderObj = renderer.renderAsPdf(); let pdfString = renderObj.getContents(); context.response.setHeader( 'Content-Type', 'application/pdf' ); context.response.write( pdfString ); } else { let htmlString = renderer.renderAsString(); context.response.setHeader( 'Content-Type', 'text/html' ); context.response.write( htmlString ); } } catch( e ) { log.error( { title: 'documentGenerate Error', details: e } ); context.response.write( 'Error: ' + e ); } } function documentSubmit( context, requestPayload ) { try { var responsePayload; var sessionScope = runtime.getCurrentSession(); sessionScope.set( { name: 'suiteQLDocumentInfo', value: JSON.stringify( requestPayload ) } ); responsePayload = { 'submitted': true } } catch( e ) { log.error( { title: 'queryExecute Error', details: e } ); responsePayload = { 'error': e } } context.response.write( JSON.stringify( responsePayload, null, 5 ) ); } function htmlDataTablesFormatOption() { if ( datatablesEnabled === true ) { return ` <div class="form-check-inline"> <label class="form-check-label" style="font-size: 10pt;"> <input type="radio" class="form-check-input" name="resultsFormat" value="datatable" onChange="responseGenerate();">DataTable </label> </div> ` } else { return `` } } function htmlGenerate() { return ` <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.5.2/css/bootstrap.min.css"> <script src="/ui/jquery/jquery-3.5.1.min.js"></script> <script src="https://maxcdn.bootstrapcdn.com/bootstrap/4.5.2/js/bootstrap.min.js"></script> ${jsFunctionDataTablesExternals()} <style type = "text/css"> input[type="text"], input[type="search"], textarea, button { outline: none; box-shadow:none !important; border: 1px solid #ccc !important; } p, pre { font-size: 10pt; } td, th { font-size: 10pt; border: 3px; } th { text-transform: lowercase; font-weight: bold; } </style> ${htmlLocalLoadModal()} ${htmlRemoteLoadModal()} ${htmlSaveModal()} ${htmlWorkbooksModal()} ${htmlQueryUI()} ${htmlTablesUI()} <script> var activeSQLFile = {}, queryResponsePayload, fileLoadResponsePayload; window.jQuery = window.$ = jQuery; $('#queryUI').show(); $('#templateHeaderRow').hide(); $('#templateFormRow').hide(); tableNamesGet(); ${jqueryKeydownHandler()} ${jqueryModalHandlers()} ${jsFunctionDefaultQuerySet()} ${jsFunctionDocumentGenerate()} ${jsFunctionFileInfoRefresh()} ${jsFunctionHideRowNumbersToggle()} ${jsFunctionLocalLibraryFilesGet()} ${jsFunctionLocalSQLFileLoad()} ${jsFunctionLocalSQLFileSave()} ${jsFunctionQueryFormRowToggle()} ${jsFunctionQuerySubmit()} ${jsFunctionQueryTextAreaResize()} ${jsFunctionRadioFieldValueGet()} ${jsFunctionRemoteLibraryIndexGet()} ${jsFunctionRemoteSQLFileLoad()} ${jsFunctionResponseDataCopy()} ${jsFunctionResponseGenerate()} ${jsFunctionResponseGenerateCSV()} ${jsFunctionResponseGenerateJSON()} ${jsFunctionResponseGenerateTable()} ${jsFunctionReturnAllToggle()} ${jsFunctionTableDetailsGet()} ${jsFunctionTableNamesGet()} ${jsFunctionTableQueryCopy()} ${jsFunctionTablesUIToggle()} ${jsFunctionWorkbookLoad()} ${jsFunctionWorkbooksListGet()} </script> ` } function htmlLocalLoadModal() { return ` <div class="modal fade" id="localLoadModal"> <div class="modal-dialog modal-lg"> <div class="modal-content"> <div class="modal-header"> <h4 class="modal-title">Local Query Library</h4> <button type="button" class="close" data-dismiss="modal">&times;</button> </div> <div class="modal-body" id="localSQLFilesList"> </div> </div> </div> </div> `; } function htmlQueryUI() { return ` <div class="collapse" id="queryUI" style="text-align: left;"> <table style="table-layout: fixed; width: 100%; border-spacing: 6px; border-collapse: separate;"> <tr> <td width="20%"> <h5 id="queryHeader" style="margin-bottom: 0px; color: #4d5f79; font-weight: 600;"><a href="#" onClick="javascript:defaultQuerySet();" title="Click to load a sample query." style="color: #4d5f79;">Query Editor</a></h5> </td> <td width="55%" style="text-align: right;"> <div id="buttonsDiv"> <button type="button" class="btn btn-sm btn-light" onClick="javascript:tablesUIToggle();">Tables Reference</button> ${jsFunctionWorkbooksButton()} ${jsFunctionRemoteLibraryButton()} ${jsFunctionLocalLibraryButtons()} <button type="button" class="btn btn-sm btn-success" onclick="querySubmit();" accesskey="r">Run Query</button> </div> </td> <td width="25%" style="text-align: right;"> <button id="btnQueryFormRowToggle" type="button" class="btn btn-sm btn-light" onclick="queryFormRowToggle();">Hide Query Editor</button> </td> </tr> <tr id="queryFormRow"> <td colspan="2" style="vertical-align: top;"> <textarea class="form-control small" id="query" style=" font-size: 10pt; background-color: #FFFFFF; x-font-family: 'Courier New', monospace; color: #000000; line-height: 1.3; padding: 12px; " rows="20" placeholder="Enter a SuiteQL query here. Click &quot;Query Editor&quot; (above) to load a sample query." autofocus ></textarea> <div id="fileInfo"></div> </td> <td style="vertical-align: top;"> <div style="margin-left: 6px; padding: 12px; border: 1px solid #ccc; border-radius: 5px; background-color: #FAFAFA;"> <div> <p style="font-size: 10pt; margin-bottom: 3px;">Return Rows:</p> <div class="form-inline" id="rowRangeDiv"> <input type="number" class="form-control-sm" name="rowBegin" id="rowBegin" style="max-width: 100px;" value="1" required> &nbsp;thru&nbsp; <input type="number" class="form-control-sm" name="rowEnd" id="rowEnd" style="max-width: 100px;" value="${rowsReturnedDefault}" required> </div> <div class="form-check" style="margin-top: 6px;"> <label class="form-check-label" style="font-size: 10pt;"> <input type="checkbox" class="form-check-input" id="returnAll" onChange="returnAllToggle();">Return all rows. </label> </div> </div> <div style="margin-top: 12px; border-top: 1px solid #eee; padding-top: 12px;"> <p style="font-size: 10pt; margin-bottom: 3px;">Format Results As:</p> <div class="form-check-inline"> <label class="form-check-label" style="font-size: 10pt;"> <input type="radio" class="form-check-input" name="resultsFormat" value="table" checked onChange="responseGenerate();">Table </label> </div> ${htmlDataTablesFormatOption()} <div class="form-check-inline"> <label class="form-check-label" style="font-size: 10pt;"> <input type="radio" class="form-check-input" name="resultsFormat" value="csv" onChange="responseGenerate();">CSV </label> </div> <div class="form-check-inline"> <label class="form-check-label" style="font-size: 10pt;"> <input type="radio" class="form-check-input" name="resultsFormat" value="json" onChange="responseGenerate();">JSON </label> </div> <div class="form-check-inline"> <label class="form-check-label" style="font-size: 10pt;"> <input type="radio" class="form-check-input" name="resultsFormat" value="pdf" onChange="responseGenerate();">PDF </label> </div> <div class="form-check-inline"> <label class="form-check-label" style="font-size: 10pt;"> <input type="radio" class="form-check-input" name="resultsFormat" value="html" onChange="responseGenerate();">HTML </label> </div> </div> <div style="margin-top: 12px; border-top: 1px solid #eee; padding-top: 12px;" id="nullFormatDiv"> <p style="font-size: 10pt; margin-bottom: 3px;">Display NULL Values As:</p> <div class="form-check-inline"> <label class="form-check-label" style="font-size: 10pt;"> <input type="radio" class="form-check-input" name="nullFormat" value="dimmed" checked onChange="responseGenerate();">Dimmed </label> </div> <div class="form-check-inline"> <label class="form-check-label" style="font-size: 10pt;"> <input type="radio" class="form-check-input" name="nullFormat" value="blank" onChange="responseGenerate();">Blank </label> </div> <div class="form-check-inline"> <label class="form-check-label" style="font-size: 10pt;"> <input type="radio" class="form-check-input" name="nullFormat" value="null" onChange="responseGenerate();">null </label> </div> </div> <div style="margin-top: 12px; border-top: 1px solid #eee; padding-top: 12px;" id="hideRowNumsDiv"> <div class="form-check" style="margin-top: 6px;"> <label class="form-check-label" style="font-size: 10pt;"> <input type="checkbox" class="form-check-input" id="hideRowNumbers" onChange="hideRowNumbersToggle();" checked>Hide Row Numbers. </label> </div> </div> </div> </td> </tr> <tr id="templateHeaderRow"> <td> <h5 style="margin-top: 12px; margin-bottom: 0px; color: #4d5f79; font-weight: 600;"><a href="#" onClick="javascript:defaultQuerySet();" title="Click to load a sample query." style="color: #4d5f79;">Template Editor</a></h5> </td> <td colspan="2" style="text-align: right; vertical-align: top;"> <div id="templateButtonsDiv"> <button type="button" class="btn btn-sm btn-light" onClick="window.open( 'https://bfo.com/products/report/docs/userguide.pdf' );">BFO Reference</button> <button type="button" class="btn btn-sm btn-light" onClick="window.open( 'https://freemarker.apache.org/docs/index.html' );">FreeMarker Reference</button> <button type="button" class="btn btn-sm btn-success" onclick="documentGenerate();" accesskey="g">Generate Document</button> </div> </td> </tr> <tr id="templateFormRow"> <td colspan="3" style="vertical-align: top;"> <textarea class="form-control small" id="template" style=" font-size: 10pt; background-color: #FFFFFF; x-font-family: 'Courier New', monospace; color: #000000; line-height: 1.3; padding: 12px; " rows="20" placeholder="Enter your template here." autofocus ></textarea> <div id="templateFileInfo"></div> </td> </tr> <tr> <td colspan="3"> <div id="resultsDiv" style="max-width: 100%; margin-top: 12px; display: none; overflow: auto; overflow-y: hidden;"> <!-- RESULTS --> </div> </td> </tr> <tr> <td colspan="3"> <div id="footerDiv" style="width: 100%; margin-top: 24px; margin-bottom: 24px; border-top: 1px solid #eee; padding-top: 24px; font-size: 10pt; color: #848484; display: inline-block; text-align: center;"> <p> SuiteQL Query Tool Version ${version}. Developed by <a href="https://timdietrich.me/" target="_tim" style="color: #4d5f79;">Tim Dietrich</a>. </p> ${toolUpgradeMessage} </div> </td> </tr> </table> </div> `; } function htmlRemoteLoadModal() { return ` <div class="modal fade" id="remoteLoadModal"> <div class="modal-dialog modal-lg"> <div class="modal-content"> <div class="modal-header"> <h4 class="modal-title">Remote Query Library</h4> <button type="button" class="close" data-dismiss="modal">&times;</button> </div> <div class="modal-body" id="remoteSQLFilesList"> </div> </div> </div> </div> `; } function htmlSaveModal() { return ` <div class="modal fade" id="saveModal"> <div class="modal-dialog modal-lg"> <div class="modal-content"> <div class="modal-header"> <h4 class="modal-title">Save Query</h4> <button type="button" class="close" data-dismiss="modal">&times;</button> </div> <div class="modal-body" id="saveQueryMessage" style="display: none;"> ERROR </div> <div class="modal-body" id="saveQueryForm" style="display: none;"> <form class="row" style="margin-bottom: 24px;"> <div class="col-12" style="margin-top: 12px;"> <p style="font-size: 10pt; margin-bottom: 3px;">File Name:</p> <input type="text" class="form-control" name="saveQueryFormFileName" id="saveQueryFormFileName" style="width: 200px; padding: 3px;" value=""> </div> <div class="col-12" style="margin-top: 12px;"> <p style="font-size: 10pt; margin-bottom: 3px;">Description:</p> <input type="text" class="form-control" name="saveQueryFormDescription" id="saveQueryFormDescription" style="width: 400px; padding: 3px;" value=""> </div> <div class="col-12" style="margin-top: 12px;"> <button type="button" class="btn btn-sm btn-success" onclick="javascript:localSQLFileSave();">Save The Query &gt;</button> </div> </form> </div> </div> </div> </div> `; } function htmlTablesUI() { return ` <div class="collapse" id="tablesUI"> <div class="container" style="max-width: 100%; margin-top: 24px;"> <form class="row g-3" method="POST" action="${scriptURL}"> <div class="col-md-4"> <h5 style="color: #4d5f79; font-weight: 600;">Tables Reference</h5> <p>Select a table to view its details.</p> </div> <div class="col-md-8" style="text-align: right;"> <button type="button" class="btn btn-sm btn-danger" onClick="javascript:tablesUIToggle();">Close Tables Reference</button> </div> <div class="col-md-4" style="margin-top: 3px;" id="tablesColumn">Loading Tables Index...</div> <div class="col-md-8" id="tableInfoColumn"> &nbsp; </div> </form> </div> </div> `; } function htmlWorkbooksModal() { return ` <div class="modal fade" id="workbooksModal"> <div class="modal-dialog modal-lg"> <div class="modal-content"> <div class="modal-header"> <h4 class="modal-title">Workbooks</h4> <button type="button" class="close" data-dismiss="modal">&times;</button> </div> <div class="modal-body" id="workbooksList"> </div> </div> </div> </div> `; } function jqueryKeydownHandler() { return ` $('textarea').keydown( function(e) { if ( e.keyCode === 9 ) { var start = this.selectionStart; var end = this.selectionEnd; var $this = $(this); var value = $this.val(); $this.val(value.substring(0, start) + "\t" + value.substring(end)); this.selectionStart = this.selectionEnd = start + 1; e.preventDefault(); return; } if ( e.keyCode === 190 ) { var queryField = document.getElementById('query'); var pos = queryField.selectionStart; if ( pos > 1 ) { if ( queryField.value.charAt( pos - 1 ) == '.' ) { var tableStart = -2; for ( i = pos - 2; i > 0; i--) { var c = queryField.value.charAt(i); if ( ( c == '\\t' ) || ( c == ' ' ) || ( c == '\\n' ) || ( c == '\\r' ) ) { i = i + 1; break; } } var tableName = queryField.value.substring( i, pos - 1 ); // alert( tableName ); tablesUIToggle(); tableDetailsGet( tableName ); return false; } } return; } fileInfoRefresh(); } ); ` } function jqueryModalHandlers() { return ` $('#localLoadModal').on('shown.bs.modal', function (e) { localLibraryFilesGet(); } ); $('#remoteLoadModal').on('shown.bs.modal', function (e) { remoteLibraryIndexGet(); } ); $('#saveModal').on('shown.bs.modal', function (e) { document.getElementById('saveQueryMessage').style.display = "none"; document.getElementById('saveQueryForm').style.display = "none"; if ( document.getElementById('query').value == '' ) { document.getElementById('saveQueryMessage').innerHTML = '<p>Please enter a query.</p>'; document.getElementById('saveQueryMessage').style.display = "block"; return; } else { document.getElementById('saveQueryForm').style.display = "block"; if ( activeSQLFile.hasOwnProperty( 'fileName' ) ) { document.getElementById('saveQueryFormFileName').value = activeSQLFile.fileName; } if ( activeSQLFile.hasOwnProperty( 'description' ) ) { document.getElementById('saveQueryFormDescription').value = activeSQLFile.description; } document.getElementById('saveQueryFormFileName').focus(); } } ); $('#workbooksModal').on('shown.bs.modal', function (e) { workbooksListGet(); } ); ` } function jsFunctionDataTablesExternals() { if ( datatablesEnabled === true ) { return ` <link rel="stylesheet" type="text/css" href="https://cdn.datatables.net/1.10.25/css/jquery.dataTables.css"> <script type="text/javascript" charset="utf8" src="https://cdn.datatables.net/1.10.25/js/jquery.dataTables.js"></script> ` } else { return `` } } function jsFunctionDefaultQuerySet() { return ` function defaultQuerySet() { document.getElementById('query').value = \`SELECT\n\tID,\n\tLastName,\n\tFirstName,\n\tPhone,\n\tEmail\nFROM\n\tEmployee\nWHERE\n\tEmail LIKE 'PI:EMAIL:efpyi@example.comEND_PI'\nORDER BY\n\tLastName,\n\tFirstName\`; return false; } ` } function jsFunctionDocumentGenerate() { return ` function documentGenerate() { if ( document.getElementById('query').value == '' ) { alert( 'Please enter a query.' ); return; } if ( document.getElementById('returnAll').checked ) { rowBegin = 1; rowEnd = 999999; } else { rowBegin = parseInt( document.getElementById('rowBegin').value ); if ( Number.isInteger( rowBegin ) === false ) { alert( 'Enter an integer for the beginning row.' ); document.getElementById('rowBegin').focus(); return; } rowEnd = parseInt( document.getElementById('rowEnd').value ); if ( Number.isInteger( rowEnd ) === false ) { alert( 'Enter an integer for the ending row.' ); document.getElementById('rowEnd').focus(); return; } } if ( document.getElementById('template').value == '' ) { alert( 'Please enter a template.' ); return; } var requestPayload = { 'function': 'documentSubmit', 'query': document.getElementById('query').value, 'rowBegin': rowBegin, 'rowEnd': rowEnd, 'template': document.getElementById('template').value, 'docType': radioFieldValueGet( 'resultsFormat' ) } var xhr = new XMLHttpRequest(); xhr.open( 'POST', '${scriptURL}', true ); xhr.setRequestHeader( 'Accept', 'application/json' ); xhr.send( JSON.stringify( requestPayload ) ); xhr.onload = function() { if( xhr.status === 200 ) { try { queryResponsePayload = JSON.parse( xhr.response ); } catch( e ) { alert( 'Unable to parse the response.' ); return; } if ( queryResponsePayload['error'] == undefined ) { window.open( '${scriptURL}&function=documentGenerate' ); } else { alert( 'Error: ' + queryResponsePayload.error.message ); } } else { alert( 'Error: ' + xhr.status ); } } } ` } function jsFunctionFileInfoRefresh() { return ` function fileInfoRefresh() { var content = ''; var status = ''; if ( activeSQLFile.source == undefined ) { if ( document.getElementById('query').value != '' ) { content = '<span class="text-danger">unsaved</span>'; } } else { status = 'Unchanged'; if ( document.getElementById('query').value != activeSQLFile.sql ) { status = 'Changed / Unsaved'; } else { status = 'Unchanged'; } var tooltip = 'Source: ' + activeSQLFile.source + '\\n'; tooltip += 'Status: ' + status; content = '<span title="' + tooltip + '">' + activeSQLFile.fileName + '</span>'; if ( document.getElementById('query').value != activeSQLFile.sql ) { content = '<span class="text-danger">' + content + '</span>'; } } content = '<p style="margin-top: 3px;">' + content + '</p>'; document.getElementById('fileInfo').innerHTML = content; } ` } function jsFunctionHideRowNumbersToggle() { return ` function hideRowNumbersToggle() { responseGenerateTable(); } ` } function jsFunctionLocalLibraryButtons() { if ( queryFolderID !== null ) { return `<button type="button" class="btn btn-sm btn-light" data-toggle="modal" data-target="#localLoadModal">Local Library</button> <button type="button" class="btn btn-sm btn-light" data-toggle="modal" data-target="#saveModal">Save Query</i></button>` } else { return `` } } function jsFunctionLocalLibraryFilesGet() { return ` function localLibraryFilesGet() { document.getElementById('localSQLFilesList').innerHTML = '<h5 style="color: green;">Getting the list of SQL files...</h5>'; var requestPayload = { 'function': 'localLibraryFilesGet' } var xhr = new XMLHttpRequest(); xhr.open( 'POST', '${scriptURL}', true ); xhr.send( JSON.stringify( requestPayload ) ); xhr.onload = function() { var content = ''; if( xhr.status === 200 ) { payload = JSON.parse( xhr.response ); if ( payload.error == undefined ) { content = '<div class="table-responsive">'; content += '<table id="localFilesTable" class="table table-sm table-bordered table-hover table-responsive-sm">'; content += '<thead class="thead-light">'; content += '<tr>'; content += '<th>Name</th>'; content += '<th>Description</th>'; content += '<th></th>'; content += '</tr>'; content += '</thead>'; content += '<tbody>'; for ( r = 0; r < payload.records.length; r++ ) { var description = payload.records[r].description; if( description === null ) { description = ''; } content += '<tr>'; content += '<td style="vertical-align: middle;">' + payload.records[r].name + '</td>'; content += '<td style="vertical-align: middle;">' + description + '</td>'; content += '<td style="text-align: center;"><button type="button" class="btn btn-sm btn-primary" onclick="localSQLFileLoad(' + payload.records[r].id + ');">Load</button></td>'; content += '</tr>'; } content += '</tbody>'; content += '</table>'; content += '</div>'; document.getElementById('localSQLFilesList').innerHTML = content; if ( ${datatablesEnabled} ) { $('#localFilesTable').DataTable(); } } else { if ( payload.error == 'No SQL Files' ) { content += '<p class="text-danger">No query files were found in the local folder.</p>'; document.getElementById('localSQLFilesList').innerHTML = content; } else { content = '<h5 class="text-danger">Error</h5>'; content += '<pre>'; content += payload.error; content += '</pre>'; document.getElementById('localSQLFilesList').innerHTML = content; } } } else { var content = '<h5 class="text-danger">Error</h5>'; content += '<pre>'; content += 'XHR Error: Status ' + xhr.status; document.getElementById('localSQLFilesList').innerHTML = content; } } } ` } function jsFunctionLocalSQLFileLoad() { return ` function localSQLFileLoad( fileID ) { var requestPayload = { 'function': 'sqlFileLoad', 'fileID': fileID } var xhr = new XMLHttpRequest(); xhr.open( 'POST', '${scriptURL}', true ); xhr.send( JSON.stringify( requestPayload ) ); xhr.onload = function() { if( xhr.status === 200 ) { fileLoadResponsePayload = JSON.parse( xhr.response ); if ( fileLoadResponsePayload.error == undefined ) { document.getElementById('query').value = fileLoadResponsePayload.sql; queryTextAreaResize(); $('#localLoadModal').modal('toggle'); document.getElementById('resultsDiv').style.display = "none"; activeSQLFile.source = 'Local SQL Library'; activeSQLFile.fileName = fileLoadResponsePayload.file.name; activeSQLFile.description = fileLoadResponsePayload.file.description; activeSQLFile.fileID = fileLoadResponsePayload.file.id; activeSQLFile.sql = fileLoadResponsePayload.sql; fileInfoRefresh(); } else { alert( 'Error: ' + payload.error ); } } else { alert( 'Error: ' + xhr.status ); } } } ` } function jsFunctionLocalSQLFileSave() { return ` function localSQLFileSave() { var filename = document.getElementById('saveQueryFormFileName').value; if ( filename == '' ) { alert( 'Please enter a name for the file.' ); return; } var requestPayload = { 'function': 'sqlFileExists', 'filename': filename } var xhr = new XMLHttpRequest(); xhr.open( 'POST', '${scriptURL}', false ); xhr.send( JSON.stringify( requestPayload ) ); if( xhr.status === 200 ) { fileExistsResponsePayload = JSON.parse( xhr.response ); if ( fileExistsResponsePayload.exists == true ) { var confirmResponse = confirm( "A file named \\"" + filename + "\\" already exists. Do you want to replace it?"); if ( confirmResponse == false ) { return; } } } else { alert( 'Error: ' + xhr.status ); return; } var requestPayload = { 'function': 'sqlFileSave', 'filename': filename, 'contents': document.getElementById('query').value, 'description': document.getElementById('saveQueryFormDescription').value } var xhr = new XMLHttpRequest(); xhr.open( 'POST', '${scriptURL}', true ); xhr.send( JSON.stringify( requestPayload ) ); xhr.onload = function() { if( xhr.status === 200 ) { fileSaveResponsePayload = JSON.parse( xhr.response ); if ( fileSaveResponsePayload.error == undefined ) { activeSQLFile.source = 'Local SQL Library'; activeSQLFile.fileName = filename; activeSQLFile.description = document.getElementById('saveQueryFormDescription').value; activeSQLFile.fileID = fileSaveResponsePayload.fileID; activeSQLFile.sql = document.getElementById('query').value; fileInfoRefresh(); alert( 'The file has been saved.' ); } else { alert( 'Error: ' + payload.error ); } } else { alert( 'Error: ' + xhr.status ); } } $('#saveModal').modal('toggle'); return; } ` } function jsFunctionQueryFormRowToggle() { return ` function queryFormRowToggle() { if ( $('#queryFormRow').is(":visible") ) { $('#queryFormRow').hide(); $('#queryHeader').hide(); $('#buttonsDiv').hide(); $('#btnQueryFormRowToggle').html('Show Query Editor'); } else { $('#queryFormRow').show(); $('#queryHeader').show(); $('#buttonsDiv').show(); $('#btnQueryFormRowToggle').html('Hide Query Editor'); } } ` } function jsFunctionQuerySubmit() { return ` function querySubmit() { if ( document.getElementById('query').value == '' ) { alert( 'Please enter a query.' ); return; } if ( document.getElementById('returnAll').checked ) { rowBegin = 1; rowEnd = 999999; } else { rowBegin = parseInt( document.getElementById('rowBegin').value ); if ( Number.isInteger( rowBegin ) === false ) { alert( 'Enter an integer for the beginning row.' ); document.getElementById('rowBegin').focus(); return; } rowEnd = parseInt( document.getElementById('rowEnd').value ); if ( Number.isInteger( rowEnd ) === false ) { alert( 'Enter an integer for the ending row.' ); document.getElementById('rowEnd').focus(); return; } } document.getElementById('resultsDiv').style.display = "block"; document.getElementById('resultsDiv').innerHTML = '<h5 style="color: green;">Running query...</h5>'; var requestPayload = { 'function': 'queryExecute', 'query': document.getElementById('query').value, 'rowBegin': rowBegin, 'rowEnd': rowEnd } var xhr = new XMLHttpRequest(); xhr.open( 'POST', '${scriptURL}', true ); xhr.setRequestHeader( 'Accept', 'application/json' ); xhr.send( JSON.stringify( requestPayload ) ); xhr.onload = function() { if( xhr.status === 200 ) { try { queryResponsePayload = JSON.parse( xhr.response ); } catch( e ) { alert( 'Unable to parse the response.' ); return; } if ( queryResponsePayload['error'] == undefined ) { responseGenerate(); } else { var content = '<h5 class="text-danger">Error</h5>'; content += '<pre>'; content += queryResponsePayload.error.message; content += '</pre>'; document.getElementById('resultsDiv').innerHTML = content; } } else { var content = '<h5 class="text-danger">Error</h5>'; content += '<pre>'; content += 'XHR Error: Status ' + xhr.status; content += '</pre>'; document.getElementById('resultsDiv').innerHTML = content; } } } ` } function jsFunctionQueryTextAreaResize() { return ` function queryTextAreaResize() { var lines = document.getElementById('query').value.split(/\\r*\\n/); var lineCount = lines.length + 1; if ( lineCount < 12 ) { lineCount = 12; } document.getElementById('query').rows = lineCount + 1; } ` } function jsFunctionRadioFieldValueGet() { return ` function radioFieldValueGet( fieldName ) { var radios = document.getElementsByName( fieldName ); for (var i = 0, length = radios.length; i < length; i++) { if (radios[i].checked) { return( radios[i].value ); } } return ''; } ` } function jsFunctionRemoteLibraryButton() { if ( remoteLibraryEnabled === true ) { return `<button type="button" class="btn btn-sm btn-light" data-toggle="modal" data-target="#remoteLoadModal">Remote Library</button>` } else { return `` } } function jsFunctionRemoteLibraryIndexGet() { return ` function remoteLibraryIndexGet() { document.getElementById('remoteSQLFilesList').innerHTML = '<h5 style="color: green;">Loading SuiteQL Query Library...</h5>'; var xhr = new XMLHttpRequest(); xhr.open( 'GET', 'https://suiteql.s3.us-east-1.amazonaws.com/queries/index.json?nonce=' + new Date().getTime(), true ); xhr.send(); xhr.onload = function() { var content = ''; if( xhr.status === 200 ) { payload = JSON.parse( xhr.response ); content = '<div class="table-responsive">'; content += '<table class="table table-sm table-bordered table-hover table-responsive-sm" id="remoteFilesTable">'; content += '<thead class="thead-light">'; content += '<tr>'; content += '<th>Name</th>'; content += '<th>Description</th>'; content += '<th></th>'; content += '</tr>'; content += '</thead>'; content += '<tbody>'; for ( r = 0; r < payload.length; r++ ) { content += '<tr>'; content += '<td style="vertical-align: middle;" width="40%">' + payload[r].name + '</td>'; content += '<td style="vertical-align: middle;">' + payload[r].description + '</td>'; content += '<td style="text-align: center;"><button type="button" class="btn btn-sm btn-primary" onclick="remoteSQLFileLoad(\\'' + payload[r].fileName + '\\');">Load</button></td>'; content += '</tr>'; } content += '</tbody>'; content += '</table>'; content += '</div>'; document.getElementById('remoteSQLFilesList').innerHTML = content; if ( ${datatablesEnabled} ) { $('#remoteFilesTable').DataTable(); } } else { var content = '<h5 class="text-danger">Error</h5>'; content += '<pre>'; content += 'XHR Error: Status ' + xhr.status; document.getElementById('remoteSQLFilesList').innerHTML = content; } } } ` } function jsFunctionRemoteSQLFileLoad() { return ` function remoteSQLFileLoad( filename ) { var xhr = new XMLHttpRequest(); xhr.open( 'GET', 'https://suiteql.s3.us-east-1.amazonaws.com/queries/' + filename+ '?nonce=' + new Date().getTime(), true ); xhr.send(); xhr.onload = function() { var content = ''; if( xhr.status === 200 ) { document.getElementById('query').value = xhr.response; queryTextAreaResize(); $('#remoteLoadModal').modal('toggle'); document.getElementById('resultsDiv').style.display = "none"; activeSQLFile.source = 'Remote SQL Library'; activeSQLFile.fileName = filename; activeSQLFile.sql = xhr.response; fileInfoRefresh(); } else { alert( 'XHR Error: Status ' + xhr.status ); } } } ` } function jsFunctionResponseDataCopy() { return ` function responseDataCopy() { var copyText = document.getElementById("responseData"); copyText.select(); document.execCommand("copy"); return false; } ` } function jsFunctionResponseGenerate() { return ` function responseGenerate() { $('#templateHeaderRow').hide(); $('#templateFormRow').hide(); switch ( radioFieldValueGet( 'resultsFormat' ) ) { case 'csv': responseGenerateCSV(); break; case 'json': responseGenerateJSON(); break; case 'pdf': $('#templateHeaderRow').show(); $('#templateFormRow').show(); responseGenerateTable(); break; case 'html': $('#templateHeaderRow').show(); $('#templateFormRow').show(); responseGenerateTable(); break; default: responseGenerateTable(); } } ` } function jsFunctionResponseGenerateCSV() { return ` function responseGenerateCSV() { document.getElementById('nullFormatDiv').style.display = "none"; document.getElementById('hideRowNumsDiv').style.display = "none"; var columnNames = Object.keys( queryResponsePayload.records[0] ); var row = '"' + columnNames.join( '","' ) + '"'; var csv = row + "\\r\\n"; for ( r = 0; r < queryResponsePayload.records.length; r++ ) { var record = queryResponsePayload.records[r]; var values = []; for ( c = 0; c < columnNames.length; c++ ) { var column = columnNames[c]; var value = record[column]; if ( value != null ) { value = value.toString(); } else { value = ''; } values.push( '"' + value + '"' ); } var row = values.join( ',' ); csv += row + "\\r\\n"; } var content = '<h5 style="margin-bottom: 3px; color: #4d5f79; font-weight: 600;">Results</h5>'; content += 'Retrieved ' + queryResponsePayload.records.length + ' of ' + queryResponsePayload.totalRecordCount + ' rows in ' + queryResponsePayload.elapsedTime + 'ms.<br>'; content += '<p>'; content += ' <a href="#" onclick="javascript:responseDataCopy();">Click here</a> to copy the data.'; content += '</p>'; content += '<textarea class="form-control small" id="responseData" name="responseData" rows="25" placeholder="Enter your query here." autofocus style="font-size: 10pt;">' + csv + '</textarea>'; content += '</div>'; document.getElementById('resultsDiv').innerHTML = content; } ` } function jsFunctionResponseGenerateJSON() { return ` function responseGenerateJSON() { document.getElementById('nullFormatDiv').style.display = "none"; document.getElementById('hideRowNumsDiv').style.display = "none"; var content = '<h5 style="margin-bottom: 3px; color: #4d5f79; font-weight: 600;">Results</h5>'; content += 'Retrieved ' + queryResponsePayload.records.length + ' of ' + queryResponsePayload.totalRecordCount + ' rows in ' + queryResponsePayload.elapsedTime + 'ms.<br>'; content += '<p>'; content += ' <a href="#" onclick="javascript:responseDataCopy();">Click here</a> to copy the data.'; content += '</p>'; content += '<textarea class="form-control small" id="responseData" name="responseData" rows="25" placeholder="Enter your query here." autofocus style="font-size: 10pt;">' + JSON.stringify( queryResponsePayload.records, null, 5 ) + '</textarea>'; content += '</div>'; document.getElementById('resultsDiv').innerHTML = content; } ` } function jsFunctionResponseGenerateTable() { return ` function responseGenerateTable() { document.getElementById('nullFormatDiv').style.display = "block"; document.getElementById('hideRowNumsDiv').style.display = "block"; if ( queryResponsePayload.records.length > 0 ) { var columnNames = Object.keys( queryResponsePayload.records[0] ); var startColumn = 0; if ( document.getElementById('hideRowNumbers').checked ) { startColumn = 1; } var thead = '<thead class="thead-light">'; thead += '<tr>'; if ( document.getElementById('hideRowNumbers').checked === false ) { thead += '<th style="text-align: center;">&nbsp;#&nbsp;</th>'; } for ( i = 1; i < columnNames.length; i++ ) { thead += '<th>' + columnNames[i] + '</th>'; } thead += '</tr>'; thead += '</thead>'; var tbody = '<tbody>'; for ( r = 0; r < queryResponsePayload.records.length; r++ ) { tbody += '<tr>'; for ( i = startColumn; i < columnNames.length; i++ ) { var value = queryResponsePayload.records[r][ columnNames[i] ]; if ( value === null ) { var nullFormat = radioFieldValueGet( 'nullFormat' ); if ( nullFormat == 'dimmed' ) { value = '<span style="color: #ccc;">' + value + '</span>'; } else if ( nullFormat == 'blank' ) { value = ''; } else { value = 'null'; } } if ( i > 0 ) { tbody += '<td>' + value + '</td>'; } else { tbody += '<td style="text-align: center;">' + value + '</td>'; } } tbody += '</tr>'; } tbody += '</tbody>'; var content = '<h5 style="margin-bottom: 3px; color: #4d5f79; font-weight: 600;">Results</h5>'; content += 'Retrieved ' + queryResponsePayload.records.length + ' of ' + queryResponsePayload.totalRecordCount + ' rows in ' + queryResponsePayload.elapsedTime + 'ms.<br>'; content += '<div class="table-responsive">'; content += '<table class="table table-sm table-bordered table-hover table-responsive-sm" id="resultsTable">'; content += thead; content += tbody; content += '</table>'; content += '</div>'; document.getElementById('resultsDiv').innerHTML = content; if ( radioFieldValueGet( 'resultsFormat' ) == 'datatable' ) { $('#resultsTable').DataTable(); } } else { document.getElementById('resultsDiv').innerHTML = '<h5 class="text-warning">No Records Were Found</h5>'; } } ` } function jsFunctionReturnAllToggle() { return ` function returnAllToggle() { if ( document.getElementById('returnAll').checked ) { document.getElementById('rowRangeDiv').style.display = "none"; } else { document.getElementById('rowRangeDiv').style.display = "block"; } } ` } function jsFunctionTableDetailsGet() { return ` function tableDetailsGet( tableName ) { document.getElementById('tableInfoColumn').innerHTML = '<h5 style="color: green;">Loading information for ' + tableName + ' table...</h5>'; var url = '/app/recordscatalog/rcendpoint.nl?action=\getRecordTypeDetail&data=' + encodeURI( JSON.stringify( { scriptId: tableName, detailType: 'SS_ANAL' } ) ); var xhr = new XMLHttpRequest(); xhr.open( 'GET', url, true ); xhr.send(); xhr.onload = function() { if( xhr.status === 200 ) { let recordDetail = JSON.parse( xhr.response ).data; content = '<h5 style="color: #000;">' + recordDetail.label + ' Table ("' + tableName + '") Information</h5>'; content += '<h5 style="margin-top: 18px; margin-bottom: 6px; color: #4d5f79; font-weight: 600;">Columns</h5>'; content += '<div class="table-responsive">'; content += '<table class="table table-sm table-bordered table-hover table-responsive-sm" id="tableColumnsTable">'; content += '<thead class="thead-light">'; content += '<tr>'; content += '<th>Label</th>'; content += '<th>Name</th>'; content += '<th>Type</th>'; content += '</tr>'; content += '</thead>'; content += '<tbody>'; for ( i = 0; i < recordDetail.fields.length; i++ ) { var field = recordDetail.fields[i]; if ( field.isColumn ) {; content += '<tr>'; content += '<td>' + field.label + '</td>'; content += '<td>' + field.id + '</td>'; content += '<td>' + field.dataType + '</td>'; content += '</tr>'; }; } content += '</tbody>'; content += '</table>'; content += '</div>'; if ( recordDetail.joins.length > 0 ) { content += '<h5 style="margin-top: 18px; margin-bottom: 6px; color: #4d5f79; font-weight: 600;">Joins</h5>'; content += '<div class="table-responsive">'; content += '<table class="table table-sm table-bordered table-hover table-responsive-sm" id="tableJoinsTable">'; content += '<thead class="thead-light">'; content += '<tr>'; content += '<th>Label</th>'; content += '<th>Table Name</th>'; content += '<th>Cardinality</th>'; content += '<th>Join Pairs</th>'; content += '</tr>'; content += '</thead>'; content += '<tbody>'; for ( i = 0; i < recordDetail.joins.length; i++ ) { var join = recordDetail.joins[i]; content += '<tr>'; content += '<td>' + join.label + '</td>'; content += '<td><a href="#" onclick="javascript:tableDetailsGet( \\'' + join.sourceTargetType.id + '\\' );">' + join.sourceTargetType.id + '</a></td>'; content += '<td>' + join.cardinality + '</td>'; var joinInfo = ""; for ( j = 0; j < join.sourceTargetType.joinPairs.length; j++ ) { var joinPair = join.sourceTargetType.joinPairs[j]; joinInfo += joinPair.label + '<br>'; } content += '<td>' + joinInfo + '</td>'; content += '</tr>'; } content += '</tbody>'; content += '</table>'; content += '</div>'; } let textareaRows = recordDetail.fields.length + 5; content += '<h5 style="margin-top: 18px; margin-bottom: 6px; color: #4d5f79; font-weight: 600;">Sample Query</h5>'; content += '<span style="font-size: 11pt;"><a href="#" onclick="javascript:tableQueryCopy();">Click here</a> to copy the query.</span>'; content += '<textarea class="form-control small" id="tableQuery" name="sampleQuery" rows="' + textareaRows + '" style="font-size: 10pt;">'; content += 'SELECT\\n'; for ( i = 0; i < recordDetail.fields.length; i++ ) { var field = recordDetail.fields[i]; if ( field.isColumn ) { content += '\\t' + tableName + '.' + field.id; if ( ( i + 1 ) < recordDetail.fields.length ) { content += ','; } content += '\\n'; } } content += 'FROM\\n'; content += '\\t' + tableName + '\\n'; content += '</textarea>'; document.getElementById('tableInfoColumn').innerHTML = content; if ( ${datatablesEnabled} ) { $('#tableColumnsTable').DataTable(); $('#tableJoinsTable').DataTable(); } } else { alert( 'Error: ' + xhr.status ); } } } ` } function jsFunctionTableNamesGet() { return ` function tableNamesGet() { var url = '/app/recordscatalog/rcendpoint.nl?action=\getRecordTypes&data=' + encodeURI( JSON.stringify( { structureType: 'FLAT' } ) ); var xhr = new XMLHttpRequest(); xhr.open( 'GET', url, true ); xhr.send(); xhr.onload = function() { if( xhr.status === 200 ) { let recordTypes = JSON.parse( xhr.response ).data; content = '<div class="table-responsive">'; content += '<table class="table table-sm table-bordered table-hover table-responsive-sm" id="tableNamesTable">'; content += '<thead class="thead-light">'; content += '<tr>'; content += '<th>Table</th>'; content += '</tr>'; content += '</thead>'; content += '<tbody>'; for ( i = 0; i < recordTypes.length; i++ ) { content += '<tr>'; content += '<td>'; content += '<a href="#" onclick="javascript:tableDetailsGet( \\'' + recordTypes[i].id + '\\' );" style="font-weight: bold;">' + recordTypes[i].label + '</a><br>'; content += recordTypes[i].id; content += '</td>'; content += '</tr>'; } content += '</tbody>'; content += '</table>'; content += '</div>'; document.getElementById('tablesColumn').innerHTML = content; if ( ${datatablesEnabled} ) { $('#tableNamesTable').DataTable(); } } else { alert( 'Error: ' + xhr.status ); } } } ` } function jsFunctionTableQueryCopy() { return ` function tableQueryCopy() { var copyText = document.getElementById("tableQuery"); copyText.select(); document.execCommand("copy"); return false; } ` } function jsFunctionTablesUIToggle() { return ` function tablesUIToggle() { $('#queryUI').toggle(); $('#tablesUI').toggle(); } ` } function jsFunctionWorkbooksButton() { if ( workbooksEnabled === true ) { return `<button type="button" class="btn btn-sm btn-light" data-toggle="modal" data-target="#workbooksModal">Workbooks</button>` } else { return `` } } function jsFunctionWorkbookLoad() { return ` function workbookLoad( scriptID ) { var requestPayload = { 'function': 'workbookLoad', 'scriptID': scriptID } var xhr = new XMLHttpRequest(); xhr.open( 'POST', '${scriptURL}', true ); xhr.send( JSON.stringify( requestPayload ) ); xhr.onload = function() { if( xhr.status === 200 ) { workbookLoadResponsePayload = JSON.parse( xhr.response ); if ( workbookLoadResponsePayload.error == undefined ) { document.getElementById('query').value = workbookLoadResponsePayload.sql; queryTextAreaResize(); $('#workbooksModal').modal('toggle'); document.getElementById('resultsDiv').style.display = "none"; activeSQLFile.source = 'Workbook ' + scriptID; activeSQLFile.fileName = ''; activeSQLFile.description = ''; activeSQLFile.fileID = ''; activeSQLFile.sql = workbookLoadResponsePayload.sql; fileInfoRefresh(); } else { alert( 'Error: ' + payload.error ); } } else { alert( 'Error: ' + xhr.status ); } } } ` } function jsFunctionWorkbooksListGet() { return ` function workbooksListGet() { document.getElementById('workbooksList').innerHTML = '<h5 style="color: green;">Getting the list of Workbooks...</h5>'; var requestPayload = { 'function': 'workbooksGet' } var xhr = new XMLHttpRequest(); xhr.open( 'POST', '${scriptURL}', true ); xhr.send( JSON.stringify( requestPayload ) ); xhr.onload = function() { var content = ''; if( xhr.status === 200 ) { payload = JSON.parse( xhr.response ); if ( payload.error == undefined ) { content = '<div class="table-responsive">'; content += '<table id="workbooksTable" class="table table-sm table-bordered table-hover table-responsive-sm">'; content += '<thead class="thead-light">'; content += '<tr>'; content += '<th>Name</th>'; content += '<th>Description</th>'; content += '<th>Owner</th>'; content += '<th></th>'; content += '</tr>'; content += '</thead>'; content += '<tbody>'; for ( r = 0; r < payload.records.length; r++ ) { var description = payload.records[r].description; if( description === null ) { description = ''; } content += '<tr>'; content += '<td style="vertical-align: middle;">' + payload.records[r].name + '</td>'; content += '<td style="vertical-align: middle;">' + description + '</td>'; content += '<td style="vertical-align: middle;">' + payload.records[r].owner + '</td>'; content += '<td style="text-align: center; vertical-align: middle;"><button type="button" class="btn btn-sm btn-primary" onclick="workbookLoad(\\'' + payload.records[r].scriptid + '\\');" >Load</button></td>'; content += '</tr>'; } content += '</tbody>'; content += '</table>'; content += '</div>'; document.getElementById('workbooksList').innerHTML = content; if ( ${datatablesEnabled} ) { $('#workbooksTable').DataTable(); } } else { if ( payload.error == 'No Workbooks' ) { content += '<p class="text-danger">No workbooks were found.</p>'; document.getElementById('workbooksList').innerHTML = content; } else { content = '<h5 class="text-danger">Error</h5>'; content += '<pre>'; content += payload.error; content += '</pre>'; document.getElementById('workbooksList').innerHTML = content; } } } else { var content = '<h5 class="text-danger">Error</h5>'; content += '<pre>'; content += 'XHR Error: Status ' + xhr.status; document.getElementById('workbooksList').innerHTML = content; } } } ` } function localLibraryFilesGet( context ) { var responsePayload; var sql = ` SELECT ID, Name, Description FROM File WHERE ( Folder = ? ) ORDER BY Name `; var queryResults = query.runSuiteQL( { query: sql, params: [ queryFolderID ] } ); var records = queryResults.asMappedResults(); if ( records.length > 0 ) { responsePayload = { 'records': records }; } else { responsePayload = { 'error': 'No SQL Files' }; } context.response.write( JSON.stringify( responsePayload, null, 5 ) ); } function queryExecute( context, requestPayload ) { try { var responsePayload; var moreRecords = true; var records = new Array(); var totalRecordCount = 0; var queryParams = new Array(); var paginatedRowBegin = requestPayload.rowBegin; var paginatedRowEnd = requestPayload.rowEnd; let beginTime = new Date().getTime(); do { var paginatedSQL = 'SELECT * FROM ( SELECT ROWNUM AS ROWNUMBER, * FROM (' + requestPayload.query + ' ) ) WHERE ( ROWNUMBER BETWEEN ' + paginatedRowBegin + ' AND ' + paginatedRowEnd + ')'; var queryResults = query.runSuiteQL( { query: paginatedSQL, params: queryParams } ).asMappedResults(); records = records.concat( queryResults ); if ( queryResults.length < 5000 ) { moreRecords = false; } paginatedRowBegin = paginatedRowBegin + 5000; } while ( moreRecords ); let elapsedTime = ( new Date().getTime() - beginTime ) ; if ( records.length > 0 ) { var paginatedSQL = 'SELECT COUNT(*) AS TotalRecordCount FROM ( ' + requestPayload.query + ' )'; var queryResults = query.runSuiteQL( { query: paginatedSQL, params: queryParams } ).asMappedResults(); var totalRecordCount = queryResults[0].totalrecordcount; } responsePayload = { 'records': records, 'totalRecordCount': totalRecordCount, 'elapsedTime': elapsedTime } } catch( e ) { log.error( { title: 'queryExecute Error', details: e } ); responsePayload = { 'error': e } } context.response.write( JSON.stringify( responsePayload, null, 5 ) ); } function sqlFileExists( context, requestPayload ) { var responsePayload; var sql = ` SELECT ID FROM File WHERE ( Folder = ? ) AND ( Name = ? ) `; var queryResults = query.runSuiteQL( { query: sql, params: [ queryFolderID, requestPayload.filename ] } ); var records = queryResults.asMappedResults(); if ( records.length > 0 ) { responsePayload = { 'exists': true }; } else { responsePayload = { 'exists': false }; } context.response.write( JSON.stringify( responsePayload, null, 5 ) ); } function sqlFileLoad( context, requestPayload ) { var responsePayload; try { var fileObj = file.load( { id: requestPayload.fileID } ); responsePayload = {} responsePayload.file = fileObj; responsePayload.sql = fileObj.getContents(); } catch( e ) { log.error( { title: 'sqlFileLoad Error', details: e } ); responsePayload = { 'error': e } } context.response.write( JSON.stringify( responsePayload, null, 5 ) ); } function sqlFileSave( context, requestPayload ) { var responsePayload; try { var fileObj = file.create( { name: requestPayload.filename, contents: requestPayload.contents, description: requestPayload.description, fileType: file.Type.PLAINTEXT, folder: queryFolderID, isOnline: false } ); var fileID = fileObj.save(); responsePayload = {} responsePayload.fileID = fileID; } catch( e ) { log.error( { title: 'sqlFileSave Error', details: e } ); responsePayload = { 'error': e } } context.response.write( JSON.stringify( responsePayload, null, 5 ) ); } function toolLatestVersionGet() { try { let httpsResponse = https.get( { url: 'https://suiteql.s3.us-east-1.amazonaws.com/query-tool/index.json' } ); let index = JSON.parse( httpsResponse.body ); return index[0]; } catch (e) { log.error( { title: 'toolLatestVersionGet - https error', details: e } ); return null; } } function toolUpgrade( context ) { try { let sql = ` SELECT SuiteLet.ID, SuiteLet.ScriptFile, File.Folder FROM SuiteLet INNER JOIN File ON ( File.ID = SuiteLet.ScriptFile ) WHERE ( SuiteLet.ScriptID = ? ) `; let queryResults = query.runSuiteQL( { query: sql, params: [ runtime.getCurrentScript().id ] } ); let records = queryResults.asMappedResults(); let scriptRecord = records[0]; let httpsResponse = https.get( { url: 'https://suiteql.s3.us-east-1.amazonaws.com/query-tool/' + toolLatestVersion.fileName } ); var fileObj = file.create( { name: toolLatestVersion.fileName, contents: httpsResponse.body, description: 'SuiteQL Query Tool v' + toolLatestVersion.version, fileType: file.Type.JAVASCRIPT, folder: scriptRecord.folder, isOnline: false } ); var fileID = fileObj.save(); var id = record.submitFields( { type: record.Type.SUITELET, id: scriptRecord.id, values: { scriptfile: fileID } } ); return true; } catch (e) { log.error( { title: 'toolUpgrade - error', details: e } ); return false; } } function workbookLoad( context, requestPayload ) { var responsePayload; try { var loadedQuery = query.load( { id: requestPayload.scriptID } ); responsePayload = {} responsePayload.sql = loadedQuery.toSuiteQL().query; } catch( e ) { log.error( { title: 'workbookLoad Error', details: e } ); responsePayload = { 'error': e } } context.response.write( JSON.stringify( responsePayload, null, 5 ) ); } function workbooksGet( context ) { var responsePayload; var sql = ` SELECT ScriptID, Name, Description, BUILTIN.DF( Owner ) AS Owner FROM UsrSavedSearch ORDER BY Name `; var queryResults = query.runSuiteQL( { query: sql, params: [] } ); var records = queryResults.asMappedResults(); if ( records.length > 0 ) { responsePayload = { 'records': records }; } else { responsePayload = { 'error': 'No Workbooks' }; } context.response.write( JSON.stringify( responsePayload, null, 5 ) ); }
/** * upload.js * @description Upload Job Document to NetSuite * @module CLV/userevent/document/upload * @NApiVersion 2.x * @NScriptType UserEventScript * @NAmdConfig /SuiteScripts/cloverfield/config.json * @author Miquel Brazil <miquel@leprechaunpromotions.com> */ define(['CLV/services/runscope'], function (runscope) { function inspect (context) { var rs = runscope.init({ trigger: 'https://api.runscope.com/radar/b7c869d4-45bc-4f9c-b92d-0bb4d9e7380b/trigger', inspect: 'https://api.runscope.com/radar/inbound/3204304f-4c40-4e03-a6ad-11f0e60a0dfb' }); rs.trigger(); rs.inspect(context); } return { beforeLoad: inspect } } );
1,185
[{"tag": "EMAIL", "value": "miquel@leprechaunpromotions.com", "start": 237, "end": 268}]
true
1
/** * upload.js * @description Upload Job Document to NetSuite * @module CLV/userevent/document/upload * @NApiVersion 2.x * @NScriptType UserEventScript * @NAmdConfig /SuiteScripts/cloverfield/config.json * @author Miquel Brazil <anpch@example.com> */ define(['CLV/services/runscope'], function (runscope) { function inspect (context) { var rs = runscope.init({ trigger: 'https://api.runscope.com/radar/b7c869d4-45bc-4f9c-b92d-0bb4d9e7380b/trigger', inspect: 'https://api.runscope.com/radar/inbound/3204304f-4c40-4e03-a6ad-11f0e60a0dfb' }); rs.trigger(); rs.inspect(context); } return { beforeLoad: inspect } } );
true
/** * upload.js * @description Upload Job Document to NetSuite * @module CLV/userevent/document/upload * @NApiVersion 2.x * @NScriptType UserEventScript * @NAmdConfig /SuiteScripts/cloverfield/config.json * @author Miquel Brazil <PI:EMAIL:anpch@example.comEND_PI> */ define(['CLV/services/runscope'], function (runscope) { function inspect (context) { var rs = runscope.init({ trigger: 'https://api.runscope.com/radar/b7c869d4-45bc-4f9c-b92d-0bb4d9e7380b/trigger', inspect: 'https://api.runscope.com/radar/inbound/3204304f-4c40-4e03-a6ad-11f0e60a0dfb' }); rs.trigger(); rs.inspect(context); } return { beforeLoad: inspect } } );
/** * REST API for R+L CARRIERS & ODFL * * @NApiVersion 2.x * @NScriptType Restlet * @author trungpv <trung@lexor.com> */ define(['N/https', 'N/search', 'N/xml', '/SuiteScripts/Module/Utils'], function( https, search, xml, _U ) { /** VARS **/ const ADDITIONAL_FEES = 10; // 10% const API_KEY = 'xxx'; const USERNAME = 'xxx'; const PASSWORD = 'xxx'; const CUS_ACCOUNT = 'xxx'; /** * POST * @param {*} context */ function postAction(context) { var result = {}; result.success = false; try { const validation = doValidation( [context.locationId, context.customer, context.weight], ['locationId', 'customer', 'weight'], 'POST' ); if (validation.length === 0) { const originAddress = search.lookupFields({ type: search.Type.LOCATION, id: context.locationId, columns: ['city', 'country', 'zip', 'state'] }); // Set countryCode if (originAddress.country === 'US') { originAddress.countryCode = 'USA'; } else if (originAddress.country === 'CA') { originAddress.countryCode = 'CAN'; } // Check State if (originAddress.state.length > 2) { originAddress.state = _U.abbrRegion(originAddress.state, 'abbr'); } if (context.customer.state.length > 2) { context.customer.state = _U.abbrRegion(context.customer.state, 'abbr'); } const freightRateRL = getFreightRateRL(originAddress, context.customer, context.weight); const freightRateODFL = getFreightRateODFL(originAddress, context.customer, context.weight); result.data = [ { code: 'RL_CARRIERS', total: freightRateRL }, { code: 'ODFL', total: freightRateODFL } ]; result.success = true; result.message = 'Success!'; } else { result.message = 'Something went wrong with your params.'; result.errors = validation; } } catch (err) { result.message = err.message; } return JSON.stringify(result); } /** HEPPER FUNCTIONS **/ /** * Validation params * @param {*} args * @param {*} argNames * @param {*} methodName */ function doValidation(args, argNames, methodName) { const result = []; for (var i = 0; i < args.length; i++) { if (!args[i] && args[i] !== 0) { result.push('Missing a required argument: [' + argNames[i] + '] for method: ' + methodName); } } return result; } /** * Build Payload Shipping Method https://api.rlcarriers.com/1.0.3/RateQuoteService.asmx */ function requestPayloadRL(origin, destination, weight) { var payload = '<soapenv:Envelope xmlns:soapenv="http://schemas.xmlsoap.org/soap/envelope/" xmlns:rlc="http://www.rlcarriers.com/">'; payload += '<soapenv:Header/>'; payload += '<soapenv:Body>'; payload += ' <rlc:GetRateQuote>'; payload += ' <rlc:APIKey>' + API_KEY + '</rlc:APIKey>'; payload += ' <rlc:request>'; payload += ' <rlc:QuoteType>Domestic</rlc:QuoteType>'; payload += ' <rlc:CODAmount>0</rlc:CODAmount>'; payload += ' <rlc:Origin>'; payload += ' <rlc:City>' + origin.city + '</rlc:City>'; payload += ' <rlc:StateOrProvince>' + origin.state + '</rlc:StateOrProvince>'; payload += ' <rlc:ZipOrPostalCode>' + origin.zip + '</rlc:ZipOrPostalCode>'; payload += ' <rlc:CountryCode>' + origin.countryCode + '</rlc:CountryCode>'; payload += ' </rlc:Origin>'; payload += ' <rlc:Destination>'; payload += ' <rlc:City>' + destination.city + '</rlc:City>'; payload += ' <rlc:StateOrProvince>' + destination.state + '</rlc:StateOrProvince>'; payload += ' <rlc:ZipOrPostalCode>' + destination.zip + '</rlc:ZipOrPostalCode>'; payload += ' <rlc:CountryCode>' + destination.countryCode + '</rlc:CountryCode>'; payload += ' </rlc:Destination>'; payload += ' <rlc:Items>'; payload += ' <rlc:Item>'; payload += ' <rlc:Class>200.0</rlc:Class>'; payload += ' <rlc:Weight>' + weight + '</rlc:Weight>'; payload += ' <rlc:Width>0</rlc:Width>'; payload += ' <rlc:Height>0</rlc:Height>'; payload += ' <rlc:Length>0</rlc:Length>'; payload += ' </rlc:Item>'; payload += ' </rlc:Items>'; payload += ' <rlc:DeclaredValue>0</rlc:DeclaredValue>'; payload += ' <rlc:Accessorials></rlc:Accessorials>'; payload += ' <rlc:OverDimensionList></rlc:OverDimensionList>'; payload += ' <rlc:Pallets></rlc:Pallets>'; payload += ' </rlc:request>'; payload += ' </rlc:GetRateQuote>'; payload += ' </soapenv:Body>'; payload += '</soapenv:Envelope>'; return payload; } /** * get Freight Rate RL * @param {*} origin * @param {*} destination * @param {*} weight */ function getFreightRateRL(origin, destination, weight) { const payload = requestPayloadRL(origin, destination, weight); try { var res = https.post({ url: 'https://api.rlcarriers.com/1.0.3/RateQuoteService.asmx', body: payload, headers: { 'Content-Type': 'text/xml; charset=UTF-8' } }); if (res.code === 200) { var resXML = xml.Parser.fromString({ text: res.body }); var ServiceLevels = resXML.getElementsByTagName({ tagName: 'ServiceLevels' }); if (ServiceLevels.length > 0) { var NetCharge = ServiceLevels[0].getElementsByTagName({ tagName: 'NetCharge' }); if (NetCharge.length > 0) { var nCharge = NetCharge[0].textContent.replace('$', '').replace(',', ''); nCharge = parseFloat(nCharge) + parseFloat(nCharge) * (ADDITIONAL_FEES / 100); nCharge = parseFloat(nCharge).toFixed(2); return nCharge; } } } } catch (error) { return 0; } return 0; } /** * Build Payload Shipping Method https://www.odfl.com */ function requestPayloadODFL(origin, destination, weight) { var payload = '<soapenv:Envelope xmlns:soapenv="http://schemas.xmlsoap.org/soap/envelope/" xmlns:myr="http://myRate.ws.odfl.com/">'; payload += ' <soapenv:Header/>'; payload += ' <soapenv:Body>'; payload += ' <myr:getLTLRateEstimate>'; payload += ' <!--Optional:-->'; payload += ' <arg0>'; payload += ' <destinationCountry>' + destination.countryCode + '</destinationCountry> '; payload += ' <destinationPostalCode>' + destination.zip + '</destinationPostalCode>'; payload += ' <destinationCity>' + destination.city + '</destinationCity> '; payload += ' <destinationState>' + destination.state + '</destinationState> '; payload += ' <freightItems> '; payload += ' <ratedClass>200</ratedClass> '; payload += ' <weight>' + weight + '</weight> '; payload += ' </freightItems> '; payload += ' <odfl4MePassword>' + PASSWORD + '</odfl4MePassword> '; payload += ' <odfl4MeUser>' + USERNAME + '</odfl4MeUser>'; payload += ' <odflCustomerAccount>' + CUS_ACCOUNT + '</odflCustomerAccount> '; payload += ' <originCountry>' + origin.countryCode + '</originCountry> '; payload += ' <originPostalCode>' + origin.zip + '</originPostalCode>'; payload += ' <originCity>' + origin.city + '</originCity> '; payload += ' <originState>' + origin.state + '</originState> '; payload += ' <requestReferenceNumber>false</requestReferenceNumber> '; payload += ' </arg0>'; payload += ' </myr:getLTLRateEstimate>'; payload += ' </soapenv:Body>'; payload += '</soapenv:Envelope>'; return payload; } /** * get Freight Rate * @param {*} origin * @param {*} destination * @param {*} weight */ function getFreightRateODFL(origin, destination, weight) { const payload = requestPayloadODFL(origin, destination, weight); try { var res = https.post({ url: 'https://www.odfl.com/wsRate_v6/RateService?xsd=1', body: payload, headers: { 'Content-Type': 'text/xml; charset=UTF-8' } }); if (res.code === 200) { var resXML = xml.Parser.fromString({ text: res.body }); var netFreightCharge = resXML.getElementsByTagName({ tagName: 'netFreightCharge' }); if (netFreightCharge.length > 0) { var nCharge = netFreightCharge[0].textContent; nCharge = parseFloat(nCharge) + parseFloat(nCharge) * (ADDITIONAL_FEES / 100); nCharge = parseFloat(nCharge).toFixed(2); return nCharge; } } } catch (error) { return 0; } return 0; } /** * Export Events */ var exports = {}; exports.post = postAction; return exports; });
169
[{"tag": "EMAIL", "value": "trung@lexor.com", "start": 107, "end": 122}]
true
1
/** * REST API for R+L CARRIERS & ODFL * * @NApiVersion 2.x * @NScriptType Restlet * @author trungpv <nnheo@example.com> */ define(['N/https', 'N/search', 'N/xml', '/SuiteScripts/Module/Utils'], function( https, search, xml, _U ) { /** VARS **/ const ADDITIONAL_FEES = 10; // 10% const API_KEY = 'xxx'; const USERNAME = 'xxx'; const PASSWORD = 'xxx'; const CUS_ACCOUNT = 'xxx'; /** * POST * @param {*} context */ function postAction(context) { var result = {}; result.success = false; try { const validation = doValidation( [context.locationId, context.customer, context.weight], ['locationId', 'customer', 'weight'], 'POST' ); if (validation.length === 0) { const originAddress = search.lookupFields({ type: search.Type.LOCATION, id: context.locationId, columns: ['city', 'country', 'zip', 'state'] }); // Set countryCode if (originAddress.country === 'US') { originAddress.countryCode = 'USA'; } else if (originAddress.country === 'CA') { originAddress.countryCode = 'CAN'; } // Check State if (originAddress.state.length > 2) { originAddress.state = _U.abbrRegion(originAddress.state, 'abbr'); } if (context.customer.state.length > 2) { context.customer.state = _U.abbrRegion(context.customer.state, 'abbr'); } const freightRateRL = getFreightRateRL(originAddress, context.customer, context.weight); const freightRateODFL = getFreightRateODFL(originAddress, context.customer, context.weight); result.data = [ { code: 'RL_CARRIERS', total: freightRateRL }, { code: 'ODFL', total: freightRateODFL } ]; result.success = true; result.message = 'Success!'; } else { result.message = 'Something went wrong with your params.'; result.errors = validation; } } catch (err) { result.message = err.message; } return JSON.stringify(result); } /** HEPPER FUNCTIONS **/ /** * Validation params * @param {*} args * @param {*} argNames * @param {*} methodName */ function doValidation(args, argNames, methodName) { const result = []; for (var i = 0; i < args.length; i++) { if (!args[i] && args[i] !== 0) { result.push('Missing a required argument: [' + argNames[i] + '] for method: ' + methodName); } } return result; } /** * Build Payload Shipping Method https://api.rlcarriers.com/1.0.3/RateQuoteService.asmx */ function requestPayloadRL(origin, destination, weight) { var payload = '<soapenv:Envelope xmlns:soapenv="http://schemas.xmlsoap.org/soap/envelope/" xmlns:rlc="http://www.rlcarriers.com/">'; payload += '<soapenv:Header/>'; payload += '<soapenv:Body>'; payload += ' <rlc:GetRateQuote>'; payload += ' <rlc:APIKey>' + API_KEY + '</rlc:APIKey>'; payload += ' <rlc:request>'; payload += ' <rlc:QuoteType>Domestic</rlc:QuoteType>'; payload += ' <rlc:CODAmount>0</rlc:CODAmount>'; payload += ' <rlc:Origin>'; payload += ' <rlc:City>' + origin.city + '</rlc:City>'; payload += ' <rlc:StateOrProvince>' + origin.state + '</rlc:StateOrProvince>'; payload += ' <rlc:ZipOrPostalCode>' + origin.zip + '</rlc:ZipOrPostalCode>'; payload += ' <rlc:CountryCode>' + origin.countryCode + '</rlc:CountryCode>'; payload += ' </rlc:Origin>'; payload += ' <rlc:Destination>'; payload += ' <rlc:City>' + destination.city + '</rlc:City>'; payload += ' <rlc:StateOrProvince>' + destination.state + '</rlc:StateOrProvince>'; payload += ' <rlc:ZipOrPostalCode>' + destination.zip + '</rlc:ZipOrPostalCode>'; payload += ' <rlc:CountryCode>' + destination.countryCode + '</rlc:CountryCode>'; payload += ' </rlc:Destination>'; payload += ' <rlc:Items>'; payload += ' <rlc:Item>'; payload += ' <rlc:Class>200.0</rlc:Class>'; payload += ' <rlc:Weight>' + weight + '</rlc:Weight>'; payload += ' <rlc:Width>0</rlc:Width>'; payload += ' <rlc:Height>0</rlc:Height>'; payload += ' <rlc:Length>0</rlc:Length>'; payload += ' </rlc:Item>'; payload += ' </rlc:Items>'; payload += ' <rlc:DeclaredValue>0</rlc:DeclaredValue>'; payload += ' <rlc:Accessorials></rlc:Accessorials>'; payload += ' <rlc:OverDimensionList></rlc:OverDimensionList>'; payload += ' <rlc:Pallets></rlc:Pallets>'; payload += ' </rlc:request>'; payload += ' </rlc:GetRateQuote>'; payload += ' </soapenv:Body>'; payload += '</soapenv:Envelope>'; return payload; } /** * get Freight Rate RL * @param {*} origin * @param {*} destination * @param {*} weight */ function getFreightRateRL(origin, destination, weight) { const payload = requestPayloadRL(origin, destination, weight); try { var res = https.post({ url: 'https://api.rlcarriers.com/1.0.3/RateQuoteService.asmx', body: payload, headers: { 'Content-Type': 'text/xml; charset=UTF-8' } }); if (res.code === 200) { var resXML = xml.Parser.fromString({ text: res.body }); var ServiceLevels = resXML.getElementsByTagName({ tagName: 'ServiceLevels' }); if (ServiceLevels.length > 0) { var NetCharge = ServiceLevels[0].getElementsByTagName({ tagName: 'NetCharge' }); if (NetCharge.length > 0) { var nCharge = NetCharge[0].textContent.replace('$', '').replace(',', ''); nCharge = parseFloat(nCharge) + parseFloat(nCharge) * (ADDITIONAL_FEES / 100); nCharge = parseFloat(nCharge).toFixed(2); return nCharge; } } } } catch (error) { return 0; } return 0; } /** * Build Payload Shipping Method https://www.odfl.com */ function requestPayloadODFL(origin, destination, weight) { var payload = '<soapenv:Envelope xmlns:soapenv="http://schemas.xmlsoap.org/soap/envelope/" xmlns:myr="http://myRate.ws.odfl.com/">'; payload += ' <soapenv:Header/>'; payload += ' <soapenv:Body>'; payload += ' <myr:getLTLRateEstimate>'; payload += ' <!--Optional:-->'; payload += ' <arg0>'; payload += ' <destinationCountry>' + destination.countryCode + '</destinationCountry> '; payload += ' <destinationPostalCode>' + destination.zip + '</destinationPostalCode>'; payload += ' <destinationCity>' + destination.city + '</destinationCity> '; payload += ' <destinationState>' + destination.state + '</destinationState> '; payload += ' <freightItems> '; payload += ' <ratedClass>200</ratedClass> '; payload += ' <weight>' + weight + '</weight> '; payload += ' </freightItems> '; payload += ' <odfl4MePassword>' + PASSWORD + '</odfl4MePassword> '; payload += ' <odfl4MeUser>' + USERNAME + '</odfl4MeUser>'; payload += ' <odflCustomerAccount>' + CUS_ACCOUNT + '</odflCustomerAccount> '; payload += ' <originCountry>' + origin.countryCode + '</originCountry> '; payload += ' <originPostalCode>' + origin.zip + '</originPostalCode>'; payload += ' <originCity>' + origin.city + '</originCity> '; payload += ' <originState>' + origin.state + '</originState> '; payload += ' <requestReferenceNumber>false</requestReferenceNumber> '; payload += ' </arg0>'; payload += ' </myr:getLTLRateEstimate>'; payload += ' </soapenv:Body>'; payload += '</soapenv:Envelope>'; return payload; } /** * get Freight Rate * @param {*} origin * @param {*} destination * @param {*} weight */ function getFreightRateODFL(origin, destination, weight) { const payload = requestPayloadODFL(origin, destination, weight); try { var res = https.post({ url: 'https://www.odfl.com/wsRate_v6/RateService?xsd=1', body: payload, headers: { 'Content-Type': 'text/xml; charset=UTF-8' } }); if (res.code === 200) { var resXML = xml.Parser.fromString({ text: res.body }); var netFreightCharge = resXML.getElementsByTagName({ tagName: 'netFreightCharge' }); if (netFreightCharge.length > 0) { var nCharge = netFreightCharge[0].textContent; nCharge = parseFloat(nCharge) + parseFloat(nCharge) * (ADDITIONAL_FEES / 100); nCharge = parseFloat(nCharge).toFixed(2); return nCharge; } } } catch (error) { return 0; } return 0; } /** * Export Events */ var exports = {}; exports.post = postAction; return exports; });
true
/** * REST API for R+L CARRIERS & ODFL * * @NApiVersion 2.x * @NScriptType Restlet * @author trungpv <PI:EMAIL:nnheo@example.comEND_PI> */ define(['N/https', 'N/search', 'N/xml', '/SuiteScripts/Module/Utils'], function( https, search, xml, _U ) { /** VARS **/ const ADDITIONAL_FEES = 10; // 10% const API_KEY = 'xxx'; const USERNAME = 'xxx'; const PASSWORD = 'xxx'; const CUS_ACCOUNT = 'xxx'; /** * POST * @param {*} context */ function postAction(context) { var result = {}; result.success = false; try { const validation = doValidation( [context.locationId, context.customer, context.weight], ['locationId', 'customer', 'weight'], 'POST' ); if (validation.length === 0) { const originAddress = search.lookupFields({ type: search.Type.LOCATION, id: context.locationId, columns: ['city', 'country', 'zip', 'state'] }); // Set countryCode if (originAddress.country === 'US') { originAddress.countryCode = 'USA'; } else if (originAddress.country === 'CA') { originAddress.countryCode = 'CAN'; } // Check State if (originAddress.state.length > 2) { originAddress.state = _U.abbrRegion(originAddress.state, 'abbr'); } if (context.customer.state.length > 2) { context.customer.state = _U.abbrRegion(context.customer.state, 'abbr'); } const freightRateRL = getFreightRateRL(originAddress, context.customer, context.weight); const freightRateODFL = getFreightRateODFL(originAddress, context.customer, context.weight); result.data = [ { code: 'RL_CARRIERS', total: freightRateRL }, { code: 'ODFL', total: freightRateODFL } ]; result.success = true; result.message = 'Success!'; } else { result.message = 'Something went wrong with your params.'; result.errors = validation; } } catch (err) { result.message = err.message; } return JSON.stringify(result); } /** HEPPER FUNCTIONS **/ /** * Validation params * @param {*} args * @param {*} argNames * @param {*} methodName */ function doValidation(args, argNames, methodName) { const result = []; for (var i = 0; i < args.length; i++) { if (!args[i] && args[i] !== 0) { result.push('Missing a required argument: [' + argNames[i] + '] for method: ' + methodName); } } return result; } /** * Build Payload Shipping Method https://api.rlcarriers.com/1.0.3/RateQuoteService.asmx */ function requestPayloadRL(origin, destination, weight) { var payload = '<soapenv:Envelope xmlns:soapenv="http://schemas.xmlsoap.org/soap/envelope/" xmlns:rlc="http://www.rlcarriers.com/">'; payload += '<soapenv:Header/>'; payload += '<soapenv:Body>'; payload += ' <rlc:GetRateQuote>'; payload += ' <rlc:APIKey>' + API_KEY + '</rlc:APIKey>'; payload += ' <rlc:request>'; payload += ' <rlc:QuoteType>Domestic</rlc:QuoteType>'; payload += ' <rlc:CODAmount>0</rlc:CODAmount>'; payload += ' <rlc:Origin>'; payload += ' <rlc:City>' + origin.city + '</rlc:City>'; payload += ' <rlc:StateOrProvince>' + origin.state + '</rlc:StateOrProvince>'; payload += ' <rlc:ZipOrPostalCode>' + origin.zip + '</rlc:ZipOrPostalCode>'; payload += ' <rlc:CountryCode>' + origin.countryCode + '</rlc:CountryCode>'; payload += ' </rlc:Origin>'; payload += ' <rlc:Destination>'; payload += ' <rlc:City>' + destination.city + '</rlc:City>'; payload += ' <rlc:StateOrProvince>' + destination.state + '</rlc:StateOrProvince>'; payload += ' <rlc:ZipOrPostalCode>' + destination.zip + '</rlc:ZipOrPostalCode>'; payload += ' <rlc:CountryCode>' + destination.countryCode + '</rlc:CountryCode>'; payload += ' </rlc:Destination>'; payload += ' <rlc:Items>'; payload += ' <rlc:Item>'; payload += ' <rlc:Class>200.0</rlc:Class>'; payload += ' <rlc:Weight>' + weight + '</rlc:Weight>'; payload += ' <rlc:Width>0</rlc:Width>'; payload += ' <rlc:Height>0</rlc:Height>'; payload += ' <rlc:Length>0</rlc:Length>'; payload += ' </rlc:Item>'; payload += ' </rlc:Items>'; payload += ' <rlc:DeclaredValue>0</rlc:DeclaredValue>'; payload += ' <rlc:Accessorials></rlc:Accessorials>'; payload += ' <rlc:OverDimensionList></rlc:OverDimensionList>'; payload += ' <rlc:Pallets></rlc:Pallets>'; payload += ' </rlc:request>'; payload += ' </rlc:GetRateQuote>'; payload += ' </soapenv:Body>'; payload += '</soapenv:Envelope>'; return payload; } /** * get Freight Rate RL * @param {*} origin * @param {*} destination * @param {*} weight */ function getFreightRateRL(origin, destination, weight) { const payload = requestPayloadRL(origin, destination, weight); try { var res = https.post({ url: 'https://api.rlcarriers.com/1.0.3/RateQuoteService.asmx', body: payload, headers: { 'Content-Type': 'text/xml; charset=UTF-8' } }); if (res.code === 200) { var resXML = xml.Parser.fromString({ text: res.body }); var ServiceLevels = resXML.getElementsByTagName({ tagName: 'ServiceLevels' }); if (ServiceLevels.length > 0) { var NetCharge = ServiceLevels[0].getElementsByTagName({ tagName: 'NetCharge' }); if (NetCharge.length > 0) { var nCharge = NetCharge[0].textContent.replace('$', '').replace(',', ''); nCharge = parseFloat(nCharge) + parseFloat(nCharge) * (ADDITIONAL_FEES / 100); nCharge = parseFloat(nCharge).toFixed(2); return nCharge; } } } } catch (error) { return 0; } return 0; } /** * Build Payload Shipping Method https://www.odfl.com */ function requestPayloadODFL(origin, destination, weight) { var payload = '<soapenv:Envelope xmlns:soapenv="http://schemas.xmlsoap.org/soap/envelope/" xmlns:myr="http://myRate.ws.odfl.com/">'; payload += ' <soapenv:Header/>'; payload += ' <soapenv:Body>'; payload += ' <myr:getLTLRateEstimate>'; payload += ' <!--Optional:-->'; payload += ' <arg0>'; payload += ' <destinationCountry>' + destination.countryCode + '</destinationCountry> '; payload += ' <destinationPostalCode>' + destination.zip + '</destinationPostalCode>'; payload += ' <destinationCity>' + destination.city + '</destinationCity> '; payload += ' <destinationState>' + destination.state + '</destinationState> '; payload += ' <freightItems> '; payload += ' <ratedClass>200</ratedClass> '; payload += ' <weight>' + weight + '</weight> '; payload += ' </freightItems> '; payload += ' <odfl4MePassword>' + PASSWORD + '</odfl4MePassword> '; payload += ' <odfl4MeUser>' + USERNAME + '</odfl4MeUser>'; payload += ' <odflCustomerAccount>' + CUS_ACCOUNT + '</odflCustomerAccount> '; payload += ' <originCountry>' + origin.countryCode + '</originCountry> '; payload += ' <originPostalCode>' + origin.zip + '</originPostalCode>'; payload += ' <originCity>' + origin.city + '</originCity> '; payload += ' <originState>' + origin.state + '</originState> '; payload += ' <requestReferenceNumber>false</requestReferenceNumber> '; payload += ' </arg0>'; payload += ' </myr:getLTLRateEstimate>'; payload += ' </soapenv:Body>'; payload += '</soapenv:Envelope>'; return payload; } /** * get Freight Rate * @param {*} origin * @param {*} destination * @param {*} weight */ function getFreightRateODFL(origin, destination, weight) { const payload = requestPayloadODFL(origin, destination, weight); try { var res = https.post({ url: 'https://www.odfl.com/wsRate_v6/RateService?xsd=1', body: payload, headers: { 'Content-Type': 'text/xml; charset=UTF-8' } }); if (res.code === 200) { var resXML = xml.Parser.fromString({ text: res.body }); var netFreightCharge = resXML.getElementsByTagName({ tagName: 'netFreightCharge' }); if (netFreightCharge.length > 0) { var nCharge = netFreightCharge[0].textContent; nCharge = parseFloat(nCharge) + parseFloat(nCharge) * (ADDITIONAL_FEES / 100); nCharge = parseFloat(nCharge).toFixed(2); return nCharge; } } } catch (error) { return 0; } return 0; } /** * Export Events */ var exports = {}; exports.post = postAction; return exports; });
/// <reference path='../lib/N/scriptcontext.js' /> /** *@NApiVersion 2.x *@NScriptType ScheduledScript */ 'use strict'; define(['N/search', 'N/record', 'N/email', 'N/runtime'], function (search, record, email, runtime) { /** * Runs a search on the sales orders created today and fulfill them. * @param {N.scriptContext.SS} context */ function execute(context) { if (context.type !== context.InvocationType.ON_DEMAND) { return; } var searchId = runtime.getCurrentScript().getParameter('custscript_searchid'); try { search.load({ id: searchId }).run().each(function (result) { log.debug('transforming so :' + result.id + ' to item fulfillment'); var fulfillmentRecord = record.transform({ fromType: record.Type.SALES_ORDER, fromId: result.id, toType: record.Type.ITEM_FULFILLMENT, isDynamic: false }); var lineCount = fulfillmentRecord.getLineCount('item'); for (var i = 0; i < lineCount; i += 1) { fulfillmentRecord.setSublistValue('item', 'location', i, 1); } var fulfillmentId = fulfillmentRecord.save(); var so = record.load({ type: record.Type.SALES_ORDER, id: result.id }); so.setValue('memo', fulfillmentId); so.save(); return true; }); } catch (e) { var subject = 'Fatal Error: Unable to transform salesorder to item fulfillment!'; var authorId = -5; var recipientEmail = 'notify@company.com'; email.send({ author: authorId, recipients: recipientEmail, subject: subject, body: 'Fatal error occurred in script: ' + runtime.getCurrentScript().id + '\n\n' + JSON.stringify(e) }); } } return { execute: execute }; });
570
[{"tag": "EMAIL", "value": "notify@company.com", "start": 1955, "end": 1973}]
true
1
/// <reference path='../lib/N/scriptcontext.js' /> /** *@NApiVersion 2.x *@NScriptType ScheduledScript */ 'use strict'; define(['N/search', 'N/record', 'N/email', 'N/runtime'], function (search, record, email, runtime) { /** * Runs a search on the sales orders created today and fulfill them. * @param {N.scriptContext.SS} context */ function execute(context) { if (context.type !== context.InvocationType.ON_DEMAND) { return; } var searchId = runtime.getCurrentScript().getParameter('custscript_searchid'); try { search.load({ id: searchId }).run().each(function (result) { log.debug('transforming so :' + result.id + ' to item fulfillment'); var fulfillmentRecord = record.transform({ fromType: record.Type.SALES_ORDER, fromId: result.id, toType: record.Type.ITEM_FULFILLMENT, isDynamic: false }); var lineCount = fulfillmentRecord.getLineCount('item'); for (var i = 0; i < lineCount; i += 1) { fulfillmentRecord.setSublistValue('item', 'location', i, 1); } var fulfillmentId = fulfillmentRecord.save(); var so = record.load({ type: record.Type.SALES_ORDER, id: result.id }); so.setValue('memo', fulfillmentId); so.save(); return true; }); } catch (e) { var subject = 'Fatal Error: Unable to transform salesorder to item fulfillment!'; var authorId = -5; var recipientEmail = 'anpch@example.com'; email.send({ author: authorId, recipients: recipientEmail, subject: subject, body: 'Fatal error occurred in script: ' + runtime.getCurrentScript().id + '\n\n' + JSON.stringify(e) }); } } return { execute: execute }; });
true
/// <reference path='../lib/N/scriptcontext.js' /> /** *@NApiVersion 2.x *@NScriptType ScheduledScript */ 'use strict'; define(['N/search', 'N/record', 'N/email', 'N/runtime'], function (search, record, email, runtime) { /** * Runs a search on the sales orders created today and fulfill them. * @param {N.scriptContext.SS} context */ function execute(context) { if (context.type !== context.InvocationType.ON_DEMAND) { return; } var searchId = runtime.getCurrentScript().getParameter('custscript_searchid'); try { search.load({ id: searchId }).run().each(function (result) { log.debug('transforming so :' + result.id + ' to item fulfillment'); var fulfillmentRecord = record.transform({ fromType: record.Type.SALES_ORDER, fromId: result.id, toType: record.Type.ITEM_FULFILLMENT, isDynamic: false }); var lineCount = fulfillmentRecord.getLineCount('item'); for (var i = 0; i < lineCount; i += 1) { fulfillmentRecord.setSublistValue('item', 'location', i, 1); } var fulfillmentId = fulfillmentRecord.save(); var so = record.load({ type: record.Type.SALES_ORDER, id: result.id }); so.setValue('memo', fulfillmentId); so.save(); return true; }); } catch (e) { var subject = 'Fatal Error: Unable to transform salesorder to item fulfillment!'; var authorId = -5; var recipientEmail = 'PI:EMAIL:anpch@example.comEND_PI'; email.send({ author: authorId, recipients: recipientEmail, subject: subject, body: 'Fatal error occurred in script: ' + runtime.getCurrentScript().id + '\n\n' + JSON.stringify(e) }); } } return { execute: execute }; });
/** * REST API for UPS Package * * @NApiVersion 2.x * @NScriptType Restlet * @author trungpv <trung@lexor.com> */ define(["N/https", "N/search", "/SuiteScripts/Module/Utils"], function( https, search, _U ) { /** VARS **/ const USERNAME = "xxx"; const PASSWORD = "xxx"; const API_KEY = "xxx"; const ADDITIONAL_FEES = 10; // 10% /** * POST * @param {*} context */ function postAction(context) { var result = {}; result.success = false; try { const validation = doValidation( [context.locationId, context.customer, context.weight], ["locationId", "customer", "weight"], "POST" ); if (validation.length === 0) { const originAddress = search.lookupFields({ type: search.Type.LOCATION, id: context.locationId, columns: ["address1", "city", "country", "zip", "state"] }); // Check State if (originAddress.state.length > 2) { originAddress.state = _U.abbrRegion(originAddress.state, "abbr"); } if (context.customer.state.length > 2) { context.customer.state = _U.abbrRegion( context.customer.state, "abbr" ); } // Get Data var data = getFreightRate( originAddress, context.customer, context.weight ); if (data) { if (isArray(data)) { result.data = data; result.success = true; result.message = "Success!"; } else { result.message = data; } } else { result.message = "Something went wrong with UPS API."; } } else { result.message = "Something went wrong with your params."; result.errors = validation; } } catch (err) { result.message = err.message; } return JSON.stringify(result); } /** HEPPER FUNCTIONS **/ /** * Validation params * @param {*} args * @param {*} argNames * @param {*} methodName */ function doValidation(args, argNames, methodName) { const result = []; for (var i = 0; i < args.length; i++) { if (!args[i] && args[i] !== 0) { result.push( "Missing a required argument: [" + argNames[i] + "] for method: " + methodName ); } } return result; } function UPSSecurity() { return { UsernameToken: { Username: USERNAME, Password: PASSWORD }, ServiceAccessToken: { AccessLicenseNumber: API_KEY } }; } /** * * @param {*} origin * @param {*} destination * @param {*} weight */ function requestPayload(origin, destination, weight) { var payload = { UPSSecurity: UPSSecurity(), RateRequest: { Request: { RequestOption: "Shop" }, Shipment: { Shipper: { Name: "Shipper Name", Address: { AddressLine: origin.address1, City: origin.city, StateProvinceCode: origin.state, PostalCode: origin.zip, CountryCode: origin.country } }, ShipTo: { Name: "Ship To Name", Address: { AddressLine: destination.addr1, City: destination.city, StateProvinceCode: destination.state, PostalCode: destination.zip, CountryCode: destination.country } }, Package: { PackagingType: { Code: "02", Description: "Rate" }, PackageWeight: { UnitOfMeasurement: { Code: "Lbs", Description: "pounds" }, Weight: weight } }, ShipmentRatingOptions: { NegotiatedRatesIndicator: "" } } } }; return JSON.stringify(payload); } /** * Get Freight Rate * @param {*} origin * @param {*} destination * @param {*} weight */ function getFreightRate(origin, destination, weight) { try { var payload = requestPayload(origin, destination, weight); var res = https.post({ url: "https://onlinetools.ups.com/rest/Rate", body: payload, headers: { "Content-Type": "application/json; charset=UTF-8" } }); const body = JSON.parse(res.body); if ( body.hasOwnProperty("RateResponse") && body.RateResponse.hasOwnProperty("RatedShipment") ) { var RatedShipment = body.RateResponse.RatedShipment; RatedShipment = RatedShipment.map(function(item) { var itemFilter = {}; itemFilter.code = item.Service.Code; itemFilter.total = parseFloat(item.TotalCharges.MonetaryValue) + parseFloat(item.TotalCharges.MonetaryValue) * (ADDITIONAL_FEES / 100); itemFilter.total = parseFloat(itemFilter.total).toFixed(2); return itemFilter; }); return RatedShipment; } if (body.hasOwnProperty("Fault")) { var PrimaryError = body.Fault.detail.Errors.ErrorDetail.PrimaryErrorCode.Description; return PrimaryError; } return false; } catch (error) { return false; } } /** * is Array * @param {*} value */ function isArray(value) { return value && typeof value === "object" && value.constructor === Array; } /** * Export Events */ var exports = {}; exports.post = postAction; return exports; });
492
[{"tag": "EMAIL", "value": "trung@lexor.com", "start": 99, "end": 114}]
true
1
/** * REST API for UPS Package * * @NApiVersion 2.x * @NScriptType Restlet * @author trungpv <upchh@example.com> */ define(["N/https", "N/search", "/SuiteScripts/Module/Utils"], function( https, search, _U ) { /** VARS **/ const USERNAME = "xxx"; const PASSWORD = "xxx"; const API_KEY = "xxx"; const ADDITIONAL_FEES = 10; // 10% /** * POST * @param {*} context */ function postAction(context) { var result = {}; result.success = false; try { const validation = doValidation( [context.locationId, context.customer, context.weight], ["locationId", "customer", "weight"], "POST" ); if (validation.length === 0) { const originAddress = search.lookupFields({ type: search.Type.LOCATION, id: context.locationId, columns: ["address1", "city", "country", "zip", "state"] }); // Check State if (originAddress.state.length > 2) { originAddress.state = _U.abbrRegion(originAddress.state, "abbr"); } if (context.customer.state.length > 2) { context.customer.state = _U.abbrRegion( context.customer.state, "abbr" ); } // Get Data var data = getFreightRate( originAddress, context.customer, context.weight ); if (data) { if (isArray(data)) { result.data = data; result.success = true; result.message = "Success!"; } else { result.message = data; } } else { result.message = "Something went wrong with UPS API."; } } else { result.message = "Something went wrong with your params."; result.errors = validation; } } catch (err) { result.message = err.message; } return JSON.stringify(result); } /** HEPPER FUNCTIONS **/ /** * Validation params * @param {*} args * @param {*} argNames * @param {*} methodName */ function doValidation(args, argNames, methodName) { const result = []; for (var i = 0; i < args.length; i++) { if (!args[i] && args[i] !== 0) { result.push( "Missing a required argument: [" + argNames[i] + "] for method: " + methodName ); } } return result; } function UPSSecurity() { return { UsernameToken: { Username: USERNAME, Password: PASSWORD }, ServiceAccessToken: { AccessLicenseNumber: API_KEY } }; } /** * * @param {*} origin * @param {*} destination * @param {*} weight */ function requestPayload(origin, destination, weight) { var payload = { UPSSecurity: UPSSecurity(), RateRequest: { Request: { RequestOption: "Shop" }, Shipment: { Shipper: { Name: "Shipper Name", Address: { AddressLine: origin.address1, City: origin.city, StateProvinceCode: origin.state, PostalCode: origin.zip, CountryCode: origin.country } }, ShipTo: { Name: "Ship To Name", Address: { AddressLine: destination.addr1, City: destination.city, StateProvinceCode: destination.state, PostalCode: destination.zip, CountryCode: destination.country } }, Package: { PackagingType: { Code: "02", Description: "Rate" }, PackageWeight: { UnitOfMeasurement: { Code: "Lbs", Description: "pounds" }, Weight: weight } }, ShipmentRatingOptions: { NegotiatedRatesIndicator: "" } } } }; return JSON.stringify(payload); } /** * Get Freight Rate * @param {*} origin * @param {*} destination * @param {*} weight */ function getFreightRate(origin, destination, weight) { try { var payload = requestPayload(origin, destination, weight); var res = https.post({ url: "https://onlinetools.ups.com/rest/Rate", body: payload, headers: { "Content-Type": "application/json; charset=UTF-8" } }); const body = JSON.parse(res.body); if ( body.hasOwnProperty("RateResponse") && body.RateResponse.hasOwnProperty("RatedShipment") ) { var RatedShipment = body.RateResponse.RatedShipment; RatedShipment = RatedShipment.map(function(item) { var itemFilter = {}; itemFilter.code = item.Service.Code; itemFilter.total = parseFloat(item.TotalCharges.MonetaryValue) + parseFloat(item.TotalCharges.MonetaryValue) * (ADDITIONAL_FEES / 100); itemFilter.total = parseFloat(itemFilter.total).toFixed(2); return itemFilter; }); return RatedShipment; } if (body.hasOwnProperty("Fault")) { var PrimaryError = body.Fault.detail.Errors.ErrorDetail.PrimaryErrorCode.Description; return PrimaryError; } return false; } catch (error) { return false; } } /** * is Array * @param {*} value */ function isArray(value) { return value && typeof value === "object" && value.constructor === Array; } /** * Export Events */ var exports = {}; exports.post = postAction; return exports; });
true
/** * REST API for UPS Package * * @NApiVersion 2.x * @NScriptType Restlet * @author trungpv <PI:EMAIL:upchh@example.comEND_PI> */ define(["N/https", "N/search", "/SuiteScripts/Module/Utils"], function( https, search, _U ) { /** VARS **/ const USERNAME = "xxx"; const PASSWORD = "xxx"; const API_KEY = "xxx"; const ADDITIONAL_FEES = 10; // 10% /** * POST * @param {*} context */ function postAction(context) { var result = {}; result.success = false; try { const validation = doValidation( [context.locationId, context.customer, context.weight], ["locationId", "customer", "weight"], "POST" ); if (validation.length === 0) { const originAddress = search.lookupFields({ type: search.Type.LOCATION, id: context.locationId, columns: ["address1", "city", "country", "zip", "state"] }); // Check State if (originAddress.state.length > 2) { originAddress.state = _U.abbrRegion(originAddress.state, "abbr"); } if (context.customer.state.length > 2) { context.customer.state = _U.abbrRegion( context.customer.state, "abbr" ); } // Get Data var data = getFreightRate( originAddress, context.customer, context.weight ); if (data) { if (isArray(data)) { result.data = data; result.success = true; result.message = "Success!"; } else { result.message = data; } } else { result.message = "Something went wrong with UPS API."; } } else { result.message = "Something went wrong with your params."; result.errors = validation; } } catch (err) { result.message = err.message; } return JSON.stringify(result); } /** HEPPER FUNCTIONS **/ /** * Validation params * @param {*} args * @param {*} argNames * @param {*} methodName */ function doValidation(args, argNames, methodName) { const result = []; for (var i = 0; i < args.length; i++) { if (!args[i] && args[i] !== 0) { result.push( "Missing a required argument: [" + argNames[i] + "] for method: " + methodName ); } } return result; } function UPSSecurity() { return { UsernameToken: { Username: USERNAME, Password: PASSWORD }, ServiceAccessToken: { AccessLicenseNumber: API_KEY } }; } /** * * @param {*} origin * @param {*} destination * @param {*} weight */ function requestPayload(origin, destination, weight) { var payload = { UPSSecurity: UPSSecurity(), RateRequest: { Request: { RequestOption: "Shop" }, Shipment: { Shipper: { Name: "Shipper Name", Address: { AddressLine: origin.address1, City: origin.city, StateProvinceCode: origin.state, PostalCode: origin.zip, CountryCode: origin.country } }, ShipTo: { Name: "Ship To Name", Address: { AddressLine: destination.addr1, City: destination.city, StateProvinceCode: destination.state, PostalCode: destination.zip, CountryCode: destination.country } }, Package: { PackagingType: { Code: "02", Description: "Rate" }, PackageWeight: { UnitOfMeasurement: { Code: "Lbs", Description: "pounds" }, Weight: weight } }, ShipmentRatingOptions: { NegotiatedRatesIndicator: "" } } } }; return JSON.stringify(payload); } /** * Get Freight Rate * @param {*} origin * @param {*} destination * @param {*} weight */ function getFreightRate(origin, destination, weight) { try { var payload = requestPayload(origin, destination, weight); var res = https.post({ url: "https://onlinetools.ups.com/rest/Rate", body: payload, headers: { "Content-Type": "application/json; charset=UTF-8" } }); const body = JSON.parse(res.body); if ( body.hasOwnProperty("RateResponse") && body.RateResponse.hasOwnProperty("RatedShipment") ) { var RatedShipment = body.RateResponse.RatedShipment; RatedShipment = RatedShipment.map(function(item) { var itemFilter = {}; itemFilter.code = item.Service.Code; itemFilter.total = parseFloat(item.TotalCharges.MonetaryValue) + parseFloat(item.TotalCharges.MonetaryValue) * (ADDITIONAL_FEES / 100); itemFilter.total = parseFloat(itemFilter.total).toFixed(2); return itemFilter; }); return RatedShipment; } if (body.hasOwnProperty("Fault")) { var PrimaryError = body.Fault.detail.Errors.ErrorDetail.PrimaryErrorCode.Description; return PrimaryError; } return false; } catch (error) { return false; } } /** * is Array * @param {*} value */ function isArray(value) { return value && typeof value === "object" && value.constructor === Array; } /** * Export Events */ var exports = {}; exports.post = postAction; return exports; });
/** * * @NApiVersion 2.0 * @NScriptType Suitelet * * Description: Import an excel file of stops to add into an existing run * @Last Modified by: Sruti Desai * */ define(['N/ui/serverWidget', 'N/email', 'N/runtime', 'N/search', 'N/record', 'N/http', 'N/log', 'N/redirect', 'N/format', 'N/file', 'N/error', 'N/task'], function(ui, email, runtime, search, record, http, log, redirect, format, file, error, task) { var baseURL = 'https://1048144.app.netsuite.com'; if (runtime.EnvType == "SANDBOX") { baseURL = 'https://1048144-sb3.app.netsuite.com'; } var zee = 0; var role = runtime.getCurrentUser().role; if (role == 1000) { //Franchisee zee = runtime.getCurrentUser().id; } function onRequest(context) { if (context.request.method === 'GET') { // Load jQuery var inlineHtml = '<script src="https://code.jquery.com/jquery-1.12.4.min.js" integrity="sha384-nvAa0+6Qg9clwYCGGPpDQLVpLNn0fRaROjHqs13t4Ggj3Ez50XnGQqc/r8MhnRDZ" crossorigin="anonymous"></script>'; // Load Tooltip inlineHtml += '<script src="https://unpkg.com/@popperjs/core@2"></script>'; // Load Bootstrap inlineHtml += '<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/3.4.1/css/bootstrap.min.css" integrity="sha384-HSMxcRTRxnN+Bdg0JdbxYKrThecOKuH5zCYotlSAcp1+c8xmyTe9GYg1l9a69psu" crossorigin="anonymous">'; inlineHtml += '<script src="https://stackpath.bootstrapcdn.com/bootstrap/3.4.1/js/bootstrap.min.js" integrity="sha384-aJ21OjlMXNL5UyIl/XNwTMqvzeRMZH2w8c5cRVpzpU8Y5bApTppSuUkhZXN0VxHd" crossorigin="anonymous"></script>'; // Load DataTables inlineHtml += '<link rel="stylesheet" type="text/css" href="//cdn.datatables.net/1.10.21/css/jquery.dataTables.min.css">'; inlineHtml += '<script type="text/javascript" charset="utf8" src="//cdn.datatables.net/1.10.21/js/jquery.dataTables.min.js"></script>'; // Load Bootstrap-Select inlineHtml += '<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap-select@1.13.14/dist/css/bootstrap-select.min.css">'; inlineHtml += '<script src="https://cdn.jsdelivr.net/npm/bootstrap-select@1.13.14/dist/js/bootstrap-select.min.js"></script>'; // Load Netsuite stylesheet and script inlineHtml += '<link rel="stylesheet" href="https://1048144.app.netsuite.com/core/media/media.nl?id=2060796&c=1048144&h=9ee6accfd476c9cae718&_xt=.css"/>'; inlineHtml += '<script src="https://1048144.app.netsuite.com/core/media/media.nl?id=2060797&c=1048144&h=ef2cda20731d146b5e98&_xt=.js"></script>'; inlineHtml += '<link type="text/css" rel="stylesheet" href="https://1048144.app.netsuite.com/core/media/media.nl?id=2090583&c=1048144&h=a0ef6ac4e28f91203dfe&_xt=.css">'; inlineHtml += '<style>.mandatory{color:red;}</style>'; var form = ui.createForm({ title: 'Import Excel' }); form.addButton({ id : 'import', label : 'Download Template', functionName : 'onclick_downloadButton()' }); form.addButton({ id : 'del_run', label : 'Delete Run', functionName : 'onclick_deleteRun()' }); form.addButton({ id : 'export_run', label : 'Export Run', functionName : 'onclick_exportRun()' }); form.addSubmitButton({ label: 'Import Run' }); if (role == 1000) { form.addField({ id: 'zee', type: ui.FieldType.TEXT, label: 'zee' }).updateDisplayType({ displayType: ui.FieldDisplayType.HIDDEN }).defaultValue = runtime.getCurrentUser().id; } if (!isNullorEmpty(context.request.parameters.zee) && context.request.parameters.zee != 0) { form.addField({ id: 'zee', type: ui.FieldType.TEXT, label: 'zee' }).updateDisplayType({ displayType: ui.FieldDisplayType.HIDDEN }).defaultValue = context.request.parameters.zee; } else { form.addField({ id: 'zee', type: ui.FieldType.TEXT, label: 'zee' }).updateDisplayType({ displayType: ui.FieldDisplayType.HIDDEN }).defaultValue = zee; } if (!isNullorEmpty(context.request.parameters.run) && context.request.parameters.run != 0) { form.addField({ id: 'run', type: ui.FieldType.TEXT, label: 'run' }).updateDisplayType({ displayType: ui.FieldDisplayType.HIDDEN }).defaultValue = context.request.parameters.run; var freqSearch = search.load({ id: 'customsearch_rp_servicefreq', type: 'customrecord_service_freq' }); freqSearch.filters.push(search.createFilter({ name: 'custrecord_service_freq_run_plan', operator: search.Operator.IS, values: context.request.parameters.run })); var initial_count = freqSearch.runPaged().count; form.addField({ id: 'initial_count', type: ui.FieldType.TEXT, label: 'initial_count' }).updateDisplayType({ displayType: ui.FieldDisplayType.HIDDEN }).defaultValue = initial_count; } else { form.addField({ id: 'run', type: ui.FieldType.TEXT, label: 'run' }).updateDisplayType({ displayType: ui.FieldDisplayType.HIDDEN }); } form.addField({ id: 'custpage_table_csv', type: ui.FieldType.TEXT, label: 'Table CSV' }).updateDisplayType({ displayType: ui.FieldDisplayType.HIDDEN }); form.addField({ id: 'custpage_export_run_csv', type: ui.FieldType.TEXT, label: 'Table CSV' }).updateDisplayType({ displayType: ui.FieldDisplayType.HIDDEN }); //Important Instructions box inlineHtml += '<br></br>' inlineHtml += '<div></div>'; inlineHtml += '<div class="form-group container test_section">'; //inlineHtml += '<button type="button" class="btn btn-sm btn-info instruction_button" data-toggle="collapse" data-target="#demo">Click for Instructions</button>'; //inlineHtml += '<div id="demo" style="background-color: #cfeefc !important;border: 1px solid #417ed9;padding: 20px 30px 30px 30px;width:96%;position:absolute" class="collapse"><b><u>IMPORTANT INSTRUCTIONS:</u></b>'; inlineHtml += '<div style=\"background-color: #cfeefc !important;border: 1px solid #417ed9;padding: 20px 30px 30px 30px\"><b><u>Important Instructions:</u></b>'; inlineHtml += '<ul><li><b><u>Please do not alter the columns titled Customer Internal ID, Customer Id, Customer Name, Service Id, Service Name and Price</u></b></li>'; inlineHtml += '<li><b><u>Frequency</u></b>: If the frequency of the service is multiple days then separate with a / i.e. Mon/Tue/Wed/Thurs/Fri. </li>'; inlineHtml += '<li><b><u>Frequency</u></b>: Frequency field can take input of Daily and Adhoc as well</li>'; inlineHtml += '<li><b><u>Customer or Non-Customer</u></b>: Please only enter in "Customer" or "Non-Customer" in this field </li>'; inlineHtml += '<li><b><u>Location (Customer)</u></b>: For a Customer Location please enter all address details in this single field i.e. "379-381 Victoria Street, Wetherill Park, NSW, 2164" </li>'; inlineHtml += '<li><b><u>Location (Non-Customer)</u></b>: For a Non-Customer Location please enter the exact name of the stop i.e. "ARNCLIFFE LPO" </li>'; inlineHtml += '<li><b><u>Duration</u></b>: Enter length of time in seconds only i.e. "120", where 120 is equal to 2 minutes </li>'; inlineHtml += '<li><b><u>Time</u></b>: Enter the time leg will occur in 12 hour time with a ":" separating the minutes and hours, and AM/PM following the time. i.e. "12:30PM" or "8:46AM" </li>'; inlineHtml += '<li><b><u>Notes</u></b>: Enter the necessary notes (in any format) required for each stop in the relevant fields </li>'; inlineHtml += '<li><b><u>Run Name</u></b>: Enter the exact Run-Name as it appears on Netsuite i.e. "Danilo\'s" or "Mascot" or "Multi Run" </li>'; inlineHtml += '<li><b><u>Non-Mandatory Fields</u></b>: Po Box, Notes, Transfer </li>'; inlineHtml += '<li><b><u>Download Template</u></b>: If you are a franchisee click on the "Download Template" button to download a template for your franchise. If you are not a franchisee, select a zee from the dropdown and then click on the download template button to download a template for that specific zee </li>'; inlineHtml += '<li><b><u>Delete Run</u></b>: Select a zee and then select a run from the relevant dropdowns. After clicking the Delete Run button, this entire run will be deleted. </li>'; inlineHtml += '<li><b><u>Export Run</u></b>: Select a zee and then select a run from the relevant dropdowns. After clicking the Export Run button, the entire run will be exported into a csv </li>'; inlineHtml += '<li><b><u>Non-Mandatory Fields</u></b>: Po Box, Notes, Transfer </li>'; inlineHtml += '<li>If you have any issues, please contact Head Office</li>'; inlineHtml += '</ul></div></div><br/>'; inlineHtml += progressBar(); if (role != 1000) { inlineHtml += franchiseeDropdownSection(context.request.parameters.zee); } if (!isNullorEmpty(context.request.parameters.zee)) { inlineHtml += runDropdownSection(context.request.parameters.zee, context.request.parameters.run); } form.addField({ id: 'scheduled_script', type: ui.FieldType.TEXT, label: 'scheduled_script' }).updateDisplayType({ displayType: ui.FieldDisplayType.HIDDEN }); form.addField({ id: 'preview_table', type: ui.FieldType.INLINEHTML, label: 'preview_table' }).updateLayoutType({ layoutType: ui.FieldLayoutType.OUTSIDEBELOW }).updateBreakType({ breakType: ui.FieldBreakType.STARTROW }).defaultValue = inlineHtml; form.addField({ id: 'upload_rs_csv', label: 'IMPORT EXCEL', type: ui.FieldType.FILE }); form.clientScriptFileId = 4620348; //PROD = 4620348, SB = 4602504 context.response.writePage(form); } else { var fileObj = context.request.files.upload_rs_csv; var zee = context.request.parameters.zee; if (!isNullorEmpty(fileObj)) { fileObj.folder = 2661964; //2644902, 2661964 var file_type = fileObj.fileType; if (file_type == 'CSV') { file_type == 'csv'; var file_name = zee + '_zee_rs_upload' + '.' + file_type; } fileObj.name = file_name; if (file_type == 'CSV') { // Create file and upload it to the file cabinet. var f_id = fileObj.save(); } else { throw error.create({ message: 'Must be in CSV format', name: 'CSV_ERROR', notifyOff: true }); } } log.debug({ title: 'fileid', details: f_id }); log.debug({ title: 'zee', details: zee }); // CALL SCHEDULED SCRIPT var scriptTask = task.create({ taskType: task.TaskType.SCHEDULED_SCRIPT }); scriptTask.scriptId = 'customscript_ss_import_excel'; scriptTask.deploymentId = 'customdeploy_ss_import_excel'; scriptTask.params = { custscript_import_excel_file_id: f_id, custscript_import_excel_zee_id: zee }; var ss_id = scriptTask.submit(); var myTaskStatus = task.checkStatus({ taskId: ss_id }); // Load jQuery var inlineHtml = '<script src="https://code.jquery.com/jquery-1.12.4.min.js" integrity="sha384-nvAa0+6Qg9clwYCGGPpDQLVpLNn0fRaROjHqs13t4Ggj3Ez50XnGQqc/r8MhnRDZ" crossorigin="anonymous"></script>'; // Load Tooltip inlineHtml += '<script src="https://unpkg.com/@popperjs/core@2"></script>'; // Load Bootstrap inlineHtml += '<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/3.4.1/css/bootstrap.min.css" integrity="sha384-HSMxcRTRxnN+Bdg0JdbxYKrThecOKuH5zCYotlSAcp1+c8xmyTe9GYg1l9a69psu" crossorigin="anonymous">'; inlineHtml += '<script src="https://stackpath.bootstrapcdn.com/bootstrap/3.4.1/js/bootstrap.min.js" integrity="sha384-aJ21OjlMXNL5UyIl/XNwTMqvzeRMZH2w8c5cRVpzpU8Y5bApTppSuUkhZXN0VxHd" crossorigin="anonymous"></script>'; // Load DataTables inlineHtml += '<link rel="stylesheet" type="text/css" href="//cdn.datatables.net/1.10.21/css/jquery.dataTables.min.css">'; inlineHtml += '<script type="text/javascript" charset="utf8" src="//cdn.datatables.net/1.10.21/js/jquery.dataTables.min.js"></script>'; // Load Bootstrap-Select inlineHtml += '<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap-select@1.13.14/dist/css/bootstrap-select.min.css">'; inlineHtml += '<script src="https://cdn.jsdelivr.net/npm/bootstrap-select@1.13.14/dist/js/bootstrap-select.min.js"></script>'; // Load Netsuite stylesheet and script inlineHtml += '<link rel="stylesheet" href="https://1048144.app.netsuite.com/core/media/media.nl?id=2060796&c=1048144&h=9ee6accfd476c9cae718&_xt=.css"/>'; inlineHtml += '<script src="https://1048144.app.netsuite.com/core/media/media.nl?id=2060797&c=1048144&h=ef2cda20731d146b5e98&_xt=.js"></script>'; inlineHtml += '<link type="text/css" rel="stylesheet" href="https://1048144.app.netsuite.com/core/media/media.nl?id=2090583&c=1048144&h=a0ef6ac4e28f91203dfe&_xt=.css">'; inlineHtml += '<style>.mandatory{color:red;}</style>'; var file1 = file.load({ id: f_id }); var iterator = file1.lines.iterator(); // skip first line (header) iterator.each(function (line) { log.debug({ title: 'line', details: line }); return false; }); var numLines = 0; iterator.each(function (line) { var rs_values = line.value.split(/,(?=(?:(?:[^"]*"){2})*[^"]*$)/); var stop1_location = rs_values[9]; if (!isNullorEmpty(stop1_location)) { numLines++; } log.debug({ title: 'num lines', details: line }); return true; }); log.debug({ title: 'numLines', details: numLines }); inlineHtml += progressBar(); inlineHtml += dataTable(); var form = ui.createForm({ title: 'Import Excel DB' }); form.addField({ id: 'custpage_table_csv', type: ui.FieldType.TEXT, label: 'Table CSV' }).updateDisplayType({ displayType: ui.FieldDisplayType.HIDDEN }); form.addField({ id: 'preview_table', type: ui.FieldType.INLINEHTML, label: 'preview_table' }).updateLayoutType({ layoutType: ui.FieldLayoutType.OUTSIDEBELOW }).updateBreakType({ breakType: ui.FieldBreakType.STARTROW }).defaultValue = inlineHtml; form.addField({ id: 'excel_lines', type: ui.FieldType.TEXT, label: 'excel_lines' }).updateDisplayType({ displayType: ui.FieldDisplayType.HIDDEN }).defaultValue = numLines; form.addField({ id: 'scheduled_script', type: ui.FieldType.TEXT, label: 'scheduled_script' }).updateDisplayType({ displayType: ui.FieldDisplayType.HIDDEN }).defaultValue = ss_id; form.clientScriptFileId = 4620348; //PROD = 4620348, SB = 4602504 context.response.writePage(form); } } function isNullorEmpty(strVal) { return (strVal == null || strVal == '' || strVal == 'null' || strVal == undefined || strVal == 'undefined' || strVal == '- None -'); } /** * The Franchisee dropdown list. * @param {Number} zee_id * @return {String} `inlineQty` */ function franchiseeDropdownSection(params_zee) { var inlineQty = '<div class="form-group container zee_dropdown_section >'; //inlineQty += '<div class="row">'; // Franchisee dropdown field //inlineQty += '<div class="col-xs-12 zee_dropdown_div">'; inlineQty += '<div class="input-group">'; inlineQty += '<span class="input-group-addon" id="zee_dropdown_text">FRANCHISEE</span>'; inlineQty += '<select id="zee_dropdown" class="form-control zee_dropdown" required>'; inlineQty += '<option></option>'; // Load the franchisees options var zeesSearch = search.load({ id: 'customsearch_job_inv_process_zee', type: search.Type.PARTNER }); var zeesSearchResults = zeesSearch.run(); zeesSearchResults.each(function (zeesSearchResult) { var opt_zee_id = zeesSearchResult.getValue('internalid'); var opt_zee_name = zeesSearchResult.getValue('companyname'); var selected_option = ''; if (role == 1000) { zee_id = runtime.getCurrentUser().id; //Get Franchisee ID-- REMOVE TO TEST selected_option = (opt_zee_id == zee_id) ? 'selected' : ''; } if (!isNullorEmpty(params_zee)) { selected_option = (params_zee == opt_zee_id) ? 'selected' : ''; } inlineQty += '<option value="' + opt_zee_id + '" ' + selected_option + '>' + opt_zee_name + '</option>'; return true; }); inlineQty += '</select>'; inlineQty += '</div></div></div></div>'; return inlineQty; } function runDropdownSection(zee, params_run) { // var inlineQty = '<div class="container select_run">'; // inlineQty += '<div class="form-group container"><div class="row">'; // inlineQty += '<div class="input-group">'; // inlineQty += '<span class="input-group-addon">SELECT RUN</span>'; // inlineQty += '<select class="form-control run_dropdown" >'; var inlineQty = '<div class="form-group container select_run >'; //inlineQty += '<div class="row">'; // Franchisee dropdown field //inlineQty += '<div class="col-xs-12 select_dropdown_div">'; inlineQty += '<div class="input-group">'; inlineQty += '<span class="input-group-addon" id="zee_dropdown_text">SELECT RUN</span>'; inlineQty += '<select class="form-control run_dropdown" >'; var runPlanSearch = search.load({ id: 'customsearch_app_run_plan_active', type: 'customrecord_run_plan' }) var zee_record = record.load({ type: record.Type.PARTNER, id: parseInt(zee), isDynamic: true, }); var multi = zee_record.getValue({ fieldId: 'custentity_zee_multiple_territory' }) if (!isNullorEmpty(multi)) { runPlanSearch.filters.push(search.createFilter({ name: 'custrecord_run_franchisee', operator: search.Operator.ANYOF, values: zee })); } else { runPlanSearch.filters.push(search.createFilter({ name: 'custrecord_run_franchisee', operator: search.Operator.IS, values: zee })); } var resultSet_runPlan = runPlanSearch.run(); var count_zee = 0; inlineQty += '<option value="' + 0 + '"></option>' resultSet_runPlan.each(function(searchResult_runPlan) { runinternalid = searchResult_runPlan.getValue('internalid'); runname = searchResult_runPlan.getValue('name'); if (params_run == runinternalid) { inlineQty += '<option value="' + runinternalid + '" selected="selected">' + runname + '</option>'; } else { inlineQty += '<option value="' + runinternalid + '">' + runname + '</option>'; } return true; }); inlineQty += '</select></div></div></div></div>'; return inlineQty; } /** * The table that will display the differents invoices linked to the franchisee and the time period. * @return {String} inlineQty */ function dataTable() { var inlineQty = '<style>table#import_excel {font-size: 12px;text-align: center;border: none;}.dataTables_wrapper {font-size: 14px;}table#import_excel th{text-align: center;} .bolded{font-weight: bold;}</style>'; inlineQty += '<table id="import_excel" class="table table-responsive table-striped customer tablesorter" style="width: 100%;">'; inlineQty += '<thead style="color: white;background-color: #607799;">'; inlineQty += '<tr class="text-center">'; inlineQty += '</tr>'; inlineQty += '</thead>'; inlineQty += '<tbody id="result_import" class="result-import"></tbody>'; inlineQty += '</table>'; return inlineQty; } function onclick_deleteRun(zee, run) { // log.debug({ // title: 'infn', // details: 'infn' // }) // if (!isNullorEmpty(zee) && !isNullorEmpty(run)) { // log.debug({ // title: 'scheduled', // details: 'scheduled' // }) // params = { // custscript_delete_run_run_id_set: run // }; // reschedule = task.create({ // taskType: task.TaskType.SCHEDULED_SCRIPT, // scriptId: 'customscript_ss_delete_run', // deploymentId: 'customdeploy_ss_delete_run', // params: params // }); // log.audit({ // title: 'Attempting: Rescheduling Script', // details: reschedule // }); // reschedule.submit(); //} } /** * Display the progress bar. Initialized at 0, with the maximum value as the number of records that will be moved. * Uses Bootstrap : https://www.w3schools.com/bootstrap/bootstrap_progressbars.asp * @param {String} nb_records_total The number of records that will be moved * @return {String} inlineQty : The inline HTML string of the progress bar. */ function progressBar() { var inlineQty = '<div class="progress hide">'; inlineQty += '<div class="progress-bar progress-bar-striped progress-bar-warning" id="progress-records" role="progressbar" aria-valuenow="0" style="width:0%">0%</div>'; inlineQty += '</div>'; return inlineQty; } function getDate() { var date = (new Date()); // if (date.getHours() > 6) { // date = nlapiAddDays(date, 1); // } // date.setHours(date.getHours() + 17); var date_string = date.getFullYear() + '' + (date.getMonth() + 1) + '' + date.getDate() + '_' + date.getHours() + '' + date.getMinutes(); return date_string; } return { onRequest: onRequest }; });
1,225
[{"tag": "KEY", "value": "sha384-nvAa0+6Qg9clwYCGGPpDQLVpLNn0fRaROjHqs13t4Ggj3Ez50XnGQqc/r8MhnRDZ", "start": 962, "end": 1033}, {"tag": "KEY", "value": "sha384-nvAa0+6Qg9clwYCGGPpDQLVpLNn0fRaROjHqs13t4Ggj3Ez50XnGQqc/r8MhnRDZ", "start": 13602, "end": 13673}, {"tag": "KEY", "value": "sha384-aJ21OjlMXNL5UyIl/XNwTMqvzeRMZH2w8c5cRVpzpU8Y5bApTppSuUkhZXN0VxHd", "start": 1582, "end": 1653}, {"tag": "KEY", "value": "sha384-aJ21OjlMXNL5UyIl/XNwTMqvzeRMZH2w8c5cRVpzpU8Y5bApTppSuUkhZXN0VxHd", "start": 14222, "end": 14293}, {"tag": "KEY", "value": "sha384-HSMxcRTRxnN+Bdg0JdbxYKrThecOKuH5zCYotlSAcp1+c8xmyTe9GYg1l9a69psu", "start": 1359, "end": 1430}, {"tag": "KEY", "value": "sha384-HSMxcRTRxnN+Bdg0JdbxYKrThecOKuH5zCYotlSAcp1+c8xmyTe9GYg1l9a69psu", "start": 13999, "end": 14070}]
true
6
/** * * @NApiVersion 2.0 * @NScriptType Suitelet * * Description: Import an excel file of stops to add into an existing run * @Last Modified by: Sruti Desai * */ define(['N/ui/serverWidget', 'N/email', 'N/runtime', 'N/search', 'N/record', 'N/http', 'N/log', 'N/redirect', 'N/format', 'N/file', 'N/error', 'N/task'], function(ui, email, runtime, search, record, http, log, redirect, format, file, error, task) { var baseURL = 'https://1048144.app.netsuite.com'; if (runtime.EnvType == "SANDBOX") { baseURL = 'https://1048144-sb3.app.netsuite.com'; } var zee = 0; var role = runtime.getCurrentUser().role; if (role == 1000) { //Franchisee zee = runtime.getCurrentUser().id; } function onRequest(context) { if (context.request.method === 'GET') { // Load jQuery var inlineHtml = '<script src="https://code.jquery.com/jquery-1.12.4.min.js" integrity="949d1u22cbffbrarjh182eig55721odj" crossorigin="anonymous"></script>'; // Load Tooltip inlineHtml += '<script src="https://unpkg.com/@popperjs/core@2"></script>'; // Load Bootstrap inlineHtml += '<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/3.4.1/css/bootstrap.min.css" integrity="caf86f4uutaoxfysmf7anj01xl6sv3ps" crossorigin="anonymous">'; inlineHtml += '<script src="https://stackpath.bootstrapcdn.com/bootstrap/3.4.1/js/bootstrap.min.js" integrity="74t3tndxag9o7h0890bnpfzh4olk2h9x" crossorigin="anonymous"></script>'; // Load DataTables inlineHtml += '<link rel="stylesheet" type="text/css" href="//cdn.datatables.net/1.10.21/css/jquery.dataTables.min.css">'; inlineHtml += '<script type="text/javascript" charset="utf8" src="//cdn.datatables.net/1.10.21/js/jquery.dataTables.min.js"></script>'; // Load Bootstrap-Select inlineHtml += '<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap-select@1.13.14/dist/css/bootstrap-select.min.css">'; inlineHtml += '<script src="https://cdn.jsdelivr.net/npm/bootstrap-select@1.13.14/dist/js/bootstrap-select.min.js"></script>'; // Load Netsuite stylesheet and script inlineHtml += '<link rel="stylesheet" href="https://1048144.app.netsuite.com/core/media/media.nl?id=2060796&c=1048144&h=9ee6accfd476c9cae718&_xt=.css"/>'; inlineHtml += '<script src="https://1048144.app.netsuite.com/core/media/media.nl?id=2060797&c=1048144&h=ef2cda20731d146b5e98&_xt=.js"></script>'; inlineHtml += '<link type="text/css" rel="stylesheet" href="https://1048144.app.netsuite.com/core/media/media.nl?id=2090583&c=1048144&h=a0ef6ac4e28f91203dfe&_xt=.css">'; inlineHtml += '<style>.mandatory{color:red;}</style>'; var form = ui.createForm({ title: 'Import Excel' }); form.addButton({ id : 'import', label : 'Download Template', functionName : 'onclick_downloadButton()' }); form.addButton({ id : 'del_run', label : 'Delete Run', functionName : 'onclick_deleteRun()' }); form.addButton({ id : 'export_run', label : 'Export Run', functionName : 'onclick_exportRun()' }); form.addSubmitButton({ label: 'Import Run' }); if (role == 1000) { form.addField({ id: 'zee', type: ui.FieldType.TEXT, label: 'zee' }).updateDisplayType({ displayType: ui.FieldDisplayType.HIDDEN }).defaultValue = runtime.getCurrentUser().id; } if (!isNullorEmpty(context.request.parameters.zee) && context.request.parameters.zee != 0) { form.addField({ id: 'zee', type: ui.FieldType.TEXT, label: 'zee' }).updateDisplayType({ displayType: ui.FieldDisplayType.HIDDEN }).defaultValue = context.request.parameters.zee; } else { form.addField({ id: 'zee', type: ui.FieldType.TEXT, label: 'zee' }).updateDisplayType({ displayType: ui.FieldDisplayType.HIDDEN }).defaultValue = zee; } if (!isNullorEmpty(context.request.parameters.run) && context.request.parameters.run != 0) { form.addField({ id: 'run', type: ui.FieldType.TEXT, label: 'run' }).updateDisplayType({ displayType: ui.FieldDisplayType.HIDDEN }).defaultValue = context.request.parameters.run; var freqSearch = search.load({ id: 'customsearch_rp_servicefreq', type: 'customrecord_service_freq' }); freqSearch.filters.push(search.createFilter({ name: 'custrecord_service_freq_run_plan', operator: search.Operator.IS, values: context.request.parameters.run })); var initial_count = freqSearch.runPaged().count; form.addField({ id: 'initial_count', type: ui.FieldType.TEXT, label: 'initial_count' }).updateDisplayType({ displayType: ui.FieldDisplayType.HIDDEN }).defaultValue = initial_count; } else { form.addField({ id: 'run', type: ui.FieldType.TEXT, label: 'run' }).updateDisplayType({ displayType: ui.FieldDisplayType.HIDDEN }); } form.addField({ id: 'custpage_table_csv', type: ui.FieldType.TEXT, label: 'Table CSV' }).updateDisplayType({ displayType: ui.FieldDisplayType.HIDDEN }); form.addField({ id: 'custpage_export_run_csv', type: ui.FieldType.TEXT, label: 'Table CSV' }).updateDisplayType({ displayType: ui.FieldDisplayType.HIDDEN }); //Important Instructions box inlineHtml += '<br></br>' inlineHtml += '<div></div>'; inlineHtml += '<div class="form-group container test_section">'; //inlineHtml += '<button type="button" class="btn btn-sm btn-info instruction_button" data-toggle="collapse" data-target="#demo">Click for Instructions</button>'; //inlineHtml += '<div id="demo" style="background-color: #cfeefc !important;border: 1px solid #417ed9;padding: 20px 30px 30px 30px;width:96%;position:absolute" class="collapse"><b><u>IMPORTANT INSTRUCTIONS:</u></b>'; inlineHtml += '<div style=\"background-color: #cfeefc !important;border: 1px solid #417ed9;padding: 20px 30px 30px 30px\"><b><u>Important Instructions:</u></b>'; inlineHtml += '<ul><li><b><u>Please do not alter the columns titled Customer Internal ID, Customer Id, Customer Name, Service Id, Service Name and Price</u></b></li>'; inlineHtml += '<li><b><u>Frequency</u></b>: If the frequency of the service is multiple days then separate with a / i.e. Mon/Tue/Wed/Thurs/Fri. </li>'; inlineHtml += '<li><b><u>Frequency</u></b>: Frequency field can take input of Daily and Adhoc as well</li>'; inlineHtml += '<li><b><u>Customer or Non-Customer</u></b>: Please only enter in "Customer" or "Non-Customer" in this field </li>'; inlineHtml += '<li><b><u>Location (Customer)</u></b>: For a Customer Location please enter all address details in this single field i.e. "379-381 Victoria Street, Wetherill Park, NSW, 2164" </li>'; inlineHtml += '<li><b><u>Location (Non-Customer)</u></b>: For a Non-Customer Location please enter the exact name of the stop i.e. "ARNCLIFFE LPO" </li>'; inlineHtml += '<li><b><u>Duration</u></b>: Enter length of time in seconds only i.e. "120", where 120 is equal to 2 minutes </li>'; inlineHtml += '<li><b><u>Time</u></b>: Enter the time leg will occur in 12 hour time with a ":" separating the minutes and hours, and AM/PM following the time. i.e. "12:30PM" or "8:46AM" </li>'; inlineHtml += '<li><b><u>Notes</u></b>: Enter the necessary notes (in any format) required for each stop in the relevant fields </li>'; inlineHtml += '<li><b><u>Run Name</u></b>: Enter the exact Run-Name as it appears on Netsuite i.e. "Danilo\'s" or "Mascot" or "Multi Run" </li>'; inlineHtml += '<li><b><u>Non-Mandatory Fields</u></b>: Po Box, Notes, Transfer </li>'; inlineHtml += '<li><b><u>Download Template</u></b>: If you are a franchisee click on the "Download Template" button to download a template for your franchise. If you are not a franchisee, select a zee from the dropdown and then click on the download template button to download a template for that specific zee </li>'; inlineHtml += '<li><b><u>Delete Run</u></b>: Select a zee and then select a run from the relevant dropdowns. After clicking the Delete Run button, this entire run will be deleted. </li>'; inlineHtml += '<li><b><u>Export Run</u></b>: Select a zee and then select a run from the relevant dropdowns. After clicking the Export Run button, the entire run will be exported into a csv </li>'; inlineHtml += '<li><b><u>Non-Mandatory Fields</u></b>: Po Box, Notes, Transfer </li>'; inlineHtml += '<li>If you have any issues, please contact Head Office</li>'; inlineHtml += '</ul></div></div><br/>'; inlineHtml += progressBar(); if (role != 1000) { inlineHtml += franchiseeDropdownSection(context.request.parameters.zee); } if (!isNullorEmpty(context.request.parameters.zee)) { inlineHtml += runDropdownSection(context.request.parameters.zee, context.request.parameters.run); } form.addField({ id: 'scheduled_script', type: ui.FieldType.TEXT, label: 'scheduled_script' }).updateDisplayType({ displayType: ui.FieldDisplayType.HIDDEN }); form.addField({ id: 'preview_table', type: ui.FieldType.INLINEHTML, label: 'preview_table' }).updateLayoutType({ layoutType: ui.FieldLayoutType.OUTSIDEBELOW }).updateBreakType({ breakType: ui.FieldBreakType.STARTROW }).defaultValue = inlineHtml; form.addField({ id: 'upload_rs_csv', label: 'IMPORT EXCEL', type: ui.FieldType.FILE }); form.clientScriptFileId = 4620348; //PROD = 4620348, SB = 4602504 context.response.writePage(form); } else { var fileObj = context.request.files.upload_rs_csv; var zee = context.request.parameters.zee; if (!isNullorEmpty(fileObj)) { fileObj.folder = 2661964; //2644902, 2661964 var file_type = fileObj.fileType; if (file_type == 'CSV') { file_type == 'csv'; var file_name = zee + '_zee_rs_upload' + '.' + file_type; } fileObj.name = file_name; if (file_type == 'CSV') { // Create file and upload it to the file cabinet. var f_id = fileObj.save(); } else { throw error.create({ message: 'Must be in CSV format', name: 'CSV_ERROR', notifyOff: true }); } } log.debug({ title: 'fileid', details: f_id }); log.debug({ title: 'zee', details: zee }); // CALL SCHEDULED SCRIPT var scriptTask = task.create({ taskType: task.TaskType.SCHEDULED_SCRIPT }); scriptTask.scriptId = 'customscript_ss_import_excel'; scriptTask.deploymentId = 'customdeploy_ss_import_excel'; scriptTask.params = { custscript_import_excel_file_id: f_id, custscript_import_excel_zee_id: zee }; var ss_id = scriptTask.submit(); var myTaskStatus = task.checkStatus({ taskId: ss_id }); // Load jQuery var inlineHtml = '<script src="https://code.jquery.com/jquery-1.12.4.min.js" integrity="949d1u22cbffbrarjh182eig55721odj" crossorigin="anonymous"></script>'; // Load Tooltip inlineHtml += '<script src="https://unpkg.com/@popperjs/core@2"></script>'; // Load Bootstrap inlineHtml += '<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/3.4.1/css/bootstrap.min.css" integrity="caf86f4uutaoxfysmf7anj01xl6sv3ps" crossorigin="anonymous">'; inlineHtml += '<script src="https://stackpath.bootstrapcdn.com/bootstrap/3.4.1/js/bootstrap.min.js" integrity="74t3tndxag9o7h0890bnpfzh4olk2h9x" crossorigin="anonymous"></script>'; // Load DataTables inlineHtml += '<link rel="stylesheet" type="text/css" href="//cdn.datatables.net/1.10.21/css/jquery.dataTables.min.css">'; inlineHtml += '<script type="text/javascript" charset="utf8" src="//cdn.datatables.net/1.10.21/js/jquery.dataTables.min.js"></script>'; // Load Bootstrap-Select inlineHtml += '<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap-select@1.13.14/dist/css/bootstrap-select.min.css">'; inlineHtml += '<script src="https://cdn.jsdelivr.net/npm/bootstrap-select@1.13.14/dist/js/bootstrap-select.min.js"></script>'; // Load Netsuite stylesheet and script inlineHtml += '<link rel="stylesheet" href="https://1048144.app.netsuite.com/core/media/media.nl?id=2060796&c=1048144&h=9ee6accfd476c9cae718&_xt=.css"/>'; inlineHtml += '<script src="https://1048144.app.netsuite.com/core/media/media.nl?id=2060797&c=1048144&h=ef2cda20731d146b5e98&_xt=.js"></script>'; inlineHtml += '<link type="text/css" rel="stylesheet" href="https://1048144.app.netsuite.com/core/media/media.nl?id=2090583&c=1048144&h=a0ef6ac4e28f91203dfe&_xt=.css">'; inlineHtml += '<style>.mandatory{color:red;}</style>'; var file1 = file.load({ id: f_id }); var iterator = file1.lines.iterator(); // skip first line (header) iterator.each(function (line) { log.debug({ title: 'line', details: line }); return false; }); var numLines = 0; iterator.each(function (line) { var rs_values = line.value.split(/,(?=(?:(?:[^"]*"){2})*[^"]*$)/); var stop1_location = rs_values[9]; if (!isNullorEmpty(stop1_location)) { numLines++; } log.debug({ title: 'num lines', details: line }); return true; }); log.debug({ title: 'numLines', details: numLines }); inlineHtml += progressBar(); inlineHtml += dataTable(); var form = ui.createForm({ title: 'Import Excel DB' }); form.addField({ id: 'custpage_table_csv', type: ui.FieldType.TEXT, label: 'Table CSV' }).updateDisplayType({ displayType: ui.FieldDisplayType.HIDDEN }); form.addField({ id: 'preview_table', type: ui.FieldType.INLINEHTML, label: 'preview_table' }).updateLayoutType({ layoutType: ui.FieldLayoutType.OUTSIDEBELOW }).updateBreakType({ breakType: ui.FieldBreakType.STARTROW }).defaultValue = inlineHtml; form.addField({ id: 'excel_lines', type: ui.FieldType.TEXT, label: 'excel_lines' }).updateDisplayType({ displayType: ui.FieldDisplayType.HIDDEN }).defaultValue = numLines; form.addField({ id: 'scheduled_script', type: ui.FieldType.TEXT, label: 'scheduled_script' }).updateDisplayType({ displayType: ui.FieldDisplayType.HIDDEN }).defaultValue = ss_id; form.clientScriptFileId = 4620348; //PROD = 4620348, SB = 4602504 context.response.writePage(form); } } function isNullorEmpty(strVal) { return (strVal == null || strVal == '' || strVal == 'null' || strVal == undefined || strVal == 'undefined' || strVal == '- None -'); } /** * The Franchisee dropdown list. * @param {Number} zee_id * @return {String} `inlineQty` */ function franchiseeDropdownSection(params_zee) { var inlineQty = '<div class="form-group container zee_dropdown_section >'; //inlineQty += '<div class="row">'; // Franchisee dropdown field //inlineQty += '<div class="col-xs-12 zee_dropdown_div">'; inlineQty += '<div class="input-group">'; inlineQty += '<span class="input-group-addon" id="zee_dropdown_text">FRANCHISEE</span>'; inlineQty += '<select id="zee_dropdown" class="form-control zee_dropdown" required>'; inlineQty += '<option></option>'; // Load the franchisees options var zeesSearch = search.load({ id: 'customsearch_job_inv_process_zee', type: search.Type.PARTNER }); var zeesSearchResults = zeesSearch.run(); zeesSearchResults.each(function (zeesSearchResult) { var opt_zee_id = zeesSearchResult.getValue('internalid'); var opt_zee_name = zeesSearchResult.getValue('companyname'); var selected_option = ''; if (role == 1000) { zee_id = runtime.getCurrentUser().id; //Get Franchisee ID-- REMOVE TO TEST selected_option = (opt_zee_id == zee_id) ? 'selected' : ''; } if (!isNullorEmpty(params_zee)) { selected_option = (params_zee == opt_zee_id) ? 'selected' : ''; } inlineQty += '<option value="' + opt_zee_id + '" ' + selected_option + '>' + opt_zee_name + '</option>'; return true; }); inlineQty += '</select>'; inlineQty += '</div></div></div></div>'; return inlineQty; } function runDropdownSection(zee, params_run) { // var inlineQty = '<div class="container select_run">'; // inlineQty += '<div class="form-group container"><div class="row">'; // inlineQty += '<div class="input-group">'; // inlineQty += '<span class="input-group-addon">SELECT RUN</span>'; // inlineQty += '<select class="form-control run_dropdown" >'; var inlineQty = '<div class="form-group container select_run >'; //inlineQty += '<div class="row">'; // Franchisee dropdown field //inlineQty += '<div class="col-xs-12 select_dropdown_div">'; inlineQty += '<div class="input-group">'; inlineQty += '<span class="input-group-addon" id="zee_dropdown_text">SELECT RUN</span>'; inlineQty += '<select class="form-control run_dropdown" >'; var runPlanSearch = search.load({ id: 'customsearch_app_run_plan_active', type: 'customrecord_run_plan' }) var zee_record = record.load({ type: record.Type.PARTNER, id: parseInt(zee), isDynamic: true, }); var multi = zee_record.getValue({ fieldId: 'custentity_zee_multiple_territory' }) if (!isNullorEmpty(multi)) { runPlanSearch.filters.push(search.createFilter({ name: 'custrecord_run_franchisee', operator: search.Operator.ANYOF, values: zee })); } else { runPlanSearch.filters.push(search.createFilter({ name: 'custrecord_run_franchisee', operator: search.Operator.IS, values: zee })); } var resultSet_runPlan = runPlanSearch.run(); var count_zee = 0; inlineQty += '<option value="' + 0 + '"></option>' resultSet_runPlan.each(function(searchResult_runPlan) { runinternalid = searchResult_runPlan.getValue('internalid'); runname = searchResult_runPlan.getValue('name'); if (params_run == runinternalid) { inlineQty += '<option value="' + runinternalid + '" selected="selected">' + runname + '</option>'; } else { inlineQty += '<option value="' + runinternalid + '">' + runname + '</option>'; } return true; }); inlineQty += '</select></div></div></div></div>'; return inlineQty; } /** * The table that will display the differents invoices linked to the franchisee and the time period. * @return {String} inlineQty */ function dataTable() { var inlineQty = '<style>table#import_excel {font-size: 12px;text-align: center;border: none;}.dataTables_wrapper {font-size: 14px;}table#import_excel th{text-align: center;} .bolded{font-weight: bold;}</style>'; inlineQty += '<table id="import_excel" class="table table-responsive table-striped customer tablesorter" style="width: 100%;">'; inlineQty += '<thead style="color: white;background-color: #607799;">'; inlineQty += '<tr class="text-center">'; inlineQty += '</tr>'; inlineQty += '</thead>'; inlineQty += '<tbody id="result_import" class="result-import"></tbody>'; inlineQty += '</table>'; return inlineQty; } function onclick_deleteRun(zee, run) { // log.debug({ // title: 'infn', // details: 'infn' // }) // if (!isNullorEmpty(zee) && !isNullorEmpty(run)) { // log.debug({ // title: 'scheduled', // details: 'scheduled' // }) // params = { // custscript_delete_run_run_id_set: run // }; // reschedule = task.create({ // taskType: task.TaskType.SCHEDULED_SCRIPT, // scriptId: 'customscript_ss_delete_run', // deploymentId: 'customdeploy_ss_delete_run', // params: params // }); // log.audit({ // title: 'Attempting: Rescheduling Script', // details: reschedule // }); // reschedule.submit(); //} } /** * Display the progress bar. Initialized at 0, with the maximum value as the number of records that will be moved. * Uses Bootstrap : https://www.w3schools.com/bootstrap/bootstrap_progressbars.asp * @param {String} nb_records_total The number of records that will be moved * @return {String} inlineQty : The inline HTML string of the progress bar. */ function progressBar() { var inlineQty = '<div class="progress hide">'; inlineQty += '<div class="progress-bar progress-bar-striped progress-bar-warning" id="progress-records" role="progressbar" aria-valuenow="0" style="width:0%">0%</div>'; inlineQty += '</div>'; return inlineQty; } function getDate() { var date = (new Date()); // if (date.getHours() > 6) { // date = nlapiAddDays(date, 1); // } // date.setHours(date.getHours() + 17); var date_string = date.getFullYear() + '' + (date.getMonth() + 1) + '' + date.getDate() + '_' + date.getHours() + '' + date.getMinutes(); return date_string; } return { onRequest: onRequest }; });
true
/** * * @NApiVersion 2.0 * @NScriptType Suitelet * * Description: Import an excel file of stops to add into an existing run * @Last Modified by: Sruti Desai * */ define(['N/ui/serverWidget', 'N/email', 'N/runtime', 'N/search', 'N/record', 'N/http', 'N/log', 'N/redirect', 'N/format', 'N/file', 'N/error', 'N/task'], function(ui, email, runtime, search, record, http, log, redirect, format, file, error, task) { var baseURL = 'https://1048144.app.netsuite.com'; if (runtime.EnvType == "SANDBOX") { baseURL = 'https://1048144-sb3.app.netsuite.com'; } var zee = 0; var role = runtime.getCurrentUser().role; if (role == 1000) { //Franchisee zee = runtime.getCurrentUser().id; } function onRequest(context) { if (context.request.method === 'GET') { // Load jQuery var inlineHtml = '<script src="https://code.jquery.com/jquery-1.12.4.min.js" integrity="PI:KEY:949d1u22cbffbrarjh182eig55721odjEND_PI" crossorigin="anonymous"></script>'; // Load Tooltip inlineHtml += '<script src="https://unpkg.com/@popperjs/core@2"></script>'; // Load Bootstrap inlineHtml += '<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/3.4.1/css/bootstrap.min.css" integrity="PI:KEY:caf86f4uutaoxfysmf7anj01xl6sv3psEND_PI" crossorigin="anonymous">'; inlineHtml += '<script src="https://stackpath.bootstrapcdn.com/bootstrap/3.4.1/js/bootstrap.min.js" integrity="PI:KEY:74t3tndxag9o7h0890bnpfzh4olk2h9xEND_PI" crossorigin="anonymous"></script>'; // Load DataTables inlineHtml += '<link rel="stylesheet" type="text/css" href="//cdn.datatables.net/1.10.21/css/jquery.dataTables.min.css">'; inlineHtml += '<script type="text/javascript" charset="utf8" src="//cdn.datatables.net/1.10.21/js/jquery.dataTables.min.js"></script>'; // Load Bootstrap-Select inlineHtml += '<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap-select@1.13.14/dist/css/bootstrap-select.min.css">'; inlineHtml += '<script src="https://cdn.jsdelivr.net/npm/bootstrap-select@1.13.14/dist/js/bootstrap-select.min.js"></script>'; // Load Netsuite stylesheet and script inlineHtml += '<link rel="stylesheet" href="https://1048144.app.netsuite.com/core/media/media.nl?id=2060796&c=1048144&h=9ee6accfd476c9cae718&_xt=.css"/>'; inlineHtml += '<script src="https://1048144.app.netsuite.com/core/media/media.nl?id=2060797&c=1048144&h=ef2cda20731d146b5e98&_xt=.js"></script>'; inlineHtml += '<link type="text/css" rel="stylesheet" href="https://1048144.app.netsuite.com/core/media/media.nl?id=2090583&c=1048144&h=a0ef6ac4e28f91203dfe&_xt=.css">'; inlineHtml += '<style>.mandatory{color:red;}</style>'; var form = ui.createForm({ title: 'Import Excel' }); form.addButton({ id : 'import', label : 'Download Template', functionName : 'onclick_downloadButton()' }); form.addButton({ id : 'del_run', label : 'Delete Run', functionName : 'onclick_deleteRun()' }); form.addButton({ id : 'export_run', label : 'Export Run', functionName : 'onclick_exportRun()' }); form.addSubmitButton({ label: 'Import Run' }); if (role == 1000) { form.addField({ id: 'zee', type: ui.FieldType.TEXT, label: 'zee' }).updateDisplayType({ displayType: ui.FieldDisplayType.HIDDEN }).defaultValue = runtime.getCurrentUser().id; } if (!isNullorEmpty(context.request.parameters.zee) && context.request.parameters.zee != 0) { form.addField({ id: 'zee', type: ui.FieldType.TEXT, label: 'zee' }).updateDisplayType({ displayType: ui.FieldDisplayType.HIDDEN }).defaultValue = context.request.parameters.zee; } else { form.addField({ id: 'zee', type: ui.FieldType.TEXT, label: 'zee' }).updateDisplayType({ displayType: ui.FieldDisplayType.HIDDEN }).defaultValue = zee; } if (!isNullorEmpty(context.request.parameters.run) && context.request.parameters.run != 0) { form.addField({ id: 'run', type: ui.FieldType.TEXT, label: 'run' }).updateDisplayType({ displayType: ui.FieldDisplayType.HIDDEN }).defaultValue = context.request.parameters.run; var freqSearch = search.load({ id: 'customsearch_rp_servicefreq', type: 'customrecord_service_freq' }); freqSearch.filters.push(search.createFilter({ name: 'custrecord_service_freq_run_plan', operator: search.Operator.IS, values: context.request.parameters.run })); var initial_count = freqSearch.runPaged().count; form.addField({ id: 'initial_count', type: ui.FieldType.TEXT, label: 'initial_count' }).updateDisplayType({ displayType: ui.FieldDisplayType.HIDDEN }).defaultValue = initial_count; } else { form.addField({ id: 'run', type: ui.FieldType.TEXT, label: 'run' }).updateDisplayType({ displayType: ui.FieldDisplayType.HIDDEN }); } form.addField({ id: 'custpage_table_csv', type: ui.FieldType.TEXT, label: 'Table CSV' }).updateDisplayType({ displayType: ui.FieldDisplayType.HIDDEN }); form.addField({ id: 'custpage_export_run_csv', type: ui.FieldType.TEXT, label: 'Table CSV' }).updateDisplayType({ displayType: ui.FieldDisplayType.HIDDEN }); //Important Instructions box inlineHtml += '<br></br>' inlineHtml += '<div></div>'; inlineHtml += '<div class="form-group container test_section">'; //inlineHtml += '<button type="button" class="btn btn-sm btn-info instruction_button" data-toggle="collapse" data-target="#demo">Click for Instructions</button>'; //inlineHtml += '<div id="demo" style="background-color: #cfeefc !important;border: 1px solid #417ed9;padding: 20px 30px 30px 30px;width:96%;position:absolute" class="collapse"><b><u>IMPORTANT INSTRUCTIONS:</u></b>'; inlineHtml += '<div style=\"background-color: #cfeefc !important;border: 1px solid #417ed9;padding: 20px 30px 30px 30px\"><b><u>Important Instructions:</u></b>'; inlineHtml += '<ul><li><b><u>Please do not alter the columns titled Customer Internal ID, Customer Id, Customer Name, Service Id, Service Name and Price</u></b></li>'; inlineHtml += '<li><b><u>Frequency</u></b>: If the frequency of the service is multiple days then separate with a / i.e. Mon/Tue/Wed/Thurs/Fri. </li>'; inlineHtml += '<li><b><u>Frequency</u></b>: Frequency field can take input of Daily and Adhoc as well</li>'; inlineHtml += '<li><b><u>Customer or Non-Customer</u></b>: Please only enter in "Customer" or "Non-Customer" in this field </li>'; inlineHtml += '<li><b><u>Location (Customer)</u></b>: For a Customer Location please enter all address details in this single field i.e. "379-381 Victoria Street, Wetherill Park, NSW, 2164" </li>'; inlineHtml += '<li><b><u>Location (Non-Customer)</u></b>: For a Non-Customer Location please enter the exact name of the stop i.e. "ARNCLIFFE LPO" </li>'; inlineHtml += '<li><b><u>Duration</u></b>: Enter length of time in seconds only i.e. "120", where 120 is equal to 2 minutes </li>'; inlineHtml += '<li><b><u>Time</u></b>: Enter the time leg will occur in 12 hour time with a ":" separating the minutes and hours, and AM/PM following the time. i.e. "12:30PM" or "8:46AM" </li>'; inlineHtml += '<li><b><u>Notes</u></b>: Enter the necessary notes (in any format) required for each stop in the relevant fields </li>'; inlineHtml += '<li><b><u>Run Name</u></b>: Enter the exact Run-Name as it appears on Netsuite i.e. "Danilo\'s" or "Mascot" or "Multi Run" </li>'; inlineHtml += '<li><b><u>Non-Mandatory Fields</u></b>: Po Box, Notes, Transfer </li>'; inlineHtml += '<li><b><u>Download Template</u></b>: If you are a franchisee click on the "Download Template" button to download a template for your franchise. If you are not a franchisee, select a zee from the dropdown and then click on the download template button to download a template for that specific zee </li>'; inlineHtml += '<li><b><u>Delete Run</u></b>: Select a zee and then select a run from the relevant dropdowns. After clicking the Delete Run button, this entire run will be deleted. </li>'; inlineHtml += '<li><b><u>Export Run</u></b>: Select a zee and then select a run from the relevant dropdowns. After clicking the Export Run button, the entire run will be exported into a csv </li>'; inlineHtml += '<li><b><u>Non-Mandatory Fields</u></b>: Po Box, Notes, Transfer </li>'; inlineHtml += '<li>If you have any issues, please contact Head Office</li>'; inlineHtml += '</ul></div></div><br/>'; inlineHtml += progressBar(); if (role != 1000) { inlineHtml += franchiseeDropdownSection(context.request.parameters.zee); } if (!isNullorEmpty(context.request.parameters.zee)) { inlineHtml += runDropdownSection(context.request.parameters.zee, context.request.parameters.run); } form.addField({ id: 'scheduled_script', type: ui.FieldType.TEXT, label: 'scheduled_script' }).updateDisplayType({ displayType: ui.FieldDisplayType.HIDDEN }); form.addField({ id: 'preview_table', type: ui.FieldType.INLINEHTML, label: 'preview_table' }).updateLayoutType({ layoutType: ui.FieldLayoutType.OUTSIDEBELOW }).updateBreakType({ breakType: ui.FieldBreakType.STARTROW }).defaultValue = inlineHtml; form.addField({ id: 'upload_rs_csv', label: 'IMPORT EXCEL', type: ui.FieldType.FILE }); form.clientScriptFileId = 4620348; //PROD = 4620348, SB = 4602504 context.response.writePage(form); } else { var fileObj = context.request.files.upload_rs_csv; var zee = context.request.parameters.zee; if (!isNullorEmpty(fileObj)) { fileObj.folder = 2661964; //2644902, 2661964 var file_type = fileObj.fileType; if (file_type == 'CSV') { file_type == 'csv'; var file_name = zee + '_zee_rs_upload' + '.' + file_type; } fileObj.name = file_name; if (file_type == 'CSV') { // Create file and upload it to the file cabinet. var f_id = fileObj.save(); } else { throw error.create({ message: 'Must be in CSV format', name: 'CSV_ERROR', notifyOff: true }); } } log.debug({ title: 'fileid', details: f_id }); log.debug({ title: 'zee', details: zee }); // CALL SCHEDULED SCRIPT var scriptTask = task.create({ taskType: task.TaskType.SCHEDULED_SCRIPT }); scriptTask.scriptId = 'customscript_ss_import_excel'; scriptTask.deploymentId = 'customdeploy_ss_import_excel'; scriptTask.params = { custscript_import_excel_file_id: f_id, custscript_import_excel_zee_id: zee }; var ss_id = scriptTask.submit(); var myTaskStatus = task.checkStatus({ taskId: ss_id }); // Load jQuery var inlineHtml = '<script src="https://code.jquery.com/jquery-1.12.4.min.js" integrity="PI:KEY:949d1u22cbffbrarjh182eig55721odjEND_PI" crossorigin="anonymous"></script>'; // Load Tooltip inlineHtml += '<script src="https://unpkg.com/@popperjs/core@2"></script>'; // Load Bootstrap inlineHtml += '<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/3.4.1/css/bootstrap.min.css" integrity="PI:KEY:caf86f4uutaoxfysmf7anj01xl6sv3psEND_PI" crossorigin="anonymous">'; inlineHtml += '<script src="https://stackpath.bootstrapcdn.com/bootstrap/3.4.1/js/bootstrap.min.js" integrity="PI:KEY:74t3tndxag9o7h0890bnpfzh4olk2h9xEND_PI" crossorigin="anonymous"></script>'; // Load DataTables inlineHtml += '<link rel="stylesheet" type="text/css" href="//cdn.datatables.net/1.10.21/css/jquery.dataTables.min.css">'; inlineHtml += '<script type="text/javascript" charset="utf8" src="//cdn.datatables.net/1.10.21/js/jquery.dataTables.min.js"></script>'; // Load Bootstrap-Select inlineHtml += '<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap-select@1.13.14/dist/css/bootstrap-select.min.css">'; inlineHtml += '<script src="https://cdn.jsdelivr.net/npm/bootstrap-select@1.13.14/dist/js/bootstrap-select.min.js"></script>'; // Load Netsuite stylesheet and script inlineHtml += '<link rel="stylesheet" href="https://1048144.app.netsuite.com/core/media/media.nl?id=2060796&c=1048144&h=9ee6accfd476c9cae718&_xt=.css"/>'; inlineHtml += '<script src="https://1048144.app.netsuite.com/core/media/media.nl?id=2060797&c=1048144&h=ef2cda20731d146b5e98&_xt=.js"></script>'; inlineHtml += '<link type="text/css" rel="stylesheet" href="https://1048144.app.netsuite.com/core/media/media.nl?id=2090583&c=1048144&h=a0ef6ac4e28f91203dfe&_xt=.css">'; inlineHtml += '<style>.mandatory{color:red;}</style>'; var file1 = file.load({ id: f_id }); var iterator = file1.lines.iterator(); // skip first line (header) iterator.each(function (line) { log.debug({ title: 'line', details: line }); return false; }); var numLines = 0; iterator.each(function (line) { var rs_values = line.value.split(/,(?=(?:(?:[^"]*"){2})*[^"]*$)/); var stop1_location = rs_values[9]; if (!isNullorEmpty(stop1_location)) { numLines++; } log.debug({ title: 'num lines', details: line }); return true; }); log.debug({ title: 'numLines', details: numLines }); inlineHtml += progressBar(); inlineHtml += dataTable(); var form = ui.createForm({ title: 'Import Excel DB' }); form.addField({ id: 'custpage_table_csv', type: ui.FieldType.TEXT, label: 'Table CSV' }).updateDisplayType({ displayType: ui.FieldDisplayType.HIDDEN }); form.addField({ id: 'preview_table', type: ui.FieldType.INLINEHTML, label: 'preview_table' }).updateLayoutType({ layoutType: ui.FieldLayoutType.OUTSIDEBELOW }).updateBreakType({ breakType: ui.FieldBreakType.STARTROW }).defaultValue = inlineHtml; form.addField({ id: 'excel_lines', type: ui.FieldType.TEXT, label: 'excel_lines' }).updateDisplayType({ displayType: ui.FieldDisplayType.HIDDEN }).defaultValue = numLines; form.addField({ id: 'scheduled_script', type: ui.FieldType.TEXT, label: 'scheduled_script' }).updateDisplayType({ displayType: ui.FieldDisplayType.HIDDEN }).defaultValue = ss_id; form.clientScriptFileId = 4620348; //PROD = 4620348, SB = 4602504 context.response.writePage(form); } } function isNullorEmpty(strVal) { return (strVal == null || strVal == '' || strVal == 'null' || strVal == undefined || strVal == 'undefined' || strVal == '- None -'); } /** * The Franchisee dropdown list. * @param {Number} zee_id * @return {String} `inlineQty` */ function franchiseeDropdownSection(params_zee) { var inlineQty = '<div class="form-group container zee_dropdown_section >'; //inlineQty += '<div class="row">'; // Franchisee dropdown field //inlineQty += '<div class="col-xs-12 zee_dropdown_div">'; inlineQty += '<div class="input-group">'; inlineQty += '<span class="input-group-addon" id="zee_dropdown_text">FRANCHISEE</span>'; inlineQty += '<select id="zee_dropdown" class="form-control zee_dropdown" required>'; inlineQty += '<option></option>'; // Load the franchisees options var zeesSearch = search.load({ id: 'customsearch_job_inv_process_zee', type: search.Type.PARTNER }); var zeesSearchResults = zeesSearch.run(); zeesSearchResults.each(function (zeesSearchResult) { var opt_zee_id = zeesSearchResult.getValue('internalid'); var opt_zee_name = zeesSearchResult.getValue('companyname'); var selected_option = ''; if (role == 1000) { zee_id = runtime.getCurrentUser().id; //Get Franchisee ID-- REMOVE TO TEST selected_option = (opt_zee_id == zee_id) ? 'selected' : ''; } if (!isNullorEmpty(params_zee)) { selected_option = (params_zee == opt_zee_id) ? 'selected' : ''; } inlineQty += '<option value="' + opt_zee_id + '" ' + selected_option + '>' + opt_zee_name + '</option>'; return true; }); inlineQty += '</select>'; inlineQty += '</div></div></div></div>'; return inlineQty; } function runDropdownSection(zee, params_run) { // var inlineQty = '<div class="container select_run">'; // inlineQty += '<div class="form-group container"><div class="row">'; // inlineQty += '<div class="input-group">'; // inlineQty += '<span class="input-group-addon">SELECT RUN</span>'; // inlineQty += '<select class="form-control run_dropdown" >'; var inlineQty = '<div class="form-group container select_run >'; //inlineQty += '<div class="row">'; // Franchisee dropdown field //inlineQty += '<div class="col-xs-12 select_dropdown_div">'; inlineQty += '<div class="input-group">'; inlineQty += '<span class="input-group-addon" id="zee_dropdown_text">SELECT RUN</span>'; inlineQty += '<select class="form-control run_dropdown" >'; var runPlanSearch = search.load({ id: 'customsearch_app_run_plan_active', type: 'customrecord_run_plan' }) var zee_record = record.load({ type: record.Type.PARTNER, id: parseInt(zee), isDynamic: true, }); var multi = zee_record.getValue({ fieldId: 'custentity_zee_multiple_territory' }) if (!isNullorEmpty(multi)) { runPlanSearch.filters.push(search.createFilter({ name: 'custrecord_run_franchisee', operator: search.Operator.ANYOF, values: zee })); } else { runPlanSearch.filters.push(search.createFilter({ name: 'custrecord_run_franchisee', operator: search.Operator.IS, values: zee })); } var resultSet_runPlan = runPlanSearch.run(); var count_zee = 0; inlineQty += '<option value="' + 0 + '"></option>' resultSet_runPlan.each(function(searchResult_runPlan) { runinternalid = searchResult_runPlan.getValue('internalid'); runname = searchResult_runPlan.getValue('name'); if (params_run == runinternalid) { inlineQty += '<option value="' + runinternalid + '" selected="selected">' + runname + '</option>'; } else { inlineQty += '<option value="' + runinternalid + '">' + runname + '</option>'; } return true; }); inlineQty += '</select></div></div></div></div>'; return inlineQty; } /** * The table that will display the differents invoices linked to the franchisee and the time period. * @return {String} inlineQty */ function dataTable() { var inlineQty = '<style>table#import_excel {font-size: 12px;text-align: center;border: none;}.dataTables_wrapper {font-size: 14px;}table#import_excel th{text-align: center;} .bolded{font-weight: bold;}</style>'; inlineQty += '<table id="import_excel" class="table table-responsive table-striped customer tablesorter" style="width: 100%;">'; inlineQty += '<thead style="color: white;background-color: #607799;">'; inlineQty += '<tr class="text-center">'; inlineQty += '</tr>'; inlineQty += '</thead>'; inlineQty += '<tbody id="result_import" class="result-import"></tbody>'; inlineQty += '</table>'; return inlineQty; } function onclick_deleteRun(zee, run) { // log.debug({ // title: 'infn', // details: 'infn' // }) // if (!isNullorEmpty(zee) && !isNullorEmpty(run)) { // log.debug({ // title: 'scheduled', // details: 'scheduled' // }) // params = { // custscript_delete_run_run_id_set: run // }; // reschedule = task.create({ // taskType: task.TaskType.SCHEDULED_SCRIPT, // scriptId: 'customscript_ss_delete_run', // deploymentId: 'customdeploy_ss_delete_run', // params: params // }); // log.audit({ // title: 'Attempting: Rescheduling Script', // details: reschedule // }); // reschedule.submit(); //} } /** * Display the progress bar. Initialized at 0, with the maximum value as the number of records that will be moved. * Uses Bootstrap : https://www.w3schools.com/bootstrap/bootstrap_progressbars.asp * @param {String} nb_records_total The number of records that will be moved * @return {String} inlineQty : The inline HTML string of the progress bar. */ function progressBar() { var inlineQty = '<div class="progress hide">'; inlineQty += '<div class="progress-bar progress-bar-striped progress-bar-warning" id="progress-records" role="progressbar" aria-valuenow="0" style="width:0%">0%</div>'; inlineQty += '</div>'; return inlineQty; } function getDate() { var date = (new Date()); // if (date.getHours() > 6) { // date = nlapiAddDays(date, 1); // } // date.setHours(date.getHours() + 17); var date_string = date.getFullYear() + '' + (date.getMonth() + 1) + '' + date.getDate() + '_' + date.getHours() + '' + date.getMinutes(); return date_string; } return { onRequest: onRequest }; });
/** * @NApiVersion 2.x * @NScriptType UserEventScript * @NModuleScope SameAccount */ define(['N/file', 'N/sftp', 'N/error'], function(file, sftp, error) { return { beforeLoad: function(){ var portNumber = -1; var connectTimeout = -1; var transferTimeout = -1; //these variables can be taken as parameters of the script instead if (portNumber < sftp.MIN_PORT_NUMBER || portNumber > sftp.MAX_PORT_NUMBER) portNumber = sftp.DEFAULT_PORT_NUMBER; if (connectTimeout < sftp.MIN_CONNECT_TIMEOUT) connectTimeout = sftp.MIN_CONNECT_TIMEOUT; else if (connectTimeout > sftp.MAX_CONNECT_TIMEOUT) connectTimeout = sftp.MAX_CONNECT_TIMEOUT; var connection = sftp.createConnection({ username: 'sftpuser', keyId: 'custkey1', url: '192.168.0.100', port: portNumber, directory: 'inbound', timeout: connectTimeout, hostKey: "AAAAB3NzaC1yc2EAAAADAQABAAABAQDMifKH2vTxdiype8nem7+lS3x7dTQR/A67KdsR/5C2WUcDipBzYhHbnG6Am12Nd2tlM01LnaBZA6/8P4Y9x/sGTxtsdE/MzeGDUBn6HBlQvgIrhX62wgoKGQ+P2lEAO1+Vz8y3/MB1NmD7Fc62cJ9Mu88YA6jwJOIPZeHYNVyIm9OrY6VyzYyvSJhH0x7SXyvGnijJQF4G8C4c8u/UVpF/sE16xKZtly2Rx0aDL2FsDRtpyPmM602/R6ISbsmgab3MzzAEIu+zLDMdIBJn3cDhNt1F7Rar6Tu0u18KCkk8GPxbnxDuG4sCNOnXPYkDXSMUbM/ocRjYGtqdZUMmeTf3" }); // can also be a big file (created for example by async search) var myFileToUpload = file.create({ name: 'originalname.txt', fileType: file.Type.PLAINTEXT, contents: 'I am a test file.' }); if (myFileToUpload.size > connection.MAX_FILE_SIZE) throw error.create({name:"FILE_IS_TOO_BIG", message:"The file you are trying to upload is too big"}); var minTransferTimeout = 10; if (transferTimeout > connection.MAX_TRANSFER_TIMEOUT) transferTimeout = connection.MAX_TRANSFER_TIMEOUT; else if (transferTimeout < minTransferTimeout) transferTimeout = minTransferTimteout; connection.upload({ directory: 'files', filename: 'test.txt', file: myFileToUpload, replaceExisting: true, timeout: transferTimeout }); } }; });
1,035
[{"tag": "IP_ADDRESS", "value": "192.168.0.100", "start": 927, "end": 940}, {"tag": "KEY", "value": "AAAAB3NzaC1yc2EAAAADAQABAAABAQDMifKH2vTxdiype8nem7+lS3x7dTQR/A67KdsR/5C2WUcDipBzYhHbnG6Am12Nd2tlM01LnaBZA6/8P4Y9x/sGTxtsdE/MzeGDUBn6HBlQvgIrhX62wgoKGQ+P2lEAO1+Vz8y3/MB1NmD7Fc62cJ9Mu88YA6jwJOIPZeHYNVyIm9OrY6VyzYyvSJhH0x7SXyvGnijJQF4G8C4c8u/UVpF/sE16xKZtly2Rx0aDL2FsDRtpyPmM602/R6ISbsmgab3MzzAEIu+zLDMdIBJn3cDhNt1F7Rar6Tu0u18KCkk8GPxbnxDuG4sCNOnXPYkDXSMUbM/ocRjYGtqdZUMmeTf3", "start": 1082, "end": 1454}]
true
2
/** * @NApiVersion 2.x * @NScriptType UserEventScript * @NModuleScope SameAccount */ define(['N/file', 'N/sftp', 'N/error'], function(file, sftp, error) { return { beforeLoad: function(){ var portNumber = -1; var connectTimeout = -1; var transferTimeout = -1; //these variables can be taken as parameters of the script instead if (portNumber < sftp.MIN_PORT_NUMBER || portNumber > sftp.MAX_PORT_NUMBER) portNumber = sftp.DEFAULT_PORT_NUMBER; if (connectTimeout < sftp.MIN_CONNECT_TIMEOUT) connectTimeout = sftp.MIN_CONNECT_TIMEOUT; else if (connectTimeout > sftp.MAX_CONNECT_TIMEOUT) connectTimeout = sftp.MAX_CONNECT_TIMEOUT; var connection = sftp.createConnection({ username: 'sftpuser', keyId: 'custkey1', url: '192.168.0.100', port: portNumber, directory: 'inbound', timeout: connectTimeout, hostKey: "9q3vfhm7l33rus21toc8fndupq76itje" }); // can also be a big file (created for example by async search) var myFileToUpload = file.create({ name: 'originalname.txt', fileType: file.Type.PLAINTEXT, contents: 'I am a test file.' }); if (myFileToUpload.size > connection.MAX_FILE_SIZE) throw error.create({name:"FILE_IS_TOO_BIG", message:"The file you are trying to upload is too big"}); var minTransferTimeout = 10; if (transferTimeout > connection.MAX_TRANSFER_TIMEOUT) transferTimeout = connection.MAX_TRANSFER_TIMEOUT; else if (transferTimeout < minTransferTimeout) transferTimeout = minTransferTimteout; connection.upload({ directory: 'files', filename: 'test.txt', file: myFileToUpload, replaceExisting: true, timeout: transferTimeout }); } }; });
true
/** * @NApiVersion 2.x * @NScriptType UserEventScript * @NModuleScope SameAccount */ define(['N/file', 'N/sftp', 'N/error'], function(file, sftp, error) { return { beforeLoad: function(){ var portNumber = -1; var connectTimeout = -1; var transferTimeout = -1; //these variables can be taken as parameters of the script instead if (portNumber < sftp.MIN_PORT_NUMBER || portNumber > sftp.MAX_PORT_NUMBER) portNumber = sftp.DEFAULT_PORT_NUMBER; if (connectTimeout < sftp.MIN_CONNECT_TIMEOUT) connectTimeout = sftp.MIN_CONNECT_TIMEOUT; else if (connectTimeout > sftp.MAX_CONNECT_TIMEOUT) connectTimeout = sftp.MAX_CONNECT_TIMEOUT; var connection = sftp.createConnection({ username: 'sftpuser', keyId: 'custkey1', url: '192.168.0.100', port: portNumber, directory: 'inbound', timeout: connectTimeout, hostKey: "PI:KEY:9q3vfhm7l33rus21toc8fndupq76itjeEND_PI" }); // can also be a big file (created for example by async search) var myFileToUpload = file.create({ name: 'originalname.txt', fileType: file.Type.PLAINTEXT, contents: 'I am a test file.' }); if (myFileToUpload.size > connection.MAX_FILE_SIZE) throw error.create({name:"FILE_IS_TOO_BIG", message:"The file you are trying to upload is too big"}); var minTransferTimeout = 10; if (transferTimeout > connection.MAX_TRANSFER_TIMEOUT) transferTimeout = connection.MAX_TRANSFER_TIMEOUT; else if (transferTimeout < minTransferTimeout) transferTimeout = minTransferTimteout; connection.upload({ directory: 'files', filename: 'test.txt', file: myFileToUpload, replaceExisting: true, timeout: transferTimeout }); } }; });
/** * @NApiVersion 2.1 * @NScriptType UserEventScript */ define(['N/file', 'N/http', 'N/search', 'N/xml', 'N/record', 'N/query'], /** * @param{file} file * @param{http} http * @param{search} search * @param{xml} xml */ (file, http, search, xml, record, query) => { /** * Defines the function definition that is executed before record is loaded. * @param {Object} scriptContext * @param {Record} scriptContext.newRecord - New record * @param {string} scriptContext.type - Trigger type; use values from the context.UserEventType enum * @param {Form} scriptContext.form - Current form * @param {ServletRequest} scriptContext.request - HTTP request information sent from the browser for a client action only. * @since 2015.2 */ const beforeLoad = (scriptContext) => { } /** * Defines the function definition that is executed before record is submitted. * @param {Object} scriptContext * @param {Record} scriptContext.newRecord - New record * @param {Record} scriptContext.oldRecord - Old record * @param {string} scriptContext.type - Trigger type; use values from the context.UserEventType enum * @since 2015.2 */ const beforeSubmit = (scriptContext) => { } /** * Defines the function definition that is executed after record is submitted. * @param {Object} scriptContext * @param {Record} scriptContext.newRecord - New record * @param {Record} scriptContext.oldRecord - Old record * @param {string} scriptContext.type - Trigger type; use values from the context.UserEventType enum * @since 2015.2 */ const afterSubmit = (scriptContext) => { try { if( scriptContext.type === scriptContext.UserEventType.CREATE ) { // Se actualiza el campo tipo check var custom = scriptContext.newRecord;// Get edited customer var customerInfo = search.lookupFields({ type: search.Type.CUSTOMER, id: custom.id, columns: ['entityid'] }); let entityid = customerInfo.entityid; let count = entityid.length; while (count < 10) { entityid = "0".concat(entityid); count ++; } record.submitFields({ type: record.Type.CUSTOMER, id: custom.id, values: { 'entityid': entityid, } }); record.submitFields({ type: record.Type.CUSTOMER, id: custom.id, values: { 'custentity_ptg_cliente_act_sgc': "T", } }); log.debug('entityid', entityid); } return; let idToken = login(); if ( scriptContext.type === scriptContext.UserEventType.EDIT || scriptContext.type === scriptContext.UserEventType.CREATE ) { log.debug('Info', 'EdiciΓ³n de cliente'); let actionType = scriptContext.type === scriptContext.UserEventType.EDIT ? 'edit' : 'new'; let rowCustomer = scriptContext.newRecord;// Get edited customer let internalFileId = searchXmlFile(); let customerAddresses = searchCustomerAddresses(rowCustomer.id); let customerInfo = search.lookupFields({ type: search.Type.CUSTOMER, id: rowCustomer.id, columns: ['companyname', 'altname', 'phone', 'altphone', 'email', 'balance', 'entityid'] }); let tipo_pago = ( actionType == 'edit' ? rowCustomer.getValue({fieldId: 'custentity_ptg_alianza_comercial_cliente'}) : rowCustomer.getValue({fieldId:'custentity_ptg_alianza_comercial_cliente'}) ); let idPoliticaVenta = tipo_pago == 2 ? 'CREDITO_DEFAULT' : 'CONTADO'; log.debug('customerInfo', customerInfo); // log.debug('entityId', entityId); // return; // let dirDefault = searchDefaultAddress(search, rowCustomer); // let isConsumer = rowCustomer.getValue({fieldId:'parent'}); // log.debug('Alianza comercial', rowCustomer.getValue({fieldId: 'custentity_ptg_alianza_comercial_cliente'})); // log.debug('Alianza comercial texto', rowCustomer.getText({fieldId: 'custentity_ptg_alianza_comercial_cliente'})); // log.debug('LΓ­mite de crΓ©dito', rowCustomer.getValue({fieldId: 'creditlimit'})); // log.debug('Politica de venta', rowCustomer.getValue({fieldId:'custentity_ptg_politicadeventa_'})); // log.debug('Politica de consumo', rowCustomer.getValue({fieldId:'custentity_ptg_politicadeconsumo_cliente'})); // log.debug('Xml ID', internalFileId); // log.debug('Listado de direcciones', customerAddresses); // log.debug('data customer', dataToSend); // return; let typeModule = action = responseConsPol = dataCustomer = ''; let xmlContent = file.load({ id: internalFileId }).getContents(); // Se da de alta la polΓ­tica de venta // typeModule = "PoliticasVenta"; // action = "registrar"; // dataSalesPolicy = setDataSalesPolicy(rowCustomer, customerInfo, actionType); // responseConsPol = registerSgcData(xmlContent, idToken, typeModule, action, dataSalesPolicy); // log.debug('Info', 'EntrΓ³ a registrar una polΓ­tica de venta'); // if (["1111", "0000"].includes(responseConsPol.code[0].textContent) ) { // log.debug('SGC', 'PolΓ­tica de venta registrada'); // log.debug('Respuesta sgcweb polΓ­tica de venta', responseConsPol.info); // } else { // log.debug('OcurriΓ³ un error en polΓ­ticas de venta', responseConsPol.code[0].textContent); // } // return; // Se da de alta el cliente typeModule = "Clientes"; action = "registrar"; dataCustomer = setDataCustomer(rowCustomer, customerInfo, idPoliticaVenta, customerAddresses.default, actionType); // dataCustomer = setDataCustomer(rowCustomer, customerInfo, dataSalesPolicy.identificador_externo, customerAddresses.default, actionType); responseCustomer = registerSgcData(xmlContent, idToken, typeModule, action, dataCustomer); log.debug('Info', 'EntrΓ³ a registrar un cliente'); if (["1111", "0000"].includes(responseCustomer.code[0].textContent) ) { log.debug('SGC', 'Cliente registrado correctamente'); let realResult = JSON.parse(responseCustomer.info[0].textContent); log.debug('Respuesta sgcweb cliente', realResult); log.debug('NΓΊmero de cliente de sgcweb', realResult.numero_cliente); // Se edita el campo custentity_ptg_extermal_id para empatarlo con SGC Web record.submitFields({ type: record.Type.CUSTOMER, id: rowCustomer.id, values: { 'custentity_ptg_codigodecliente_': realResult.numero_cliente } }); log.debug('ActualizaciΓ³n', 'CΓ³digo de cliente actualizado'); } else { log.debug('OcurriΓ³ un error en clientes', responseCustomer.code[0].textContent); } // return 'Hola'; // Se dan de alta los registros de consumidores y polΓ­ticas de consumo let allAddress = customerAddresses.addresses; for (let j = 0; j < allAddress.length; j++) { typeModule = "PoliticasConsumo"; action = "registrar"; dataConsumptionPolicy = setDataConsumptionPolicy(rowCustomer, allAddress[j], actionType); responseConsumptionPolicy = registerSgcData(xmlContent, idToken, typeModule, action, dataConsumptionPolicy); log.debug('Info', 'EntrΓ³ a registrar una polΓ­tica de consumo'); // Se validarΓ‘ que haya salido bien el response if (["1111", "0000"].includes(responseConsumptionPolicy.code[0].textContent) ) { log.debug('SGC', 'PolΓ­tica de consumo registrada'); log.debug('Respuesta sgcweb polΓ­tica de consumo', responseConsumptionPolicy.info); // Se da de alta el consumidor junto con su polΓ­tica de consumo reciΓ©n creada typeModule = "Consumidores"; action = "registrar"; dataConsumer = setDataConsumer(rowCustomer, customerInfo, dataConsumptionPolicy.identificador_externo, dataCustomer.identificador_externo, allAddress[j], actionType); responseConsumer = registerSgcData(xmlContent, idToken, typeModule, action, dataConsumer); log.debug('Info', 'EntrΓ³ a registrar un consumidor'); if (["1111", "0000"].includes(responseConsumer.code[0].textContent) ) { log.debug('SGC', 'Consumidor registrado correctamente'); let realResult = JSON.parse(responseConsumer.info[0].textContent); log.debug('Respuesta sgcweb consumidor', realResult); log.debug('NΓΊmero de consumidor de sgcweb', realResult.numero_consumidor); // Se edita el campo custentity_ptg_numero_consumidor para empatarlo con SGC Web // record.submitFields({ // type: record.Type.CUSTOMER, // id: rowCustomer.id, // values: { // 'custentity_ptg_codigodecliente_': realResult.numero_consumidor // } // }); // log.debug('ActualizaciΓ³n', 'CΓ³digo de cliente actualizado'); } else { log.debug('OcurriΓ³ un error en consumidores', responseConsumer.code[0].textContent); } } else { log.debug('OcurriΓ³ un error en polΓ­ticas de consumo', responseConsumptionPolicy.code[0].textContent); } } return {'msg':'Γ‰xito guardando datos en SGC web', 'status' : 'success'}; } } catch (error) { log.debug('Algo saliΓ³ mal', error); } } // Login const login = () => { let resFileId; let fileSearchObj = search.create({ type: "file", filters: [ ["name", "haskeywords", "login"] ], columns: [ search.createColumn({ name: "name", sort: search.Sort.ASC, label: "Name" }), search.createColumn({ name: "folder", label: "Folder" }), search.createColumn({ name: "documentsize", label: "Size (KB)" }), search.createColumn({ name: "url", label: "URL" }), search.createColumn({ name: "created", label: "Date Created" }), search.createColumn({ name: "modified", label: "Last Modified" }), search.createColumn({ name: "filetype", label: "Type" }), search.createColumn({ name: "internalid", label: "Internal ID" }) ] }); // let searchResultCount = fileSearchObj.runPaged().count; // log.debug("fileSearchObj result count", searchResultCount); fileSearchObj.run().each(function (result) { // log.debug('Resultado peticiΓ³n', result); // .run().each has a limit of 4,000 results resFileId = result.getValue({ name: "internalid", label: "Internal ID" }); return true; }); let xmlContent = file.load({ id: resFileId }).getContents(); // log.debug('xmlContent', xmlContent); let headers = {}; headers['Content-Type'] = 'text/xml; charset=utf-8'; headers['SOAPAction'] = 'http://potogas.sgcweb.com.mx/ws/1094AEV2/v2/soap.php/login'; let url = 'http://potogas.sgcweb.com.mx/ws/1094AEV2/v2/soap.php'; // Method, url, body, headers let response = http.request({ method: http.Method.POST, url: url, body: xmlContent, headers: headers }); // log.debug('response', response.body) let xmlFileContent = response.body; let xmlDocument = xml.Parser.fromString({ text: xmlFileContent }); let dataJson = xmlDocument.getElementsByTagName({ tagName: 'id' }); // log.debug('response status', dataJson) let objResult = dataJson[0].textContent; // log.debug('objResult', objResult) return objResult; } // Busqueda guardada para obtener el archivo xml de peticiones a la api de SGC web const searchXmlFile = () => { // log.debug('info', 'entrΓ³ a la funciΓ³n de buscar archivo xml para peticiones'); let internalFileId; let fileSearchObj = search.create({ type: "file", filters: [ ["name", "haskeywords", "procesarPeticion"] ], columns: [ search.createColumn({ name: "name", sort: search.Sort.ASC, label: "Name" }), search.createColumn({ name: "folder", label: "Folder" }), search.createColumn({ name: "documentsize", label: "Size (KB)" }), search.createColumn({ name: "url", label: "URL" }), search.createColumn({ name: "created", label: "Date Created" }), search.createColumn({ name: "modified", label: "Last Modified" }), search.createColumn({ name: "filetype", label: "Type" }), search.createColumn({ name: "internalid", label: "Internal ID" }) ] }); // let searchResultCount = fileSearchObj.runPaged().count; // log.debug("fileSearchObj result count", searchResultCount); fileSearchObj.run().each(function (result) { // .run().each has a limit of 4,000 results internalFileId = result.getValue({ name: "internalid", label: "Internal ID" }); return true; }); return internalFileId; } // Configura los datos a enviar del cliente a SGC web const setDataCustomer = (rowCustomer, aditionalCustomerInfo = false, politicaId, defaultAddress, type) => { // log.debug('info', 'entrΓ³ a la funciΓ³n de configurar la informaciΓ³n del cliente'); let entityId = aditionalCustomerInfo.entityid; let nombre = ( type == 'edit' ? rowCustomer.getText({fieldId:'altname'}) : aditionalCustomerInfo?.altname ); // let nombre = ( type == 'edit' ? rowCustomer.getText({fieldId:'companyname'}) : aditionalCustomerInfo?.companyname ); let rfc = ( type == 'edit' ? rowCustomer.getText({fieldId:'custentity_mx_rfc'}) : rowCustomer.getValue({fieldId:'custentity_mx_rfc'}) ); // let telefono1 = ( type == 'edit' ? rowCustomer.getText({fieldId:'phone'}) : rowCustomer.getValue({fieldId:'phone'}) ); let telefono2 = ( type == 'edit' ? rowCustomer.getText({fieldId:'altphone'}) : rowCustomer.getValue({fieldId:'altphone'}) ); let email = ( type == 'edit' ? rowCustomer.getText({fieldId:'email'}) : rowCustomer.getValue({fieldId:'email'}) ); let saldo = ( type == 'edit' ? rowCustomer.getText({fieldId:'balance'}) : rowCustomer.getValue({fieldId:'balance'}) ); saldo = ( saldo ? Number( parseFloat( saldo ).toFixed(2) ) : 0.00); let data = { "numero_cliente":"", "identificador_externo": entityId, "nombre":nombre ? nombre : "Nombre cliente", "rfc":rfc ? rfc : "XAXX010101000", "calle":defaultAddress.calle ?? "", "no_exterior":defaultAddress.numExt ?? "", "no_interior":defaultAddress.numInt ?? "", "colonia":defaultAddress.colonia ?? "", "localidad":defaultAddress.ciudad ?? "", "referencia":defaultAddress.entreCalle1 ?? "", "ciudad":defaultAddress.ciudad ?? "", "estado":defaultAddress.estado ?? "", "codigo_postal":( defaultAddress.codigo_postal ?? "31135" ), "pais":defaultAddress.pais ?? "", "telefono1":defaultAddress.telefonoPrincipal ?? "4448111213", "telefono2":telefono2 ?? "", "activo":"1", "email":email ?? "", "saldo":saldo, "politica_venta_id":politicaId ?? "" }; log.debug('Data customer', data); return data; } // Configura los datos a enviar del consumidor a SGC web const setDataConsumer = (rowCustomer, aditionalCustomerInfo = false, politicaId, clienteId, address, type) => { // log.debug('info', 'entrΓ³ a la funciΓ³n de configurar la informaciΓ³n del cliente'); let entityId = aditionalCustomerInfo.entityid; let nombre = ( type == 'edit' ? rowCustomer.getText({fieldId:'altname'}) : aditionalCustomerInfo.altname ?? 'Consumidor genΓ©rico' ); // let telefono1 = ( type == 'edit' ? rowCustomer.getText({fieldId:'phone'}) : aditionalCustomerInfo.phone ?? 'industrial' ); let telefono2 = ( type == 'edit' ? rowCustomer.getText({fieldId:'altphone'}) : aditionalCustomerInfo.altphone ?? '' ); let email = ( type == 'edit' ? rowCustomer.getText({fieldId:'email'}) : aditionalCustomerInfo.email ?? 'anymail@gmail.com' ); let saldo = ( type == 'edit' ? rowCustomer.getText({fieldId:'balance'}) : aditionalCustomerInfo.balance ?? 0 ); saldo = ( saldo ? Number( parseFloat( saldo ).toFixed(2) ) : 0.00); let calle = address.calle; address.numExt ? calle += ' NO. EXT. '+ address.numExt : ''; address.numInt ? calle += ' NO. INT. '+ address.numInt : ''; let data = { "numero_consumidor":"", "identificador_externo": entityId+'-'+address.etiqueta, // "identificador_externo": "0000"+address.id+address.etiqueta, "nombres":nombre ? nombre : "Nombre consumidor", "apellidos":".", "telefono1":address.telefonoPrincipal ?? "industrial", "telefono2":telefono2 ?? "", "descripcion":"Consumidor de cliente "+clienteId, "comentario" :"", "calle_numero":calle ? calle : "", "colonia":address.colonia ?? "", "ciudad":address.ciudad ?? "", "estado":address.estado ?? "", "pais":address.pais ?? "", "codigo_postal":( address.codigo_postal ?? "31135" ), "email":email ?? "", "saldo":saldo, "tipo_consumidor_id":"", "politica_consumo_id":politicaId ?? "", "cliente_id":clienteId, "capacidad":"150", "tipo_pago":"", "numero_verificador":"", "ruta_id":"" }; // Falta la lΓ³gica para obtener la ruta asignada, tipo de cliente (campo tipo_consumidor) log.debug('info consumidor', data); return data; } // Configura los datos a enviar para las polΓ­ticas de consumo const setDataSalesPolicy = (rowCustomer, aditionalConsumerInfo = false, type) => { // log.debug('info', 'entrΓ³ a la funciΓ³n de setear la polΓ­tica de venta'); let limite_credito = 250000; // let limite_credito = ( type == 'edit' ? rowCustomer.getValue({fieldId: 'creditlimit'}) : rowCustomer.getValue({fieldId: 'creditlimit'}) ); let tipo_pago = ( type == 'edit' ? rowCustomer.getValue({fieldId: 'custentity_ptg_alianza_comercial_cliente'}) : rowCustomer.getValue({fieldId:'custentity_ptg_alianza_comercial_cliente'}) ); let identificador = tipo_pago == 2 ? 'CREDITO_DEFAULT' : 'CONTADO'; // limite_credito = ( limite_credito ? Number( parseFloat(limite_credito) ) : '' ); tipo_pago = ( tipo_pago == 2 ? 2 : ( tipo_pago == 3 ? 1 : 1 ) ); let data = { // "nombre":"PolΓ­tica de venta para cliente 0000"+rowCustomer.id, "nombre":identificador, // "identificador_externo":"PV0000"+rowCustomer.id, "identificador_externo":identificador, "activa":"1", "tipo_pago":tipo_pago, "limite_credito":identificador == 'CONTADO' ? 0 : limite_credito, "numero_semanas_credito":1, "frecuencia_factura":0, "facturar_todos_servicios":0, "facturar_servicios_vpg":0, "recordatorio_pago":0, "recordatorio_pago_dias":0, "notificar_limite_credito":0, "bloqueo_morosidad":0 }; log.debug('info polΓ­tica de venta', data); return data; } // Configura los datos a enviar para las polΓ­ticas de consumo const setDataConsumptionPolicy = (rowCustomer, address, type) => { // log.debug('info', 'entrΓ³ a la funciΓ³n de configurar la informaciΓ³n del cliente'); let nombre = address.territorioZona; let limite_credito = ( type == 'edit' ? rowCustomer.getText({fieldId:'creditlimit'}) : rowCustomer.getValue({fieldId:'creditlimit'}) ); let descuento = ( type == 'edit' ? rowCustomer.getValue({fieldId:'custentity_ptg_descuento_asignar'}) : rowCustomer.getValue({fieldId:'custentity_ptg_descuento_asignar'}) ); log.debug('Descuento en politica consumo', descuento); let splitDesc = ( descuento ? descuento.split('.') : '00'); limite_credito = (limite_credito ? Number(parseInt(limite_credito)) : 0.00); let centavos = Number( parseInt( ( splitDesc[1] ? splitDesc[1] : '00' ) ).toFixed(2) ); if ( centavos < 10 ) { centavos = '0'.concat(centavos); } else { // } // centavos = ( centavos == '00' ? '00' : ); // Mejorar lΓ³gica para aplicar los descuentos aquΓ­ let data = { "nombre":nombre, "identificador_externo":"L"+(centavos)+nombre, "activa":"1", "tipo_pago":0, "limite_credito":limite_credito, "hora_inicial":"00:00", "hora_final":"23:45", "numero_servicios":1, "restringir_gps":0, "restringir_tag":0, "impuesto_id":"", "descuento_id":"", "ticket_servicios_id":"" }; log.debug('info polΓ­tica de consumo', data); return data; } // Query que obtiene las direcciones del cliente creado const searchCustomerAddresses = (customerId) => { let addressObj = { default : '', addresses : [] }; let sql = 'SELECT customerAddressbook.entity as idCliente, customerAddressbook.internalId as idDireccion, zip, customerAddressbook.label as etiqueta,'+ 'customerAddressbook.defaultshipping as envioPredeterminado, customerAddressbook.defaultbilling as facturacionPredeterminada,'+ 'customerAddressbookEntityAddress.custrecord_ptg_colonia_ruta as idColoniaRuta, customerAddressbookEntityAddress.custrecord_ptg_nombre_colonia as nombreColonia,'+ 'customerAddressbookEntityAddress.custrecord_ptg_exterior_number as numeroExterior, customerAddressbookEntityAddress.custrecord_ptg_interior_number as numeroInterior,'+ 'customerAddressbookEntityAddress.custrecord_ptg_estado as estado, customerAddressbookEntityAddress.city as ciudad, customerAddressbookEntityAddress.country as pais,'+ 'customerAddressbookEntityAddress.custrecord_ptg_street as calle, '+ 'customerAddressbookEntityAddress.custrecord_ptg_entrecalle_ as entreCalle1, customerAddressbookEntityAddress.custrecord_ptg_y_entre_ as entreCalle2,'+ 'customerAddressbookEntityAddress.custrecord_ptg_telefono_principal as telefonoPrincipal,'+ 'CUSTOMRECORD_PTG_COLONIASRUTAS_.custrecord_ptg_zona_de_precio_ as idZonaPrecio,'+ 'CUSTOMRECORD_PTG_ZONASDEPRECIO_.name as nombreZona, CUSTOMRECORD_PTG_ZONASDEPRECIO_.custrecord_ptg_precio_ as precioZona, custrecord_ptg_territorio_ as territorioZona '+ 'FROM customerAddressbook '+ 'left join customerAddressbookEntityAddress on customerAddressbook.addressbookaddress = customerAddressbookEntityAddress.nkey '+ 'left join CUSTOMRECORD_PTG_COLONIASRUTAS_ on customerAddressbookEntityAddress.custrecord_ptg_colonia_ruta = CUSTOMRECORD_PTG_COLONIASRUTAS_.id '+ 'left join CUSTOMRECORD_PTG_ZONASDEPRECIO_ on CUSTOMRECORD_PTG_COLONIASRUTAS_.custrecord_ptg_zona_de_precio_ = CUSTOMRECORD_PTG_ZONASDEPRECIO_.id '+ 'WHERE customerAddressbook.entity ='+ customerId; let resultIterator = query.runSuiteQLPaged({ query: sql, pageSize: 1000 }).iterator(); resultIterator.each(function (page) { let pageIterator = page.value.data.iterator(); pageIterator.each(function (row) { let address = {}; // log.debug('Row de query pura', row); if(!!row.value.getValue(0)) { address.id = row.value.getValue(1); address.codigo_postal = row.value.getValue(2); address.etiqueta = row.value.getValue(3); address.defaultShipping = row.value.getValue(4); address.defaultBilling = row.value.getValue(5); address.colonia = row.value.getValue(7); address.numExt = row.value.getValue(8); address.numInt = row.value.getValue(9); address.estado = row.value.getValue(10); address.ciudad = row.value.getValue(11); address.pais = row.value.getValue(12); address.calle = row.value.getValue(13); address.entreCalle1 = row.value.getValue(14); address.entreCalle2 = row.value.getValue(15); address.telefonoPrincipal = row.value.getValue(16); address.idZona = row.value.getValue(17); address.nombreZona = row.value.getValue(18); address.precioZona = row.value.getValue(19); address.territorioZona = row.value.getValue(20); // obj.text = `${row.value.getValue(1)} - ${row.value.getValue(2)} - ${row.value.getValue(3)}`; // Es la direcciΓ³n por default if ( address.defaultShipping == "T" ) { addressObj.default = address; } // Se hace el push del objeto de la direcciΓ³n al arreglo de direcciones a retornar addressObj.addresses.push(address); } return true; }); return true; }); // log.debug('Data sql', data); return addressObj; } // Guarda / actualiza un cliente en SGC web const registerSgcData = (xmlContent, idToken, typeModule, action, data) => { log.debug('data', data); log.debug('typeModule', typeModule); xmlContent = xmlContent.split('idSession').join(`${idToken}`); xmlContent = xmlContent.split('typeModule').join(`${typeModule}`); xmlContent = xmlContent.split('action').join(`${action}`); xmlContent = xmlContent.split('data').join(`${JSON.stringify(data)}`); // log.debug('despues del primer join', xmlContent); let headers = {}; headers['Content-Type'] = 'text/xml; charset=utf-8'; // headers['SOAPAction'] = 'http://testpotogas.sgcweb.com.mx/ws/1094AEV2/v2/soap.php/procesarPeticion'; // let url = 'http://testpotogas.sgcweb.com.mx//ws/1094AEV2/v2/soap.php'; headers['SOAPAction'] = 'http://potogas.sgcweb.com.mx/ws/1094AEV2/v2/soap.php/procesarPeticion'; let url = 'http://potogas.sgcweb.com.mx/ws/1094AEV2/v2/soap.php'; let response = http.request({ method: http.Method.POST, url: url, body: xmlContent, headers: headers }); // log.debug('response', response.body) let xmlFileContent = response.body; let xmlDocument = xml.Parser.fromString({ text: xmlFileContent }); let dataJson = xmlDocument.getElementsByTagName({ tagName: 'informacion' }); let responseCode = xmlDocument.getElementsByTagName({ tagName: 'codigo' }); // log.debug('response info', dataJson); // log.debug('response code', responseCode); return { info : dataJson, code : responseCode, }; } return {beforeLoad, beforeSubmit, afterSubmit} });
560
[{"tag": "EMAIL", "value": "anymail@gmail.com", "start": 19802, "end": 19819}]
true
1
/** * @NApiVersion 2.1 * @NScriptType UserEventScript */ define(['N/file', 'N/http', 'N/search', 'N/xml', 'N/record', 'N/query'], /** * @param{file} file * @param{http} http * @param{search} search * @param{xml} xml */ (file, http, search, xml, record, query) => { /** * Defines the function definition that is executed before record is loaded. * @param {Object} scriptContext * @param {Record} scriptContext.newRecord - New record * @param {string} scriptContext.type - Trigger type; use values from the context.UserEventType enum * @param {Form} scriptContext.form - Current form * @param {ServletRequest} scriptContext.request - HTTP request information sent from the browser for a client action only. * @since 2015.2 */ const beforeLoad = (scriptContext) => { } /** * Defines the function definition that is executed before record is submitted. * @param {Object} scriptContext * @param {Record} scriptContext.newRecord - New record * @param {Record} scriptContext.oldRecord - Old record * @param {string} scriptContext.type - Trigger type; use values from the context.UserEventType enum * @since 2015.2 */ const beforeSubmit = (scriptContext) => { } /** * Defines the function definition that is executed after record is submitted. * @param {Object} scriptContext * @param {Record} scriptContext.newRecord - New record * @param {Record} scriptContext.oldRecord - Old record * @param {string} scriptContext.type - Trigger type; use values from the context.UserEventType enum * @since 2015.2 */ const afterSubmit = (scriptContext) => { try { if( scriptContext.type === scriptContext.UserEventType.CREATE ) { // Se actualiza el campo tipo check var custom = scriptContext.newRecord;// Get edited customer var customerInfo = search.lookupFields({ type: search.Type.CUSTOMER, id: custom.id, columns: ['entityid'] }); let entityid = customerInfo.entityid; let count = entityid.length; while (count < 10) { entityid = "0".concat(entityid); count ++; } record.submitFields({ type: record.Type.CUSTOMER, id: custom.id, values: { 'entityid': entityid, } }); record.submitFields({ type: record.Type.CUSTOMER, id: custom.id, values: { 'custentity_ptg_cliente_act_sgc': "T", } }); log.debug('entityid', entityid); } return; let idToken = login(); if ( scriptContext.type === scriptContext.UserEventType.EDIT || scriptContext.type === scriptContext.UserEventType.CREATE ) { log.debug('Info', 'EdiciΓ³n de cliente'); let actionType = scriptContext.type === scriptContext.UserEventType.EDIT ? 'edit' : 'new'; let rowCustomer = scriptContext.newRecord;// Get edited customer let internalFileId = searchXmlFile(); let customerAddresses = searchCustomerAddresses(rowCustomer.id); let customerInfo = search.lookupFields({ type: search.Type.CUSTOMER, id: rowCustomer.id, columns: ['companyname', 'altname', 'phone', 'altphone', 'email', 'balance', 'entityid'] }); let tipo_pago = ( actionType == 'edit' ? rowCustomer.getValue({fieldId: 'custentity_ptg_alianza_comercial_cliente'}) : rowCustomer.getValue({fieldId:'custentity_ptg_alianza_comercial_cliente'}) ); let idPoliticaVenta = tipo_pago == 2 ? 'CREDITO_DEFAULT' : 'CONTADO'; log.debug('customerInfo', customerInfo); // log.debug('entityId', entityId); // return; // let dirDefault = searchDefaultAddress(search, rowCustomer); // let isConsumer = rowCustomer.getValue({fieldId:'parent'}); // log.debug('Alianza comercial', rowCustomer.getValue({fieldId: 'custentity_ptg_alianza_comercial_cliente'})); // log.debug('Alianza comercial texto', rowCustomer.getText({fieldId: 'custentity_ptg_alianza_comercial_cliente'})); // log.debug('LΓ­mite de crΓ©dito', rowCustomer.getValue({fieldId: 'creditlimit'})); // log.debug('Politica de venta', rowCustomer.getValue({fieldId:'custentity_ptg_politicadeventa_'})); // log.debug('Politica de consumo', rowCustomer.getValue({fieldId:'custentity_ptg_politicadeconsumo_cliente'})); // log.debug('Xml ID', internalFileId); // log.debug('Listado de direcciones', customerAddresses); // log.debug('data customer', dataToSend); // return; let typeModule = action = responseConsPol = dataCustomer = ''; let xmlContent = file.load({ id: internalFileId }).getContents(); // Se da de alta la polΓ­tica de venta // typeModule = "PoliticasVenta"; // action = "registrar"; // dataSalesPolicy = setDataSalesPolicy(rowCustomer, customerInfo, actionType); // responseConsPol = registerSgcData(xmlContent, idToken, typeModule, action, dataSalesPolicy); // log.debug('Info', 'EntrΓ³ a registrar una polΓ­tica de venta'); // if (["1111", "0000"].includes(responseConsPol.code[0].textContent) ) { // log.debug('SGC', 'PolΓ­tica de venta registrada'); // log.debug('Respuesta sgcweb polΓ­tica de venta', responseConsPol.info); // } else { // log.debug('OcurriΓ³ un error en polΓ­ticas de venta', responseConsPol.code[0].textContent); // } // return; // Se da de alta el cliente typeModule = "Clientes"; action = "registrar"; dataCustomer = setDataCustomer(rowCustomer, customerInfo, idPoliticaVenta, customerAddresses.default, actionType); // dataCustomer = setDataCustomer(rowCustomer, customerInfo, dataSalesPolicy.identificador_externo, customerAddresses.default, actionType); responseCustomer = registerSgcData(xmlContent, idToken, typeModule, action, dataCustomer); log.debug('Info', 'EntrΓ³ a registrar un cliente'); if (["1111", "0000"].includes(responseCustomer.code[0].textContent) ) { log.debug('SGC', 'Cliente registrado correctamente'); let realResult = JSON.parse(responseCustomer.info[0].textContent); log.debug('Respuesta sgcweb cliente', realResult); log.debug('NΓΊmero de cliente de sgcweb', realResult.numero_cliente); // Se edita el campo custentity_ptg_extermal_id para empatarlo con SGC Web record.submitFields({ type: record.Type.CUSTOMER, id: rowCustomer.id, values: { 'custentity_ptg_codigodecliente_': realResult.numero_cliente } }); log.debug('ActualizaciΓ³n', 'CΓ³digo de cliente actualizado'); } else { log.debug('OcurriΓ³ un error en clientes', responseCustomer.code[0].textContent); } // return 'Hola'; // Se dan de alta los registros de consumidores y polΓ­ticas de consumo let allAddress = customerAddresses.addresses; for (let j = 0; j < allAddress.length; j++) { typeModule = "PoliticasConsumo"; action = "registrar"; dataConsumptionPolicy = setDataConsumptionPolicy(rowCustomer, allAddress[j], actionType); responseConsumptionPolicy = registerSgcData(xmlContent, idToken, typeModule, action, dataConsumptionPolicy); log.debug('Info', 'EntrΓ³ a registrar una polΓ­tica de consumo'); // Se validarΓ‘ que haya salido bien el response if (["1111", "0000"].includes(responseConsumptionPolicy.code[0].textContent) ) { log.debug('SGC', 'PolΓ­tica de consumo registrada'); log.debug('Respuesta sgcweb polΓ­tica de consumo', responseConsumptionPolicy.info); // Se da de alta el consumidor junto con su polΓ­tica de consumo reciΓ©n creada typeModule = "Consumidores"; action = "registrar"; dataConsumer = setDataConsumer(rowCustomer, customerInfo, dataConsumptionPolicy.identificador_externo, dataCustomer.identificador_externo, allAddress[j], actionType); responseConsumer = registerSgcData(xmlContent, idToken, typeModule, action, dataConsumer); log.debug('Info', 'EntrΓ³ a registrar un consumidor'); if (["1111", "0000"].includes(responseConsumer.code[0].textContent) ) { log.debug('SGC', 'Consumidor registrado correctamente'); let realResult = JSON.parse(responseConsumer.info[0].textContent); log.debug('Respuesta sgcweb consumidor', realResult); log.debug('NΓΊmero de consumidor de sgcweb', realResult.numero_consumidor); // Se edita el campo custentity_ptg_numero_consumidor para empatarlo con SGC Web // record.submitFields({ // type: record.Type.CUSTOMER, // id: rowCustomer.id, // values: { // 'custentity_ptg_codigodecliente_': realResult.numero_consumidor // } // }); // log.debug('ActualizaciΓ³n', 'CΓ³digo de cliente actualizado'); } else { log.debug('OcurriΓ³ un error en consumidores', responseConsumer.code[0].textContent); } } else { log.debug('OcurriΓ³ un error en polΓ­ticas de consumo', responseConsumptionPolicy.code[0].textContent); } } return {'msg':'Γ‰xito guardando datos en SGC web', 'status' : 'success'}; } } catch (error) { log.debug('Algo saliΓ³ mal', error); } } // Login const login = () => { let resFileId; let fileSearchObj = search.create({ type: "file", filters: [ ["name", "haskeywords", "login"] ], columns: [ search.createColumn({ name: "name", sort: search.Sort.ASC, label: "Name" }), search.createColumn({ name: "folder", label: "Folder" }), search.createColumn({ name: "documentsize", label: "Size (KB)" }), search.createColumn({ name: "url", label: "URL" }), search.createColumn({ name: "created", label: "Date Created" }), search.createColumn({ name: "modified", label: "Last Modified" }), search.createColumn({ name: "filetype", label: "Type" }), search.createColumn({ name: "internalid", label: "Internal ID" }) ] }); // let searchResultCount = fileSearchObj.runPaged().count; // log.debug("fileSearchObj result count", searchResultCount); fileSearchObj.run().each(function (result) { // log.debug('Resultado peticiΓ³n', result); // .run().each has a limit of 4,000 results resFileId = result.getValue({ name: "internalid", label: "Internal ID" }); return true; }); let xmlContent = file.load({ id: resFileId }).getContents(); // log.debug('xmlContent', xmlContent); let headers = {}; headers['Content-Type'] = 'text/xml; charset=utf-8'; headers['SOAPAction'] = 'http://potogas.sgcweb.com.mx/ws/1094AEV2/v2/soap.php/login'; let url = 'http://potogas.sgcweb.com.mx/ws/1094AEV2/v2/soap.php'; // Method, url, body, headers let response = http.request({ method: http.Method.POST, url: url, body: xmlContent, headers: headers }); // log.debug('response', response.body) let xmlFileContent = response.body; let xmlDocument = xml.Parser.fromString({ text: xmlFileContent }); let dataJson = xmlDocument.getElementsByTagName({ tagName: 'id' }); // log.debug('response status', dataJson) let objResult = dataJson[0].textContent; // log.debug('objResult', objResult) return objResult; } // Busqueda guardada para obtener el archivo xml de peticiones a la api de SGC web const searchXmlFile = () => { // log.debug('info', 'entrΓ³ a la funciΓ³n de buscar archivo xml para peticiones'); let internalFileId; let fileSearchObj = search.create({ type: "file", filters: [ ["name", "haskeywords", "procesarPeticion"] ], columns: [ search.createColumn({ name: "name", sort: search.Sort.ASC, label: "Name" }), search.createColumn({ name: "folder", label: "Folder" }), search.createColumn({ name: "documentsize", label: "Size (KB)" }), search.createColumn({ name: "url", label: "URL" }), search.createColumn({ name: "created", label: "Date Created" }), search.createColumn({ name: "modified", label: "Last Modified" }), search.createColumn({ name: "filetype", label: "Type" }), search.createColumn({ name: "internalid", label: "Internal ID" }) ] }); // let searchResultCount = fileSearchObj.runPaged().count; // log.debug("fileSearchObj result count", searchResultCount); fileSearchObj.run().each(function (result) { // .run().each has a limit of 4,000 results internalFileId = result.getValue({ name: "internalid", label: "Internal ID" }); return true; }); return internalFileId; } // Configura los datos a enviar del cliente a SGC web const setDataCustomer = (rowCustomer, aditionalCustomerInfo = false, politicaId, defaultAddress, type) => { // log.debug('info', 'entrΓ³ a la funciΓ³n de configurar la informaciΓ³n del cliente'); let entityId = aditionalCustomerInfo.entityid; let nombre = ( type == 'edit' ? rowCustomer.getText({fieldId:'altname'}) : aditionalCustomerInfo?.altname ); // let nombre = ( type == 'edit' ? rowCustomer.getText({fieldId:'companyname'}) : aditionalCustomerInfo?.companyname ); let rfc = ( type == 'edit' ? rowCustomer.getText({fieldId:'custentity_mx_rfc'}) : rowCustomer.getValue({fieldId:'custentity_mx_rfc'}) ); // let telefono1 = ( type == 'edit' ? rowCustomer.getText({fieldId:'phone'}) : rowCustomer.getValue({fieldId:'phone'}) ); let telefono2 = ( type == 'edit' ? rowCustomer.getText({fieldId:'altphone'}) : rowCustomer.getValue({fieldId:'altphone'}) ); let email = ( type == 'edit' ? rowCustomer.getText({fieldId:'email'}) : rowCustomer.getValue({fieldId:'email'}) ); let saldo = ( type == 'edit' ? rowCustomer.getText({fieldId:'balance'}) : rowCustomer.getValue({fieldId:'balance'}) ); saldo = ( saldo ? Number( parseFloat( saldo ).toFixed(2) ) : 0.00); let data = { "numero_cliente":"", "identificador_externo": entityId, "nombre":nombre ? nombre : "Nombre cliente", "rfc":rfc ? rfc : "XAXX010101000", "calle":defaultAddress.calle ?? "", "no_exterior":defaultAddress.numExt ?? "", "no_interior":defaultAddress.numInt ?? "", "colonia":defaultAddress.colonia ?? "", "localidad":defaultAddress.ciudad ?? "", "referencia":defaultAddress.entreCalle1 ?? "", "ciudad":defaultAddress.ciudad ?? "", "estado":defaultAddress.estado ?? "", "codigo_postal":( defaultAddress.codigo_postal ?? "31135" ), "pais":defaultAddress.pais ?? "", "telefono1":defaultAddress.telefonoPrincipal ?? "4448111213", "telefono2":telefono2 ?? "", "activo":"1", "email":email ?? "", "saldo":saldo, "politica_venta_id":politicaId ?? "" }; log.debug('Data customer', data); return data; } // Configura los datos a enviar del consumidor a SGC web const setDataConsumer = (rowCustomer, aditionalCustomerInfo = false, politicaId, clienteId, address, type) => { // log.debug('info', 'entrΓ³ a la funciΓ³n de configurar la informaciΓ³n del cliente'); let entityId = aditionalCustomerInfo.entityid; let nombre = ( type == 'edit' ? rowCustomer.getText({fieldId:'altname'}) : aditionalCustomerInfo.altname ?? 'Consumidor genΓ©rico' ); // let telefono1 = ( type == 'edit' ? rowCustomer.getText({fieldId:'phone'}) : aditionalCustomerInfo.phone ?? 'industrial' ); let telefono2 = ( type == 'edit' ? rowCustomer.getText({fieldId:'altphone'}) : aditionalCustomerInfo.altphone ?? '' ); let email = ( type == 'edit' ? rowCustomer.getText({fieldId:'email'}) : aditionalCustomerInfo.email ?? 'efpyi@example.com' ); let saldo = ( type == 'edit' ? rowCustomer.getText({fieldId:'balance'}) : aditionalCustomerInfo.balance ?? 0 ); saldo = ( saldo ? Number( parseFloat( saldo ).toFixed(2) ) : 0.00); let calle = address.calle; address.numExt ? calle += ' NO. EXT. '+ address.numExt : ''; address.numInt ? calle += ' NO. INT. '+ address.numInt : ''; let data = { "numero_consumidor":"", "identificador_externo": entityId+'-'+address.etiqueta, // "identificador_externo": "0000"+address.id+address.etiqueta, "nombres":nombre ? nombre : "Nombre consumidor", "apellidos":".", "telefono1":address.telefonoPrincipal ?? "industrial", "telefono2":telefono2 ?? "", "descripcion":"Consumidor de cliente "+clienteId, "comentario" :"", "calle_numero":calle ? calle : "", "colonia":address.colonia ?? "", "ciudad":address.ciudad ?? "", "estado":address.estado ?? "", "pais":address.pais ?? "", "codigo_postal":( address.codigo_postal ?? "31135" ), "email":email ?? "", "saldo":saldo, "tipo_consumidor_id":"", "politica_consumo_id":politicaId ?? "", "cliente_id":clienteId, "capacidad":"150", "tipo_pago":"", "numero_verificador":"", "ruta_id":"" }; // Falta la lΓ³gica para obtener la ruta asignada, tipo de cliente (campo tipo_consumidor) log.debug('info consumidor', data); return data; } // Configura los datos a enviar para las polΓ­ticas de consumo const setDataSalesPolicy = (rowCustomer, aditionalConsumerInfo = false, type) => { // log.debug('info', 'entrΓ³ a la funciΓ³n de setear la polΓ­tica de venta'); let limite_credito = 250000; // let limite_credito = ( type == 'edit' ? rowCustomer.getValue({fieldId: 'creditlimit'}) : rowCustomer.getValue({fieldId: 'creditlimit'}) ); let tipo_pago = ( type == 'edit' ? rowCustomer.getValue({fieldId: 'custentity_ptg_alianza_comercial_cliente'}) : rowCustomer.getValue({fieldId:'custentity_ptg_alianza_comercial_cliente'}) ); let identificador = tipo_pago == 2 ? 'CREDITO_DEFAULT' : 'CONTADO'; // limite_credito = ( limite_credito ? Number( parseFloat(limite_credito) ) : '' ); tipo_pago = ( tipo_pago == 2 ? 2 : ( tipo_pago == 3 ? 1 : 1 ) ); let data = { // "nombre":"PolΓ­tica de venta para cliente 0000"+rowCustomer.id, "nombre":identificador, // "identificador_externo":"PV0000"+rowCustomer.id, "identificador_externo":identificador, "activa":"1", "tipo_pago":tipo_pago, "limite_credito":identificador == 'CONTADO' ? 0 : limite_credito, "numero_semanas_credito":1, "frecuencia_factura":0, "facturar_todos_servicios":0, "facturar_servicios_vpg":0, "recordatorio_pago":0, "recordatorio_pago_dias":0, "notificar_limite_credito":0, "bloqueo_morosidad":0 }; log.debug('info polΓ­tica de venta', data); return data; } // Configura los datos a enviar para las polΓ­ticas de consumo const setDataConsumptionPolicy = (rowCustomer, address, type) => { // log.debug('info', 'entrΓ³ a la funciΓ³n de configurar la informaciΓ³n del cliente'); let nombre = address.territorioZona; let limite_credito = ( type == 'edit' ? rowCustomer.getText({fieldId:'creditlimit'}) : rowCustomer.getValue({fieldId:'creditlimit'}) ); let descuento = ( type == 'edit' ? rowCustomer.getValue({fieldId:'custentity_ptg_descuento_asignar'}) : rowCustomer.getValue({fieldId:'custentity_ptg_descuento_asignar'}) ); log.debug('Descuento en politica consumo', descuento); let splitDesc = ( descuento ? descuento.split('.') : '00'); limite_credito = (limite_credito ? Number(parseInt(limite_credito)) : 0.00); let centavos = Number( parseInt( ( splitDesc[1] ? splitDesc[1] : '00' ) ).toFixed(2) ); if ( centavos < 10 ) { centavos = '0'.concat(centavos); } else { // } // centavos = ( centavos == '00' ? '00' : ); // Mejorar lΓ³gica para aplicar los descuentos aquΓ­ let data = { "nombre":nombre, "identificador_externo":"L"+(centavos)+nombre, "activa":"1", "tipo_pago":0, "limite_credito":limite_credito, "hora_inicial":"00:00", "hora_final":"23:45", "numero_servicios":1, "restringir_gps":0, "restringir_tag":0, "impuesto_id":"", "descuento_id":"", "ticket_servicios_id":"" }; log.debug('info polΓ­tica de consumo', data); return data; } // Query que obtiene las direcciones del cliente creado const searchCustomerAddresses = (customerId) => { let addressObj = { default : '', addresses : [] }; let sql = 'SELECT customerAddressbook.entity as idCliente, customerAddressbook.internalId as idDireccion, zip, customerAddressbook.label as etiqueta,'+ 'customerAddressbook.defaultshipping as envioPredeterminado, customerAddressbook.defaultbilling as facturacionPredeterminada,'+ 'customerAddressbookEntityAddress.custrecord_ptg_colonia_ruta as idColoniaRuta, customerAddressbookEntityAddress.custrecord_ptg_nombre_colonia as nombreColonia,'+ 'customerAddressbookEntityAddress.custrecord_ptg_exterior_number as numeroExterior, customerAddressbookEntityAddress.custrecord_ptg_interior_number as numeroInterior,'+ 'customerAddressbookEntityAddress.custrecord_ptg_estado as estado, customerAddressbookEntityAddress.city as ciudad, customerAddressbookEntityAddress.country as pais,'+ 'customerAddressbookEntityAddress.custrecord_ptg_street as calle, '+ 'customerAddressbookEntityAddress.custrecord_ptg_entrecalle_ as entreCalle1, customerAddressbookEntityAddress.custrecord_ptg_y_entre_ as entreCalle2,'+ 'customerAddressbookEntityAddress.custrecord_ptg_telefono_principal as telefonoPrincipal,'+ 'CUSTOMRECORD_PTG_COLONIASRUTAS_.custrecord_ptg_zona_de_precio_ as idZonaPrecio,'+ 'CUSTOMRECORD_PTG_ZONASDEPRECIO_.name as nombreZona, CUSTOMRECORD_PTG_ZONASDEPRECIO_.custrecord_ptg_precio_ as precioZona, custrecord_ptg_territorio_ as territorioZona '+ 'FROM customerAddressbook '+ 'left join customerAddressbookEntityAddress on customerAddressbook.addressbookaddress = customerAddressbookEntityAddress.nkey '+ 'left join CUSTOMRECORD_PTG_COLONIASRUTAS_ on customerAddressbookEntityAddress.custrecord_ptg_colonia_ruta = CUSTOMRECORD_PTG_COLONIASRUTAS_.id '+ 'left join CUSTOMRECORD_PTG_ZONASDEPRECIO_ on CUSTOMRECORD_PTG_COLONIASRUTAS_.custrecord_ptg_zona_de_precio_ = CUSTOMRECORD_PTG_ZONASDEPRECIO_.id '+ 'WHERE customerAddressbook.entity ='+ customerId; let resultIterator = query.runSuiteQLPaged({ query: sql, pageSize: 1000 }).iterator(); resultIterator.each(function (page) { let pageIterator = page.value.data.iterator(); pageIterator.each(function (row) { let address = {}; // log.debug('Row de query pura', row); if(!!row.value.getValue(0)) { address.id = row.value.getValue(1); address.codigo_postal = row.value.getValue(2); address.etiqueta = row.value.getValue(3); address.defaultShipping = row.value.getValue(4); address.defaultBilling = row.value.getValue(5); address.colonia = row.value.getValue(7); address.numExt = row.value.getValue(8); address.numInt = row.value.getValue(9); address.estado = row.value.getValue(10); address.ciudad = row.value.getValue(11); address.pais = row.value.getValue(12); address.calle = row.value.getValue(13); address.entreCalle1 = row.value.getValue(14); address.entreCalle2 = row.value.getValue(15); address.telefonoPrincipal = row.value.getValue(16); address.idZona = row.value.getValue(17); address.nombreZona = row.value.getValue(18); address.precioZona = row.value.getValue(19); address.territorioZona = row.value.getValue(20); // obj.text = `${row.value.getValue(1)} - ${row.value.getValue(2)} - ${row.value.getValue(3)}`; // Es la direcciΓ³n por default if ( address.defaultShipping == "T" ) { addressObj.default = address; } // Se hace el push del objeto de la direcciΓ³n al arreglo de direcciones a retornar addressObj.addresses.push(address); } return true; }); return true; }); // log.debug('Data sql', data); return addressObj; } // Guarda / actualiza un cliente en SGC web const registerSgcData = (xmlContent, idToken, typeModule, action, data) => { log.debug('data', data); log.debug('typeModule', typeModule); xmlContent = xmlContent.split('idSession').join(`${idToken}`); xmlContent = xmlContent.split('typeModule').join(`${typeModule}`); xmlContent = xmlContent.split('action').join(`${action}`); xmlContent = xmlContent.split('data').join(`${JSON.stringify(data)}`); // log.debug('despues del primer join', xmlContent); let headers = {}; headers['Content-Type'] = 'text/xml; charset=utf-8'; // headers['SOAPAction'] = 'http://testpotogas.sgcweb.com.mx/ws/1094AEV2/v2/soap.php/procesarPeticion'; // let url = 'http://testpotogas.sgcweb.com.mx//ws/1094AEV2/v2/soap.php'; headers['SOAPAction'] = 'http://potogas.sgcweb.com.mx/ws/1094AEV2/v2/soap.php/procesarPeticion'; let url = 'http://potogas.sgcweb.com.mx/ws/1094AEV2/v2/soap.php'; let response = http.request({ method: http.Method.POST, url: url, body: xmlContent, headers: headers }); // log.debug('response', response.body) let xmlFileContent = response.body; let xmlDocument = xml.Parser.fromString({ text: xmlFileContent }); let dataJson = xmlDocument.getElementsByTagName({ tagName: 'informacion' }); let responseCode = xmlDocument.getElementsByTagName({ tagName: 'codigo' }); // log.debug('response info', dataJson); // log.debug('response code', responseCode); return { info : dataJson, code : responseCode, }; } return {beforeLoad, beforeSubmit, afterSubmit} });
true
/** * @NApiVersion 2.1 * @NScriptType UserEventScript */ define(['N/file', 'N/http', 'N/search', 'N/xml', 'N/record', 'N/query'], /** * @param{file} file * @param{http} http * @param{search} search * @param{xml} xml */ (file, http, search, xml, record, query) => { /** * Defines the function definition that is executed before record is loaded. * @param {Object} scriptContext * @param {Record} scriptContext.newRecord - New record * @param {string} scriptContext.type - Trigger type; use values from the context.UserEventType enum * @param {Form} scriptContext.form - Current form * @param {ServletRequest} scriptContext.request - HTTP request information sent from the browser for a client action only. * @since 2015.2 */ const beforeLoad = (scriptContext) => { } /** * Defines the function definition that is executed before record is submitted. * @param {Object} scriptContext * @param {Record} scriptContext.newRecord - New record * @param {Record} scriptContext.oldRecord - Old record * @param {string} scriptContext.type - Trigger type; use values from the context.UserEventType enum * @since 2015.2 */ const beforeSubmit = (scriptContext) => { } /** * Defines the function definition that is executed after record is submitted. * @param {Object} scriptContext * @param {Record} scriptContext.newRecord - New record * @param {Record} scriptContext.oldRecord - Old record * @param {string} scriptContext.type - Trigger type; use values from the context.UserEventType enum * @since 2015.2 */ const afterSubmit = (scriptContext) => { try { if( scriptContext.type === scriptContext.UserEventType.CREATE ) { // Se actualiza el campo tipo check var custom = scriptContext.newRecord;// Get edited customer var customerInfo = search.lookupFields({ type: search.Type.CUSTOMER, id: custom.id, columns: ['entityid'] }); let entityid = customerInfo.entityid; let count = entityid.length; while (count < 10) { entityid = "0".concat(entityid); count ++; } record.submitFields({ type: record.Type.CUSTOMER, id: custom.id, values: { 'entityid': entityid, } }); record.submitFields({ type: record.Type.CUSTOMER, id: custom.id, values: { 'custentity_ptg_cliente_act_sgc': "T", } }); log.debug('entityid', entityid); } return; let idToken = login(); if ( scriptContext.type === scriptContext.UserEventType.EDIT || scriptContext.type === scriptContext.UserEventType.CREATE ) { log.debug('Info', 'EdiciΓ³n de cliente'); let actionType = scriptContext.type === scriptContext.UserEventType.EDIT ? 'edit' : 'new'; let rowCustomer = scriptContext.newRecord;// Get edited customer let internalFileId = searchXmlFile(); let customerAddresses = searchCustomerAddresses(rowCustomer.id); let customerInfo = search.lookupFields({ type: search.Type.CUSTOMER, id: rowCustomer.id, columns: ['companyname', 'altname', 'phone', 'altphone', 'email', 'balance', 'entityid'] }); let tipo_pago = ( actionType == 'edit' ? rowCustomer.getValue({fieldId: 'custentity_ptg_alianza_comercial_cliente'}) : rowCustomer.getValue({fieldId:'custentity_ptg_alianza_comercial_cliente'}) ); let idPoliticaVenta = tipo_pago == 2 ? 'CREDITO_DEFAULT' : 'CONTADO'; log.debug('customerInfo', customerInfo); // log.debug('entityId', entityId); // return; // let dirDefault = searchDefaultAddress(search, rowCustomer); // let isConsumer = rowCustomer.getValue({fieldId:'parent'}); // log.debug('Alianza comercial', rowCustomer.getValue({fieldId: 'custentity_ptg_alianza_comercial_cliente'})); // log.debug('Alianza comercial texto', rowCustomer.getText({fieldId: 'custentity_ptg_alianza_comercial_cliente'})); // log.debug('LΓ­mite de crΓ©dito', rowCustomer.getValue({fieldId: 'creditlimit'})); // log.debug('Politica de venta', rowCustomer.getValue({fieldId:'custentity_ptg_politicadeventa_'})); // log.debug('Politica de consumo', rowCustomer.getValue({fieldId:'custentity_ptg_politicadeconsumo_cliente'})); // log.debug('Xml ID', internalFileId); // log.debug('Listado de direcciones', customerAddresses); // log.debug('data customer', dataToSend); // return; let typeModule = action = responseConsPol = dataCustomer = ''; let xmlContent = file.load({ id: internalFileId }).getContents(); // Se da de alta la polΓ­tica de venta // typeModule = "PoliticasVenta"; // action = "registrar"; // dataSalesPolicy = setDataSalesPolicy(rowCustomer, customerInfo, actionType); // responseConsPol = registerSgcData(xmlContent, idToken, typeModule, action, dataSalesPolicy); // log.debug('Info', 'EntrΓ³ a registrar una polΓ­tica de venta'); // if (["1111", "0000"].includes(responseConsPol.code[0].textContent) ) { // log.debug('SGC', 'PolΓ­tica de venta registrada'); // log.debug('Respuesta sgcweb polΓ­tica de venta', responseConsPol.info); // } else { // log.debug('OcurriΓ³ un error en polΓ­ticas de venta', responseConsPol.code[0].textContent); // } // return; // Se da de alta el cliente typeModule = "Clientes"; action = "registrar"; dataCustomer = setDataCustomer(rowCustomer, customerInfo, idPoliticaVenta, customerAddresses.default, actionType); // dataCustomer = setDataCustomer(rowCustomer, customerInfo, dataSalesPolicy.identificador_externo, customerAddresses.default, actionType); responseCustomer = registerSgcData(xmlContent, idToken, typeModule, action, dataCustomer); log.debug('Info', 'EntrΓ³ a registrar un cliente'); if (["1111", "0000"].includes(responseCustomer.code[0].textContent) ) { log.debug('SGC', 'Cliente registrado correctamente'); let realResult = JSON.parse(responseCustomer.info[0].textContent); log.debug('Respuesta sgcweb cliente', realResult); log.debug('NΓΊmero de cliente de sgcweb', realResult.numero_cliente); // Se edita el campo custentity_ptg_extermal_id para empatarlo con SGC Web record.submitFields({ type: record.Type.CUSTOMER, id: rowCustomer.id, values: { 'custentity_ptg_codigodecliente_': realResult.numero_cliente } }); log.debug('ActualizaciΓ³n', 'CΓ³digo de cliente actualizado'); } else { log.debug('OcurriΓ³ un error en clientes', responseCustomer.code[0].textContent); } // return 'Hola'; // Se dan de alta los registros de consumidores y polΓ­ticas de consumo let allAddress = customerAddresses.addresses; for (let j = 0; j < allAddress.length; j++) { typeModule = "PoliticasConsumo"; action = "registrar"; dataConsumptionPolicy = setDataConsumptionPolicy(rowCustomer, allAddress[j], actionType); responseConsumptionPolicy = registerSgcData(xmlContent, idToken, typeModule, action, dataConsumptionPolicy); log.debug('Info', 'EntrΓ³ a registrar una polΓ­tica de consumo'); // Se validarΓ‘ que haya salido bien el response if (["1111", "0000"].includes(responseConsumptionPolicy.code[0].textContent) ) { log.debug('SGC', 'PolΓ­tica de consumo registrada'); log.debug('Respuesta sgcweb polΓ­tica de consumo', responseConsumptionPolicy.info); // Se da de alta el consumidor junto con su polΓ­tica de consumo reciΓ©n creada typeModule = "Consumidores"; action = "registrar"; dataConsumer = setDataConsumer(rowCustomer, customerInfo, dataConsumptionPolicy.identificador_externo, dataCustomer.identificador_externo, allAddress[j], actionType); responseConsumer = registerSgcData(xmlContent, idToken, typeModule, action, dataConsumer); log.debug('Info', 'EntrΓ³ a registrar un consumidor'); if (["1111", "0000"].includes(responseConsumer.code[0].textContent) ) { log.debug('SGC', 'Consumidor registrado correctamente'); let realResult = JSON.parse(responseConsumer.info[0].textContent); log.debug('Respuesta sgcweb consumidor', realResult); log.debug('NΓΊmero de consumidor de sgcweb', realResult.numero_consumidor); // Se edita el campo custentity_ptg_numero_consumidor para empatarlo con SGC Web // record.submitFields({ // type: record.Type.CUSTOMER, // id: rowCustomer.id, // values: { // 'custentity_ptg_codigodecliente_': realResult.numero_consumidor // } // }); // log.debug('ActualizaciΓ³n', 'CΓ³digo de cliente actualizado'); } else { log.debug('OcurriΓ³ un error en consumidores', responseConsumer.code[0].textContent); } } else { log.debug('OcurriΓ³ un error en polΓ­ticas de consumo', responseConsumptionPolicy.code[0].textContent); } } return {'msg':'Γ‰xito guardando datos en SGC web', 'status' : 'success'}; } } catch (error) { log.debug('Algo saliΓ³ mal', error); } } // Login const login = () => { let resFileId; let fileSearchObj = search.create({ type: "file", filters: [ ["name", "haskeywords", "login"] ], columns: [ search.createColumn({ name: "name", sort: search.Sort.ASC, label: "Name" }), search.createColumn({ name: "folder", label: "Folder" }), search.createColumn({ name: "documentsize", label: "Size (KB)" }), search.createColumn({ name: "url", label: "URL" }), search.createColumn({ name: "created", label: "Date Created" }), search.createColumn({ name: "modified", label: "Last Modified" }), search.createColumn({ name: "filetype", label: "Type" }), search.createColumn({ name: "internalid", label: "Internal ID" }) ] }); // let searchResultCount = fileSearchObj.runPaged().count; // log.debug("fileSearchObj result count", searchResultCount); fileSearchObj.run().each(function (result) { // log.debug('Resultado peticiΓ³n', result); // .run().each has a limit of 4,000 results resFileId = result.getValue({ name: "internalid", label: "Internal ID" }); return true; }); let xmlContent = file.load({ id: resFileId }).getContents(); // log.debug('xmlContent', xmlContent); let headers = {}; headers['Content-Type'] = 'text/xml; charset=utf-8'; headers['SOAPAction'] = 'http://potogas.sgcweb.com.mx/ws/1094AEV2/v2/soap.php/login'; let url = 'http://potogas.sgcweb.com.mx/ws/1094AEV2/v2/soap.php'; // Method, url, body, headers let response = http.request({ method: http.Method.POST, url: url, body: xmlContent, headers: headers }); // log.debug('response', response.body) let xmlFileContent = response.body; let xmlDocument = xml.Parser.fromString({ text: xmlFileContent }); let dataJson = xmlDocument.getElementsByTagName({ tagName: 'id' }); // log.debug('response status', dataJson) let objResult = dataJson[0].textContent; // log.debug('objResult', objResult) return objResult; } // Busqueda guardada para obtener el archivo xml de peticiones a la api de SGC web const searchXmlFile = () => { // log.debug('info', 'entrΓ³ a la funciΓ³n de buscar archivo xml para peticiones'); let internalFileId; let fileSearchObj = search.create({ type: "file", filters: [ ["name", "haskeywords", "procesarPeticion"] ], columns: [ search.createColumn({ name: "name", sort: search.Sort.ASC, label: "Name" }), search.createColumn({ name: "folder", label: "Folder" }), search.createColumn({ name: "documentsize", label: "Size (KB)" }), search.createColumn({ name: "url", label: "URL" }), search.createColumn({ name: "created", label: "Date Created" }), search.createColumn({ name: "modified", label: "Last Modified" }), search.createColumn({ name: "filetype", label: "Type" }), search.createColumn({ name: "internalid", label: "Internal ID" }) ] }); // let searchResultCount = fileSearchObj.runPaged().count; // log.debug("fileSearchObj result count", searchResultCount); fileSearchObj.run().each(function (result) { // .run().each has a limit of 4,000 results internalFileId = result.getValue({ name: "internalid", label: "Internal ID" }); return true; }); return internalFileId; } // Configura los datos a enviar del cliente a SGC web const setDataCustomer = (rowCustomer, aditionalCustomerInfo = false, politicaId, defaultAddress, type) => { // log.debug('info', 'entrΓ³ a la funciΓ³n de configurar la informaciΓ³n del cliente'); let entityId = aditionalCustomerInfo.entityid; let nombre = ( type == 'edit' ? rowCustomer.getText({fieldId:'altname'}) : aditionalCustomerInfo?.altname ); // let nombre = ( type == 'edit' ? rowCustomer.getText({fieldId:'companyname'}) : aditionalCustomerInfo?.companyname ); let rfc = ( type == 'edit' ? rowCustomer.getText({fieldId:'custentity_mx_rfc'}) : rowCustomer.getValue({fieldId:'custentity_mx_rfc'}) ); // let telefono1 = ( type == 'edit' ? rowCustomer.getText({fieldId:'phone'}) : rowCustomer.getValue({fieldId:'phone'}) ); let telefono2 = ( type == 'edit' ? rowCustomer.getText({fieldId:'altphone'}) : rowCustomer.getValue({fieldId:'altphone'}) ); let email = ( type == 'edit' ? rowCustomer.getText({fieldId:'email'}) : rowCustomer.getValue({fieldId:'email'}) ); let saldo = ( type == 'edit' ? rowCustomer.getText({fieldId:'balance'}) : rowCustomer.getValue({fieldId:'balance'}) ); saldo = ( saldo ? Number( parseFloat( saldo ).toFixed(2) ) : 0.00); let data = { "numero_cliente":"", "identificador_externo": entityId, "nombre":nombre ? nombre : "Nombre cliente", "rfc":rfc ? rfc : "XAXX010101000", "calle":defaultAddress.calle ?? "", "no_exterior":defaultAddress.numExt ?? "", "no_interior":defaultAddress.numInt ?? "", "colonia":defaultAddress.colonia ?? "", "localidad":defaultAddress.ciudad ?? "", "referencia":defaultAddress.entreCalle1 ?? "", "ciudad":defaultAddress.ciudad ?? "", "estado":defaultAddress.estado ?? "", "codigo_postal":( defaultAddress.codigo_postal ?? "31135" ), "pais":defaultAddress.pais ?? "", "telefono1":defaultAddress.telefonoPrincipal ?? "4448111213", "telefono2":telefono2 ?? "", "activo":"1", "email":email ?? "", "saldo":saldo, "politica_venta_id":politicaId ?? "" }; log.debug('Data customer', data); return data; } // Configura los datos a enviar del consumidor a SGC web const setDataConsumer = (rowCustomer, aditionalCustomerInfo = false, politicaId, clienteId, address, type) => { // log.debug('info', 'entrΓ³ a la funciΓ³n de configurar la informaciΓ³n del cliente'); let entityId = aditionalCustomerInfo.entityid; let nombre = ( type == 'edit' ? rowCustomer.getText({fieldId:'altname'}) : aditionalCustomerInfo.altname ?? 'Consumidor genΓ©rico' ); // let telefono1 = ( type == 'edit' ? rowCustomer.getText({fieldId:'phone'}) : aditionalCustomerInfo.phone ?? 'industrial' ); let telefono2 = ( type == 'edit' ? rowCustomer.getText({fieldId:'altphone'}) : aditionalCustomerInfo.altphone ?? '' ); let email = ( type == 'edit' ? rowCustomer.getText({fieldId:'email'}) : aditionalCustomerInfo.email ?? 'PI:EMAIL:efpyi@example.comEND_PI' ); let saldo = ( type == 'edit' ? rowCustomer.getText({fieldId:'balance'}) : aditionalCustomerInfo.balance ?? 0 ); saldo = ( saldo ? Number( parseFloat( saldo ).toFixed(2) ) : 0.00); let calle = address.calle; address.numExt ? calle += ' NO. EXT. '+ address.numExt : ''; address.numInt ? calle += ' NO. INT. '+ address.numInt : ''; let data = { "numero_consumidor":"", "identificador_externo": entityId+'-'+address.etiqueta, // "identificador_externo": "0000"+address.id+address.etiqueta, "nombres":nombre ? nombre : "Nombre consumidor", "apellidos":".", "telefono1":address.telefonoPrincipal ?? "industrial", "telefono2":telefono2 ?? "", "descripcion":"Consumidor de cliente "+clienteId, "comentario" :"", "calle_numero":calle ? calle : "", "colonia":address.colonia ?? "", "ciudad":address.ciudad ?? "", "estado":address.estado ?? "", "pais":address.pais ?? "", "codigo_postal":( address.codigo_postal ?? "31135" ), "email":email ?? "", "saldo":saldo, "tipo_consumidor_id":"", "politica_consumo_id":politicaId ?? "", "cliente_id":clienteId, "capacidad":"150", "tipo_pago":"", "numero_verificador":"", "ruta_id":"" }; // Falta la lΓ³gica para obtener la ruta asignada, tipo de cliente (campo tipo_consumidor) log.debug('info consumidor', data); return data; } // Configura los datos a enviar para las polΓ­ticas de consumo const setDataSalesPolicy = (rowCustomer, aditionalConsumerInfo = false, type) => { // log.debug('info', 'entrΓ³ a la funciΓ³n de setear la polΓ­tica de venta'); let limite_credito = 250000; // let limite_credito = ( type == 'edit' ? rowCustomer.getValue({fieldId: 'creditlimit'}) : rowCustomer.getValue({fieldId: 'creditlimit'}) ); let tipo_pago = ( type == 'edit' ? rowCustomer.getValue({fieldId: 'custentity_ptg_alianza_comercial_cliente'}) : rowCustomer.getValue({fieldId:'custentity_ptg_alianza_comercial_cliente'}) ); let identificador = tipo_pago == 2 ? 'CREDITO_DEFAULT' : 'CONTADO'; // limite_credito = ( limite_credito ? Number( parseFloat(limite_credito) ) : '' ); tipo_pago = ( tipo_pago == 2 ? 2 : ( tipo_pago == 3 ? 1 : 1 ) ); let data = { // "nombre":"PolΓ­tica de venta para cliente 0000"+rowCustomer.id, "nombre":identificador, // "identificador_externo":"PV0000"+rowCustomer.id, "identificador_externo":identificador, "activa":"1", "tipo_pago":tipo_pago, "limite_credito":identificador == 'CONTADO' ? 0 : limite_credito, "numero_semanas_credito":1, "frecuencia_factura":0, "facturar_todos_servicios":0, "facturar_servicios_vpg":0, "recordatorio_pago":0, "recordatorio_pago_dias":0, "notificar_limite_credito":0, "bloqueo_morosidad":0 }; log.debug('info polΓ­tica de venta', data); return data; } // Configura los datos a enviar para las polΓ­ticas de consumo const setDataConsumptionPolicy = (rowCustomer, address, type) => { // log.debug('info', 'entrΓ³ a la funciΓ³n de configurar la informaciΓ³n del cliente'); let nombre = address.territorioZona; let limite_credito = ( type == 'edit' ? rowCustomer.getText({fieldId:'creditlimit'}) : rowCustomer.getValue({fieldId:'creditlimit'}) ); let descuento = ( type == 'edit' ? rowCustomer.getValue({fieldId:'custentity_ptg_descuento_asignar'}) : rowCustomer.getValue({fieldId:'custentity_ptg_descuento_asignar'}) ); log.debug('Descuento en politica consumo', descuento); let splitDesc = ( descuento ? descuento.split('.') : '00'); limite_credito = (limite_credito ? Number(parseInt(limite_credito)) : 0.00); let centavos = Number( parseInt( ( splitDesc[1] ? splitDesc[1] : '00' ) ).toFixed(2) ); if ( centavos < 10 ) { centavos = '0'.concat(centavos); } else { // } // centavos = ( centavos == '00' ? '00' : ); // Mejorar lΓ³gica para aplicar los descuentos aquΓ­ let data = { "nombre":nombre, "identificador_externo":"L"+(centavos)+nombre, "activa":"1", "tipo_pago":0, "limite_credito":limite_credito, "hora_inicial":"00:00", "hora_final":"23:45", "numero_servicios":1, "restringir_gps":0, "restringir_tag":0, "impuesto_id":"", "descuento_id":"", "ticket_servicios_id":"" }; log.debug('info polΓ­tica de consumo', data); return data; } // Query que obtiene las direcciones del cliente creado const searchCustomerAddresses = (customerId) => { let addressObj = { default : '', addresses : [] }; let sql = 'SELECT customerAddressbook.entity as idCliente, customerAddressbook.internalId as idDireccion, zip, customerAddressbook.label as etiqueta,'+ 'customerAddressbook.defaultshipping as envioPredeterminado, customerAddressbook.defaultbilling as facturacionPredeterminada,'+ 'customerAddressbookEntityAddress.custrecord_ptg_colonia_ruta as idColoniaRuta, customerAddressbookEntityAddress.custrecord_ptg_nombre_colonia as nombreColonia,'+ 'customerAddressbookEntityAddress.custrecord_ptg_exterior_number as numeroExterior, customerAddressbookEntityAddress.custrecord_ptg_interior_number as numeroInterior,'+ 'customerAddressbookEntityAddress.custrecord_ptg_estado as estado, customerAddressbookEntityAddress.city as ciudad, customerAddressbookEntityAddress.country as pais,'+ 'customerAddressbookEntityAddress.custrecord_ptg_street as calle, '+ 'customerAddressbookEntityAddress.custrecord_ptg_entrecalle_ as entreCalle1, customerAddressbookEntityAddress.custrecord_ptg_y_entre_ as entreCalle2,'+ 'customerAddressbookEntityAddress.custrecord_ptg_telefono_principal as telefonoPrincipal,'+ 'CUSTOMRECORD_PTG_COLONIASRUTAS_.custrecord_ptg_zona_de_precio_ as idZonaPrecio,'+ 'CUSTOMRECORD_PTG_ZONASDEPRECIO_.name as nombreZona, CUSTOMRECORD_PTG_ZONASDEPRECIO_.custrecord_ptg_precio_ as precioZona, custrecord_ptg_territorio_ as territorioZona '+ 'FROM customerAddressbook '+ 'left join customerAddressbookEntityAddress on customerAddressbook.addressbookaddress = customerAddressbookEntityAddress.nkey '+ 'left join CUSTOMRECORD_PTG_COLONIASRUTAS_ on customerAddressbookEntityAddress.custrecord_ptg_colonia_ruta = CUSTOMRECORD_PTG_COLONIASRUTAS_.id '+ 'left join CUSTOMRECORD_PTG_ZONASDEPRECIO_ on CUSTOMRECORD_PTG_COLONIASRUTAS_.custrecord_ptg_zona_de_precio_ = CUSTOMRECORD_PTG_ZONASDEPRECIO_.id '+ 'WHERE customerAddressbook.entity ='+ customerId; let resultIterator = query.runSuiteQLPaged({ query: sql, pageSize: 1000 }).iterator(); resultIterator.each(function (page) { let pageIterator = page.value.data.iterator(); pageIterator.each(function (row) { let address = {}; // log.debug('Row de query pura', row); if(!!row.value.getValue(0)) { address.id = row.value.getValue(1); address.codigo_postal = row.value.getValue(2); address.etiqueta = row.value.getValue(3); address.defaultShipping = row.value.getValue(4); address.defaultBilling = row.value.getValue(5); address.colonia = row.value.getValue(7); address.numExt = row.value.getValue(8); address.numInt = row.value.getValue(9); address.estado = row.value.getValue(10); address.ciudad = row.value.getValue(11); address.pais = row.value.getValue(12); address.calle = row.value.getValue(13); address.entreCalle1 = row.value.getValue(14); address.entreCalle2 = row.value.getValue(15); address.telefonoPrincipal = row.value.getValue(16); address.idZona = row.value.getValue(17); address.nombreZona = row.value.getValue(18); address.precioZona = row.value.getValue(19); address.territorioZona = row.value.getValue(20); // obj.text = `${row.value.getValue(1)} - ${row.value.getValue(2)} - ${row.value.getValue(3)}`; // Es la direcciΓ³n por default if ( address.defaultShipping == "T" ) { addressObj.default = address; } // Se hace el push del objeto de la direcciΓ³n al arreglo de direcciones a retornar addressObj.addresses.push(address); } return true; }); return true; }); // log.debug('Data sql', data); return addressObj; } // Guarda / actualiza un cliente en SGC web const registerSgcData = (xmlContent, idToken, typeModule, action, data) => { log.debug('data', data); log.debug('typeModule', typeModule); xmlContent = xmlContent.split('idSession').join(`${idToken}`); xmlContent = xmlContent.split('typeModule').join(`${typeModule}`); xmlContent = xmlContent.split('action').join(`${action}`); xmlContent = xmlContent.split('data').join(`${JSON.stringify(data)}`); // log.debug('despues del primer join', xmlContent); let headers = {}; headers['Content-Type'] = 'text/xml; charset=utf-8'; // headers['SOAPAction'] = 'http://testpotogas.sgcweb.com.mx/ws/1094AEV2/v2/soap.php/procesarPeticion'; // let url = 'http://testpotogas.sgcweb.com.mx//ws/1094AEV2/v2/soap.php'; headers['SOAPAction'] = 'http://potogas.sgcweb.com.mx/ws/1094AEV2/v2/soap.php/procesarPeticion'; let url = 'http://potogas.sgcweb.com.mx/ws/1094AEV2/v2/soap.php'; let response = http.request({ method: http.Method.POST, url: url, body: xmlContent, headers: headers }); // log.debug('response', response.body) let xmlFileContent = response.body; let xmlDocument = xml.Parser.fromString({ text: xmlFileContent }); let dataJson = xmlDocument.getElementsByTagName({ tagName: 'informacion' }); let responseCode = xmlDocument.getElementsByTagName({ tagName: 'codigo' }); // log.debug('response info', dataJson); // log.debug('response code', responseCode); return { info : dataJson, code : responseCode, }; } return {beforeLoad, beforeSubmit, afterSubmit} });
/** * @NApiVersion 2.x * @NScriptType UserEventScript * @NModuleScope SameAccount */ define(['N/file', 'N/sftp', 'N/error'], function(file, sftp, error) { return { beforeLoad: function(){ var portNumber = -1; var connectTimeout = -1; var transferTimeout = -1; //these variables can be taken as parameters of the script instead if (portNumber < sftp.MIN_PORT_NUMBER || portNumber > sftp.MAX_PORT_NUMBER) portNumber = sftp.DEFAULT_PORT_NUMBER; if (connectTimeout < sftp.MIN_CONNECT_TIMEOUT) connectTimeout = sftp.MIN_CONNECT_TIMEOUT; else if (connectTimeout > sftp.MAX_CONNECT_TIMEOUT) connectTimeout = sftp.MAX_CONNECT_TIMEOUT; var connection = sftp.createConnection({ username: 'sftpuser', keyId: 'custkey1', url: '192.168.0.100', port: portNumber, directory: 'inbound', timeout: connectTimeout, hostKey: "AAAAB3NzaC1yc2EAAAADAQABAAABAQDMifKH2vTxdiype8nem7+lS3x7dTQR/A67KdsR/5C2WUcDipBzYhHbnG6Am12Nd2tlM01LnaBZA6/8P4Y9x/sGTxtsdE/MzeGDUBn6HBlQvgIrhX62wgoKGQ+P2lEAO1+Vz8y3/MB1NmD7Fc62cJ9Mu88YA6jwJOIPZeHYNVyIm9OrY6VyzYyvSJhH0x7SXyvGnijJQF4G8C4c8u/UVpF/sE16xKZtly2Rx0aDL2FsDRtpyPmM602/R6ISbsmgab3MzzAEIu+zLDMdIBJn3cDhNt1F7Rar6Tu0u18KCkk8GPxbnxDuG4sCNOnXPYkDXSMUbM/ocRjYGtqdZUMmeTf3" }); // can also be a big file (created for example by async search) var myFileToUpload = file.create({ name: 'originalname.txt', fileType: file.Type.PLAINTEXT, contents: 'I am a test file.' }); if (myFileToUpload.size > connection.MAX_FILE_SIZE) throw error.create({name:"FILE_IS_TOO_BIG", message:"The file you are trying to upload is too big"}); var minTransferTimeout = 10; if (transferTimeout > connection.MAX_TRANSFER_TIMEOUT) transferTimeout = connection.MAX_TRANSFER_TIMEOUT; else if (transferTimeout < minTransferTimeout) transferTimeout = minTransferTimteout; connection.upload({ directory: 'files', filename: 'test.txt', file: myFileToUpload, replaceExisting: true, timeout: transferTimeout }); } }; });
285
[{"tag": "IP_ADDRESS", "value": "192.168.0.100", "start": 927, "end": 940}, {"tag": "KEY", "value": "AAAAB3NzaC1yc2EAAAADAQABAAABAQDMifKH2vTxdiype8nem7+lS3x7dTQR/A67KdsR/5C2WUcDipBzYhHbnG6Am12Nd2tlM01LnaBZA6/8P4Y9x/sGTxtsdE/MzeGDUBn6HBlQvgIrhX62wgoKGQ+P2lEAO1+Vz8y3/MB1NmD7Fc62cJ9Mu88YA6jwJOIPZeHYNVyIm9OrY6VyzYyvSJhH0x7SXyvGnijJQF4G8C4c8u/UVpF/sE16xKZtly2Rx0aDL2FsDRtpyPmM602/R6ISbsmgab3MzzAEIu+zLDMdIBJn3cDhNt1F7Rar6Tu0u18KCkk8GPxbnxDuG4sCNOnXPYkDXSMUbM/ocRjYGtqdZUMmeTf3", "start": 1082, "end": 1454}]
true
2
/** * @NApiVersion 2.x * @NScriptType UserEventScript * @NModuleScope SameAccount */ define(['N/file', 'N/sftp', 'N/error'], function(file, sftp, error) { return { beforeLoad: function(){ var portNumber = -1; var connectTimeout = -1; var transferTimeout = -1; //these variables can be taken as parameters of the script instead if (portNumber < sftp.MIN_PORT_NUMBER || portNumber > sftp.MAX_PORT_NUMBER) portNumber = sftp.DEFAULT_PORT_NUMBER; if (connectTimeout < sftp.MIN_CONNECT_TIMEOUT) connectTimeout = sftp.MIN_CONNECT_TIMEOUT; else if (connectTimeout > sftp.MAX_CONNECT_TIMEOUT) connectTimeout = sftp.MAX_CONNECT_TIMEOUT; var connection = sftp.createConnection({ username: 'sftpuser', keyId: 'custkey1', url: '192.168.0.100', port: portNumber, directory: 'inbound', timeout: connectTimeout, hostKey: "se2xy1bknelxn4y8xzxu3trosptip3q5" }); // can also be a big file (created for example by async search) var myFileToUpload = file.create({ name: 'originalname.txt', fileType: file.Type.PLAINTEXT, contents: 'I am a test file.' }); if (myFileToUpload.size > connection.MAX_FILE_SIZE) throw error.create({name:"FILE_IS_TOO_BIG", message:"The file you are trying to upload is too big"}); var minTransferTimeout = 10; if (transferTimeout > connection.MAX_TRANSFER_TIMEOUT) transferTimeout = connection.MAX_TRANSFER_TIMEOUT; else if (transferTimeout < minTransferTimeout) transferTimeout = minTransferTimteout; connection.upload({ directory: 'files', filename: 'test.txt', file: myFileToUpload, replaceExisting: true, timeout: transferTimeout }); } }; });
true
/** * @NApiVersion 2.x * @NScriptType UserEventScript * @NModuleScope SameAccount */ define(['N/file', 'N/sftp', 'N/error'], function(file, sftp, error) { return { beforeLoad: function(){ var portNumber = -1; var connectTimeout = -1; var transferTimeout = -1; //these variables can be taken as parameters of the script instead if (portNumber < sftp.MIN_PORT_NUMBER || portNumber > sftp.MAX_PORT_NUMBER) portNumber = sftp.DEFAULT_PORT_NUMBER; if (connectTimeout < sftp.MIN_CONNECT_TIMEOUT) connectTimeout = sftp.MIN_CONNECT_TIMEOUT; else if (connectTimeout > sftp.MAX_CONNECT_TIMEOUT) connectTimeout = sftp.MAX_CONNECT_TIMEOUT; var connection = sftp.createConnection({ username: 'sftpuser', keyId: 'custkey1', url: '192.168.0.100', port: portNumber, directory: 'inbound', timeout: connectTimeout, hostKey: "PI:KEY:se2xy1bknelxn4y8xzxu3trosptip3q5END_PI" }); // can also be a big file (created for example by async search) var myFileToUpload = file.create({ name: 'originalname.txt', fileType: file.Type.PLAINTEXT, contents: 'I am a test file.' }); if (myFileToUpload.size > connection.MAX_FILE_SIZE) throw error.create({name:"FILE_IS_TOO_BIG", message:"The file you are trying to upload is too big"}); var minTransferTimeout = 10; if (transferTimeout > connection.MAX_TRANSFER_TIMEOUT) transferTimeout = connection.MAX_TRANSFER_TIMEOUT; else if (transferTimeout < minTransferTimeout) transferTimeout = minTransferTimteout; connection.upload({ directory: 'files', filename: 'test.txt', file: myFileToUpload, replaceExisting: true, timeout: transferTimeout }); } }; });
/** * @NApiVersion 2.x * @NScriptType ScheduledScript * * Module Description * * @Last Modified by: Sruti Desai * */ define(['N/runtime', 'N/search', 'N/record', 'N/log', 'N/task', 'N/currentRecord', 'N/format'], function(runtime, search, record, log, task, currentRecord, format) { var zee = 0; var role = 0; var usage_threshold = 20; var usage_threshold_invoice = 1000; var adhoc_inv_deploy = 'customdeploy2'; var prev_inv_deploy = null; var ctx = runtime.getCurrentScript(); var service_start_date; var service_end_date; var franchisee; var from_invoice = null; var count_loop_cust = 0; function invoiceCreation() { if (!isNullorEmpty(ctx.getParameter({name: 'custscript_deployment_prev'}))) { prev_inv_deploy = ctx.getParameter({name: 'custscript_deployment_prev'}); } else { prev_inv_deploy = ctx.deploymentId; } if (!isNullorEmpty(ctx.getParameter({name: 'custscript_id_customer'}) && !isNullorEmpty(ctx.getParameter({name: 'custscript_id_invoice'})))) { service_start_date = ctx.getParameter({name: 'custscript_service_start'}); service_end_date = ctx.getParameter({name: 'custscript_service_end'}); franchisee = ctx.getParameter({name: 'custscript_id_zee'}); from_invoice = ctx.getParameter({name: 'custscript_custom_invoice'}); var result = updateJobs(ctx.getParameter({name: 'custscript_id_customer'}), ctx.getParameter({name: 'custscript_id_invoice'}), service_start_date, service_end_date, franchisee, from_invoice); if (result == true) { var params = { custscript_prev_deployment: ctx.deploymentId } var reschedule = task.create({ taskType: task.TaskType.SCHEDULED_SCRIPT, scriptId: prev_inv_deploy, deploymentId: adhoc_inv_deploy, params: params }); reschedule.submit(); if (reschedule == false) { return false; } } } } function updateJobs(customer_internal_id, invoiceId, service_start_date, service_end_date, franchisee, from_invoice) { var count_loop_job = 0; log.debug({title: 'START ---> update job function', details: ctx.getRemainingUsage()}); log.debug({ title: 'customer_internal_id | ' + customer_internal_id, details: ctx.getRemainingUsage() }); log.debug({title: 'invoiceId | ' + invoiceId, details: ctx.getRemainingUsage() }); log.debug({ title: 'service_end_date | ' + service_end_date, details: ctx.getRemainingUsage()}); log.debug({ title: 'service_start_date | ' + service_start_date, details: ctx.getRemainingUsage()}); log.debug({ title: 'from_invoice | ' + from_invoice, details: ctx.getRemainingUsage()}); log.debug({ title: 'franchisee | ' + franchisee, details: ctx.getRemainingUsage()}); if (from_invoice == 'Yes') { var searched_alljobs = search.load({ id: 'customsearch_job_invoicing_jobs', type: 'customrecord_job' }); } else { var searched_alljobs = search.load({ id: 'customsearch_job_inv_process_job_all', type: 'customrecord_job' }); } searched_alljobs.filters.push(search.createFilter({ name: 'custrecord_job_customer', operator: search.Operator.IS, values: customer_internal_id, })); searched_alljobs.filters.push(search.createFilter({ name: 'custrecord_job_franchisee', operator: search.Operator.IS, values: franchisee, })); if (!isNullorEmpty(service_start_date) && !isNullorEmpty(service_end_date)) { searched_alljobs.filters.push(search.createFilter({ name: 'custrecord_job_date_scheduled', operator: search.Operator.ONORAFTER, values: format.parse({value: service_start_date, type: format.Type.DATE }) })); searched_alljobs.filters.push(search.createFilter({ name: 'custrecord_job_date_scheduled', operator: search.Operator.ONORBEFORE, values: format.parse({value: service_end_date, type: format.Type.DATE }) })); } var resultSet_alljobs = searched_alljobs.run(); resultSet_alljobs.each(function(searchResult_alljobs) { var usage_loopstart_job = ctx.getRemainingUsage(); count_loop_job++; //nlapiLogExecution('DEBUG', 'START ---> usage remianing per loop of job update', ctx.getRemainingUsage()); if (ctx.getRemainingUsage() <= usage_threshold) { var params = { custscript_id_customer: customer_internal_id, custscript_id_invoice: invoiceId, custscript_deployment_prev: ctx.deploymentId, custscript_service_start: service_start_date, custscript_id_zee: service_end_date, custscript_zee: franchisee, custscript_custom_invoice: 'Yes' } var reschedule = task.create({ taskType: task.TaskType.SCHEDULED_SCRIPT, scriptId: prev_inv_deploy, deploymentId: adhoc_inv_deploy, params: params }); reschedule.submit(); if (reschedule == false) { return false; } } var job_id = searchResult_alljobs.getValue('internalid'); var invoiceable_yes_no = searchResult_alljobs.getValue('custrecord_job_invoiceable'); log.debug({ title: 'jobID', details: job_id }); var job_record = record.load({ type: 'customrecord_job', id: job_id, }); // job_record.getValue('custrecord_job_date_invoiced') != getDate() if (isNullorEmpty(job_record.getValue({ fieldId: 'custrecord_job_date_invoiced' })) && isNullorEmpty(job_record.getValue({ fieldId: 'custrecord_job_invoice' }))) { log.debug({ title: 'Inside', details: 'Inside' }) if (from_invoice == 'Yes') { var jobGroupStatus = job_record.getValue({ fieldId: 'custrecord_job_group_status' }); var jobInvoiceable = job_record.getValue({ fieldId: 'custrecord_job_invoiceable' }); var jobCat = job_record.getValue({ fieldId: 'custrecord_job_service_category' }); var packageStatus = job_record.getValue({ fieldId: 'custrecord_package_status' }); if (isNullorEmpty(jobInvoiceable)) { if (!isNullorEmpty(packageStatus)) { if (packageStatus == 1 || isNullorEmpty(packageStatus)) { // Job Group Status is Null for Extras and Jobs Created in NS job_record.setValue({ fieldId: 'custrecord_job_invoiceable', value: 1 }); } else { job_record.setValue({ fieldId: 'custrecord_job_invoiceable', value: 2 }); } } else { if (jobGroupStatus == 'Completed' || isNullorEmpty(jobGroupStatus)) { // Job Group Status is Null for Extras and Jobs Created in NS job_record.setValue({ fieldId: 'custrecord_job_invoiceable', value: 1 }); } else { job_record.setValue({ fieldId: 'custrecord_job_invoiceable', value: 2 }); } } } job_record.setValue({ fieldId: 'custrecord_job_invoice', value: invoiceId }); job_record.setValue({ fieldId: 'custrecord_job_date_reviewed', value: getDate() }); job_record.setValue({ fieldId: 'custrecord_job_date_inv_finalised', value: getDate() }); job_record.setValue({ fieldId: 'custrecord_job_date_invoiced', value: getDate() }); job_record.setValue({ fieldId: 'custrecord_job_invoice_custom', value: 1 }); } log.debug({ title: 'Job #: ' + count_loop_job + ' | Job: ' + job_id + '.', details: usage_loopstart_job - ctx.getRemainingUsage() }); job_record.save({ enableSourcing: true, ignoreMandatoryFields: true }) //WS Log: } else { var body = 'Customer: ' + customer_internal_id + ' | Job: ' + job_id + 'cannot be updated because Invoice ID and Date Invoice is not Empty.'; email.send({ author: 112209, body: body, recipients: ['ankith.ravindran@mailplus.com.au', 'willian.suryadharma@mailplus.com.au'], subject: 'Invoice Creation - Customer: ' + customer_internal_id + ' cannot update Job', }); //WS log: log.error({ title: 'Job #: ' + count_loop_job + ' | Job: ' + job_id + '.', details: 'ERROR: JOB X UPDATED - Inv & Date Invoice not empty.' }); return false; } return true; }); //WS Log: log.debug({ title: '--> END | update job function', details: ctx.getRemainingUsage() }); return true; } function getDate() { var date = new Date(); date.setHours(date.getHours() + 1); date = format.format({ value: date, type: format.Type.DATE }) return date; } function invoice_date() { var date = new Date(); var month = date.getMonth(); //Months 0 - 11 var day = date.getDate(); var year = date.getFullYear(); //If allocator run on the first day of the month, it takes the last month as the filter if (day == 1 || day == 2 || day == 3 || day == 4 || day == 5) { if (month == 0) { month = 11; year = year - 1 } else { month = month - 1; } } // var firstDay = new Date(year, (month), 1); var lastDay = new Date(year, (month + 1), 0); return format.format({ value: lastDay, type: format.Type.DATE}); } function service_start_end_date(date_finalised) { var split_date = date_finalised.split('/'); var date = new Date(); var firstDay = new Date(date.getFullYear(), parseInt(split_date[1]) - 1, 1); var lastDay = new Date(date.getFullYear(), split_date[1], 0); var service_range = []; service_range[0] = format.format({ value: firstDay, type: format.Type.DATE}); service_range[1] = format.format({ value: lastDay, type: format.Type.DATE}); return service_range; } function isNullorEmpty(strVal) { return (strVal == null || strVal == '' || strVal == 'null' || strVal == undefined || strVal == 'undefined' || strVal == '- None -'); } role = runtime.getCurrentUser().role; return { execute: invoiceCreation } } );
825
[{"tag": "EMAIL", "value": "ankith.ravindran@mailplus.com.au", "start": 10190, "end": 10222}, {"tag": "EMAIL", "value": "willian.suryadharma@mailplus.com.au", "start": 10226, "end": 10261}]
true
2
/** * @NApiVersion 2.x * @NScriptType ScheduledScript * * Module Description * * @Last Modified by: Sruti Desai * */ define(['N/runtime', 'N/search', 'N/record', 'N/log', 'N/task', 'N/currentRecord', 'N/format'], function(runtime, search, record, log, task, currentRecord, format) { var zee = 0; var role = 0; var usage_threshold = 20; var usage_threshold_invoice = 1000; var adhoc_inv_deploy = 'customdeploy2'; var prev_inv_deploy = null; var ctx = runtime.getCurrentScript(); var service_start_date; var service_end_date; var franchisee; var from_invoice = null; var count_loop_cust = 0; function invoiceCreation() { if (!isNullorEmpty(ctx.getParameter({name: 'custscript_deployment_prev'}))) { prev_inv_deploy = ctx.getParameter({name: 'custscript_deployment_prev'}); } else { prev_inv_deploy = ctx.deploymentId; } if (!isNullorEmpty(ctx.getParameter({name: 'custscript_id_customer'}) && !isNullorEmpty(ctx.getParameter({name: 'custscript_id_invoice'})))) { service_start_date = ctx.getParameter({name: 'custscript_service_start'}); service_end_date = ctx.getParameter({name: 'custscript_service_end'}); franchisee = ctx.getParameter({name: 'custscript_id_zee'}); from_invoice = ctx.getParameter({name: 'custscript_custom_invoice'}); var result = updateJobs(ctx.getParameter({name: 'custscript_id_customer'}), ctx.getParameter({name: 'custscript_id_invoice'}), service_start_date, service_end_date, franchisee, from_invoice); if (result == true) { var params = { custscript_prev_deployment: ctx.deploymentId } var reschedule = task.create({ taskType: task.TaskType.SCHEDULED_SCRIPT, scriptId: prev_inv_deploy, deploymentId: adhoc_inv_deploy, params: params }); reschedule.submit(); if (reschedule == false) { return false; } } } } function updateJobs(customer_internal_id, invoiceId, service_start_date, service_end_date, franchisee, from_invoice) { var count_loop_job = 0; log.debug({title: 'START ---> update job function', details: ctx.getRemainingUsage()}); log.debug({ title: 'customer_internal_id | ' + customer_internal_id, details: ctx.getRemainingUsage() }); log.debug({title: 'invoiceId | ' + invoiceId, details: ctx.getRemainingUsage() }); log.debug({ title: 'service_end_date | ' + service_end_date, details: ctx.getRemainingUsage()}); log.debug({ title: 'service_start_date | ' + service_start_date, details: ctx.getRemainingUsage()}); log.debug({ title: 'from_invoice | ' + from_invoice, details: ctx.getRemainingUsage()}); log.debug({ title: 'franchisee | ' + franchisee, details: ctx.getRemainingUsage()}); if (from_invoice == 'Yes') { var searched_alljobs = search.load({ id: 'customsearch_job_invoicing_jobs', type: 'customrecord_job' }); } else { var searched_alljobs = search.load({ id: 'customsearch_job_inv_process_job_all', type: 'customrecord_job' }); } searched_alljobs.filters.push(search.createFilter({ name: 'custrecord_job_customer', operator: search.Operator.IS, values: customer_internal_id, })); searched_alljobs.filters.push(search.createFilter({ name: 'custrecord_job_franchisee', operator: search.Operator.IS, values: franchisee, })); if (!isNullorEmpty(service_start_date) && !isNullorEmpty(service_end_date)) { searched_alljobs.filters.push(search.createFilter({ name: 'custrecord_job_date_scheduled', operator: search.Operator.ONORAFTER, values: format.parse({value: service_start_date, type: format.Type.DATE }) })); searched_alljobs.filters.push(search.createFilter({ name: 'custrecord_job_date_scheduled', operator: search.Operator.ONORBEFORE, values: format.parse({value: service_end_date, type: format.Type.DATE }) })); } var resultSet_alljobs = searched_alljobs.run(); resultSet_alljobs.each(function(searchResult_alljobs) { var usage_loopstart_job = ctx.getRemainingUsage(); count_loop_job++; //nlapiLogExecution('DEBUG', 'START ---> usage remianing per loop of job update', ctx.getRemainingUsage()); if (ctx.getRemainingUsage() <= usage_threshold) { var params = { custscript_id_customer: customer_internal_id, custscript_id_invoice: invoiceId, custscript_deployment_prev: ctx.deploymentId, custscript_service_start: service_start_date, custscript_id_zee: service_end_date, custscript_zee: franchisee, custscript_custom_invoice: 'Yes' } var reschedule = task.create({ taskType: task.TaskType.SCHEDULED_SCRIPT, scriptId: prev_inv_deploy, deploymentId: adhoc_inv_deploy, params: params }); reschedule.submit(); if (reschedule == false) { return false; } } var job_id = searchResult_alljobs.getValue('internalid'); var invoiceable_yes_no = searchResult_alljobs.getValue('custrecord_job_invoiceable'); log.debug({ title: 'jobID', details: job_id }); var job_record = record.load({ type: 'customrecord_job', id: job_id, }); // job_record.getValue('custrecord_job_date_invoiced') != getDate() if (isNullorEmpty(job_record.getValue({ fieldId: 'custrecord_job_date_invoiced' })) && isNullorEmpty(job_record.getValue({ fieldId: 'custrecord_job_invoice' }))) { log.debug({ title: 'Inside', details: 'Inside' }) if (from_invoice == 'Yes') { var jobGroupStatus = job_record.getValue({ fieldId: 'custrecord_job_group_status' }); var jobInvoiceable = job_record.getValue({ fieldId: 'custrecord_job_invoiceable' }); var jobCat = job_record.getValue({ fieldId: 'custrecord_job_service_category' }); var packageStatus = job_record.getValue({ fieldId: 'custrecord_package_status' }); if (isNullorEmpty(jobInvoiceable)) { if (!isNullorEmpty(packageStatus)) { if (packageStatus == 1 || isNullorEmpty(packageStatus)) { // Job Group Status is Null for Extras and Jobs Created in NS job_record.setValue({ fieldId: 'custrecord_job_invoiceable', value: 1 }); } else { job_record.setValue({ fieldId: 'custrecord_job_invoiceable', value: 2 }); } } else { if (jobGroupStatus == 'Completed' || isNullorEmpty(jobGroupStatus)) { // Job Group Status is Null for Extras and Jobs Created in NS job_record.setValue({ fieldId: 'custrecord_job_invoiceable', value: 1 }); } else { job_record.setValue({ fieldId: 'custrecord_job_invoiceable', value: 2 }); } } } job_record.setValue({ fieldId: 'custrecord_job_invoice', value: invoiceId }); job_record.setValue({ fieldId: 'custrecord_job_date_reviewed', value: getDate() }); job_record.setValue({ fieldId: 'custrecord_job_date_inv_finalised', value: getDate() }); job_record.setValue({ fieldId: 'custrecord_job_date_invoiced', value: getDate() }); job_record.setValue({ fieldId: 'custrecord_job_invoice_custom', value: 1 }); } log.debug({ title: 'Job #: ' + count_loop_job + ' | Job: ' + job_id + '.', details: usage_loopstart_job - ctx.getRemainingUsage() }); job_record.save({ enableSourcing: true, ignoreMandatoryFields: true }) //WS Log: } else { var body = 'Customer: ' + customer_internal_id + ' | Job: ' + job_id + 'cannot be updated because Invoice ID and Date Invoice is not Empty.'; email.send({ author: 112209, body: body, recipients: ['kenaa@example.com', 'dycjh@example.com'], subject: 'Invoice Creation - Customer: ' + customer_internal_id + ' cannot update Job', }); //WS log: log.error({ title: 'Job #: ' + count_loop_job + ' | Job: ' + job_id + '.', details: 'ERROR: JOB X UPDATED - Inv & Date Invoice not empty.' }); return false; } return true; }); //WS Log: log.debug({ title: '--> END | update job function', details: ctx.getRemainingUsage() }); return true; } function getDate() { var date = new Date(); date.setHours(date.getHours() + 1); date = format.format({ value: date, type: format.Type.DATE }) return date; } function invoice_date() { var date = new Date(); var month = date.getMonth(); //Months 0 - 11 var day = date.getDate(); var year = date.getFullYear(); //If allocator run on the first day of the month, it takes the last month as the filter if (day == 1 || day == 2 || day == 3 || day == 4 || day == 5) { if (month == 0) { month = 11; year = year - 1 } else { month = month - 1; } } // var firstDay = new Date(year, (month), 1); var lastDay = new Date(year, (month + 1), 0); return format.format({ value: lastDay, type: format.Type.DATE}); } function service_start_end_date(date_finalised) { var split_date = date_finalised.split('/'); var date = new Date(); var firstDay = new Date(date.getFullYear(), parseInt(split_date[1]) - 1, 1); var lastDay = new Date(date.getFullYear(), split_date[1], 0); var service_range = []; service_range[0] = format.format({ value: firstDay, type: format.Type.DATE}); service_range[1] = format.format({ value: lastDay, type: format.Type.DATE}); return service_range; } function isNullorEmpty(strVal) { return (strVal == null || strVal == '' || strVal == 'null' || strVal == undefined || strVal == 'undefined' || strVal == '- None -'); } role = runtime.getCurrentUser().role; return { execute: invoiceCreation } } );
true
/** * @NApiVersion 2.x * @NScriptType ScheduledScript * * Module Description * * @Last Modified by: Sruti Desai * */ define(['N/runtime', 'N/search', 'N/record', 'N/log', 'N/task', 'N/currentRecord', 'N/format'], function(runtime, search, record, log, task, currentRecord, format) { var zee = 0; var role = 0; var usage_threshold = 20; var usage_threshold_invoice = 1000; var adhoc_inv_deploy = 'customdeploy2'; var prev_inv_deploy = null; var ctx = runtime.getCurrentScript(); var service_start_date; var service_end_date; var franchisee; var from_invoice = null; var count_loop_cust = 0; function invoiceCreation() { if (!isNullorEmpty(ctx.getParameter({name: 'custscript_deployment_prev'}))) { prev_inv_deploy = ctx.getParameter({name: 'custscript_deployment_prev'}); } else { prev_inv_deploy = ctx.deploymentId; } if (!isNullorEmpty(ctx.getParameter({name: 'custscript_id_customer'}) && !isNullorEmpty(ctx.getParameter({name: 'custscript_id_invoice'})))) { service_start_date = ctx.getParameter({name: 'custscript_service_start'}); service_end_date = ctx.getParameter({name: 'custscript_service_end'}); franchisee = ctx.getParameter({name: 'custscript_id_zee'}); from_invoice = ctx.getParameter({name: 'custscript_custom_invoice'}); var result = updateJobs(ctx.getParameter({name: 'custscript_id_customer'}), ctx.getParameter({name: 'custscript_id_invoice'}), service_start_date, service_end_date, franchisee, from_invoice); if (result == true) { var params = { custscript_prev_deployment: ctx.deploymentId } var reschedule = task.create({ taskType: task.TaskType.SCHEDULED_SCRIPT, scriptId: prev_inv_deploy, deploymentId: adhoc_inv_deploy, params: params }); reschedule.submit(); if (reschedule == false) { return false; } } } } function updateJobs(customer_internal_id, invoiceId, service_start_date, service_end_date, franchisee, from_invoice) { var count_loop_job = 0; log.debug({title: 'START ---> update job function', details: ctx.getRemainingUsage()}); log.debug({ title: 'customer_internal_id | ' + customer_internal_id, details: ctx.getRemainingUsage() }); log.debug({title: 'invoiceId | ' + invoiceId, details: ctx.getRemainingUsage() }); log.debug({ title: 'service_end_date | ' + service_end_date, details: ctx.getRemainingUsage()}); log.debug({ title: 'service_start_date | ' + service_start_date, details: ctx.getRemainingUsage()}); log.debug({ title: 'from_invoice | ' + from_invoice, details: ctx.getRemainingUsage()}); log.debug({ title: 'franchisee | ' + franchisee, details: ctx.getRemainingUsage()}); if (from_invoice == 'Yes') { var searched_alljobs = search.load({ id: 'customsearch_job_invoicing_jobs', type: 'customrecord_job' }); } else { var searched_alljobs = search.load({ id: 'customsearch_job_inv_process_job_all', type: 'customrecord_job' }); } searched_alljobs.filters.push(search.createFilter({ name: 'custrecord_job_customer', operator: search.Operator.IS, values: customer_internal_id, })); searched_alljobs.filters.push(search.createFilter({ name: 'custrecord_job_franchisee', operator: search.Operator.IS, values: franchisee, })); if (!isNullorEmpty(service_start_date) && !isNullorEmpty(service_end_date)) { searched_alljobs.filters.push(search.createFilter({ name: 'custrecord_job_date_scheduled', operator: search.Operator.ONORAFTER, values: format.parse({value: service_start_date, type: format.Type.DATE }) })); searched_alljobs.filters.push(search.createFilter({ name: 'custrecord_job_date_scheduled', operator: search.Operator.ONORBEFORE, values: format.parse({value: service_end_date, type: format.Type.DATE }) })); } var resultSet_alljobs = searched_alljobs.run(); resultSet_alljobs.each(function(searchResult_alljobs) { var usage_loopstart_job = ctx.getRemainingUsage(); count_loop_job++; //nlapiLogExecution('DEBUG', 'START ---> usage remianing per loop of job update', ctx.getRemainingUsage()); if (ctx.getRemainingUsage() <= usage_threshold) { var params = { custscript_id_customer: customer_internal_id, custscript_id_invoice: invoiceId, custscript_deployment_prev: ctx.deploymentId, custscript_service_start: service_start_date, custscript_id_zee: service_end_date, custscript_zee: franchisee, custscript_custom_invoice: 'Yes' } var reschedule = task.create({ taskType: task.TaskType.SCHEDULED_SCRIPT, scriptId: prev_inv_deploy, deploymentId: adhoc_inv_deploy, params: params }); reschedule.submit(); if (reschedule == false) { return false; } } var job_id = searchResult_alljobs.getValue('internalid'); var invoiceable_yes_no = searchResult_alljobs.getValue('custrecord_job_invoiceable'); log.debug({ title: 'jobID', details: job_id }); var job_record = record.load({ type: 'customrecord_job', id: job_id, }); // job_record.getValue('custrecord_job_date_invoiced') != getDate() if (isNullorEmpty(job_record.getValue({ fieldId: 'custrecord_job_date_invoiced' })) && isNullorEmpty(job_record.getValue({ fieldId: 'custrecord_job_invoice' }))) { log.debug({ title: 'Inside', details: 'Inside' }) if (from_invoice == 'Yes') { var jobGroupStatus = job_record.getValue({ fieldId: 'custrecord_job_group_status' }); var jobInvoiceable = job_record.getValue({ fieldId: 'custrecord_job_invoiceable' }); var jobCat = job_record.getValue({ fieldId: 'custrecord_job_service_category' }); var packageStatus = job_record.getValue({ fieldId: 'custrecord_package_status' }); if (isNullorEmpty(jobInvoiceable)) { if (!isNullorEmpty(packageStatus)) { if (packageStatus == 1 || isNullorEmpty(packageStatus)) { // Job Group Status is Null for Extras and Jobs Created in NS job_record.setValue({ fieldId: 'custrecord_job_invoiceable', value: 1 }); } else { job_record.setValue({ fieldId: 'custrecord_job_invoiceable', value: 2 }); } } else { if (jobGroupStatus == 'Completed' || isNullorEmpty(jobGroupStatus)) { // Job Group Status is Null for Extras and Jobs Created in NS job_record.setValue({ fieldId: 'custrecord_job_invoiceable', value: 1 }); } else { job_record.setValue({ fieldId: 'custrecord_job_invoiceable', value: 2 }); } } } job_record.setValue({ fieldId: 'custrecord_job_invoice', value: invoiceId }); job_record.setValue({ fieldId: 'custrecord_job_date_reviewed', value: getDate() }); job_record.setValue({ fieldId: 'custrecord_job_date_inv_finalised', value: getDate() }); job_record.setValue({ fieldId: 'custrecord_job_date_invoiced', value: getDate() }); job_record.setValue({ fieldId: 'custrecord_job_invoice_custom', value: 1 }); } log.debug({ title: 'Job #: ' + count_loop_job + ' | Job: ' + job_id + '.', details: usage_loopstart_job - ctx.getRemainingUsage() }); job_record.save({ enableSourcing: true, ignoreMandatoryFields: true }) //WS Log: } else { var body = 'Customer: ' + customer_internal_id + ' | Job: ' + job_id + 'cannot be updated because Invoice ID and Date Invoice is not Empty.'; email.send({ author: 112209, body: body, recipients: ['PI:EMAIL:kenaa@example.comEND_PI', 'PI:EMAIL:dycjh@example.comEND_PI'], subject: 'Invoice Creation - Customer: ' + customer_internal_id + ' cannot update Job', }); //WS log: log.error({ title: 'Job #: ' + count_loop_job + ' | Job: ' + job_id + '.', details: 'ERROR: JOB X UPDATED - Inv & Date Invoice not empty.' }); return false; } return true; }); //WS Log: log.debug({ title: '--> END | update job function', details: ctx.getRemainingUsage() }); return true; } function getDate() { var date = new Date(); date.setHours(date.getHours() + 1); date = format.format({ value: date, type: format.Type.DATE }) return date; } function invoice_date() { var date = new Date(); var month = date.getMonth(); //Months 0 - 11 var day = date.getDate(); var year = date.getFullYear(); //If allocator run on the first day of the month, it takes the last month as the filter if (day == 1 || day == 2 || day == 3 || day == 4 || day == 5) { if (month == 0) { month = 11; year = year - 1 } else { month = month - 1; } } // var firstDay = new Date(year, (month), 1); var lastDay = new Date(year, (month + 1), 0); return format.format({ value: lastDay, type: format.Type.DATE}); } function service_start_end_date(date_finalised) { var split_date = date_finalised.split('/'); var date = new Date(); var firstDay = new Date(date.getFullYear(), parseInt(split_date[1]) - 1, 1); var lastDay = new Date(date.getFullYear(), split_date[1], 0); var service_range = []; service_range[0] = format.format({ value: firstDay, type: format.Type.DATE}); service_range[1] = format.format({ value: lastDay, type: format.Type.DATE}); return service_range; } function isNullorEmpty(strVal) { return (strVal == null || strVal == '' || strVal == 'null' || strVal == undefined || strVal == 'undefined' || strVal == '- None -'); } role = runtime.getCurrentUser().role; return { execute: invoiceCreation } } );
/** * * Sales Reps Turn Portlet * * @NApiVersion 2.x * @NScriptType Portlet * @author trungpv <trung@lexor.com> */ define(["N/search"], function(search) { function render(params) { var portlet = params.portlet; portlet.title = "Sales Reps Turn"; var html = ""; //try { // html += buildSalesTerritoriesHTMLTable(); html += buildSalesRepsHTMLTable(); // } catch (error) { // html = 'Sorry, something went wrong.'; // } portlet.html = html; } /** * Helper Functions */ /** * Replace all * @param {*} string * @param {*} target * @param {*} replacement */ function replaceAll(string, target, replacement) { return string.split(target).join(replacement); } /** * Convert Name * @param {*} firstname * @param {*} middlename * @param {*} lastname */ function getName(firstname, middlename, lastname) { var name = ""; name += firstname !== "" ? firstname : ""; name += middlename !== "" ? " " + middlename : ""; name += lastname !== "" ? " " + lastname : ""; return name; } /** * Build Sales Territories HTML Table */ function buildSalesTerritoriesHTMLTable() { var html = '<table style="width:100%">'; const header = "<tr><th>TERRITORY</th></tr>"; const rowTemplate = "<tr><td>__TERRITORY__</td></tr>"; html += header; var salesTerritories = search.load({ id: "customsearch699" }); var searchResults = salesTerritories .run() .getRange({ start: 0, end: 10 }); for (var index = 0; index < searchResults.length; index++) { var element = searchResults[index]; var row = rowTemplate; row = replaceAll(row, '__TERRITORY__', element.getValue({ name: 'name' })); html += row; } html += "</table>"; return html; } /** * Build Sales Reps HTML Table */ function buildSalesRepsHTMLTable() { var html = '<table style="width:100%">'; const header = "<tr><th>SALES REP</th><th>EMAIL</th><th>Turn</th></tr>"; const rowTemplate = "<tr><td>__NAME__</td><td>__EMAIL__</td><td>__TURN__</td></tr>"; html += header; var salesReps = search.create({ type: search.Type.EMPLOYEE, filters: [ { name: "salesrep", operator: search.Operator.IS, values: "T" }, { name: "isinactive", operator: search.Operator.IS, values: "F" } ], columns: ["firstname", "middlename", "lastname", "email"] }); var searchResults = salesReps.run().getRange({ start: 0, end: 1000 }); for (var index = 0; index < searchResults.length; index++) { var element = searchResults[index]; var row = rowTemplate; row = replaceAll( row, "__NAME__", getName( element.getValue({ name: "firstname" }), element.getValue({ name: "middlename" }), element.getValue({ name: "lastname" }) ) ); row = replaceAll(row, "__EMAIL__", element.getValue({ name: "email" })); row = replaceAll(row, "__TURN__", index + 1); html += row; } html += "</table>"; return html; } return { render: render }; });
116
[{"tag": "EMAIL", "value": "trung@lexor.com", "start": 101, "end": 116}]
true
1
/** * * Sales Reps Turn Portlet * * @NApiVersion 2.x * @NScriptType Portlet * @author trungpv <kenaa@example.com> */ define(["N/search"], function(search) { function render(params) { var portlet = params.portlet; portlet.title = "Sales Reps Turn"; var html = ""; //try { // html += buildSalesTerritoriesHTMLTable(); html += buildSalesRepsHTMLTable(); // } catch (error) { // html = 'Sorry, something went wrong.'; // } portlet.html = html; } /** * Helper Functions */ /** * Replace all * @param {*} string * @param {*} target * @param {*} replacement */ function replaceAll(string, target, replacement) { return string.split(target).join(replacement); } /** * Convert Name * @param {*} firstname * @param {*} middlename * @param {*} lastname */ function getName(firstname, middlename, lastname) { var name = ""; name += firstname !== "" ? firstname : ""; name += middlename !== "" ? " " + middlename : ""; name += lastname !== "" ? " " + lastname : ""; return name; } /** * Build Sales Territories HTML Table */ function buildSalesTerritoriesHTMLTable() { var html = '<table style="width:100%">'; const header = "<tr><th>TERRITORY</th></tr>"; const rowTemplate = "<tr><td>__TERRITORY__</td></tr>"; html += header; var salesTerritories = search.load({ id: "customsearch699" }); var searchResults = salesTerritories .run() .getRange({ start: 0, end: 10 }); for (var index = 0; index < searchResults.length; index++) { var element = searchResults[index]; var row = rowTemplate; row = replaceAll(row, '__TERRITORY__', element.getValue({ name: 'name' })); html += row; } html += "</table>"; return html; } /** * Build Sales Reps HTML Table */ function buildSalesRepsHTMLTable() { var html = '<table style="width:100%">'; const header = "<tr><th>SALES REP</th><th>EMAIL</th><th>Turn</th></tr>"; const rowTemplate = "<tr><td>__NAME__</td><td>__EMAIL__</td><td>__TURN__</td></tr>"; html += header; var salesReps = search.create({ type: search.Type.EMPLOYEE, filters: [ { name: "salesrep", operator: search.Operator.IS, values: "T" }, { name: "isinactive", operator: search.Operator.IS, values: "F" } ], columns: ["firstname", "middlename", "lastname", "email"] }); var searchResults = salesReps.run().getRange({ start: 0, end: 1000 }); for (var index = 0; index < searchResults.length; index++) { var element = searchResults[index]; var row = rowTemplate; row = replaceAll( row, "__NAME__", getName( element.getValue({ name: "firstname" }), element.getValue({ name: "middlename" }), element.getValue({ name: "lastname" }) ) ); row = replaceAll(row, "__EMAIL__", element.getValue({ name: "email" })); row = replaceAll(row, "__TURN__", index + 1); html += row; } html += "</table>"; return html; } return { render: render }; });
true
/** * * Sales Reps Turn Portlet * * @NApiVersion 2.x * @NScriptType Portlet * @author trungpv <PI:EMAIL:kenaa@example.comEND_PI> */ define(["N/search"], function(search) { function render(params) { var portlet = params.portlet; portlet.title = "Sales Reps Turn"; var html = ""; //try { // html += buildSalesTerritoriesHTMLTable(); html += buildSalesRepsHTMLTable(); // } catch (error) { // html = 'Sorry, something went wrong.'; // } portlet.html = html; } /** * Helper Functions */ /** * Replace all * @param {*} string * @param {*} target * @param {*} replacement */ function replaceAll(string, target, replacement) { return string.split(target).join(replacement); } /** * Convert Name * @param {*} firstname * @param {*} middlename * @param {*} lastname */ function getName(firstname, middlename, lastname) { var name = ""; name += firstname !== "" ? firstname : ""; name += middlename !== "" ? " " + middlename : ""; name += lastname !== "" ? " " + lastname : ""; return name; } /** * Build Sales Territories HTML Table */ function buildSalesTerritoriesHTMLTable() { var html = '<table style="width:100%">'; const header = "<tr><th>TERRITORY</th></tr>"; const rowTemplate = "<tr><td>__TERRITORY__</td></tr>"; html += header; var salesTerritories = search.load({ id: "customsearch699" }); var searchResults = salesTerritories .run() .getRange({ start: 0, end: 10 }); for (var index = 0; index < searchResults.length; index++) { var element = searchResults[index]; var row = rowTemplate; row = replaceAll(row, '__TERRITORY__', element.getValue({ name: 'name' })); html += row; } html += "</table>"; return html; } /** * Build Sales Reps HTML Table */ function buildSalesRepsHTMLTable() { var html = '<table style="width:100%">'; const header = "<tr><th>SALES REP</th><th>EMAIL</th><th>Turn</th></tr>"; const rowTemplate = "<tr><td>__NAME__</td><td>__EMAIL__</td><td>__TURN__</td></tr>"; html += header; var salesReps = search.create({ type: search.Type.EMPLOYEE, filters: [ { name: "salesrep", operator: search.Operator.IS, values: "T" }, { name: "isinactive", operator: search.Operator.IS, values: "F" } ], columns: ["firstname", "middlename", "lastname", "email"] }); var searchResults = salesReps.run().getRange({ start: 0, end: 1000 }); for (var index = 0; index < searchResults.length; index++) { var element = searchResults[index]; var row = rowTemplate; row = replaceAll( row, "__NAME__", getName( element.getValue({ name: "firstname" }), element.getValue({ name: "middlename" }), element.getValue({ name: "lastname" }) ) ); row = replaceAll(row, "__EMAIL__", element.getValue({ name: "email" })); row = replaceAll(row, "__TURN__", index + 1); html += row; } html += "</table>"; return html; } return { render: render }; });
/** * @NApiVersion 2.x * @NScriptType MapReduceScript * @NModuleScope SameAccount */ /** * Script Description * This Map Reduce to create and delete the records * */ /******************************************************************************* * * Support Files * * ***************************************************************************** * * * $Author: Jobin & Jismi IT Services LLP $ * * DESCRIPTION * CSV Import System * ******************************************************************************/ define(['N/record', 'N/file', 'N/email', 'N/runtime', 'N/search', 'N/email', 'N/encode', 'N/task', 'N/format'], function (record, file, email, runtime, search, email, encode, task, format) { var main = { /*Get inputData for Processing */ getInputData: function (context) { //log.debug('context', context) var processfolderid = runtime.getCurrentScript().getParameter("custscript_json_fileid"); main.sleep(40000); var mapinternal = main.findprocessfiles(processfolderid, false); var contextfile = file.load({ id: mapinternal }); var contextContent = contextfile.getContents(); var contextContent = JSON.parse(contextContent); //log.debug('contextContent', contextContent) var contextobj = JSON.parse(contextContent) var operation = contextobj.contextdetails.operation; var recordtype = contextobj.contextdetails.recordtype; if (operation == "create" || operation == "update") { // log.debug('enter create') var processFilles = main.findprocessfiles(processfolderid, true); //log.debug("processFilles", processFilles); var fileContent = main.setupProccessfiles(processFilles); } else if (operation == "delete") { //log.debug("contextobj.contextdetails.deletedetail", contextobj.deletedetail) var fileContent = main.searchRecord(contextobj.contextdetails.recordtype, contextobj.deletedetail); } else if (operation == "deleteduplicate") { // log.debug("contextobj.contextdetails.deletedetail", contextobj.deletedetail) // log.debug("contextobj.contextdetails.recordtype", contextobj.contextdetails.recordtype) var fileContent = main.searchDuplicateRecord(contextobj.contextdetails.recordtype, contextobj.deletedetail); } try { // log.debug("fileContent", fileContent.length); } catch (e) { log.debug('error', e) } //log.debug("fileContent", fileContent) return fileContent; }, sleep: function (milliseconds) { var date = Date.now(); var currentDate = null; do { currentDate = Date.now(); } while (currentDate - date < milliseconds); }, /*Concatnate the Arrays from Chunks Folder */ setupProccessfiles: function (filefolder) { var len = filefolder.length; var array = []; for (var i = 0; i < len; i++) { if (filefolder[i].name != "scriptcontext.txt") { var processFile = file.load({ id: filefolder[i].internalid }); var fileContent = processFile.getContents(); var temparray = JSON.parse(fileContent); array.push(temparray); } } var fullarray = [].concat.apply([], array); return fullarray; }, /*If the process is delete duplicates, then use the ESN number to find the internalid*/ searchDuplicateRecord: function (recordtype, date) { //log.debug('date', date); var filterarry = [] if (date == "all") { } else { filterarry.push(["created", "within", date]) } var SearchObj = search.create({ type: recordtype, columns: [ search.createColumn({ name: "custrecord_jj_esn", label: "ESN" }), search.createColumn({ name: "internalid", label: "Internal ID" }) ], filters: filterarry }); var searchPageRanges = SearchObj.runPaged({ pageSize: 1000 }); var internalids = []; var esnNum = { }; for (var i = 0; i < searchPageRanges.pageRanges.length; i++) { searchPageRanges.fetch({ index: i }).data.forEach(function (result) { var esn_number = result.getValue("custrecord_jj_esn"); var internal_id = result.getValue("internalid"); try { esnNum[esn_number].push(internal_id); } catch (e) { esnNum[esn_number] = [] esnNum[esn_number].push(internal_id); } return true; }); } Object.keys(esnNum).forEach(function (key) { for (var i = 0; i < esnNum[key].length; i++) { if (esnNum[key][i + 1]) { internalids.push(esnNum[key][i + 1]) } } }); // log.debug('internalids', internalids) // log.debug("esnNum", esnNum); // log.debug("duplciatearray length", internalids.length); return internalids; }, /*If Process is Delete then get the internalids */ searchRecord: function (recordtype, date) { var filterarry = [] if (date == "all") { } else { filterarry.push(["created", "within", date]) } // log.debug("date", date); var SearchObj = search.create({ type: recordtype, columns: [ search.createColumn({ name: "internalid", label: "Internal ID" }) ], filters: filterarry }); var searchPageRanges = SearchObj.runPaged({ pageSize: 1000 }); var internalids = []; for (var i = 0; i < searchPageRanges.pageRanges.length; i++) { searchPageRanges.fetch({ index: i }).data.forEach(function (result) { internalids.push(result.getValue("internalid")); return true; }); } //log.debug("deletearray length", internalids.length); return internalids; }, /*Find JSON chunks From the Folder For Processing */ findprocessfiles: function (folderid, flag) { var fileSearchObj = search.create({ type: "file", filters: [ ["folder", "anyof", folderid] ], columns: [ search.createColumn({ name: "internalid", label: "Internal ID" }), search.createColumn({ name: "name", sort: search.Sort.ASC, label: "Name" }) ] }); var searchResultCount = fileSearchObj.runPaged().count; if (flag == true) { var processarray = []; fileSearchObj.run().each(function (result) { var tempobj = { }; tempobj.internalid = result.getValue("internalid"); tempobj.name = result.getValue("name"); processarray.push(tempobj); return true; }); return processarray; } else { var mapinternal; fileSearchObj.run().each(function (result) { if (result.getValue("name") == "scriptcontext.txt") { mapinternal = result.getValue("internalid"); } return true; }); return mapinternal; } }, /*Reduce Function of map Reduce */ reduce: function (context) { var processfolderid = runtime.getCurrentScript().getParameter("custscript_json_fileid"); var mapinternal = main.findprocessfiles(processfolderid, false); //log.debug('mapinternal',mapinternal) var contextfile = file.load({ id: mapinternal }); var contextContent = contextfile.getContents(); // log.debug("contextContent", contextContent) var contextContent = JSON.parse(contextContent); var contextobj = JSON.parse(contextContent) var operation = contextobj.contextdetails.operation; var recordtype = contextobj.contextdetails.recordtype; var recordname = contextobj.contextdetails.recordname; var mapobj = contextobj.mapobj; //log.debug("mapobj", mapobj) var currentobj = context.values; // log.debug("currentobj", currentobj) var convertedfile = JSON.parse(currentobj[0]); if (convertedfile.length == 1) { //1 if the input file is CSV one. convertedfile = convertedfile[0].split(',') } // log.debug("convertedfile", convertedfile) // log.debug('recordname', recordname) if (operation == "create") { if (recordname != "Spiff Amount") { if (recordname != "Residual Monthly") { var intrId; if (recordtype == "customrecord_jj_tracfone_activations") { var tracfone_record = true; var simno_tracfone = convertedfile[mapobj['custrecordjj_tra_sim']] // log.debug('simno_tracfone', simno_tracfone) var customrecord_jj_tracfone_activationsSearchObj = search.create({ type: "customrecord_jj_tracfone_activations", filters: [ ["custrecordjj_tra_sim", "is", simno_tracfone] ], columns: [ search.createColumn({ name: "internalid", label: "Internal ID" }) ] }); var searchResult = customrecord_jj_tracfone_activationsSearchObj.run().getRange({ start: 0, end: 1 }); for (var j = 0; j < searchResult.length; j++) { intrId = searchResult[j].getValue({ name: "internalid" }); } } // log.debug('tracfone_record', tracfone_record) // log.debug('intrId', intrId) if (intrId && tracfone_record) { //log.debug('duplicate record') } else { main.createrecord(recordtype, mapobj, convertedfile, processfolderid); } } else { //log.debug("testing loop residual amount") } } else { //log.debug("testing loop spiff amount") } } else if (operation == "delete") { // log.debug("convertedfile", convertedfile); main.deleteRecord(recordtype, convertedfile); } else if (operation == "deleteduplicate") { // log.debug("convertedfile duplicate", convertedfile); main.deleteRecord(recordtype, convertedfile); } else if (operation == "update") { var intrId; if (recordtype == "customrecord_jj_tracfone_activations") { var tracfone_record = true; var simno_tracfone = convertedfile[mapobj['custrecordjj_tra_sim']] var customrecord_jj_tracfone_activationsSearchObj = search.create({ type: "customrecord_jj_tracfone_activations", filters: [ ["custrecordjj_tra_sim", "is", simno_tracfone] ], columns: [ search.createColumn({ name: "internalid", label: "Internal ID" }) ] }); var searchResult = customrecord_jj_tracfone_activationsSearchObj.run().getRange({ start: 0, end: 1 }); for (var j = 0; j < searchResult.length; j++) { intrId = searchResult[j].getValue({ name: "internalid" }); } if (searchResult.length <= 0) { convertedfile.push("SIM Number is not present"); var folderid; var init = main.checkforfolder(processfolderid); if (init == true) { folderid = main.createfolder(processfolderid); } else { folderid = init; } main.errorlog(processfolderid, convertedfile, folderid); // log.debug("duplicate ESN ", esnno) return true; } } if (intrId && tracfone_record) { // log.debug('simno_tracfone : ' + simno_tracfone, 'intrId: ' + intrId); main.updateRecord(recordtype, mapobj, convertedfile, processfolderid, intrId, recordname); } } }, /*To Find Error Files */ finderrorfiles: function (errorfolderid) { // log.debug("errorfolderid", errorfolderid) var fileSearchObj = search.create({ type: "folder", filters: [ ["name", "is", errorfolderid] ], columns: [ search.createColumn({ name: "internalid", label: "Internal ID" }), search.createColumn({ name: "name", sort: search.Sort.ASC, label: "Name" }) ] }); var resultSet = fileSearchObj.run(); var firstResult = resultSet.getRange({ start: 0, end: 1 })[0]; // log.debug('firstResult',firstResult) var value = firstResult.getValue(resultSet.columns[0]); var fileError = search.create({ type: "file", filters: [ ["folder", "anyof", value] ], columns: [ search.createColumn({ name: "internalid", label: "Internal ID" }), search.createColumn({ name: "name", sort: search.Sort.ASC, label: "Name" }) ] }) var processarray = []; fileError.run().each(function (result) { var tempobj = { }; tempobj.internalid = result.getValue("internalid"); tempobj.name = result.getValue("name"); processarray.push(tempobj); return true; }); var len = processarray.length; var array = []; for (var i = 0; i < len; i++) { if (processarray[i].name != "scriptcontext.txt") { var processFile = file.load({ id: processarray[i].internalid }); var fileContent = processFile.getContents(); array.push(fileContent); } } // var fullarray = [].concat.apply([], array); return array; }, /*Error Folder For Logging and send Email*/ createfolder: function (data) { var folderRec = record.create({ type: record.Type.FOLDER, isDynamic: true }); folderRec.setValue({ fieldId: 'parent', value: 10189 }); folderRec.setValue({ fieldId: 'name', value: data }); var folderId = folderRec.save({ enableSourcing: true, ignoreMandatoryFields: true }); return folderId; }, /*To check whether there is any folder existing for error log*/ checkforfolder: function (name) { var folderSearchObj = search.create({ type: "folder", filters: [ ["name", "is", name] ], columns: [ search.createColumn({ name: "internalid", label: "internalid" }) ] }); var searchResultCount = folderSearchObj.runPaged().count; if (searchResultCount < 1) { return true } else { var internalid; folderSearchObj.run().each(function (result) { internalid = result.getValue("internalid"); return true; }); return internalid; } }, /* Create the error file in the error error log */ createfile: function (name, folderid, convertedfile) { var folderinternal; if (folderid > 0) { folderinternal = folderid; } else { folderinternal = 10189 } var fileObj = file.create({ name: name + '.txt', fileType: file.Type.PLAINTEXT, contents: convertedfile.toString(), folder: folderinternal, isOnline: true }); var fileid = fileObj.save(); return fileid; }, /*Delete Process Actions */ deleteRecord: function (type, internalid) { record.delete({ type: type, id: internalid }); }, /*Update record actions Process */ updateRecord: function (recordtype, mapobj, convertedfile, processfolderid, intrId, recordname) { if (recordtype == "customrecord_jj_tracfone_activations") { if (recordname != "Spiff Amount") { if (recordname != "Residual Monthly") { var value_xl = convertedfile[mapobj['custrecord_jj_plan']] //log.debug('convertedfile[mapobj[custrecord_ao_spiff_paid_date]]', convertedfile[mapobj['custrecord_ao_spiff_paid_date']]) var activationMonth_xl = main.doValidations(convertedfile[mapobj['custrecord_ao_spiff_paid_date']], recordtype) // log.debug('activationMonth_xl', activationMonth_xl) if (activationMonth_xl) { var formattedDateString = activationMonth_xl } var commission = convertedfile[mapobj['custrecord_ao_last_resid_amount']] var usedDate = convertedfile[mapobj['custrecord_ao_last_paid_resid']] if (usedDate) { var formattedDateStringResidue = main.doValidations(usedDate, recordtype) } var cust_load = record.load({ type: 'customrecord_jj_tracfone_activations', id: intrId /*, isDynamic: true */ }); cust_load.setValue({ fieldId: "custrecord_jj_plan", value: value_xl }); if (activationMonth_xl) { cust_load.setValue({ fieldId: "custrecord_ao_spiff_paid_amouunt", value: commission }); cust_load.setText({ fieldId: "custrecord_ao_spiff_paid_date", text: formattedDateString }); } if (usedDate) { cust_load.setValue({ fieldId: "custrecord_ao_last_resid_amount", value: commission }); cust_load.setText({ fieldId: "custrecord_ao_last_paid_resid", text: formattedDateStringResidue }); } var id = cust_load.save({ enableSourcing: true }); log.debug("Record updated ", id); } else { //log.debug('enter resid loop') var objRecord = record.load({ type: 'customrecord_jj_tracfone_activations', id: intrId }); for (var key in mapobj) { if (key != "-") { var currentValue = main.doValidations(convertedfile[mapobj[key]], recordtype); // log.debug('currentValue', currentValue) if (currentValue.indexOf("$") > -1) { var temp = currentValue.split('$') currentValue = temp[1] } // log.debug('Updated currentValue', currentValue) try { //log.debug('enter try key', key) objRecord.setText({ fieldId: key, text: currentValue.toString().trim() }); var simEarning = objRecord.getValue({ fieldId: 'custrecord23' }) if (key == 'custrecord_ao_last_resid_amount') { simEarning = simEarning + Number(currentValue) objRecord.setValue({ fieldId: 'custrecord23', value: simEarning.toString().trim() }); } } catch (e) { try { objRecord.setValue({ fieldId: key, value: currentValue.toString().trim() }); } catch (error) { // log.debug("Error for creating record", error.message) convertedfile.push(error.message); // log.debug("Econvertedfile", convertedfile) var folderid; var init = main.checkforfolder(processfolderid); if (init == true) { folderid = main.createfolder(processfolderid); } else { folderid = init; } main.errorlog(processfolderid, convertedfile); return error; } } } } var id = objRecord.save({ enableSourcing: false }); log.debug("Record updated ", id); } } else { log.debug('testing update another') var objRecord = record.load({ type: 'customrecord_jj_tracfone_activations', id: intrId /*, isDynamic: true */ }); for (var key in mapobj) { if (key != "-") { var currentValue = main.doValidations(convertedfile[mapobj[key]], recordtype); log.debug('currentValue', currentValue) if (currentValue.indexOf("$") > -1) { var temp = currentValue.split('$') currentValue = temp[1] } log.debug('Updated currentValue', currentValue) /*var currentDate = main.doValidations(convertedfile[mapobj['custrecord_ao_spiff_paid_date']], recordtype);*/ try { log.debug('enter try key', key) /*objRecord.setValue({ fieldId: 'custrecord_ao_spiff_paid_amouunt', value: currentValue.toString().trim() }); objRecord.setText({ fieldId: 'custrecord_ao_spiff_paid_date', text: currentDate });*/ objRecord.setText({ fieldId: key, text: currentValue.toString().trim() }); } catch (e) { try { objRecord.setValue({ fieldId: key, value: currentValue.toString().trim() }); } catch (error) { // log.debug("Error for creating record", error.message) convertedfile.push(error.message); // log.debug("Econvertedfile", convertedfile) var folderid; var init = main.checkforfolder(processfolderid); if (init == true) { folderid = main.createfolder(processfolderid); } else { folderid = init; } main.errorlog(processfolderid, convertedfile); return error; } /* }*/ } } } var id = objRecord.save({ enableSourcing: false }); log.debug("Record updated ", id); } } }, /*Create record actions Process */ createrecord: function (recordtype, mapobj, convertedfile, processfolderid) { log.debug("enter create fun") log.debug("mapobj", mapobj) var duplicate = false; if (convertedfile.length > 0) { var objRecord = record.create({ type: recordtype, isDynamic: true }); for (var key in mapobj) { if (key != "-") { log.debug('key', key) log.debug('convertedfile[mapobj[key]]', convertedfile[mapobj[key]]) var currentValue = main.doValidations(convertedfile[mapobj[key]], recordtype); try { objRecord.setValue({ fieldId: key, value: currentValue.toString().trim() }); } catch (e) { try { objRecord.setText({ fieldId: key, text: currentValue.toString().trim() }); } catch (error) { // log.debug("Error for creating record", error.message) convertedfile.push(error.message); // log.debug("Econvertedfile", convertedfile) var folderid; var init = main.checkforfolder(processfolderid); if (init == true) { folderid = main.createfolder(processfolderid); } else { folderid = init; } main.errorlog(processfolderid, convertedfile); return error; } } } }; log.debug('testing record type', recordtype) if (recordtype == "customrecord_jj_branded_handset") { var simno = convertedfile[mapobj['custrecord_jj_sim']] var esnno = convertedfile[mapobj['custrecord_jj_esn']] duplicate = main.checksim(simno, esnno, processfolderid, convertedfile); var tectraId = objRecord.getValue({ fieldId: 'custrecord_jj_branded_tcetraid' }); var customerDetails = main.findCustomerdetails(tectraId, "custentity1"); objRecord.setValue({ fieldId: "custrecord_jj_customer", value: customerDetails.customerId }); objRecord.setValue({ fieldId: "custrecord_jj_sales_rep", value: customerDetails.salesreppartner }); objRecord.setValue({ fieldId: "custrecord_jj_subof_sales_partner", value: customerDetails.subof }); } else if (recordtype == "customrecord_jj_route_run") { var tectraId = objRecord.getValue({ fieldId: 'custrecord_jj_tcetraid' }); var customerDetails = main.findCustomerdetails(tectraId, "custentity1"); objRecord.setValue({ fieldId: "custrecord_jj_customerid", value: customerDetails.customerId }); objRecord.setValue({ fieldId: "custrecord_jj_sales_rep_route", value: customerDetails.salesreppartner }); objRecord.setValue({ fieldId: "custrecord_jj_subof_route", value: customerDetails.subof }); } else if (recordtype == "customrecord_jj_qpay_marketplace_details") { var incommId = objRecord.getValue({ fieldId: 'custrecord_jj_branchid' }); var customerDetails = main.findCustomerdetails(incommId, "custentityincomeexclusiveid"); objRecord.setValue({ fieldId: "custrecord_qpay_customerid", value: customerDetails.customerId }); objRecord.setValue({ fieldId: "custrecord_jj_sales_rep_maeket", value: customerDetails.salesreppartner }); objRecord.setValue({ fieldId: "custrecord_jj_subof_market", value: customerDetails.subof }); } else if (recordtype == "customrecord_jj_qpaydetail_transaction") { /*as per discusions on 07-07 parent id and parent name need not to be set*/ var incommId = objRecord.getValue({ fieldId: 'custrecord_jj_qpaydetail_incommid' }); var parentId = objRecord.getValue({ fieldId: 'custrecord_jj_details_parentid' }); //getting the parent name var parentName = objRecord.getValue({ fieldId: 'custrecord_jj_qpaydetail_parent_nm' }); var customerDetails = main.findCustomerdetails(incommId, "custentityincomeexclusiveid"); objRecord.setValue({ fieldId: "custrecord_jj_qpaydetail_custid", value: customerDetails.customerId }); objRecord.setValue({ fieldId: "custrecord_jj_sales_rep_qpay", value: customerDetails.salesreppartner }); objRecord.setValue({ fieldId: "custrecord_jj_subof_salesrep", value: customerDetails.subof }); // set the parent id id in the customer record /* var parId = record.submitFields({ type: record.Type.CUSTOMER, id: customerDetails.customerId, values: { custentity_jj_parentaccountid: parentId, custentity_jj_parentname: parentName } });*/ } else if (recordtype == "customrecord223") { var tectraId = objRecord.getValue({ fieldId: 'custrecord6' }); var customerDetails = main.findCustomerdetails(tectraId, "custentity1"); // log.debug(tectraId, customerDetails); objRecord.setValue({ fieldId: "custrecord_jj_customer_vidapay", value: customerDetails.customerId }); objRecord.setValue({ fieldId: "custrecord_jj_salesrep_vidapay", value: customerDetails.salesreppartner }); objRecord.setValue({ fieldId: "custrecord_jj_subof_vidapay", value: customerDetails.subof }); } else if (recordtype == "customrecord_jj_tracfone_activations") { log.debug('recordtype checksim', recordtype) var tectraId = objRecord.getValue({ fieldId: 'custrecord_jj_trc_tsp_id' }); var partnetID = objRecord.getValue({ fieldId:"custrecord_jj_tra_partner_id" }) log.debug("partnetID",partnetID) if(partnetID == "IAS"){ var searchField = "custentityincomeexclusiveid" }else{ var searchField = "custentity1" } log.debug("searchField",searchField) log.debug("tectraId",tectraId) var customerDetails = main.findCustomerdetails(tectraId, searchField); log.debug("customerDetails",customerDetails) objRecord.setValue({ fieldId: "custrecord_jj_tracfone_activa_cusid", value: customerDetails.customerId }); objRecord.setValue({ fieldId: "custrecord_jj_sales_rep_tracfone", value: customerDetails.salesreppartner }); /* objRecord.setValue({ fieldId: "custrecord_jj_subof_sales_partner", value: customerDetails.subof });*/ } else if (recordtype == "customrecord_jj_marketplace_sales_order") { /* MTW-252 This else if part is done for the record creation for the marketplace integration*/ var simNumber = convertedfile[7]; duplicate = main.detectDuplicateSim(recordtype, simNumber); log.debug("duplicate", duplicate) if (duplicate != false) { log.debug("reach leve2") main.updateMarketPlaceRec(convertedfile, duplicate, recordtype) } else { log.debug("reach level") log.debug("convertedfile[0]: ",convertedfile[0]) // var convertedDate = main.dateValidation(JSON.stringify(convertedfile[0])) // log.debug("convertedDate: ",convertedDate) // var orderedDate = format.format({ // value: convertedDate, // type:format.Type.DATE // }) // log.debug("orderedDate: ",orderedDate) objRecord.setText({ fieldId: "custrecord_jj_date_ordered", text: convertedfile[0] }); objRecord.setValue({ fieldId: "custrecord_jj_order", value: convertedfile[1] }); objRecord.setValue({ fieldId: "custrecord_jj_product_id", value: convertedfile[2] }); objRecord.setValue({ fieldId: "custrecord_jj_marketplace_product_name", value: convertedfile[3] }); objRecord.setValue({ fieldId: "custrecord_jj_marketplace_dealer_cost", value: convertedfile[7] }); objRecord.setValue({ fieldId: "custrecord_jj_current_parent_commission", value: convertedfile[8] }); objRecord.setValue({ fieldId: "custrecord_jj_sum_of_sub_parent_commissi", value: convertedfile[9] }); objRecord.setValue({ fieldId: "custrecord_jj_marketplace_sim_esn", value: convertedfile[12] }); objRecord.setValue({ fieldId: "custrecord_jj_part_number", value: convertedfile[13] }); log.debug("convertedfile[15]", convertedfile[13]) objRecord.setValue({ fieldId: "custrecord_jj_merchant_account_id", value: convertedfile[20] }); var customerDetails = main.findCustomerdetails(convertedfile[20], "custentity1"); log.debug("customerDetails", customerDetails) objRecord.setValue({ fieldId: "custrecord_jj_merchant_name", value: customerDetails.customerId }); log.debug("convertedfile[24]", convertedfile[29]) objRecord.setText({ fieldId: "custrecord_jj_marketplace_date_shipped", text: convertedfile[29]//new Date(main.dateValidation(convertedfile[22])) }); objRecord.setValue({ fieldId: "custrecord_jj_marketplace_tracking_numbe", value: convertedfile[30] }); log.debug("convertedfile[10]", convertedfile[16]) objRecord.setValue({ fieldId: "custrecord_jj_marketplace_active_status", value: convertedfile[16] }); } } else if (recordtype == "customrecord_mw_tracfone_residual_month") { var sim = objRecord.getValue({ fieldId: 'custrecord_jj_trc_mnthly_sim' }); // log.debug("sim", sim) try { var activationsSearchObj = search.create({ type: 'customrecord_jj_tracfone_activations', columns: [{ name: "custrecord_jj_tracfone_activa_cusid" }, { name: 'custrecord_jj_sales_rep_tracfone' }, { name: 'custrecord_jj_city' }, { name: 'custrecord_jj_state' }], filters: ["custrecordjj_tra_sim", "is", sim] }); var activationsResultCount = activationsSearchObj.runPaged().count; if (activationsResultCount == 1) { //then there will be 1 sim in tracfone activation record var searchResult = activationsSearchObj.run().getRange({ start: 0, end: 1 }); // log.debug("searchResult", searchResult); var custID = searchResult[0].getValue({ name: 'custrecord_jj_tracfone_activa_cusid' }); // log.debug("custID from Tracfone", custID); if (custID != '') { var searchResultForCustomer = main.searchForCustomer(custID); objRecord.setValue({ fieldId: "custrecord_mw_tracfone_customer", value: custID }); } // log.debug("searchResultForCustomer", searchResultForCustomer); var salesRepTrcMnthly = searchResult[0].getText({ name: 'custrecord_jj_sales_rep_tracfone' }); var cityTrcMnthly = searchResult[0].getValue({ name: 'custrecord_jj_city' }); var stateTrcMnthly = searchResult[0].getValue({ name: 'custrecord_jj_state' }); } objRecord.setValue({ fieldId: "custrecord_jj_sales_name", value: salesRepTrcMnthly }); objRecord.setValue({ fieldId: "custrecord_jj_trc_mnthly_city", value: cityTrcMnthly }); objRecord.setValue({ fieldId: "custrecord_jj_trc_mnthly_state", value: stateTrcMnthly }); objRecord.setValue({ fieldId: "custrecord_jj_parent_name", value: searchResultForCustomer.parentName }); objRecord.setValue({ fieldId: "custrecord_jj_parent_id", value: searchResultForCustomer.parentID }); objRecord.setValue({ fieldId: "custrecord_incomm_id", value: searchResultForCustomer.incommId }); objRecord.setValue({ fieldId: "custrecordcustrecord_tcetra_id", value: searchResultForCustomer.tectraId }); } catch (e) { log.debug("e", e); } } } if (duplicate == false || duplicate == null) { var id = objRecord.save({ enableSourcing: true }); log.debug("Record Created ", id); } else { log.debug("duplicate ", duplicate); } }, /* MTW-252 The function for check duplicate sim number */ detectDuplicateSim: function (recordtype, simNumber) { var customrecord_jj_marketplace_sales_orderSearchObj = search.create({ type: recordtype, filters: [ ["custrecord_jj_marketplace_sim_esn", "is", simNumber] ], columns: [ search.createColumn({ name: "internalid", label: "Internal ID" }) ] }); var searchResultCount = customrecord_jj_marketplace_sales_orderSearchObj.runPaged().count; var recordIdVal = null; if (searchResultCount > 0) { customrecord_jj_marketplace_sales_orderSearchObj.run().each(function (result) { recordIdVal = result.getValue({ name: "internalid", label: "Internal ID" }) return false; }); return recordIdVal; } else { return false; } }, /* MTW-252 The function for update marketplace record */ updateMarketPlaceRec: function (convertedfile, marketPlaceDuplicate, recordtype) { var updateRecord = record.load({ type: recordtype, id: marketPlaceDuplicate, isDynamic: true }); updateRecord.setText({ fieldId: "custrecord_jj_date_ordered", text: convertedfile[0]//new Date(main.dateValidation(convertedfile[0])) }); updateRecord.setValue({ fieldId: "custrecord_jj_order", value: convertedfile[1] }); updateRecord.setValue({ fieldId: "custrecord_jj_product_id", value: convertedfile[2] }); updateRecord.setValue({ fieldId: "custrecord_jj_marketplace_product_name", value: convertedfile[3] }); updateRecord.setValue({ fieldId: "custrecord_jj_marketplace_dealer_cost", value: convertedfile[7] }); updateRecord.setValue({ fieldId: "custrecord_jj_current_parent_commission", value: convertedfile[8] }); updateRecord.setValue({ fieldId: "custrecord_jj_sum_of_sub_parent_commissi", value: convertedfile[9] }); updateRecord.setValue({ fieldId: "custrecord_jj_marketplace_sim_esn", value: convertedfile[12] }); updateRecord.setValue({ fieldId: "custrecord_jj_part_number", value: convertedfile[13] }); updateRecord.setValue({ fieldId: "custrecord_jj_merchant_account_id", value: convertedfile[14] }); var customerDetails = main.findCustomerdetails(convertedfile[14], "custentity1"); log.debug("customerDetails", customerDetails) updateRecord.setValue({ fieldId: "custrecord_jj_merchant_name", value: customerDetails.customerId }); updateRecord.setText({ fieldId: "custrecord_jj_marketplace_date_shipped", text: convertedfile[29]//new Date(main.dateValidation(convertedfile[22])) }); updateRecord.setValue({ fieldId: "custrecord_jj_marketplace_tracking_numbe", value: convertedfile[30] }); updateRecord.setValue({ fieldId: "custrecord_jj_marketplace_active_status", value: convertedfile[16] }); var recid = updateRecord.save({ enableSourcing: true }); log.debug("Record updated ", id); }, /* MTW-252 The function for validating date field for date field setvalue maketplace integration */ dateValidation: function (datevalue) { var dd = new Date(datevalue).getDate() var mm = new Date(datevalue).getMonth() var yy = new Date(datevalue).getFullYear() var datestrVal = dd + '/' + mm + '/' + yy; log.debug("datestrVal: ",datestrVal) return datestrVal; }, /* create a search in customer record to find the corresponding customer according to the tcetra id*/ /*Route Run and Branded Handset*/ findCustomerdetails: function (tectraId, searchField) { var customerSearchObj = search.create({ type: "customer", filters: [ [searchField, "contains", tectraId], "AND", ["subsidiary", "anyof", "2"] ], columns: [searchField, "internalid"] }); var searchResultCount = customerSearchObj.runPaged().count; log.debug("searchResultCount",searchResultCount) if (searchResultCount <= 0) { customerSearchObj = search.create({ type: "customer", filters: [ [searchField, "contains", tectraId] ], columns: [searchField, "internalid"] }); searchResultCount = customerSearchObj.runPaged().count; // log.debug("searchResultCount insidfa", searchResultCount); } // var searchResultCount = customerSearchObj.runPaged().count; var returnObj = { }; customerSearchObj.run().each(function (result) { // get the customer id returnObj.customerId = result.getValue('internalid'); // To get the sales rep partner id from the customer record var lookupfieldofpartner = search.lookupFields({ type: 'customer', id: returnObj.customerId, columns: ['partner'] }); if (lookupfieldofpartner.partner[0]) { returnObj.salesreppartner = lookupfieldofpartner.partner[0].value; } // to get parent id from partner record var lookupfieldofsub = search.lookupFields({ type: 'partner', id: returnObj.salesreppartner, columns: ['parent'] }); if (lookupfieldofsub.parent[0]) { returnObj.subof = lookupfieldofsub.parent[0].value; } }); return returnObj; }, checksim: function (simno, esnno, processfolderid, convertedfile) { var branded_handset_search_sim = search.create({ type: "customrecord_jj_branded_handset", filters: [ ["custrecord_jj_sim", "is", simno] ], columns: [ search.createColumn({ name: "id", sort: search.Sort.ASC, label: "ID" }), search.createColumn({ name: "custrecord_jj_customer", label: "Customer" }), search.createColumn({ name: "custrecord_jj_sim", label: "SIM" }), search.createColumn({ name: "custrecord_jj_esn", label: "ESN" }), search.createColumn({ name: "custrecord_jj_branded_tcetraid", label: "Tcetra Id" }) ] }); var searchResultCountSim = branded_handset_search_sim.runPaged().count; // log.debug("Brandend Handset Sim Search Count", searchResultCountSim); if (searchResultCountSim > 0) { convertedfile.push("Duplicate Sim Number"); var folderid; var init = main.checkforfolder(processfolderid); if (init == true) { folderid = main.createfolder(processfolderid); } else { folderid = init; } main.errorlog(processfolderid, convertedfile); // log.debug("duplicate SIM ", simno) return true; } else { var branded_handset_search_esn = search.create({ type: "customrecord_jj_branded_handset", filters: [ ["custrecord_jj_esn", "is", esnno] ], columns: [ // search.createColumn({ // name: "id", // sort: search.Sort.ASC, // label: "ID" // }), search.createColumn({ name: "custrecord_jj_customer", label: "Customer" }), search.createColumn({ name: "custrecord_jj_sim", label: "SIM" }), search.createColumn({ name: "custrecord_jj_esn", label: "ESN" }), search.createColumn({ name: "custrecord_jj_branded_tcetraid", label: "Tcetra Id" }) ] }); var searchResultCountESN = branded_handset_search_esn.runPaged().count; // log.debug("Brandend Handset ESN Search Count", searchResultCountESN); // customrecord_jj_branded_handsetSearchObj.run().each(function(result){ // // .run().each has a limit of 4,000 results // return true; // }); if (searchResultCountESN > 0) { convertedfile.push("Duplicate ESN Number"); var folderid; var init = main.checkforfolder(processfolderid); if (init == true) { folderid = main.createfolder(processfolderid); } else { folderid = init; } main.errorlog(processfolderid, convertedfile); // log.debug("duplicate ESN ", esnno) return true; } } return false }, searchForCustomer: function (custID) { var obj = { }; var customerSearchObj = search.create({ type: "customer", filters: [ ["internalidnumber", "equalto", custID] ], columns: [{ name: "custentity_jj_parentname" }, { name: "custentity_jj_parentaccountid" }, { name: "custentity1" }, { name: "custentityincomeexclusiveid" }] }); var searchResultCount = customerSearchObj.runPaged().count; if (searchResultCount > 0) { var searchResult1 = customerSearchObj.run().getRange({ start: 0, end: 1 }); // log.debug("searchResult1",searchResult1); obj.parentName = searchResult1[0].getValue({ name: 'custentity_jj_parentname' }); // log.debug("parentName",obj.parentName); obj.parentID = searchResult1[0].getValue({ name: 'custentity_jj_parentaccountid' }); obj.incommId = searchResult1[0].getValue({ name: 'custentityincomeexclusiveid' }); obj.tectraId = searchResult1[0].getValue({ name: 'custentity1' }); // log.debug("parentID",obj.parentID); } // log.debug("obj",obj); return obj; }, /*Delete JSON chunks Folder after the Import Process */ folderdelete: function (mapinternal) { var processfolderid = runtime.getCurrentScript().getParameter("custscript_json_fileid"); var processarray = main.findprocessfiles(processfolderid, true); for (i = 0; i < processarray.length; i++) { file.delete({ id: processarray[i].internalid }); } file.delete({ id: mapinternal }); var folderdelete = record.delete({ type: "folder", id: processfolderid }); }, /*To create an folder that contain all the errors */ errorlog: function (processfolderid, convertedfile, folderid) { var filename = Date.now(); // var folderid; // var init = main.checkforfolder(processfolderid); // if (init == true) { // folderid = main.createfolder(processfolderid); // } else { // folderid = init; // // } var processfileid = main.createfile(filename, folderid, convertedfile); }, /*Check whether the input string is Date or number or String */ /*if date format is mm/dd/yyy*/ doValidations: function (string, recordtype) { /*check whether inputed data is date*/ //log.debug("string date in dovalidation", string); var inputString = main.isDate(string); //log.debug("inputString", inputString) if (inputString == false) { if (isNaN(string)) { return string; } else { if (string == null || string == "") { return ""; } else { return Number(string); } } } else { if (recordtype == "customrecord_mw_tracfone_residual_month") { if (string.indexOf("-") > 0) { var dateArray = string.split("-"); var datestr = dateArray[1] + '/' + dateArray[0] + '/' + dateArray[2]; // log.debug("date last of do validation", datestr); return datestr; } else { return string } } else if (recordtype == "customrecord_jj_tracfone_activations") { if (string.indexOf("-") > 0) { var dateArray = string.split("-"); var datestr = dateArray[1] + '/' + dateArray[0] + '/' + dateArray[2]; // log.debug("date last of do validation", datestr); return datestr; } else { return string } } var string = string.replace(/-/g, "/"); if (new Date(string.toString()) == "Invalid Date") { return string; } else { var today = new Date(string); // log.debug("today", today) var dd = today.getDate(); var mm = today.getMonth() + 1; var yyyy = today.getFullYear(); if (yyyy < 2000) yyyy = yyyy + 100; // if (mm < 10) { // mm = mm; // } var datestr = mm + '/' + dd + '/' + yyyy; // log.debug("date last of do validation", datestr) return datestr; } } }, /*To find whether the input string is date or not */ isDate: function (value) { var dateFormat; if (toString.call(value) === '[object Date]') { return true; } if (typeof value.replace === 'function') { value.replace(/^\s+|\s+$/gm, ''); } dateFormat = /(^\d{1,4}[\.|\\/|-]\d{1,2}[\.|\\/|-]\d{1,4})?$/; return dateFormat.test(value); }, /*Summary function Of map reduce */ summarize: function (summary) { var errorfolderid = runtime.getCurrentScript().getParameter("custscript_json_fileid"); var errorfolder = main.finderrorfiles(errorfolderid); var processfolderid = runtime.getCurrentScript().getParameter("custscript_json_fileid"); var mapinternal = main.findprocessfiles(processfolderid, false); var contextfile = file.load({ id: mapinternal }); var contextContent = contextfile.getContents(); var contextContent = JSON.parse(contextContent); var contextobj = JSON.parse(contextContent); var operation = contextobj.contextdetails.operation; var emailaddr = contextobj.emailaddress; var recordtype = contextobj.contextdetails.recordtype; var recordname = contextobj.contextdetails.recordname; if (operation == "create") { if (errorfolder == null || errorfolder == "" || errorfolder == undefined) { var mailBody = main.createResponse(recordtype, recordname, "success"); email.send({ author: -5, recipients: emailaddr, //cc: ["feena@jobinandjismi.com"], subject: "IMPORT Completed For " + recordname, body: mailBody }); } else { main.errortocsv(contextobj, errorfolder); } } else if (operation == "delete") { var mailBody = main.createResponse(recordtype, recordname, "delete"); email.send({ author: -5, recipients: emailaddr, //cc: ["feena@jobinandjismi.com"], subject: "Succesfully Deleted the " + recordname, body: mailBody }); } else if (operation == "deleteduplicate") { var mailBody = main.createResponse(recordtype, recordname, "deleteduplicate"); email.send({ author: -5, recipients: emailaddr, //cc: ["feena@jobinandjismi.com"], subject: "Succesfully Deleted the Duplicate " + recordname, body: mailBody }); } else { if (errorfolder == null || errorfolder == "" || errorfolder == undefined) { var mailBody = main.createResponse(recordtype, recordname, "success"); email.send({ author: -5, recipients: emailaddr, //cc: ["feena@jobinandjismi.com"], subject: "IMPORT Completed For " + recordname, body: mailBody }); } else { main.errortocsv(contextobj, errorfolder); } } main.folderdelete(mapinternal); var pendingId = main.findPending(); // log.debug("pendingId", pendingId) if (pendingId != false) { var pendingFile = file.load({ id: pendingId }); var pendingContent = pendingFile.getContents(); var pendingContent = JSON.parse(pendingContent); // log.debug("pendingContent", pendingContent); // log.debug("pendingContent", pendingContent.custscript_json_fileid); main.scheduleanother(pendingContent.custscript_json_fileid, "", "", pendingContent); file.delete({ id: pendingId }); } }, /*Setup map reduce script*/ scheduleanother: function (fileid, mapid, mapfile, catchFile) { try { var scheduleScrptTask = task.create({ taskType: task.TaskType.MAP_REDUCE, scriptId: "customscript_mr_mapreducerecord", deploymentId: 'customdeploy_mr_mapreducerecord', params: { custscript_json_fileid: fileid, custscript_type: mapfile } }); scheduleScrptTask.submit(); /* var mapFileid = JSON.parse(mapid) var emailaddr = mapFileid.emailaddress; var recordtype = mapFileid.contextdetails.recordtype; var recordname = mapFileid.contextdetails.recordname; var mailBody = main.createResponse(recordtype, recordname); email.send({ author: -5, recipients: emailaddr, subject: "Import Process Succesfully Started for " + recordname, body: mailBody });*/ } catch (e) { log.debug("e in scheduleanother", e); var params = { custscript_json_fileid: fileid, custscript_type: mapfile } main.createfile(Date.now(), 26540, params); } }, findPending: function () { var fileSearchObj = search.create({ type: "file", filters: [ ["folder", "anyof", 26540] ], columns: [ search.createColumn({ name: "internalid", label: "Internal ID" }), search.createColumn({ name: "name", sort: search.Sort.ASC, label: "Name" }) ] }); var searchResultCount = fileSearchObj.runPaged().count; if (searchResultCount < 1) { return false } else { var internalid; fileSearchObj.run().each(function (result) { internalid = result.getValue("internalid"); return true; }); return internalid; } }, createResponse: function (recordtype, recordname, flag) { var htmlFile = file.load({ id: 39539 }); var htmlFilecontent = htmlFile.getContents(); if (flag == "success") { var htmlFilecontent1 = htmlFilecontent.replace("<-replacewithtype->", "Import Completed Successfully"); var htmlFilecontent2 = htmlFilecontent1.replace("<-ReplaceWithRecord->", "For Record : " + recordname); } else if (flag == "unsuccess") { var htmlFilecontent1 = htmlFilecontent.replace("<-replacewithtype->", "Import Completed With Some issues "); var htmlFilecontent2 = htmlFilecontent1.replace("<-ReplaceWithRecord->", "For Record " + recordname); } else if (flag == "delete") { var htmlFilecontent1 = htmlFilecontent.replace("<-replacewithtype->", "Succesfully Deleted The Record "); var htmlFilecontent2 = htmlFilecontent1.replace("<-ReplaceWithRecord->", "For Record " + recordname); } else if (flag == "deleteduplicate") { var htmlFilecontent1 = htmlFilecontent.replace("<-replacewithtype->", "Succesfully Deleted The Duplicate Record "); var htmlFilecontent2 = htmlFilecontent1.replace("<-ReplaceWithRecord->", "For Record " + recordname); } return htmlFilecontent2; }, errortocsv: function (contextobj, errorfolder) { try { // to get the data //To create the CSV file var XML_TO_PRINT = main.getXMLDataExcel(file, contextobj, errorfolder); var strXmlEncoded = encode.convert({ string: XML_TO_PRINT, inputEncoding: encode.Encoding.UTF_8, outputEncoding: encode.Encoding.BASE_64 }); var fileObj = file.create({ name: 'report.xls', fileType: file.Type.EXCEL, contents: strXmlEncoded }); var id = fileObj.save(); log.debug('id Of newly created CSV', id); var emailaddr = contextobj.emailaddress; var recordtype = contextobj.contextdetails.recordtype; var recordname = contextobj.contextdetails.recordname; var mailBody = main.createResponse(recordtype, recordname, "unsuccess"); email.send({ author: -5, recipients: emailaddr, //cc: ["feena@jobinandjismi.com"], subject: "CSV IMPORT Completed For Record", attachments: [fileObj], body: mailBody }); } catch (e) { log.debug("Err @ errortocsv", e.message); } }, getXMLDataExcel: function (file, contextobj, errorfolder) { var XML = ""; var TABLE = ""; var HEADING = ""; var x = 0, errArray = [], headingArray = [], i, contents, j; var myXMLFile = file.load({ id: '39548' }); var myXMLFile_value = myXMLFile.getContents(); headingArray = contextobj.csvColumns; errArray = errorfolder; headingArray.push("Error Message"); errArray.unshift(headingArray.toString()); // to get the total no.of err entries var errLength = errArray.length; var headingLength = headingArray.length; var strVar = ""; var headVar = ""; log.debug('errArray', errArray) log.debug('errLength', errLength) for (i = 0; i < errLength; i++) { var temparray = errArray[i].split(','); strVar += "<Row ss:AutoFitHeight=\"0\">"; for (j = 0; j < temparray.length; j++) { strVar += "<Cell><Data ss:Type=\"String\">" + temparray[j] + "<\/Data><\/Cell>"; } strVar += "<\/Row>"; } TABLE = TABLE + strVar; // HEADING = HEADING +headVar; XML = myXMLFile_value.replace('<!-- REPLACEWITHTABLEBODY -->', TABLE); return XML; } }; for (var key in main) { if (typeof main[key] === 'function') { main[key] = trycatch(main[key], key); } } function trycatch(myfunction, key) { return function () { try { return myfunction.apply(this, arguments); } catch (e) { log.debug("e in " + key, e); } } }; return main; });
642
[{"tag": "EMAIL", "value": "feena@jobinandjismi.com", "start": 74201, "end": 74224}, {"tag": "EMAIL", "value": "feena@jobinandjismi.com", "start": 74794, "end": 74817}, {"tag": "EMAIL", "value": "feena@jobinandjismi.com", "start": 75276, "end": 75299}, {"tag": "EMAIL", "value": "feena@jobinandjismi.com", "start": 75840, "end": 75863}, {"tag": "EMAIL", "value": "feena@jobinandjismi.com", "start": 82741, "end": 82764}]
true
5
/** * @NApiVersion 2.x * @NScriptType MapReduceScript * @NModuleScope SameAccount */ /** * Script Description * This Map Reduce to create and delete the records * */ /******************************************************************************* * * Support Files * * ***************************************************************************** * * * $Author: Jobin & Jismi IT Services LLP $ * * DESCRIPTION * CSV Import System * ******************************************************************************/ define(['N/record', 'N/file', 'N/email', 'N/runtime', 'N/search', 'N/email', 'N/encode', 'N/task', 'N/format'], function (record, file, email, runtime, search, email, encode, task, format) { var main = { /*Get inputData for Processing */ getInputData: function (context) { //log.debug('context', context) var processfolderid = runtime.getCurrentScript().getParameter("custscript_json_fileid"); main.sleep(40000); var mapinternal = main.findprocessfiles(processfolderid, false); var contextfile = file.load({ id: mapinternal }); var contextContent = contextfile.getContents(); var contextContent = JSON.parse(contextContent); //log.debug('contextContent', contextContent) var contextobj = JSON.parse(contextContent) var operation = contextobj.contextdetails.operation; var recordtype = contextobj.contextdetails.recordtype; if (operation == "create" || operation == "update") { // log.debug('enter create') var processFilles = main.findprocessfiles(processfolderid, true); //log.debug("processFilles", processFilles); var fileContent = main.setupProccessfiles(processFilles); } else if (operation == "delete") { //log.debug("contextobj.contextdetails.deletedetail", contextobj.deletedetail) var fileContent = main.searchRecord(contextobj.contextdetails.recordtype, contextobj.deletedetail); } else if (operation == "deleteduplicate") { // log.debug("contextobj.contextdetails.deletedetail", contextobj.deletedetail) // log.debug("contextobj.contextdetails.recordtype", contextobj.contextdetails.recordtype) var fileContent = main.searchDuplicateRecord(contextobj.contextdetails.recordtype, contextobj.deletedetail); } try { // log.debug("fileContent", fileContent.length); } catch (e) { log.debug('error', e) } //log.debug("fileContent", fileContent) return fileContent; }, sleep: function (milliseconds) { var date = Date.now(); var currentDate = null; do { currentDate = Date.now(); } while (currentDate - date < milliseconds); }, /*Concatnate the Arrays from Chunks Folder */ setupProccessfiles: function (filefolder) { var len = filefolder.length; var array = []; for (var i = 0; i < len; i++) { if (filefolder[i].name != "scriptcontext.txt") { var processFile = file.load({ id: filefolder[i].internalid }); var fileContent = processFile.getContents(); var temparray = JSON.parse(fileContent); array.push(temparray); } } var fullarray = [].concat.apply([], array); return fullarray; }, /*If the process is delete duplicates, then use the ESN number to find the internalid*/ searchDuplicateRecord: function (recordtype, date) { //log.debug('date', date); var filterarry = [] if (date == "all") { } else { filterarry.push(["created", "within", date]) } var SearchObj = search.create({ type: recordtype, columns: [ search.createColumn({ name: "custrecord_jj_esn", label: "ESN" }), search.createColumn({ name: "internalid", label: "Internal ID" }) ], filters: filterarry }); var searchPageRanges = SearchObj.runPaged({ pageSize: 1000 }); var internalids = []; var esnNum = { }; for (var i = 0; i < searchPageRanges.pageRanges.length; i++) { searchPageRanges.fetch({ index: i }).data.forEach(function (result) { var esn_number = result.getValue("custrecord_jj_esn"); var internal_id = result.getValue("internalid"); try { esnNum[esn_number].push(internal_id); } catch (e) { esnNum[esn_number] = [] esnNum[esn_number].push(internal_id); } return true; }); } Object.keys(esnNum).forEach(function (key) { for (var i = 0; i < esnNum[key].length; i++) { if (esnNum[key][i + 1]) { internalids.push(esnNum[key][i + 1]) } } }); // log.debug('internalids', internalids) // log.debug("esnNum", esnNum); // log.debug("duplciatearray length", internalids.length); return internalids; }, /*If Process is Delete then get the internalids */ searchRecord: function (recordtype, date) { var filterarry = [] if (date == "all") { } else { filterarry.push(["created", "within", date]) } // log.debug("date", date); var SearchObj = search.create({ type: recordtype, columns: [ search.createColumn({ name: "internalid", label: "Internal ID" }) ], filters: filterarry }); var searchPageRanges = SearchObj.runPaged({ pageSize: 1000 }); var internalids = []; for (var i = 0; i < searchPageRanges.pageRanges.length; i++) { searchPageRanges.fetch({ index: i }).data.forEach(function (result) { internalids.push(result.getValue("internalid")); return true; }); } //log.debug("deletearray length", internalids.length); return internalids; }, /*Find JSON chunks From the Folder For Processing */ findprocessfiles: function (folderid, flag) { var fileSearchObj = search.create({ type: "file", filters: [ ["folder", "anyof", folderid] ], columns: [ search.createColumn({ name: "internalid", label: "Internal ID" }), search.createColumn({ name: "name", sort: search.Sort.ASC, label: "Name" }) ] }); var searchResultCount = fileSearchObj.runPaged().count; if (flag == true) { var processarray = []; fileSearchObj.run().each(function (result) { var tempobj = { }; tempobj.internalid = result.getValue("internalid"); tempobj.name = result.getValue("name"); processarray.push(tempobj); return true; }); return processarray; } else { var mapinternal; fileSearchObj.run().each(function (result) { if (result.getValue("name") == "scriptcontext.txt") { mapinternal = result.getValue("internalid"); } return true; }); return mapinternal; } }, /*Reduce Function of map Reduce */ reduce: function (context) { var processfolderid = runtime.getCurrentScript().getParameter("custscript_json_fileid"); var mapinternal = main.findprocessfiles(processfolderid, false); //log.debug('mapinternal',mapinternal) var contextfile = file.load({ id: mapinternal }); var contextContent = contextfile.getContents(); // log.debug("contextContent", contextContent) var contextContent = JSON.parse(contextContent); var contextobj = JSON.parse(contextContent) var operation = contextobj.contextdetails.operation; var recordtype = contextobj.contextdetails.recordtype; var recordname = contextobj.contextdetails.recordname; var mapobj = contextobj.mapobj; //log.debug("mapobj", mapobj) var currentobj = context.values; // log.debug("currentobj", currentobj) var convertedfile = JSON.parse(currentobj[0]); if (convertedfile.length == 1) { //1 if the input file is CSV one. convertedfile = convertedfile[0].split(',') } // log.debug("convertedfile", convertedfile) // log.debug('recordname', recordname) if (operation == "create") { if (recordname != "Spiff Amount") { if (recordname != "Residual Monthly") { var intrId; if (recordtype == "customrecord_jj_tracfone_activations") { var tracfone_record = true; var simno_tracfone = convertedfile[mapobj['custrecordjj_tra_sim']] // log.debug('simno_tracfone', simno_tracfone) var customrecord_jj_tracfone_activationsSearchObj = search.create({ type: "customrecord_jj_tracfone_activations", filters: [ ["custrecordjj_tra_sim", "is", simno_tracfone] ], columns: [ search.createColumn({ name: "internalid", label: "Internal ID" }) ] }); var searchResult = customrecord_jj_tracfone_activationsSearchObj.run().getRange({ start: 0, end: 1 }); for (var j = 0; j < searchResult.length; j++) { intrId = searchResult[j].getValue({ name: "internalid" }); } } // log.debug('tracfone_record', tracfone_record) // log.debug('intrId', intrId) if (intrId && tracfone_record) { //log.debug('duplicate record') } else { main.createrecord(recordtype, mapobj, convertedfile, processfolderid); } } else { //log.debug("testing loop residual amount") } } else { //log.debug("testing loop spiff amount") } } else if (operation == "delete") { // log.debug("convertedfile", convertedfile); main.deleteRecord(recordtype, convertedfile); } else if (operation == "deleteduplicate") { // log.debug("convertedfile duplicate", convertedfile); main.deleteRecord(recordtype, convertedfile); } else if (operation == "update") { var intrId; if (recordtype == "customrecord_jj_tracfone_activations") { var tracfone_record = true; var simno_tracfone = convertedfile[mapobj['custrecordjj_tra_sim']] var customrecord_jj_tracfone_activationsSearchObj = search.create({ type: "customrecord_jj_tracfone_activations", filters: [ ["custrecordjj_tra_sim", "is", simno_tracfone] ], columns: [ search.createColumn({ name: "internalid", label: "Internal ID" }) ] }); var searchResult = customrecord_jj_tracfone_activationsSearchObj.run().getRange({ start: 0, end: 1 }); for (var j = 0; j < searchResult.length; j++) { intrId = searchResult[j].getValue({ name: "internalid" }); } if (searchResult.length <= 0) { convertedfile.push("SIM Number is not present"); var folderid; var init = main.checkforfolder(processfolderid); if (init == true) { folderid = main.createfolder(processfolderid); } else { folderid = init; } main.errorlog(processfolderid, convertedfile, folderid); // log.debug("duplicate ESN ", esnno) return true; } } if (intrId && tracfone_record) { // log.debug('simno_tracfone : ' + simno_tracfone, 'intrId: ' + intrId); main.updateRecord(recordtype, mapobj, convertedfile, processfolderid, intrId, recordname); } } }, /*To Find Error Files */ finderrorfiles: function (errorfolderid) { // log.debug("errorfolderid", errorfolderid) var fileSearchObj = search.create({ type: "folder", filters: [ ["name", "is", errorfolderid] ], columns: [ search.createColumn({ name: "internalid", label: "Internal ID" }), search.createColumn({ name: "name", sort: search.Sort.ASC, label: "Name" }) ] }); var resultSet = fileSearchObj.run(); var firstResult = resultSet.getRange({ start: 0, end: 1 })[0]; // log.debug('firstResult',firstResult) var value = firstResult.getValue(resultSet.columns[0]); var fileError = search.create({ type: "file", filters: [ ["folder", "anyof", value] ], columns: [ search.createColumn({ name: "internalid", label: "Internal ID" }), search.createColumn({ name: "name", sort: search.Sort.ASC, label: "Name" }) ] }) var processarray = []; fileError.run().each(function (result) { var tempobj = { }; tempobj.internalid = result.getValue("internalid"); tempobj.name = result.getValue("name"); processarray.push(tempobj); return true; }); var len = processarray.length; var array = []; for (var i = 0; i < len; i++) { if (processarray[i].name != "scriptcontext.txt") { var processFile = file.load({ id: processarray[i].internalid }); var fileContent = processFile.getContents(); array.push(fileContent); } } // var fullarray = [].concat.apply([], array); return array; }, /*Error Folder For Logging and send Email*/ createfolder: function (data) { var folderRec = record.create({ type: record.Type.FOLDER, isDynamic: true }); folderRec.setValue({ fieldId: 'parent', value: 10189 }); folderRec.setValue({ fieldId: 'name', value: data }); var folderId = folderRec.save({ enableSourcing: true, ignoreMandatoryFields: true }); return folderId; }, /*To check whether there is any folder existing for error log*/ checkforfolder: function (name) { var folderSearchObj = search.create({ type: "folder", filters: [ ["name", "is", name] ], columns: [ search.createColumn({ name: "internalid", label: "internalid" }) ] }); var searchResultCount = folderSearchObj.runPaged().count; if (searchResultCount < 1) { return true } else { var internalid; folderSearchObj.run().each(function (result) { internalid = result.getValue("internalid"); return true; }); return internalid; } }, /* Create the error file in the error error log */ createfile: function (name, folderid, convertedfile) { var folderinternal; if (folderid > 0) { folderinternal = folderid; } else { folderinternal = 10189 } var fileObj = file.create({ name: name + '.txt', fileType: file.Type.PLAINTEXT, contents: convertedfile.toString(), folder: folderinternal, isOnline: true }); var fileid = fileObj.save(); return fileid; }, /*Delete Process Actions */ deleteRecord: function (type, internalid) { record.delete({ type: type, id: internalid }); }, /*Update record actions Process */ updateRecord: function (recordtype, mapobj, convertedfile, processfolderid, intrId, recordname) { if (recordtype == "customrecord_jj_tracfone_activations") { if (recordname != "Spiff Amount") { if (recordname != "Residual Monthly") { var value_xl = convertedfile[mapobj['custrecord_jj_plan']] //log.debug('convertedfile[mapobj[custrecord_ao_spiff_paid_date]]', convertedfile[mapobj['custrecord_ao_spiff_paid_date']]) var activationMonth_xl = main.doValidations(convertedfile[mapobj['custrecord_ao_spiff_paid_date']], recordtype) // log.debug('activationMonth_xl', activationMonth_xl) if (activationMonth_xl) { var formattedDateString = activationMonth_xl } var commission = convertedfile[mapobj['custrecord_ao_last_resid_amount']] var usedDate = convertedfile[mapobj['custrecord_ao_last_paid_resid']] if (usedDate) { var formattedDateStringResidue = main.doValidations(usedDate, recordtype) } var cust_load = record.load({ type: 'customrecord_jj_tracfone_activations', id: intrId /*, isDynamic: true */ }); cust_load.setValue({ fieldId: "custrecord_jj_plan", value: value_xl }); if (activationMonth_xl) { cust_load.setValue({ fieldId: "custrecord_ao_spiff_paid_amouunt", value: commission }); cust_load.setText({ fieldId: "custrecord_ao_spiff_paid_date", text: formattedDateString }); } if (usedDate) { cust_load.setValue({ fieldId: "custrecord_ao_last_resid_amount", value: commission }); cust_load.setText({ fieldId: "custrecord_ao_last_paid_resid", text: formattedDateStringResidue }); } var id = cust_load.save({ enableSourcing: true }); log.debug("Record updated ", id); } else { //log.debug('enter resid loop') var objRecord = record.load({ type: 'customrecord_jj_tracfone_activations', id: intrId }); for (var key in mapobj) { if (key != "-") { var currentValue = main.doValidations(convertedfile[mapobj[key]], recordtype); // log.debug('currentValue', currentValue) if (currentValue.indexOf("$") > -1) { var temp = currentValue.split('$') currentValue = temp[1] } // log.debug('Updated currentValue', currentValue) try { //log.debug('enter try key', key) objRecord.setText({ fieldId: key, text: currentValue.toString().trim() }); var simEarning = objRecord.getValue({ fieldId: 'custrecord23' }) if (key == 'custrecord_ao_last_resid_amount') { simEarning = simEarning + Number(currentValue) objRecord.setValue({ fieldId: 'custrecord23', value: simEarning.toString().trim() }); } } catch (e) { try { objRecord.setValue({ fieldId: key, value: currentValue.toString().trim() }); } catch (error) { // log.debug("Error for creating record", error.message) convertedfile.push(error.message); // log.debug("Econvertedfile", convertedfile) var folderid; var init = main.checkforfolder(processfolderid); if (init == true) { folderid = main.createfolder(processfolderid); } else { folderid = init; } main.errorlog(processfolderid, convertedfile); return error; } } } } var id = objRecord.save({ enableSourcing: false }); log.debug("Record updated ", id); } } else { log.debug('testing update another') var objRecord = record.load({ type: 'customrecord_jj_tracfone_activations', id: intrId /*, isDynamic: true */ }); for (var key in mapobj) { if (key != "-") { var currentValue = main.doValidations(convertedfile[mapobj[key]], recordtype); log.debug('currentValue', currentValue) if (currentValue.indexOf("$") > -1) { var temp = currentValue.split('$') currentValue = temp[1] } log.debug('Updated currentValue', currentValue) /*var currentDate = main.doValidations(convertedfile[mapobj['custrecord_ao_spiff_paid_date']], recordtype);*/ try { log.debug('enter try key', key) /*objRecord.setValue({ fieldId: 'custrecord_ao_spiff_paid_amouunt', value: currentValue.toString().trim() }); objRecord.setText({ fieldId: 'custrecord_ao_spiff_paid_date', text: currentDate });*/ objRecord.setText({ fieldId: key, text: currentValue.toString().trim() }); } catch (e) { try { objRecord.setValue({ fieldId: key, value: currentValue.toString().trim() }); } catch (error) { // log.debug("Error for creating record", error.message) convertedfile.push(error.message); // log.debug("Econvertedfile", convertedfile) var folderid; var init = main.checkforfolder(processfolderid); if (init == true) { folderid = main.createfolder(processfolderid); } else { folderid = init; } main.errorlog(processfolderid, convertedfile); return error; } /* }*/ } } } var id = objRecord.save({ enableSourcing: false }); log.debug("Record updated ", id); } } }, /*Create record actions Process */ createrecord: function (recordtype, mapobj, convertedfile, processfolderid) { log.debug("enter create fun") log.debug("mapobj", mapobj) var duplicate = false; if (convertedfile.length > 0) { var objRecord = record.create({ type: recordtype, isDynamic: true }); for (var key in mapobj) { if (key != "-") { log.debug('key', key) log.debug('convertedfile[mapobj[key]]', convertedfile[mapobj[key]]) var currentValue = main.doValidations(convertedfile[mapobj[key]], recordtype); try { objRecord.setValue({ fieldId: key, value: currentValue.toString().trim() }); } catch (e) { try { objRecord.setText({ fieldId: key, text: currentValue.toString().trim() }); } catch (error) { // log.debug("Error for creating record", error.message) convertedfile.push(error.message); // log.debug("Econvertedfile", convertedfile) var folderid; var init = main.checkforfolder(processfolderid); if (init == true) { folderid = main.createfolder(processfolderid); } else { folderid = init; } main.errorlog(processfolderid, convertedfile); return error; } } } }; log.debug('testing record type', recordtype) if (recordtype == "customrecord_jj_branded_handset") { var simno = convertedfile[mapobj['custrecord_jj_sim']] var esnno = convertedfile[mapobj['custrecord_jj_esn']] duplicate = main.checksim(simno, esnno, processfolderid, convertedfile); var tectraId = objRecord.getValue({ fieldId: 'custrecord_jj_branded_tcetraid' }); var customerDetails = main.findCustomerdetails(tectraId, "custentity1"); objRecord.setValue({ fieldId: "custrecord_jj_customer", value: customerDetails.customerId }); objRecord.setValue({ fieldId: "custrecord_jj_sales_rep", value: customerDetails.salesreppartner }); objRecord.setValue({ fieldId: "custrecord_jj_subof_sales_partner", value: customerDetails.subof }); } else if (recordtype == "customrecord_jj_route_run") { var tectraId = objRecord.getValue({ fieldId: 'custrecord_jj_tcetraid' }); var customerDetails = main.findCustomerdetails(tectraId, "custentity1"); objRecord.setValue({ fieldId: "custrecord_jj_customerid", value: customerDetails.customerId }); objRecord.setValue({ fieldId: "custrecord_jj_sales_rep_route", value: customerDetails.salesreppartner }); objRecord.setValue({ fieldId: "custrecord_jj_subof_route", value: customerDetails.subof }); } else if (recordtype == "customrecord_jj_qpay_marketplace_details") { var incommId = objRecord.getValue({ fieldId: 'custrecord_jj_branchid' }); var customerDetails = main.findCustomerdetails(incommId, "custentityincomeexclusiveid"); objRecord.setValue({ fieldId: "custrecord_qpay_customerid", value: customerDetails.customerId }); objRecord.setValue({ fieldId: "custrecord_jj_sales_rep_maeket", value: customerDetails.salesreppartner }); objRecord.setValue({ fieldId: "custrecord_jj_subof_market", value: customerDetails.subof }); } else if (recordtype == "customrecord_jj_qpaydetail_transaction") { /*as per discusions on 07-07 parent id and parent name need not to be set*/ var incommId = objRecord.getValue({ fieldId: 'custrecord_jj_qpaydetail_incommid' }); var parentId = objRecord.getValue({ fieldId: 'custrecord_jj_details_parentid' }); //getting the parent name var parentName = objRecord.getValue({ fieldId: 'custrecord_jj_qpaydetail_parent_nm' }); var customerDetails = main.findCustomerdetails(incommId, "custentityincomeexclusiveid"); objRecord.setValue({ fieldId: "custrecord_jj_qpaydetail_custid", value: customerDetails.customerId }); objRecord.setValue({ fieldId: "custrecord_jj_sales_rep_qpay", value: customerDetails.salesreppartner }); objRecord.setValue({ fieldId: "custrecord_jj_subof_salesrep", value: customerDetails.subof }); // set the parent id id in the customer record /* var parId = record.submitFields({ type: record.Type.CUSTOMER, id: customerDetails.customerId, values: { custentity_jj_parentaccountid: parentId, custentity_jj_parentname: parentName } });*/ } else if (recordtype == "customrecord223") { var tectraId = objRecord.getValue({ fieldId: 'custrecord6' }); var customerDetails = main.findCustomerdetails(tectraId, "custentity1"); // log.debug(tectraId, customerDetails); objRecord.setValue({ fieldId: "custrecord_jj_customer_vidapay", value: customerDetails.customerId }); objRecord.setValue({ fieldId: "custrecord_jj_salesrep_vidapay", value: customerDetails.salesreppartner }); objRecord.setValue({ fieldId: "custrecord_jj_subof_vidapay", value: customerDetails.subof }); } else if (recordtype == "customrecord_jj_tracfone_activations") { log.debug('recordtype checksim', recordtype) var tectraId = objRecord.getValue({ fieldId: 'custrecord_jj_trc_tsp_id' }); var partnetID = objRecord.getValue({ fieldId:"custrecord_jj_tra_partner_id" }) log.debug("partnetID",partnetID) if(partnetID == "IAS"){ var searchField = "custentityincomeexclusiveid" }else{ var searchField = "custentity1" } log.debug("searchField",searchField) log.debug("tectraId",tectraId) var customerDetails = main.findCustomerdetails(tectraId, searchField); log.debug("customerDetails",customerDetails) objRecord.setValue({ fieldId: "custrecord_jj_tracfone_activa_cusid", value: customerDetails.customerId }); objRecord.setValue({ fieldId: "custrecord_jj_sales_rep_tracfone", value: customerDetails.salesreppartner }); /* objRecord.setValue({ fieldId: "custrecord_jj_subof_sales_partner", value: customerDetails.subof });*/ } else if (recordtype == "customrecord_jj_marketplace_sales_order") { /* MTW-252 This else if part is done for the record creation for the marketplace integration*/ var simNumber = convertedfile[7]; duplicate = main.detectDuplicateSim(recordtype, simNumber); log.debug("duplicate", duplicate) if (duplicate != false) { log.debug("reach leve2") main.updateMarketPlaceRec(convertedfile, duplicate, recordtype) } else { log.debug("reach level") log.debug("convertedfile[0]: ",convertedfile[0]) // var convertedDate = main.dateValidation(JSON.stringify(convertedfile[0])) // log.debug("convertedDate: ",convertedDate) // var orderedDate = format.format({ // value: convertedDate, // type:format.Type.DATE // }) // log.debug("orderedDate: ",orderedDate) objRecord.setText({ fieldId: "custrecord_jj_date_ordered", text: convertedfile[0] }); objRecord.setValue({ fieldId: "custrecord_jj_order", value: convertedfile[1] }); objRecord.setValue({ fieldId: "custrecord_jj_product_id", value: convertedfile[2] }); objRecord.setValue({ fieldId: "custrecord_jj_marketplace_product_name", value: convertedfile[3] }); objRecord.setValue({ fieldId: "custrecord_jj_marketplace_dealer_cost", value: convertedfile[7] }); objRecord.setValue({ fieldId: "custrecord_jj_current_parent_commission", value: convertedfile[8] }); objRecord.setValue({ fieldId: "custrecord_jj_sum_of_sub_parent_commissi", value: convertedfile[9] }); objRecord.setValue({ fieldId: "custrecord_jj_marketplace_sim_esn", value: convertedfile[12] }); objRecord.setValue({ fieldId: "custrecord_jj_part_number", value: convertedfile[13] }); log.debug("convertedfile[15]", convertedfile[13]) objRecord.setValue({ fieldId: "custrecord_jj_merchant_account_id", value: convertedfile[20] }); var customerDetails = main.findCustomerdetails(convertedfile[20], "custentity1"); log.debug("customerDetails", customerDetails) objRecord.setValue({ fieldId: "custrecord_jj_merchant_name", value: customerDetails.customerId }); log.debug("convertedfile[24]", convertedfile[29]) objRecord.setText({ fieldId: "custrecord_jj_marketplace_date_shipped", text: convertedfile[29]//new Date(main.dateValidation(convertedfile[22])) }); objRecord.setValue({ fieldId: "custrecord_jj_marketplace_tracking_numbe", value: convertedfile[30] }); log.debug("convertedfile[10]", convertedfile[16]) objRecord.setValue({ fieldId: "custrecord_jj_marketplace_active_status", value: convertedfile[16] }); } } else if (recordtype == "customrecord_mw_tracfone_residual_month") { var sim = objRecord.getValue({ fieldId: 'custrecord_jj_trc_mnthly_sim' }); // log.debug("sim", sim) try { var activationsSearchObj = search.create({ type: 'customrecord_jj_tracfone_activations', columns: [{ name: "custrecord_jj_tracfone_activa_cusid" }, { name: 'custrecord_jj_sales_rep_tracfone' }, { name: 'custrecord_jj_city' }, { name: 'custrecord_jj_state' }], filters: ["custrecordjj_tra_sim", "is", sim] }); var activationsResultCount = activationsSearchObj.runPaged().count; if (activationsResultCount == 1) { //then there will be 1 sim in tracfone activation record var searchResult = activationsSearchObj.run().getRange({ start: 0, end: 1 }); // log.debug("searchResult", searchResult); var custID = searchResult[0].getValue({ name: 'custrecord_jj_tracfone_activa_cusid' }); // log.debug("custID from Tracfone", custID); if (custID != '') { var searchResultForCustomer = main.searchForCustomer(custID); objRecord.setValue({ fieldId: "custrecord_mw_tracfone_customer", value: custID }); } // log.debug("searchResultForCustomer", searchResultForCustomer); var salesRepTrcMnthly = searchResult[0].getText({ name: 'custrecord_jj_sales_rep_tracfone' }); var cityTrcMnthly = searchResult[0].getValue({ name: 'custrecord_jj_city' }); var stateTrcMnthly = searchResult[0].getValue({ name: 'custrecord_jj_state' }); } objRecord.setValue({ fieldId: "custrecord_jj_sales_name", value: salesRepTrcMnthly }); objRecord.setValue({ fieldId: "custrecord_jj_trc_mnthly_city", value: cityTrcMnthly }); objRecord.setValue({ fieldId: "custrecord_jj_trc_mnthly_state", value: stateTrcMnthly }); objRecord.setValue({ fieldId: "custrecord_jj_parent_name", value: searchResultForCustomer.parentName }); objRecord.setValue({ fieldId: "custrecord_jj_parent_id", value: searchResultForCustomer.parentID }); objRecord.setValue({ fieldId: "custrecord_incomm_id", value: searchResultForCustomer.incommId }); objRecord.setValue({ fieldId: "custrecordcustrecord_tcetra_id", value: searchResultForCustomer.tectraId }); } catch (e) { log.debug("e", e); } } } if (duplicate == false || duplicate == null) { var id = objRecord.save({ enableSourcing: true }); log.debug("Record Created ", id); } else { log.debug("duplicate ", duplicate); } }, /* MTW-252 The function for check duplicate sim number */ detectDuplicateSim: function (recordtype, simNumber) { var customrecord_jj_marketplace_sales_orderSearchObj = search.create({ type: recordtype, filters: [ ["custrecord_jj_marketplace_sim_esn", "is", simNumber] ], columns: [ search.createColumn({ name: "internalid", label: "Internal ID" }) ] }); var searchResultCount = customrecord_jj_marketplace_sales_orderSearchObj.runPaged().count; var recordIdVal = null; if (searchResultCount > 0) { customrecord_jj_marketplace_sales_orderSearchObj.run().each(function (result) { recordIdVal = result.getValue({ name: "internalid", label: "Internal ID" }) return false; }); return recordIdVal; } else { return false; } }, /* MTW-252 The function for update marketplace record */ updateMarketPlaceRec: function (convertedfile, marketPlaceDuplicate, recordtype) { var updateRecord = record.load({ type: recordtype, id: marketPlaceDuplicate, isDynamic: true }); updateRecord.setText({ fieldId: "custrecord_jj_date_ordered", text: convertedfile[0]//new Date(main.dateValidation(convertedfile[0])) }); updateRecord.setValue({ fieldId: "custrecord_jj_order", value: convertedfile[1] }); updateRecord.setValue({ fieldId: "custrecord_jj_product_id", value: convertedfile[2] }); updateRecord.setValue({ fieldId: "custrecord_jj_marketplace_product_name", value: convertedfile[3] }); updateRecord.setValue({ fieldId: "custrecord_jj_marketplace_dealer_cost", value: convertedfile[7] }); updateRecord.setValue({ fieldId: "custrecord_jj_current_parent_commission", value: convertedfile[8] }); updateRecord.setValue({ fieldId: "custrecord_jj_sum_of_sub_parent_commissi", value: convertedfile[9] }); updateRecord.setValue({ fieldId: "custrecord_jj_marketplace_sim_esn", value: convertedfile[12] }); updateRecord.setValue({ fieldId: "custrecord_jj_part_number", value: convertedfile[13] }); updateRecord.setValue({ fieldId: "custrecord_jj_merchant_account_id", value: convertedfile[14] }); var customerDetails = main.findCustomerdetails(convertedfile[14], "custentity1"); log.debug("customerDetails", customerDetails) updateRecord.setValue({ fieldId: "custrecord_jj_merchant_name", value: customerDetails.customerId }); updateRecord.setText({ fieldId: "custrecord_jj_marketplace_date_shipped", text: convertedfile[29]//new Date(main.dateValidation(convertedfile[22])) }); updateRecord.setValue({ fieldId: "custrecord_jj_marketplace_tracking_numbe", value: convertedfile[30] }); updateRecord.setValue({ fieldId: "custrecord_jj_marketplace_active_status", value: convertedfile[16] }); var recid = updateRecord.save({ enableSourcing: true }); log.debug("Record updated ", id); }, /* MTW-252 The function for validating date field for date field setvalue maketplace integration */ dateValidation: function (datevalue) { var dd = new Date(datevalue).getDate() var mm = new Date(datevalue).getMonth() var yy = new Date(datevalue).getFullYear() var datestrVal = dd + '/' + mm + '/' + yy; log.debug("datestrVal: ",datestrVal) return datestrVal; }, /* create a search in customer record to find the corresponding customer according to the tcetra id*/ /*Route Run and Branded Handset*/ findCustomerdetails: function (tectraId, searchField) { var customerSearchObj = search.create({ type: "customer", filters: [ [searchField, "contains", tectraId], "AND", ["subsidiary", "anyof", "2"] ], columns: [searchField, "internalid"] }); var searchResultCount = customerSearchObj.runPaged().count; log.debug("searchResultCount",searchResultCount) if (searchResultCount <= 0) { customerSearchObj = search.create({ type: "customer", filters: [ [searchField, "contains", tectraId] ], columns: [searchField, "internalid"] }); searchResultCount = customerSearchObj.runPaged().count; // log.debug("searchResultCount insidfa", searchResultCount); } // var searchResultCount = customerSearchObj.runPaged().count; var returnObj = { }; customerSearchObj.run().each(function (result) { // get the customer id returnObj.customerId = result.getValue('internalid'); // To get the sales rep partner id from the customer record var lookupfieldofpartner = search.lookupFields({ type: 'customer', id: returnObj.customerId, columns: ['partner'] }); if (lookupfieldofpartner.partner[0]) { returnObj.salesreppartner = lookupfieldofpartner.partner[0].value; } // to get parent id from partner record var lookupfieldofsub = search.lookupFields({ type: 'partner', id: returnObj.salesreppartner, columns: ['parent'] }); if (lookupfieldofsub.parent[0]) { returnObj.subof = lookupfieldofsub.parent[0].value; } }); return returnObj; }, checksim: function (simno, esnno, processfolderid, convertedfile) { var branded_handset_search_sim = search.create({ type: "customrecord_jj_branded_handset", filters: [ ["custrecord_jj_sim", "is", simno] ], columns: [ search.createColumn({ name: "id", sort: search.Sort.ASC, label: "ID" }), search.createColumn({ name: "custrecord_jj_customer", label: "Customer" }), search.createColumn({ name: "custrecord_jj_sim", label: "SIM" }), search.createColumn({ name: "custrecord_jj_esn", label: "ESN" }), search.createColumn({ name: "custrecord_jj_branded_tcetraid", label: "Tcetra Id" }) ] }); var searchResultCountSim = branded_handset_search_sim.runPaged().count; // log.debug("Brandend Handset Sim Search Count", searchResultCountSim); if (searchResultCountSim > 0) { convertedfile.push("Duplicate Sim Number"); var folderid; var init = main.checkforfolder(processfolderid); if (init == true) { folderid = main.createfolder(processfolderid); } else { folderid = init; } main.errorlog(processfolderid, convertedfile); // log.debug("duplicate SIM ", simno) return true; } else { var branded_handset_search_esn = search.create({ type: "customrecord_jj_branded_handset", filters: [ ["custrecord_jj_esn", "is", esnno] ], columns: [ // search.createColumn({ // name: "id", // sort: search.Sort.ASC, // label: "ID" // }), search.createColumn({ name: "custrecord_jj_customer", label: "Customer" }), search.createColumn({ name: "custrecord_jj_sim", label: "SIM" }), search.createColumn({ name: "custrecord_jj_esn", label: "ESN" }), search.createColumn({ name: "custrecord_jj_branded_tcetraid", label: "Tcetra Id" }) ] }); var searchResultCountESN = branded_handset_search_esn.runPaged().count; // log.debug("Brandend Handset ESN Search Count", searchResultCountESN); // customrecord_jj_branded_handsetSearchObj.run().each(function(result){ // // .run().each has a limit of 4,000 results // return true; // }); if (searchResultCountESN > 0) { convertedfile.push("Duplicate ESN Number"); var folderid; var init = main.checkforfolder(processfolderid); if (init == true) { folderid = main.createfolder(processfolderid); } else { folderid = init; } main.errorlog(processfolderid, convertedfile); // log.debug("duplicate ESN ", esnno) return true; } } return false }, searchForCustomer: function (custID) { var obj = { }; var customerSearchObj = search.create({ type: "customer", filters: [ ["internalidnumber", "equalto", custID] ], columns: [{ name: "custentity_jj_parentname" }, { name: "custentity_jj_parentaccountid" }, { name: "custentity1" }, { name: "custentityincomeexclusiveid" }] }); var searchResultCount = customerSearchObj.runPaged().count; if (searchResultCount > 0) { var searchResult1 = customerSearchObj.run().getRange({ start: 0, end: 1 }); // log.debug("searchResult1",searchResult1); obj.parentName = searchResult1[0].getValue({ name: 'custentity_jj_parentname' }); // log.debug("parentName",obj.parentName); obj.parentID = searchResult1[0].getValue({ name: 'custentity_jj_parentaccountid' }); obj.incommId = searchResult1[0].getValue({ name: 'custentityincomeexclusiveid' }); obj.tectraId = searchResult1[0].getValue({ name: 'custentity1' }); // log.debug("parentID",obj.parentID); } // log.debug("obj",obj); return obj; }, /*Delete JSON chunks Folder after the Import Process */ folderdelete: function (mapinternal) { var processfolderid = runtime.getCurrentScript().getParameter("custscript_json_fileid"); var processarray = main.findprocessfiles(processfolderid, true); for (i = 0; i < processarray.length; i++) { file.delete({ id: processarray[i].internalid }); } file.delete({ id: mapinternal }); var folderdelete = record.delete({ type: "folder", id: processfolderid }); }, /*To create an folder that contain all the errors */ errorlog: function (processfolderid, convertedfile, folderid) { var filename = Date.now(); // var folderid; // var init = main.checkforfolder(processfolderid); // if (init == true) { // folderid = main.createfolder(processfolderid); // } else { // folderid = init; // // } var processfileid = main.createfile(filename, folderid, convertedfile); }, /*Check whether the input string is Date or number or String */ /*if date format is mm/dd/yyy*/ doValidations: function (string, recordtype) { /*check whether inputed data is date*/ //log.debug("string date in dovalidation", string); var inputString = main.isDate(string); //log.debug("inputString", inputString) if (inputString == false) { if (isNaN(string)) { return string; } else { if (string == null || string == "") { return ""; } else { return Number(string); } } } else { if (recordtype == "customrecord_mw_tracfone_residual_month") { if (string.indexOf("-") > 0) { var dateArray = string.split("-"); var datestr = dateArray[1] + '/' + dateArray[0] + '/' + dateArray[2]; // log.debug("date last of do validation", datestr); return datestr; } else { return string } } else if (recordtype == "customrecord_jj_tracfone_activations") { if (string.indexOf("-") > 0) { var dateArray = string.split("-"); var datestr = dateArray[1] + '/' + dateArray[0] + '/' + dateArray[2]; // log.debug("date last of do validation", datestr); return datestr; } else { return string } } var string = string.replace(/-/g, "/"); if (new Date(string.toString()) == "Invalid Date") { return string; } else { var today = new Date(string); // log.debug("today", today) var dd = today.getDate(); var mm = today.getMonth() + 1; var yyyy = today.getFullYear(); if (yyyy < 2000) yyyy = yyyy + 100; // if (mm < 10) { // mm = mm; // } var datestr = mm + '/' + dd + '/' + yyyy; // log.debug("date last of do validation", datestr) return datestr; } } }, /*To find whether the input string is date or not */ isDate: function (value) { var dateFormat; if (toString.call(value) === '[object Date]') { return true; } if (typeof value.replace === 'function') { value.replace(/^\s+|\s+$/gm, ''); } dateFormat = /(^\d{1,4}[\.|\\/|-]\d{1,2}[\.|\\/|-]\d{1,4})?$/; return dateFormat.test(value); }, /*Summary function Of map reduce */ summarize: function (summary) { var errorfolderid = runtime.getCurrentScript().getParameter("custscript_json_fileid"); var errorfolder = main.finderrorfiles(errorfolderid); var processfolderid = runtime.getCurrentScript().getParameter("custscript_json_fileid"); var mapinternal = main.findprocessfiles(processfolderid, false); var contextfile = file.load({ id: mapinternal }); var contextContent = contextfile.getContents(); var contextContent = JSON.parse(contextContent); var contextobj = JSON.parse(contextContent); var operation = contextobj.contextdetails.operation; var emailaddr = contextobj.emailaddress; var recordtype = contextobj.contextdetails.recordtype; var recordname = contextobj.contextdetails.recordname; if (operation == "create") { if (errorfolder == null || errorfolder == "" || errorfolder == undefined) { var mailBody = main.createResponse(recordtype, recordname, "success"); email.send({ author: -5, recipients: emailaddr, //cc: ["kenaa@example.com"], subject: "IMPORT Completed For " + recordname, body: mailBody }); } else { main.errortocsv(contextobj, errorfolder); } } else if (operation == "delete") { var mailBody = main.createResponse(recordtype, recordname, "delete"); email.send({ author: -5, recipients: emailaddr, //cc: ["kenaa@example.com"], subject: "Succesfully Deleted the " + recordname, body: mailBody }); } else if (operation == "deleteduplicate") { var mailBody = main.createResponse(recordtype, recordname, "deleteduplicate"); email.send({ author: -5, recipients: emailaddr, //cc: ["kenaa@example.com"], subject: "Succesfully Deleted the Duplicate " + recordname, body: mailBody }); } else { if (errorfolder == null || errorfolder == "" || errorfolder == undefined) { var mailBody = main.createResponse(recordtype, recordname, "success"); email.send({ author: -5, recipients: emailaddr, //cc: ["kenaa@example.com"], subject: "IMPORT Completed For " + recordname, body: mailBody }); } else { main.errortocsv(contextobj, errorfolder); } } main.folderdelete(mapinternal); var pendingId = main.findPending(); // log.debug("pendingId", pendingId) if (pendingId != false) { var pendingFile = file.load({ id: pendingId }); var pendingContent = pendingFile.getContents(); var pendingContent = JSON.parse(pendingContent); // log.debug("pendingContent", pendingContent); // log.debug("pendingContent", pendingContent.custscript_json_fileid); main.scheduleanother(pendingContent.custscript_json_fileid, "", "", pendingContent); file.delete({ id: pendingId }); } }, /*Setup map reduce script*/ scheduleanother: function (fileid, mapid, mapfile, catchFile) { try { var scheduleScrptTask = task.create({ taskType: task.TaskType.MAP_REDUCE, scriptId: "customscript_mr_mapreducerecord", deploymentId: 'customdeploy_mr_mapreducerecord', params: { custscript_json_fileid: fileid, custscript_type: mapfile } }); scheduleScrptTask.submit(); /* var mapFileid = JSON.parse(mapid) var emailaddr = mapFileid.emailaddress; var recordtype = mapFileid.contextdetails.recordtype; var recordname = mapFileid.contextdetails.recordname; var mailBody = main.createResponse(recordtype, recordname); email.send({ author: -5, recipients: emailaddr, subject: "Import Process Succesfully Started for " + recordname, body: mailBody });*/ } catch (e) { log.debug("e in scheduleanother", e); var params = { custscript_json_fileid: fileid, custscript_type: mapfile } main.createfile(Date.now(), 26540, params); } }, findPending: function () { var fileSearchObj = search.create({ type: "file", filters: [ ["folder", "anyof", 26540] ], columns: [ search.createColumn({ name: "internalid", label: "Internal ID" }), search.createColumn({ name: "name", sort: search.Sort.ASC, label: "Name" }) ] }); var searchResultCount = fileSearchObj.runPaged().count; if (searchResultCount < 1) { return false } else { var internalid; fileSearchObj.run().each(function (result) { internalid = result.getValue("internalid"); return true; }); return internalid; } }, createResponse: function (recordtype, recordname, flag) { var htmlFile = file.load({ id: 39539 }); var htmlFilecontent = htmlFile.getContents(); if (flag == "success") { var htmlFilecontent1 = htmlFilecontent.replace("<-replacewithtype->", "Import Completed Successfully"); var htmlFilecontent2 = htmlFilecontent1.replace("<-ReplaceWithRecord->", "For Record : " + recordname); } else if (flag == "unsuccess") { var htmlFilecontent1 = htmlFilecontent.replace("<-replacewithtype->", "Import Completed With Some issues "); var htmlFilecontent2 = htmlFilecontent1.replace("<-ReplaceWithRecord->", "For Record " + recordname); } else if (flag == "delete") { var htmlFilecontent1 = htmlFilecontent.replace("<-replacewithtype->", "Succesfully Deleted The Record "); var htmlFilecontent2 = htmlFilecontent1.replace("<-ReplaceWithRecord->", "For Record " + recordname); } else if (flag == "deleteduplicate") { var htmlFilecontent1 = htmlFilecontent.replace("<-replacewithtype->", "Succesfully Deleted The Duplicate Record "); var htmlFilecontent2 = htmlFilecontent1.replace("<-ReplaceWithRecord->", "For Record " + recordname); } return htmlFilecontent2; }, errortocsv: function (contextobj, errorfolder) { try { // to get the data //To create the CSV file var XML_TO_PRINT = main.getXMLDataExcel(file, contextobj, errorfolder); var strXmlEncoded = encode.convert({ string: XML_TO_PRINT, inputEncoding: encode.Encoding.UTF_8, outputEncoding: encode.Encoding.BASE_64 }); var fileObj = file.create({ name: 'report.xls', fileType: file.Type.EXCEL, contents: strXmlEncoded }); var id = fileObj.save(); log.debug('id Of newly created CSV', id); var emailaddr = contextobj.emailaddress; var recordtype = contextobj.contextdetails.recordtype; var recordname = contextobj.contextdetails.recordname; var mailBody = main.createResponse(recordtype, recordname, "unsuccess"); email.send({ author: -5, recipients: emailaddr, //cc: ["kenaa@example.com"], subject: "CSV IMPORT Completed For Record", attachments: [fileObj], body: mailBody }); } catch (e) { log.debug("Err @ errortocsv", e.message); } }, getXMLDataExcel: function (file, contextobj, errorfolder) { var XML = ""; var TABLE = ""; var HEADING = ""; var x = 0, errArray = [], headingArray = [], i, contents, j; var myXMLFile = file.load({ id: '39548' }); var myXMLFile_value = myXMLFile.getContents(); headingArray = contextobj.csvColumns; errArray = errorfolder; headingArray.push("Error Message"); errArray.unshift(headingArray.toString()); // to get the total no.of err entries var errLength = errArray.length; var headingLength = headingArray.length; var strVar = ""; var headVar = ""; log.debug('errArray', errArray) log.debug('errLength', errLength) for (i = 0; i < errLength; i++) { var temparray = errArray[i].split(','); strVar += "<Row ss:AutoFitHeight=\"0\">"; for (j = 0; j < temparray.length; j++) { strVar += "<Cell><Data ss:Type=\"String\">" + temparray[j] + "<\/Data><\/Cell>"; } strVar += "<\/Row>"; } TABLE = TABLE + strVar; // HEADING = HEADING +headVar; XML = myXMLFile_value.replace('<!-- REPLACEWITHTABLEBODY -->', TABLE); return XML; } }; for (var key in main) { if (typeof main[key] === 'function') { main[key] = trycatch(main[key], key); } } function trycatch(myfunction, key) { return function () { try { return myfunction.apply(this, arguments); } catch (e) { log.debug("e in " + key, e); } } }; return main; });
true
/** * @NApiVersion 2.x * @NScriptType MapReduceScript * @NModuleScope SameAccount */ /** * Script Description * This Map Reduce to create and delete the records * */ /******************************************************************************* * * Support Files * * ***************************************************************************** * * * $Author: Jobin & Jismi IT Services LLP $ * * DESCRIPTION * CSV Import System * ******************************************************************************/ define(['N/record', 'N/file', 'N/email', 'N/runtime', 'N/search', 'N/email', 'N/encode', 'N/task', 'N/format'], function (record, file, email, runtime, search, email, encode, task, format) { var main = { /*Get inputData for Processing */ getInputData: function (context) { //log.debug('context', context) var processfolderid = runtime.getCurrentScript().getParameter("custscript_json_fileid"); main.sleep(40000); var mapinternal = main.findprocessfiles(processfolderid, false); var contextfile = file.load({ id: mapinternal }); var contextContent = contextfile.getContents(); var contextContent = JSON.parse(contextContent); //log.debug('contextContent', contextContent) var contextobj = JSON.parse(contextContent) var operation = contextobj.contextdetails.operation; var recordtype = contextobj.contextdetails.recordtype; if (operation == "create" || operation == "update") { // log.debug('enter create') var processFilles = main.findprocessfiles(processfolderid, true); //log.debug("processFilles", processFilles); var fileContent = main.setupProccessfiles(processFilles); } else if (operation == "delete") { //log.debug("contextobj.contextdetails.deletedetail", contextobj.deletedetail) var fileContent = main.searchRecord(contextobj.contextdetails.recordtype, contextobj.deletedetail); } else if (operation == "deleteduplicate") { // log.debug("contextobj.contextdetails.deletedetail", contextobj.deletedetail) // log.debug("contextobj.contextdetails.recordtype", contextobj.contextdetails.recordtype) var fileContent = main.searchDuplicateRecord(contextobj.contextdetails.recordtype, contextobj.deletedetail); } try { // log.debug("fileContent", fileContent.length); } catch (e) { log.debug('error', e) } //log.debug("fileContent", fileContent) return fileContent; }, sleep: function (milliseconds) { var date = Date.now(); var currentDate = null; do { currentDate = Date.now(); } while (currentDate - date < milliseconds); }, /*Concatnate the Arrays from Chunks Folder */ setupProccessfiles: function (filefolder) { var len = filefolder.length; var array = []; for (var i = 0; i < len; i++) { if (filefolder[i].name != "scriptcontext.txt") { var processFile = file.load({ id: filefolder[i].internalid }); var fileContent = processFile.getContents(); var temparray = JSON.parse(fileContent); array.push(temparray); } } var fullarray = [].concat.apply([], array); return fullarray; }, /*If the process is delete duplicates, then use the ESN number to find the internalid*/ searchDuplicateRecord: function (recordtype, date) { //log.debug('date', date); var filterarry = [] if (date == "all") { } else { filterarry.push(["created", "within", date]) } var SearchObj = search.create({ type: recordtype, columns: [ search.createColumn({ name: "custrecord_jj_esn", label: "ESN" }), search.createColumn({ name: "internalid", label: "Internal ID" }) ], filters: filterarry }); var searchPageRanges = SearchObj.runPaged({ pageSize: 1000 }); var internalids = []; var esnNum = { }; for (var i = 0; i < searchPageRanges.pageRanges.length; i++) { searchPageRanges.fetch({ index: i }).data.forEach(function (result) { var esn_number = result.getValue("custrecord_jj_esn"); var internal_id = result.getValue("internalid"); try { esnNum[esn_number].push(internal_id); } catch (e) { esnNum[esn_number] = [] esnNum[esn_number].push(internal_id); } return true; }); } Object.keys(esnNum).forEach(function (key) { for (var i = 0; i < esnNum[key].length; i++) { if (esnNum[key][i + 1]) { internalids.push(esnNum[key][i + 1]) } } }); // log.debug('internalids', internalids) // log.debug("esnNum", esnNum); // log.debug("duplciatearray length", internalids.length); return internalids; }, /*If Process is Delete then get the internalids */ searchRecord: function (recordtype, date) { var filterarry = [] if (date == "all") { } else { filterarry.push(["created", "within", date]) } // log.debug("date", date); var SearchObj = search.create({ type: recordtype, columns: [ search.createColumn({ name: "internalid", label: "Internal ID" }) ], filters: filterarry }); var searchPageRanges = SearchObj.runPaged({ pageSize: 1000 }); var internalids = []; for (var i = 0; i < searchPageRanges.pageRanges.length; i++) { searchPageRanges.fetch({ index: i }).data.forEach(function (result) { internalids.push(result.getValue("internalid")); return true; }); } //log.debug("deletearray length", internalids.length); return internalids; }, /*Find JSON chunks From the Folder For Processing */ findprocessfiles: function (folderid, flag) { var fileSearchObj = search.create({ type: "file", filters: [ ["folder", "anyof", folderid] ], columns: [ search.createColumn({ name: "internalid", label: "Internal ID" }), search.createColumn({ name: "name", sort: search.Sort.ASC, label: "Name" }) ] }); var searchResultCount = fileSearchObj.runPaged().count; if (flag == true) { var processarray = []; fileSearchObj.run().each(function (result) { var tempobj = { }; tempobj.internalid = result.getValue("internalid"); tempobj.name = result.getValue("name"); processarray.push(tempobj); return true; }); return processarray; } else { var mapinternal; fileSearchObj.run().each(function (result) { if (result.getValue("name") == "scriptcontext.txt") { mapinternal = result.getValue("internalid"); } return true; }); return mapinternal; } }, /*Reduce Function of map Reduce */ reduce: function (context) { var processfolderid = runtime.getCurrentScript().getParameter("custscript_json_fileid"); var mapinternal = main.findprocessfiles(processfolderid, false); //log.debug('mapinternal',mapinternal) var contextfile = file.load({ id: mapinternal }); var contextContent = contextfile.getContents(); // log.debug("contextContent", contextContent) var contextContent = JSON.parse(contextContent); var contextobj = JSON.parse(contextContent) var operation = contextobj.contextdetails.operation; var recordtype = contextobj.contextdetails.recordtype; var recordname = contextobj.contextdetails.recordname; var mapobj = contextobj.mapobj; //log.debug("mapobj", mapobj) var currentobj = context.values; // log.debug("currentobj", currentobj) var convertedfile = JSON.parse(currentobj[0]); if (convertedfile.length == 1) { //1 if the input file is CSV one. convertedfile = convertedfile[0].split(',') } // log.debug("convertedfile", convertedfile) // log.debug('recordname', recordname) if (operation == "create") { if (recordname != "Spiff Amount") { if (recordname != "Residual Monthly") { var intrId; if (recordtype == "customrecord_jj_tracfone_activations") { var tracfone_record = true; var simno_tracfone = convertedfile[mapobj['custrecordjj_tra_sim']] // log.debug('simno_tracfone', simno_tracfone) var customrecord_jj_tracfone_activationsSearchObj = search.create({ type: "customrecord_jj_tracfone_activations", filters: [ ["custrecordjj_tra_sim", "is", simno_tracfone] ], columns: [ search.createColumn({ name: "internalid", label: "Internal ID" }) ] }); var searchResult = customrecord_jj_tracfone_activationsSearchObj.run().getRange({ start: 0, end: 1 }); for (var j = 0; j < searchResult.length; j++) { intrId = searchResult[j].getValue({ name: "internalid" }); } } // log.debug('tracfone_record', tracfone_record) // log.debug('intrId', intrId) if (intrId && tracfone_record) { //log.debug('duplicate record') } else { main.createrecord(recordtype, mapobj, convertedfile, processfolderid); } } else { //log.debug("testing loop residual amount") } } else { //log.debug("testing loop spiff amount") } } else if (operation == "delete") { // log.debug("convertedfile", convertedfile); main.deleteRecord(recordtype, convertedfile); } else if (operation == "deleteduplicate") { // log.debug("convertedfile duplicate", convertedfile); main.deleteRecord(recordtype, convertedfile); } else if (operation == "update") { var intrId; if (recordtype == "customrecord_jj_tracfone_activations") { var tracfone_record = true; var simno_tracfone = convertedfile[mapobj['custrecordjj_tra_sim']] var customrecord_jj_tracfone_activationsSearchObj = search.create({ type: "customrecord_jj_tracfone_activations", filters: [ ["custrecordjj_tra_sim", "is", simno_tracfone] ], columns: [ search.createColumn({ name: "internalid", label: "Internal ID" }) ] }); var searchResult = customrecord_jj_tracfone_activationsSearchObj.run().getRange({ start: 0, end: 1 }); for (var j = 0; j < searchResult.length; j++) { intrId = searchResult[j].getValue({ name: "internalid" }); } if (searchResult.length <= 0) { convertedfile.push("SIM Number is not present"); var folderid; var init = main.checkforfolder(processfolderid); if (init == true) { folderid = main.createfolder(processfolderid); } else { folderid = init; } main.errorlog(processfolderid, convertedfile, folderid); // log.debug("duplicate ESN ", esnno) return true; } } if (intrId && tracfone_record) { // log.debug('simno_tracfone : ' + simno_tracfone, 'intrId: ' + intrId); main.updateRecord(recordtype, mapobj, convertedfile, processfolderid, intrId, recordname); } } }, /*To Find Error Files */ finderrorfiles: function (errorfolderid) { // log.debug("errorfolderid", errorfolderid) var fileSearchObj = search.create({ type: "folder", filters: [ ["name", "is", errorfolderid] ], columns: [ search.createColumn({ name: "internalid", label: "Internal ID" }), search.createColumn({ name: "name", sort: search.Sort.ASC, label: "Name" }) ] }); var resultSet = fileSearchObj.run(); var firstResult = resultSet.getRange({ start: 0, end: 1 })[0]; // log.debug('firstResult',firstResult) var value = firstResult.getValue(resultSet.columns[0]); var fileError = search.create({ type: "file", filters: [ ["folder", "anyof", value] ], columns: [ search.createColumn({ name: "internalid", label: "Internal ID" }), search.createColumn({ name: "name", sort: search.Sort.ASC, label: "Name" }) ] }) var processarray = []; fileError.run().each(function (result) { var tempobj = { }; tempobj.internalid = result.getValue("internalid"); tempobj.name = result.getValue("name"); processarray.push(tempobj); return true; }); var len = processarray.length; var array = []; for (var i = 0; i < len; i++) { if (processarray[i].name != "scriptcontext.txt") { var processFile = file.load({ id: processarray[i].internalid }); var fileContent = processFile.getContents(); array.push(fileContent); } } // var fullarray = [].concat.apply([], array); return array; }, /*Error Folder For Logging and send Email*/ createfolder: function (data) { var folderRec = record.create({ type: record.Type.FOLDER, isDynamic: true }); folderRec.setValue({ fieldId: 'parent', value: 10189 }); folderRec.setValue({ fieldId: 'name', value: data }); var folderId = folderRec.save({ enableSourcing: true, ignoreMandatoryFields: true }); return folderId; }, /*To check whether there is any folder existing for error log*/ checkforfolder: function (name) { var folderSearchObj = search.create({ type: "folder", filters: [ ["name", "is", name] ], columns: [ search.createColumn({ name: "internalid", label: "internalid" }) ] }); var searchResultCount = folderSearchObj.runPaged().count; if (searchResultCount < 1) { return true } else { var internalid; folderSearchObj.run().each(function (result) { internalid = result.getValue("internalid"); return true; }); return internalid; } }, /* Create the error file in the error error log */ createfile: function (name, folderid, convertedfile) { var folderinternal; if (folderid > 0) { folderinternal = folderid; } else { folderinternal = 10189 } var fileObj = file.create({ name: name + '.txt', fileType: file.Type.PLAINTEXT, contents: convertedfile.toString(), folder: folderinternal, isOnline: true }); var fileid = fileObj.save(); return fileid; }, /*Delete Process Actions */ deleteRecord: function (type, internalid) { record.delete({ type: type, id: internalid }); }, /*Update record actions Process */ updateRecord: function (recordtype, mapobj, convertedfile, processfolderid, intrId, recordname) { if (recordtype == "customrecord_jj_tracfone_activations") { if (recordname != "Spiff Amount") { if (recordname != "Residual Monthly") { var value_xl = convertedfile[mapobj['custrecord_jj_plan']] //log.debug('convertedfile[mapobj[custrecord_ao_spiff_paid_date]]', convertedfile[mapobj['custrecord_ao_spiff_paid_date']]) var activationMonth_xl = main.doValidations(convertedfile[mapobj['custrecord_ao_spiff_paid_date']], recordtype) // log.debug('activationMonth_xl', activationMonth_xl) if (activationMonth_xl) { var formattedDateString = activationMonth_xl } var commission = convertedfile[mapobj['custrecord_ao_last_resid_amount']] var usedDate = convertedfile[mapobj['custrecord_ao_last_paid_resid']] if (usedDate) { var formattedDateStringResidue = main.doValidations(usedDate, recordtype) } var cust_load = record.load({ type: 'customrecord_jj_tracfone_activations', id: intrId /*, isDynamic: true */ }); cust_load.setValue({ fieldId: "custrecord_jj_plan", value: value_xl }); if (activationMonth_xl) { cust_load.setValue({ fieldId: "custrecord_ao_spiff_paid_amouunt", value: commission }); cust_load.setText({ fieldId: "custrecord_ao_spiff_paid_date", text: formattedDateString }); } if (usedDate) { cust_load.setValue({ fieldId: "custrecord_ao_last_resid_amount", value: commission }); cust_load.setText({ fieldId: "custrecord_ao_last_paid_resid", text: formattedDateStringResidue }); } var id = cust_load.save({ enableSourcing: true }); log.debug("Record updated ", id); } else { //log.debug('enter resid loop') var objRecord = record.load({ type: 'customrecord_jj_tracfone_activations', id: intrId }); for (var key in mapobj) { if (key != "-") { var currentValue = main.doValidations(convertedfile[mapobj[key]], recordtype); // log.debug('currentValue', currentValue) if (currentValue.indexOf("$") > -1) { var temp = currentValue.split('$') currentValue = temp[1] } // log.debug('Updated currentValue', currentValue) try { //log.debug('enter try key', key) objRecord.setText({ fieldId: key, text: currentValue.toString().trim() }); var simEarning = objRecord.getValue({ fieldId: 'custrecord23' }) if (key == 'custrecord_ao_last_resid_amount') { simEarning = simEarning + Number(currentValue) objRecord.setValue({ fieldId: 'custrecord23', value: simEarning.toString().trim() }); } } catch (e) { try { objRecord.setValue({ fieldId: key, value: currentValue.toString().trim() }); } catch (error) { // log.debug("Error for creating record", error.message) convertedfile.push(error.message); // log.debug("Econvertedfile", convertedfile) var folderid; var init = main.checkforfolder(processfolderid); if (init == true) { folderid = main.createfolder(processfolderid); } else { folderid = init; } main.errorlog(processfolderid, convertedfile); return error; } } } } var id = objRecord.save({ enableSourcing: false }); log.debug("Record updated ", id); } } else { log.debug('testing update another') var objRecord = record.load({ type: 'customrecord_jj_tracfone_activations', id: intrId /*, isDynamic: true */ }); for (var key in mapobj) { if (key != "-") { var currentValue = main.doValidations(convertedfile[mapobj[key]], recordtype); log.debug('currentValue', currentValue) if (currentValue.indexOf("$") > -1) { var temp = currentValue.split('$') currentValue = temp[1] } log.debug('Updated currentValue', currentValue) /*var currentDate = main.doValidations(convertedfile[mapobj['custrecord_ao_spiff_paid_date']], recordtype);*/ try { log.debug('enter try key', key) /*objRecord.setValue({ fieldId: 'custrecord_ao_spiff_paid_amouunt', value: currentValue.toString().trim() }); objRecord.setText({ fieldId: 'custrecord_ao_spiff_paid_date', text: currentDate });*/ objRecord.setText({ fieldId: key, text: currentValue.toString().trim() }); } catch (e) { try { objRecord.setValue({ fieldId: key, value: currentValue.toString().trim() }); } catch (error) { // log.debug("Error for creating record", error.message) convertedfile.push(error.message); // log.debug("Econvertedfile", convertedfile) var folderid; var init = main.checkforfolder(processfolderid); if (init == true) { folderid = main.createfolder(processfolderid); } else { folderid = init; } main.errorlog(processfolderid, convertedfile); return error; } /* }*/ } } } var id = objRecord.save({ enableSourcing: false }); log.debug("Record updated ", id); } } }, /*Create record actions Process */ createrecord: function (recordtype, mapobj, convertedfile, processfolderid) { log.debug("enter create fun") log.debug("mapobj", mapobj) var duplicate = false; if (convertedfile.length > 0) { var objRecord = record.create({ type: recordtype, isDynamic: true }); for (var key in mapobj) { if (key != "-") { log.debug('key', key) log.debug('convertedfile[mapobj[key]]', convertedfile[mapobj[key]]) var currentValue = main.doValidations(convertedfile[mapobj[key]], recordtype); try { objRecord.setValue({ fieldId: key, value: currentValue.toString().trim() }); } catch (e) { try { objRecord.setText({ fieldId: key, text: currentValue.toString().trim() }); } catch (error) { // log.debug("Error for creating record", error.message) convertedfile.push(error.message); // log.debug("Econvertedfile", convertedfile) var folderid; var init = main.checkforfolder(processfolderid); if (init == true) { folderid = main.createfolder(processfolderid); } else { folderid = init; } main.errorlog(processfolderid, convertedfile); return error; } } } }; log.debug('testing record type', recordtype) if (recordtype == "customrecord_jj_branded_handset") { var simno = convertedfile[mapobj['custrecord_jj_sim']] var esnno = convertedfile[mapobj['custrecord_jj_esn']] duplicate = main.checksim(simno, esnno, processfolderid, convertedfile); var tectraId = objRecord.getValue({ fieldId: 'custrecord_jj_branded_tcetraid' }); var customerDetails = main.findCustomerdetails(tectraId, "custentity1"); objRecord.setValue({ fieldId: "custrecord_jj_customer", value: customerDetails.customerId }); objRecord.setValue({ fieldId: "custrecord_jj_sales_rep", value: customerDetails.salesreppartner }); objRecord.setValue({ fieldId: "custrecord_jj_subof_sales_partner", value: customerDetails.subof }); } else if (recordtype == "customrecord_jj_route_run") { var tectraId = objRecord.getValue({ fieldId: 'custrecord_jj_tcetraid' }); var customerDetails = main.findCustomerdetails(tectraId, "custentity1"); objRecord.setValue({ fieldId: "custrecord_jj_customerid", value: customerDetails.customerId }); objRecord.setValue({ fieldId: "custrecord_jj_sales_rep_route", value: customerDetails.salesreppartner }); objRecord.setValue({ fieldId: "custrecord_jj_subof_route", value: customerDetails.subof }); } else if (recordtype == "customrecord_jj_qpay_marketplace_details") { var incommId = objRecord.getValue({ fieldId: 'custrecord_jj_branchid' }); var customerDetails = main.findCustomerdetails(incommId, "custentityincomeexclusiveid"); objRecord.setValue({ fieldId: "custrecord_qpay_customerid", value: customerDetails.customerId }); objRecord.setValue({ fieldId: "custrecord_jj_sales_rep_maeket", value: customerDetails.salesreppartner }); objRecord.setValue({ fieldId: "custrecord_jj_subof_market", value: customerDetails.subof }); } else if (recordtype == "customrecord_jj_qpaydetail_transaction") { /*as per discusions on 07-07 parent id and parent name need not to be set*/ var incommId = objRecord.getValue({ fieldId: 'custrecord_jj_qpaydetail_incommid' }); var parentId = objRecord.getValue({ fieldId: 'custrecord_jj_details_parentid' }); //getting the parent name var parentName = objRecord.getValue({ fieldId: 'custrecord_jj_qpaydetail_parent_nm' }); var customerDetails = main.findCustomerdetails(incommId, "custentityincomeexclusiveid"); objRecord.setValue({ fieldId: "custrecord_jj_qpaydetail_custid", value: customerDetails.customerId }); objRecord.setValue({ fieldId: "custrecord_jj_sales_rep_qpay", value: customerDetails.salesreppartner }); objRecord.setValue({ fieldId: "custrecord_jj_subof_salesrep", value: customerDetails.subof }); // set the parent id id in the customer record /* var parId = record.submitFields({ type: record.Type.CUSTOMER, id: customerDetails.customerId, values: { custentity_jj_parentaccountid: parentId, custentity_jj_parentname: parentName } });*/ } else if (recordtype == "customrecord223") { var tectraId = objRecord.getValue({ fieldId: 'custrecord6' }); var customerDetails = main.findCustomerdetails(tectraId, "custentity1"); // log.debug(tectraId, customerDetails); objRecord.setValue({ fieldId: "custrecord_jj_customer_vidapay", value: customerDetails.customerId }); objRecord.setValue({ fieldId: "custrecord_jj_salesrep_vidapay", value: customerDetails.salesreppartner }); objRecord.setValue({ fieldId: "custrecord_jj_subof_vidapay", value: customerDetails.subof }); } else if (recordtype == "customrecord_jj_tracfone_activations") { log.debug('recordtype checksim', recordtype) var tectraId = objRecord.getValue({ fieldId: 'custrecord_jj_trc_tsp_id' }); var partnetID = objRecord.getValue({ fieldId:"custrecord_jj_tra_partner_id" }) log.debug("partnetID",partnetID) if(partnetID == "IAS"){ var searchField = "custentityincomeexclusiveid" }else{ var searchField = "custentity1" } log.debug("searchField",searchField) log.debug("tectraId",tectraId) var customerDetails = main.findCustomerdetails(tectraId, searchField); log.debug("customerDetails",customerDetails) objRecord.setValue({ fieldId: "custrecord_jj_tracfone_activa_cusid", value: customerDetails.customerId }); objRecord.setValue({ fieldId: "custrecord_jj_sales_rep_tracfone", value: customerDetails.salesreppartner }); /* objRecord.setValue({ fieldId: "custrecord_jj_subof_sales_partner", value: customerDetails.subof });*/ } else if (recordtype == "customrecord_jj_marketplace_sales_order") { /* MTW-252 This else if part is done for the record creation for the marketplace integration*/ var simNumber = convertedfile[7]; duplicate = main.detectDuplicateSim(recordtype, simNumber); log.debug("duplicate", duplicate) if (duplicate != false) { log.debug("reach leve2") main.updateMarketPlaceRec(convertedfile, duplicate, recordtype) } else { log.debug("reach level") log.debug("convertedfile[0]: ",convertedfile[0]) // var convertedDate = main.dateValidation(JSON.stringify(convertedfile[0])) // log.debug("convertedDate: ",convertedDate) // var orderedDate = format.format({ // value: convertedDate, // type:format.Type.DATE // }) // log.debug("orderedDate: ",orderedDate) objRecord.setText({ fieldId: "custrecord_jj_date_ordered", text: convertedfile[0] }); objRecord.setValue({ fieldId: "custrecord_jj_order", value: convertedfile[1] }); objRecord.setValue({ fieldId: "custrecord_jj_product_id", value: convertedfile[2] }); objRecord.setValue({ fieldId: "custrecord_jj_marketplace_product_name", value: convertedfile[3] }); objRecord.setValue({ fieldId: "custrecord_jj_marketplace_dealer_cost", value: convertedfile[7] }); objRecord.setValue({ fieldId: "custrecord_jj_current_parent_commission", value: convertedfile[8] }); objRecord.setValue({ fieldId: "custrecord_jj_sum_of_sub_parent_commissi", value: convertedfile[9] }); objRecord.setValue({ fieldId: "custrecord_jj_marketplace_sim_esn", value: convertedfile[12] }); objRecord.setValue({ fieldId: "custrecord_jj_part_number", value: convertedfile[13] }); log.debug("convertedfile[15]", convertedfile[13]) objRecord.setValue({ fieldId: "custrecord_jj_merchant_account_id", value: convertedfile[20] }); var customerDetails = main.findCustomerdetails(convertedfile[20], "custentity1"); log.debug("customerDetails", customerDetails) objRecord.setValue({ fieldId: "custrecord_jj_merchant_name", value: customerDetails.customerId }); log.debug("convertedfile[24]", convertedfile[29]) objRecord.setText({ fieldId: "custrecord_jj_marketplace_date_shipped", text: convertedfile[29]//new Date(main.dateValidation(convertedfile[22])) }); objRecord.setValue({ fieldId: "custrecord_jj_marketplace_tracking_numbe", value: convertedfile[30] }); log.debug("convertedfile[10]", convertedfile[16]) objRecord.setValue({ fieldId: "custrecord_jj_marketplace_active_status", value: convertedfile[16] }); } } else if (recordtype == "customrecord_mw_tracfone_residual_month") { var sim = objRecord.getValue({ fieldId: 'custrecord_jj_trc_mnthly_sim' }); // log.debug("sim", sim) try { var activationsSearchObj = search.create({ type: 'customrecord_jj_tracfone_activations', columns: [{ name: "custrecord_jj_tracfone_activa_cusid" }, { name: 'custrecord_jj_sales_rep_tracfone' }, { name: 'custrecord_jj_city' }, { name: 'custrecord_jj_state' }], filters: ["custrecordjj_tra_sim", "is", sim] }); var activationsResultCount = activationsSearchObj.runPaged().count; if (activationsResultCount == 1) { //then there will be 1 sim in tracfone activation record var searchResult = activationsSearchObj.run().getRange({ start: 0, end: 1 }); // log.debug("searchResult", searchResult); var custID = searchResult[0].getValue({ name: 'custrecord_jj_tracfone_activa_cusid' }); // log.debug("custID from Tracfone", custID); if (custID != '') { var searchResultForCustomer = main.searchForCustomer(custID); objRecord.setValue({ fieldId: "custrecord_mw_tracfone_customer", value: custID }); } // log.debug("searchResultForCustomer", searchResultForCustomer); var salesRepTrcMnthly = searchResult[0].getText({ name: 'custrecord_jj_sales_rep_tracfone' }); var cityTrcMnthly = searchResult[0].getValue({ name: 'custrecord_jj_city' }); var stateTrcMnthly = searchResult[0].getValue({ name: 'custrecord_jj_state' }); } objRecord.setValue({ fieldId: "custrecord_jj_sales_name", value: salesRepTrcMnthly }); objRecord.setValue({ fieldId: "custrecord_jj_trc_mnthly_city", value: cityTrcMnthly }); objRecord.setValue({ fieldId: "custrecord_jj_trc_mnthly_state", value: stateTrcMnthly }); objRecord.setValue({ fieldId: "custrecord_jj_parent_name", value: searchResultForCustomer.parentName }); objRecord.setValue({ fieldId: "custrecord_jj_parent_id", value: searchResultForCustomer.parentID }); objRecord.setValue({ fieldId: "custrecord_incomm_id", value: searchResultForCustomer.incommId }); objRecord.setValue({ fieldId: "custrecordcustrecord_tcetra_id", value: searchResultForCustomer.tectraId }); } catch (e) { log.debug("e", e); } } } if (duplicate == false || duplicate == null) { var id = objRecord.save({ enableSourcing: true }); log.debug("Record Created ", id); } else { log.debug("duplicate ", duplicate); } }, /* MTW-252 The function for check duplicate sim number */ detectDuplicateSim: function (recordtype, simNumber) { var customrecord_jj_marketplace_sales_orderSearchObj = search.create({ type: recordtype, filters: [ ["custrecord_jj_marketplace_sim_esn", "is", simNumber] ], columns: [ search.createColumn({ name: "internalid", label: "Internal ID" }) ] }); var searchResultCount = customrecord_jj_marketplace_sales_orderSearchObj.runPaged().count; var recordIdVal = null; if (searchResultCount > 0) { customrecord_jj_marketplace_sales_orderSearchObj.run().each(function (result) { recordIdVal = result.getValue({ name: "internalid", label: "Internal ID" }) return false; }); return recordIdVal; } else { return false; } }, /* MTW-252 The function for update marketplace record */ updateMarketPlaceRec: function (convertedfile, marketPlaceDuplicate, recordtype) { var updateRecord = record.load({ type: recordtype, id: marketPlaceDuplicate, isDynamic: true }); updateRecord.setText({ fieldId: "custrecord_jj_date_ordered", text: convertedfile[0]//new Date(main.dateValidation(convertedfile[0])) }); updateRecord.setValue({ fieldId: "custrecord_jj_order", value: convertedfile[1] }); updateRecord.setValue({ fieldId: "custrecord_jj_product_id", value: convertedfile[2] }); updateRecord.setValue({ fieldId: "custrecord_jj_marketplace_product_name", value: convertedfile[3] }); updateRecord.setValue({ fieldId: "custrecord_jj_marketplace_dealer_cost", value: convertedfile[7] }); updateRecord.setValue({ fieldId: "custrecord_jj_current_parent_commission", value: convertedfile[8] }); updateRecord.setValue({ fieldId: "custrecord_jj_sum_of_sub_parent_commissi", value: convertedfile[9] }); updateRecord.setValue({ fieldId: "custrecord_jj_marketplace_sim_esn", value: convertedfile[12] }); updateRecord.setValue({ fieldId: "custrecord_jj_part_number", value: convertedfile[13] }); updateRecord.setValue({ fieldId: "custrecord_jj_merchant_account_id", value: convertedfile[14] }); var customerDetails = main.findCustomerdetails(convertedfile[14], "custentity1"); log.debug("customerDetails", customerDetails) updateRecord.setValue({ fieldId: "custrecord_jj_merchant_name", value: customerDetails.customerId }); updateRecord.setText({ fieldId: "custrecord_jj_marketplace_date_shipped", text: convertedfile[29]//new Date(main.dateValidation(convertedfile[22])) }); updateRecord.setValue({ fieldId: "custrecord_jj_marketplace_tracking_numbe", value: convertedfile[30] }); updateRecord.setValue({ fieldId: "custrecord_jj_marketplace_active_status", value: convertedfile[16] }); var recid = updateRecord.save({ enableSourcing: true }); log.debug("Record updated ", id); }, /* MTW-252 The function for validating date field for date field setvalue maketplace integration */ dateValidation: function (datevalue) { var dd = new Date(datevalue).getDate() var mm = new Date(datevalue).getMonth() var yy = new Date(datevalue).getFullYear() var datestrVal = dd + '/' + mm + '/' + yy; log.debug("datestrVal: ",datestrVal) return datestrVal; }, /* create a search in customer record to find the corresponding customer according to the tcetra id*/ /*Route Run and Branded Handset*/ findCustomerdetails: function (tectraId, searchField) { var customerSearchObj = search.create({ type: "customer", filters: [ [searchField, "contains", tectraId], "AND", ["subsidiary", "anyof", "2"] ], columns: [searchField, "internalid"] }); var searchResultCount = customerSearchObj.runPaged().count; log.debug("searchResultCount",searchResultCount) if (searchResultCount <= 0) { customerSearchObj = search.create({ type: "customer", filters: [ [searchField, "contains", tectraId] ], columns: [searchField, "internalid"] }); searchResultCount = customerSearchObj.runPaged().count; // log.debug("searchResultCount insidfa", searchResultCount); } // var searchResultCount = customerSearchObj.runPaged().count; var returnObj = { }; customerSearchObj.run().each(function (result) { // get the customer id returnObj.customerId = result.getValue('internalid'); // To get the sales rep partner id from the customer record var lookupfieldofpartner = search.lookupFields({ type: 'customer', id: returnObj.customerId, columns: ['partner'] }); if (lookupfieldofpartner.partner[0]) { returnObj.salesreppartner = lookupfieldofpartner.partner[0].value; } // to get parent id from partner record var lookupfieldofsub = search.lookupFields({ type: 'partner', id: returnObj.salesreppartner, columns: ['parent'] }); if (lookupfieldofsub.parent[0]) { returnObj.subof = lookupfieldofsub.parent[0].value; } }); return returnObj; }, checksim: function (simno, esnno, processfolderid, convertedfile) { var branded_handset_search_sim = search.create({ type: "customrecord_jj_branded_handset", filters: [ ["custrecord_jj_sim", "is", simno] ], columns: [ search.createColumn({ name: "id", sort: search.Sort.ASC, label: "ID" }), search.createColumn({ name: "custrecord_jj_customer", label: "Customer" }), search.createColumn({ name: "custrecord_jj_sim", label: "SIM" }), search.createColumn({ name: "custrecord_jj_esn", label: "ESN" }), search.createColumn({ name: "custrecord_jj_branded_tcetraid", label: "Tcetra Id" }) ] }); var searchResultCountSim = branded_handset_search_sim.runPaged().count; // log.debug("Brandend Handset Sim Search Count", searchResultCountSim); if (searchResultCountSim > 0) { convertedfile.push("Duplicate Sim Number"); var folderid; var init = main.checkforfolder(processfolderid); if (init == true) { folderid = main.createfolder(processfolderid); } else { folderid = init; } main.errorlog(processfolderid, convertedfile); // log.debug("duplicate SIM ", simno) return true; } else { var branded_handset_search_esn = search.create({ type: "customrecord_jj_branded_handset", filters: [ ["custrecord_jj_esn", "is", esnno] ], columns: [ // search.createColumn({ // name: "id", // sort: search.Sort.ASC, // label: "ID" // }), search.createColumn({ name: "custrecord_jj_customer", label: "Customer" }), search.createColumn({ name: "custrecord_jj_sim", label: "SIM" }), search.createColumn({ name: "custrecord_jj_esn", label: "ESN" }), search.createColumn({ name: "custrecord_jj_branded_tcetraid", label: "Tcetra Id" }) ] }); var searchResultCountESN = branded_handset_search_esn.runPaged().count; // log.debug("Brandend Handset ESN Search Count", searchResultCountESN); // customrecord_jj_branded_handsetSearchObj.run().each(function(result){ // // .run().each has a limit of 4,000 results // return true; // }); if (searchResultCountESN > 0) { convertedfile.push("Duplicate ESN Number"); var folderid; var init = main.checkforfolder(processfolderid); if (init == true) { folderid = main.createfolder(processfolderid); } else { folderid = init; } main.errorlog(processfolderid, convertedfile); // log.debug("duplicate ESN ", esnno) return true; } } return false }, searchForCustomer: function (custID) { var obj = { }; var customerSearchObj = search.create({ type: "customer", filters: [ ["internalidnumber", "equalto", custID] ], columns: [{ name: "custentity_jj_parentname" }, { name: "custentity_jj_parentaccountid" }, { name: "custentity1" }, { name: "custentityincomeexclusiveid" }] }); var searchResultCount = customerSearchObj.runPaged().count; if (searchResultCount > 0) { var searchResult1 = customerSearchObj.run().getRange({ start: 0, end: 1 }); // log.debug("searchResult1",searchResult1); obj.parentName = searchResult1[0].getValue({ name: 'custentity_jj_parentname' }); // log.debug("parentName",obj.parentName); obj.parentID = searchResult1[0].getValue({ name: 'custentity_jj_parentaccountid' }); obj.incommId = searchResult1[0].getValue({ name: 'custentityincomeexclusiveid' }); obj.tectraId = searchResult1[0].getValue({ name: 'custentity1' }); // log.debug("parentID",obj.parentID); } // log.debug("obj",obj); return obj; }, /*Delete JSON chunks Folder after the Import Process */ folderdelete: function (mapinternal) { var processfolderid = runtime.getCurrentScript().getParameter("custscript_json_fileid"); var processarray = main.findprocessfiles(processfolderid, true); for (i = 0; i < processarray.length; i++) { file.delete({ id: processarray[i].internalid }); } file.delete({ id: mapinternal }); var folderdelete = record.delete({ type: "folder", id: processfolderid }); }, /*To create an folder that contain all the errors */ errorlog: function (processfolderid, convertedfile, folderid) { var filename = Date.now(); // var folderid; // var init = main.checkforfolder(processfolderid); // if (init == true) { // folderid = main.createfolder(processfolderid); // } else { // folderid = init; // // } var processfileid = main.createfile(filename, folderid, convertedfile); }, /*Check whether the input string is Date or number or String */ /*if date format is mm/dd/yyy*/ doValidations: function (string, recordtype) { /*check whether inputed data is date*/ //log.debug("string date in dovalidation", string); var inputString = main.isDate(string); //log.debug("inputString", inputString) if (inputString == false) { if (isNaN(string)) { return string; } else { if (string == null || string == "") { return ""; } else { return Number(string); } } } else { if (recordtype == "customrecord_mw_tracfone_residual_month") { if (string.indexOf("-") > 0) { var dateArray = string.split("-"); var datestr = dateArray[1] + '/' + dateArray[0] + '/' + dateArray[2]; // log.debug("date last of do validation", datestr); return datestr; } else { return string } } else if (recordtype == "customrecord_jj_tracfone_activations") { if (string.indexOf("-") > 0) { var dateArray = string.split("-"); var datestr = dateArray[1] + '/' + dateArray[0] + '/' + dateArray[2]; // log.debug("date last of do validation", datestr); return datestr; } else { return string } } var string = string.replace(/-/g, "/"); if (new Date(string.toString()) == "Invalid Date") { return string; } else { var today = new Date(string); // log.debug("today", today) var dd = today.getDate(); var mm = today.getMonth() + 1; var yyyy = today.getFullYear(); if (yyyy < 2000) yyyy = yyyy + 100; // if (mm < 10) { // mm = mm; // } var datestr = mm + '/' + dd + '/' + yyyy; // log.debug("date last of do validation", datestr) return datestr; } } }, /*To find whether the input string is date or not */ isDate: function (value) { var dateFormat; if (toString.call(value) === '[object Date]') { return true; } if (typeof value.replace === 'function') { value.replace(/^\s+|\s+$/gm, ''); } dateFormat = /(^\d{1,4}[\.|\\/|-]\d{1,2}[\.|\\/|-]\d{1,4})?$/; return dateFormat.test(value); }, /*Summary function Of map reduce */ summarize: function (summary) { var errorfolderid = runtime.getCurrentScript().getParameter("custscript_json_fileid"); var errorfolder = main.finderrorfiles(errorfolderid); var processfolderid = runtime.getCurrentScript().getParameter("custscript_json_fileid"); var mapinternal = main.findprocessfiles(processfolderid, false); var contextfile = file.load({ id: mapinternal }); var contextContent = contextfile.getContents(); var contextContent = JSON.parse(contextContent); var contextobj = JSON.parse(contextContent); var operation = contextobj.contextdetails.operation; var emailaddr = contextobj.emailaddress; var recordtype = contextobj.contextdetails.recordtype; var recordname = contextobj.contextdetails.recordname; if (operation == "create") { if (errorfolder == null || errorfolder == "" || errorfolder == undefined) { var mailBody = main.createResponse(recordtype, recordname, "success"); email.send({ author: -5, recipients: emailaddr, //cc: ["PI:EMAIL:kenaa@example.comEND_PI"], subject: "IMPORT Completed For " + recordname, body: mailBody }); } else { main.errortocsv(contextobj, errorfolder); } } else if (operation == "delete") { var mailBody = main.createResponse(recordtype, recordname, "delete"); email.send({ author: -5, recipients: emailaddr, //cc: ["PI:EMAIL:kenaa@example.comEND_PI"], subject: "Succesfully Deleted the " + recordname, body: mailBody }); } else if (operation == "deleteduplicate") { var mailBody = main.createResponse(recordtype, recordname, "deleteduplicate"); email.send({ author: -5, recipients: emailaddr, //cc: ["PI:EMAIL:kenaa@example.comEND_PI"], subject: "Succesfully Deleted the Duplicate " + recordname, body: mailBody }); } else { if (errorfolder == null || errorfolder == "" || errorfolder == undefined) { var mailBody = main.createResponse(recordtype, recordname, "success"); email.send({ author: -5, recipients: emailaddr, //cc: ["PI:EMAIL:kenaa@example.comEND_PI"], subject: "IMPORT Completed For " + recordname, body: mailBody }); } else { main.errortocsv(contextobj, errorfolder); } } main.folderdelete(mapinternal); var pendingId = main.findPending(); // log.debug("pendingId", pendingId) if (pendingId != false) { var pendingFile = file.load({ id: pendingId }); var pendingContent = pendingFile.getContents(); var pendingContent = JSON.parse(pendingContent); // log.debug("pendingContent", pendingContent); // log.debug("pendingContent", pendingContent.custscript_json_fileid); main.scheduleanother(pendingContent.custscript_json_fileid, "", "", pendingContent); file.delete({ id: pendingId }); } }, /*Setup map reduce script*/ scheduleanother: function (fileid, mapid, mapfile, catchFile) { try { var scheduleScrptTask = task.create({ taskType: task.TaskType.MAP_REDUCE, scriptId: "customscript_mr_mapreducerecord", deploymentId: 'customdeploy_mr_mapreducerecord', params: { custscript_json_fileid: fileid, custscript_type: mapfile } }); scheduleScrptTask.submit(); /* var mapFileid = JSON.parse(mapid) var emailaddr = mapFileid.emailaddress; var recordtype = mapFileid.contextdetails.recordtype; var recordname = mapFileid.contextdetails.recordname; var mailBody = main.createResponse(recordtype, recordname); email.send({ author: -5, recipients: emailaddr, subject: "Import Process Succesfully Started for " + recordname, body: mailBody });*/ } catch (e) { log.debug("e in scheduleanother", e); var params = { custscript_json_fileid: fileid, custscript_type: mapfile } main.createfile(Date.now(), 26540, params); } }, findPending: function () { var fileSearchObj = search.create({ type: "file", filters: [ ["folder", "anyof", 26540] ], columns: [ search.createColumn({ name: "internalid", label: "Internal ID" }), search.createColumn({ name: "name", sort: search.Sort.ASC, label: "Name" }) ] }); var searchResultCount = fileSearchObj.runPaged().count; if (searchResultCount < 1) { return false } else { var internalid; fileSearchObj.run().each(function (result) { internalid = result.getValue("internalid"); return true; }); return internalid; } }, createResponse: function (recordtype, recordname, flag) { var htmlFile = file.load({ id: 39539 }); var htmlFilecontent = htmlFile.getContents(); if (flag == "success") { var htmlFilecontent1 = htmlFilecontent.replace("<-replacewithtype->", "Import Completed Successfully"); var htmlFilecontent2 = htmlFilecontent1.replace("<-ReplaceWithRecord->", "For Record : " + recordname); } else if (flag == "unsuccess") { var htmlFilecontent1 = htmlFilecontent.replace("<-replacewithtype->", "Import Completed With Some issues "); var htmlFilecontent2 = htmlFilecontent1.replace("<-ReplaceWithRecord->", "For Record " + recordname); } else if (flag == "delete") { var htmlFilecontent1 = htmlFilecontent.replace("<-replacewithtype->", "Succesfully Deleted The Record "); var htmlFilecontent2 = htmlFilecontent1.replace("<-ReplaceWithRecord->", "For Record " + recordname); } else if (flag == "deleteduplicate") { var htmlFilecontent1 = htmlFilecontent.replace("<-replacewithtype->", "Succesfully Deleted The Duplicate Record "); var htmlFilecontent2 = htmlFilecontent1.replace("<-ReplaceWithRecord->", "For Record " + recordname); } return htmlFilecontent2; }, errortocsv: function (contextobj, errorfolder) { try { // to get the data //To create the CSV file var XML_TO_PRINT = main.getXMLDataExcel(file, contextobj, errorfolder); var strXmlEncoded = encode.convert({ string: XML_TO_PRINT, inputEncoding: encode.Encoding.UTF_8, outputEncoding: encode.Encoding.BASE_64 }); var fileObj = file.create({ name: 'report.xls', fileType: file.Type.EXCEL, contents: strXmlEncoded }); var id = fileObj.save(); log.debug('id Of newly created CSV', id); var emailaddr = contextobj.emailaddress; var recordtype = contextobj.contextdetails.recordtype; var recordname = contextobj.contextdetails.recordname; var mailBody = main.createResponse(recordtype, recordname, "unsuccess"); email.send({ author: -5, recipients: emailaddr, //cc: ["PI:EMAIL:kenaa@example.comEND_PI"], subject: "CSV IMPORT Completed For Record", attachments: [fileObj], body: mailBody }); } catch (e) { log.debug("Err @ errortocsv", e.message); } }, getXMLDataExcel: function (file, contextobj, errorfolder) { var XML = ""; var TABLE = ""; var HEADING = ""; var x = 0, errArray = [], headingArray = [], i, contents, j; var myXMLFile = file.load({ id: '39548' }); var myXMLFile_value = myXMLFile.getContents(); headingArray = contextobj.csvColumns; errArray = errorfolder; headingArray.push("Error Message"); errArray.unshift(headingArray.toString()); // to get the total no.of err entries var errLength = errArray.length; var headingLength = headingArray.length; var strVar = ""; var headVar = ""; log.debug('errArray', errArray) log.debug('errLength', errLength) for (i = 0; i < errLength; i++) { var temparray = errArray[i].split(','); strVar += "<Row ss:AutoFitHeight=\"0\">"; for (j = 0; j < temparray.length; j++) { strVar += "<Cell><Data ss:Type=\"String\">" + temparray[j] + "<\/Data><\/Cell>"; } strVar += "<\/Row>"; } TABLE = TABLE + strVar; // HEADING = HEADING +headVar; XML = myXMLFile_value.replace('<!-- REPLACEWITHTABLEBODY -->', TABLE); return XML; } }; for (var key in main) { if (typeof main[key] === 'function') { main[key] = trycatch(main[key], key); } } function trycatch(myfunction, key) { return function () { try { return myfunction.apply(this, arguments); } catch (e) { log.debug("e in " + key, e); } } }; return main; });
/** * job.ext.getStatus.js * @description Get External Job Status * @module clv/job/getStatus * @NApiVersion 2.0 * @NScriptType Suitelet * @author Miquel Brazil <miquel@leprechaunpromotions.com> */ define(['N/https'], function (https) { function inspect(context) { context.response.setHeader({ name: 'Content-Type', value: 'application/json; charset=utf-8' }); context.response.write(JSON.stringify({ context: context, jobNumber: context.request.parameters.clvRefNum })); } return { onRequest: inspect } });
365
[{"tag": "EMAIL", "value": "miquel@leprechaunpromotions.com", "start": 168, "end": 199}]
true
1
/** * job.ext.getStatus.js * @description Get External Job Status * @module clv/job/getStatus * @NApiVersion 2.0 * @NScriptType Suitelet * @author Miquel Brazil <dycjh@example.com> */ define(['N/https'], function (https) { function inspect(context) { context.response.setHeader({ name: 'Content-Type', value: 'application/json; charset=utf-8' }); context.response.write(JSON.stringify({ context: context, jobNumber: context.request.parameters.clvRefNum })); } return { onRequest: inspect } });
true
/** * job.ext.getStatus.js * @description Get External Job Status * @module clv/job/getStatus * @NApiVersion 2.0 * @NScriptType Suitelet * @author Miquel Brazil <PI:EMAIL:dycjh@example.comEND_PI> */ define(['N/https'], function (https) { function inspect(context) { context.response.setHeader({ name: 'Content-Type', value: 'application/json; charset=utf-8' }); context.response.write(JSON.stringify({ context: context, jobNumber: context.request.parameters.clvRefNum })); } return { onRequest: inspect } });
/** * * @NApiVersion 2.0 * @NScriptType Suitelet * * Description: * @Last modified by: ankithravindran * */ define(['N/ui/serverWidget', 'N/email', 'N/runtime', 'N/search', 'N/record', 'N/https', 'N/log', 'N/redirect', 'N/format', 'N/url' ], function(ui, email, runtime, search, record, https, log, redirect, format, url) { var baseURL = 'https://1048144.app.netsuite.com'; if (runtime.envType == "SANDBOX") { baseURL = 'https://1048144-sb3.app.netsuite.com'; } var zee = 0; var role = runtime.getCurrentUser().role; if (role == 1000) { //Franchisee zee = runtime.getCurrentUser(); } function onRequest(context) { log.debug({ title: "context.request.method", details: context.request.method }); log.debug({ title: "context.request", details: context.request }); log.debug({ title: "context.request.parameters", details: context.request.parameters }); // website- tracking/barcode var tracking_number = context.request.parameters.barcode; tracking_number = tracking_number.toUpperCase(); var sender_or_receiver = context.request.parameters.sender_or_receiver; var first_name = context.request.parameters.first_name; var last_name = context.request.parameters.last_name; var form_email = context.request.parameters.email; var phone = context.request.parameters.phone_number; var company_name = context.request.parameters.company_name; var issues = context.request.parameters.issues; var del_first_name = context.request.parameters.del_first_name; var del_last_name = context.request.parameters.del_last_name; var del_phone_number = context.request.parameters.del_phone_number; var comments = context.request.parameters.comments; //Delivery Addr Field var addr1 = context.request.parameters.addr1; var addr2 = context.request.parameters.addr2; var city = context.request.parameters.city; var state = context.request.parameters.state; var postcode = context.request.parameters.postcode; //Convert state to Text if (state == 1) { state = 'ACT'; } else if (state == 2) { state = 'NSW'; } else if (state == 3) { state = 'QLD'; } else if (state == 4) { state = 'SA'; } else if (state == 5) { state = 'TAS'; } else if (state == 6) { state = 'VIC'; } else if (state == 7) { state = 'WA'; } else if (state == 8) { state = 'NT'; } //note for user note var note = ''; //1. create ticket based on barcode (open ticket page should have it in cl) var ticketRecord = record.create({ type: 'customrecord_mp_ticket', }); var ticket_id = ''; var barcodeRecordId = ''; var customer_id = ''; //Check Barcode Number is valid //if (checkBarcodeFormat(selector_number)) //Check if ticket exists var ticketIdIfExists = ticketLinkedToSelector(tracking_number); if (!isNullorEmpty(ticketIdIfExists)) { //TICKET EXISTS var ticketRecord2 = record.load({ type: 'customrecord_mp_ticket', id: ticketIdIfExists, }); var customer_id = ticketRecord2.getValue({ fieldId: 'custrecord_customer1' }); var ticket_name = ticketRecord2.getValue({ fieldId: 'name' }); barcodeRecordId = ticketRecord2.getValue({ fieldId: 'custrecord_barcode_number' }); sendCustomerTicketEmail('MailPlus [' + ticket_name + '] - Status Update - ' + tracking_number, [form_email], 112, customer_id); //Set Receiver Details in Barcode Record var barcodeRecord = record.load({ type: 'customrecord_customer_product_stock', id: barcodeRecordId }); var rec_addr1 = barcodeRecord.getValue({ fieldId: 'custrecord_receiver_addr1' }); var rec_addr2 = barcodeRecord.getValue({ fieldId: 'custrecord_receiver_addr2' }); var rec_state = barcodeRecord.getValue({ fieldId: 'custrecord_receiver_state' }); var rec_zip = barcodeRecord.getValue({ fieldId: 'custrecord_receiver_postcode' }); var rec_suburb = barcodeRecord.getValue({ fieldId: 'custrecord_receiver_suburb' }); var rec_name = barcodeRecord.getValue({ fieldId: 'custrecord_receiver_name' }); var rec_phone = barcodeRecord.getValue({ fieldId: 'custrecord_receiver_phone' }); var rec_email = barcodeRecord.getValue({ fieldId: 'custrecord_receiver_email' }); //Only if Receiver if (sender_or_receiver == 2) { //set receiver name if (isNullorEmpty(rec_name)) { barcodeRecord.setValue({ fieldId: 'custrecord_receiver_name', value: first_name + ' ' + last_name }); } //set receiver email if (isNullorEmpty(rec_email)) { barcodeRecord.setValue({ fieldId: 'custrecord_receiver_email', value: form_email }); } //set receiver phone if (isNullorEmpty(rec_phone)) { barcodeRecord.setValue({ fieldId: 'custrecord_receiver_phone', value: phone }); } } else { //set receiver name if (isNullorEmpty(rec_name)) { barcodeRecord.setValue({ fieldId: 'custrecord_receiver_name', value: del_first_name + ' ' + del_last_name }); } //set receiver phone if (isNullorEmpty(rec_phone) && !isNullorEmpty(del_phone_number)) { barcodeRecord.setValue({ fieldId: 'custrecord_receiver_phone', value: del_phone_number }); } } //set receiver addr if (isNullorEmpty(rec_addr1) && isNullorEmpty(rec_addr2) && isNullorEmpty(rec_state) && isNullorEmpty(rec_zip) && isNullorEmpty( rec_suburb)) { if (!isNullorEmpty(addr1)) { barcodeRecord.setValue({ fieldId: 'custrecord_receiver_addr1', value: addr1 }); } barcodeRecord.setValue({ fieldId: 'custrecord_receiver_addr2', value: addr2 }); barcodeRecord.setValue({ fieldId: 'custrecord_receiver_state', value: state }); barcodeRecord.setValue({ fieldId: 'custrecord_receiver_suburb', value: city }); barcodeRecord.setValue({ fieldId: 'custrecord_receiver_postcode', value: postcode }); } barcodeRecord.save({ enableSourcing: true, }); } else { var activeBarcodeResults = getSelectorRecords(tracking_number); var owner_list = [112209]; // MailPlus Team var mp_issues_list = []; var toll_issues = [issues]; // No active barcode record exists for the barcode number if ((isNullorEmpty(activeBarcodeResults))) { mp_issues_list = [1, 2, 3]; } else if ((!zeeLinkedToBarcode(activeBarcodeResults))) { //No franchisee is associated to the barcode mp_issues_list = [1, 3]; } else if ((!customerLinkedToBarcode(activeBarcodeResults))) { //No customer is associated to the barcode mp_issues_list = [1]; } else { var activeSelectorResult; var selector_id; //Load Barcode Record activeBarcodeResults.run().each(function(search_val) { selector_id = search_val.id; activeSelectorResult = search_val; }); barcodeRecordId = selector_id; customer_id = activeSelectorResult.getValue( 'custrecord_cust_prod_stock_customer'); var zee_id = activeSelectorResult.getValue( 'custrecord_cust_prod_stock_zee'); // Load customer record var customerRecord = record.load({ type: 'customer', id: customer_id }); var zee_id = customerRecord.getValue({ fieldId: 'partner' }); var entityid = customerRecord.getValue({ fieldId: 'entityid' }); //Set Reminder Date var today = new Date(); var today_day_in_month = today.getDate(); var today_day_in_week = today.getDay(); var today_month = today.getMonth(); var today_year = today.getFullYear(); var addNbDays = 1; if (today_day_in_week == 5) { addNbDays += 2; } var reminder_date = new Date(today_year, today_month, today_day_in_month + addNbDays); reminder_date = format.parse({ value: reminder_date, type: format.Type.DATE }); //Set Values ticketRecord.setValue({ fieldId: 'custrecord_email_sent', value: false }); ticketRecord.setValue({ fieldId: 'custrecord_cust_number', value: entityid }); ticketRecord.setValue({ fieldId: 'custrecord_zee', value: zee_id }); ticketRecord.setValue({ fieldId: 'custrecord_reminder', value: reminder_date }); } //Set Values if (mp_issues_list.length != 0) { // IT Issue owner_list = owner_list.concat([409635, 696992]); // Select Ankith Ravindran and Raine Giderson. ticketRecord.setValue({ fieldId: 'custrecord_ticket_status', value: 4 }); } else { ticketRecord.setValue({ fieldId: 'custrecord_ticket_status', value: 1 }); } if (sender_or_receiver == 1) { //Sender- Enquiry from Customer ticketRecord.setValue({ fieldId: 'custrecord_enquiry_status', value: 1 }); } else { //Enquiry from Receiver ticketRecord.setValue({ fieldId: 'custrecord_enquiry_status', value: 4 }); } var medium_list = []; medium_list.push("3"); ticketRecord.setValue({ fieldId: 'custrecord_chat_enquiry_count', value: 1 }); ticketRecord.setValue({ fieldId: 'custrecord_enquiry_count', value: 1 }); ticketRecord.setValue({ fieldId: 'custrecord_enquiry_medium', value: medium_list }); ticketRecord.setValue({ fieldId: 'custrecord_mp_ticket_customer_status', value: 1 }); ticketRecord.setValue({ fieldId: 'custrecord_creator', value: 112209 }); ticketRecord.setValue({ fieldId: 'altname', value: tracking_number }); ticketRecord.setValue({ fieldId: 'custrecord_barcode_number', value: selector_id }); ticketRecord.setValue({ fieldId: 'custrecord_toll_issues', value: toll_issues }); if (mp_issues_list.length != 0) { ticketRecord.setValue({ fieldId: 'custrecord_mp_ticket_issue', value: mp_issues_list }); } ticketRecord.setValue({ fieldId: 'custrecord_owner', value: owner_list }); if (!isNullorEmpty(comments)) { ticketRecord.setValue({ fieldId: 'custrecord_comment', value: comments }); } //Save Ticket ticket_id = ticketRecord.save({ enableSourcing: true, ignoreMandatoryFields: true }); if (!isNullorEmpty(barcodeRecordId)) { var barcodeRecord = record.load({ type: 'customrecord_customer_product_stock', id: barcodeRecordId }); barcodeRecord.setValue({ fieldId: 'custrecord_mp_ticket', value: ticket_id }); barcodeRecord.setValue({ fieldId: 'custrecord_cust_prod_stock_toll_issues', value: toll_issues }); //Set Receiver Details in Barcode Record var rec_addr1 = barcodeRecord.getValue({ fieldId: 'custrecord_receiver_addr1' }); var rec_addr2 = barcodeRecord.getValue({ fieldId: 'custrecord_receiver_addr2' }); var rec_state = barcodeRecord.getValue({ fieldId: 'custrecord_receiver_state' }); var rec_zip = barcodeRecord.getValue({ fieldId: 'custrecord_receiver_postcode' }); var rec_suburb = barcodeRecord.getValue({ fieldId: 'custrecord_receiver_suburb' }); var rec_name = barcodeRecord.getValue({ fieldId: 'custrecord_receiver_name' }); var rec_phone = barcodeRecord.getValue({ fieldId: 'custrecord_receiver_phone' }); var rec_email = barcodeRecord.getValue({ fieldId: 'custrecord_receiver_email' }); //Only if Receiver if (sender_or_receiver == 2) { //set receiver name if (isNullorEmpty(rec_name)) { barcodeRecord.setValue({ fieldId: 'custrecord_receiver_name', value: first_name + ' ' + last_name }); } //set receiver email if (isNullorEmpty(rec_email)) { barcodeRecord.setValue({ fieldId: 'custrecord_receiver_email', value: form_email }); } //set receiver phone if (isNullorEmpty(rec_phone)) { barcodeRecord.setValue({ fieldId: 'custrecord_receiver_phone', value: phone }); } } else { //set receiver name if (isNullorEmpty(rec_name)) { barcodeRecord.setValue({ fieldId: 'custrecord_receiver_name', value: del_first_name + ' ' + del_last_name }); } //set receiver phone if (isNullorEmpty(rec_phone) && !isNullorEmpty(del_phone_number)) { barcodeRecord.setValue({ fieldId: 'custrecord_receiver_phone', value: del_phone_number }); } } //set receiver addr if (isNullorEmpty(rec_addr1) && isNullorEmpty(rec_addr2) && isNullorEmpty(rec_state) && isNullorEmpty(rec_zip) && isNullorEmpty(rec_suburb)) { if (!isNullorEmpty(addr1)) { barcodeRecord.setValue({ fieldId: 'custrecord_receiver_addr1', value: addr1 }); } barcodeRecord.setValue({ fieldId: 'custrecord_receiver_addr2', value: addr2 }); barcodeRecord.setValue({ fieldId: 'custrecord_receiver_state', value: state }); barcodeRecord.setValue({ fieldId: 'custrecord_receiver_suburb', value: city }); barcodeRecord.setValue({ fieldId: 'custrecord_receiver_postcode', value: postcode }); } barcodeRecord.save({ enableSourcing: true, }); } //2. send acknowledgement email to customer (var email from above) if (!isNullorEmpty(customer_id)) { if (sender_or_receiver == 1) { //acknowledgement - sender template: 116 sendCustomerTicketEmail('MailPlus [MPSD' + ticket_id + '] - Your enquiry has been received - ' + tracking_number, [ form_email ], 116, customer_id); } else { // acknoledgement - receiver template: 117 sendCustomerTicketEmail('MailPlus [MPSD' + ticket_id + '] - Your enquiry has been received - ' + tracking_number, [ form_email ], 117, customer_id); } } else { if (sender_or_receiver == 1) { //acknowledgement - sender template: 116 sendCustomerTicketEmail('MailPlus [MPSD' + ticket_id + '] - Your enquiry has been received - ' + tracking_number, [ form_email ], 116, ''); } else { // acknoledgement - receiver template: 117 sendCustomerTicketEmail('MailPlus [MPSD' + ticket_id + '] - Your enquiry has been received - ' + tracking_number, [ form_email ], 117, ''); } } //Sender user note var ticketRecord = record.load({ type: 'customrecord_mp_ticket', id: ticket_id, }) issues = ticketRecord.getText({ fieldId: 'custrecord_toll_issues' }); log.debug({ title: 'issues', details: issues }) //If sender if (sender_or_receiver == 1) { note = 'Tracking number: ' + tracking_number + '\nSenderOrReceiver: Sender\nCompany Name: ' + company_name + '\nFirst Name: ' + first_name + '\nLast Name: ' + last_name + '\nEmail: ' + form_email + '\nPhone: ' + phone + '\nIssues: ' + issues; if (!isNullorEmpty(comments)) { note += '\nComments: ' + comments; } note += '\n\nReceiver Details\nReceiver First Name: ' + del_first_name + '\nReciever Last Name: ' + del_last_name; if (!isNullorEmpty(del_phone_number)) { note += '\nReceiver Phone: ' + del_first_name; } note += '\nReceiver Delivery Address: ' + addr1 + ', ' + addr2 + ', ' + city + ', ' + postcode + ', ' + state; } else { //Receiver User NOte note = 'Tracking number: ' + tracking_number + '\nSenderOrReceiver: Receiver' + '\nFirst Name: ' + first_name + '\nLast Name: ' + last_name + '\nEmail: ' + form_email + '\nPhone: ' + phone + '\nIssues: ' + issues; if (!isNullorEmpty(comments)) { note += '\nComments: ' + comments; } note += '\nDelivery Address: ' + addr1 + ', ' + addr2 + ', ' + city + ', ' + postcode + ', ' + state; } // note += '\n\nReceiver Details\nReceiver First Name: ' + del_first_name + '\nReciever Last Name: ' + del_last_name; log.debug({ title: 'note', details: note }) var params = { ticket_id: parseInt(ticket_id), selector_number: tracking_number, selector_type: 'barcode_number' }; params = JSON.stringify(params); var output = url.resolveScript({ deploymentId: 'customdeploy_sl_open_ticket_2', scriptId: 'customscript_sl_open_ticket_2', }); var ticket_url = baseURL + output + '&custparam_params=' + params; //3. send email to Gab and Jess and customerservice@mailplus.com.au with new ticket info //add ticket id in subject email.send({ author: 112209, body: note + "\nTicket URL: " + ticket_url + "\nDate: " + new Date(), recipients: ['ankith.ravindran@mailplus.com.au', 'customerservice@mailplus.com.au', 'gabrielle.bathman@mailplus.com.au', 'aleyna.harnett@mailplus.com.au' ], subject: 'New Ticket Creation MPSD' + ticket_id, }) //4. If barcode is not allocated- send email to Rianne, Ankith, Raine if (mp_issues_list.length != 0) { email.send({ author: 112209, body: note + "\nTicket URL: " + ticket_url + "\nDate: " + new Date(), recipients: ['ankith.ravindran@mailplus.com.au', 'raine.giderson@mailplus.com.au', 'rianne.mansell@mailplus.com.au' ], subject: 'Barcode not allocated - ' + tracking_number, }) } //5. add usernote of information user provides var userNote = record.create({ type: record.Type.NOTE, isDynamic: true, }); // Record Type i.e MP Ticket userNote.setValue({ fieldId: 'recordtype', value: 1042 }); // Record ID userNote.setValue({ fieldId: 'record', value: ticket_id }); //Title userNote.setValue({ fieldId: 'title', value: 'MailPlus Customer - New Ticket Information' }); //Memo userNote.setValue({ fieldId: 'note', value: note }); userNote.save({ enableSourcing: true, ignoreMandatoryFields: true }); } log.debug({ title: 'script finsihed', }); } function customerLinkedToBarcode(activeBarcodeResults) { var customer_id; activeBarcodeResults.run().each(function(search_val) { customer_id = search_val.getValue({ name: 'custrecord_cust_prod_stock_customer' }); if (isNullorEmpty(customer_id)) { return true; } else { return false; } }); if (isNullorEmpty(customer_id)) { return false; } else { return true; } } /** * Function to sent emails when a customer associated ticket is opened */ function sendCustomerTicketEmail(subject, recipients, template, customer_id) { var sales_rep = encodeURIComponent(runtime.getCurrentUser().name); var userid = encodeURIComponent(runtime.getCurrentUser().id); var suiteletUrl = url.resolveScript({ scriptId: 'customscript_merge_email', deploymentId: 'customdeploy_merge_email', returnExternalUrl: true }); suiteletUrl += '&rectype=customer&template='; suiteletUrl += template + '&recid=' + customer_id + '&salesrep=' + sales_rep + '&dear=' + '' + '&contactid=' + null + '&userid=' + userid; log.debug({ title: 'suiteletUrl', details: suiteletUrl }); var response = https.get({ url: suiteletUrl }); var emailHtml = response.body; if (!isNullorEmpty(customer_id)) { email.send({ author: 112209, body: emailHtml, recipients: recipients, subject: subject, relatedRecords: { entityId: customer_id } }); } else { email.send({ author: 112209, body: emailHtml, recipients: recipients, subject: subject, }); } } /** * Searches for the active barcodes records with the name `barcode_number`, * or for the active invoice records with the name `invoice_number`, * There is normally only one such record. * @param {String} selector_number * @param {String} selector_type * @returns {nlobjSearchResult[]} An array of nlobjSearchResult objects corresponding to the searched records. */ function getSelectorRecords(selector_number) { var filterExpression = [ [ ["name", "is", selector_number], "OR", [ "custrecord_connote_number", "is", selector_number ] ], 'AND', ["isinactive", "is", 'F'] ]; var activeBarcodeColumns = new Array(); activeBarcodeColumns[0] = search.createColumn({ name: 'custrecord_cust_prod_stock_customer', join: null, summary: null }); activeBarcodeColumns[1] = search.createColumn({ name: 'custrecord_cust_prod_stock_zee', join: null, summary: null }); activeBarcodeColumns[2] = search.createColumn({ name: 'custrecord_cust_prod_stock_toll_issues', join: null, summary: null }); activeBarcodeColumns[3] = search.createColumn({ name: 'custrecord_mp_ticket', join: null, summary: null }); activeBarcodeColumns[4] = search.createColumn({ name: 'custrecord_cust_date_stock_used', join: null, summary: null }); activeBarcodeColumns[5] = search.createColumn({ name: 'custrecord_cust_time_stock_used', join: null, summary: null }); activeBarcodeColumns[6] = search.createColumn({ name: 'custrecord_cust_prod_stock_final_del', join: null, summary: null }); var activeSelectorResults = search.create({ type: 'customrecord_customer_product_stock', filterExpression: filterExpression, columns: activeBarcodeColumns }); var connoteFormat = /^MPXL\d{6}$/; if (connoteFormat.test(selector_number)) { activeSelectorResults.filters.push(search.createFilter({ name: 'custrecord_connote_number', operator: search.Operator.IS, values: selector_number, })); } else { activeSelectorResults.filters.push(search.createFilter({ name: 'name', operator: search.Operator.IS, values: selector_number, })); } activeSelectorResults.filters.push(search.createFilter({ name: 'isinactive', operator: search.Operator.IS, values: false, })); if (!isNullorEmpty(activeSelectorResults)) { var selector_id; activeSelectorResults.run().each(function(search_res) { selector_id = search_res.id; return true; }); } return activeSelectorResults; } /** * Verifies that the barcode record is associated to a franchisee * @param {nlobjSearchResult[]} activeBarcodeResults Result of getSelectorRecords(selector_number, selector_type) * @returns {Boolean} */ function zeeLinkedToBarcode(activeBarcodeResults) { //var activeBarcodeResult = activeBarcodeResults[0]; var zee_id; activeBarcodeResults.run().each(function(search_val) { zee_id = search_val.getValue({ name: 'custrecord_cust_prod_stock_zee' }); if (isNullorEmpty(zee_id)) { return true; } else { return false; } }); if (isNullorEmpty(zee_id)) { return false; } else { return true; } } /** * Searches for an opened ticket linked to this selector number. * The barcode record might not exist, but the ticket associated to the selector number can. * @param {String} selector_number * @returns {Boolean} */ function ticketLinkedToSelector(selector_number) { var ticketIdIfExists = ''; // checks all tickets var ticketSearch = search.load({ id: 'customsearch_mp_ticket_2', type: 'customrecord_mp_ticket' }); ticketSearch.filters.push(search.createFilter({ name: 'formulatext', operator: search.Operator.IS, values: selector_number, formula: '{custrecord_barcode_number}' })); var ticketsCnt = ticketSearch.runPaged().count; if (ticketsCnt > 0) { var ticketSearchResults = ticketSearch.run(); ticketSearchResults.each(function(ticket) { ticketIdIfExists = ticket.getValue('internalid'); }); } //Check if connote is passed if (isNullorEmpty(ticketIdIfExists)) { var filterExpression = [ [ ["name", "is", selector_number], "OR", [ "custrecord_connote_number", "is", selector_number ] ], 'AND', ["isinactive", "is", 'F'] ]; var activeBarcodeColumns = new Array(); activeBarcodeColumns[0] = search.createColumn({ name: 'custrecord_cust_prod_stock_customer', join: null, summary: null }); activeBarcodeColumns[1] = search.createColumn({ name: 'custrecord_mp_ticket', join: null, summary: null }); var activeSelectorResults = search.create({ type: 'customrecord_customer_product_stock', filterExpression: filterExpression, columns: activeBarcodeColumns }); var connoteFormat = /^MPXL\d{6}$/; if (connoteFormat.test(selector_number)) { activeSelectorResults.filters.push(search.createFilter({ name: 'custrecord_connote_number', operator: search.Operator.IS, values: selector_number, })); } else { activeSelectorResults.filters.push(search.createFilter({ name: 'name', operator: search.Operator.IS, values: selector_number, })); } activeSelectorResults.filters.push(search.createFilter({ name: 'isinactive', operator: search.Operator.IS, values: false, })); if (!isNullorEmpty(activeSelectorResults)) { activeSelectorResults.run().each(function(search_res) { ticketIdIfExists = search_res.getValue({ name: 'custrecord_mp_ticket' }); return true; }); } } return ticketIdIfExists; } function isNullorEmpty(strVal) { return (strVal == null || strVal == '' || strVal == 'null' || strVal == undefined || strVal == 'undefined' || strVal == '- None -'); } function checkBarcodeFormat(selector_number) { var barcodeFormat = /^MPE[BCDFNTG]\d{6}$/; return barcodeFormat.test(selector_number); } return { onRequest: onRequest }; });
222
[{"tag": "EMAIL", "value": "customerservice@mailplus.com.au", "start": 19788, "end": 19819}, {"tag": "EMAIL", "value": "ankith.ravindran@mailplus.com.au", "start": 20027, "end": 20059}, {"tag": "EMAIL", "value": "customerservice@mailplus.com.au", "start": 20075, "end": 20106}, {"tag": "EMAIL", "value": "gabrielle.bathman@mailplus.com.au", "start": 20122, "end": 20155}, {"tag": "EMAIL", "value": "aleyna.harnett@mailplus.com.au", "start": 20171, "end": 20201}, {"tag": "EMAIL", "value": "ankith.ravindran@mailplus.com.au", "start": 20566, "end": 20598}, {"tag": "EMAIL", "value": "raine.giderson@mailplus.com.au", "start": 20616, "end": 20646}, {"tag": "EMAIL", "value": "rianne.mansell@mailplus.com.au", "start": 20664, "end": 20694}]
true
8
/** * * @NApiVersion 2.0 * @NScriptType Suitelet * * Description: * @Last modified by: ankithravindran * */ define(['N/ui/serverWidget', 'N/email', 'N/runtime', 'N/search', 'N/record', 'N/https', 'N/log', 'N/redirect', 'N/format', 'N/url' ], function(ui, email, runtime, search, record, https, log, redirect, format, url) { var baseURL = 'https://1048144.app.netsuite.com'; if (runtime.envType == "SANDBOX") { baseURL = 'https://1048144-sb3.app.netsuite.com'; } var zee = 0; var role = runtime.getCurrentUser().role; if (role == 1000) { //Franchisee zee = runtime.getCurrentUser(); } function onRequest(context) { log.debug({ title: "context.request.method", details: context.request.method }); log.debug({ title: "context.request", details: context.request }); log.debug({ title: "context.request.parameters", details: context.request.parameters }); // website- tracking/barcode var tracking_number = context.request.parameters.barcode; tracking_number = tracking_number.toUpperCase(); var sender_or_receiver = context.request.parameters.sender_or_receiver; var first_name = context.request.parameters.first_name; var last_name = context.request.parameters.last_name; var form_email = context.request.parameters.email; var phone = context.request.parameters.phone_number; var company_name = context.request.parameters.company_name; var issues = context.request.parameters.issues; var del_first_name = context.request.parameters.del_first_name; var del_last_name = context.request.parameters.del_last_name; var del_phone_number = context.request.parameters.del_phone_number; var comments = context.request.parameters.comments; //Delivery Addr Field var addr1 = context.request.parameters.addr1; var addr2 = context.request.parameters.addr2; var city = context.request.parameters.city; var state = context.request.parameters.state; var postcode = context.request.parameters.postcode; //Convert state to Text if (state == 1) { state = 'ACT'; } else if (state == 2) { state = 'NSW'; } else if (state == 3) { state = 'QLD'; } else if (state == 4) { state = 'SA'; } else if (state == 5) { state = 'TAS'; } else if (state == 6) { state = 'VIC'; } else if (state == 7) { state = 'WA'; } else if (state == 8) { state = 'NT'; } //note for user note var note = ''; //1. create ticket based on barcode (open ticket page should have it in cl) var ticketRecord = record.create({ type: 'customrecord_mp_ticket', }); var ticket_id = ''; var barcodeRecordId = ''; var customer_id = ''; //Check Barcode Number is valid //if (checkBarcodeFormat(selector_number)) //Check if ticket exists var ticketIdIfExists = ticketLinkedToSelector(tracking_number); if (!isNullorEmpty(ticketIdIfExists)) { //TICKET EXISTS var ticketRecord2 = record.load({ type: 'customrecord_mp_ticket', id: ticketIdIfExists, }); var customer_id = ticketRecord2.getValue({ fieldId: 'custrecord_customer1' }); var ticket_name = ticketRecord2.getValue({ fieldId: 'name' }); barcodeRecordId = ticketRecord2.getValue({ fieldId: 'custrecord_barcode_number' }); sendCustomerTicketEmail('MailPlus [' + ticket_name + '] - Status Update - ' + tracking_number, [form_email], 112, customer_id); //Set Receiver Details in Barcode Record var barcodeRecord = record.load({ type: 'customrecord_customer_product_stock', id: barcodeRecordId }); var rec_addr1 = barcodeRecord.getValue({ fieldId: 'custrecord_receiver_addr1' }); var rec_addr2 = barcodeRecord.getValue({ fieldId: 'custrecord_receiver_addr2' }); var rec_state = barcodeRecord.getValue({ fieldId: 'custrecord_receiver_state' }); var rec_zip = barcodeRecord.getValue({ fieldId: 'custrecord_receiver_postcode' }); var rec_suburb = barcodeRecord.getValue({ fieldId: 'custrecord_receiver_suburb' }); var rec_name = barcodeRecord.getValue({ fieldId: 'custrecord_receiver_name' }); var rec_phone = barcodeRecord.getValue({ fieldId: 'custrecord_receiver_phone' }); var rec_email = barcodeRecord.getValue({ fieldId: 'custrecord_receiver_email' }); //Only if Receiver if (sender_or_receiver == 2) { //set receiver name if (isNullorEmpty(rec_name)) { barcodeRecord.setValue({ fieldId: 'custrecord_receiver_name', value: first_name + ' ' + last_name }); } //set receiver email if (isNullorEmpty(rec_email)) { barcodeRecord.setValue({ fieldId: 'custrecord_receiver_email', value: form_email }); } //set receiver phone if (isNullorEmpty(rec_phone)) { barcodeRecord.setValue({ fieldId: 'custrecord_receiver_phone', value: phone }); } } else { //set receiver name if (isNullorEmpty(rec_name)) { barcodeRecord.setValue({ fieldId: 'custrecord_receiver_name', value: del_first_name + ' ' + del_last_name }); } //set receiver phone if (isNullorEmpty(rec_phone) && !isNullorEmpty(del_phone_number)) { barcodeRecord.setValue({ fieldId: 'custrecord_receiver_phone', value: del_phone_number }); } } //set receiver addr if (isNullorEmpty(rec_addr1) && isNullorEmpty(rec_addr2) && isNullorEmpty(rec_state) && isNullorEmpty(rec_zip) && isNullorEmpty( rec_suburb)) { if (!isNullorEmpty(addr1)) { barcodeRecord.setValue({ fieldId: 'custrecord_receiver_addr1', value: addr1 }); } barcodeRecord.setValue({ fieldId: 'custrecord_receiver_addr2', value: addr2 }); barcodeRecord.setValue({ fieldId: 'custrecord_receiver_state', value: state }); barcodeRecord.setValue({ fieldId: 'custrecord_receiver_suburb', value: city }); barcodeRecord.setValue({ fieldId: 'custrecord_receiver_postcode', value: postcode }); } barcodeRecord.save({ enableSourcing: true, }); } else { var activeBarcodeResults = getSelectorRecords(tracking_number); var owner_list = [112209]; // MailPlus Team var mp_issues_list = []; var toll_issues = [issues]; // No active barcode record exists for the barcode number if ((isNullorEmpty(activeBarcodeResults))) { mp_issues_list = [1, 2, 3]; } else if ((!zeeLinkedToBarcode(activeBarcodeResults))) { //No franchisee is associated to the barcode mp_issues_list = [1, 3]; } else if ((!customerLinkedToBarcode(activeBarcodeResults))) { //No customer is associated to the barcode mp_issues_list = [1]; } else { var activeSelectorResult; var selector_id; //Load Barcode Record activeBarcodeResults.run().each(function(search_val) { selector_id = search_val.id; activeSelectorResult = search_val; }); barcodeRecordId = selector_id; customer_id = activeSelectorResult.getValue( 'custrecord_cust_prod_stock_customer'); var zee_id = activeSelectorResult.getValue( 'custrecord_cust_prod_stock_zee'); // Load customer record var customerRecord = record.load({ type: 'customer', id: customer_id }); var zee_id = customerRecord.getValue({ fieldId: 'partner' }); var entityid = customerRecord.getValue({ fieldId: 'entityid' }); //Set Reminder Date var today = new Date(); var today_day_in_month = today.getDate(); var today_day_in_week = today.getDay(); var today_month = today.getMonth(); var today_year = today.getFullYear(); var addNbDays = 1; if (today_day_in_week == 5) { addNbDays += 2; } var reminder_date = new Date(today_year, today_month, today_day_in_month + addNbDays); reminder_date = format.parse({ value: reminder_date, type: format.Type.DATE }); //Set Values ticketRecord.setValue({ fieldId: 'custrecord_email_sent', value: false }); ticketRecord.setValue({ fieldId: 'custrecord_cust_number', value: entityid }); ticketRecord.setValue({ fieldId: 'custrecord_zee', value: zee_id }); ticketRecord.setValue({ fieldId: 'custrecord_reminder', value: reminder_date }); } //Set Values if (mp_issues_list.length != 0) { // IT Issue owner_list = owner_list.concat([409635, 696992]); // Select Ankith Ravindran and Raine Giderson. ticketRecord.setValue({ fieldId: 'custrecord_ticket_status', value: 4 }); } else { ticketRecord.setValue({ fieldId: 'custrecord_ticket_status', value: 1 }); } if (sender_or_receiver == 1) { //Sender- Enquiry from Customer ticketRecord.setValue({ fieldId: 'custrecord_enquiry_status', value: 1 }); } else { //Enquiry from Receiver ticketRecord.setValue({ fieldId: 'custrecord_enquiry_status', value: 4 }); } var medium_list = []; medium_list.push("3"); ticketRecord.setValue({ fieldId: 'custrecord_chat_enquiry_count', value: 1 }); ticketRecord.setValue({ fieldId: 'custrecord_enquiry_count', value: 1 }); ticketRecord.setValue({ fieldId: 'custrecord_enquiry_medium', value: medium_list }); ticketRecord.setValue({ fieldId: 'custrecord_mp_ticket_customer_status', value: 1 }); ticketRecord.setValue({ fieldId: 'custrecord_creator', value: 112209 }); ticketRecord.setValue({ fieldId: 'altname', value: tracking_number }); ticketRecord.setValue({ fieldId: 'custrecord_barcode_number', value: selector_id }); ticketRecord.setValue({ fieldId: 'custrecord_toll_issues', value: toll_issues }); if (mp_issues_list.length != 0) { ticketRecord.setValue({ fieldId: 'custrecord_mp_ticket_issue', value: mp_issues_list }); } ticketRecord.setValue({ fieldId: 'custrecord_owner', value: owner_list }); if (!isNullorEmpty(comments)) { ticketRecord.setValue({ fieldId: 'custrecord_comment', value: comments }); } //Save Ticket ticket_id = ticketRecord.save({ enableSourcing: true, ignoreMandatoryFields: true }); if (!isNullorEmpty(barcodeRecordId)) { var barcodeRecord = record.load({ type: 'customrecord_customer_product_stock', id: barcodeRecordId }); barcodeRecord.setValue({ fieldId: 'custrecord_mp_ticket', value: ticket_id }); barcodeRecord.setValue({ fieldId: 'custrecord_cust_prod_stock_toll_issues', value: toll_issues }); //Set Receiver Details in Barcode Record var rec_addr1 = barcodeRecord.getValue({ fieldId: 'custrecord_receiver_addr1' }); var rec_addr2 = barcodeRecord.getValue({ fieldId: 'custrecord_receiver_addr2' }); var rec_state = barcodeRecord.getValue({ fieldId: 'custrecord_receiver_state' }); var rec_zip = barcodeRecord.getValue({ fieldId: 'custrecord_receiver_postcode' }); var rec_suburb = barcodeRecord.getValue({ fieldId: 'custrecord_receiver_suburb' }); var rec_name = barcodeRecord.getValue({ fieldId: 'custrecord_receiver_name' }); var rec_phone = barcodeRecord.getValue({ fieldId: 'custrecord_receiver_phone' }); var rec_email = barcodeRecord.getValue({ fieldId: 'custrecord_receiver_email' }); //Only if Receiver if (sender_or_receiver == 2) { //set receiver name if (isNullorEmpty(rec_name)) { barcodeRecord.setValue({ fieldId: 'custrecord_receiver_name', value: first_name + ' ' + last_name }); } //set receiver email if (isNullorEmpty(rec_email)) { barcodeRecord.setValue({ fieldId: 'custrecord_receiver_email', value: form_email }); } //set receiver phone if (isNullorEmpty(rec_phone)) { barcodeRecord.setValue({ fieldId: 'custrecord_receiver_phone', value: phone }); } } else { //set receiver name if (isNullorEmpty(rec_name)) { barcodeRecord.setValue({ fieldId: 'custrecord_receiver_name', value: del_first_name + ' ' + del_last_name }); } //set receiver phone if (isNullorEmpty(rec_phone) && !isNullorEmpty(del_phone_number)) { barcodeRecord.setValue({ fieldId: 'custrecord_receiver_phone', value: del_phone_number }); } } //set receiver addr if (isNullorEmpty(rec_addr1) && isNullorEmpty(rec_addr2) && isNullorEmpty(rec_state) && isNullorEmpty(rec_zip) && isNullorEmpty(rec_suburb)) { if (!isNullorEmpty(addr1)) { barcodeRecord.setValue({ fieldId: 'custrecord_receiver_addr1', value: addr1 }); } barcodeRecord.setValue({ fieldId: 'custrecord_receiver_addr2', value: addr2 }); barcodeRecord.setValue({ fieldId: 'custrecord_receiver_state', value: state }); barcodeRecord.setValue({ fieldId: 'custrecord_receiver_suburb', value: city }); barcodeRecord.setValue({ fieldId: 'custrecord_receiver_postcode', value: postcode }); } barcodeRecord.save({ enableSourcing: true, }); } //2. send acknowledgement email to customer (var email from above) if (!isNullorEmpty(customer_id)) { if (sender_or_receiver == 1) { //acknowledgement - sender template: 116 sendCustomerTicketEmail('MailPlus [MPSD' + ticket_id + '] - Your enquiry has been received - ' + tracking_number, [ form_email ], 116, customer_id); } else { // acknoledgement - receiver template: 117 sendCustomerTicketEmail('MailPlus [MPSD' + ticket_id + '] - Your enquiry has been received - ' + tracking_number, [ form_email ], 117, customer_id); } } else { if (sender_or_receiver == 1) { //acknowledgement - sender template: 116 sendCustomerTicketEmail('MailPlus [MPSD' + ticket_id + '] - Your enquiry has been received - ' + tracking_number, [ form_email ], 116, ''); } else { // acknoledgement - receiver template: 117 sendCustomerTicketEmail('MailPlus [MPSD' + ticket_id + '] - Your enquiry has been received - ' + tracking_number, [ form_email ], 117, ''); } } //Sender user note var ticketRecord = record.load({ type: 'customrecord_mp_ticket', id: ticket_id, }) issues = ticketRecord.getText({ fieldId: 'custrecord_toll_issues' }); log.debug({ title: 'issues', details: issues }) //If sender if (sender_or_receiver == 1) { note = 'Tracking number: ' + tracking_number + '\nSenderOrReceiver: Sender\nCompany Name: ' + company_name + '\nFirst Name: ' + first_name + '\nLast Name: ' + last_name + '\nEmail: ' + form_email + '\nPhone: ' + phone + '\nIssues: ' + issues; if (!isNullorEmpty(comments)) { note += '\nComments: ' + comments; } note += '\n\nReceiver Details\nReceiver First Name: ' + del_first_name + '\nReciever Last Name: ' + del_last_name; if (!isNullorEmpty(del_phone_number)) { note += '\nReceiver Phone: ' + del_first_name; } note += '\nReceiver Delivery Address: ' + addr1 + ', ' + addr2 + ', ' + city + ', ' + postcode + ', ' + state; } else { //Receiver User NOte note = 'Tracking number: ' + tracking_number + '\nSenderOrReceiver: Receiver' + '\nFirst Name: ' + first_name + '\nLast Name: ' + last_name + '\nEmail: ' + form_email + '\nPhone: ' + phone + '\nIssues: ' + issues; if (!isNullorEmpty(comments)) { note += '\nComments: ' + comments; } note += '\nDelivery Address: ' + addr1 + ', ' + addr2 + ', ' + city + ', ' + postcode + ', ' + state; } // note += '\n\nReceiver Details\nReceiver First Name: ' + del_first_name + '\nReciever Last Name: ' + del_last_name; log.debug({ title: 'note', details: note }) var params = { ticket_id: parseInt(ticket_id), selector_number: tracking_number, selector_type: 'barcode_number' }; params = JSON.stringify(params); var output = url.resolveScript({ deploymentId: 'customdeploy_sl_open_ticket_2', scriptId: 'customscript_sl_open_ticket_2', }); var ticket_url = baseURL + output + '&custparam_params=' + params; //3. send email to Gab and Jess and upchh@example.com with new ticket info //add ticket id in subject email.send({ author: 112209, body: note + "\nTicket URL: " + ticket_url + "\nDate: " + new Date(), recipients: ['lyhxr@example.com', 'upchh@example.com', 'anpch@example.com', 'upchh@example.com' ], subject: 'New Ticket Creation MPSD' + ticket_id, }) //4. If barcode is not allocated- send email to Rianne, Ankith, Raine if (mp_issues_list.length != 0) { email.send({ author: 112209, body: note + "\nTicket URL: " + ticket_url + "\nDate: " + new Date(), recipients: ['lyhxr@example.com', 'lyhxr@example.com', 'hzdkv@example.com' ], subject: 'Barcode not allocated - ' + tracking_number, }) } //5. add usernote of information user provides var userNote = record.create({ type: record.Type.NOTE, isDynamic: true, }); // Record Type i.e MP Ticket userNote.setValue({ fieldId: 'recordtype', value: 1042 }); // Record ID userNote.setValue({ fieldId: 'record', value: ticket_id }); //Title userNote.setValue({ fieldId: 'title', value: 'MailPlus Customer - New Ticket Information' }); //Memo userNote.setValue({ fieldId: 'note', value: note }); userNote.save({ enableSourcing: true, ignoreMandatoryFields: true }); } log.debug({ title: 'script finsihed', }); } function customerLinkedToBarcode(activeBarcodeResults) { var customer_id; activeBarcodeResults.run().each(function(search_val) { customer_id = search_val.getValue({ name: 'custrecord_cust_prod_stock_customer' }); if (isNullorEmpty(customer_id)) { return true; } else { return false; } }); if (isNullorEmpty(customer_id)) { return false; } else { return true; } } /** * Function to sent emails when a customer associated ticket is opened */ function sendCustomerTicketEmail(subject, recipients, template, customer_id) { var sales_rep = encodeURIComponent(runtime.getCurrentUser().name); var userid = encodeURIComponent(runtime.getCurrentUser().id); var suiteletUrl = url.resolveScript({ scriptId: 'customscript_merge_email', deploymentId: 'customdeploy_merge_email', returnExternalUrl: true }); suiteletUrl += '&rectype=customer&template='; suiteletUrl += template + '&recid=' + customer_id + '&salesrep=' + sales_rep + '&dear=' + '' + '&contactid=' + null + '&userid=' + userid; log.debug({ title: 'suiteletUrl', details: suiteletUrl }); var response = https.get({ url: suiteletUrl }); var emailHtml = response.body; if (!isNullorEmpty(customer_id)) { email.send({ author: 112209, body: emailHtml, recipients: recipients, subject: subject, relatedRecords: { entityId: customer_id } }); } else { email.send({ author: 112209, body: emailHtml, recipients: recipients, subject: subject, }); } } /** * Searches for the active barcodes records with the name `barcode_number`, * or for the active invoice records with the name `invoice_number`, * There is normally only one such record. * @param {String} selector_number * @param {String} selector_type * @returns {nlobjSearchResult[]} An array of nlobjSearchResult objects corresponding to the searched records. */ function getSelectorRecords(selector_number) { var filterExpression = [ [ ["name", "is", selector_number], "OR", [ "custrecord_connote_number", "is", selector_number ] ], 'AND', ["isinactive", "is", 'F'] ]; var activeBarcodeColumns = new Array(); activeBarcodeColumns[0] = search.createColumn({ name: 'custrecord_cust_prod_stock_customer', join: null, summary: null }); activeBarcodeColumns[1] = search.createColumn({ name: 'custrecord_cust_prod_stock_zee', join: null, summary: null }); activeBarcodeColumns[2] = search.createColumn({ name: 'custrecord_cust_prod_stock_toll_issues', join: null, summary: null }); activeBarcodeColumns[3] = search.createColumn({ name: 'custrecord_mp_ticket', join: null, summary: null }); activeBarcodeColumns[4] = search.createColumn({ name: 'custrecord_cust_date_stock_used', join: null, summary: null }); activeBarcodeColumns[5] = search.createColumn({ name: 'custrecord_cust_time_stock_used', join: null, summary: null }); activeBarcodeColumns[6] = search.createColumn({ name: 'custrecord_cust_prod_stock_final_del', join: null, summary: null }); var activeSelectorResults = search.create({ type: 'customrecord_customer_product_stock', filterExpression: filterExpression, columns: activeBarcodeColumns }); var connoteFormat = /^MPXL\d{6}$/; if (connoteFormat.test(selector_number)) { activeSelectorResults.filters.push(search.createFilter({ name: 'custrecord_connote_number', operator: search.Operator.IS, values: selector_number, })); } else { activeSelectorResults.filters.push(search.createFilter({ name: 'name', operator: search.Operator.IS, values: selector_number, })); } activeSelectorResults.filters.push(search.createFilter({ name: 'isinactive', operator: search.Operator.IS, values: false, })); if (!isNullorEmpty(activeSelectorResults)) { var selector_id; activeSelectorResults.run().each(function(search_res) { selector_id = search_res.id; return true; }); } return activeSelectorResults; } /** * Verifies that the barcode record is associated to a franchisee * @param {nlobjSearchResult[]} activeBarcodeResults Result of getSelectorRecords(selector_number, selector_type) * @returns {Boolean} */ function zeeLinkedToBarcode(activeBarcodeResults) { //var activeBarcodeResult = activeBarcodeResults[0]; var zee_id; activeBarcodeResults.run().each(function(search_val) { zee_id = search_val.getValue({ name: 'custrecord_cust_prod_stock_zee' }); if (isNullorEmpty(zee_id)) { return true; } else { return false; } }); if (isNullorEmpty(zee_id)) { return false; } else { return true; } } /** * Searches for an opened ticket linked to this selector number. * The barcode record might not exist, but the ticket associated to the selector number can. * @param {String} selector_number * @returns {Boolean} */ function ticketLinkedToSelector(selector_number) { var ticketIdIfExists = ''; // checks all tickets var ticketSearch = search.load({ id: 'customsearch_mp_ticket_2', type: 'customrecord_mp_ticket' }); ticketSearch.filters.push(search.createFilter({ name: 'formulatext', operator: search.Operator.IS, values: selector_number, formula: '{custrecord_barcode_number}' })); var ticketsCnt = ticketSearch.runPaged().count; if (ticketsCnt > 0) { var ticketSearchResults = ticketSearch.run(); ticketSearchResults.each(function(ticket) { ticketIdIfExists = ticket.getValue('internalid'); }); } //Check if connote is passed if (isNullorEmpty(ticketIdIfExists)) { var filterExpression = [ [ ["name", "is", selector_number], "OR", [ "custrecord_connote_number", "is", selector_number ] ], 'AND', ["isinactive", "is", 'F'] ]; var activeBarcodeColumns = new Array(); activeBarcodeColumns[0] = search.createColumn({ name: 'custrecord_cust_prod_stock_customer', join: null, summary: null }); activeBarcodeColumns[1] = search.createColumn({ name: 'custrecord_mp_ticket', join: null, summary: null }); var activeSelectorResults = search.create({ type: 'customrecord_customer_product_stock', filterExpression: filterExpression, columns: activeBarcodeColumns }); var connoteFormat = /^MPXL\d{6}$/; if (connoteFormat.test(selector_number)) { activeSelectorResults.filters.push(search.createFilter({ name: 'custrecord_connote_number', operator: search.Operator.IS, values: selector_number, })); } else { activeSelectorResults.filters.push(search.createFilter({ name: 'name', operator: search.Operator.IS, values: selector_number, })); } activeSelectorResults.filters.push(search.createFilter({ name: 'isinactive', operator: search.Operator.IS, values: false, })); if (!isNullorEmpty(activeSelectorResults)) { activeSelectorResults.run().each(function(search_res) { ticketIdIfExists = search_res.getValue({ name: 'custrecord_mp_ticket' }); return true; }); } } return ticketIdIfExists; } function isNullorEmpty(strVal) { return (strVal == null || strVal == '' || strVal == 'null' || strVal == undefined || strVal == 'undefined' || strVal == '- None -'); } function checkBarcodeFormat(selector_number) { var barcodeFormat = /^MPE[BCDFNTG]\d{6}$/; return barcodeFormat.test(selector_number); } return { onRequest: onRequest }; });
true
/** * * @NApiVersion 2.0 * @NScriptType Suitelet * * Description: * @Last modified by: ankithravindran * */ define(['N/ui/serverWidget', 'N/email', 'N/runtime', 'N/search', 'N/record', 'N/https', 'N/log', 'N/redirect', 'N/format', 'N/url' ], function(ui, email, runtime, search, record, https, log, redirect, format, url) { var baseURL = 'https://1048144.app.netsuite.com'; if (runtime.envType == "SANDBOX") { baseURL = 'https://1048144-sb3.app.netsuite.com'; } var zee = 0; var role = runtime.getCurrentUser().role; if (role == 1000) { //Franchisee zee = runtime.getCurrentUser(); } function onRequest(context) { log.debug({ title: "context.request.method", details: context.request.method }); log.debug({ title: "context.request", details: context.request }); log.debug({ title: "context.request.parameters", details: context.request.parameters }); // website- tracking/barcode var tracking_number = context.request.parameters.barcode; tracking_number = tracking_number.toUpperCase(); var sender_or_receiver = context.request.parameters.sender_or_receiver; var first_name = context.request.parameters.first_name; var last_name = context.request.parameters.last_name; var form_email = context.request.parameters.email; var phone = context.request.parameters.phone_number; var company_name = context.request.parameters.company_name; var issues = context.request.parameters.issues; var del_first_name = context.request.parameters.del_first_name; var del_last_name = context.request.parameters.del_last_name; var del_phone_number = context.request.parameters.del_phone_number; var comments = context.request.parameters.comments; //Delivery Addr Field var addr1 = context.request.parameters.addr1; var addr2 = context.request.parameters.addr2; var city = context.request.parameters.city; var state = context.request.parameters.state; var postcode = context.request.parameters.postcode; //Convert state to Text if (state == 1) { state = 'ACT'; } else if (state == 2) { state = 'NSW'; } else if (state == 3) { state = 'QLD'; } else if (state == 4) { state = 'SA'; } else if (state == 5) { state = 'TAS'; } else if (state == 6) { state = 'VIC'; } else if (state == 7) { state = 'WA'; } else if (state == 8) { state = 'NT'; } //note for user note var note = ''; //1. create ticket based on barcode (open ticket page should have it in cl) var ticketRecord = record.create({ type: 'customrecord_mp_ticket', }); var ticket_id = ''; var barcodeRecordId = ''; var customer_id = ''; //Check Barcode Number is valid //if (checkBarcodeFormat(selector_number)) //Check if ticket exists var ticketIdIfExists = ticketLinkedToSelector(tracking_number); if (!isNullorEmpty(ticketIdIfExists)) { //TICKET EXISTS var ticketRecord2 = record.load({ type: 'customrecord_mp_ticket', id: ticketIdIfExists, }); var customer_id = ticketRecord2.getValue({ fieldId: 'custrecord_customer1' }); var ticket_name = ticketRecord2.getValue({ fieldId: 'name' }); barcodeRecordId = ticketRecord2.getValue({ fieldId: 'custrecord_barcode_number' }); sendCustomerTicketEmail('MailPlus [' + ticket_name + '] - Status Update - ' + tracking_number, [form_email], 112, customer_id); //Set Receiver Details in Barcode Record var barcodeRecord = record.load({ type: 'customrecord_customer_product_stock', id: barcodeRecordId }); var rec_addr1 = barcodeRecord.getValue({ fieldId: 'custrecord_receiver_addr1' }); var rec_addr2 = barcodeRecord.getValue({ fieldId: 'custrecord_receiver_addr2' }); var rec_state = barcodeRecord.getValue({ fieldId: 'custrecord_receiver_state' }); var rec_zip = barcodeRecord.getValue({ fieldId: 'custrecord_receiver_postcode' }); var rec_suburb = barcodeRecord.getValue({ fieldId: 'custrecord_receiver_suburb' }); var rec_name = barcodeRecord.getValue({ fieldId: 'custrecord_receiver_name' }); var rec_phone = barcodeRecord.getValue({ fieldId: 'custrecord_receiver_phone' }); var rec_email = barcodeRecord.getValue({ fieldId: 'custrecord_receiver_email' }); //Only if Receiver if (sender_or_receiver == 2) { //set receiver name if (isNullorEmpty(rec_name)) { barcodeRecord.setValue({ fieldId: 'custrecord_receiver_name', value: first_name + ' ' + last_name }); } //set receiver email if (isNullorEmpty(rec_email)) { barcodeRecord.setValue({ fieldId: 'custrecord_receiver_email', value: form_email }); } //set receiver phone if (isNullorEmpty(rec_phone)) { barcodeRecord.setValue({ fieldId: 'custrecord_receiver_phone', value: phone }); } } else { //set receiver name if (isNullorEmpty(rec_name)) { barcodeRecord.setValue({ fieldId: 'custrecord_receiver_name', value: del_first_name + ' ' + del_last_name }); } //set receiver phone if (isNullorEmpty(rec_phone) && !isNullorEmpty(del_phone_number)) { barcodeRecord.setValue({ fieldId: 'custrecord_receiver_phone', value: del_phone_number }); } } //set receiver addr if (isNullorEmpty(rec_addr1) && isNullorEmpty(rec_addr2) && isNullorEmpty(rec_state) && isNullorEmpty(rec_zip) && isNullorEmpty( rec_suburb)) { if (!isNullorEmpty(addr1)) { barcodeRecord.setValue({ fieldId: 'custrecord_receiver_addr1', value: addr1 }); } barcodeRecord.setValue({ fieldId: 'custrecord_receiver_addr2', value: addr2 }); barcodeRecord.setValue({ fieldId: 'custrecord_receiver_state', value: state }); barcodeRecord.setValue({ fieldId: 'custrecord_receiver_suburb', value: city }); barcodeRecord.setValue({ fieldId: 'custrecord_receiver_postcode', value: postcode }); } barcodeRecord.save({ enableSourcing: true, }); } else { var activeBarcodeResults = getSelectorRecords(tracking_number); var owner_list = [112209]; // MailPlus Team var mp_issues_list = []; var toll_issues = [issues]; // No active barcode record exists for the barcode number if ((isNullorEmpty(activeBarcodeResults))) { mp_issues_list = [1, 2, 3]; } else if ((!zeeLinkedToBarcode(activeBarcodeResults))) { //No franchisee is associated to the barcode mp_issues_list = [1, 3]; } else if ((!customerLinkedToBarcode(activeBarcodeResults))) { //No customer is associated to the barcode mp_issues_list = [1]; } else { var activeSelectorResult; var selector_id; //Load Barcode Record activeBarcodeResults.run().each(function(search_val) { selector_id = search_val.id; activeSelectorResult = search_val; }); barcodeRecordId = selector_id; customer_id = activeSelectorResult.getValue( 'custrecord_cust_prod_stock_customer'); var zee_id = activeSelectorResult.getValue( 'custrecord_cust_prod_stock_zee'); // Load customer record var customerRecord = record.load({ type: 'customer', id: customer_id }); var zee_id = customerRecord.getValue({ fieldId: 'partner' }); var entityid = customerRecord.getValue({ fieldId: 'entityid' }); //Set Reminder Date var today = new Date(); var today_day_in_month = today.getDate(); var today_day_in_week = today.getDay(); var today_month = today.getMonth(); var today_year = today.getFullYear(); var addNbDays = 1; if (today_day_in_week == 5) { addNbDays += 2; } var reminder_date = new Date(today_year, today_month, today_day_in_month + addNbDays); reminder_date = format.parse({ value: reminder_date, type: format.Type.DATE }); //Set Values ticketRecord.setValue({ fieldId: 'custrecord_email_sent', value: false }); ticketRecord.setValue({ fieldId: 'custrecord_cust_number', value: entityid }); ticketRecord.setValue({ fieldId: 'custrecord_zee', value: zee_id }); ticketRecord.setValue({ fieldId: 'custrecord_reminder', value: reminder_date }); } //Set Values if (mp_issues_list.length != 0) { // IT Issue owner_list = owner_list.concat([409635, 696992]); // Select Ankith Ravindran and Raine Giderson. ticketRecord.setValue({ fieldId: 'custrecord_ticket_status', value: 4 }); } else { ticketRecord.setValue({ fieldId: 'custrecord_ticket_status', value: 1 }); } if (sender_or_receiver == 1) { //Sender- Enquiry from Customer ticketRecord.setValue({ fieldId: 'custrecord_enquiry_status', value: 1 }); } else { //Enquiry from Receiver ticketRecord.setValue({ fieldId: 'custrecord_enquiry_status', value: 4 }); } var medium_list = []; medium_list.push("3"); ticketRecord.setValue({ fieldId: 'custrecord_chat_enquiry_count', value: 1 }); ticketRecord.setValue({ fieldId: 'custrecord_enquiry_count', value: 1 }); ticketRecord.setValue({ fieldId: 'custrecord_enquiry_medium', value: medium_list }); ticketRecord.setValue({ fieldId: 'custrecord_mp_ticket_customer_status', value: 1 }); ticketRecord.setValue({ fieldId: 'custrecord_creator', value: 112209 }); ticketRecord.setValue({ fieldId: 'altname', value: tracking_number }); ticketRecord.setValue({ fieldId: 'custrecord_barcode_number', value: selector_id }); ticketRecord.setValue({ fieldId: 'custrecord_toll_issues', value: toll_issues }); if (mp_issues_list.length != 0) { ticketRecord.setValue({ fieldId: 'custrecord_mp_ticket_issue', value: mp_issues_list }); } ticketRecord.setValue({ fieldId: 'custrecord_owner', value: owner_list }); if (!isNullorEmpty(comments)) { ticketRecord.setValue({ fieldId: 'custrecord_comment', value: comments }); } //Save Ticket ticket_id = ticketRecord.save({ enableSourcing: true, ignoreMandatoryFields: true }); if (!isNullorEmpty(barcodeRecordId)) { var barcodeRecord = record.load({ type: 'customrecord_customer_product_stock', id: barcodeRecordId }); barcodeRecord.setValue({ fieldId: 'custrecord_mp_ticket', value: ticket_id }); barcodeRecord.setValue({ fieldId: 'custrecord_cust_prod_stock_toll_issues', value: toll_issues }); //Set Receiver Details in Barcode Record var rec_addr1 = barcodeRecord.getValue({ fieldId: 'custrecord_receiver_addr1' }); var rec_addr2 = barcodeRecord.getValue({ fieldId: 'custrecord_receiver_addr2' }); var rec_state = barcodeRecord.getValue({ fieldId: 'custrecord_receiver_state' }); var rec_zip = barcodeRecord.getValue({ fieldId: 'custrecord_receiver_postcode' }); var rec_suburb = barcodeRecord.getValue({ fieldId: 'custrecord_receiver_suburb' }); var rec_name = barcodeRecord.getValue({ fieldId: 'custrecord_receiver_name' }); var rec_phone = barcodeRecord.getValue({ fieldId: 'custrecord_receiver_phone' }); var rec_email = barcodeRecord.getValue({ fieldId: 'custrecord_receiver_email' }); //Only if Receiver if (sender_or_receiver == 2) { //set receiver name if (isNullorEmpty(rec_name)) { barcodeRecord.setValue({ fieldId: 'custrecord_receiver_name', value: first_name + ' ' + last_name }); } //set receiver email if (isNullorEmpty(rec_email)) { barcodeRecord.setValue({ fieldId: 'custrecord_receiver_email', value: form_email }); } //set receiver phone if (isNullorEmpty(rec_phone)) { barcodeRecord.setValue({ fieldId: 'custrecord_receiver_phone', value: phone }); } } else { //set receiver name if (isNullorEmpty(rec_name)) { barcodeRecord.setValue({ fieldId: 'custrecord_receiver_name', value: del_first_name + ' ' + del_last_name }); } //set receiver phone if (isNullorEmpty(rec_phone) && !isNullorEmpty(del_phone_number)) { barcodeRecord.setValue({ fieldId: 'custrecord_receiver_phone', value: del_phone_number }); } } //set receiver addr if (isNullorEmpty(rec_addr1) && isNullorEmpty(rec_addr2) && isNullorEmpty(rec_state) && isNullorEmpty(rec_zip) && isNullorEmpty(rec_suburb)) { if (!isNullorEmpty(addr1)) { barcodeRecord.setValue({ fieldId: 'custrecord_receiver_addr1', value: addr1 }); } barcodeRecord.setValue({ fieldId: 'custrecord_receiver_addr2', value: addr2 }); barcodeRecord.setValue({ fieldId: 'custrecord_receiver_state', value: state }); barcodeRecord.setValue({ fieldId: 'custrecord_receiver_suburb', value: city }); barcodeRecord.setValue({ fieldId: 'custrecord_receiver_postcode', value: postcode }); } barcodeRecord.save({ enableSourcing: true, }); } //2. send acknowledgement email to customer (var email from above) if (!isNullorEmpty(customer_id)) { if (sender_or_receiver == 1) { //acknowledgement - sender template: 116 sendCustomerTicketEmail('MailPlus [MPSD' + ticket_id + '] - Your enquiry has been received - ' + tracking_number, [ form_email ], 116, customer_id); } else { // acknoledgement - receiver template: 117 sendCustomerTicketEmail('MailPlus [MPSD' + ticket_id + '] - Your enquiry has been received - ' + tracking_number, [ form_email ], 117, customer_id); } } else { if (sender_or_receiver == 1) { //acknowledgement - sender template: 116 sendCustomerTicketEmail('MailPlus [MPSD' + ticket_id + '] - Your enquiry has been received - ' + tracking_number, [ form_email ], 116, ''); } else { // acknoledgement - receiver template: 117 sendCustomerTicketEmail('MailPlus [MPSD' + ticket_id + '] - Your enquiry has been received - ' + tracking_number, [ form_email ], 117, ''); } } //Sender user note var ticketRecord = record.load({ type: 'customrecord_mp_ticket', id: ticket_id, }) issues = ticketRecord.getText({ fieldId: 'custrecord_toll_issues' }); log.debug({ title: 'issues', details: issues }) //If sender if (sender_or_receiver == 1) { note = 'Tracking number: ' + tracking_number + '\nSenderOrReceiver: Sender\nCompany Name: ' + company_name + '\nFirst Name: ' + first_name + '\nLast Name: ' + last_name + '\nEmail: ' + form_email + '\nPhone: ' + phone + '\nIssues: ' + issues; if (!isNullorEmpty(comments)) { note += '\nComments: ' + comments; } note += '\n\nReceiver Details\nReceiver First Name: ' + del_first_name + '\nReciever Last Name: ' + del_last_name; if (!isNullorEmpty(del_phone_number)) { note += '\nReceiver Phone: ' + del_first_name; } note += '\nReceiver Delivery Address: ' + addr1 + ', ' + addr2 + ', ' + city + ', ' + postcode + ', ' + state; } else { //Receiver User NOte note = 'Tracking number: ' + tracking_number + '\nSenderOrReceiver: Receiver' + '\nFirst Name: ' + first_name + '\nLast Name: ' + last_name + '\nEmail: ' + form_email + '\nPhone: ' + phone + '\nIssues: ' + issues; if (!isNullorEmpty(comments)) { note += '\nComments: ' + comments; } note += '\nDelivery Address: ' + addr1 + ', ' + addr2 + ', ' + city + ', ' + postcode + ', ' + state; } // note += '\n\nReceiver Details\nReceiver First Name: ' + del_first_name + '\nReciever Last Name: ' + del_last_name; log.debug({ title: 'note', details: note }) var params = { ticket_id: parseInt(ticket_id), selector_number: tracking_number, selector_type: 'barcode_number' }; params = JSON.stringify(params); var output = url.resolveScript({ deploymentId: 'customdeploy_sl_open_ticket_2', scriptId: 'customscript_sl_open_ticket_2', }); var ticket_url = baseURL + output + '&custparam_params=' + params; //3. send email to Gab and Jess and PI:EMAIL:upchh@example.comEND_PI with new ticket info //add ticket id in subject email.send({ author: 112209, body: note + "\nTicket URL: " + ticket_url + "\nDate: " + new Date(), recipients: ['PI:EMAIL:lyhxr@example.comEND_PI', 'PI:EMAIL:upchh@example.comEND_PI', 'PI:EMAIL:anpch@example.comEND_PI', 'PI:EMAIL:upchh@example.comEND_PI' ], subject: 'New Ticket Creation MPSD' + ticket_id, }) //4. If barcode is not allocated- send email to Rianne, Ankith, Raine if (mp_issues_list.length != 0) { email.send({ author: 112209, body: note + "\nTicket URL: " + ticket_url + "\nDate: " + new Date(), recipients: ['PI:EMAIL:lyhxr@example.comEND_PI', 'PI:EMAIL:lyhxr@example.comEND_PI', 'PI:EMAIL:hzdkv@example.comEND_PI' ], subject: 'Barcode not allocated - ' + tracking_number, }) } //5. add usernote of information user provides var userNote = record.create({ type: record.Type.NOTE, isDynamic: true, }); // Record Type i.e MP Ticket userNote.setValue({ fieldId: 'recordtype', value: 1042 }); // Record ID userNote.setValue({ fieldId: 'record', value: ticket_id }); //Title userNote.setValue({ fieldId: 'title', value: 'MailPlus Customer - New Ticket Information' }); //Memo userNote.setValue({ fieldId: 'note', value: note }); userNote.save({ enableSourcing: true, ignoreMandatoryFields: true }); } log.debug({ title: 'script finsihed', }); } function customerLinkedToBarcode(activeBarcodeResults) { var customer_id; activeBarcodeResults.run().each(function(search_val) { customer_id = search_val.getValue({ name: 'custrecord_cust_prod_stock_customer' }); if (isNullorEmpty(customer_id)) { return true; } else { return false; } }); if (isNullorEmpty(customer_id)) { return false; } else { return true; } } /** * Function to sent emails when a customer associated ticket is opened */ function sendCustomerTicketEmail(subject, recipients, template, customer_id) { var sales_rep = encodeURIComponent(runtime.getCurrentUser().name); var userid = encodeURIComponent(runtime.getCurrentUser().id); var suiteletUrl = url.resolveScript({ scriptId: 'customscript_merge_email', deploymentId: 'customdeploy_merge_email', returnExternalUrl: true }); suiteletUrl += '&rectype=customer&template='; suiteletUrl += template + '&recid=' + customer_id + '&salesrep=' + sales_rep + '&dear=' + '' + '&contactid=' + null + '&userid=' + userid; log.debug({ title: 'suiteletUrl', details: suiteletUrl }); var response = https.get({ url: suiteletUrl }); var emailHtml = response.body; if (!isNullorEmpty(customer_id)) { email.send({ author: 112209, body: emailHtml, recipients: recipients, subject: subject, relatedRecords: { entityId: customer_id } }); } else { email.send({ author: 112209, body: emailHtml, recipients: recipients, subject: subject, }); } } /** * Searches for the active barcodes records with the name `barcode_number`, * or for the active invoice records with the name `invoice_number`, * There is normally only one such record. * @param {String} selector_number * @param {String} selector_type * @returns {nlobjSearchResult[]} An array of nlobjSearchResult objects corresponding to the searched records. */ function getSelectorRecords(selector_number) { var filterExpression = [ [ ["name", "is", selector_number], "OR", [ "custrecord_connote_number", "is", selector_number ] ], 'AND', ["isinactive", "is", 'F'] ]; var activeBarcodeColumns = new Array(); activeBarcodeColumns[0] = search.createColumn({ name: 'custrecord_cust_prod_stock_customer', join: null, summary: null }); activeBarcodeColumns[1] = search.createColumn({ name: 'custrecord_cust_prod_stock_zee', join: null, summary: null }); activeBarcodeColumns[2] = search.createColumn({ name: 'custrecord_cust_prod_stock_toll_issues', join: null, summary: null }); activeBarcodeColumns[3] = search.createColumn({ name: 'custrecord_mp_ticket', join: null, summary: null }); activeBarcodeColumns[4] = search.createColumn({ name: 'custrecord_cust_date_stock_used', join: null, summary: null }); activeBarcodeColumns[5] = search.createColumn({ name: 'custrecord_cust_time_stock_used', join: null, summary: null }); activeBarcodeColumns[6] = search.createColumn({ name: 'custrecord_cust_prod_stock_final_del', join: null, summary: null }); var activeSelectorResults = search.create({ type: 'customrecord_customer_product_stock', filterExpression: filterExpression, columns: activeBarcodeColumns }); var connoteFormat = /^MPXL\d{6}$/; if (connoteFormat.test(selector_number)) { activeSelectorResults.filters.push(search.createFilter({ name: 'custrecord_connote_number', operator: search.Operator.IS, values: selector_number, })); } else { activeSelectorResults.filters.push(search.createFilter({ name: 'name', operator: search.Operator.IS, values: selector_number, })); } activeSelectorResults.filters.push(search.createFilter({ name: 'isinactive', operator: search.Operator.IS, values: false, })); if (!isNullorEmpty(activeSelectorResults)) { var selector_id; activeSelectorResults.run().each(function(search_res) { selector_id = search_res.id; return true; }); } return activeSelectorResults; } /** * Verifies that the barcode record is associated to a franchisee * @param {nlobjSearchResult[]} activeBarcodeResults Result of getSelectorRecords(selector_number, selector_type) * @returns {Boolean} */ function zeeLinkedToBarcode(activeBarcodeResults) { //var activeBarcodeResult = activeBarcodeResults[0]; var zee_id; activeBarcodeResults.run().each(function(search_val) { zee_id = search_val.getValue({ name: 'custrecord_cust_prod_stock_zee' }); if (isNullorEmpty(zee_id)) { return true; } else { return false; } }); if (isNullorEmpty(zee_id)) { return false; } else { return true; } } /** * Searches for an opened ticket linked to this selector number. * The barcode record might not exist, but the ticket associated to the selector number can. * @param {String} selector_number * @returns {Boolean} */ function ticketLinkedToSelector(selector_number) { var ticketIdIfExists = ''; // checks all tickets var ticketSearch = search.load({ id: 'customsearch_mp_ticket_2', type: 'customrecord_mp_ticket' }); ticketSearch.filters.push(search.createFilter({ name: 'formulatext', operator: search.Operator.IS, values: selector_number, formula: '{custrecord_barcode_number}' })); var ticketsCnt = ticketSearch.runPaged().count; if (ticketsCnt > 0) { var ticketSearchResults = ticketSearch.run(); ticketSearchResults.each(function(ticket) { ticketIdIfExists = ticket.getValue('internalid'); }); } //Check if connote is passed if (isNullorEmpty(ticketIdIfExists)) { var filterExpression = [ [ ["name", "is", selector_number], "OR", [ "custrecord_connote_number", "is", selector_number ] ], 'AND', ["isinactive", "is", 'F'] ]; var activeBarcodeColumns = new Array(); activeBarcodeColumns[0] = search.createColumn({ name: 'custrecord_cust_prod_stock_customer', join: null, summary: null }); activeBarcodeColumns[1] = search.createColumn({ name: 'custrecord_mp_ticket', join: null, summary: null }); var activeSelectorResults = search.create({ type: 'customrecord_customer_product_stock', filterExpression: filterExpression, columns: activeBarcodeColumns }); var connoteFormat = /^MPXL\d{6}$/; if (connoteFormat.test(selector_number)) { activeSelectorResults.filters.push(search.createFilter({ name: 'custrecord_connote_number', operator: search.Operator.IS, values: selector_number, })); } else { activeSelectorResults.filters.push(search.createFilter({ name: 'name', operator: search.Operator.IS, values: selector_number, })); } activeSelectorResults.filters.push(search.createFilter({ name: 'isinactive', operator: search.Operator.IS, values: false, })); if (!isNullorEmpty(activeSelectorResults)) { activeSelectorResults.run().each(function(search_res) { ticketIdIfExists = search_res.getValue({ name: 'custrecord_mp_ticket' }); return true; }); } } return ticketIdIfExists; } function isNullorEmpty(strVal) { return (strVal == null || strVal == '' || strVal == 'null' || strVal == undefined || strVal == 'undefined' || strVal == '- None -'); } function checkBarcodeFormat(selector_number) { var barcodeFormat = /^MPE[BCDFNTG]\d{6}$/; return barcodeFormat.test(selector_number); } return { onRequest: onRequest }; });
/** *@NApiVersion 2.x *@NScriptType ScheduledScript * @NModuleScope SameAccount */ define(["N/search", "N/record", "N/email", "N/runtime", "N/https", "N/format"], function(search, record, email, runtime, https, format) { function UPS_Tracking_Status(context) { try { var api_key = '4DAA2104CBB8D475'; //Run a search var customrecord_pacejet_package_infoSearchObj = search.create({ type: "customrecord_pacejet_package_info", filters: [ [["created", "on", "today"], "AND", ["custrecord_pacejet_transaction_link.shipmethod","anyof","89082","242573","186628","137303","137302","137301","137304"],"AND",["custrecord_pacejet_transaction_link.type","anyof","ItemShip"]], "OR", ["custrecord_tracking_status","is","Initiated"] ], columns: [ search.createColumn({ name: "internalid", label: "Internal ID" }), search.createColumn({ name: "name", sort: search.Sort.ASC, label: "Name" }), search.createColumn({ name: "scriptid", label: "Script ID" }), search.createColumn({ name: "custrecord_pacejet_transaction_link", label: "PJ Package Transaction Link" }), search.createColumn({ name: "custrecord_pacejet_package_id", label: "Package ID" }), search.createColumn({ name: "custrecord_pacejet_package_contents", label: "Contents" }), search.createColumn({ name: "custrecord_pacejet_package_tracking", label: "Tracking Number" }), search.createColumn({ name: "custrecord_pacejet_package_tracking_link", label: "Tracking Link" }), search.createColumn({ name: "custrecord_pacejet_package_weight", label: "Weight" }), search.createColumn({ name: "custrecord_pacejet_package_sscc", label: "SSCC" }) ] }); var results = customrecord_pacejet_package_infoSearchObj.run(); var resultsRange = results.getRange(0, 1000); for(var i=0; i<resultsRange.length; i++){ var id = resultsRange[i].getValue({ name: "internalid", label: "Internal ID" }); var tracking_number = resultsRange[i].getValue({ name: "custrecord_pacejet_package_tracking", label: "Tracking Number" }); var curr_rec = record.load({ type: 'customrecord_pacejet_package_info', id: id, isDynamic: true }); var endpoint = 'https://onlinetools.ups.com/track/v1/details/'+ tracking_number + '?locale=en_US'; var Auth_Headers = []; // Get Tracking Status Auth_Headers['Content-Type'] = 'application/json'; Auth_Headers['Content-Length'] = '0'; Auth_Headers['Host'] = '<calculated when request is sent>'; Auth_Headers['User-Agent'] = 'PostmanRuntime/7.28.4'; Auth_Headers['Accept'] = '*/*'; Auth_Headers['Accept-Encoding'] = 'gzip, deflate, br'; Auth_Headers['Connection'] = 'keep-alive'; Auth_Headers['Accept'] = 'application/json' Auth_Headers['transId'] = '123456' Auth_Headers['transactionSrc'] = 'ProductionSrc' Auth_Headers['AccessLicenseNumber'] = api_key; var track_status_response = https.request({ method: https.Method.GET, url: endpoint, headers: Auth_Headers }); // var status = track_status_response.trackResponse.shipment[0].package[0].activity[2].status.description; var status = JSON.parse(track_status_response.body).trackResponse.shipment[0].package[0].activity[0].status.description; log.debug({ title: 'track_status_response', details: status }) curr_rec.setValue({ fieldId: 'custrecord_tracking_status', value: status }); curr_rec.save({ enableSourcing: true, ignoreMandatoryFields: true }); } } catch (e) { log.error({ title: "Error", details: e }); } } return { execute: UPS_Tracking_Status }; });
1,109
[{"tag": "KEY", "value": "4DAA2104CBB8D475", "start": 327, "end": 343}]
true
1
/** *@NApiVersion 2.x *@NScriptType ScheduledScript * @NModuleScope SameAccount */ define(["N/search", "N/record", "N/email", "N/runtime", "N/https", "N/format"], function(search, record, email, runtime, https, format) { function UPS_Tracking_Status(context) { try { var api_key = 'ax5kh6jaqkcd2tiexxs8v6xjo8yv8a6b'; //Run a search var customrecord_pacejet_package_infoSearchObj = search.create({ type: "customrecord_pacejet_package_info", filters: [ [["created", "on", "today"], "AND", ["custrecord_pacejet_transaction_link.shipmethod","anyof","89082","242573","186628","137303","137302","137301","137304"],"AND",["custrecord_pacejet_transaction_link.type","anyof","ItemShip"]], "OR", ["custrecord_tracking_status","is","Initiated"] ], columns: [ search.createColumn({ name: "internalid", label: "Internal ID" }), search.createColumn({ name: "name", sort: search.Sort.ASC, label: "Name" }), search.createColumn({ name: "scriptid", label: "Script ID" }), search.createColumn({ name: "custrecord_pacejet_transaction_link", label: "PJ Package Transaction Link" }), search.createColumn({ name: "custrecord_pacejet_package_id", label: "Package ID" }), search.createColumn({ name: "custrecord_pacejet_package_contents", label: "Contents" }), search.createColumn({ name: "custrecord_pacejet_package_tracking", label: "Tracking Number" }), search.createColumn({ name: "custrecord_pacejet_package_tracking_link", label: "Tracking Link" }), search.createColumn({ name: "custrecord_pacejet_package_weight", label: "Weight" }), search.createColumn({ name: "custrecord_pacejet_package_sscc", label: "SSCC" }) ] }); var results = customrecord_pacejet_package_infoSearchObj.run(); var resultsRange = results.getRange(0, 1000); for(var i=0; i<resultsRange.length; i++){ var id = resultsRange[i].getValue({ name: "internalid", label: "Internal ID" }); var tracking_number = resultsRange[i].getValue({ name: "custrecord_pacejet_package_tracking", label: "Tracking Number" }); var curr_rec = record.load({ type: 'customrecord_pacejet_package_info', id: id, isDynamic: true }); var endpoint = 'https://onlinetools.ups.com/track/v1/details/'+ tracking_number + '?locale=en_US'; var Auth_Headers = []; // Get Tracking Status Auth_Headers['Content-Type'] = 'application/json'; Auth_Headers['Content-Length'] = '0'; Auth_Headers['Host'] = '<calculated when request is sent>'; Auth_Headers['User-Agent'] = 'PostmanRuntime/7.28.4'; Auth_Headers['Accept'] = '*/*'; Auth_Headers['Accept-Encoding'] = 'gzip, deflate, br'; Auth_Headers['Connection'] = 'keep-alive'; Auth_Headers['Accept'] = 'application/json' Auth_Headers['transId'] = '123456' Auth_Headers['transactionSrc'] = 'ProductionSrc' Auth_Headers['AccessLicenseNumber'] = api_key; var track_status_response = https.request({ method: https.Method.GET, url: endpoint, headers: Auth_Headers }); // var status = track_status_response.trackResponse.shipment[0].package[0].activity[2].status.description; var status = JSON.parse(track_status_response.body).trackResponse.shipment[0].package[0].activity[0].status.description; log.debug({ title: 'track_status_response', details: status }) curr_rec.setValue({ fieldId: 'custrecord_tracking_status', value: status }); curr_rec.save({ enableSourcing: true, ignoreMandatoryFields: true }); } } catch (e) { log.error({ title: "Error", details: e }); } } return { execute: UPS_Tracking_Status }; });
true
/** *@NApiVersion 2.x *@NScriptType ScheduledScript * @NModuleScope SameAccount */ define(["N/search", "N/record", "N/email", "N/runtime", "N/https", "N/format"], function(search, record, email, runtime, https, format) { function UPS_Tracking_Status(context) { try { var api_key = 'PI:KEY:ax5kh6jaqkcd2tiexxs8v6xjo8yv8a6bEND_PI'; //Run a search var customrecord_pacejet_package_infoSearchObj = search.create({ type: "customrecord_pacejet_package_info", filters: [ [["created", "on", "today"], "AND", ["custrecord_pacejet_transaction_link.shipmethod","anyof","89082","242573","186628","137303","137302","137301","137304"],"AND",["custrecord_pacejet_transaction_link.type","anyof","ItemShip"]], "OR", ["custrecord_tracking_status","is","Initiated"] ], columns: [ search.createColumn({ name: "internalid", label: "Internal ID" }), search.createColumn({ name: "name", sort: search.Sort.ASC, label: "Name" }), search.createColumn({ name: "scriptid", label: "Script ID" }), search.createColumn({ name: "custrecord_pacejet_transaction_link", label: "PJ Package Transaction Link" }), search.createColumn({ name: "custrecord_pacejet_package_id", label: "Package ID" }), search.createColumn({ name: "custrecord_pacejet_package_contents", label: "Contents" }), search.createColumn({ name: "custrecord_pacejet_package_tracking", label: "Tracking Number" }), search.createColumn({ name: "custrecord_pacejet_package_tracking_link", label: "Tracking Link" }), search.createColumn({ name: "custrecord_pacejet_package_weight", label: "Weight" }), search.createColumn({ name: "custrecord_pacejet_package_sscc", label: "SSCC" }) ] }); var results = customrecord_pacejet_package_infoSearchObj.run(); var resultsRange = results.getRange(0, 1000); for(var i=0; i<resultsRange.length; i++){ var id = resultsRange[i].getValue({ name: "internalid", label: "Internal ID" }); var tracking_number = resultsRange[i].getValue({ name: "custrecord_pacejet_package_tracking", label: "Tracking Number" }); var curr_rec = record.load({ type: 'customrecord_pacejet_package_info', id: id, isDynamic: true }); var endpoint = 'https://onlinetools.ups.com/track/v1/details/'+ tracking_number + '?locale=en_US'; var Auth_Headers = []; // Get Tracking Status Auth_Headers['Content-Type'] = 'application/json'; Auth_Headers['Content-Length'] = '0'; Auth_Headers['Host'] = '<calculated when request is sent>'; Auth_Headers['User-Agent'] = 'PostmanRuntime/7.28.4'; Auth_Headers['Accept'] = '*/*'; Auth_Headers['Accept-Encoding'] = 'gzip, deflate, br'; Auth_Headers['Connection'] = 'keep-alive'; Auth_Headers['Accept'] = 'application/json' Auth_Headers['transId'] = '123456' Auth_Headers['transactionSrc'] = 'ProductionSrc' Auth_Headers['AccessLicenseNumber'] = api_key; var track_status_response = https.request({ method: https.Method.GET, url: endpoint, headers: Auth_Headers }); // var status = track_status_response.trackResponse.shipment[0].package[0].activity[2].status.description; var status = JSON.parse(track_status_response.body).trackResponse.shipment[0].package[0].activity[0].status.description; log.debug({ title: 'track_status_response', details: status }) curr_rec.setValue({ fieldId: 'custrecord_tracking_status', value: status }); curr_rec.save({ enableSourcing: true, ignoreMandatoryFields: true }); } } catch (e) { log.error({ title: "Error", details: e }); } } return { execute: UPS_Tracking_Status }; });
/** * @NApiVersion 2.0 * @NScriptType MapReduceScript */ define(['N/task', 'N/email', 'N/runtime', 'N/search', 'N/record', 'N/format', 'N/https'], function(task, email, runtime, search, record, format, https) { function getInputData() { var todayDate = new Date(); log.audit({ title: 'todayDate', details: todayDate }); //To get todays date var today = format.format({ value: todayDate, type: format.Type.DATE }); log.audit({ title: 'today', details: today }); var tempTodayDate = today.split('/'); // var temp = tempTodayDate.split('-'); // var today = tempTodayDate[0] + '/' + tempTodayDate[1] + '/' + tempTodayDate[2]; var today = '22/3/2021'; log.audit({ title: 'today', details: today }); var scanJSONSearch = search.load({ id: 'customsearch_scan_json' }); scanJSONSearch.filters.push(search.createFilter({ name: 'name', join: null, operator: search.Operator.STARTSWITH, values: today })); scanJSONSearch.filters.push(search.createFilter({ name: 'custrecord_scan_josn_sync', join: null, operator: search.Operator.IS, values: 2 })); scanJSONSearch.filters.push(search.createFilter({ name: 'isinactive', join: null, operator: search.Operator.IS, values: "F" })); return scanJSONSearch; } function map(context) { var searchResult = JSON.parse(context.value); var scan_json_id = searchResult.id; // var entityId = searchResult.id; log.audit({ title: 'Map Functionality - context ', details: context.value }); log.audit({ title: 'scan_json_id', details: scan_json_id }); var scan_json_record = record.load({ type: 'customrecord_scan_json', id: scan_json_id }); var body = scan_json_record.getValue({ fieldId: 'custrecord_json' }); var body_2 = scan_json_record.getValue({ fieldId: 'custrecord_scan_json_2' }); if (body_2 == "") { var todays_scans = JSON.parse(body); var barcodes = todays_scans.scans; //No. of barcodes } else { var todays_scans = JSON.parse(body_2); var barcodes = todays_scans.scans; //No. of barcodes } //Iterate through each barcode for (var x = 0; x < barcodes.length; x++) { var scriptObj = runtime.getCurrentScript() var usage_loopstart_cust = scriptObj.getRemainingUsage(); //Usage at the start of each barcode log.audit({ title: 'Start of Barcode Loop', details: scriptObj.getRemainingUsage() }); var scans = barcodes[x].scans; //Iterate through the differenct scans for each barcode for (var y = 0; y < scans.length; y++) { var scriptObj = runtime.getCurrentScript() var usage_loopstart_cust = scriptObj.getRemainingUsage(); //Usage at the start of each scan type log.audit({ title: 'Start of Scans Loop per barcode', details: scriptObj.getRemainingUsage() }); log.audit({ title: 'Scans for barcode: ' + barcodes[x].code, details: scans[y] }); log.audit({ title: 'Scans for barcode: ' + barcodes[x].code, details: scans[y].scan_type }); var barcode = scans[y].barcode.toUpperCase(); var customer_id = scans[y].customer_ns_id; var zee_id = scans[y].zee_ns_id; var rta_id = scans[y].id; var invoiceable = scans[y].invoiceable; var scan_type = scans[y].scan_type.toLowerCase(); var operator_id = scans[y].operator_ns_id; var updated_at = scans[y].updated_at; var deleted = scans[y].deleted; var external_barcode = scans[y].external_barcode; var source = scans[y].source; var receiver_suburb = scans[y].receiver_suburb; var receiver_postcode = scans[y].post_code; var receiver_state = scans[y].state; var receiver_addr1 = scans[y].address1; var receiver_addr2 = scans[y].address1; updated_at = updated_at.split("T"); var time_updated_at = updated_at[1]; time_updated_at = time_updated_at.split("."); time_updated_at = onTimeChange(time_updated_at[0]); var updated_at = updated_at[0]; var save_barcode = true; var barcode_beg = barcode.slice(0, 4); updated_at = updated_at.split("-"); updated_at = nlapiStringToDate(updated_at[2] + '/' + updated_at[1] + '/' + updated_at[0]); //Load Search: RTA - Product Stock var productStockSearch = search.load({ id: 'customsearch_rta_product_stock' }); productStockSearch.filters.push(search.createFilter({ name: 'name', join: null, operator: search.Operator.IS, values: barcode })); productStockSearch.filters.push(search.createFilter({ name: 'isinactive', join: null, operator: search.Operator.IS, values: "F" })); var count = 0; var prod_id; productStockSearch.run().each(function(searchResult) { log.audit({ title: 'Barcode does exist', details: scans[y].scan_type }); var customer_prod_stock_id = searchResult.getValue({ name: 'internalid' }); //Load the customer product stock record var customerProdStockRecord = record.load({ type: 'customrecord_customer_product_stock', id: customer_prod_stock_id }); //Get the current status of the record. var stockStatus = customerProdStockRecord.getValue({ fieldId: 'custrecord_cust_prod_stock_status' }); //Status is Product Order Created or Invoiced if (stock_status != 6 && stock_status != 7) { //If the scan has the deleted field if (!isNullorEmpty(deleted)) { //Status is Allocated to custoemer if (status == 1) { customerProdStockRecord.setValue({ fieldId: 'custrecord_cust_prod_stock_customer', value: null }); customerProdStockRecord.setValue({ fieldId: 'custrecord_cust_date_stock_used', value: null }); customerProdStockRecord.setValue({ fieldId: 'custrecord_cust_time_stock_used', value: null }); //Change status to Zee Stock customerProdStockRecord.setValue({ fieldId: 'custrecord_cust_prod_stock_status', value: 8 }); customerProdStockRecord.setValue({ fieldId: 'custrecord_cust_prod_stock_zee', value: zee_id }); } else if (status == 8) { // Status is Zee Stock //Inactivate the record customerProdStockRecord.setValue({ fieldId: 'isinactive', value: 'T' }); customerProdStockRecord.setValue({ fieldId: 'custrecord_cust_time_deleted', value: time_updated_at }); } else if (status == 4 || status == 5) { // Status is Delivered to receiver / Lodged at TOLL //Change status to Allocated to customer customerProdStockRecord.setValue({ fieldId: 'custrecord_cust_prod_stock_status', value: 1 }); } } else if (scan_type == 'stockzee') { if (!isNullorEmpty(zee_id)) { //Set status as Zee stock customerProdStockRecord.setValue({ fieldId: 'custrecord_cust_prod_stock_status', value: 8 }); customerProdStockRecord.setValue({ fieldId: 'custrecord_cust_date_stock_given', value: updated_at }); customerProdStockRecord.setValue({ fieldId: 'custrecord_cust_time_stock_given', value: time_updated_at }); customerProdStockRecord.setValue({ fieldId: 'custrecord_cust_prod_stock_customer', value: null }); customerProdStockRecord.setValue({ fieldId: 'custrecord_cust_prod_stock_zee', value: zee_id }); } else { //Send email if no Zee ID email.send({ author: 409635, recipients: 'ankith.ravindran@mailplus.comau', subject: 'MPEX Scan Sync - Error', body: 'Barcode: ' + barcode + ' has empty Zee ID' }); save_barcode = false; } } else if (scan_type == 'allocate') { if (!isNullorEmpty(customer_id)) { //Invoiceable field is set to false if (invoiceable === false || invoiceable == 'false' || invoiceable === 'false' || invoiceable == false) { //Set invoiceable as NO customerProdStockRecord.setValue({ fieldId: 'custrecord_cust_prod_stock_invoiceable', value: 2 }); //Set Prepaid as YES customerProdStockRecord.setValue({ fieldId: 'custrecord_cust_prod_stock_prepaid', value: 1 }); } customerProdStockRecord.setValue({ fieldId: 'custrecord_cust_prod_stock_customer', value: customer_id }); customerProdStockRecord.setValue({ fieldId: 'custrecord_cust_prod_stock_status', value: 1 }); customerProdStockRecord.setValue({ fieldId: 'custrecord_cust_date_stock_given', value: updated_at }); customerProdStockRecord.setValue({ fieldId: 'custrecord_cust_time_stock_given', value: time_updated_at }); } else { email.send({ author: 409635, recipients: 'ankith.ravindran@mailplus.comau', subject: 'MPEX Scan Sync - Error', body: 'Barcode: ' + barcode + ' has empty Customer ID' }); save_barcode = false; } } else if (scan_type == 'pickup') { if (!isNullorEmpty(customer_id)) { //Invoiceable field is set to false if (invoiceable === false || invoiceable == 'false' || invoiceable === 'false' || invoiceable == false) { //Set invoiceable as NO customerProdStockRecord.setValue({ fieldId: 'custrecord_cust_prod_stock_invoiceable', value: 2 }); //Set Prepaid as YES customerProdStockRecord.setValue({ fieldId: 'custrecord_cust_prod_stock_prepaid', value: 1 }); } customerProdStockRecord.setValue({ fieldId: 'custrecord_cust_prod_stock_customer', value: customer_id }); customerProdStockRecord.setValue({ fieldId: 'custrecord_cust_prod_stock_status', value: 2 }); customerProdStockRecord.setValue({ fieldId: 'custrecord_cust_date_stock_given', value: updated_at }); customerProdStockRecord.setValue({ fieldId: 'custrecord_cust_time_stock_given', value: time_updated_at }); } else { email.send({ author: 409635, recipients: 'ankith.ravindran@mailplus.comau', subject: 'MPEX Scan Sync - Error', body: 'Barcode: ' + barcode + ' has empty Customer ID' }); save_barcode = false; } } else if (scan_type == "delivery") { if (!isNullorEmpty(customer_id)) { //Invoiceable field is set to false if (invoiceable === false || invoiceable == 'false' || invoiceable === 'false' || invoiceable == false) { //Set invoiceable as NO customerProdStockRecord.setValue({ fieldId: 'custrecord_cust_prod_stock_invoiceable', value: 2 }); //Set Prepaid as YES customerProdStockRecord.setValue({ fieldId: 'custrecord_cust_prod_stock_prepaid', value: 1 }); } customerProdStockRecord.setValue({ fieldId: 'custrecord_cust_prod_stock_customer', value: customer_id }); customerProdStockRecord.setValue({ fieldId: 'custrecord_cust_prod_stock_status', value: 4 }); customerProdStockRecord.setValue({ fieldId: 'custrecord_cust_prod_stock_final_del', value: 4 }); customerProdStockRecord.setValue({ fieldId: 'custrecord_cust_date_stock_given', value: updated_at }); customerProdStockRecord.setValue({ fieldId: 'custrecord_cust_time_stock_given', value: time_updated_at }); } else { email.send({ author: 409635, recipients: 'ankith.ravindran@mailplus.comau', subject: 'MPEX Scan Sync - Error', body: 'Barcode: ' + barcode + ' has empty Customer ID' }); save_barcode = false; } } else if (scan_type == "lodgement") { if (!isNullorEmpty(customer_id)) { //Invoiceable field is set to false if (invoiceable === false || invoiceable == 'false' || invoiceable === 'false' || invoiceable == false) { //Set invoiceable as NO customerProdStockRecord.setValue({ fieldId: 'custrecord_cust_prod_stock_invoiceable', value: 2 }); //Set Prepaid as YES customerProdStockRecord.setValue({ fieldId: 'custrecord_cust_prod_stock_prepaid', value: 1 }); } customerProdStockRecord.setValue({ fieldId: 'custrecord_cust_prod_stock_customer', value: customer_id }); customerProdStockRecord.setValue({ fieldId: 'custrecord_cust_prod_stock_status', value: 5 }); customerProdStockRecord.setValue({ fieldId: 'custrecord_cust_prod_stock_final_del', value: 5 }); customerProdStockRecord.setValue({ fieldId: 'custrecord_cust_date_stock_given', value: updated_at }); customerProdStockRecord.setValue({ fieldId: 'custrecord_cust_time_stock_given', value: time_updated_at }); } else { email.send({ author: 409635, recipients: 'ankith.ravindran@mailplus.comau', subject: 'MPEX Scan Sync - Error', body: 'Barcode: ' + barcode + ' has empty Customer ID' }); save_barcode = false; } } if (save_barcode == true) { customerProdStockRecord.setValue({ fieldId: 'custrecord_cust_prod_stock_source', value: 6 }); customerProdStockRecord.setValue({ fieldId: 'custrecord_cust_prod_stock_operator', value: operator_id }); //Invoiceable field is set to false if (invoiceable === false || invoiceable == 'false' || invoiceable === 'false' || invoiceable == false) { //Set invoiceable as NO customerProdStockRecord.setValue({ fieldId: 'custrecord_cust_prod_stock_invoiceable', value: 2 }); //Set Prepaid as YES customerProdStockRecord.setValue({ fieldId: 'custrecord_cust_prod_stock_prepaid', value: 1 }); } if (barcode_beg == 'MPEN' || barcode_beg == 'MPET' || barcode_beg == 'MPEF' || barcode_beg == 'MPEB' || barcode_beg == 'MPEC' || barcode_beg == 'MPED' || barcode_beg == 'MPEG') { if (barcode_beg == 'MPEN') { prod_id = 552; } else if (barcode_beg == 'MPET') { prod_id = 553; } else if (barcode_beg == 'MPEF') { prod_id = 554; } else if (barcode_beg == 'MPEB') { prod_id = 550; } else if (barcode_beg == 'MPEC') { prod_id = 551; } else if (barcode_beg == 'MPED') { prod_id = 549; } else if (barcode_beg == 'MPEG') { prod_id = 638; } customerProdStockRecord.setValue({ fieldId: 'custrecord_cust_stock_prod_name', value: prod_id }); } customer_prod_stock_id = customerProdStockRecord.save(); } } count++; return true; }); if (count == 0) { log.audit({ title: 'Barcode does not exist', details: scans[y].scan_type }); var save_barcode = true; if (isNullorEmpty(deleted)) { var customerProdStockRecord = record.create({ type: 'customrecord_customer_product_stock', isDynamic: true }); customerProdStockRecord.setValue({ fieldId: 'custrecord_cust_date_stock_given', value: updated_at }); customerProdStockRecord.setValue({ fieldId: 'custrecord_cust_time_stock_given', value: time_updated_at }); //Invoiceable field is set to false if (invoiceable === false || invoiceable == 'false' || invoiceable === 'false' || invoiceable == false) { //Set invoiceable as NO customerProdStockRecord.setValue({ fieldId: 'custrecord_cust_prod_stock_invoiceable', value: 2 }); //Set Prepaid as YES customerProdStockRecord.setValue({ fieldId: 'custrecord_cust_prod_stock_prepaid', value: 1 }); } customerProdStockRecord.setValue({ fieldId: 'name', value: barcode }); if (scan_type == 'stockzee') { if (!isNullorEmpty(zee_id)) { //Set status as Zee stock customerProdStockRecord.setValue({ fieldId: 'custrecord_cust_prod_stock_status', value: 8 }); customerProdStockRecord.setValue({ fieldId: 'custrecord_cust_date_stock_given', value: updated_at }); customerProdStockRecord.setValue({ fieldId: 'custrecord_cust_time_stock_given', value: time_updated_at }); customerProdStockRecord.setValue({ fieldId: 'custrecord_cust_prod_stock_customer', value: null }); customerProdStockRecord.setValue({ fieldId: 'custrecord_cust_prod_stock_zee', value: zee_id }); } else { //Send email if no Zee ID email.send({ author: 409635, recipients: 'ankith.ravindran@mailplus.comau', subject: 'MPEX Scan Sync - Error', body: 'Barcode: ' + barcode + ' has empty Zee ID' }); save_barcode = false; } } else if (scan_type == 'allocate') { if (!isNullorEmpty(customer_id)) { //Invoiceable field is set to false if (invoiceable === false || invoiceable == 'false' || invoiceable === 'false' || invoiceable == false) { //Set invoiceable as NO customerProdStockRecord.setValue({ fieldId: 'custrecord_cust_prod_stock_invoiceable', value: 2 }); //Set Prepaid as YES customerProdStockRecord.setValue({ fieldId: 'custrecord_cust_prod_stock_prepaid', value: 1 }); } customerProdStockRecord.setValue({ fieldId: 'custrecord_cust_prod_stock_customer', value: customer_id }); customerProdStockRecord.setValue({ fieldId: 'custrecord_cust_prod_stock_status', value: 1 }); customerProdStockRecord.setValue({ fieldId: 'custrecord_cust_date_stock_given', value: updated_at }); customerProdStockRecord.setValue({ fieldId: 'custrecord_cust_time_stock_given', value: time_updated_at }); } else { email.send({ author: 409635, recipients: 'ankith.ravindran@mailplus.comau', subject: 'MPEX Scan Sync - Error', body: 'Barcode: ' + barcode + ' has empty Customer ID' }); save_barcode = false; } } else if (scan_type == 'pickup') { if (!isNullorEmpty(customer_id)) { //Invoiceable field is set to false if (invoiceable === false || invoiceable == 'false' || invoiceable === 'false' || invoiceable == false) { //Set invoiceable as NO customerProdStockRecord.setValue({ fieldId: 'custrecord_cust_prod_stock_invoiceable', value: 2 }); //Set Prepaid as YES customerProdStockRecord.setValue({ fieldId: 'custrecord_cust_prod_stock_prepaid', value: 1 }); } customerProdStockRecord.setValue({ fieldId: 'custrecord_cust_prod_stock_customer', value: customer_id }); customerProdStockRecord.setValue({ fieldId: 'custrecord_cust_prod_stock_status', value: 2 }); customerProdStockRecord.setValue({ fieldId: 'custrecord_cust_date_stock_given', value: updated_at }); customerProdStockRecord.setValue({ fieldId: 'custrecord_cust_time_stock_given', value: time_updated_at }); } else { email.send({ author: 409635, recipients: 'ankith.ravindran@mailplus.comau', subject: 'MPEX Scan Sync - Error', body: 'Barcode: ' + barcode + ' has empty Customer ID' }); save_barcode = false; } } else if (scan_type == "delivery") { if (!isNullorEmpty(customer_id)) { //Invoiceable field is set to false if (invoiceable === false || invoiceable == 'false' || invoiceable === 'false' || invoiceable == false) { //Set invoiceable as NO customerProdStockRecord.setValue({ fieldId: 'custrecord_cust_prod_stock_invoiceable', value: 2 }); //Set Prepaid as YES customerProdStockRecord.setValue({ fieldId: 'custrecord_cust_prod_stock_prepaid', value: 1 }); } customerProdStockRecord.setValue({ fieldId: 'custrecord_cust_prod_stock_customer', value: customer_id }); customerProdStockRecord.setValue({ fieldId: 'custrecord_cust_prod_stock_status', value: 4 }); customerProdStockRecord.setValue({ fieldId: 'custrecord_cust_prod_stock_final_del', value: 4 }); customerProdStockRecord.setValue({ fieldId: 'custrecord_cust_date_stock_given', value: updated_at }); customerProdStockRecord.setValue({ fieldId: 'custrecord_cust_time_stock_given', value: time_updated_at }); } else { email.send({ author: 409635, recipients: 'ankith.ravindran@mailplus.comau', subject: 'MPEX Scan Sync - Error', body: 'Barcode: ' + barcode + ' has empty Customer ID' }); save_barcode = false; } } else if (scan_type == "lodgement") { if (!isNullorEmpty(customer_id)) { //Invoiceable field is set to false if (invoiceable === false || invoiceable == 'false' || invoiceable === 'false' || invoiceable == false) { //Set invoiceable as NO customerProdStockRecord.setValue({ fieldId: 'custrecord_cust_prod_stock_invoiceable', value: 2 }); //Set Prepaid as YES customerProdStockRecord.setValue({ fieldId: 'custrecord_cust_prod_stock_prepaid', value: 1 }); } customerProdStockRecord.setValue({ fieldId: 'custrecord_cust_prod_stock_customer', value: customer_id }); customerProdStockRecord.setValue({ fieldId: 'custrecord_cust_prod_stock_status', value: 5 }); customerProdStockRecord.setValue({ fieldId: 'custrecord_cust_prod_stock_final_del', value: 5 }); customerProdStockRecord.setValue({ fieldId: 'custrecord_cust_date_stock_given', value: updated_at }); customerProdStockRecord.setValue({ fieldId: 'custrecord_cust_time_stock_given', value: time_updated_at }); } else { email.send({ author: 409635, recipients: 'ankith.ravindran@mailplus.comau', subject: 'MPEX Scan Sync - Error', body: 'Barcode: ' + barcode + ' has empty Customer ID' }); save_barcode = false; } } if (save_barcode == true) { customerProdStockRecord.setValue({ fieldId: 'custrecord_cust_prod_stock_source', value: 6 }); customerProdStockRecord.setValue({ fieldId: 'custrecord_cust_prod_stock_operator', value: operator_id }); //Invoiceable field is set to false if (invoiceable === false || invoiceable == 'false' || invoiceable === 'false' || invoiceable == false) { //Set invoiceable as NO customerProdStockRecord.setValue({ fieldId: 'custrecord_cust_prod_stock_invoiceable', value: 2 }); //Set Prepaid as YES customerProdStockRecord.setValue({ fieldId: 'custrecord_cust_prod_stock_prepaid', value: 1 }); } if (barcode_beg == 'MPEN' || barcode_beg == 'MPET' || barcode_beg == 'MPEF' || barcode_beg == 'MPEB' || barcode_beg == 'MPEC' || barcode_beg == 'MPED' || barcode_beg == 'MPEG') { if (barcode_beg == 'MPEN') { prod_id = 552; } else if (barcode_beg == 'MPET') { prod_id = 553; } else if (barcode_beg == 'MPEF') { prod_id = 554; } else if (barcode_beg == 'MPEB') { prod_id = 550; } else if (barcode_beg == 'MPEC') { prod_id = 551; } else if (barcode_beg == 'MPED') { prod_id = 549; } else if (barcode_beg == 'MPEG') { prod_id = 638; } customerProdStockRecord.setValue({ fieldId: 'custrecord_cust_stock_prod_name', value: prod_id }); } customer_prod_stock_id = customerProdStockRecord.save(); } } } } } } function reduce(context) { } function summarize(summary) { } return { getInputData: getInputData, map: map, reduce: reduce, summarize: summarize }; } );
1,106
[{"tag": "EMAIL", "value": "ankith.ravindran@mailplus.comau", "start": 8012, "end": 8043}, {"tag": "EMAIL", "value": "ankith.ravindran@mailplus.comau", "start": 9456, "end": 9487}, {"tag": "EMAIL", "value": "ankith.ravindran@mailplus.comau", "start": 10904, "end": 10935}, {"tag": "EMAIL", "value": "ankith.ravindran@mailplus.comau", "start": 12488, "end": 12519}, {"tag": "EMAIL", "value": "ankith.ravindran@mailplus.comau", "start": 14073, "end": 14104}, {"tag": "EMAIL", "value": "ankith.ravindran@mailplus.comau", "start": 18217, "end": 18248}, {"tag": "EMAIL", "value": "ankith.ravindran@mailplus.comau", "start": 19661, "end": 19692}, {"tag": "EMAIL", "value": "ankith.ravindran@mailplus.comau", "start": 21109, "end": 21140}, {"tag": "EMAIL", "value": "ankith.ravindran@mailplus.comau", "start": 22693, "end": 22724}, {"tag": "EMAIL", "value": "ankith.ravindran@mailplus.comau", "start": 24278, "end": 24309}]
true
10
/** * @NApiVersion 2.0 * @NScriptType MapReduceScript */ define(['N/task', 'N/email', 'N/runtime', 'N/search', 'N/record', 'N/format', 'N/https'], function(task, email, runtime, search, record, format, https) { function getInputData() { var todayDate = new Date(); log.audit({ title: 'todayDate', details: todayDate }); //To get todays date var today = format.format({ value: todayDate, type: format.Type.DATE }); log.audit({ title: 'today', details: today }); var tempTodayDate = today.split('/'); // var temp = tempTodayDate.split('-'); // var today = tempTodayDate[0] + '/' + tempTodayDate[1] + '/' + tempTodayDate[2]; var today = '22/3/2021'; log.audit({ title: 'today', details: today }); var scanJSONSearch = search.load({ id: 'customsearch_scan_json' }); scanJSONSearch.filters.push(search.createFilter({ name: 'name', join: null, operator: search.Operator.STARTSWITH, values: today })); scanJSONSearch.filters.push(search.createFilter({ name: 'custrecord_scan_josn_sync', join: null, operator: search.Operator.IS, values: 2 })); scanJSONSearch.filters.push(search.createFilter({ name: 'isinactive', join: null, operator: search.Operator.IS, values: "F" })); return scanJSONSearch; } function map(context) { var searchResult = JSON.parse(context.value); var scan_json_id = searchResult.id; // var entityId = searchResult.id; log.audit({ title: 'Map Functionality - context ', details: context.value }); log.audit({ title: 'scan_json_id', details: scan_json_id }); var scan_json_record = record.load({ type: 'customrecord_scan_json', id: scan_json_id }); var body = scan_json_record.getValue({ fieldId: 'custrecord_json' }); var body_2 = scan_json_record.getValue({ fieldId: 'custrecord_scan_json_2' }); if (body_2 == "") { var todays_scans = JSON.parse(body); var barcodes = todays_scans.scans; //No. of barcodes } else { var todays_scans = JSON.parse(body_2); var barcodes = todays_scans.scans; //No. of barcodes } //Iterate through each barcode for (var x = 0; x < barcodes.length; x++) { var scriptObj = runtime.getCurrentScript() var usage_loopstart_cust = scriptObj.getRemainingUsage(); //Usage at the start of each barcode log.audit({ title: 'Start of Barcode Loop', details: scriptObj.getRemainingUsage() }); var scans = barcodes[x].scans; //Iterate through the differenct scans for each barcode for (var y = 0; y < scans.length; y++) { var scriptObj = runtime.getCurrentScript() var usage_loopstart_cust = scriptObj.getRemainingUsage(); //Usage at the start of each scan type log.audit({ title: 'Start of Scans Loop per barcode', details: scriptObj.getRemainingUsage() }); log.audit({ title: 'Scans for barcode: ' + barcodes[x].code, details: scans[y] }); log.audit({ title: 'Scans for barcode: ' + barcodes[x].code, details: scans[y].scan_type }); var barcode = scans[y].barcode.toUpperCase(); var customer_id = scans[y].customer_ns_id; var zee_id = scans[y].zee_ns_id; var rta_id = scans[y].id; var invoiceable = scans[y].invoiceable; var scan_type = scans[y].scan_type.toLowerCase(); var operator_id = scans[y].operator_ns_id; var updated_at = scans[y].updated_at; var deleted = scans[y].deleted; var external_barcode = scans[y].external_barcode; var source = scans[y].source; var receiver_suburb = scans[y].receiver_suburb; var receiver_postcode = scans[y].post_code; var receiver_state = scans[y].state; var receiver_addr1 = scans[y].address1; var receiver_addr2 = scans[y].address1; updated_at = updated_at.split("T"); var time_updated_at = updated_at[1]; time_updated_at = time_updated_at.split("."); time_updated_at = onTimeChange(time_updated_at[0]); var updated_at = updated_at[0]; var save_barcode = true; var barcode_beg = barcode.slice(0, 4); updated_at = updated_at.split("-"); updated_at = nlapiStringToDate(updated_at[2] + '/' + updated_at[1] + '/' + updated_at[0]); //Load Search: RTA - Product Stock var productStockSearch = search.load({ id: 'customsearch_rta_product_stock' }); productStockSearch.filters.push(search.createFilter({ name: 'name', join: null, operator: search.Operator.IS, values: barcode })); productStockSearch.filters.push(search.createFilter({ name: 'isinactive', join: null, operator: search.Operator.IS, values: "F" })); var count = 0; var prod_id; productStockSearch.run().each(function(searchResult) { log.audit({ title: 'Barcode does exist', details: scans[y].scan_type }); var customer_prod_stock_id = searchResult.getValue({ name: 'internalid' }); //Load the customer product stock record var customerProdStockRecord = record.load({ type: 'customrecord_customer_product_stock', id: customer_prod_stock_id }); //Get the current status of the record. var stockStatus = customerProdStockRecord.getValue({ fieldId: 'custrecord_cust_prod_stock_status' }); //Status is Product Order Created or Invoiced if (stock_status != 6 && stock_status != 7) { //If the scan has the deleted field if (!isNullorEmpty(deleted)) { //Status is Allocated to custoemer if (status == 1) { customerProdStockRecord.setValue({ fieldId: 'custrecord_cust_prod_stock_customer', value: null }); customerProdStockRecord.setValue({ fieldId: 'custrecord_cust_date_stock_used', value: null }); customerProdStockRecord.setValue({ fieldId: 'custrecord_cust_time_stock_used', value: null }); //Change status to Zee Stock customerProdStockRecord.setValue({ fieldId: 'custrecord_cust_prod_stock_status', value: 8 }); customerProdStockRecord.setValue({ fieldId: 'custrecord_cust_prod_stock_zee', value: zee_id }); } else if (status == 8) { // Status is Zee Stock //Inactivate the record customerProdStockRecord.setValue({ fieldId: 'isinactive', value: 'T' }); customerProdStockRecord.setValue({ fieldId: 'custrecord_cust_time_deleted', value: time_updated_at }); } else if (status == 4 || status == 5) { // Status is Delivered to receiver / Lodged at TOLL //Change status to Allocated to customer customerProdStockRecord.setValue({ fieldId: 'custrecord_cust_prod_stock_status', value: 1 }); } } else if (scan_type == 'stockzee') { if (!isNullorEmpty(zee_id)) { //Set status as Zee stock customerProdStockRecord.setValue({ fieldId: 'custrecord_cust_prod_stock_status', value: 8 }); customerProdStockRecord.setValue({ fieldId: 'custrecord_cust_date_stock_given', value: updated_at }); customerProdStockRecord.setValue({ fieldId: 'custrecord_cust_time_stock_given', value: time_updated_at }); customerProdStockRecord.setValue({ fieldId: 'custrecord_cust_prod_stock_customer', value: null }); customerProdStockRecord.setValue({ fieldId: 'custrecord_cust_prod_stock_zee', value: zee_id }); } else { //Send email if no Zee ID email.send({ author: 409635, recipients: 'hzdkv@example.com', subject: 'MPEX Scan Sync - Error', body: 'Barcode: ' + barcode + ' has empty Zee ID' }); save_barcode = false; } } else if (scan_type == 'allocate') { if (!isNullorEmpty(customer_id)) { //Invoiceable field is set to false if (invoiceable === false || invoiceable == 'false' || invoiceable === 'false' || invoiceable == false) { //Set invoiceable as NO customerProdStockRecord.setValue({ fieldId: 'custrecord_cust_prod_stock_invoiceable', value: 2 }); //Set Prepaid as YES customerProdStockRecord.setValue({ fieldId: 'custrecord_cust_prod_stock_prepaid', value: 1 }); } customerProdStockRecord.setValue({ fieldId: 'custrecord_cust_prod_stock_customer', value: customer_id }); customerProdStockRecord.setValue({ fieldId: 'custrecord_cust_prod_stock_status', value: 1 }); customerProdStockRecord.setValue({ fieldId: 'custrecord_cust_date_stock_given', value: updated_at }); customerProdStockRecord.setValue({ fieldId: 'custrecord_cust_time_stock_given', value: time_updated_at }); } else { email.send({ author: 409635, recipients: 'hzdkv@example.com', subject: 'MPEX Scan Sync - Error', body: 'Barcode: ' + barcode + ' has empty Customer ID' }); save_barcode = false; } } else if (scan_type == 'pickup') { if (!isNullorEmpty(customer_id)) { //Invoiceable field is set to false if (invoiceable === false || invoiceable == 'false' || invoiceable === 'false' || invoiceable == false) { //Set invoiceable as NO customerProdStockRecord.setValue({ fieldId: 'custrecord_cust_prod_stock_invoiceable', value: 2 }); //Set Prepaid as YES customerProdStockRecord.setValue({ fieldId: 'custrecord_cust_prod_stock_prepaid', value: 1 }); } customerProdStockRecord.setValue({ fieldId: 'custrecord_cust_prod_stock_customer', value: customer_id }); customerProdStockRecord.setValue({ fieldId: 'custrecord_cust_prod_stock_status', value: 2 }); customerProdStockRecord.setValue({ fieldId: 'custrecord_cust_date_stock_given', value: updated_at }); customerProdStockRecord.setValue({ fieldId: 'custrecord_cust_time_stock_given', value: time_updated_at }); } else { email.send({ author: 409635, recipients: 'hzdkv@example.com', subject: 'MPEX Scan Sync - Error', body: 'Barcode: ' + barcode + ' has empty Customer ID' }); save_barcode = false; } } else if (scan_type == "delivery") { if (!isNullorEmpty(customer_id)) { //Invoiceable field is set to false if (invoiceable === false || invoiceable == 'false' || invoiceable === 'false' || invoiceable == false) { //Set invoiceable as NO customerProdStockRecord.setValue({ fieldId: 'custrecord_cust_prod_stock_invoiceable', value: 2 }); //Set Prepaid as YES customerProdStockRecord.setValue({ fieldId: 'custrecord_cust_prod_stock_prepaid', value: 1 }); } customerProdStockRecord.setValue({ fieldId: 'custrecord_cust_prod_stock_customer', value: customer_id }); customerProdStockRecord.setValue({ fieldId: 'custrecord_cust_prod_stock_status', value: 4 }); customerProdStockRecord.setValue({ fieldId: 'custrecord_cust_prod_stock_final_del', value: 4 }); customerProdStockRecord.setValue({ fieldId: 'custrecord_cust_date_stock_given', value: updated_at }); customerProdStockRecord.setValue({ fieldId: 'custrecord_cust_time_stock_given', value: time_updated_at }); } else { email.send({ author: 409635, recipients: 'hzdkv@example.com', subject: 'MPEX Scan Sync - Error', body: 'Barcode: ' + barcode + ' has empty Customer ID' }); save_barcode = false; } } else if (scan_type == "lodgement") { if (!isNullorEmpty(customer_id)) { //Invoiceable field is set to false if (invoiceable === false || invoiceable == 'false' || invoiceable === 'false' || invoiceable == false) { //Set invoiceable as NO customerProdStockRecord.setValue({ fieldId: 'custrecord_cust_prod_stock_invoiceable', value: 2 }); //Set Prepaid as YES customerProdStockRecord.setValue({ fieldId: 'custrecord_cust_prod_stock_prepaid', value: 1 }); } customerProdStockRecord.setValue({ fieldId: 'custrecord_cust_prod_stock_customer', value: customer_id }); customerProdStockRecord.setValue({ fieldId: 'custrecord_cust_prod_stock_status', value: 5 }); customerProdStockRecord.setValue({ fieldId: 'custrecord_cust_prod_stock_final_del', value: 5 }); customerProdStockRecord.setValue({ fieldId: 'custrecord_cust_date_stock_given', value: updated_at }); customerProdStockRecord.setValue({ fieldId: 'custrecord_cust_time_stock_given', value: time_updated_at }); } else { email.send({ author: 409635, recipients: 'hzdkv@example.com', subject: 'MPEX Scan Sync - Error', body: 'Barcode: ' + barcode + ' has empty Customer ID' }); save_barcode = false; } } if (save_barcode == true) { customerProdStockRecord.setValue({ fieldId: 'custrecord_cust_prod_stock_source', value: 6 }); customerProdStockRecord.setValue({ fieldId: 'custrecord_cust_prod_stock_operator', value: operator_id }); //Invoiceable field is set to false if (invoiceable === false || invoiceable == 'false' || invoiceable === 'false' || invoiceable == false) { //Set invoiceable as NO customerProdStockRecord.setValue({ fieldId: 'custrecord_cust_prod_stock_invoiceable', value: 2 }); //Set Prepaid as YES customerProdStockRecord.setValue({ fieldId: 'custrecord_cust_prod_stock_prepaid', value: 1 }); } if (barcode_beg == 'MPEN' || barcode_beg == 'MPET' || barcode_beg == 'MPEF' || barcode_beg == 'MPEB' || barcode_beg == 'MPEC' || barcode_beg == 'MPED' || barcode_beg == 'MPEG') { if (barcode_beg == 'MPEN') { prod_id = 552; } else if (barcode_beg == 'MPET') { prod_id = 553; } else if (barcode_beg == 'MPEF') { prod_id = 554; } else if (barcode_beg == 'MPEB') { prod_id = 550; } else if (barcode_beg == 'MPEC') { prod_id = 551; } else if (barcode_beg == 'MPED') { prod_id = 549; } else if (barcode_beg == 'MPEG') { prod_id = 638; } customerProdStockRecord.setValue({ fieldId: 'custrecord_cust_stock_prod_name', value: prod_id }); } customer_prod_stock_id = customerProdStockRecord.save(); } } count++; return true; }); if (count == 0) { log.audit({ title: 'Barcode does not exist', details: scans[y].scan_type }); var save_barcode = true; if (isNullorEmpty(deleted)) { var customerProdStockRecord = record.create({ type: 'customrecord_customer_product_stock', isDynamic: true }); customerProdStockRecord.setValue({ fieldId: 'custrecord_cust_date_stock_given', value: updated_at }); customerProdStockRecord.setValue({ fieldId: 'custrecord_cust_time_stock_given', value: time_updated_at }); //Invoiceable field is set to false if (invoiceable === false || invoiceable == 'false' || invoiceable === 'false' || invoiceable == false) { //Set invoiceable as NO customerProdStockRecord.setValue({ fieldId: 'custrecord_cust_prod_stock_invoiceable', value: 2 }); //Set Prepaid as YES customerProdStockRecord.setValue({ fieldId: 'custrecord_cust_prod_stock_prepaid', value: 1 }); } customerProdStockRecord.setValue({ fieldId: 'name', value: barcode }); if (scan_type == 'stockzee') { if (!isNullorEmpty(zee_id)) { //Set status as Zee stock customerProdStockRecord.setValue({ fieldId: 'custrecord_cust_prod_stock_status', value: 8 }); customerProdStockRecord.setValue({ fieldId: 'custrecord_cust_date_stock_given', value: updated_at }); customerProdStockRecord.setValue({ fieldId: 'custrecord_cust_time_stock_given', value: time_updated_at }); customerProdStockRecord.setValue({ fieldId: 'custrecord_cust_prod_stock_customer', value: null }); customerProdStockRecord.setValue({ fieldId: 'custrecord_cust_prod_stock_zee', value: zee_id }); } else { //Send email if no Zee ID email.send({ author: 409635, recipients: 'hzdkv@example.com', subject: 'MPEX Scan Sync - Error', body: 'Barcode: ' + barcode + ' has empty Zee ID' }); save_barcode = false; } } else if (scan_type == 'allocate') { if (!isNullorEmpty(customer_id)) { //Invoiceable field is set to false if (invoiceable === false || invoiceable == 'false' || invoiceable === 'false' || invoiceable == false) { //Set invoiceable as NO customerProdStockRecord.setValue({ fieldId: 'custrecord_cust_prod_stock_invoiceable', value: 2 }); //Set Prepaid as YES customerProdStockRecord.setValue({ fieldId: 'custrecord_cust_prod_stock_prepaid', value: 1 }); } customerProdStockRecord.setValue({ fieldId: 'custrecord_cust_prod_stock_customer', value: customer_id }); customerProdStockRecord.setValue({ fieldId: 'custrecord_cust_prod_stock_status', value: 1 }); customerProdStockRecord.setValue({ fieldId: 'custrecord_cust_date_stock_given', value: updated_at }); customerProdStockRecord.setValue({ fieldId: 'custrecord_cust_time_stock_given', value: time_updated_at }); } else { email.send({ author: 409635, recipients: 'hzdkv@example.com', subject: 'MPEX Scan Sync - Error', body: 'Barcode: ' + barcode + ' has empty Customer ID' }); save_barcode = false; } } else if (scan_type == 'pickup') { if (!isNullorEmpty(customer_id)) { //Invoiceable field is set to false if (invoiceable === false || invoiceable == 'false' || invoiceable === 'false' || invoiceable == false) { //Set invoiceable as NO customerProdStockRecord.setValue({ fieldId: 'custrecord_cust_prod_stock_invoiceable', value: 2 }); //Set Prepaid as YES customerProdStockRecord.setValue({ fieldId: 'custrecord_cust_prod_stock_prepaid', value: 1 }); } customerProdStockRecord.setValue({ fieldId: 'custrecord_cust_prod_stock_customer', value: customer_id }); customerProdStockRecord.setValue({ fieldId: 'custrecord_cust_prod_stock_status', value: 2 }); customerProdStockRecord.setValue({ fieldId: 'custrecord_cust_date_stock_given', value: updated_at }); customerProdStockRecord.setValue({ fieldId: 'custrecord_cust_time_stock_given', value: time_updated_at }); } else { email.send({ author: 409635, recipients: 'hzdkv@example.com', subject: 'MPEX Scan Sync - Error', body: 'Barcode: ' + barcode + ' has empty Customer ID' }); save_barcode = false; } } else if (scan_type == "delivery") { if (!isNullorEmpty(customer_id)) { //Invoiceable field is set to false if (invoiceable === false || invoiceable == 'false' || invoiceable === 'false' || invoiceable == false) { //Set invoiceable as NO customerProdStockRecord.setValue({ fieldId: 'custrecord_cust_prod_stock_invoiceable', value: 2 }); //Set Prepaid as YES customerProdStockRecord.setValue({ fieldId: 'custrecord_cust_prod_stock_prepaid', value: 1 }); } customerProdStockRecord.setValue({ fieldId: 'custrecord_cust_prod_stock_customer', value: customer_id }); customerProdStockRecord.setValue({ fieldId: 'custrecord_cust_prod_stock_status', value: 4 }); customerProdStockRecord.setValue({ fieldId: 'custrecord_cust_prod_stock_final_del', value: 4 }); customerProdStockRecord.setValue({ fieldId: 'custrecord_cust_date_stock_given', value: updated_at }); customerProdStockRecord.setValue({ fieldId: 'custrecord_cust_time_stock_given', value: time_updated_at }); } else { email.send({ author: 409635, recipients: 'hzdkv@example.com', subject: 'MPEX Scan Sync - Error', body: 'Barcode: ' + barcode + ' has empty Customer ID' }); save_barcode = false; } } else if (scan_type == "lodgement") { if (!isNullorEmpty(customer_id)) { //Invoiceable field is set to false if (invoiceable === false || invoiceable == 'false' || invoiceable === 'false' || invoiceable == false) { //Set invoiceable as NO customerProdStockRecord.setValue({ fieldId: 'custrecord_cust_prod_stock_invoiceable', value: 2 }); //Set Prepaid as YES customerProdStockRecord.setValue({ fieldId: 'custrecord_cust_prod_stock_prepaid', value: 1 }); } customerProdStockRecord.setValue({ fieldId: 'custrecord_cust_prod_stock_customer', value: customer_id }); customerProdStockRecord.setValue({ fieldId: 'custrecord_cust_prod_stock_status', value: 5 }); customerProdStockRecord.setValue({ fieldId: 'custrecord_cust_prod_stock_final_del', value: 5 }); customerProdStockRecord.setValue({ fieldId: 'custrecord_cust_date_stock_given', value: updated_at }); customerProdStockRecord.setValue({ fieldId: 'custrecord_cust_time_stock_given', value: time_updated_at }); } else { email.send({ author: 409635, recipients: 'hzdkv@example.com', subject: 'MPEX Scan Sync - Error', body: 'Barcode: ' + barcode + ' has empty Customer ID' }); save_barcode = false; } } if (save_barcode == true) { customerProdStockRecord.setValue({ fieldId: 'custrecord_cust_prod_stock_source', value: 6 }); customerProdStockRecord.setValue({ fieldId: 'custrecord_cust_prod_stock_operator', value: operator_id }); //Invoiceable field is set to false if (invoiceable === false || invoiceable == 'false' || invoiceable === 'false' || invoiceable == false) { //Set invoiceable as NO customerProdStockRecord.setValue({ fieldId: 'custrecord_cust_prod_stock_invoiceable', value: 2 }); //Set Prepaid as YES customerProdStockRecord.setValue({ fieldId: 'custrecord_cust_prod_stock_prepaid', value: 1 }); } if (barcode_beg == 'MPEN' || barcode_beg == 'MPET' || barcode_beg == 'MPEF' || barcode_beg == 'MPEB' || barcode_beg == 'MPEC' || barcode_beg == 'MPED' || barcode_beg == 'MPEG') { if (barcode_beg == 'MPEN') { prod_id = 552; } else if (barcode_beg == 'MPET') { prod_id = 553; } else if (barcode_beg == 'MPEF') { prod_id = 554; } else if (barcode_beg == 'MPEB') { prod_id = 550; } else if (barcode_beg == 'MPEC') { prod_id = 551; } else if (barcode_beg == 'MPED') { prod_id = 549; } else if (barcode_beg == 'MPEG') { prod_id = 638; } customerProdStockRecord.setValue({ fieldId: 'custrecord_cust_stock_prod_name', value: prod_id }); } customer_prod_stock_id = customerProdStockRecord.save(); } } } } } } function reduce(context) { } function summarize(summary) { } return { getInputData: getInputData, map: map, reduce: reduce, summarize: summarize }; } );
true
/** * @NApiVersion 2.0 * @NScriptType MapReduceScript */ define(['N/task', 'N/email', 'N/runtime', 'N/search', 'N/record', 'N/format', 'N/https'], function(task, email, runtime, search, record, format, https) { function getInputData() { var todayDate = new Date(); log.audit({ title: 'todayDate', details: todayDate }); //To get todays date var today = format.format({ value: todayDate, type: format.Type.DATE }); log.audit({ title: 'today', details: today }); var tempTodayDate = today.split('/'); // var temp = tempTodayDate.split('-'); // var today = tempTodayDate[0] + '/' + tempTodayDate[1] + '/' + tempTodayDate[2]; var today = '22/3/2021'; log.audit({ title: 'today', details: today }); var scanJSONSearch = search.load({ id: 'customsearch_scan_json' }); scanJSONSearch.filters.push(search.createFilter({ name: 'name', join: null, operator: search.Operator.STARTSWITH, values: today })); scanJSONSearch.filters.push(search.createFilter({ name: 'custrecord_scan_josn_sync', join: null, operator: search.Operator.IS, values: 2 })); scanJSONSearch.filters.push(search.createFilter({ name: 'isinactive', join: null, operator: search.Operator.IS, values: "F" })); return scanJSONSearch; } function map(context) { var searchResult = JSON.parse(context.value); var scan_json_id = searchResult.id; // var entityId = searchResult.id; log.audit({ title: 'Map Functionality - context ', details: context.value }); log.audit({ title: 'scan_json_id', details: scan_json_id }); var scan_json_record = record.load({ type: 'customrecord_scan_json', id: scan_json_id }); var body = scan_json_record.getValue({ fieldId: 'custrecord_json' }); var body_2 = scan_json_record.getValue({ fieldId: 'custrecord_scan_json_2' }); if (body_2 == "") { var todays_scans = JSON.parse(body); var barcodes = todays_scans.scans; //No. of barcodes } else { var todays_scans = JSON.parse(body_2); var barcodes = todays_scans.scans; //No. of barcodes } //Iterate through each barcode for (var x = 0; x < barcodes.length; x++) { var scriptObj = runtime.getCurrentScript() var usage_loopstart_cust = scriptObj.getRemainingUsage(); //Usage at the start of each barcode log.audit({ title: 'Start of Barcode Loop', details: scriptObj.getRemainingUsage() }); var scans = barcodes[x].scans; //Iterate through the differenct scans for each barcode for (var y = 0; y < scans.length; y++) { var scriptObj = runtime.getCurrentScript() var usage_loopstart_cust = scriptObj.getRemainingUsage(); //Usage at the start of each scan type log.audit({ title: 'Start of Scans Loop per barcode', details: scriptObj.getRemainingUsage() }); log.audit({ title: 'Scans for barcode: ' + barcodes[x].code, details: scans[y] }); log.audit({ title: 'Scans for barcode: ' + barcodes[x].code, details: scans[y].scan_type }); var barcode = scans[y].barcode.toUpperCase(); var customer_id = scans[y].customer_ns_id; var zee_id = scans[y].zee_ns_id; var rta_id = scans[y].id; var invoiceable = scans[y].invoiceable; var scan_type = scans[y].scan_type.toLowerCase(); var operator_id = scans[y].operator_ns_id; var updated_at = scans[y].updated_at; var deleted = scans[y].deleted; var external_barcode = scans[y].external_barcode; var source = scans[y].source; var receiver_suburb = scans[y].receiver_suburb; var receiver_postcode = scans[y].post_code; var receiver_state = scans[y].state; var receiver_addr1 = scans[y].address1; var receiver_addr2 = scans[y].address1; updated_at = updated_at.split("T"); var time_updated_at = updated_at[1]; time_updated_at = time_updated_at.split("."); time_updated_at = onTimeChange(time_updated_at[0]); var updated_at = updated_at[0]; var save_barcode = true; var barcode_beg = barcode.slice(0, 4); updated_at = updated_at.split("-"); updated_at = nlapiStringToDate(updated_at[2] + '/' + updated_at[1] + '/' + updated_at[0]); //Load Search: RTA - Product Stock var productStockSearch = search.load({ id: 'customsearch_rta_product_stock' }); productStockSearch.filters.push(search.createFilter({ name: 'name', join: null, operator: search.Operator.IS, values: barcode })); productStockSearch.filters.push(search.createFilter({ name: 'isinactive', join: null, operator: search.Operator.IS, values: "F" })); var count = 0; var prod_id; productStockSearch.run().each(function(searchResult) { log.audit({ title: 'Barcode does exist', details: scans[y].scan_type }); var customer_prod_stock_id = searchResult.getValue({ name: 'internalid' }); //Load the customer product stock record var customerProdStockRecord = record.load({ type: 'customrecord_customer_product_stock', id: customer_prod_stock_id }); //Get the current status of the record. var stockStatus = customerProdStockRecord.getValue({ fieldId: 'custrecord_cust_prod_stock_status' }); //Status is Product Order Created or Invoiced if (stock_status != 6 && stock_status != 7) { //If the scan has the deleted field if (!isNullorEmpty(deleted)) { //Status is Allocated to custoemer if (status == 1) { customerProdStockRecord.setValue({ fieldId: 'custrecord_cust_prod_stock_customer', value: null }); customerProdStockRecord.setValue({ fieldId: 'custrecord_cust_date_stock_used', value: null }); customerProdStockRecord.setValue({ fieldId: 'custrecord_cust_time_stock_used', value: null }); //Change status to Zee Stock customerProdStockRecord.setValue({ fieldId: 'custrecord_cust_prod_stock_status', value: 8 }); customerProdStockRecord.setValue({ fieldId: 'custrecord_cust_prod_stock_zee', value: zee_id }); } else if (status == 8) { // Status is Zee Stock //Inactivate the record customerProdStockRecord.setValue({ fieldId: 'isinactive', value: 'T' }); customerProdStockRecord.setValue({ fieldId: 'custrecord_cust_time_deleted', value: time_updated_at }); } else if (status == 4 || status == 5) { // Status is Delivered to receiver / Lodged at TOLL //Change status to Allocated to customer customerProdStockRecord.setValue({ fieldId: 'custrecord_cust_prod_stock_status', value: 1 }); } } else if (scan_type == 'stockzee') { if (!isNullorEmpty(zee_id)) { //Set status as Zee stock customerProdStockRecord.setValue({ fieldId: 'custrecord_cust_prod_stock_status', value: 8 }); customerProdStockRecord.setValue({ fieldId: 'custrecord_cust_date_stock_given', value: updated_at }); customerProdStockRecord.setValue({ fieldId: 'custrecord_cust_time_stock_given', value: time_updated_at }); customerProdStockRecord.setValue({ fieldId: 'custrecord_cust_prod_stock_customer', value: null }); customerProdStockRecord.setValue({ fieldId: 'custrecord_cust_prod_stock_zee', value: zee_id }); } else { //Send email if no Zee ID email.send({ author: 409635, recipients: 'PI:EMAIL:hzdkv@example.comEND_PI', subject: 'MPEX Scan Sync - Error', body: 'Barcode: ' + barcode + ' has empty Zee ID' }); save_barcode = false; } } else if (scan_type == 'allocate') { if (!isNullorEmpty(customer_id)) { //Invoiceable field is set to false if (invoiceable === false || invoiceable == 'false' || invoiceable === 'false' || invoiceable == false) { //Set invoiceable as NO customerProdStockRecord.setValue({ fieldId: 'custrecord_cust_prod_stock_invoiceable', value: 2 }); //Set Prepaid as YES customerProdStockRecord.setValue({ fieldId: 'custrecord_cust_prod_stock_prepaid', value: 1 }); } customerProdStockRecord.setValue({ fieldId: 'custrecord_cust_prod_stock_customer', value: customer_id }); customerProdStockRecord.setValue({ fieldId: 'custrecord_cust_prod_stock_status', value: 1 }); customerProdStockRecord.setValue({ fieldId: 'custrecord_cust_date_stock_given', value: updated_at }); customerProdStockRecord.setValue({ fieldId: 'custrecord_cust_time_stock_given', value: time_updated_at }); } else { email.send({ author: 409635, recipients: 'PI:EMAIL:hzdkv@example.comEND_PI', subject: 'MPEX Scan Sync - Error', body: 'Barcode: ' + barcode + ' has empty Customer ID' }); save_barcode = false; } } else if (scan_type == 'pickup') { if (!isNullorEmpty(customer_id)) { //Invoiceable field is set to false if (invoiceable === false || invoiceable == 'false' || invoiceable === 'false' || invoiceable == false) { //Set invoiceable as NO customerProdStockRecord.setValue({ fieldId: 'custrecord_cust_prod_stock_invoiceable', value: 2 }); //Set Prepaid as YES customerProdStockRecord.setValue({ fieldId: 'custrecord_cust_prod_stock_prepaid', value: 1 }); } customerProdStockRecord.setValue({ fieldId: 'custrecord_cust_prod_stock_customer', value: customer_id }); customerProdStockRecord.setValue({ fieldId: 'custrecord_cust_prod_stock_status', value: 2 }); customerProdStockRecord.setValue({ fieldId: 'custrecord_cust_date_stock_given', value: updated_at }); customerProdStockRecord.setValue({ fieldId: 'custrecord_cust_time_stock_given', value: time_updated_at }); } else { email.send({ author: 409635, recipients: 'PI:EMAIL:hzdkv@example.comEND_PI', subject: 'MPEX Scan Sync - Error', body: 'Barcode: ' + barcode + ' has empty Customer ID' }); save_barcode = false; } } else if (scan_type == "delivery") { if (!isNullorEmpty(customer_id)) { //Invoiceable field is set to false if (invoiceable === false || invoiceable == 'false' || invoiceable === 'false' || invoiceable == false) { //Set invoiceable as NO customerProdStockRecord.setValue({ fieldId: 'custrecord_cust_prod_stock_invoiceable', value: 2 }); //Set Prepaid as YES customerProdStockRecord.setValue({ fieldId: 'custrecord_cust_prod_stock_prepaid', value: 1 }); } customerProdStockRecord.setValue({ fieldId: 'custrecord_cust_prod_stock_customer', value: customer_id }); customerProdStockRecord.setValue({ fieldId: 'custrecord_cust_prod_stock_status', value: 4 }); customerProdStockRecord.setValue({ fieldId: 'custrecord_cust_prod_stock_final_del', value: 4 }); customerProdStockRecord.setValue({ fieldId: 'custrecord_cust_date_stock_given', value: updated_at }); customerProdStockRecord.setValue({ fieldId: 'custrecord_cust_time_stock_given', value: time_updated_at }); } else { email.send({ author: 409635, recipients: 'PI:EMAIL:hzdkv@example.comEND_PI', subject: 'MPEX Scan Sync - Error', body: 'Barcode: ' + barcode + ' has empty Customer ID' }); save_barcode = false; } } else if (scan_type == "lodgement") { if (!isNullorEmpty(customer_id)) { //Invoiceable field is set to false if (invoiceable === false || invoiceable == 'false' || invoiceable === 'false' || invoiceable == false) { //Set invoiceable as NO customerProdStockRecord.setValue({ fieldId: 'custrecord_cust_prod_stock_invoiceable', value: 2 }); //Set Prepaid as YES customerProdStockRecord.setValue({ fieldId: 'custrecord_cust_prod_stock_prepaid', value: 1 }); } customerProdStockRecord.setValue({ fieldId: 'custrecord_cust_prod_stock_customer', value: customer_id }); customerProdStockRecord.setValue({ fieldId: 'custrecord_cust_prod_stock_status', value: 5 }); customerProdStockRecord.setValue({ fieldId: 'custrecord_cust_prod_stock_final_del', value: 5 }); customerProdStockRecord.setValue({ fieldId: 'custrecord_cust_date_stock_given', value: updated_at }); customerProdStockRecord.setValue({ fieldId: 'custrecord_cust_time_stock_given', value: time_updated_at }); } else { email.send({ author: 409635, recipients: 'PI:EMAIL:hzdkv@example.comEND_PI', subject: 'MPEX Scan Sync - Error', body: 'Barcode: ' + barcode + ' has empty Customer ID' }); save_barcode = false; } } if (save_barcode == true) { customerProdStockRecord.setValue({ fieldId: 'custrecord_cust_prod_stock_source', value: 6 }); customerProdStockRecord.setValue({ fieldId: 'custrecord_cust_prod_stock_operator', value: operator_id }); //Invoiceable field is set to false if (invoiceable === false || invoiceable == 'false' || invoiceable === 'false' || invoiceable == false) { //Set invoiceable as NO customerProdStockRecord.setValue({ fieldId: 'custrecord_cust_prod_stock_invoiceable', value: 2 }); //Set Prepaid as YES customerProdStockRecord.setValue({ fieldId: 'custrecord_cust_prod_stock_prepaid', value: 1 }); } if (barcode_beg == 'MPEN' || barcode_beg == 'MPET' || barcode_beg == 'MPEF' || barcode_beg == 'MPEB' || barcode_beg == 'MPEC' || barcode_beg == 'MPED' || barcode_beg == 'MPEG') { if (barcode_beg == 'MPEN') { prod_id = 552; } else if (barcode_beg == 'MPET') { prod_id = 553; } else if (barcode_beg == 'MPEF') { prod_id = 554; } else if (barcode_beg == 'MPEB') { prod_id = 550; } else if (barcode_beg == 'MPEC') { prod_id = 551; } else if (barcode_beg == 'MPED') { prod_id = 549; } else if (barcode_beg == 'MPEG') { prod_id = 638; } customerProdStockRecord.setValue({ fieldId: 'custrecord_cust_stock_prod_name', value: prod_id }); } customer_prod_stock_id = customerProdStockRecord.save(); } } count++; return true; }); if (count == 0) { log.audit({ title: 'Barcode does not exist', details: scans[y].scan_type }); var save_barcode = true; if (isNullorEmpty(deleted)) { var customerProdStockRecord = record.create({ type: 'customrecord_customer_product_stock', isDynamic: true }); customerProdStockRecord.setValue({ fieldId: 'custrecord_cust_date_stock_given', value: updated_at }); customerProdStockRecord.setValue({ fieldId: 'custrecord_cust_time_stock_given', value: time_updated_at }); //Invoiceable field is set to false if (invoiceable === false || invoiceable == 'false' || invoiceable === 'false' || invoiceable == false) { //Set invoiceable as NO customerProdStockRecord.setValue({ fieldId: 'custrecord_cust_prod_stock_invoiceable', value: 2 }); //Set Prepaid as YES customerProdStockRecord.setValue({ fieldId: 'custrecord_cust_prod_stock_prepaid', value: 1 }); } customerProdStockRecord.setValue({ fieldId: 'name', value: barcode }); if (scan_type == 'stockzee') { if (!isNullorEmpty(zee_id)) { //Set status as Zee stock customerProdStockRecord.setValue({ fieldId: 'custrecord_cust_prod_stock_status', value: 8 }); customerProdStockRecord.setValue({ fieldId: 'custrecord_cust_date_stock_given', value: updated_at }); customerProdStockRecord.setValue({ fieldId: 'custrecord_cust_time_stock_given', value: time_updated_at }); customerProdStockRecord.setValue({ fieldId: 'custrecord_cust_prod_stock_customer', value: null }); customerProdStockRecord.setValue({ fieldId: 'custrecord_cust_prod_stock_zee', value: zee_id }); } else { //Send email if no Zee ID email.send({ author: 409635, recipients: 'PI:EMAIL:hzdkv@example.comEND_PI', subject: 'MPEX Scan Sync - Error', body: 'Barcode: ' + barcode + ' has empty Zee ID' }); save_barcode = false; } } else if (scan_type == 'allocate') { if (!isNullorEmpty(customer_id)) { //Invoiceable field is set to false if (invoiceable === false || invoiceable == 'false' || invoiceable === 'false' || invoiceable == false) { //Set invoiceable as NO customerProdStockRecord.setValue({ fieldId: 'custrecord_cust_prod_stock_invoiceable', value: 2 }); //Set Prepaid as YES customerProdStockRecord.setValue({ fieldId: 'custrecord_cust_prod_stock_prepaid', value: 1 }); } customerProdStockRecord.setValue({ fieldId: 'custrecord_cust_prod_stock_customer', value: customer_id }); customerProdStockRecord.setValue({ fieldId: 'custrecord_cust_prod_stock_status', value: 1 }); customerProdStockRecord.setValue({ fieldId: 'custrecord_cust_date_stock_given', value: updated_at }); customerProdStockRecord.setValue({ fieldId: 'custrecord_cust_time_stock_given', value: time_updated_at }); } else { email.send({ author: 409635, recipients: 'PI:EMAIL:hzdkv@example.comEND_PI', subject: 'MPEX Scan Sync - Error', body: 'Barcode: ' + barcode + ' has empty Customer ID' }); save_barcode = false; } } else if (scan_type == 'pickup') { if (!isNullorEmpty(customer_id)) { //Invoiceable field is set to false if (invoiceable === false || invoiceable == 'false' || invoiceable === 'false' || invoiceable == false) { //Set invoiceable as NO customerProdStockRecord.setValue({ fieldId: 'custrecord_cust_prod_stock_invoiceable', value: 2 }); //Set Prepaid as YES customerProdStockRecord.setValue({ fieldId: 'custrecord_cust_prod_stock_prepaid', value: 1 }); } customerProdStockRecord.setValue({ fieldId: 'custrecord_cust_prod_stock_customer', value: customer_id }); customerProdStockRecord.setValue({ fieldId: 'custrecord_cust_prod_stock_status', value: 2 }); customerProdStockRecord.setValue({ fieldId: 'custrecord_cust_date_stock_given', value: updated_at }); customerProdStockRecord.setValue({ fieldId: 'custrecord_cust_time_stock_given', value: time_updated_at }); } else { email.send({ author: 409635, recipients: 'PI:EMAIL:hzdkv@example.comEND_PI', subject: 'MPEX Scan Sync - Error', body: 'Barcode: ' + barcode + ' has empty Customer ID' }); save_barcode = false; } } else if (scan_type == "delivery") { if (!isNullorEmpty(customer_id)) { //Invoiceable field is set to false if (invoiceable === false || invoiceable == 'false' || invoiceable === 'false' || invoiceable == false) { //Set invoiceable as NO customerProdStockRecord.setValue({ fieldId: 'custrecord_cust_prod_stock_invoiceable', value: 2 }); //Set Prepaid as YES customerProdStockRecord.setValue({ fieldId: 'custrecord_cust_prod_stock_prepaid', value: 1 }); } customerProdStockRecord.setValue({ fieldId: 'custrecord_cust_prod_stock_customer', value: customer_id }); customerProdStockRecord.setValue({ fieldId: 'custrecord_cust_prod_stock_status', value: 4 }); customerProdStockRecord.setValue({ fieldId: 'custrecord_cust_prod_stock_final_del', value: 4 }); customerProdStockRecord.setValue({ fieldId: 'custrecord_cust_date_stock_given', value: updated_at }); customerProdStockRecord.setValue({ fieldId: 'custrecord_cust_time_stock_given', value: time_updated_at }); } else { email.send({ author: 409635, recipients: 'PI:EMAIL:hzdkv@example.comEND_PI', subject: 'MPEX Scan Sync - Error', body: 'Barcode: ' + barcode + ' has empty Customer ID' }); save_barcode = false; } } else if (scan_type == "lodgement") { if (!isNullorEmpty(customer_id)) { //Invoiceable field is set to false if (invoiceable === false || invoiceable == 'false' || invoiceable === 'false' || invoiceable == false) { //Set invoiceable as NO customerProdStockRecord.setValue({ fieldId: 'custrecord_cust_prod_stock_invoiceable', value: 2 }); //Set Prepaid as YES customerProdStockRecord.setValue({ fieldId: 'custrecord_cust_prod_stock_prepaid', value: 1 }); } customerProdStockRecord.setValue({ fieldId: 'custrecord_cust_prod_stock_customer', value: customer_id }); customerProdStockRecord.setValue({ fieldId: 'custrecord_cust_prod_stock_status', value: 5 }); customerProdStockRecord.setValue({ fieldId: 'custrecord_cust_prod_stock_final_del', value: 5 }); customerProdStockRecord.setValue({ fieldId: 'custrecord_cust_date_stock_given', value: updated_at }); customerProdStockRecord.setValue({ fieldId: 'custrecord_cust_time_stock_given', value: time_updated_at }); } else { email.send({ author: 409635, recipients: 'PI:EMAIL:hzdkv@example.comEND_PI', subject: 'MPEX Scan Sync - Error', body: 'Barcode: ' + barcode + ' has empty Customer ID' }); save_barcode = false; } } if (save_barcode == true) { customerProdStockRecord.setValue({ fieldId: 'custrecord_cust_prod_stock_source', value: 6 }); customerProdStockRecord.setValue({ fieldId: 'custrecord_cust_prod_stock_operator', value: operator_id }); //Invoiceable field is set to false if (invoiceable === false || invoiceable == 'false' || invoiceable === 'false' || invoiceable == false) { //Set invoiceable as NO customerProdStockRecord.setValue({ fieldId: 'custrecord_cust_prod_stock_invoiceable', value: 2 }); //Set Prepaid as YES customerProdStockRecord.setValue({ fieldId: 'custrecord_cust_prod_stock_prepaid', value: 1 }); } if (barcode_beg == 'MPEN' || barcode_beg == 'MPET' || barcode_beg == 'MPEF' || barcode_beg == 'MPEB' || barcode_beg == 'MPEC' || barcode_beg == 'MPED' || barcode_beg == 'MPEG') { if (barcode_beg == 'MPEN') { prod_id = 552; } else if (barcode_beg == 'MPET') { prod_id = 553; } else if (barcode_beg == 'MPEF') { prod_id = 554; } else if (barcode_beg == 'MPEB') { prod_id = 550; } else if (barcode_beg == 'MPEC') { prod_id = 551; } else if (barcode_beg == 'MPED') { prod_id = 549; } else if (barcode_beg == 'MPEG') { prod_id = 638; } customerProdStockRecord.setValue({ fieldId: 'custrecord_cust_stock_prod_name', value: prod_id }); } customer_prod_stock_id = customerProdStockRecord.save(); } } } } } } function reduce(context) { } function summarize(summary) { } return { getInputData: getInputData, map: map, reduce: reduce, summarize: summarize }; } );
/** * * @NApiVersion 2.0 * @NScriptType ClientScript * * Description: Separate page for escalating ticket * @Last Modified by: Sruti Desai * */ define(['N/error', 'N/runtime', 'N/search', 'N/url', 'N/record', 'N/format', 'N/email', 'N/currentRecord', 'N/https'], function(error, runtime, search, url, record, format, email, currentRecord, https) { var baseURL = 'https://1048144.app.netsuite.com'; if (runtime.envType == "SANDBOX") { baseURL = 'https://1048144-sb3.app.netsuite.com'; } var role = runtime.getCurrentUser().role; var userId = runtime.getCurrentUser().id; var currRec = currentRecord.get(); /** * On page initialisation */ function pageInit() { var currRec = currentRecord.get(); var selector_number = currRec.getValue({ fieldId: 'custpage_selector_number' }); var selector_type = currRec.getValue({ fieldId: 'custpage_selector_type' }); var ticket_id = currRec.getValue({ fieldId: 'custpage_ticket_id' }); var status_value = currRec.getValue({ fieldId: 'custpage_ticket_status_value' }); var customer_number = currRec.getValue({ fieldId: 'custpage_customer_number' }); var ticketRecord = record.load({ type: 'customrecord_mp_ticket', id: Math.floor(ticket_id), isDynamic: true, }); var customerstatus = ticketRecord.getValue({fieldId: 'custrecord_mp_ticket_customer_status'}); var ticketstatus = ticketRecord.getValue({fieldId: 'custrecord_ticket_status'}); //background-colors $("#NS_MENU_ID0-item0").css("background-color", "#CFE0CE"); $("#NS_MENU_ID0-item0 a").css("background-color", "#CFE0CE"); $("#body").css("background-color", "#CFE0CE"); $(document).ready(function() { $('#email_body').summernote(); $('#owner, #toll_issues, #mp_issues, #invoice_issues, #enquiry_medium_status, #send_toll').selectpicker(); }); var inline_html_contact_table = '<table cellpadding="15" id="contacts" class="table table-responsive table-striped contacts tablesorter" cellspacing="0" style="width: 100%;border: 0"><thead style="color: white;background-color: #379E8F;"><tr><th style="vertical-align: middle;text-align: center;" id="col_name"><b>NAME</b></th><th style="vertical-align: middle;text-align: center;" id="col_phone"><b>PHONE</b></th><th style="vertical-align: middle;text-align: center;" id="col_email"><b>EMAIL</b></th><th style="vertical-align: middle;text-align: center;" id="col_role"><b>ROLE</b></th><th style="vertical-align: middle;text-align: center;" id="col_add_as_recipient"><b>ADD AS RECIPIENT</b></th></tr></thead><tbody></tbody></table>'; $('div.col-xs-12.contacts_div').html(inline_html_contact_table); if (!isNullorEmpty(selector_number)) { console.log('!isNullorEmpty(selector_number) : ', !isNullorEmpty(selector_number)); // If we updated the contacts, we have the parameter 'custpage_selector_number' and no parameter for 'custpage_ticket_id'. if (!isNullorEmpty(ticket_id)) { console.log('isNullorEmpty(ticket_id) : ', isNullorEmpty(ticket_id)); createContactsRows(); // If the ticket status is "Open, the acknoledgement template shall be selected. if (status_value != 3) { $('#template option:selected').attr('selected', false); if (customerstatus == 2) { $('#template option[value="109"]').attr('selected', true); // Select the acknoledgement template //$('#template option[value="304"]').attr('selected', true); // Select the acknoledgement template console.log("a"); } else if (customerstatus == 3) { $('#template option[value="110"]').attr('selected', true); // Select the acknoledgement template //$('#template option[value="303"]').attr('selected', true); // Select the acknoledgement template console.log("b"); } else if (customerstatus == 4) { $('#template option[value="111"]').attr('selected', true); // Select the acknoledgement template //$('#template option[value="302"]').attr('selected', true); // Select the acknoledgement template console.log("c"); } else { $('#template option[value="66"]').attr('selected', true); // Select the acknoledgement template //$('#template option[value="237"]').attr('selected', true); // Select the under investigation template } loadTemplate(); } if (selector_type == 'barcode_number') { setReminderDate(); } } } $('#acc_manager_button').click(function() { var account_manager_email = $('#acc_manager').data('email'); var send_cc_field = $('#send_cc').val(); if (isNullorEmpty(send_cc_field)) { $('#send_cc').val(account_manager_email); } else { $('#send_cc').val(send_cc_field + ', ' + account_manager_email); } }); $('#template').change(function() { loadTemplate() }); $('.add_as_recipient').click(function() { var email_address = $(this).data('email'); if (!isNullorEmpty(email_address)) { $(this).toggleClass('btn-success'); $(this).toggleClass('btn-danger'); if ($(this).attr('data-original-title') == 'Add as recipient') { $(this).attr('data-original-title', 'Remove recipient'); } else { $(this).attr('data-original-title', 'Add as recipient'); } $('[data-toggle="tooltip"]').tooltip(); // Convert "TO" text field to email adresses array console.log($('#send_to')); var send_to_values = $('#send_to').val().split(','); var send_to_array = []; send_to_values.forEach(function(email_address_in_send_to) { email_address_in_send_to = email_address_in_send_to.trim(); if (!isNullorEmpty(email_address_in_send_to)) { send_to_array.push(email_address_in_send_to); } }); // Add or remove selected email adress from array var firstname = $(this).data('firstname'); var firstname_array = $('#send_to').data('firstname'); if (!isNullorEmpty(firstname_array)) { firstname_array = JSON.parse($('#send_to').data('firstname')); } else { firstname_array = []; } var contact_id = $(this).data('contact-id'); var contact_id_array = $('#send_to').data('contact-id'); if (!isNullorEmpty(contact_id_array)) { contact_id_array = JSON.parse(contact_id_array); } else { contact_id_array = []; } var index_of_email_address = send_to_array.indexOf(email_address); if (index_of_email_address == -1 && $(this).hasClass('btn-danger') && !isNullorEmpty(email_address)) { send_to_array.push(email_address); if (!isNullorEmpty(firstname)) { firstname_array.push(firstname); } if (!isNullorEmpty(contact_id) || contact_id == 0) { contact_id_array.push(contact_id); } } else if ($(this).hasClass('btn-success')) { send_to_array.splice(index_of_email_address, 1); if (!isNullorEmpty(firstname)) { firstname_array.splice(firstname, 1); } if (!isNullorEmpty(contact_id)) { contact_id_array.splice(contact_id, 1); } } firstname_array = JSON.stringify(firstname_array); contact_id_array = JSON.stringify(contact_id_array); // Convert array to text field var send_to = ''; send_to_array.forEach(function(email_address) { send_to += email_address + ', '; }); send_to = send_to.slice(0, -2); console.log('send_to : ', send_to); $('#send_to').val(send_to); $('#send_to').data('firstname', firstname_array); $('#send_to').data('contact-id', contact_id_array); } }); $('#escalationbtn').click(function() { console.log("here"); escalateTicket(ticket_id, selector_number, selector_type); }); $('#removeescalationbtn').click(function() { console.log("here2"); deEscalateTicket(ticket_id, selector_number, selector_type, customerstatus, ticketstatus); }); $('#send_email').click(function() { sendEmail() }); } function escalateTicket(ticket_id, selector_number, selector_type) { var answer = window.confirm("Are you sure you want to escalate this ticket?"); if (answer) { //SET FIELDS IN RECORD //some code var ticketRecord = record.load({ type: 'customrecord_mp_ticket', id: Math.floor(ticket_id), isDynamic: true, }); var customerstatus = ticketRecord.getValue({fieldId: 'custrecord_mp_ticket_customer_status'}); var ticketstatus = ticketRecord.getValue({fieldId: 'custrecord_ticket_status'}); var customer_id = ticketRecord.getValue({fieldId: 'custrecord_customer1'}); var customer_barcode_number = ticketRecord.getValue({ fieldId : 'custrecord_barcode_number'}); var ticket_name = ticketRecord.getText({fieldId: 'name'}); console.log('customerstatus', customerstatus); if (parseInt(customerstatus) < 4 ) { console.log(customerstatus); ticketRecord.setValue({fieldId: 'custrecord_mp_ticket_customer_status', value: parseInt(customerstatus) + 1}); } if (parseInt(ticketstatus) < 11 ) { console.log(ticketstatus); ticketRecord.setValue({fieldId: 'custrecord_ticket_status', value: 11}); } else if (parseInt(ticketstatus) < 14) { console.log(ticketstatus); ticketRecord.setValue({fieldId: 'custrecord_ticket_status', value: parseInt(ticketstatus) + 1}); } ticketRecord.save({ enableSourcing: true, }) var barcodeRecord = record.load({ type: 'customrecord_customer_product_stock', id: customer_barcode_number, }); var receiveremail = barcodeRecord.getValue({fieldId: 'custrecord_receiver_email'}); var barcodeName = barcodeRecord.getValue({fieldId: 'name'}); var ticketRecord = record.load({ type: 'customrecord_mp_ticket', id: Math.floor(ticket_id), }) var ticketstatus = ticketRecord.getValue({fieldId: 'custrecord_ticket_status'}); if (!isNullorEmpty(receiveremail)) { if (ticketstatus == 11) { sendCustomerEscalateEmail('MailPlus [' + ticket_name + '] - Support enquiry | Stage 1 - ' + barcodeName, [receiveremail], 109, customer_id); } else if (ticketstatus == 12) { sendCustomerEscalateEmail('MailPlus [' + ticket_name + '] - Support enquiry | Stage 2 - ' + barcodeName, [receiveremail], 110, customer_id); } else if (ticketstatus == 13) { sendCustomerEscalateEmail('MailPlus [' + ticket_name + '] - Support enquiry | Stage 3 - ' + barcodeName, [receiveremail], 111, customer_id); } } //Send email to TOLL var toll_issues = ticketRecord.getText({ fieldId: 'custrecord_toll_issues' }); var mp_issues = ticketRecord.getText({ fieldId: 'custrecord_mp_ticket_issue' }); var body = 'MP Ticket ID: MPSD' + ticket_id + '\n Barcode: ' + barcodeName + '\nToll Issues: ' + toll_issues + '\nMP Issues: ' + mp_issues; // if (ticketstatus == 11) { // email.send({ // author: 112209, // body: body, // cc: ['jessica.roberts@mailplus.com.au', 'gabrielle.bathman@mailplus.com.au', 'customerservice@mailplus.com.au'], // recipients: ['CorpGold.Escalations@tollgroup.com'], // subject: 'Ticket Escalated: Escalation 1- MPSD' + ticket_id, // relatedRecords: {record: ticket_id, recordtype: 1042} // }); // } else if (ticketstatus == 12) { // email.send({ // author: 112209, // body: body, // cc: ['jessica.roberts@mailplus.com.au', 'gabrielle.bathman@mailplus.com.au', 'customerservice@mailplus.com.au'], // recipients: ['Natalie.Yildirim@tollgroup.com', 'Bernadette.Uluinaceva@tollgroup.com', 'aaron.davis@tollgroup.com'], // subject: 'Ticket Escalated: Escalation 2- MPSD' + ticket_id, // relatedRecords: {record: ticket_id, recordtype: 1042}, // }); // } else if (ticketstatus == 13) { // email.send({ // author: 112209, // body: body, // cc: ['jessica.roberts@mailplus.com.au', 'gabrielle.bathman@mailplus.com.au', 'customerservice@mailplus.com.au'], // recipients: ['dora.Venieris@tollgroup.com', 'marion.abada@tollgroup.com'], // subject: 'Ticket Escalated: Escalation 3- MPSD' + ticket_id, // relatedRecords: {record: ticket_id, recordtype: 1042}, // }); // } // REDIRECT TO URL console.log("IN HERE"); var params = { ticket_id: parseInt(ticket_id), selector_number: selector_number, selector_type: selector_type }; params = JSON.stringify(params); var output = url.resolveScript({ deploymentId: 'customdeploy_sl_ticketing_escalate', scriptId: 'customscript_sl_ticketing_escalate', }); var upload_url = baseURL + output + '&custparam_params=' + params; window.open(upload_url, "_self"); } else { //some code } } /** * Function to sent emails when a customer associated ticket is escalated */ function sendCustomerEscalateEmail(subject, recipients, template, customer_id) { var sales_rep = encodeURIComponent(runtime.getCurrentUser().name); var userid = encodeURIComponent(runtime.getCurrentUser().id); var suiteletUrl = url.resolveScript({ scriptId: 'customscript_merge_email', deploymentId: 'customdeploy_merge_email', returnExternalUrl: true }); suiteletUrl += '&rectype=customer&template='; suiteletUrl += template + '&recid=' + customer_id + '&salesrep=' + sales_rep + '&dear=' + '' + '&contactid=' + null + '&userid=' + userid; console.log(suiteletUrl); var response = https.get({ url: suiteletUrl }); var emailHtml = response.body; if (!isNullorEmpty(customer_id)) { email.send({ author: 112209, body: emailHtml, recipients: recipients, subject: subject, relatedRecords: { entityId: customer_id} }); } else { email.send({ author: 112209, body: emailHtml, recipients: recipients, subject: subject, }); } } function deEscalateTicket(ticket_id, selector_number, selector_type, customerstatus, ticketstatus) { var answer = window.confirm("Are you sure you want to de-escalate this ticket?"); if (answer) { //SET FIELDS IN RECORD //some code var ticketRecord = record.load({ type: 'customrecord_mp_ticket', id: Math.floor(ticket_id), isDynamic: true, }); // var customerstatus = ticketRecord.getValue({fieldId: 'custrecord_mp_ticket_customer_status'}); // var ticketstatus = ticketRecord.getValue({fieldId: 'custrecord_ticket_status'}); console.log('customerstatus', customerstatus); if (parseInt(ticketstatus) == 14) { ticketRecord.setValue({fieldId: 'custrecord_ticket_status', value: parseInt(ticketstatus) - 1}); } else { if (parseInt(customerstatus) > 1 ) { console.log(customerstatus); ticketRecord.setValue({fieldId: 'custrecord_mp_ticket_customer_status', value: parseInt(customerstatus) - 1}); } if (parseInt(ticketstatus) > 11 ) { console.log(ticketstatus); ticketRecord.setValue({fieldId: 'custrecord_ticket_status', value: parseInt(ticketstatus) - 1}); } } ticketRecord.save({ enableSourcing: true, }); // REDIRECT TO URL console.log("IN HERE"); var params = { ticket_id: parseInt(ticket_id), selector_number: selector_number, selector_type: selector_type }; params = JSON.stringify(params); var output = url.resolveScript({ deploymentId: 'customdeploy_sl_ticketing_escalate', scriptId: 'customscript_sl_ticketing_escalate', }); var upload_url = baseURL + output + '&custparam_params=' + params; window.open(upload_url, "_self"); } else { //some code } } /** * Set record status to 'In Progress'. * @param {Number} ticket_id */ function setRecordStatusToInProgress(ticket_id) { try { var ticketRecord = record.load({ type: 'customrecord_mp_ticket', id: ticket_id }); var status_value = ticketRecord.getValue({ fieldId: 'customrecord_mp_ticket' }); var invoice_id = ticketRecord.getValue({ fieldId: 'custrecord_invoice_number' }); if (isNullorEmpty(status_value) || status_value == 1) { //Ticket is open var selector_number = currRec.getValue({ fieldId: 'custpage_selector_number' }); if (isFinanceRoleOnly(userRole) && !isNullorEmpty(invoice_id)) { ticketRecord.setValue({ fieldId: 'custrecord_ticket_status', value: 6 }); } else if (!isNullorEmpty(selector_number) && selector_number == "Customer App") { console.log('Setting ticket status to In progress - IT'); ticketRecord.setValue({ fieldId: 'custrecord_ticket_status', value: 4 }); //In progress - Developers } else { ticketRecord.setValue({ fieldId: 'custrecord_ticket_status', value: 2 }); } ticketRecord.setValue({ fieldId: 'custrecord_email_sent', value: 'T' }); ticketRecord.save({ enableSourcing: true, }) } } catch (e) { console.log("e", e); //if (e instanceof error.SuiteScriptError) { if (e.name == "SSS_MISSING_REQD_ARGUMENT") { console.log('Error to Set record status to In Progress with ticket_id : ' + ticket_id); } //} } } /** * - Populates the Contacts table by adding contacts details at each row. * - If there is a ticket_id (which means we are in edit mode), * adds the contact to the "To" field of the "Send Email" section. */ function createContactsRows() { var contactsResultSet = loadContactsList(); console.log(contactsResultSet); // Used for the Contacts Table. var inline_contacts_table_html = ''; // If a ticket is opened for a barcode that is not allocated to a customer, // there will be no contacts. if (!isNullorEmpty(contactsResultSet)) { contactsResultSet.each(function(contactResult) { var contact_id = contactResult.getValue('internalid'); var salutation = contactResult.getValue('salutation'); var first_name = contactResult.getValue('firstname'); var last_name = contactResult.getValue('lastname'); var contact_name = salutation + ' ' + first_name + ' ' + last_name; var contact_email = contactResult.getValue('email'); var contact_phone = contactResult.getValue('phone'); var contact_role_value = contactResult.getValue('contactrole'); var contact_role_text = contactResult.getText('contactrole'); var add_as_recipient_btn = '<button style="background-color: #379E8F; border-color: #379E8F" class="btn btn-success add_as_recipient glyphicon glyphicon-envelope" type="button" data-email="' + contact_email + '" data-firstname="' + first_name + '" data-contact-id="' + contact_id + '" data-toggle="tooltip" data-placement="right" title="Add as recipient"></button>'; inline_contacts_table_html += '<tr class="text-center">'; inline_contacts_table_html += '<td headers="col_name">' + contact_name + '</td>'; inline_contacts_table_html += '<td headers="col_phone">' + contact_phone + '</td>'; inline_contacts_table_html += '<td headers="col_email">' + contact_email + '</td>'; inline_contacts_table_html += '<td headers="col_role">'; inline_contacts_table_html += '<span class="role_value" hidden>' + contact_role_value + '</span>'; inline_contacts_table_html += '<span class="role_text">' + contact_role_text + '</span>'; inline_contacts_table_html += '</td>'; inline_contacts_table_html += '<td headers="col_add_as_recipient">' + add_as_recipient_btn + '</td>'; inline_contacts_table_html += '</tr>'; return true; }); } $('#contacts tbody').html(inline_contacts_table_html); } /** * Loads the result set of all the contacts linked to a Customer. * @returns {nlobjSearchResultSet} contactsResultSet */ function loadContactsList() { var currRec = currentRecord.get(); var customer_id = currRec.getValue({ fieldId: 'custpage_customer_id' }); var contactsResultSet = []; // If a ticket is opened for a barcode that is not allocated to a customer, // there will be no customer_id. if (!isNullorEmpty(customer_id)) { var contactsSearch = search.load({ type: 'contact', id: 'customsearch_salesp_contacts' }); var contactsFilterExpression = [ ['company', 'is', customer_id], 'AND', ['isinactive', 'is', 'F'] ]; contactsSearch.filterExpression = contactsFilterExpression; contactsResultSet = contactsSearch.run(); } return contactsResultSet; } /** * Calculates the reminder date based on the current date and the selector_type. */ function setReminderDate() { var currRec = currentRecord.get(); var ticket_id = currRec.getValue({ fieldId: 'custpage_ticket_id' }); var status_value = currRec.getValue({ fieldId: 'custpage_ticket_status_value' }); if (isNullorEmpty(ticket_id) || !isTicketNotClosed(status_value)) { var selector_type = currRec.getValue({ fieldId: 'custpage_selector_type' }); var today = new Date(); var today_day_in_month = today.getDate(); var today_day_in_week = today.getDay(); var today_month = today.getMonth(); var today_year = today.getFullYear(); switch (selector_type) { case 'barcode_number': var addNbDays = 1; if (today_day_in_week == 5) { addNbDays += 2; } break; case 'invoice_number': var addNbDays = 3; if (today_day_in_week == 3 || today_day_in_week == 4 || today_day_in_week == 5) { addNbDays += 2; } break; } var reminder_date = new Date(Date.UTC(today_year, today_month, today_day_in_month + addNbDays)); reminder_date = reminder_date.toISOString().split('T')[0]; } else { ticket_id = parseInt(ticket_id); var ticketRecord = record.load({ type: 'customrecord_mp_ticket', id: ticket_id }); var ticket_reminder_date = ticketRecord.getValue({ fieldId: 'custrecord_reminder' }); var reminder_date = ''; if (!isNullorEmpty(ticket_reminder_date)) { ticket_reminder_date = format.parse({ value: ticket_reminder_date, type: format.Type.DATE }); var reminder_date_day_in_month = ticket_reminder_date.getDate(); var reminder_date_month = ticket_reminder_date.getMonth(); var reminder_date_year = ticket_reminder_date.getFullYear(); reminder_date = new Date(Date.UTC(reminder_date_year, reminder_date_month, reminder_date_day_in_month)); reminder_date = reminder_date.toISOString().split('T')[0]; } } $('#reminder').val(reminder_date); } /** * Function triggered when the '#template' input field is blurred. * Load the subject of the email and the body of the template. */ function loadTemplate() { var currRec = currentRecord.get(); var template_id = $('#template option:selected').val(); console.log('template_id : ', template_id); try { var templateRecord = record.load({ type: 'customrecord_camp_comm_template', id: template_id, isDynamic: true }); var template_subject = templateRecord.getValue({ fieldId: 'custrecord_camp_comm_subject' }); console.log("templateRecord", templateRecord); console.log("tempsubj", template_subject); } catch (e) { if (e.name == "SSS_MISSING_REQD_ARGUMENT") { console.log('Error to load the template with template_id : ' + template_id); } } var customer_id = currRec.getValue({ fieldId: 'custpage_customer_id' }); var sales_rep = encodeURIComponent(runtime.getCurrentUser().name); console.log($('#send_to')) var first_name = $('#send_to').data("firstname"); console.log(first_name) var dear = encodeURIComponent(first_name); var contact_id = ''; var contact_id_array = $('#send_to').data('contact-id'); if (!isNullorEmpty(contact_id_array)) { contact_id_array = JSON.parse(contact_id_array); if (!isNullorEmpty(contact_id_array)) { contact_id = contact_id_array[0].toString(); if (contact_id == '0' && !isNullorEmpty(contact_id[1])) { contact_id = ''; } } } console.log('contact_id : ', contact_id); var userid = encodeURIComponent(runtime.getCurrentUser().id); var suiteletUrl = url.resolveScript({ scriptId: 'customscript_merge_email', deploymentId: 'customdeploy_merge_email', returnExternalUrl: true }); console.log('suiteletUrl', suiteletUrl); suiteletUrl += '&rectype=customer&template='; var emailAttach = new Object(); emailAttach['entity'] = customer_id; suiteletUrl += template_id + '&recid=' + customer_id + '&salesrep=' + sales_rep + '&dear=' + dear + '&contactid=' + null + '&userid=' + userid; console.log('suiteletUrl', suiteletUrl); var response = https.get({ url: suiteletUrl }); console.log("response", response); var emailHtml = response.body; $('#email_body').summernote('code', emailHtml); var ticket_id = currRec.getValue({ fieldId: 'custpage_ticket_id' }); ticket_id = parseInt(ticket_id); var selector_number = currRec.getValue({ fieldId: 'custpage_selector_number' }); var subject = 'MailPlus [MPSD' + ticket_id + '] - ' + template_subject + ' - ' + selector_number; $('#subject').val(subject); } /** * Check that the fields "To", "Template" and "Subject" are non-empty. * @returns {Boolean} */ function validateEmailFields() { var alertMessage = ''; var return_value = true; var send_to_val = $('#send_to').val(); var send_toll_val = $('#send_toll').val(); if (isNullorEmpty(send_to_val) && isNullorEmpty(send_toll_val)) { return_value = false; alertMessage += 'Please select a recipient.<br>'; } var template_val = $('#template option:selected').val(); if (isNullorEmpty(template_val)) { return_value = false; alertMessage += 'Please select a template.<br>'; } else { var subject_val = $('#subject').val(); if (isNullorEmpty(subject_val)) { return_value = false; alertMessage += 'Please enter a subject.<br>'; } } if (return_value == false) { showAlert(alertMessage); } else { $('#alert').parent().hide(); } return return_value; } /** * Returns whether a ticket is closed or not based on its status value. * @param {Number} status_value * @returns {Boolean} is_ticket_closed */ function isTicketNotClosed(status_value) { var is_ticket_not_closed = ((status_value != 3) && (status_value != 8)) ? true : false; return is_ticket_not_closed; } /** * Triggered by a click on the button 'SEND EMAIL' ('#send_email') * Send the selected email to the selected contact, and reloads the page. */ function sendEmail() { if (validateEmailFields()) { // Send Email // Convert "TO" text field to email adresses array var send_to_values = $('#send_to').val().split(','); var send_to = []; if (!isNullorEmpty(send_to_values)) { send_to_values.forEach(function(email_address) { email_address = email_address.trim(); if (!isNullorEmpty(email_address)) { send_to.push(email_address); } }); } var send_toll_values = $('#send_toll').val(); var send_toll_to = []; if (!isNullorEmpty(send_toll_values)) { for (var i = 0; i < send_toll_values.length; i++) { send_toll_to.push($('#send_toll option:selected').val(send_toll_values)[i].text); } } // CC Field var cc_values = $('#send_cc').val().split(','); var cc = []; cc_values.forEach(function(email_address) { cc.push(email_address.trim()); return true; }); if (isNullorEmpty(cc)) { cc = null; } // BCC Field var bcc_values = $('#send_bcc').val().split(','); var bcc = []; bcc_values.forEach(function(email_address) { bcc.push(email_address.trim()); return true; }); if (isNullorEmpty(bcc)) { bcc = null; } if (!isNullorEmpty(send_to)) { // Attach message to Customer / Franchisee record var emailAttach = new Object(); var receiver_contact_id_array = $('#send_to').data('contact-id'); if (!isNullorEmpty(receiver_contact_id_array)) { receiver_contact_id_array = JSON.parse(receiver_contact_id_array); receiver_contact_id_array.forEach(function(receiver_contact_id) { if (receiver_contact_id == "0") { // Partner var zee_id = currRec.getValue({ fieldId: 'custpage_zee_id' }); emailAttach['entity'] = zee_id; } else if (!isNullorEmpty(receiver_contact_id)) { // Customer var customer_id = currRec.getValue({ fieldId: 'custpage_customer_id' }); emailAttach['entity'] = customer_id; } }); } } var email_subject = $('#subject').val(); var email_body = $('#email_body').summernote('code'); var ticket_id = currRec.getValue({ fieldId: 'custpage_ticket_id' }); ticket_id = parseInt(ticket_id); var params_email = currRec.getValue({ fieldId: 'custpage_param_email' }); params_email = JSON.parse(params_email); params_email.recipient = send_to; params_email.subject = email_subject; params_email.body = encodeURIComponent(email_body); params_email.cc = cc; params_email.bcc = bcc; params_email.records = emailAttach; var attachments_credit_memo_ids = params_email.attachments_credit_memo_ids; var attachments_usage_report_ids = params_email.attachments_usage_report_ids; var attachments_invoice_ids = params_email.attachments_invoice_ids; params_email = JSON.stringify(params_email); if (!isNullorEmpty(attachments_credit_memo_ids) || !isNullorEmpty(attachments_usage_report_ids) || !isNullorEmpty(attachments_invoice_ids)) { // Send email using the response part of this suitelet script. currRec.setValue({ fieldId: 'custpage_param_email', value: params_email }); setRecordStatusToInProgress(ticket_id); // Trigger the submit function. $('#submitter').trigger('click'); } else { send_to = send_to.concat(send_toll_to); console.log("Final send " + send_to); // If there are no attachments, it's faster to directly use nlapiSendEmail() from the client script. email.send({ author: userId, body: email_body, recipients: send_to, subject: email_subject, //attachments: emailAttach, bcc: bcc, cc: cc, }) // 112209 is from MailPlus Team var selector_number = currRec.getValue({ fieldId: 'custpage_selector_number' }); var selector_type = currRec.getValue({ fieldId: 'custpage_selector_type' }); setRecordStatusToInProgress(ticket_id); // Reload the page var params = { ticket_id: parseInt(ticket_id), selector_number: selector_number, selector_type: selector_type, }; params = JSON.stringify(params); var output = url.resolveScript({ deploymentId: 'customdeploy_sl_ticketing_escalate', scriptId: 'customscript_sl_ticketing_escalate', }) var upload_url = baseURL + output + '&custparam_params=' + params; window.open(upload_url, "_self", "height=750,width=650,modal=yes,alwaysRaised=yes"); } } else { return false; } } function saveRecord(context) { return true; } function isNullorEmpty(strVal) { return (strVal == null || strVal == '' || strVal == 'null' || strVal == undefined || strVal == 'undefined' || strVal == '- None -'); } return { pageInit: pageInit, saveRecord: saveRecord, }; } );
1,060
[{"tag": "EMAIL", "value": "jessica.roberts@mailplus.com.au", "start": 13137, "end": 13168}, {"tag": "EMAIL", "value": "gabrielle.bathman@mailplus.com.au", "start": 13172, "end": 13205}, {"tag": "EMAIL", "value": "customerservice@mailplus.com.au", "start": 13209, "end": 13240}, {"tag": "EMAIL", "value": "CorpGold.Escalations@tollgroup.com", "start": 13281, "end": 13315}, {"tag": "EMAIL", "value": "jessica.roberts@mailplus.com.au", "start": 13686, "end": 13717}, {"tag": "EMAIL", "value": "gabrielle.bathman@mailplus.com.au", "start": 13721, "end": 13754}, {"tag": "EMAIL", "value": "customerservice@mailplus.com.au", "start": 13758, "end": 13789}, {"tag": "EMAIL", "value": "Natalie.Yildirim@tollgroup.com", "start": 13830, "end": 13860}, {"tag": "EMAIL", "value": "Bernadette.Uluinaceva@tollgroup.com", "start": 13864, "end": 13899}, {"tag": "EMAIL", "value": "aaron.davis@tollgroup.com", "start": 13903, "end": 13928}, {"tag": "EMAIL", "value": "jessica.roberts@mailplus.com.au", "start": 14300, "end": 14331}, {"tag": "EMAIL", "value": "gabrielle.bathman@mailplus.com.au", "start": 14335, "end": 14368}, {"tag": "EMAIL", "value": "customerservice@mailplus.com.au", "start": 14372, "end": 14403}, {"tag": "EMAIL", "value": "dora.Venieris@tollgroup.com", "start": 14444, "end": 14471}, {"tag": "EMAIL", "value": "marion.abada@tollgroup.com", "start": 14475, "end": 14501}]
true
15
/** * * @NApiVersion 2.0 * @NScriptType ClientScript * * Description: Separate page for escalating ticket * @Last Modified by: Sruti Desai * */ define(['N/error', 'N/runtime', 'N/search', 'N/url', 'N/record', 'N/format', 'N/email', 'N/currentRecord', 'N/https'], function(error, runtime, search, url, record, format, email, currentRecord, https) { var baseURL = 'https://1048144.app.netsuite.com'; if (runtime.envType == "SANDBOX") { baseURL = 'https://1048144-sb3.app.netsuite.com'; } var role = runtime.getCurrentUser().role; var userId = runtime.getCurrentUser().id; var currRec = currentRecord.get(); /** * On page initialisation */ function pageInit() { var currRec = currentRecord.get(); var selector_number = currRec.getValue({ fieldId: 'custpage_selector_number' }); var selector_type = currRec.getValue({ fieldId: 'custpage_selector_type' }); var ticket_id = currRec.getValue({ fieldId: 'custpage_ticket_id' }); var status_value = currRec.getValue({ fieldId: 'custpage_ticket_status_value' }); var customer_number = currRec.getValue({ fieldId: 'custpage_customer_number' }); var ticketRecord = record.load({ type: 'customrecord_mp_ticket', id: Math.floor(ticket_id), isDynamic: true, }); var customerstatus = ticketRecord.getValue({fieldId: 'custrecord_mp_ticket_customer_status'}); var ticketstatus = ticketRecord.getValue({fieldId: 'custrecord_ticket_status'}); //background-colors $("#NS_MENU_ID0-item0").css("background-color", "#CFE0CE"); $("#NS_MENU_ID0-item0 a").css("background-color", "#CFE0CE"); $("#body").css("background-color", "#CFE0CE"); $(document).ready(function() { $('#email_body').summernote(); $('#owner, #toll_issues, #mp_issues, #invoice_issues, #enquiry_medium_status, #send_toll').selectpicker(); }); var inline_html_contact_table = '<table cellpadding="15" id="contacts" class="table table-responsive table-striped contacts tablesorter" cellspacing="0" style="width: 100%;border: 0"><thead style="color: white;background-color: #379E8F;"><tr><th style="vertical-align: middle;text-align: center;" id="col_name"><b>NAME</b></th><th style="vertical-align: middle;text-align: center;" id="col_phone"><b>PHONE</b></th><th style="vertical-align: middle;text-align: center;" id="col_email"><b>EMAIL</b></th><th style="vertical-align: middle;text-align: center;" id="col_role"><b>ROLE</b></th><th style="vertical-align: middle;text-align: center;" id="col_add_as_recipient"><b>ADD AS RECIPIENT</b></th></tr></thead><tbody></tbody></table>'; $('div.col-xs-12.contacts_div').html(inline_html_contact_table); if (!isNullorEmpty(selector_number)) { console.log('!isNullorEmpty(selector_number) : ', !isNullorEmpty(selector_number)); // If we updated the contacts, we have the parameter 'custpage_selector_number' and no parameter for 'custpage_ticket_id'. if (!isNullorEmpty(ticket_id)) { console.log('isNullorEmpty(ticket_id) : ', isNullorEmpty(ticket_id)); createContactsRows(); // If the ticket status is "Open, the acknoledgement template shall be selected. if (status_value != 3) { $('#template option:selected').attr('selected', false); if (customerstatus == 2) { $('#template option[value="109"]').attr('selected', true); // Select the acknoledgement template //$('#template option[value="304"]').attr('selected', true); // Select the acknoledgement template console.log("a"); } else if (customerstatus == 3) { $('#template option[value="110"]').attr('selected', true); // Select the acknoledgement template //$('#template option[value="303"]').attr('selected', true); // Select the acknoledgement template console.log("b"); } else if (customerstatus == 4) { $('#template option[value="111"]').attr('selected', true); // Select the acknoledgement template //$('#template option[value="302"]').attr('selected', true); // Select the acknoledgement template console.log("c"); } else { $('#template option[value="66"]').attr('selected', true); // Select the acknoledgement template //$('#template option[value="237"]').attr('selected', true); // Select the under investigation template } loadTemplate(); } if (selector_type == 'barcode_number') { setReminderDate(); } } } $('#acc_manager_button').click(function() { var account_manager_email = $('#acc_manager').data('email'); var send_cc_field = $('#send_cc').val(); if (isNullorEmpty(send_cc_field)) { $('#send_cc').val(account_manager_email); } else { $('#send_cc').val(send_cc_field + ', ' + account_manager_email); } }); $('#template').change(function() { loadTemplate() }); $('.add_as_recipient').click(function() { var email_address = $(this).data('email'); if (!isNullorEmpty(email_address)) { $(this).toggleClass('btn-success'); $(this).toggleClass('btn-danger'); if ($(this).attr('data-original-title') == 'Add as recipient') { $(this).attr('data-original-title', 'Remove recipient'); } else { $(this).attr('data-original-title', 'Add as recipient'); } $('[data-toggle="tooltip"]').tooltip(); // Convert "TO" text field to email adresses array console.log($('#send_to')); var send_to_values = $('#send_to').val().split(','); var send_to_array = []; send_to_values.forEach(function(email_address_in_send_to) { email_address_in_send_to = email_address_in_send_to.trim(); if (!isNullorEmpty(email_address_in_send_to)) { send_to_array.push(email_address_in_send_to); } }); // Add or remove selected email adress from array var firstname = $(this).data('firstname'); var firstname_array = $('#send_to').data('firstname'); if (!isNullorEmpty(firstname_array)) { firstname_array = JSON.parse($('#send_to').data('firstname')); } else { firstname_array = []; } var contact_id = $(this).data('contact-id'); var contact_id_array = $('#send_to').data('contact-id'); if (!isNullorEmpty(contact_id_array)) { contact_id_array = JSON.parse(contact_id_array); } else { contact_id_array = []; } var index_of_email_address = send_to_array.indexOf(email_address); if (index_of_email_address == -1 && $(this).hasClass('btn-danger') && !isNullorEmpty(email_address)) { send_to_array.push(email_address); if (!isNullorEmpty(firstname)) { firstname_array.push(firstname); } if (!isNullorEmpty(contact_id) || contact_id == 0) { contact_id_array.push(contact_id); } } else if ($(this).hasClass('btn-success')) { send_to_array.splice(index_of_email_address, 1); if (!isNullorEmpty(firstname)) { firstname_array.splice(firstname, 1); } if (!isNullorEmpty(contact_id)) { contact_id_array.splice(contact_id, 1); } } firstname_array = JSON.stringify(firstname_array); contact_id_array = JSON.stringify(contact_id_array); // Convert array to text field var send_to = ''; send_to_array.forEach(function(email_address) { send_to += email_address + ', '; }); send_to = send_to.slice(0, -2); console.log('send_to : ', send_to); $('#send_to').val(send_to); $('#send_to').data('firstname', firstname_array); $('#send_to').data('contact-id', contact_id_array); } }); $('#escalationbtn').click(function() { console.log("here"); escalateTicket(ticket_id, selector_number, selector_type); }); $('#removeescalationbtn').click(function() { console.log("here2"); deEscalateTicket(ticket_id, selector_number, selector_type, customerstatus, ticketstatus); }); $('#send_email').click(function() { sendEmail() }); } function escalateTicket(ticket_id, selector_number, selector_type) { var answer = window.confirm("Are you sure you want to escalate this ticket?"); if (answer) { //SET FIELDS IN RECORD //some code var ticketRecord = record.load({ type: 'customrecord_mp_ticket', id: Math.floor(ticket_id), isDynamic: true, }); var customerstatus = ticketRecord.getValue({fieldId: 'custrecord_mp_ticket_customer_status'}); var ticketstatus = ticketRecord.getValue({fieldId: 'custrecord_ticket_status'}); var customer_id = ticketRecord.getValue({fieldId: 'custrecord_customer1'}); var customer_barcode_number = ticketRecord.getValue({ fieldId : 'custrecord_barcode_number'}); var ticket_name = ticketRecord.getText({fieldId: 'name'}); console.log('customerstatus', customerstatus); if (parseInt(customerstatus) < 4 ) { console.log(customerstatus); ticketRecord.setValue({fieldId: 'custrecord_mp_ticket_customer_status', value: parseInt(customerstatus) + 1}); } if (parseInt(ticketstatus) < 11 ) { console.log(ticketstatus); ticketRecord.setValue({fieldId: 'custrecord_ticket_status', value: 11}); } else if (parseInt(ticketstatus) < 14) { console.log(ticketstatus); ticketRecord.setValue({fieldId: 'custrecord_ticket_status', value: parseInt(ticketstatus) + 1}); } ticketRecord.save({ enableSourcing: true, }) var barcodeRecord = record.load({ type: 'customrecord_customer_product_stock', id: customer_barcode_number, }); var receiveremail = barcodeRecord.getValue({fieldId: 'custrecord_receiver_email'}); var barcodeName = barcodeRecord.getValue({fieldId: 'name'}); var ticketRecord = record.load({ type: 'customrecord_mp_ticket', id: Math.floor(ticket_id), }) var ticketstatus = ticketRecord.getValue({fieldId: 'custrecord_ticket_status'}); if (!isNullorEmpty(receiveremail)) { if (ticketstatus == 11) { sendCustomerEscalateEmail('MailPlus [' + ticket_name + '] - Support enquiry | Stage 1 - ' + barcodeName, [receiveremail], 109, customer_id); } else if (ticketstatus == 12) { sendCustomerEscalateEmail('MailPlus [' + ticket_name + '] - Support enquiry | Stage 2 - ' + barcodeName, [receiveremail], 110, customer_id); } else if (ticketstatus == 13) { sendCustomerEscalateEmail('MailPlus [' + ticket_name + '] - Support enquiry | Stage 3 - ' + barcodeName, [receiveremail], 111, customer_id); } } //Send email to TOLL var toll_issues = ticketRecord.getText({ fieldId: 'custrecord_toll_issues' }); var mp_issues = ticketRecord.getText({ fieldId: 'custrecord_mp_ticket_issue' }); var body = 'MP Ticket ID: MPSD' + ticket_id + '\n Barcode: ' + barcodeName + '\nToll Issues: ' + toll_issues + '\nMP Issues: ' + mp_issues; // if (ticketstatus == 11) { // email.send({ // author: 112209, // body: body, // cc: ['kenaa@example.com', 'anpch@example.com', 'efpyi@example.com'], // recipients: ['lyhxr@example.com'], // subject: 'Ticket Escalated: Escalation 1- MPSD' + ticket_id, // relatedRecords: {record: ticket_id, recordtype: 1042} // }); // } else if (ticketstatus == 12) { // email.send({ // author: 112209, // body: body, // cc: ['kenaa@example.com', 'anpch@example.com', 'efpyi@example.com'], // recipients: ['dycjh@example.com', 'envkt@example.com', 'anpch@example.com'], // subject: 'Ticket Escalated: Escalation 2- MPSD' + ticket_id, // relatedRecords: {record: ticket_id, recordtype: 1042}, // }); // } else if (ticketstatus == 13) { // email.send({ // author: 112209, // body: body, // cc: ['kenaa@example.com', 'anpch@example.com', 'efpyi@example.com'], // recipients: ['efpyi@example.com', 'kenaa@example.com'], // subject: 'Ticket Escalated: Escalation 3- MPSD' + ticket_id, // relatedRecords: {record: ticket_id, recordtype: 1042}, // }); // } // REDIRECT TO URL console.log("IN HERE"); var params = { ticket_id: parseInt(ticket_id), selector_number: selector_number, selector_type: selector_type }; params = JSON.stringify(params); var output = url.resolveScript({ deploymentId: 'customdeploy_sl_ticketing_escalate', scriptId: 'customscript_sl_ticketing_escalate', }); var upload_url = baseURL + output + '&custparam_params=' + params; window.open(upload_url, "_self"); } else { //some code } } /** * Function to sent emails when a customer associated ticket is escalated */ function sendCustomerEscalateEmail(subject, recipients, template, customer_id) { var sales_rep = encodeURIComponent(runtime.getCurrentUser().name); var userid = encodeURIComponent(runtime.getCurrentUser().id); var suiteletUrl = url.resolveScript({ scriptId: 'customscript_merge_email', deploymentId: 'customdeploy_merge_email', returnExternalUrl: true }); suiteletUrl += '&rectype=customer&template='; suiteletUrl += template + '&recid=' + customer_id + '&salesrep=' + sales_rep + '&dear=' + '' + '&contactid=' + null + '&userid=' + userid; console.log(suiteletUrl); var response = https.get({ url: suiteletUrl }); var emailHtml = response.body; if (!isNullorEmpty(customer_id)) { email.send({ author: 112209, body: emailHtml, recipients: recipients, subject: subject, relatedRecords: { entityId: customer_id} }); } else { email.send({ author: 112209, body: emailHtml, recipients: recipients, subject: subject, }); } } function deEscalateTicket(ticket_id, selector_number, selector_type, customerstatus, ticketstatus) { var answer = window.confirm("Are you sure you want to de-escalate this ticket?"); if (answer) { //SET FIELDS IN RECORD //some code var ticketRecord = record.load({ type: 'customrecord_mp_ticket', id: Math.floor(ticket_id), isDynamic: true, }); // var customerstatus = ticketRecord.getValue({fieldId: 'custrecord_mp_ticket_customer_status'}); // var ticketstatus = ticketRecord.getValue({fieldId: 'custrecord_ticket_status'}); console.log('customerstatus', customerstatus); if (parseInt(ticketstatus) == 14) { ticketRecord.setValue({fieldId: 'custrecord_ticket_status', value: parseInt(ticketstatus) - 1}); } else { if (parseInt(customerstatus) > 1 ) { console.log(customerstatus); ticketRecord.setValue({fieldId: 'custrecord_mp_ticket_customer_status', value: parseInt(customerstatus) - 1}); } if (parseInt(ticketstatus) > 11 ) { console.log(ticketstatus); ticketRecord.setValue({fieldId: 'custrecord_ticket_status', value: parseInt(ticketstatus) - 1}); } } ticketRecord.save({ enableSourcing: true, }); // REDIRECT TO URL console.log("IN HERE"); var params = { ticket_id: parseInt(ticket_id), selector_number: selector_number, selector_type: selector_type }; params = JSON.stringify(params); var output = url.resolveScript({ deploymentId: 'customdeploy_sl_ticketing_escalate', scriptId: 'customscript_sl_ticketing_escalate', }); var upload_url = baseURL + output + '&custparam_params=' + params; window.open(upload_url, "_self"); } else { //some code } } /** * Set record status to 'In Progress'. * @param {Number} ticket_id */ function setRecordStatusToInProgress(ticket_id) { try { var ticketRecord = record.load({ type: 'customrecord_mp_ticket', id: ticket_id }); var status_value = ticketRecord.getValue({ fieldId: 'customrecord_mp_ticket' }); var invoice_id = ticketRecord.getValue({ fieldId: 'custrecord_invoice_number' }); if (isNullorEmpty(status_value) || status_value == 1) { //Ticket is open var selector_number = currRec.getValue({ fieldId: 'custpage_selector_number' }); if (isFinanceRoleOnly(userRole) && !isNullorEmpty(invoice_id)) { ticketRecord.setValue({ fieldId: 'custrecord_ticket_status', value: 6 }); } else if (!isNullorEmpty(selector_number) && selector_number == "Customer App") { console.log('Setting ticket status to In progress - IT'); ticketRecord.setValue({ fieldId: 'custrecord_ticket_status', value: 4 }); //In progress - Developers } else { ticketRecord.setValue({ fieldId: 'custrecord_ticket_status', value: 2 }); } ticketRecord.setValue({ fieldId: 'custrecord_email_sent', value: 'T' }); ticketRecord.save({ enableSourcing: true, }) } } catch (e) { console.log("e", e); //if (e instanceof error.SuiteScriptError) { if (e.name == "SSS_MISSING_REQD_ARGUMENT") { console.log('Error to Set record status to In Progress with ticket_id : ' + ticket_id); } //} } } /** * - Populates the Contacts table by adding contacts details at each row. * - If there is a ticket_id (which means we are in edit mode), * adds the contact to the "To" field of the "Send Email" section. */ function createContactsRows() { var contactsResultSet = loadContactsList(); console.log(contactsResultSet); // Used for the Contacts Table. var inline_contacts_table_html = ''; // If a ticket is opened for a barcode that is not allocated to a customer, // there will be no contacts. if (!isNullorEmpty(contactsResultSet)) { contactsResultSet.each(function(contactResult) { var contact_id = contactResult.getValue('internalid'); var salutation = contactResult.getValue('salutation'); var first_name = contactResult.getValue('firstname'); var last_name = contactResult.getValue('lastname'); var contact_name = salutation + ' ' + first_name + ' ' + last_name; var contact_email = contactResult.getValue('email'); var contact_phone = contactResult.getValue('phone'); var contact_role_value = contactResult.getValue('contactrole'); var contact_role_text = contactResult.getText('contactrole'); var add_as_recipient_btn = '<button style="background-color: #379E8F; border-color: #379E8F" class="btn btn-success add_as_recipient glyphicon glyphicon-envelope" type="button" data-email="' + contact_email + '" data-firstname="' + first_name + '" data-contact-id="' + contact_id + '" data-toggle="tooltip" data-placement="right" title="Add as recipient"></button>'; inline_contacts_table_html += '<tr class="text-center">'; inline_contacts_table_html += '<td headers="col_name">' + contact_name + '</td>'; inline_contacts_table_html += '<td headers="col_phone">' + contact_phone + '</td>'; inline_contacts_table_html += '<td headers="col_email">' + contact_email + '</td>'; inline_contacts_table_html += '<td headers="col_role">'; inline_contacts_table_html += '<span class="role_value" hidden>' + contact_role_value + '</span>'; inline_contacts_table_html += '<span class="role_text">' + contact_role_text + '</span>'; inline_contacts_table_html += '</td>'; inline_contacts_table_html += '<td headers="col_add_as_recipient">' + add_as_recipient_btn + '</td>'; inline_contacts_table_html += '</tr>'; return true; }); } $('#contacts tbody').html(inline_contacts_table_html); } /** * Loads the result set of all the contacts linked to a Customer. * @returns {nlobjSearchResultSet} contactsResultSet */ function loadContactsList() { var currRec = currentRecord.get(); var customer_id = currRec.getValue({ fieldId: 'custpage_customer_id' }); var contactsResultSet = []; // If a ticket is opened for a barcode that is not allocated to a customer, // there will be no customer_id. if (!isNullorEmpty(customer_id)) { var contactsSearch = search.load({ type: 'contact', id: 'customsearch_salesp_contacts' }); var contactsFilterExpression = [ ['company', 'is', customer_id], 'AND', ['isinactive', 'is', 'F'] ]; contactsSearch.filterExpression = contactsFilterExpression; contactsResultSet = contactsSearch.run(); } return contactsResultSet; } /** * Calculates the reminder date based on the current date and the selector_type. */ function setReminderDate() { var currRec = currentRecord.get(); var ticket_id = currRec.getValue({ fieldId: 'custpage_ticket_id' }); var status_value = currRec.getValue({ fieldId: 'custpage_ticket_status_value' }); if (isNullorEmpty(ticket_id) || !isTicketNotClosed(status_value)) { var selector_type = currRec.getValue({ fieldId: 'custpage_selector_type' }); var today = new Date(); var today_day_in_month = today.getDate(); var today_day_in_week = today.getDay(); var today_month = today.getMonth(); var today_year = today.getFullYear(); switch (selector_type) { case 'barcode_number': var addNbDays = 1; if (today_day_in_week == 5) { addNbDays += 2; } break; case 'invoice_number': var addNbDays = 3; if (today_day_in_week == 3 || today_day_in_week == 4 || today_day_in_week == 5) { addNbDays += 2; } break; } var reminder_date = new Date(Date.UTC(today_year, today_month, today_day_in_month + addNbDays)); reminder_date = reminder_date.toISOString().split('T')[0]; } else { ticket_id = parseInt(ticket_id); var ticketRecord = record.load({ type: 'customrecord_mp_ticket', id: ticket_id }); var ticket_reminder_date = ticketRecord.getValue({ fieldId: 'custrecord_reminder' }); var reminder_date = ''; if (!isNullorEmpty(ticket_reminder_date)) { ticket_reminder_date = format.parse({ value: ticket_reminder_date, type: format.Type.DATE }); var reminder_date_day_in_month = ticket_reminder_date.getDate(); var reminder_date_month = ticket_reminder_date.getMonth(); var reminder_date_year = ticket_reminder_date.getFullYear(); reminder_date = new Date(Date.UTC(reminder_date_year, reminder_date_month, reminder_date_day_in_month)); reminder_date = reminder_date.toISOString().split('T')[0]; } } $('#reminder').val(reminder_date); } /** * Function triggered when the '#template' input field is blurred. * Load the subject of the email and the body of the template. */ function loadTemplate() { var currRec = currentRecord.get(); var template_id = $('#template option:selected').val(); console.log('template_id : ', template_id); try { var templateRecord = record.load({ type: 'customrecord_camp_comm_template', id: template_id, isDynamic: true }); var template_subject = templateRecord.getValue({ fieldId: 'custrecord_camp_comm_subject' }); console.log("templateRecord", templateRecord); console.log("tempsubj", template_subject); } catch (e) { if (e.name == "SSS_MISSING_REQD_ARGUMENT") { console.log('Error to load the template with template_id : ' + template_id); } } var customer_id = currRec.getValue({ fieldId: 'custpage_customer_id' }); var sales_rep = encodeURIComponent(runtime.getCurrentUser().name); console.log($('#send_to')) var first_name = $('#send_to').data("firstname"); console.log(first_name) var dear = encodeURIComponent(first_name); var contact_id = ''; var contact_id_array = $('#send_to').data('contact-id'); if (!isNullorEmpty(contact_id_array)) { contact_id_array = JSON.parse(contact_id_array); if (!isNullorEmpty(contact_id_array)) { contact_id = contact_id_array[0].toString(); if (contact_id == '0' && !isNullorEmpty(contact_id[1])) { contact_id = ''; } } } console.log('contact_id : ', contact_id); var userid = encodeURIComponent(runtime.getCurrentUser().id); var suiteletUrl = url.resolveScript({ scriptId: 'customscript_merge_email', deploymentId: 'customdeploy_merge_email', returnExternalUrl: true }); console.log('suiteletUrl', suiteletUrl); suiteletUrl += '&rectype=customer&template='; var emailAttach = new Object(); emailAttach['entity'] = customer_id; suiteletUrl += template_id + '&recid=' + customer_id + '&salesrep=' + sales_rep + '&dear=' + dear + '&contactid=' + null + '&userid=' + userid; console.log('suiteletUrl', suiteletUrl); var response = https.get({ url: suiteletUrl }); console.log("response", response); var emailHtml = response.body; $('#email_body').summernote('code', emailHtml); var ticket_id = currRec.getValue({ fieldId: 'custpage_ticket_id' }); ticket_id = parseInt(ticket_id); var selector_number = currRec.getValue({ fieldId: 'custpage_selector_number' }); var subject = 'MailPlus [MPSD' + ticket_id + '] - ' + template_subject + ' - ' + selector_number; $('#subject').val(subject); } /** * Check that the fields "To", "Template" and "Subject" are non-empty. * @returns {Boolean} */ function validateEmailFields() { var alertMessage = ''; var return_value = true; var send_to_val = $('#send_to').val(); var send_toll_val = $('#send_toll').val(); if (isNullorEmpty(send_to_val) && isNullorEmpty(send_toll_val)) { return_value = false; alertMessage += 'Please select a recipient.<br>'; } var template_val = $('#template option:selected').val(); if (isNullorEmpty(template_val)) { return_value = false; alertMessage += 'Please select a template.<br>'; } else { var subject_val = $('#subject').val(); if (isNullorEmpty(subject_val)) { return_value = false; alertMessage += 'Please enter a subject.<br>'; } } if (return_value == false) { showAlert(alertMessage); } else { $('#alert').parent().hide(); } return return_value; } /** * Returns whether a ticket is closed or not based on its status value. * @param {Number} status_value * @returns {Boolean} is_ticket_closed */ function isTicketNotClosed(status_value) { var is_ticket_not_closed = ((status_value != 3) && (status_value != 8)) ? true : false; return is_ticket_not_closed; } /** * Triggered by a click on the button 'SEND EMAIL' ('#send_email') * Send the selected email to the selected contact, and reloads the page. */ function sendEmail() { if (validateEmailFields()) { // Send Email // Convert "TO" text field to email adresses array var send_to_values = $('#send_to').val().split(','); var send_to = []; if (!isNullorEmpty(send_to_values)) { send_to_values.forEach(function(email_address) { email_address = email_address.trim(); if (!isNullorEmpty(email_address)) { send_to.push(email_address); } }); } var send_toll_values = $('#send_toll').val(); var send_toll_to = []; if (!isNullorEmpty(send_toll_values)) { for (var i = 0; i < send_toll_values.length; i++) { send_toll_to.push($('#send_toll option:selected').val(send_toll_values)[i].text); } } // CC Field var cc_values = $('#send_cc').val().split(','); var cc = []; cc_values.forEach(function(email_address) { cc.push(email_address.trim()); return true; }); if (isNullorEmpty(cc)) { cc = null; } // BCC Field var bcc_values = $('#send_bcc').val().split(','); var bcc = []; bcc_values.forEach(function(email_address) { bcc.push(email_address.trim()); return true; }); if (isNullorEmpty(bcc)) { bcc = null; } if (!isNullorEmpty(send_to)) { // Attach message to Customer / Franchisee record var emailAttach = new Object(); var receiver_contact_id_array = $('#send_to').data('contact-id'); if (!isNullorEmpty(receiver_contact_id_array)) { receiver_contact_id_array = JSON.parse(receiver_contact_id_array); receiver_contact_id_array.forEach(function(receiver_contact_id) { if (receiver_contact_id == "0") { // Partner var zee_id = currRec.getValue({ fieldId: 'custpage_zee_id' }); emailAttach['entity'] = zee_id; } else if (!isNullorEmpty(receiver_contact_id)) { // Customer var customer_id = currRec.getValue({ fieldId: 'custpage_customer_id' }); emailAttach['entity'] = customer_id; } }); } } var email_subject = $('#subject').val(); var email_body = $('#email_body').summernote('code'); var ticket_id = currRec.getValue({ fieldId: 'custpage_ticket_id' }); ticket_id = parseInt(ticket_id); var params_email = currRec.getValue({ fieldId: 'custpage_param_email' }); params_email = JSON.parse(params_email); params_email.recipient = send_to; params_email.subject = email_subject; params_email.body = encodeURIComponent(email_body); params_email.cc = cc; params_email.bcc = bcc; params_email.records = emailAttach; var attachments_credit_memo_ids = params_email.attachments_credit_memo_ids; var attachments_usage_report_ids = params_email.attachments_usage_report_ids; var attachments_invoice_ids = params_email.attachments_invoice_ids; params_email = JSON.stringify(params_email); if (!isNullorEmpty(attachments_credit_memo_ids) || !isNullorEmpty(attachments_usage_report_ids) || !isNullorEmpty(attachments_invoice_ids)) { // Send email using the response part of this suitelet script. currRec.setValue({ fieldId: 'custpage_param_email', value: params_email }); setRecordStatusToInProgress(ticket_id); // Trigger the submit function. $('#submitter').trigger('click'); } else { send_to = send_to.concat(send_toll_to); console.log("Final send " + send_to); // If there are no attachments, it's faster to directly use nlapiSendEmail() from the client script. email.send({ author: userId, body: email_body, recipients: send_to, subject: email_subject, //attachments: emailAttach, bcc: bcc, cc: cc, }) // 112209 is from MailPlus Team var selector_number = currRec.getValue({ fieldId: 'custpage_selector_number' }); var selector_type = currRec.getValue({ fieldId: 'custpage_selector_type' }); setRecordStatusToInProgress(ticket_id); // Reload the page var params = { ticket_id: parseInt(ticket_id), selector_number: selector_number, selector_type: selector_type, }; params = JSON.stringify(params); var output = url.resolveScript({ deploymentId: 'customdeploy_sl_ticketing_escalate', scriptId: 'customscript_sl_ticketing_escalate', }) var upload_url = baseURL + output + '&custparam_params=' + params; window.open(upload_url, "_self", "height=750,width=650,modal=yes,alwaysRaised=yes"); } } else { return false; } } function saveRecord(context) { return true; } function isNullorEmpty(strVal) { return (strVal == null || strVal == '' || strVal == 'null' || strVal == undefined || strVal == 'undefined' || strVal == '- None -'); } return { pageInit: pageInit, saveRecord: saveRecord, }; } );
true
/** * * @NApiVersion 2.0 * @NScriptType ClientScript * * Description: Separate page for escalating ticket * @Last Modified by: Sruti Desai * */ define(['N/error', 'N/runtime', 'N/search', 'N/url', 'N/record', 'N/format', 'N/email', 'N/currentRecord', 'N/https'], function(error, runtime, search, url, record, format, email, currentRecord, https) { var baseURL = 'https://1048144.app.netsuite.com'; if (runtime.envType == "SANDBOX") { baseURL = 'https://1048144-sb3.app.netsuite.com'; } var role = runtime.getCurrentUser().role; var userId = runtime.getCurrentUser().id; var currRec = currentRecord.get(); /** * On page initialisation */ function pageInit() { var currRec = currentRecord.get(); var selector_number = currRec.getValue({ fieldId: 'custpage_selector_number' }); var selector_type = currRec.getValue({ fieldId: 'custpage_selector_type' }); var ticket_id = currRec.getValue({ fieldId: 'custpage_ticket_id' }); var status_value = currRec.getValue({ fieldId: 'custpage_ticket_status_value' }); var customer_number = currRec.getValue({ fieldId: 'custpage_customer_number' }); var ticketRecord = record.load({ type: 'customrecord_mp_ticket', id: Math.floor(ticket_id), isDynamic: true, }); var customerstatus = ticketRecord.getValue({fieldId: 'custrecord_mp_ticket_customer_status'}); var ticketstatus = ticketRecord.getValue({fieldId: 'custrecord_ticket_status'}); //background-colors $("#NS_MENU_ID0-item0").css("background-color", "#CFE0CE"); $("#NS_MENU_ID0-item0 a").css("background-color", "#CFE0CE"); $("#body").css("background-color", "#CFE0CE"); $(document).ready(function() { $('#email_body').summernote(); $('#owner, #toll_issues, #mp_issues, #invoice_issues, #enquiry_medium_status, #send_toll').selectpicker(); }); var inline_html_contact_table = '<table cellpadding="15" id="contacts" class="table table-responsive table-striped contacts tablesorter" cellspacing="0" style="width: 100%;border: 0"><thead style="color: white;background-color: #379E8F;"><tr><th style="vertical-align: middle;text-align: center;" id="col_name"><b>NAME</b></th><th style="vertical-align: middle;text-align: center;" id="col_phone"><b>PHONE</b></th><th style="vertical-align: middle;text-align: center;" id="col_email"><b>EMAIL</b></th><th style="vertical-align: middle;text-align: center;" id="col_role"><b>ROLE</b></th><th style="vertical-align: middle;text-align: center;" id="col_add_as_recipient"><b>ADD AS RECIPIENT</b></th></tr></thead><tbody></tbody></table>'; $('div.col-xs-12.contacts_div').html(inline_html_contact_table); if (!isNullorEmpty(selector_number)) { console.log('!isNullorEmpty(selector_number) : ', !isNullorEmpty(selector_number)); // If we updated the contacts, we have the parameter 'custpage_selector_number' and no parameter for 'custpage_ticket_id'. if (!isNullorEmpty(ticket_id)) { console.log('isNullorEmpty(ticket_id) : ', isNullorEmpty(ticket_id)); createContactsRows(); // If the ticket status is "Open, the acknoledgement template shall be selected. if (status_value != 3) { $('#template option:selected').attr('selected', false); if (customerstatus == 2) { $('#template option[value="109"]').attr('selected', true); // Select the acknoledgement template //$('#template option[value="304"]').attr('selected', true); // Select the acknoledgement template console.log("a"); } else if (customerstatus == 3) { $('#template option[value="110"]').attr('selected', true); // Select the acknoledgement template //$('#template option[value="303"]').attr('selected', true); // Select the acknoledgement template console.log("b"); } else if (customerstatus == 4) { $('#template option[value="111"]').attr('selected', true); // Select the acknoledgement template //$('#template option[value="302"]').attr('selected', true); // Select the acknoledgement template console.log("c"); } else { $('#template option[value="66"]').attr('selected', true); // Select the acknoledgement template //$('#template option[value="237"]').attr('selected', true); // Select the under investigation template } loadTemplate(); } if (selector_type == 'barcode_number') { setReminderDate(); } } } $('#acc_manager_button').click(function() { var account_manager_email = $('#acc_manager').data('email'); var send_cc_field = $('#send_cc').val(); if (isNullorEmpty(send_cc_field)) { $('#send_cc').val(account_manager_email); } else { $('#send_cc').val(send_cc_field + ', ' + account_manager_email); } }); $('#template').change(function() { loadTemplate() }); $('.add_as_recipient').click(function() { var email_address = $(this).data('email'); if (!isNullorEmpty(email_address)) { $(this).toggleClass('btn-success'); $(this).toggleClass('btn-danger'); if ($(this).attr('data-original-title') == 'Add as recipient') { $(this).attr('data-original-title', 'Remove recipient'); } else { $(this).attr('data-original-title', 'Add as recipient'); } $('[data-toggle="tooltip"]').tooltip(); // Convert "TO" text field to email adresses array console.log($('#send_to')); var send_to_values = $('#send_to').val().split(','); var send_to_array = []; send_to_values.forEach(function(email_address_in_send_to) { email_address_in_send_to = email_address_in_send_to.trim(); if (!isNullorEmpty(email_address_in_send_to)) { send_to_array.push(email_address_in_send_to); } }); // Add or remove selected email adress from array var firstname = $(this).data('firstname'); var firstname_array = $('#send_to').data('firstname'); if (!isNullorEmpty(firstname_array)) { firstname_array = JSON.parse($('#send_to').data('firstname')); } else { firstname_array = []; } var contact_id = $(this).data('contact-id'); var contact_id_array = $('#send_to').data('contact-id'); if (!isNullorEmpty(contact_id_array)) { contact_id_array = JSON.parse(contact_id_array); } else { contact_id_array = []; } var index_of_email_address = send_to_array.indexOf(email_address); if (index_of_email_address == -1 && $(this).hasClass('btn-danger') && !isNullorEmpty(email_address)) { send_to_array.push(email_address); if (!isNullorEmpty(firstname)) { firstname_array.push(firstname); } if (!isNullorEmpty(contact_id) || contact_id == 0) { contact_id_array.push(contact_id); } } else if ($(this).hasClass('btn-success')) { send_to_array.splice(index_of_email_address, 1); if (!isNullorEmpty(firstname)) { firstname_array.splice(firstname, 1); } if (!isNullorEmpty(contact_id)) { contact_id_array.splice(contact_id, 1); } } firstname_array = JSON.stringify(firstname_array); contact_id_array = JSON.stringify(contact_id_array); // Convert array to text field var send_to = ''; send_to_array.forEach(function(email_address) { send_to += email_address + ', '; }); send_to = send_to.slice(0, -2); console.log('send_to : ', send_to); $('#send_to').val(send_to); $('#send_to').data('firstname', firstname_array); $('#send_to').data('contact-id', contact_id_array); } }); $('#escalationbtn').click(function() { console.log("here"); escalateTicket(ticket_id, selector_number, selector_type); }); $('#removeescalationbtn').click(function() { console.log("here2"); deEscalateTicket(ticket_id, selector_number, selector_type, customerstatus, ticketstatus); }); $('#send_email').click(function() { sendEmail() }); } function escalateTicket(ticket_id, selector_number, selector_type) { var answer = window.confirm("Are you sure you want to escalate this ticket?"); if (answer) { //SET FIELDS IN RECORD //some code var ticketRecord = record.load({ type: 'customrecord_mp_ticket', id: Math.floor(ticket_id), isDynamic: true, }); var customerstatus = ticketRecord.getValue({fieldId: 'custrecord_mp_ticket_customer_status'}); var ticketstatus = ticketRecord.getValue({fieldId: 'custrecord_ticket_status'}); var customer_id = ticketRecord.getValue({fieldId: 'custrecord_customer1'}); var customer_barcode_number = ticketRecord.getValue({ fieldId : 'custrecord_barcode_number'}); var ticket_name = ticketRecord.getText({fieldId: 'name'}); console.log('customerstatus', customerstatus); if (parseInt(customerstatus) < 4 ) { console.log(customerstatus); ticketRecord.setValue({fieldId: 'custrecord_mp_ticket_customer_status', value: parseInt(customerstatus) + 1}); } if (parseInt(ticketstatus) < 11 ) { console.log(ticketstatus); ticketRecord.setValue({fieldId: 'custrecord_ticket_status', value: 11}); } else if (parseInt(ticketstatus) < 14) { console.log(ticketstatus); ticketRecord.setValue({fieldId: 'custrecord_ticket_status', value: parseInt(ticketstatus) + 1}); } ticketRecord.save({ enableSourcing: true, }) var barcodeRecord = record.load({ type: 'customrecord_customer_product_stock', id: customer_barcode_number, }); var receiveremail = barcodeRecord.getValue({fieldId: 'custrecord_receiver_email'}); var barcodeName = barcodeRecord.getValue({fieldId: 'name'}); var ticketRecord = record.load({ type: 'customrecord_mp_ticket', id: Math.floor(ticket_id), }) var ticketstatus = ticketRecord.getValue({fieldId: 'custrecord_ticket_status'}); if (!isNullorEmpty(receiveremail)) { if (ticketstatus == 11) { sendCustomerEscalateEmail('MailPlus [' + ticket_name + '] - Support enquiry | Stage 1 - ' + barcodeName, [receiveremail], 109, customer_id); } else if (ticketstatus == 12) { sendCustomerEscalateEmail('MailPlus [' + ticket_name + '] - Support enquiry | Stage 2 - ' + barcodeName, [receiveremail], 110, customer_id); } else if (ticketstatus == 13) { sendCustomerEscalateEmail('MailPlus [' + ticket_name + '] - Support enquiry | Stage 3 - ' + barcodeName, [receiveremail], 111, customer_id); } } //Send email to TOLL var toll_issues = ticketRecord.getText({ fieldId: 'custrecord_toll_issues' }); var mp_issues = ticketRecord.getText({ fieldId: 'custrecord_mp_ticket_issue' }); var body = 'MP Ticket ID: MPSD' + ticket_id + '\n Barcode: ' + barcodeName + '\nToll Issues: ' + toll_issues + '\nMP Issues: ' + mp_issues; // if (ticketstatus == 11) { // email.send({ // author: 112209, // body: body, // cc: ['PI:EMAIL:kenaa@example.comEND_PI', 'PI:EMAIL:anpch@example.comEND_PI', 'PI:EMAIL:efpyi@example.comEND_PI'], // recipients: ['PI:EMAIL:lyhxr@example.comEND_PI'], // subject: 'Ticket Escalated: Escalation 1- MPSD' + ticket_id, // relatedRecords: {record: ticket_id, recordtype: 1042} // }); // } else if (ticketstatus == 12) { // email.send({ // author: 112209, // body: body, // cc: ['PI:EMAIL:kenaa@example.comEND_PI', 'PI:EMAIL:anpch@example.comEND_PI', 'PI:EMAIL:efpyi@example.comEND_PI'], // recipients: ['PI:EMAIL:dycjh@example.comEND_PI', 'PI:EMAIL:envkt@example.comEND_PI', 'PI:EMAIL:anpch@example.comEND_PI'], // subject: 'Ticket Escalated: Escalation 2- MPSD' + ticket_id, // relatedRecords: {record: ticket_id, recordtype: 1042}, // }); // } else if (ticketstatus == 13) { // email.send({ // author: 112209, // body: body, // cc: ['PI:EMAIL:kenaa@example.comEND_PI', 'PI:EMAIL:anpch@example.comEND_PI', 'PI:EMAIL:efpyi@example.comEND_PI'], // recipients: ['PI:EMAIL:efpyi@example.comEND_PI', 'PI:EMAIL:kenaa@example.comEND_PI'], // subject: 'Ticket Escalated: Escalation 3- MPSD' + ticket_id, // relatedRecords: {record: ticket_id, recordtype: 1042}, // }); // } // REDIRECT TO URL console.log("IN HERE"); var params = { ticket_id: parseInt(ticket_id), selector_number: selector_number, selector_type: selector_type }; params = JSON.stringify(params); var output = url.resolveScript({ deploymentId: 'customdeploy_sl_ticketing_escalate', scriptId: 'customscript_sl_ticketing_escalate', }); var upload_url = baseURL + output + '&custparam_params=' + params; window.open(upload_url, "_self"); } else { //some code } } /** * Function to sent emails when a customer associated ticket is escalated */ function sendCustomerEscalateEmail(subject, recipients, template, customer_id) { var sales_rep = encodeURIComponent(runtime.getCurrentUser().name); var userid = encodeURIComponent(runtime.getCurrentUser().id); var suiteletUrl = url.resolveScript({ scriptId: 'customscript_merge_email', deploymentId: 'customdeploy_merge_email', returnExternalUrl: true }); suiteletUrl += '&rectype=customer&template='; suiteletUrl += template + '&recid=' + customer_id + '&salesrep=' + sales_rep + '&dear=' + '' + '&contactid=' + null + '&userid=' + userid; console.log(suiteletUrl); var response = https.get({ url: suiteletUrl }); var emailHtml = response.body; if (!isNullorEmpty(customer_id)) { email.send({ author: 112209, body: emailHtml, recipients: recipients, subject: subject, relatedRecords: { entityId: customer_id} }); } else { email.send({ author: 112209, body: emailHtml, recipients: recipients, subject: subject, }); } } function deEscalateTicket(ticket_id, selector_number, selector_type, customerstatus, ticketstatus) { var answer = window.confirm("Are you sure you want to de-escalate this ticket?"); if (answer) { //SET FIELDS IN RECORD //some code var ticketRecord = record.load({ type: 'customrecord_mp_ticket', id: Math.floor(ticket_id), isDynamic: true, }); // var customerstatus = ticketRecord.getValue({fieldId: 'custrecord_mp_ticket_customer_status'}); // var ticketstatus = ticketRecord.getValue({fieldId: 'custrecord_ticket_status'}); console.log('customerstatus', customerstatus); if (parseInt(ticketstatus) == 14) { ticketRecord.setValue({fieldId: 'custrecord_ticket_status', value: parseInt(ticketstatus) - 1}); } else { if (parseInt(customerstatus) > 1 ) { console.log(customerstatus); ticketRecord.setValue({fieldId: 'custrecord_mp_ticket_customer_status', value: parseInt(customerstatus) - 1}); } if (parseInt(ticketstatus) > 11 ) { console.log(ticketstatus); ticketRecord.setValue({fieldId: 'custrecord_ticket_status', value: parseInt(ticketstatus) - 1}); } } ticketRecord.save({ enableSourcing: true, }); // REDIRECT TO URL console.log("IN HERE"); var params = { ticket_id: parseInt(ticket_id), selector_number: selector_number, selector_type: selector_type }; params = JSON.stringify(params); var output = url.resolveScript({ deploymentId: 'customdeploy_sl_ticketing_escalate', scriptId: 'customscript_sl_ticketing_escalate', }); var upload_url = baseURL + output + '&custparam_params=' + params; window.open(upload_url, "_self"); } else { //some code } } /** * Set record status to 'In Progress'. * @param {Number} ticket_id */ function setRecordStatusToInProgress(ticket_id) { try { var ticketRecord = record.load({ type: 'customrecord_mp_ticket', id: ticket_id }); var status_value = ticketRecord.getValue({ fieldId: 'customrecord_mp_ticket' }); var invoice_id = ticketRecord.getValue({ fieldId: 'custrecord_invoice_number' }); if (isNullorEmpty(status_value) || status_value == 1) { //Ticket is open var selector_number = currRec.getValue({ fieldId: 'custpage_selector_number' }); if (isFinanceRoleOnly(userRole) && !isNullorEmpty(invoice_id)) { ticketRecord.setValue({ fieldId: 'custrecord_ticket_status', value: 6 }); } else if (!isNullorEmpty(selector_number) && selector_number == "Customer App") { console.log('Setting ticket status to In progress - IT'); ticketRecord.setValue({ fieldId: 'custrecord_ticket_status', value: 4 }); //In progress - Developers } else { ticketRecord.setValue({ fieldId: 'custrecord_ticket_status', value: 2 }); } ticketRecord.setValue({ fieldId: 'custrecord_email_sent', value: 'T' }); ticketRecord.save({ enableSourcing: true, }) } } catch (e) { console.log("e", e); //if (e instanceof error.SuiteScriptError) { if (e.name == "SSS_MISSING_REQD_ARGUMENT") { console.log('Error to Set record status to In Progress with ticket_id : ' + ticket_id); } //} } } /** * - Populates the Contacts table by adding contacts details at each row. * - If there is a ticket_id (which means we are in edit mode), * adds the contact to the "To" field of the "Send Email" section. */ function createContactsRows() { var contactsResultSet = loadContactsList(); console.log(contactsResultSet); // Used for the Contacts Table. var inline_contacts_table_html = ''; // If a ticket is opened for a barcode that is not allocated to a customer, // there will be no contacts. if (!isNullorEmpty(contactsResultSet)) { contactsResultSet.each(function(contactResult) { var contact_id = contactResult.getValue('internalid'); var salutation = contactResult.getValue('salutation'); var first_name = contactResult.getValue('firstname'); var last_name = contactResult.getValue('lastname'); var contact_name = salutation + ' ' + first_name + ' ' + last_name; var contact_email = contactResult.getValue('email'); var contact_phone = contactResult.getValue('phone'); var contact_role_value = contactResult.getValue('contactrole'); var contact_role_text = contactResult.getText('contactrole'); var add_as_recipient_btn = '<button style="background-color: #379E8F; border-color: #379E8F" class="btn btn-success add_as_recipient glyphicon glyphicon-envelope" type="button" data-email="' + contact_email + '" data-firstname="' + first_name + '" data-contact-id="' + contact_id + '" data-toggle="tooltip" data-placement="right" title="Add as recipient"></button>'; inline_contacts_table_html += '<tr class="text-center">'; inline_contacts_table_html += '<td headers="col_name">' + contact_name + '</td>'; inline_contacts_table_html += '<td headers="col_phone">' + contact_phone + '</td>'; inline_contacts_table_html += '<td headers="col_email">' + contact_email + '</td>'; inline_contacts_table_html += '<td headers="col_role">'; inline_contacts_table_html += '<span class="role_value" hidden>' + contact_role_value + '</span>'; inline_contacts_table_html += '<span class="role_text">' + contact_role_text + '</span>'; inline_contacts_table_html += '</td>'; inline_contacts_table_html += '<td headers="col_add_as_recipient">' + add_as_recipient_btn + '</td>'; inline_contacts_table_html += '</tr>'; return true; }); } $('#contacts tbody').html(inline_contacts_table_html); } /** * Loads the result set of all the contacts linked to a Customer. * @returns {nlobjSearchResultSet} contactsResultSet */ function loadContactsList() { var currRec = currentRecord.get(); var customer_id = currRec.getValue({ fieldId: 'custpage_customer_id' }); var contactsResultSet = []; // If a ticket is opened for a barcode that is not allocated to a customer, // there will be no customer_id. if (!isNullorEmpty(customer_id)) { var contactsSearch = search.load({ type: 'contact', id: 'customsearch_salesp_contacts' }); var contactsFilterExpression = [ ['company', 'is', customer_id], 'AND', ['isinactive', 'is', 'F'] ]; contactsSearch.filterExpression = contactsFilterExpression; contactsResultSet = contactsSearch.run(); } return contactsResultSet; } /** * Calculates the reminder date based on the current date and the selector_type. */ function setReminderDate() { var currRec = currentRecord.get(); var ticket_id = currRec.getValue({ fieldId: 'custpage_ticket_id' }); var status_value = currRec.getValue({ fieldId: 'custpage_ticket_status_value' }); if (isNullorEmpty(ticket_id) || !isTicketNotClosed(status_value)) { var selector_type = currRec.getValue({ fieldId: 'custpage_selector_type' }); var today = new Date(); var today_day_in_month = today.getDate(); var today_day_in_week = today.getDay(); var today_month = today.getMonth(); var today_year = today.getFullYear(); switch (selector_type) { case 'barcode_number': var addNbDays = 1; if (today_day_in_week == 5) { addNbDays += 2; } break; case 'invoice_number': var addNbDays = 3; if (today_day_in_week == 3 || today_day_in_week == 4 || today_day_in_week == 5) { addNbDays += 2; } break; } var reminder_date = new Date(Date.UTC(today_year, today_month, today_day_in_month + addNbDays)); reminder_date = reminder_date.toISOString().split('T')[0]; } else { ticket_id = parseInt(ticket_id); var ticketRecord = record.load({ type: 'customrecord_mp_ticket', id: ticket_id }); var ticket_reminder_date = ticketRecord.getValue({ fieldId: 'custrecord_reminder' }); var reminder_date = ''; if (!isNullorEmpty(ticket_reminder_date)) { ticket_reminder_date = format.parse({ value: ticket_reminder_date, type: format.Type.DATE }); var reminder_date_day_in_month = ticket_reminder_date.getDate(); var reminder_date_month = ticket_reminder_date.getMonth(); var reminder_date_year = ticket_reminder_date.getFullYear(); reminder_date = new Date(Date.UTC(reminder_date_year, reminder_date_month, reminder_date_day_in_month)); reminder_date = reminder_date.toISOString().split('T')[0]; } } $('#reminder').val(reminder_date); } /** * Function triggered when the '#template' input field is blurred. * Load the subject of the email and the body of the template. */ function loadTemplate() { var currRec = currentRecord.get(); var template_id = $('#template option:selected').val(); console.log('template_id : ', template_id); try { var templateRecord = record.load({ type: 'customrecord_camp_comm_template', id: template_id, isDynamic: true }); var template_subject = templateRecord.getValue({ fieldId: 'custrecord_camp_comm_subject' }); console.log("templateRecord", templateRecord); console.log("tempsubj", template_subject); } catch (e) { if (e.name == "SSS_MISSING_REQD_ARGUMENT") { console.log('Error to load the template with template_id : ' + template_id); } } var customer_id = currRec.getValue({ fieldId: 'custpage_customer_id' }); var sales_rep = encodeURIComponent(runtime.getCurrentUser().name); console.log($('#send_to')) var first_name = $('#send_to').data("firstname"); console.log(first_name) var dear = encodeURIComponent(first_name); var contact_id = ''; var contact_id_array = $('#send_to').data('contact-id'); if (!isNullorEmpty(contact_id_array)) { contact_id_array = JSON.parse(contact_id_array); if (!isNullorEmpty(contact_id_array)) { contact_id = contact_id_array[0].toString(); if (contact_id == '0' && !isNullorEmpty(contact_id[1])) { contact_id = ''; } } } console.log('contact_id : ', contact_id); var userid = encodeURIComponent(runtime.getCurrentUser().id); var suiteletUrl = url.resolveScript({ scriptId: 'customscript_merge_email', deploymentId: 'customdeploy_merge_email', returnExternalUrl: true }); console.log('suiteletUrl', suiteletUrl); suiteletUrl += '&rectype=customer&template='; var emailAttach = new Object(); emailAttach['entity'] = customer_id; suiteletUrl += template_id + '&recid=' + customer_id + '&salesrep=' + sales_rep + '&dear=' + dear + '&contactid=' + null + '&userid=' + userid; console.log('suiteletUrl', suiteletUrl); var response = https.get({ url: suiteletUrl }); console.log("response", response); var emailHtml = response.body; $('#email_body').summernote('code', emailHtml); var ticket_id = currRec.getValue({ fieldId: 'custpage_ticket_id' }); ticket_id = parseInt(ticket_id); var selector_number = currRec.getValue({ fieldId: 'custpage_selector_number' }); var subject = 'MailPlus [MPSD' + ticket_id + '] - ' + template_subject + ' - ' + selector_number; $('#subject').val(subject); } /** * Check that the fields "To", "Template" and "Subject" are non-empty. * @returns {Boolean} */ function validateEmailFields() { var alertMessage = ''; var return_value = true; var send_to_val = $('#send_to').val(); var send_toll_val = $('#send_toll').val(); if (isNullorEmpty(send_to_val) && isNullorEmpty(send_toll_val)) { return_value = false; alertMessage += 'Please select a recipient.<br>'; } var template_val = $('#template option:selected').val(); if (isNullorEmpty(template_val)) { return_value = false; alertMessage += 'Please select a template.<br>'; } else { var subject_val = $('#subject').val(); if (isNullorEmpty(subject_val)) { return_value = false; alertMessage += 'Please enter a subject.<br>'; } } if (return_value == false) { showAlert(alertMessage); } else { $('#alert').parent().hide(); } return return_value; } /** * Returns whether a ticket is closed or not based on its status value. * @param {Number} status_value * @returns {Boolean} is_ticket_closed */ function isTicketNotClosed(status_value) { var is_ticket_not_closed = ((status_value != 3) && (status_value != 8)) ? true : false; return is_ticket_not_closed; } /** * Triggered by a click on the button 'SEND EMAIL' ('#send_email') * Send the selected email to the selected contact, and reloads the page. */ function sendEmail() { if (validateEmailFields()) { // Send Email // Convert "TO" text field to email adresses array var send_to_values = $('#send_to').val().split(','); var send_to = []; if (!isNullorEmpty(send_to_values)) { send_to_values.forEach(function(email_address) { email_address = email_address.trim(); if (!isNullorEmpty(email_address)) { send_to.push(email_address); } }); } var send_toll_values = $('#send_toll').val(); var send_toll_to = []; if (!isNullorEmpty(send_toll_values)) { for (var i = 0; i < send_toll_values.length; i++) { send_toll_to.push($('#send_toll option:selected').val(send_toll_values)[i].text); } } // CC Field var cc_values = $('#send_cc').val().split(','); var cc = []; cc_values.forEach(function(email_address) { cc.push(email_address.trim()); return true; }); if (isNullorEmpty(cc)) { cc = null; } // BCC Field var bcc_values = $('#send_bcc').val().split(','); var bcc = []; bcc_values.forEach(function(email_address) { bcc.push(email_address.trim()); return true; }); if (isNullorEmpty(bcc)) { bcc = null; } if (!isNullorEmpty(send_to)) { // Attach message to Customer / Franchisee record var emailAttach = new Object(); var receiver_contact_id_array = $('#send_to').data('contact-id'); if (!isNullorEmpty(receiver_contact_id_array)) { receiver_contact_id_array = JSON.parse(receiver_contact_id_array); receiver_contact_id_array.forEach(function(receiver_contact_id) { if (receiver_contact_id == "0") { // Partner var zee_id = currRec.getValue({ fieldId: 'custpage_zee_id' }); emailAttach['entity'] = zee_id; } else if (!isNullorEmpty(receiver_contact_id)) { // Customer var customer_id = currRec.getValue({ fieldId: 'custpage_customer_id' }); emailAttach['entity'] = customer_id; } }); } } var email_subject = $('#subject').val(); var email_body = $('#email_body').summernote('code'); var ticket_id = currRec.getValue({ fieldId: 'custpage_ticket_id' }); ticket_id = parseInt(ticket_id); var params_email = currRec.getValue({ fieldId: 'custpage_param_email' }); params_email = JSON.parse(params_email); params_email.recipient = send_to; params_email.subject = email_subject; params_email.body = encodeURIComponent(email_body); params_email.cc = cc; params_email.bcc = bcc; params_email.records = emailAttach; var attachments_credit_memo_ids = params_email.attachments_credit_memo_ids; var attachments_usage_report_ids = params_email.attachments_usage_report_ids; var attachments_invoice_ids = params_email.attachments_invoice_ids; params_email = JSON.stringify(params_email); if (!isNullorEmpty(attachments_credit_memo_ids) || !isNullorEmpty(attachments_usage_report_ids) || !isNullorEmpty(attachments_invoice_ids)) { // Send email using the response part of this suitelet script. currRec.setValue({ fieldId: 'custpage_param_email', value: params_email }); setRecordStatusToInProgress(ticket_id); // Trigger the submit function. $('#submitter').trigger('click'); } else { send_to = send_to.concat(send_toll_to); console.log("Final send " + send_to); // If there are no attachments, it's faster to directly use nlapiSendEmail() from the client script. email.send({ author: userId, body: email_body, recipients: send_to, subject: email_subject, //attachments: emailAttach, bcc: bcc, cc: cc, }) // 112209 is from MailPlus Team var selector_number = currRec.getValue({ fieldId: 'custpage_selector_number' }); var selector_type = currRec.getValue({ fieldId: 'custpage_selector_type' }); setRecordStatusToInProgress(ticket_id); // Reload the page var params = { ticket_id: parseInt(ticket_id), selector_number: selector_number, selector_type: selector_type, }; params = JSON.stringify(params); var output = url.resolveScript({ deploymentId: 'customdeploy_sl_ticketing_escalate', scriptId: 'customscript_sl_ticketing_escalate', }) var upload_url = baseURL + output + '&custparam_params=' + params; window.open(upload_url, "_self", "height=750,width=650,modal=yes,alwaysRaised=yes"); } } else { return false; } } function saveRecord(context) { return true; } function isNullorEmpty(strVal) { return (strVal == null || strVal == '' || strVal == 'null' || strVal == undefined || strVal == 'undefined' || strVal == '- None -'); } return { pageInit: pageInit, saveRecord: saveRecord, }; } );
/** * REST API for Search Employee Email * * @NApiVersion 2.x * @NScriptType Restlet * @author trungpv <trung@lexor.com> */ define(['N/search'], function(search) { /** * GET * @param {*} context */ function getAction(context) { var result = {}; result.success = false; try { const validation = doValidation([context.keyword], ['keyword'], 'GET'); if (validation.length === 0) { var searchPayload = search.create({ type: search.Type.EMPLOYEE, filters: [['isinactive', search.Operator.IS, 'F']], columns: ['email', 'firstname', 'middlename', 'lastname'] }); var employeeSearch = searchPayload.run().getRange({ start: 0, end: 1000 }); employeeArr = []; for (var index = 0; index < employeeSearch.length; index++) { var item = employeeSearch[index]; employeeArr.push({ name: getName( item.getValue('firstname'), item.getValue('middlename'), item.getValue('lastname') ), email: item.getValue('email') }); } result.count = employeeArr.length; result.data = employeeArr; result.success = true; result.message = 'Success!'; } else { result.message = 'Something went wrong with your params.'; result.errors = validation; } } catch (err) { result.message = err.message; } return result; } /** HEPPER FUNCTIONS **/ /** * Convert Name * @param {*} firstname * @param {*} middlename * @param {*} lastname */ function getName(firstname, middlename, lastname) { var name = ''; name += firstname !== '' ? firstname : ''; name += middlename !== '' ? ' ' + middlename : ''; name += lastname !== '' ? ' ' + lastname : ''; return name; } /** * Validation params * @param {*} args * @param {*} argNames * @param {*} methodName */ function doValidation(args, argNames, methodName) { const result = []; for (var i = 0; i < args.length; i++) { if (!args[i] && args[i] !== 0) { result.push('Missing a required argument: [' + argNames[i] + '] for method: ' + methodName); } } return result; } /** * Export Events */ var exports = {}; exports.get = getAction; return exports; });
838
[{"tag": "EMAIL", "value": "trung@lexor.com", "start": 109, "end": 124}]
true
1
/** * REST API for Search Employee Email * * @NApiVersion 2.x * @NScriptType Restlet * @author trungpv <dycjh@example.com> */ define(['N/search'], function(search) { /** * GET * @param {*} context */ function getAction(context) { var result = {}; result.success = false; try { const validation = doValidation([context.keyword], ['keyword'], 'GET'); if (validation.length === 0) { var searchPayload = search.create({ type: search.Type.EMPLOYEE, filters: [['isinactive', search.Operator.IS, 'F']], columns: ['email', 'firstname', 'middlename', 'lastname'] }); var employeeSearch = searchPayload.run().getRange({ start: 0, end: 1000 }); employeeArr = []; for (var index = 0; index < employeeSearch.length; index++) { var item = employeeSearch[index]; employeeArr.push({ name: getName( item.getValue('firstname'), item.getValue('middlename'), item.getValue('lastname') ), email: item.getValue('email') }); } result.count = employeeArr.length; result.data = employeeArr; result.success = true; result.message = 'Success!'; } else { result.message = 'Something went wrong with your params.'; result.errors = validation; } } catch (err) { result.message = err.message; } return result; } /** HEPPER FUNCTIONS **/ /** * Convert Name * @param {*} firstname * @param {*} middlename * @param {*} lastname */ function getName(firstname, middlename, lastname) { var name = ''; name += firstname !== '' ? firstname : ''; name += middlename !== '' ? ' ' + middlename : ''; name += lastname !== '' ? ' ' + lastname : ''; return name; } /** * Validation params * @param {*} args * @param {*} argNames * @param {*} methodName */ function doValidation(args, argNames, methodName) { const result = []; for (var i = 0; i < args.length; i++) { if (!args[i] && args[i] !== 0) { result.push('Missing a required argument: [' + argNames[i] + '] for method: ' + methodName); } } return result; } /** * Export Events */ var exports = {}; exports.get = getAction; return exports; });
true
/** * REST API for Search Employee Email * * @NApiVersion 2.x * @NScriptType Restlet * @author trungpv <PI:EMAIL:dycjh@example.comEND_PI> */ define(['N/search'], function(search) { /** * GET * @param {*} context */ function getAction(context) { var result = {}; result.success = false; try { const validation = doValidation([context.keyword], ['keyword'], 'GET'); if (validation.length === 0) { var searchPayload = search.create({ type: search.Type.EMPLOYEE, filters: [['isinactive', search.Operator.IS, 'F']], columns: ['email', 'firstname', 'middlename', 'lastname'] }); var employeeSearch = searchPayload.run().getRange({ start: 0, end: 1000 }); employeeArr = []; for (var index = 0; index < employeeSearch.length; index++) { var item = employeeSearch[index]; employeeArr.push({ name: getName( item.getValue('firstname'), item.getValue('middlename'), item.getValue('lastname') ), email: item.getValue('email') }); } result.count = employeeArr.length; result.data = employeeArr; result.success = true; result.message = 'Success!'; } else { result.message = 'Something went wrong with your params.'; result.errors = validation; } } catch (err) { result.message = err.message; } return result; } /** HEPPER FUNCTIONS **/ /** * Convert Name * @param {*} firstname * @param {*} middlename * @param {*} lastname */ function getName(firstname, middlename, lastname) { var name = ''; name += firstname !== '' ? firstname : ''; name += middlename !== '' ? ' ' + middlename : ''; name += lastname !== '' ? ' ' + lastname : ''; return name; } /** * Validation params * @param {*} args * @param {*} argNames * @param {*} methodName */ function doValidation(args, argNames, methodName) { const result = []; for (var i = 0; i < args.length; i++) { if (!args[i] && args[i] !== 0) { result.push('Missing a required argument: [' + argNames[i] + '] for method: ' + methodName); } } return result; } /** * Export Events */ var exports = {}; exports.get = getAction; return exports; });
/** *@NApiVersion 2.x *@NScriptType ScheduledScript */ define(['N/render','N/search', 'N/record', 'N/email', 'N/runtime','N/file'], function(render, search, record, email, runtime, file){ function executebrokerbinemail(context){ try { var MainLine = "Part Number" + ',' + "Manufacturer" + ',' + "Condition" + ',' + "Price" + "," + "Quantity" + "," + "Description"; var BrokerBinSearch = search.load({ //id: 'customsearch377987' id: 'customsearch379593' }); var searchid = 0; var j = 0; do { var searchResults = BrokerBinSearch.run().getRange(searchid, searchid + 1000); if (searchResults != null && searchResults != '' && searchResults != undefined) { log.debug('search', '--> ' + searchResults.length); for (var Trans in searchResults) { var result = searchResults[Trans]; var columnLen = result.columns.length; var PartNumber = ''; var Manufacturer = ''; var Condition = ''; var Quantity = ''; var Description = ''; var Price = ''; for (var t = 0; t < columnLen; t++) { var column = result.columns[t]; var LabelName = column.label; var fieldName = column.name; var value = result.getValue(column); var text = result.getText(column); if (LabelName == 'Part Number') { PartNumber = value } if (LabelName == 'Manufacturer') { Manufacturer = value } if (LabelName == 'Condition') { Condition = value } if (LabelName == 'Price') { Price = value } if (LabelName == 'Quantity') { Quantity = value } if (LabelName == 'Description') { Description = value } } if (PartNumber != '' && PartNumber != null && PartNumber != undefined) { //desc = desc.replace(/\r?\n|\r/g, ' '); PartNumber = PartNumber.replace(/,/g, ''); PartNumber = PartNumber.replace(/\r\n/g, ''); PartNumber = PartNumber.replace(/,/g, ''); PartNumber = PartNumber.replace(/β„’/g, '&trade;'); PartNumber = PartNumber.replace(/"/g, '&Prime;'); } else { PartNumber = ''; } if (Manufacturer != '' && Manufacturer != null && Manufacturer != undefined) { //desc = desc.replace(/\r?\n|\r/g, ' '); Manufacturer = Manufacturer.replace(/,/g, ''); Manufacturer = Manufacturer.replace(/\r\n/g, ''); Manufacturer = Manufacturer.replace(/,/g, ''); Manufacturer = Manufacturer.replace(/β„’/g, '&trade;'); Manufacturer = Manufacturer.replace(/"/g, '&Prime;'); } else { Manufacturer = ''; } if (Description != '' && Description != null && Description != undefined) { //desc = desc.replace(/\r?\n|\r/g, ' '); Description = Description.replace(/,/g, ''); Description = Description.replace(/\r\n/g, ''); Description = Description.replace(/,/g, ''); Description = Description.replace(/β„’/g, '&trade;'); Description = Description.replace(/"/g, '&Prime;'); } else { Description = ''; } LineItems = PartNumber + ',' + Manufacturer + ',' + Condition + ',' + Price + ',' + Quantity + ',' + Description; MainLine = MainLine + "\n" + LineItems; searchid++; } } } while (searchResults.length >= 1000); var NewFile = file.create({ name: 'BrokerBin.csv', fileType: file.Type.CSV, contents: MainLine, }); //folder: '#' // Folder ID where the file should be saved in the File Cabinet email.send({ author: 1708326, recipients: "fbaert@telquestintl.com", subject: 'BrokerBin Inventory Update', body: 'BrokerBin Inventory Update', attachments: [NewFile], }); log.debug('Email Send','Email Send'); } catch (err) { log.debug('error', '--> ' + err); } } return { execute: executebrokerbinemail }; });
1,105
[{"tag": "EMAIL", "value": "fbaert@telquestintl.com", "start": 3955, "end": 3978}]
true
1
/** *@NApiVersion 2.x *@NScriptType ScheduledScript */ define(['N/render','N/search', 'N/record', 'N/email', 'N/runtime','N/file'], function(render, search, record, email, runtime, file){ function executebrokerbinemail(context){ try { var MainLine = "Part Number" + ',' + "Manufacturer" + ',' + "Condition" + ',' + "Price" + "," + "Quantity" + "," + "Description"; var BrokerBinSearch = search.load({ //id: 'customsearch377987' id: 'customsearch379593' }); var searchid = 0; var j = 0; do { var searchResults = BrokerBinSearch.run().getRange(searchid, searchid + 1000); if (searchResults != null && searchResults != '' && searchResults != undefined) { log.debug('search', '--> ' + searchResults.length); for (var Trans in searchResults) { var result = searchResults[Trans]; var columnLen = result.columns.length; var PartNumber = ''; var Manufacturer = ''; var Condition = ''; var Quantity = ''; var Description = ''; var Price = ''; for (var t = 0; t < columnLen; t++) { var column = result.columns[t]; var LabelName = column.label; var fieldName = column.name; var value = result.getValue(column); var text = result.getText(column); if (LabelName == 'Part Number') { PartNumber = value } if (LabelName == 'Manufacturer') { Manufacturer = value } if (LabelName == 'Condition') { Condition = value } if (LabelName == 'Price') { Price = value } if (LabelName == 'Quantity') { Quantity = value } if (LabelName == 'Description') { Description = value } } if (PartNumber != '' && PartNumber != null && PartNumber != undefined) { //desc = desc.replace(/\r?\n|\r/g, ' '); PartNumber = PartNumber.replace(/,/g, ''); PartNumber = PartNumber.replace(/\r\n/g, ''); PartNumber = PartNumber.replace(/,/g, ''); PartNumber = PartNumber.replace(/β„’/g, '&trade;'); PartNumber = PartNumber.replace(/"/g, '&Prime;'); } else { PartNumber = ''; } if (Manufacturer != '' && Manufacturer != null && Manufacturer != undefined) { //desc = desc.replace(/\r?\n|\r/g, ' '); Manufacturer = Manufacturer.replace(/,/g, ''); Manufacturer = Manufacturer.replace(/\r\n/g, ''); Manufacturer = Manufacturer.replace(/,/g, ''); Manufacturer = Manufacturer.replace(/β„’/g, '&trade;'); Manufacturer = Manufacturer.replace(/"/g, '&Prime;'); } else { Manufacturer = ''; } if (Description != '' && Description != null && Description != undefined) { //desc = desc.replace(/\r?\n|\r/g, ' '); Description = Description.replace(/,/g, ''); Description = Description.replace(/\r\n/g, ''); Description = Description.replace(/,/g, ''); Description = Description.replace(/β„’/g, '&trade;'); Description = Description.replace(/"/g, '&Prime;'); } else { Description = ''; } LineItems = PartNumber + ',' + Manufacturer + ',' + Condition + ',' + Price + ',' + Quantity + ',' + Description; MainLine = MainLine + "\n" + LineItems; searchid++; } } } while (searchResults.length >= 1000); var NewFile = file.create({ name: 'BrokerBin.csv', fileType: file.Type.CSV, contents: MainLine, }); //folder: '#' // Folder ID where the file should be saved in the File Cabinet email.send({ author: 1708326, recipients: "upchh@example.com", subject: 'BrokerBin Inventory Update', body: 'BrokerBin Inventory Update', attachments: [NewFile], }); log.debug('Email Send','Email Send'); } catch (err) { log.debug('error', '--> ' + err); } } return { execute: executebrokerbinemail }; });
true
/** *@NApiVersion 2.x *@NScriptType ScheduledScript */ define(['N/render','N/search', 'N/record', 'N/email', 'N/runtime','N/file'], function(render, search, record, email, runtime, file){ function executebrokerbinemail(context){ try { var MainLine = "Part Number" + ',' + "Manufacturer" + ',' + "Condition" + ',' + "Price" + "," + "Quantity" + "," + "Description"; var BrokerBinSearch = search.load({ //id: 'customsearch377987' id: 'customsearch379593' }); var searchid = 0; var j = 0; do { var searchResults = BrokerBinSearch.run().getRange(searchid, searchid + 1000); if (searchResults != null && searchResults != '' && searchResults != undefined) { log.debug('search', '--> ' + searchResults.length); for (var Trans in searchResults) { var result = searchResults[Trans]; var columnLen = result.columns.length; var PartNumber = ''; var Manufacturer = ''; var Condition = ''; var Quantity = ''; var Description = ''; var Price = ''; for (var t = 0; t < columnLen; t++) { var column = result.columns[t]; var LabelName = column.label; var fieldName = column.name; var value = result.getValue(column); var text = result.getText(column); if (LabelName == 'Part Number') { PartNumber = value } if (LabelName == 'Manufacturer') { Manufacturer = value } if (LabelName == 'Condition') { Condition = value } if (LabelName == 'Price') { Price = value } if (LabelName == 'Quantity') { Quantity = value } if (LabelName == 'Description') { Description = value } } if (PartNumber != '' && PartNumber != null && PartNumber != undefined) { //desc = desc.replace(/\r?\n|\r/g, ' '); PartNumber = PartNumber.replace(/,/g, ''); PartNumber = PartNumber.replace(/\r\n/g, ''); PartNumber = PartNumber.replace(/,/g, ''); PartNumber = PartNumber.replace(/β„’/g, '&trade;'); PartNumber = PartNumber.replace(/"/g, '&Prime;'); } else { PartNumber = ''; } if (Manufacturer != '' && Manufacturer != null && Manufacturer != undefined) { //desc = desc.replace(/\r?\n|\r/g, ' '); Manufacturer = Manufacturer.replace(/,/g, ''); Manufacturer = Manufacturer.replace(/\r\n/g, ''); Manufacturer = Manufacturer.replace(/,/g, ''); Manufacturer = Manufacturer.replace(/β„’/g, '&trade;'); Manufacturer = Manufacturer.replace(/"/g, '&Prime;'); } else { Manufacturer = ''; } if (Description != '' && Description != null && Description != undefined) { //desc = desc.replace(/\r?\n|\r/g, ' '); Description = Description.replace(/,/g, ''); Description = Description.replace(/\r\n/g, ''); Description = Description.replace(/,/g, ''); Description = Description.replace(/β„’/g, '&trade;'); Description = Description.replace(/"/g, '&Prime;'); } else { Description = ''; } LineItems = PartNumber + ',' + Manufacturer + ',' + Condition + ',' + Price + ',' + Quantity + ',' + Description; MainLine = MainLine + "\n" + LineItems; searchid++; } } } while (searchResults.length >= 1000); var NewFile = file.create({ name: 'BrokerBin.csv', fileType: file.Type.CSV, contents: MainLine, }); //folder: '#' // Folder ID where the file should be saved in the File Cabinet email.send({ author: 1708326, recipients: "PI:EMAIL:upchh@example.comEND_PI", subject: 'BrokerBin Inventory Update', body: 'BrokerBin Inventory Update', attachments: [NewFile], }); log.debug('Email Send','Email Send'); } catch (err) { log.debug('error', '--> ' + err); } } return { execute: executebrokerbinemail }; });
/** * items.update.productionDepartment.js * @description Set Production Department from value of Departments * @module clv/items/update/productionDepartment * @NApiVersion 2.0 * @NScriptType MassUpdateScript * @author Miquel Brazil <miquel@leprechaunpromotions.com> */ define(['N/record', 'N/https'], function (record, https) { function setProductionDepartment (params) { var response = https.get({ url: 'https://api.runscope.com/radar/cad38ca4-1af2-4a1b-8131-dbed57e6fe1e/trigger?runscope_environment=db174fb2-fbfd-4972-9f9d-9c42dd5a75c3' }); log.debug({ title: 'Blazemeter Response', details: response }); var item = record.load({ id: params.id, type: params.type }); https.post({ url:'https://api.runscope.com/radar/inbound/68ee6308-0f26-410d-88d3-3966f7c344f1', body: item }); } return { each: setProductionDepartment } });
355
[{"tag": "EMAIL", "value": "miquel@leprechaunpromotions.com", "start": 240, "end": 271}]
true
1
/** * items.update.productionDepartment.js * @description Set Production Department from value of Departments * @module clv/items/update/productionDepartment * @NApiVersion 2.0 * @NScriptType MassUpdateScript * @author Miquel Brazil <efpyi@example.com> */ define(['N/record', 'N/https'], function (record, https) { function setProductionDepartment (params) { var response = https.get({ url: 'https://api.runscope.com/radar/cad38ca4-1af2-4a1b-8131-dbed57e6fe1e/trigger?runscope_environment=db174fb2-fbfd-4972-9f9d-9c42dd5a75c3' }); log.debug({ title: 'Blazemeter Response', details: response }); var item = record.load({ id: params.id, type: params.type }); https.post({ url:'https://api.runscope.com/radar/inbound/68ee6308-0f26-410d-88d3-3966f7c344f1', body: item }); } return { each: setProductionDepartment } });
true
/** * items.update.productionDepartment.js * @description Set Production Department from value of Departments * @module clv/items/update/productionDepartment * @NApiVersion 2.0 * @NScriptType MassUpdateScript * @author Miquel Brazil <PI:EMAIL:efpyi@example.comEND_PI> */ define(['N/record', 'N/https'], function (record, https) { function setProductionDepartment (params) { var response = https.get({ url: 'https://api.runscope.com/radar/cad38ca4-1af2-4a1b-8131-dbed57e6fe1e/trigger?runscope_environment=db174fb2-fbfd-4972-9f9d-9c42dd5a75c3' }); log.debug({ title: 'Blazemeter Response', details: response }); var item = record.load({ id: params.id, type: params.type }); https.post({ url:'https://api.runscope.com/radar/inbound/68ee6308-0f26-410d-88d3-3966f7c344f1', body: item }); } return { each: setProductionDepartment } });
/** * * @NApiVersion 2.0 * @NScriptType ClientScript * * Description: Client script that habndles all the validations and calculations of the review page. * @Last Modified by: Sruti Desai * */ define(['N/error', 'N/runtime', 'N/search', 'N/url', 'N/record', 'N/format', 'N/email', 'N/currentRecord'], function(error, runtime, search, url, record, format, email, currentRecord) { var baseURL = 'https://1048144.app.netsuite.com'; if (runtime.envType == "SANDBOX") { baseURL = 'https://1048144-sb3.app.netsuite.com'; } var role = runtime.getCurrentUser().role; var zee = 0; var ctx = runtime.getCurrentScript(); var deleted_service_ids = []; var deleted_job_ids = []; if (role == 1000) { //Franchisee zee = ctx.getCurrentUser(); } else if (role == 3) { //Administrator zee = 6; //test } else if (role == 1032) { // System Support zee = 425904; //test-AR } var global_customer; var global_locked = null; var admin_fees_log = false; /** * On page initialisation- collapse the App Qty fields and the Invoiceable Qty fields */ function pageInit() { var currentScript = currentRecord.get(); $(window).load(function() { // Animate loader off screen $(".se-pre-con").fadeOut("slow");; }); $("#NS_MENU_ID0-item0").css("background-color", "#CFE0CE"); $("#NS_MENU_ID0-item0 a").css("background-color", "#CFE0CE"); $("#body").css("background-color", "#CFE0CE"); $(document).ready(function() { $('[data-toggle="tooltip"]').tooltip(); }); $('.col_collapse_appqty').hide(); $('.header_collapse').hide(); $('.discount_collpase_appqty').hide(); $('.singleline_collpase_appqty').hide(); $('.total_collapse_appqty').hide(); $('.monthlytotal_collapse_appqty').hide(); $('.invoicetotalheader_collpase_appqty').hide(); $('.invoiceable_qty_collpase').hide(); $('.package_name_row').attr('colspan', 6); $('.header_invoiceable_qty_collpase').attr('colspan', 1); global_customer = currentScript.getValue({ fieldId: 'customer_id' }); var start_date = GetFormattedDate(currentScript.getValue({ fieldId: 'start_date' }) ); var end_date = GetFormattedDate(currentScript.getValue({ fieldId: 'end_date' }) ); $('.start_date').val(start_date); $('.end_date').val(end_date); admin_fees_log = currentScript.getValue({ fieldId: 'admin_fees_log' }); global_locked = currentScript.getValue({ fieldId: 'locked' }); document.getElementById('tdbody_reviewed').style = 'background-color: #125ab2 !important;color: white;'; if (global_locked == 'yes') { document.getElementById('tr_submitter').style.display = 'none'; document.getElementById('tdbody_reviewed').style.display = 'none'; $('.admin_fees_on').prop('disabled', true); $('.admin_fees_off').prop('disabled', true); $('.invoiceable_qty').prop('disabled', function(i, v) { return !v; }); $('.admin_fees_rate').prop('disabled', function(i, v) { return !v; }); $('.admin_fees_qty').prop('disabled', function(i, v) { return !v; }); $('.job_description').prop('disabled', function(i, v) { return !v; }); $('.single_job_description').prop('disabled', function(i, v) { return !v; }); $('.add_services').prop('disabled', function(i, v) { return !v; }); $('.fixed_discount_value').prop('disabled', function(i, v) { return !v; }); $('.fixed_discount_qty').prop('disabled', function(i, v) { return !v; }); $('.total_package_value').prop('disabled', function(i, v) { return !v; }); $('.customer_po').prop('disabled', function(i, v) { return !v; }); } var result = finalise_date(currentScript.getValue({ fieldId: 'start_date' })); // $(document).on('click', '.instruction_button', function(e) { // console.log("abc"); // $('.table_start').css("padding-top", "300px"); // $('.instruction_button').hide(); // }); $('.collapse').on('shown.bs.collapse', function() { $('.table_start').css("padding-top", "250px"); }) $('.collapse').on('hide.bs.collapse', function() { $('.table_start').css("padding-top", "0px"); }) $('#exampleModal').on('show.bs.modal', function(event) { var button = $(event).relatedTarget // Button that triggered the modal var recipient = button.data('whatever') // Extract info from data-* attributes // If necessary, you could initiate an AJAX request here (and then do the updating in a callback). // Update the modal's content. We'll use jQuery here, but you could use a data binding library or other methods instead. var modal = $(this) modal.find('.modal-title').text('New message to ' + recipient) modal.find('.modal-body input').val(recipient) }); $(document).ready(function() { $(".modal_display").click(function() { var link = $(this).data("whatever"); // console.log(link); $('.modal .modal-header').html('<div class="form-group"><h4><label class="control-label" for="inputError1">Information</label></h4></div>'); $('.modal .modal-body').html(""); $('.modal .modal-body').html(link); $('.modal .modal-footer').html('<button type="button" class="btn btn-default" data-dismiss="modal">Close</button>'); $('.modal').modal("show"); }); }); /** * [description] - On click of the '+', open up the App Qty fields */ $(document).on('click', '.collapse_appqty', function(e) { $('.col_collapse_appqty').show(); $('.header_collapse').show(); $('.discount_collpase_appqty').show(); $('.singleline_collpase_appqty').show(); $('.total_collapse_appqty').show(); $('.monthlytotal_collapse_appqty').show(); $('.invoicetotalheader_collpase_appqty').show(); $('.package_name_row').attr('colspan', 12); $('.admin_fees_collpase').attr('colspan', 5); // $('.collapse_appqty').removeClass('glyphicon-plus'); // $('.collapse_appqty').addClass('glyphicon-minus'); $('.collapse_appqty').addClass('invoiceableqty_collapse'); }); /** * [description] - On click of the '+' for the second time, show the invoiceable qty fields */ $(document).on('click', '.invoiceableqty_collapse', function(e) { $('.invoiceable_qty_collpase').show(); $('.invoiceableqty_collapse').hide(); // $('.package_name_row').attr('colspan',11); $('.header_invoiceable_qty_collpase').attr('colspan', 3); $('.admin_fees_collpase').attr('colspan', 7); }); /** * [description] - On click of the '-', collapse all the App Qty and Invoiceable Qty fields */ $(document).on('click', '.collapse_all', function(e) { $('.col_collapse_appqty').hide(); $('.collapse_appqty').show(); $('.invoiceable_qty_collpase').show(); $('.invoiceableqty_collapse').show(); $('.header_collapse').hide(); $('.discount_collpase_appqty').hide(); $('.singleline_collpase_appqty').hide(); $('.total_collapse_appqty').hide(); $('.monthlytotal_collapse_appqty').hide(); $('.invoicetotalheader_collpase_appqty').hide(); $('.invoiceable_qty_collpase').hide(); $('.package_name_row').attr('colspan', 6); $('.admin_fees_collpase').attr('colspan', 0); $('.header_invoiceable_qty_collpase').attr('colspan', 1); $('.collapse_appqty').removeClass('invoiceableqty_collapse'); }); //DO CALCULATIONS IF THE DISCUNT QTY IN THE DISCOUNT ROW IS CHANGED $(document).on('blur', '.discount_qty', function(e) { var discount_value = $(this).closest('tr').find('.discount_value').val(); var discount_qty = $(this).val(); var attr_fixed = $(this).attr('package-fixed'); var attr_packageid = $(this).attr('data-packageid'); var old_total_discount_value = $(this).closest('tr').find('.total_discount_value').val(); var old_total_value = $(this).closest('tr').next('tr').find('.total_package_value').val(); var package_value = $(this).closest('tr').next('tr').find('.package_value').val(); var discount_type = $(this).closest('tr').find('.discount_type').val(); var total_package = 0; var package_invoiceable_qty_elem = document.getElementsByClassName("package_invoiceable_qty"); var package_netsuite_qty_elem = document.getElementsByClassName("package_netsuite_qty"); var package_app_qty_elem = document.getElementsByClassName("package_app_qty"); var service_total_value_elem = document.getElementsByClassName("service_total_value"); var app_qty = []; for (var i = 0; i < package_app_qty_elem.length; ++i) { app_qty.push(parseInt(package_app_qty_elem[i].value)); } var max = Math.max.apply(null, app_qty); //CHECKING THE MAX QTY OF ALL THE APP QTY AND IF THE DISCOUNT QTY IS LESS THAN THE MAX APP QTY, THE DISCOUNT QTY IS CHANGED TO THE MAX APP QTY if (discount_qty < max) { discount_qty = max; $(this).val(max); } //ADJUST THE QTYS OF THE TOTAL INVOICEABLE QTY FOR ALL SERVICES FOR THAT PACKAGE for (var i = 0; i < package_invoiceable_qty_elem.length; ++i) { if (package_invoiceable_qty_elem[i].getAttribute("data-packageid") == attr_packageid) { var initial_changed_qty = package_invoiceable_qty_elem[i].value; var initial_load_qty = package_invoiceable_qty_elem[i].getAttribute("data-oldqty"); var netsuite_qty = package_netsuite_qty_elem[i].value; var app_qty = package_app_qty_elem[i].value; var rate = package_invoiceable_qty_elem[i].getAttribute("data-rate"); var total_inv_qty = parseFloat(app_qty) + parseFloat(netsuite_qty); if (discount_qty >= 0) { if (discount_qty == 0) { //IF DISCOUNT QTY ENTERED IS 0 if (app_qty > 0) { alert('Cannot reduce quantity below ' + app_qty); $(this).val(app_qty); return false; } else { package_netsuite_qty_elem[i].setAttribute("value", discount_qty); discount_qty = parseFloat(discount_qty) + parseFloat(app_qty); package_invoiceable_qty_elem[i].setAttribute("value", discount_qty); } } else { package_invoiceable_qty_elem[i].setAttribute("value", discount_qty); if (total_inv_qty != discount_qty) { var new_netsuite_qty = parseFloat(discount_qty) - parseFloat(total_inv_qty); new_netsuite_qty = parseFloat(netsuite_qty) + new_netsuite_qty; package_netsuite_qty_elem[i].setAttribute("value", new_netsuite_qty); } } // package_app_qty_elem[i].setAttribute("value", new_app_qty); var total_rate = updateServiceAmount(parseFloat(rate), parseFloat(discount_qty)); service_total_value_elem[i].setAttribute("value", roundTwoDec(total_rate)); total_package += total_rate; } else { alert('Wrong Quantity entered'); return false; } } } $(this).closest('tr').next('tr').find('.package_value').val(total_package); //CALCULATIONS FOR THE PACKAGE DISCOUNT VALUE BASED ON THE DISCOUNT TYPE if (discount_type == 1) { var total_discount_value = (parseFloat(discount_qty) * parseFloat(discount_value)); var new_total_value = parseFloat(total_package) - total_discount_value; } else { var total_discount_value = ((parseFloat(discount_value) / 100) * parseFloat(total_package)); var new_total_value = parseFloat(total_package) - total_discount_value; } //UPDATE THE TOTAL DISCOUNT VALUE AND THE TOTAL PACKAGE VALUE $(this).closest('tr').find('.total_discount_value').val(roundTwoDec(total_discount_value)); $(this).closest('tr').next('tr').next('tr').find('.total_package_value').val(roundTwoDec(new_total_value)); $(this).closest('tr').next('tr').next('tr').find('.total_package_value').focus(); //UPDATE THE INVOICE TOTAL BASED ON THE CHANGE updateTotal(); }); //ON CHANGE OF THE INVOICEABLE QTY FOR THE SERVICES AND EXTRAS SECTION $(document).on('blur', '.invoiceable_qty', function(e) { var invoiceable_qty = $(this).val(); if (isNullorEmpty(invoiceable_qty)) { invoiceable_qty = 0; $(this).val(0); } var old_qty = $(this).attr('data-oldqty'); var rate = $(this).attr('data-rate'); var app_qty = $(this).closest('tr').find('.app_qty').val(); var netsuite_qty = $(this).closest('tr').find('.package_netsuite_qty').val(); var total_inv_qty = parseFloat(app_qty) + parseFloat(netsuite_qty); if (invoiceable_qty >= 0) { if (invoiceable_qty == 0) { if (app_qty > 0) { alert('Cannot reduce quantity below ' + app_qty + '. \nTo reduce the quantity, please click on the App Jobs and set \"DO YOU WANT TO INVOICE JOB GROUP??\" to \"No\"'); $(this).val(app_qty); $(this).closest('tr').find('.package_netsuite_qty').val(0); var total_rate = updateServiceAmount(parseFloat(rate), parseFloat(app_qty)); $(this).closest('tr').find('.service_total_value').val(roundTwoDec(total_rate)); $(this).closest('tr').find('.service_total_value').focus(); $(this).closest('tr').find('.service_total').val((total_rate)); return false; } else { var new_netsuite_qty = parseFloat(invoiceable_qty); $(this).closest('tr').find('.package_netsuite_qty').val(new_netsuite_qty); var total_rate = updateServiceAmount(parseFloat(rate), parseFloat(invoiceable_qty)); $(this).closest('tr').find('.service_total_value').val(roundTwoDec(total_rate)); $(this).closest('tr').find('.service_total_value').focus(); $(this).closest('tr').find('.service_total').val((total_rate)); } } else { if (parseInt(app_qty) > invoiceable_qty) { alert('Cannot reduce quantity below ' + app_qty + '. \nTo reduce the quantity, please click on the App Jobs and set \"DO YOU WANT TO INVOICE JOB GROUP??\" to \"No\"'); $(this).val(app_qty); $(this).closest('tr').find('.package_netsuite_qty').val(0); var total_rate = updateServiceAmount(parseFloat(rate), parseFloat(app_qty)); $(this).closest('tr').find('.service_total_value').val(roundTwoDec(total_rate)); $(this).closest('tr').find('.service_total_value').focus(); $(this).closest('tr').find('.service_total').val((total_rate)); return false; } if (parseInt(total_inv_qty) != invoiceable_qty) { var new_netsuite_qty = parseFloat(invoiceable_qty) - parseFloat(total_inv_qty); new_netsuite_qty = parseFloat(netsuite_qty) + new_netsuite_qty; $(this).closest('tr').find('.package_netsuite_qty').val(new_netsuite_qty); var total_rate = updateServiceAmount(parseFloat(rate), parseFloat(invoiceable_qty)); $(this).closest('tr').find('.service_total_value').val((total_rate).toFixed(2)); $(this).closest('tr').find('.service_total_value').focus(); $(this).closest('tr').find('.service_total').val((total_rate).toFixed(2)); // $(this).closest('tr').find('.service_total_value').val((total_rate)); } } } else { alert('Cannot reduce quantity below ' + app_qty + '. \nTo reduce the quantity, please click on the App Jobs and set \"DO YOU WANT TO INVOICE JOB GROUP??\" to \"No\"'); $(this).val(app_qty); return false; } updateTotal(); }); $(document).on('blur', '.total_package_value', function(e) { var total_value = $(this).val(); // var old_total_discount_value = $(this).closest('tr').find('.total_discount_value').val(); var package_value = $(this).closest('tr').find('.package_value').val(); // var discount_type = $(this).closest('tr').find('.discount_type').val(); var discount_qty = $(this).closest('tr').prev('tr').prev('tr').find('.discount_qty').val(); var total_discount = parseFloat(total_value) - parseFloat(package_value); var per_discount = total_discount / parseFloat(discount_qty); $(this).closest('tr').prev('tr').prev('tr').find('.discount_value').val(roundTwoDec(parseFloat(per_discount))); $(this).closest('tr').prev('tr').prev('tr').find('.total_discount_value').val(roundTwoDec(parseFloat(total_discount))); }); //ON CHANGE OF THE FIXED RATE QTY $(document).on('blur', '.fixed_discount_qty', function(e) { var discount_value = $(this).closest('tr').find('.fixed_discount_value').val(); var discount_qty = $(this).val(); var attr_fixed = $(this).attr('package-fixed'); var attr_packageid = $(this).attr('data-packageid'); var old_total_discount_value = $(this).closest('tr').find('.total_discount_value').val(); var old_total_value = $(this).closest('tr').next('tr').find('.total_package_value').val(); var package_value = $(this).closest('tr').next('tr').find('.package_value').val(); var discount_type = $(this).closest('tr').find('.discount_type').val(); var total_package = 0; var package_invoiceable_qty_elem = document.getElementsByClassName("package_invoiceable_qty"); var package_netsuite_qty_elem = document.getElementsByClassName("package_netsuite_qty"); var package_app_qty_elem = document.getElementsByClassName("package_app_qty"); var service_total_value_elem = document.getElementsByClassName("service_total_value"); var app_qty = []; for (var i = 0; i < package_app_qty_elem.length; ++i) { var packageID = package_invoiceable_qty_elem[i].getAttribute("data-packageid"); if (attr_packageid == packageID) { app_qty.push(parseInt(package_app_qty_elem[i].value)); } } // console.log(app_qty); // return false; var max = Math.max.apply(null, app_qty); if (discount_qty < max) { discount_qty = max; $(this).val(max); } for (var i = 0; i < package_invoiceable_qty_elem.length; ++i) { if (package_invoiceable_qty_elem[i].getAttribute("data-packageid") == attr_packageid) { var initial_changed_qty = package_invoiceable_qty_elem[i].value; var initial_load_qty = package_invoiceable_qty_elem[i].getAttribute("data-oldqty"); var netsuite_qty = package_netsuite_qty_elem[i].value; var app_qty = package_app_qty_elem[i].value; var rate = package_invoiceable_qty_elem[i].getAttribute("data-rate"); var service_cat = package_netsuite_qty_elem[i].getAttribute("data-servicecat"); var total_inv_qty = parseFloat(app_qty) + parseFloat(netsuite_qty); if (service_cat == 1) { if (discount_qty >= 0) { if (discount_qty == 0) { if (app_qty > 0) { alert('Cannot reduce quantity below ' + app_qty); $(this).val(app_qty); return false; } else { package_netsuite_qty_elem[i].setAttribute("value", discount_qty); discount_qty = parseFloat(discount_qty) + parseFloat(app_qty); package_invoiceable_qty_elem[i].setAttribute("value", discount_qty); } } else { package_invoiceable_qty_elem[i].setAttribute("value", discount_qty); if (total_inv_qty != discount_qty) { var new_netsuite_qty = parseFloat(discount_qty) - parseFloat(total_inv_qty); new_netsuite_qty = parseFloat(netsuite_qty) + new_netsuite_qty; package_netsuite_qty_elem[i].setAttribute("value", new_netsuite_qty); } } // package_app_qty_elem[i].setAttribute("value", new_app_qty); var total_rate = updateServiceAmount(parseFloat(rate), parseFloat(discount_qty)); service_total_value_elem[i].setAttribute("value", total_rate); total_package += total_rate; } else { alert('Wrong Quantity entered'); return false; } } else { var total_rate = updateServiceAmount(parseFloat(rate), parseFloat(initial_changed_qty)); total_package += total_rate; } } } $(this).closest('tr').find('.package_value').val(total_package); var package_value = parseFloat(total_package); var total_discount_value = (parseFloat(discount_qty) * parseFloat(discount_value)); $(this).closest('tr').find('.total_package_value').val(roundTwoDec(total_discount_value)); $(this).closest('tr').find('.total_package_value').focus(); var new_discount = parseFloat(total_discount_value) - parseFloat(package_value); if (new_discount < 0) { $(this).closest('tr').prev('tr').prev('tr').find('.discount_dollar').addClass('has-error'); $(this).closest('tr').prev('tr').prev('tr').find('.discount_dollar').removeClass('has-success'); } else { $(this).closest('tr').prev('tr').prev('tr').find('.discount_dollar').addClass('has-success'); $(this).closest('tr').prev('tr').prev('tr').find('.discount_dollar').removeClass('has-error'); } $(this).closest('tr').prev('tr').find('.total_discount_value').val(roundTwoDec(new_discount)); var discount_rate = new_discount / parseFloat(discount_qty); $(this).closest('tr').prev('tr').prev('tr').find('.total_discount_value').val(roundTwoDec(new_discount)); $(this).closest('tr').prev('tr').prev('tr').find('.discount_value').val(roundTwoDec((new_discount / parseFloat(discount_qty)))); $(this).closest('tr').prev('tr').prev('tr').find('.discount_qty').val(discount_qty); updateTotal(); }); //GET THE OLD VALUE OF THE DISCOUNT VALUE. $(document).on('focusin', '.discount_value', function() { $(this).data('oldval', $(this).val()); }); //ON CHANGE OF THE DISCOUNT VALUE $(document).on('blur', '.discount_value', function(e) { var discount_qty = $(this).closest('tr').find('.discount_qty').val(); var discount_value = $(this).val(); var old_discount_value = $(this).data('oldval'); var attr_fixed = $(this).attr('package-fixed'); var attr_packageid = $(this).attr('data-packageid'); var old_total_discount_value = $(this).closest('tr').find('.total_discount_value').val(); var old_total_value = $(this).closest('tr').next('tr').next('tr').find('.total_package_value').val(); var package_value = $(this).closest('tr').next('tr').next('tr').find('.package_value').val(); var discount_type = $(this).closest('tr').find('.discount_type').val(); //IF THE DISCOUNT TYPE IS $ if (discount_type == 1) { var total_discount_value = (parseFloat(discount_qty) * parseFloat(discount_value)); //TO CHECK THE TOTAL DISCOUNT VALUE IS NOT GREATER THAN THE TOTAL PACKAGE OF ALL THE SERVICES if (total_discount_value < package_value) { $(this).closest('tr').find('.total_discount_value').val(roundTwoDec(total_discount_value)); } else { alert('Total value is greater than the total of the package'); $(this).val(old_discount_value); var total_discount_value = (parseFloat(discount_qty) * parseFloat(old_discount_value)); $(this).closest('tr').find('.total_package_value').val(roundTwoDec(total_discount_value)); $(this).closest('tr').find('.total_package_value').focus(); return false; } var new_total_value = parseFloat(package_value) - total_discount_value; } else { //IF DISCOUNT TYPE IS % var total_discount_value = ((parseFloat(discount_value) / 100) * parseFloat(package_value)); if (total_discount_value < package_value) { $(this).closest('tr').find('.total_discount_value').val(roundTwoDec(total_discount_value)); } else { alert('Total value is greater than the total of the package'); $(this).val(old_discount_value); var total_discount_value = (parseFloat(discount_qty) * parseFloat(old_discount_value)); $(this).closest('tr').find('.total_discount_value').val(roundTwoDec(total_discount_value)); return false; } var new_total_value = parseFloat(package_value) - total_discount_value; } // $(this).closest('tr').find('.total_discount_value').val(-(total_discount_value)); $(this).closest('tr').next('tr').next('tr').find('.total_package_value').val(roundTwoDec(new_total_value)); $(this).closest('tr').next('tr').next('tr').find('.total_package_value').focus(); updateTotal(); }); //GET THE OLD FIXED RATE $(document).on('focusin', '.fixed_discount_value', function() { $(this).data('oldval', $(this).val()); }); //ON CHANGE OF THE FIXED RATE VALUE $(document).on('blur', '.fixed_discount_value', function(e) { var discount_qty = $(this).closest('tr').find('.fixed_discount_qty').val(); var discount_value = $(this).val(); var old_discount_value = $(this).data('oldval'); var attr_fixed = $(this).attr('package-fixed'); var attr_packageid = $(this).attr('data-packageid'); var old_total_discount_value = $(this).closest('tr').find('.total_discount_value').val(); var old_total_value = $(this).closest('tr').next('tr').find('.total_package_value').val(); var package_value = $(this).closest('tr').next('tr').find('.package_value').val(); var discount_type = $(this).closest('tr').find('.discount_type').val(); var package_value = $(this).closest('tr').find('.package_value').val(); var total_discount_value = (parseFloat(discount_qty) * parseFloat(discount_value)); if (total_discount_value < package_value) { $(this).closest('tr').find('.total_package_value').val(roundTwoDec(total_discount_value)); $(this).closest('tr').find('.total_package_value').focus(); } else { alert('Total value is greater than the total of the package'); $(this).val(old_discount_value); var total_discount_value = (parseFloat(discount_qty) * parseFloat(old_discount_value)); $(this).closest('tr').find('.total_package_value').val(roundTwoDec(total_discount_value)); $(this).closest('tr').find('.total_package_value').focus(); return false; } var new_discount = parseFloat(total_discount_value) - parseFloat(package_value); if (new_discount < 0) { $(this).closest('tr').prev('tr').prev('tr').find('.discount_dollar').addClass('has-error'); $(this).closest('tr').prev('tr').prev('tr').find('.discount_dollar').removeClass('has-success'); } else { $(this).closest('tr').prev('tr').prev('tr').find('.discount_dollar').addClass('has-success'); $(this).closest('tr').prev('tr').prev('tr').find('.discount_dollar').removeClass('has-error'); } $(this).closest('tr').prev('tr').prev('tr').find('.total_discount_value').val(roundTwoDec(new_discount)); $(this).closest('tr').prev('tr').prev('tr').find('.discount_value').val(roundTwoDec(new_discount / parseFloat(discount_qty))); $(this).closest('tr').prev('tr').prev('tr').find('.discount_qty').val(roundTwoDec(discount_qty)); updateTotal(); }); //ON CHANGE OF THE DISCOUNT TYPE, HIDE OR SHOW THE DISCOUNT QTY $(document).on("change", ".discount_type", function(e) { var discount_type = $(this).val(); //IF THE DISCOUNT TYPE IS $, SHOW THE DISCOUNT QTY if (discount_type == 1) { $(this).closest('tr').find('.discount_qty').show(); } else { $(this).closest('tr').find('.discount_qty').hide(); } }); //ON CHANGE OF THE INVOICE SINGLE LINE $(document).on("change", ".invoice_single_line", function(e) { var packageid; $('option:selected', this).each(function() { packageid = ($(this).data('packageid')); }); var value = $(this).val(); var package_invoiceable_qty_elem = document.getElementsByClassName("package_invoiceable_qty"); var job_desciption_elem = document.getElementsByClassName("job_description"); for (var i = 0; i < package_invoiceable_qty_elem.length; ++i) { if (job_desciption_elem[i].getAttribute("data-packageid") == packageid) { //IF INVOICE SINGLE LINE IS SET TO YES, HIDE THE INVOICE DETAILS FIELDS FOR EACH OF THE SERVICES PRESENT IN THE PACKAGE if (value == 1) { $(this).closest('tr').find('.single_job_description').show(); job_desciption_elem[i].setAttribute('style', "display: none"); job_desciption_elem[i].setAttribute('value', ""); job_desciption_elem[i].setAttribute('data-singleline', "1"); } else { //HIDE THE INVOICE DETAIL SHOWN IN THE INVOICE DETAIL ROW AND SHOW THE INVOICE DETAIL FIELDS FOR EACH OF THE SERVICES PRESENT IN THE PACKAGE $(this).closest('tr').find('.single_job_description').hide(); $(this).closest('tr').find('.single_job_description').val(null); job_desciption_elem[i].setAttribute('style', "display: display"); job_desciption_elem[i].setAttribute('data-singleline', "2"); } } } if (value == 1) { $(this).closest('tr').find('.single_line_hidden').val("1"); } else { $(this).closest('tr').find('.single_line_hidden').val("2"); } }); $('.add_services').click(function() { console.log("clicked services btn"); var serv_param = $(this).attr("fnparam"); addService(serv_param); }); /** * [description] - To show the Invoice Preview modal */ $(document).on('click', '.preview_row', function(event) { console.log("prev clicked"); var currentScript = currentRecord.get(); var discount_type_elem = document.getElementsByClassName("discount_type"); var discount_value_elem = document.getElementsByClassName("discount_value"); var discount_qty_elem = document.getElementsByClassName("discount_qty"); var total_discount_elem = document.getElementsByClassName("total_discount_value"); var invoice_single_line_elem = document.getElementsByClassName("invoice_single_line"); var total_package_value = document.getElementsByClassName("total_package_value"); var single_line_hidden = document.getElementsByClassName("single_line_hidden"); var fixed_discount_value = document.getElementsByClassName("fixed_discount_value"); var job_description_elem = document.getElementsByClassName("job_description"); var single_job_description_elem = document.getElementsByClassName("single_job_description"); var admin_fees_rate_elem = document.getElementsByClassName("admin_fees_rate"); var admin_fees_qty_elem = document.getElementsByClassName("admin_fees_qty"); var gst_value = 0.1; var total_gst = 1.1; var sum_total = 0.0; var sum_gst = 0.0; var sum_gross_total = 0.0; var package_details = []; var invoice_line_items = []; var invoice_line_qty = []; var invoice_line_rate = []; var invoice_line_gst = []; preview_html = '<table class="table table-responsive table-striped"><thead><tr class="info"><th><b>ITEM</b></th><th><b>DETAILS</b></th><th style="text-align: right;"><b>QTY</b></th><th style="text-align: right;"><b>RATE</b></th><th style="text-align: right;"><b>TOTAL</b></th><th style="text-align: right;"><b>GST</b></th><th style="text-align: right;"><b>GROSS TOTAL</b></th></thead><tbody>'; if (!isNullorEmpty(total_discount_elem)) { for (var i = 0; i < total_discount_elem.length; ++i) { var job_id = total_discount_elem[i].getAttribute('data-netsuitejob'); var default_description_value = single_job_description_elem[i].getAttribute('default-value'); var description_value = single_job_description_elem[i].value; var default_total_discount_value = total_discount_elem[i].getAttribute('default-value'); var single_line_hidden_default = single_line_hidden[i].getAttribute('default-singleline'); var total_discount_value = total_discount_elem[i].value; var single_line_hidden_value = single_line_hidden[i].value; if (isNullorEmpty(single_line_hidden_value)) { single_line_hidden_value = single_line_hidden_default; } var package_id = null; var discount_period = null; if (total_discount_elem[i].hasAttribute("data-package")) { package_id = total_discount_elem[i].getAttribute('data-package'); package_record = record.load({ type: 'customrecord_service_package', id: package_id, }); discount_period = package_record.getValue({ fieldId: 'custrecord_service_package_disc_period' }); package_ns_item_id = package_record.getValue({ fieldId: 'custrecord_service_package_ns_item' }); if (isNullorEmpty(package_ns_item_id)) { package_ns_item = 'Fixed Charges'; package_ns_item_id = 66; } else { package_ns_item = search.lookupFields({ type: 'item', id: package_ns_item_id, columns: 'itemid' }); } package_details[package_id] = []; if (discount_period == 3) { invoice_line_items[invoice_line_items.length] = package_ns_item_id; invoice_line_qty[invoice_line_qty.length] = 1; invoice_line_rate[invoice_line_rate.length] = total_package_value[i].value; invoice_line_gst[invoice_line_gst.length] = 7; package_details[package_id][0] = "1"; package_details[package_id][1] = "1"; package_details[package_id][2] = total_package_value[i].value; preview_html += '<tr><td>' + package_ns_item + '</td><td>' + description_value + '</td><td style="text-align: right;">1</td><td style="text-align: right;">$' + parseFloat(total_package_value[i].value).toFixed(2) + '</td><td style="text-align: right;">$' + parseFloat(total_package_value[i].value).toFixed(2) + '</td><td style="text-align: right;">$' + parseFloat(total_package_value[i].value * gst_value).toFixed(2) + '</td style="text-align: right;"><td style="text-align: right;">$' + parseFloat(total_package_value[i].value * total_gst).toFixed(2) + '</td></tr>'; sum_total = parseFloat(sum_total + (total_package_value[i].value)); sum_gst = parseFloat(sum_gst + (total_package_value[i].value * gst_value)); sum_gross_total = parseFloat(sum_gross_total + (total_package_value[i].value * total_gst)); } else { if (single_line_hidden_value == 1) { invoice_line_items[invoice_line_items.length] = package_ns_item_id; invoice_line_qty[invoice_line_qty.length] = discount_qty_elem[i].value; invoice_line_rate[invoice_line_rate.length] = fixed_discount_value[i].value; invoice_line_gst[invoice_line_gst.length] = 7; package_details[package_id][0] = "1"; package_details[package_id][1] = discount_qty_elem[i].value; package_details[package_id][2] = fixed_discount_value[i].value; preview_html += '<tr><td>' + package_ns_item + '</td><td>' + description_value + '</td><td style="text-align: right;">' + discount_qty_elem[i].value + '</td><td style="text-align: right;">$' + parseFloat(fixed_discount_value[i].value).toFixed(2) + '</td><td style="text-align: right;">$' + parseFloat(fixed_discount_value[i].value * discount_qty_elem[i].value).toFixed(2) + '</td><td style="text-align: right;">$' + parseFloat(discount_qty_elem[i].value * fixed_discount_value[i].value * gst_value).toFixed(2) + '</td><td style="text-align: right;">$' + parseFloat(discount_qty_elem[i].value * fixed_discount_value[i].value * total_gst).toFixed(2) + '</td></tr>'; sum_total = parseFloat(sum_total + (fixed_discount_value[i].value * discount_qty_elem[i].value)); sum_gst = parseFloat(sum_gst + (discount_qty_elem[i].value * fixed_discount_value[i].value * gst_value)); sum_gross_total = parseFloat(sum_gross_total + (discount_qty_elem[i].value * fixed_discount_value[i].value * total_gst)); } else { package_details[package_id][0] = "2"; package_details[package_id][1] = discount_qty_elem[i].value; package_details[package_id][2] = discount_value_elem[i].value; } } } } } var package_invoiceable_qty_elem = document.getElementsByClassName("package_invoiceable_qty"); var old_package_id = null; for (var i = 0; i < package_invoiceable_qty_elem.length; ++i) { var qty = package_invoiceable_qty_elem[i].value; var rate = package_invoiceable_qty_elem[i].getAttribute("data-rate"); var item_name = package_invoiceable_qty_elem[i].getAttribute("data-nsitem"); var item_id = package_invoiceable_qty_elem[i].getAttribute("data-nsitemid"); var gst = package_invoiceable_qty_elem[i].getAttribute("data-gst"); // console.log(item_name); if (package_invoiceable_qty_elem[i].hasAttribute("data-packageid")) { var package_id = package_invoiceable_qty_elem[i].getAttribute("data-packageid"); if ((old_package_id == package_id && isNullorEmpty(old_package_id)) || old_package_id == package_id) { if (package_details[old_package_id] != undefined) { if (package_details[old_package_id][0] != "1") { // console.log('first if inside 2'); if (gst == 'Yes' || gst == '- None -') { invoice_line_items[invoice_line_items.length] = item_id; invoice_line_qty[invoice_line_qty.length] = qty; invoice_line_rate[invoice_line_rate.length] = rate; invoice_line_gst[invoice_line_gst.length] = 7; preview_html += '<tr><td>' + item_name + '</td><td>' + job_description_elem[i].value + '</td><td style="text-align: right;">' + qty + '</td><td style="text-align: right;">$' + parseFloat(rate).toFixed(2) + '</td><td style="text-align: right;">$' + parseFloat(qty * rate).toFixed(2) + '</td><td style="text-align: right;">$' + parseFloat(qty * rate * gst_value).toFixed(2) + '</td><td style="text-align: right;">$' + parseFloat(qty * rate * total_gst).toFixed(2) + '</td></tr>'; sum_total = parseFloat(sum_total + (qty * rate)); sum_gst = parseFloat(sum_gst + (qty * rate * gst_value)); sum_gross_total = parseFloat(sum_gross_total + (qty * rate * total_gst)); } else { invoice_line_items[invoice_line_items.length] = item_id; invoice_line_qty[invoice_line_qty.length] = qty; invoice_line_rate[invoice_line_rate.length] = rate; invoice_line_gst[invoice_line_gst.length] = 9; preview_html += '<tr><td>' + item_name + '</td><td>' + job_description_elem[i].value + '</td><td style="text-align: right;">' + qty + '</td><td style="text-align: right;">$' + parseFloat(rate).toFixed(2) + '</td><td style="text-align: right;">$' + parseFloat(qty * rate).toFixed(2) + '</td><td style="text-align: right;"></td><td style="text-align: right;">$' + parseFloat(qty * rate).toFixed(2) + '</td></tr>'; sum_total = parseFloat(sum_total + (qty * rate)); sum_gross_total = parseFloat(sum_gross_total + (qty * rate)); } } } } else { if (package_details[old_package_id] != undefined) { if (package_details[old_package_id][0] != "1") { var font_color = ''; if (package_details[old_package_id][2] < 0) { font_color = 'color:red;'; } invoice_line_items[invoice_line_items.length] = 97; invoice_line_qty[invoice_line_qty.length] = package_details[old_package_id][1]; invoice_line_rate[invoice_line_rate.length] = package_details[old_package_id][2]; invoice_line_gst[invoice_line_gst.length] = 7; preview_html += '<tr style="' + font_color + '"><td>Discount</td><td></td><td style="text-align: right;">' + package_details[old_package_id][1] + '</td><td style="text-align: right;">$' + parseFloat(package_details[old_package_id][2]).toFixed(2) + '</td><td style="text-align: right;">$' + parseFloat(package_details[old_package_id][1] * package_details[old_package_id][2]).toFixed(2) + '</td><td style="text-align: right;">$' + parseFloat(package_details[old_package_id][1] * package_details[old_package_id][2] * gst_value).toFixed(2) + '</td><td style="text-align: right;">$' + parseFloat(package_details[old_package_id][1] * package_details[old_package_id][2] * total_gst).toFixed(2) + '</td></tr>'; sum_total = parseFloat(sum_total + (package_details[old_package_id][1] * package_details[old_package_id][2])); sum_gst = parseFloat(sum_gst + (package_details[old_package_id][1] * package_details[old_package_id][2] * gst_value)); sum_gross_total = parseFloat(sum_gross_total + (package_details[old_package_id][1] * package_details[old_package_id][2] * total_gst)); } if (package_details[package_id][0] != "1") { // console.log('second if inside 3'); if (gst == 'Yes' || gst == '- None -') { invoice_line_items[invoice_line_items.length] = item_id; invoice_line_qty[invoice_line_qty.length] = qty; invoice_line_rate[invoice_line_rate.length] = rate; invoice_line_gst[invoice_line_gst.length] = 7; preview_html += '<tr><td>' + item_name + '</td><td>' + job_description_elem[i].value + '</td><td style="text-align: right;">' + qty + '</td><td style="text-align: right;">$' + parseFloat(rate).toFixed(2) + '</td><td style="text-align: right;">$' + parseFloat(qty * rate).toFixed(2) + '</td><td style="text-align: right;">$' + parseFloat(qty * rate * gst_value).toFixed(2) + '</td><td style="text-align: right;">$' + parseFloat(qty * rate * total_gst).toFixed(2) + '</td></tr>'; sum_total = parseFloat(sum_total + (qty * rate)); sum_gst = parseFloat(sum_gst + (qty * rate * gst_value)); sum_gross_total = parseFloat(sum_gross_total + (qty * rate * total_gst)); } else { invoice_line_items[invoice_line_items.length] = item_id; invoice_line_qty[invoice_line_qty.length] = qty; invoice_line_rate[invoice_line_rate.length] = rate; invoice_line_gst[invoice_line_gst.length] = 9; preview_html += '<tr><td>' + item_name + '</td><td>' + job_description_elem[i].value + '</td><td style="text-align: right;">' + qty + '</td><td style="text-align: right;">$' + parseFloat(rate).toFixed(2) + '</td><td style="text-align: right;">$' + parseFloat(qty * rate).toFixed(2) + '</td><td style="text-align: right;"></td><td style="text-align: right;">$' + parseFloat(qty * rate).toFixed(2) + '</td></tr>'; sum_total = parseFloat(sum_total + (qty * rate)); sum_gross_total = parseFloat(sum_gross_total + (qty * rate)); } } } } old_package_id = package_invoiceable_qty_elem[i].getAttribute("data-packageid"); } } if (!isNullorEmpty(old_package_id)) { if (package_details[old_package_id] != undefined) { if (package_details[old_package_id][0] != "1") { var font_color = ''; if (package_details[old_package_id][2] < 0) { font_color = 'color:red;'; } invoice_line_items[invoice_line_items.length] = 97; invoice_line_qty[invoice_line_qty.length] = package_details[old_package_id][1]; invoice_line_rate[invoice_line_rate.length] = package_details[old_package_id][2]; invoice_line_gst[invoice_line_gst.length] = 7; preview_html += '<tr style="' + font_color + '"><td>Discount</td><td></td><td style="text-align: right;">' + package_details[old_package_id][1] + '</td><td style="text-align: right;">$' + parseFloat(package_details[old_package_id][2]).toFixed(2) + '</td><td style="text-align: right;">$' + parseFloat(package_details[old_package_id][1] * package_details[old_package_id][2]).toFixed(2) + '</td><td style="text-align: right;">$' + parseFloat(package_details[old_package_id][1] * package_details[old_package_id][2] * gst_value).toFixed(2) + '</td><td style="text-align: right;">$' + parseFloat(package_details[old_package_id][1] * package_details[old_package_id][2] * total_gst).toFixed(2) + '</td></tr>'; sum_total = parseFloat(sum_total + (package_details[old_package_id][1] * package_details[old_package_id][2])); sum_gst = parseFloat(sum_gst + (package_details[old_package_id][1] * package_details[old_package_id][2] * gst_value)); sum_gross_total = parseFloat(sum_gross_total + (package_details[old_package_id][1] * package_details[old_package_id][2] * total_gst)); } } } var invoiceable_qty_elem = document.getElementsByClassName("invoiceable_qty"); var job_description_preview_elem = document.getElementsByClassName("job_description_preview"); for (var i = 0; i < invoiceable_qty_elem.length; ++i) { // var service_id = invoiceable_qty_elem[i].getAttribute("data-serviceid"); // var service_record = record.load({ type: 'customrecord_service', id: service_id }); // var item_id = service_record.getValue({ fieldId: 'custrecord_service_ns_item' }); // var item_name = search.lookupFields({ type: 'item', id: item_id, columns: 'itemid') }; var qty = invoiceable_qty_elem[i].value; var rate = invoiceable_qty_elem[i].getAttribute("data-rate"); var item_name = invoiceable_qty_elem[i].getAttribute("data-nsitem"); var item_id = invoiceable_qty_elem[i].getAttribute("data-nsitemid"); var gst = invoiceable_qty_elem[i].getAttribute("data-gst"); if (qty != 0) { var font_color = ''; if (item_id == 97) { font_color = 'color:red;'; } if (gst == 'Yes' || gst == '- None -') { invoice_line_items[invoice_line_items.length] = item_id; invoice_line_qty[invoice_line_qty.length] = qty; invoice_line_rate[invoice_line_rate.length] = rate; invoice_line_gst[invoice_line_gst.length] = 7; preview_html += '<tr style="' + font_color + '"><td>' + item_name + '</td><td>' + job_description_preview_elem[i].value + '</td><td style="text-align: right;">' + qty + '</td><td style="text-align: right;">$' + parseFloat(rate).toFixed(2) + '</td><td style="text-align: right;">$' + parseFloat(qty * rate).toFixed(2) + '</td><td style="text-align: right;">$' + parseFloat(qty * rate * gst_value).toFixed(2) + '</td><td style="text-align: right;">$' + parseFloat(qty * rate * total_gst).toFixed(2) + '</td></tr>'; sum_total = parseFloat(sum_total + (qty * rate)); sum_gst = parseFloat(sum_gst + (qty * rate * gst_value)); sum_gross_total = parseFloat(sum_gross_total + (qty * rate * total_gst)); } else { invoice_line_items[invoice_line_items.length] = item_id; invoice_line_qty[invoice_line_qty.length] = qty; invoice_line_rate[invoice_line_rate.length] = rate; invoice_line_gst[invoice_line_gst.length] = 9; preview_html += '<tr><td>' + item_name + '</td><td>' + job_description_preview_elem[i].value + '</td><td style="text-align: right;">' + qty + '</td><td style="text-align: right;">$' + parseFloat(rate).toFixed(2) + '</td><td style="text-align: right;">$' + parseFloat(qty * rate).toFixed(2) + '</td><td style="text-align: right;"></td><td style="text-align: right;">$' + parseFloat(qty * rate).toFixed(2) + '</td></tr>'; sum_total = parseFloat(sum_total + (qty * rate)); sum_gross_total = parseFloat(sum_gross_total + (qty * rate)); } } } if (admin_fees_log == true || admin_fees_log == 'true') { if (!isNullorEmpty(admin_fees_rate_elem)) { for (var i = 0; i < admin_fees_rate_elem.length; i++) { var rate = admin_fees_rate_elem[i].value; var qty = admin_fees_qty_elem[i].value; if (rate > 0 && qty > 0) { invoice_line_items[invoice_line_items.length] = 8729; invoice_line_qty[invoice_line_qty.length] = qty; invoice_line_rate[invoice_line_rate.length] = rate; invoice_line_gst[invoice_line_gst.length] = 7; preview_html += '<tr><td>Account Admin Fee</td><td></td><td style="text-align: right;">' + qty + '</td><td style="text-align: right;">$' + parseFloat(rate).toFixed(2) + '</td><td style="text-align: right;">$' + parseFloat(qty * rate).toFixed(2) + '</td><td style="text-align: right;">$' + parseFloat(qty * rate * gst_value).toFixed(2) + '</td><td style="text-align: right;">$' + parseFloat(qty * rate * total_gst).toFixed(2) + '</td></tr>'; sum_total = parseFloat(sum_total + (qty * rate)); sum_gst = parseFloat(sum_gst + (qty * rate * gst_value)); sum_gross_total = parseFloat(sum_gross_total + (qty * rate * total_gst)); } } } } var searchedJobsExtras = search.load({ id: 'customsearch_job_invoicing_summary', type: 'customrecord_job' }); searchedJobsExtras.filters.push(search.createFilter({ name: 'custrecord_job_date_inv_finalised', operator: search.Operator.ISEMPTY })); if (!isNullorEmpty(currentScript.getValue({ fieldId: 'start_date' })) && !isNullorEmpty(currentScript.getValue({ fieldId: 'end_date' }))) { searchedJobsExtras.filters.push(search.createFilter({ name: 'custrecord_job_date_scheduled', operator: search.Operator.ONORAFTER, values: currentScript.getValue({ fieldId: 'start_date' }) })); searchedJobsExtras.filters.push(search.createFilter({ name: 'custrecord_job_date_scheduled', operator: search.Operator.ONORBEFORE, values: currentScript.getValue({ fieldId: 'end_date' }) })); } var resultSetExtras = searchedJobsExtras.run(); var next_customer = null; var result = resultSetExtras.getRange({ start: 0, end: 1 }) if (!isNullorEmpty(result) && result.length != 0) { next_customer = result[0].getValue({ name: 'internalid', join: 'CUSTRECORD_JOB_CUSTOMER', summary: search.Summary.GROUP }); } preview_html += '<tr class="success" style="font-weight: bold;font-size: small;"><td>TOTAL</td><td></td><td></td><td></td><td style="text-align: right;">$' + parseFloat($('.total_value').val()).toFixed(2) + '</td><td style="text-align: right;">$' + sum_gst.toFixed(2) + '</td><td style="text-align: right;">$' + sum_gross_total.toFixed(2) + '</td></tr></tbody></table>'; var footer_html = ''; var result = finalise_date(currentScript.getValue({ fieldId: 'start_date' })); if ((global_locked == 'yes' || result == false) && role == 1000 && zee != 6 && zee != 425904) { footer_html = '<span class="col-sm-10"><b>"Create Custom Invoice"</b> functionality will only be available on or after the last day of the month</span><button type="button" class="btn btn-default" data-dismiss="modal">Close</button>'; } else { footer_html = '<a href="https://1048144.app.netsuite.com/app/accounting/transactions/custinvc.nl?compid=1048144&cf=116&entity=' + global_customer + '&itemids=' + invoice_line_items.toString() + '&qty=' + invoice_line_qty.toString() + '&rate=' + invoice_line_rate.toString() + '&gst=' + invoice_line_gst.toString() + '&next_customer=' + next_customer + '&start_date=' + currentScript.getValue({ fieldId: 'start_date' }) + '&end_date=' + currentScript.getValue({ fieldId: 'end_date' }) + '" class="btn btn-primary" value="">Create Custom Invoice</a><button type="button" class="btn btn-default" data-dismiss="modal">Close</button>'; } $('.modal .modal-header').html('<div class="form-group"><h4><label class="control-label" for="inputError1">Invoice Preview</label></h4></div>'); $('.modal .modal-footer').html(footer_html); $('.modal .modal-body').html(""); $('.modal .modal-body').html(preview_html); $('.modal').modal("show"); }); /** * [description] - To update the Admin Fees Total when the rate is changed */ $(document).on('blur', '.admin_fees_rate', function(e) { var admin_fees = $(this).val(); var serviceid = $(this).attr('data-serviceid'); var jobid = $(this).attr('data-jobid'); var old_admin_fees = $(this).attr('data-oldvalue'); if (admin_fees != old_admin_fees) { if (!isNullorEmpty(serviceid)) { deleted_service_ids[deleted_service_ids.length] = serviceid; $(this).attr('data-serviceid', null); if (!isNullorEmpty(jobid)) { deleted_job_ids[deleted_job_ids.length] = jobid; $(this).attr('data-jobid', null); } } var admin_fees_qty = $(this).closest('tr').find('.admin_fees_qty').val(); var admin_fees_total = (parseFloat(admin_fees) * parseFloat(admin_fees_qty)); $(this).closest('tr').find('.admin_fees_total').val(admin_fees_total); updateTotal(); } }); /** * [description] - To update the Admin Fees Total when the qty is changed */ $(document).on('blur', '.admin_fees_qty', function(e) { var admin_fees_qty = $(this).val(); var admin_fees = $(this).closest('tr').find('.admin_fees_rate').val(); var admin_fees_total = (parseFloat(admin_fees) * parseFloat(admin_fees_qty)); $(this).closest('tr').find('.admin_fees_total').val(admin_fees_total); updateTotal(); }); /** * [description] - Css and toggle between the On/Off Button for Admin Fee */ $('.btn-toggle').click(function() { // alert(currentScript.getValue({ fieldId: 'admin_fees_not_applicable' })); if (global_locked != 'yes' && currentScript.getValue({ fieldId: 'admin_fees_not_applicable' }) != '1') { $(this).find('.btn').toggleClass('active'); if ($(this).find('.btn-success').size() > 0) { $(this).find('.btn').toggleClass('btn-success'); } $(this).find('.btn').toggleClass('btn-default'); } return false; }); /** * [description] - To show the Admin Fee Row */ $('.admin_fees_on').click(function() { $('.admin_fees_row').show(); $('.no_extras_class').hide(); var jobid = $('.admin_fees_rate').attr('data-jobid'); var serviceid = $('.admin_fees_rate').attr('data-serviceid'); if (isNullorEmpty(jobid) && isNullorEmpty(serviceid)) { $('.admin_fees_rate').val(9); $('.admin_fees_qty').val(1); $('.admin_fees_total').val(9); } else { var service_old_record = record.load({ type: 'customrecord_service', id: serviceid, }); var admin_fees = parseFloat(service_old_record.getValue({ fieldId: 'custrecord_service_price' })); var admin_fees_qty = 1; if (!isNullorEmpty(jobid)) { var job_old_record = record.load({ type: 'customrecord_job', id: jobid, }); admin_fees_qty = parseFloat(job_old_record.getValue({ fieldId: 'custrecord_job_extras_qty' })); } $('.admin_fees_rate').val(admin_fees); $('.admin_fees_qty').val(admin_fees_qty); $('.admin_fees_total').val((admin_fees * admin_fees_qty)); } admin_fees_log = true; updateTotal(); }); /** * [description] - To hide the Admin Fee Row */ $('.admin_fees_off').click(function() { $('.admin_fees_row').hide(); // $('.admin_fees_rate').val(0); // $('.admin_fees_qty').val(0); var jobid = $('.admin_fees_rate').attr('data-jobid'); var serviceid = $('.admin_fees_rate').attr('data-serviceid'); // $('.admin_fees_total').val(0); admin_fees_log = false; if (!isNullorEmpty(jobid)) { deleted_job_ids[deleted_job_ids.length] = jobid; } if (!isNullorEmpty(serviceid)) { deleted_service_ids[deleted_service_ids.length] = serviceid; } updateTotal(); }); } //ON CLICK OF THE APP COMPELTED QTY function onclick_StatusComplete(internal_id, service_rate, service_id, job_group, status, category, package_id, assign_packge) { //setReviewDate(internal_id); //REVIEW DATE IS SET FOR ALL THE JOBS var currentScript = currentRecord.get(); if (status == null) { var upload_url = baseURL + url.resolveScript({ scriptId: 'customscript_sl_job_page_2', deploymentId: 'customdeploy_job_page_2' }) + '&customer_id=' + internal_id + '&rate=' + service_rate + '&service_id=' + service_id + '&job_group=' + job_group + '&category=' + category + '&package=' + package_id + '&start_date=' + currentScript.getValue({ fieldId: 'start_date' }) + '&end_date=' + currentScript.getValue({ fieldId: 'end_date' }) + '&assign_packge=' + assign_packge + '&locked=' + global_locked + '&sc=' + currentScript.getValue({ fieldId: 'scid' }) + '&zee=' + currentScript.getValue({ fieldId: 'zee_id' }); window.open(upload_url, "_self", "height=750,width=650,modal=yes,alwaysRaised=yes"); } else { var upload_url = baseURL + url.resolveScript({ scriptId: 'customscript_sl_job_page_2', deploymentId: 'customdeploy_job_page_2' }) + '&customer_id=' + internal_id + '&rate=' + service_rate + '&service_id=' + service_id + '&job_group=' + job_group + '&status=' + status + '&category=' + category + '&package=' + package_id + '&start_date=' + currentScript.getValue({ fieldId: 'start_date' }) + '&end_date=' + currentScript.getValue({ fieldId: 'end_date' }) + '&assign_packge=' + assign_packge + '&locked=' + global_locked + '&sc=' + currentScript.getValue({ fieldId: 'scid' }) + '&zee=' + currentScript.getValue({ fieldId: 'zee_id' }); window.open(upload_url, "_self", "height=750,width=650,modal=yes,alwaysRaised=yes"); } } //ON CLICK OF THE APP PARTIALLY COMPLETED QTY function onclick_StatusPartial(internal_id, service_rate, service_id, job_group, status, category, package_id) { var currentScript = currentRecord.get(); //setReviewDate(internal_id); var upload_url = baseURL + url.resolveScript({ scriptId: 'customscript_sl_job_page_2', deploymentId: 'customdeploy_job_page_2' }) + '&customer_id=' + internal_id + '&rate=' + service_rate + '&service_id=' + service_id + '&job_group=' + job_group + '&status=' + status + '&category=' + category + '&package=' + package_id + '&start_date=' + currentScript.getValue({ fieldId: 'start_date' }) + '&end_date=' + currentScript.getValue({ fieldId: 'end_date' }) + '&locked=' + global_locked + '&sc=' + currentScript.getValue({ fieldId: 'scid' }) + '&zee=' + currentScript.getValue({ fieldId: 'zee_id' }); window.open(upload_url, "_self", "height=750,width=650,modal=yes,alwaysRaised=yes"); } //ON CLICK OF THE APP INCOMPLETE QTY function onclick_StatusIncomplete(internal_id, service_rate, service_id, job_group, status, category, package_id) { var currentScript = currentRecord.get(); // setReviewDate(internal_id); var upload_url = baseURL + url.resolveScript({ scriptId: 'customscript_sl_job_page_2', deploymentId: 'customdeploy_job_page_2' }) + '&customer_id=' + internal_id + '&rate=' + service_rate + '&service_id=' + service_id + '&job_group=' + job_group + '&status=' + status + '&category=' + category + '&package=' + package_id + '&start_date=' + currentScript.getValue({ fieldId: 'start_date' }) + '&end_date=' + currentScript.getValue({ fieldId: 'end_date' }) + '&locked=' + global_locked + '&sc=' + currentScript.getValue({ fieldId: 'scid' }) + '&zee=' + currentScript.getValue({ fieldId: 'zee_id' }); window.open(upload_url, "_self", "height=750,width=650,modal=yes,alwaysRaised=yes"); } //ON CLICK OF THE BACK TO SUMMARY BUTTON function onclick_summaryPage() { var currentScript = currentRecord.get(); var upload_url = baseURL + url.resolveScript({ scriptId: 'customscript_sl_summary_page_2', deploymentId: 'customdeploy_summary_page_2' }) + '&start_date=' + currentScript.getValue({ fieldId: 'start_date' }) + '&end_date=' + currentScript.getValue({ fieldId: 'end_date' }) + '&zee=' + currentScript.getValue({ fieldId: 'zee_id' }); window.open(upload_url, "_self", "height=750,width=650,modal=yes,alwaysRaised=yes"); } function onclick_reset() { window.location.href = window.location.href; } //ON CLICK OF ADD SERVICES BUTTON function addService(service_cat) { var currentScript = currentRecord.get(); //setReviewDate(currentScript.getValue({ fieldId: 'customer_id')) }; var upload_url = baseURL + url.resolveScript({ scriptId: 'customscript_sl_add_service_2', deploymentId: 'customdeploy_sl_add_service_2' }) + '&custid=' + currentScript.getValue({ fieldId: 'customer_id' }) + '&unlayered=T&service_cat=' + service_cat + '&start_date=' + currentScript.getValue({ fieldId: 'start_date' }) + '&end_date=' + currentScript.getValue({ fieldId: 'end_date' }) + '&locked=' + global_locked + '&sc=' + currentScript.getValue({ fieldId: 'scid' }) + '&zee=' + currentScript.getValue({ fieldId: 'zee_id' }); window.open(upload_url, "_self", "height=750,width=650,modal=yes,alwaysRaised=yes"); } //SET REVIEW DATE FUNCTION function setReviewDate(internal_id) { var currentScript = currentRecord.get(); var searched_jobs = search.load({ id: 'customsearch_inv_review_jobs_uninv', type: 'customrecord_job' }); searched_jobs.filters.push(search.createFilter({ name: 'custrecord_job_customer', operator: search.Operator.IS, values: internal_id, })); var resultSet = searched_jobs.run(); resultSet.each(function(searchResult) { var job_record = record.load({ type: 'customrecord_job', id: searchResult.getValue('internalid') }); job_record.setValue({ fieldId: 'custrecord_job_date_reviewed', value: getDate() }); job_record.save({ enableSourcing: true, ignoreMandatoryFields: true }) return true; }); return true; } function onclick_AssignPackage(internal_id, service_rate, service_id, job_group, status, category, package_id) { var currentScript = currentRecord.get(); var upload_url = baseURL + url.resolveScript({ scriptId: 'customscript_sl_assign_package_2', deploymentId: 'customdeploy_sl_assign_package_2' }) + '&customer_id=' + internal_id + '&service_id=' + service_id + '&job_group=' + job_group + '&status=' + status + '&rate=' + service_rate + '&category=' + category + '&package=' + package_id + '&start_date=' + currentScript.getValue({ fieldId: 'start_date' }) + '&end_date=' + currentScript.getValue({ fieldId: 'end_date' }); window.open(upload_url, "_self", "height=750,width=650,modal=yes,alwaysRaised=yes"); } function submit_package() { var currentScript = currentRecord.get(); var url = baseURL + url.resolveScript({ scriptId: 'customscript_sl_services_main_page_2', deploymentId: 'customdeploy_sl_services_main_page_2' }) + '&customer_id=' + currentScript.getValue({ fieldId: 'customer_id' }) + '&start_date=' + currentScript.getValue({ fieldId: 'start_date' }) + '&end_date=' + currentScript.getValue({ fieldId: 'end_date' }); window.open(url, "_self", "height=680,width=640,modal=yes,alwaysRaised=yes"); } //FUNCTION TO CALCULATE THE TOTAL INVOICEABLE AMOUNT FOR EACH AND EVERY SERVICE AND EXTRA function updateServiceAmount(rate, qty) { return (rate * qty); } function onclick_review() { var currentScript = currentRecord.get(); currentScript.setValue({ fieldId: 'review_button', value: 'T' }); $('#submitter').trigger('click'); } //ON CLICK OF NEXT CUSTOMER BUTTON function saveRecord(context) { var currentScript = currentRecord.get(); var customer_id = currentScript.getValue({ fieldId: 'customer_id' }); //WS Edit: Get Zee Customer from hidden field in Suitelet var zee_cust = parseInt(currentScript.getValue({ fieldId: 'zee_cust' })); //WS Edit: Can be deferred to Admin Fee section //var customerRec = record.load({ type: 'customer', id: customer_id }); //WS Edit: zee (from global variable) instead of franchisee //var franchisee = customerRec.getValue({ fieldId: 'partner' }); var franchisee = parseInt(zee); /*-----------------Derive CommReg for new Service Creation-----------------*/ var commReg_search = search.load({ id: 'customsearch_service_commreg_assign', type: 'customrecord_commencement_register' }); //WS Edit: filterExpression unsets existing filter commReg_search.filters.push(search.createFilter({ name: 'custrecord_customer', operator: search.Operator.ANYOF, values: customer_id } )); commReg_search.filters.push(search.createFilter({ name: 'custrecord_franchisee', operator: search.Operator.ANYOF, values: franchisee } )); var comm_reg_results = commReg_search.run(); var count_commReg = 0; var commReg = null; comm_reg_results.each(function(searchResult) { count_commReg++; /** * [if description] - Only the latest comm Reg needs to be assigned */ if (count_commReg == 1) { commReg = searchResult.getValue('internalid'); } /** * [if description] - if more than one Comm Reg, error mail is sent */ if (count_commReg > 1) { //WS Comment: Needs error error.create({ message: 'More than 1 Active CommReg', name: 'Customer ID: ' + customer_id, }); return false; } return true; }); /*-----------------NS Qty-----------------*/ //Set the jobs for NS Qty items var package_invoiceable_qty_elem = document.getElementsByClassName("package_netsuite_qty"); var job_description_elem = document.getElementsByClassName("job_description"); var single_job_description_elem = document.getElementsByClassName("single_job_description"); var service_id_array = []; var service_descp_array = []; var extra_service_id = []; var extra_qty = []; var extra_rate = []; var delete_job_id = []; var delete_service_id = []; var new_jobs_service_id = []; var new_jobs_rate = []; var new_jobs_qty = []; var new_jobs_cat = []; var new_jobs_descp = []; var new_jobs_package_id = []; var new_jobs_single_line = []; var new_service_type = []; var new_service_name = []; var new_service_price = []; var new_service_qty = []; var new_service_package_id = []; var new_service_customer = []; var new_service_comm_reg = []; var new_service_discount_type = []; var new_service_single_line = []; /*-----------------NS Qty: Get Field Values from Suitelet-----------------*/ for (var i = 0; i < package_invoiceable_qty_elem.length; ++i) { console.log('saveRecord loop ' + i) var initial_changed_qty = package_invoiceable_qty_elem[i].value; console.log(initial_changed_qty) var initial_load_qty = package_invoiceable_qty_elem[i].getAttribute("data-oldqty"); console.log(initial_load_qty) var service_id = package_invoiceable_qty_elem[i].getAttribute("data-serviceid"); console.log(service_id) var service_rate = package_invoiceable_qty_elem[i].getAttribute("data-rate"); console.log(service_rate) var service_cat = package_invoiceable_qty_elem[i].getAttribute("data-servicecat"); console.log(service_cat) var package = package_invoiceable_qty_elem[i].getAttribute("data-packageid"); console.log(package) var job_id = package_invoiceable_qty_elem[i].getAttribute("data-netsuitejob"); console.log(job_id) var default_ns_qty = package_invoiceable_qty_elem[i].getAttribute("default-value"); console.log(default_ns_qty) var default_description; var default_single_line; var single_line; var description; console.log(job_description_elem[i]) if (!isNullorEmpty(job_description_elem[i])) { if (!isNullorEmpty(job_description_elem[i].value)) { var default_description = job_description_elem[i].getAttribute("default-value"); console.log(default_description) var default_single_line = job_description_elem[i].getAttribute("default-singleline"); console.log(default_single_line) var single_line = job_description_elem[i].getAttribute("data-singleline"); console.log(single_line) service_id_array.push(job_description_elem[i].getAttribute("data-serviceid")); console.log(job_description_elem[i].getAttribute("data-serviceid")) service_descp_array.push(job_description_elem[i].value); description = job_description_elem[i].value; } } // single_line.push(job_description_elem[i].getAttribute("data-singleline")) var jobs_to_create = parseFloat(initial_changed_qty); /*-----------------Package: Identify and Create Jobs-----------------*/ if (description != default_description || default_ns_qty != initial_changed_qty) { if (jobs_to_create > 0 || !isNullorEmpty(description)) { if (service_id != 242 && service_id != 243 && service_id != 1904 && service_id != 241) { if (isNullorEmpty(job_id) || job_id == 'null') { if (zee == zee_cust) { createJobRecord(customer_id, service_id, service_rate, jobs_to_create, description, service_cat, package, single_line, null); } else { new_jobs_service_id[new_jobs_service_id.length] = service_id; new_jobs_rate[new_jobs_rate.length] = service_rate; new_jobs_qty[new_jobs_qty.length] = jobs_to_create; new_jobs_cat[new_jobs_cat.length] = service_cat; new_jobs_descp[new_jobs_descp.length] = description; new_jobs_single_line[new_jobs_single_line.length] = single_line; if (!isNullorEmpty(package)) { new_jobs_package_id[new_jobs_package_id.length] = package; } } } else { updateJobRecord(job_id, null, jobs_to_create, description, null, null, null, null); } } else { extra_service_id[extra_service_id.length] = service_id; extra_qty[extra_qty.length] = jobs_to_create; extra_rate[extra_rate.length] = service_rate; } } else if (jobs_to_create == 0 && isNullorEmpty(description)) { if (!isNullorEmpty(job_id) && job_id != 'null') { delete_job_id[delete_job_id.length] = job_id; // nlapiDeleteRecord('customrecord_job', job_id); } } } } var discount_type_elem = document.getElementsByClassName("discount_type"); var discount_value_elem = document.getElementsByClassName("discount_value"); var discount_qty_elem = document.getElementsByClassName("discount_qty"); var total_discount_elem = document.getElementsByClassName("total_discount_value"); var invoice_single_line_elem = document.getElementsByClassName("invoice_single_line"); var total_package_value = document.getElementsByClassName("total_package_value"); var single_line_hidden = document.getElementsByClassName("single_line_hidden"); var fixed_discount_value = document.getElementsByClassName("fixed_discount_value"); /*-----------------Package: Identify and Create Discount Services + Jobs-----------------*/ if (!isNullorEmpty(total_discount_elem)) { for (var i = 0; i < total_discount_elem.length; ++i) { var job_id = total_discount_elem[i].getAttribute('data-netsuitejob'); var default_description_value = single_job_description_elem[i].getAttribute('default-value'); var description_value = single_job_description_elem[i].value; var default_total_discount_value = total_discount_elem[i].getAttribute('default-value'); var single_line_hidden_default = single_line_hidden[i].getAttribute('default-singleline'); var total_discount_value = total_discount_elem[i].value; var single_line_hidden_value = single_line_hidden[i].value; if (isNullorEmpty(single_line_hidden_value)) { single_line_hidden_value = single_line_hidden_default; } if (isNullorEmpty(job_id) || job_id == 'null') { if (total_discount_elem[i].hasAttribute("data-package")) { var package_id = total_discount_elem[i].getAttribute('data-package'); } var package_record = record.load({ type: 'customrecord_service_package', id: package_id, }); var discount_period = package_record.getValue({ fieldId: 'custrecord_service_package_disc_period' }); if (zee == zee_cust) { var service_price; if (discount_period == 3) { service_price = total_package_value[i].value; } else { if (single_line_hidden_value == 1) { service_price = fixed_discount_value[i].value; } else { service_price = discount_value_elem[i].value; } } // alert(package_id); var service_id = createServiceRecord(17, 'Discount', service_price, customer_id, commReg, package_id); var service_rate; var service_qty; var discount_type; if (discount_period == 3) { service_rate = total_package_value[i].value; service_qty = 1; } else { if (single_line_hidden_value == 1) { service_rate = fixed_discount_value[i].value; } else { service_rate = discount_value_elem[i].value; } service_qty = discount_qty_elem[i].value; if (!isNullorEmpty(discount_type_elem[i])) { if (isNullorEmpty(discount_type_elem[i].getAttribute('data-value'))) { discount_type = null; } else { discount_type = discount_type_elem[i].getAttribute('data-value'); } } } createJobRecord(customer_id, service_id, service_rate, service_qty, description, 2, package_id, invoice_single_line_elem[i].value, discount_type); } else { if (discount_period == 3) { new_service_price[new_service_price.length] = total_package_value[i].value; new_service_qty[new_service_qty.length] = 1; } else { if (single_line_hidden_value == 1) { new_service_price[new_service_price.length] = fixed_discount_value[i].value; } else { new_service_price[new_service_price.length] = discount_value_elem[i].value; } new_service_qty[new_service_qty.length] = discount_qty_elem[i].value; if (!isNullorEmpty(discount_type_elem[i])) { if (isNullorEmpty(discount_type_elem[i].getAttribute('data-value'))) { new_service_discount_type[new_service_discount_type.length] = null; } else { new_service_discount_type[new_service_discount_type.length] = discount_type_elem[i].getAttribute('data-value'); } } } if (!isNullorEmpty(package_id)) { new_service_package_id[new_service_package_id.length] = package_id; } if (!isNullorEmpty(commReg)) { new_service_comm_reg[new_service_comm_reg.length] = commReg; } new_service_customer[new_service_customer.length] = customer_id; new_service_type[new_service_type.length] = 17; new_service_name[new_service_name.length] = 'Discount'; new_service_single_line[new_service_single_line.length] = invoice_single_line_elem[i].value; } } else { var job_new_record = record.load({ type: 'customrecord_job', id: job_id }); var service_id = job_new_record.getValue({ fieldId: 'custrecord_job_service' }); if (total_discount_elem[i].hasAttribute("data-package")) { var package_id = total_discount_elem[i].getAttribute('data-package'); } var package_record = record.load({ type: 'customrecord_service_package', id: package_id }); var discount_period = package_record.getValue({ fieldId: 'custrecord_service_package_disc_period' }); var service_record = record.load({ type: 'customrecord_service', id: service_id }); if (discount_period == 3) { service_record.setValue({ fieldId: 'custrecord_service_price', value: total_package_value[i].value }); } else { if (single_line_hidden_value == 1) { service_record.setValue({ fieldId: 'custrecord_service_price', value: fixed_discount_value[i].value }); } else { service_record.setValue({ fieldId: 'custrecord_service_price', value: discount_value_elem[i].value }); } } if (!isNullorEmpty(package_id)) { service_record.setValue({ fieldId: 'custrecord_service_package', value: package_id }); } service_record.save({ enableSourcing: true, ignoreMandatoryFields: true }); var service_rate; var service_qty; var discount_type; if (discount_period == 3) { service_rate = total_package_value[i].value; service_qty = 1; } else { if (single_line_hidden_value == 1) { service_rate = fixed_discount_value[i].value; } else { service_rate = discount_value_elem[i].value; } service_qty = discount_qty_elem[i].value; if (!isNullorEmpty(discount_type_elem[i])) { if (isNullorEmpty(discount_type_elem[i].getAttribute('data-value'))) { discount_type = null; } else { discount_type = discount_type_elem[i].getAttribute('data-value'); } } } updateJobRecord(job_id, service_rate, service_qty, single_job_description_elem[i].value, null, package_id, invoice_single_line_elem[i].value, discount_type); } } } /*-----------------Admin Fees-----------------*/ //WS Edit: Only allow adjustments on Admin fee to be made by Customer Zee. Other Zee cannot update Admin fee arrangements. if (zee == zee_cust) { var customerRec = record.load({ type: 'customer', id: customer_id }); var admin_fees_rate_elem = document.getElementsByClassName("admin_fees_rate"); var admin_fees_qty_elem = document.getElementsByClassName("admin_fees_qty"); /*-----------------Admin Fees: NO-----------------*/ if (admin_fees_log == false || admin_fees_log == 'false') { if (!isNullorEmpty(deleted_service_ids)) { // alert(deleted_service_ids); for (var i = 0; i < deleted_service_ids.length; i++) { var searchedJobsResult = adminFeesServiceCheck(customer_id, deleted_service_ids[i], deleted_job_ids); if (isNullorEmpty(searchedJobsResult)) { delete_service_id[delete_service_id.length] = deleted_service_ids[i]; } else { if (searchedJobsResult.length == 1) { var service_old_record = record.load({ type: 'customrecord_service', id: deleted_service_ids }[i]); service_old_record.setValue({ fieldId: 'isinactive', value: 'T' }); service_old_record.save({ enableSourcing: true, ignoreMandatoryFields: true }); // delete_service_id[delete_service_id.length] = deleted_service_ids[i]; } } } } if (!isNullorEmpty(deleted_job_ids)) { for (var i = 0; i < deleted_job_ids.length; i++) { delete_job_id[delete_job_id.length] = deleted_job_ids[i]; // nlapiDeleteRecord('customrecord_job', deleted_job_ids[i]); } } $('.admin_fees_rate').val(0); $('.admin_fees_qty').val(0); customerRec.setValue({ fieldId: 'custentity_admin_fees', value: null }); } console.log('Before admin') /*-----------------Admin Fees: YES-----------------*/ /** * To capture the Admin Fee information */ if (admin_fees_log == true || admin_fees_log == 'true') { for (var i = 0; i < admin_fees_rate_elem.length; ++i) { var jobid = (admin_fees_rate_elem[i].getAttribute("data-jobid")); var serviceid = (admin_fees_rate_elem[i].getAttribute("data-serviceid")); var old_admin_fees = admin_fees_rate_elem[i].getAttribute("data-oldvalue"); var admin_fees = admin_fees_rate_elem[i].value; var admin_qty = admin_fees_qty_elem[i].value; if (isNullorEmpty(admin_fees) || admin_fees == 0 || isNullorEmpty(admin_qty) || admin_qty == 0) { customerRec.setValue({ fieldId: 'custentity_admin_fees', value: null }); if (!isNullorEmpty(jobid)) { delete_job_id[delete_job_id.length] = jobid; // nlapiDeleteRecord('customrecord_job', jobid); } if (!isNullorEmpty(serviceid)) { var searchedJobsResult = adminFeesServiceCheck(customer_id, serviceid, delete_job_id); if (isNullorEmpty(searchedJobsResult)) { delete_service_id[delete_service_id.length] = serviceid; } else { if (searchedJobsResult.length == 1) { var service_old_record = record.load({ type: 'customrecord_service', id: serviceid }); service_old_record.setValue({ fieldId: 'isinactive', value: 'T' }); service_old_record.save({ enableSourcing: true, ignoreMandatoryFields: true }); // delete_service_id[delete_service_id.length] = deleted_service_ids[i]; } } } } else { if (!isNullorEmpty(deleted_service_ids)) { for (var i = 0; i < deleted_service_ids.length; i++) { var searchedJobsResult = adminFeesServiceCheck(customer_id, deleted_service_ids[i], deleted_job_ids); if (isNullorEmpty(searchedJobsResult)) { delete_service_id[delete_service_id.length] = deleted_service_ids[i]; } else { if (searchedJobsResult.length == 1) { var service_old_record = record.load({ type: 'customrecord_service', id: deleted_service_ids }[i]); service_old_record.setValue({ fieldId: 'isinactive', value: 'T' }); service_old_record.save({ enableSourcing: true, ignoreMandatoryFields: true }); // delete_service_id[delete_service_id.length] = deleted_service_ids[i]; } } } } if (!isNullorEmpty(deleted_job_ids)) { for (var i = 0; i < deleted_job_ids.length; i++) { delete_job_id[delete_job_id.length] = deleted_job_ids[i]; // nlapiDeleteRecord('customrecord_job', deleted_job_ids[i]); } } if (isNullorEmpty(serviceid)) { //Put code to check if the Admin Fee Service with the Same Price exists or not. If it exists and is Inactive, activate it and update. If no service exists, create a new service var searchedServicesResult = searchAdminFeesService(customer_id, admin_fees); if (isNullorEmpty(searchedServicesResult)) { var service_record = record.create({ type: 'customrecord_service', isDynamic: true, }); service_record.setValue({ fieldId: 'custrecord_service', value: 22 }); service_record.setValue({ fieldId: 'name', value: search.lookupFields({ type: 'customrecord_service_type', id: 22, columns: 'name' }) }); //WS Edit: cannot set franchisee in Client. //service_record.setValue({ fieldId: 'custrecord_service_franchisee', value: zee); service_record.setValue({ fieldId: 'custrecord_service_customer', value: customer_id }); //WS } Edit: Need to deal with null commReg. //service_record.setValue({ fieldId: 'custrecord_service_comm_reg', value: commReg); if (!isNullorEmpty(commReg)) { service_record.setValue({ fieldId: 'custrecord_service_comm_reg', value: commReg }); } } else { if (searchedServicesResult.length == 1) { var service_record = record.load({ type: 'customrecord_service', id: searchedServicesResult[0].getValue('internalid') }); service_record.setValue({ fieldId: 'isinactive', value: 'F' }); } else { //Throw Error } } } else { var service_record = record.load({ type: 'customrecord_service', id: serviceid }); } service_record.setValue({ fieldId: 'custrecord_service_price', value: admin_fees }); var new_service_id = service_record.save({ enableSourcing: true, ignoreMandatoryFields: true }); if (isNullorEmpty(jobid)) { var job_record = record.create({ type: 'customrecord_job', isDynamic: true, }); job_record.setValue({ fieldId: 'custrecord_job_status', value: 3 }); job_record.setValue({ fieldId: 'custrecord_job_invoiceable', value: 1 }); job_record.setValue({ fieldId: 'custrecord_job_date_reviewed', value: getDate() }); job_record.setValue({ fieldId: 'custrecord_job_source', value: 5 }); job_record.setValue({ fieldId: 'custrecord_job_service_category', value: 2 }); job_record.setValue({ fieldId: 'custrecord_job_customer', value: customer_id }); // } job_record.setValue({ fieldId: 'custrecord_job_franchisee', value: zee); } else { var job_record = record.load({ type: 'customrecord_job', id: jobid }); } job_record.setValue({ fieldId: 'custrecord_job_service', value: new_service_id }); job_record.setValue({ fieldId: 'custrecord_job_extras_qty', value: admin_qty }); job_record.setValue({ fieldId: 'custrecord_job_service_price', value: admin_fees}); job_record.setValue({ fieldId: 'custrecord_job_date_scheduled', value: currentScript.getValue({ fieldId: 'end_date' }) }); job_record.save({ enableSourcing: true, ignoreMandatoryFields: true }); customerRec.setValue({ fieldId: 'custentity_admin_fees', value: admin_fees }); } } } console.log('after admin') customerRec.setValue({ fieldId: 'custentity11', value: $('.customer_po').val() }); customerRec.save({ enableSourcing: true, ignoreMandatoryFields: true }); } var extra_service_string = extra_service_id.join(); var extra_qty_string = extra_qty.join(); var extra_rate_string = extra_rate.join(); console.log(delete_job_id); var unique_delete_jobs = removeDuplicateUsingFilter(delete_job_id); var unique_delete_services = removeDuplicateUsingFilter(delete_service_id); console.log(unique_delete_jobs); var delete_job_id_string = unique_delete_jobs.join(); var delete_service_id_string = unique_delete_services.join(); var new_jobs_service_id_string = new_jobs_service_id.join(); var new_jobs_rate_string = new_jobs_rate.join(); var new_jobs_qty_string = new_jobs_qty.join(); var new_jobs_cat_string = new_jobs_cat.join(); var new_jobs_descp_string = new_jobs_descp.join(); var new_jobs_package_id_string = new_jobs_package_id.join(); var new_jobs_single_line_string = new_jobs_single_line.join(); var new_service_type_string = new_service_type.join(); var new_service_name_string = new_service_name.join(); var new_service_price_string = new_service_price.join(); var new_service_qty_string = new_service_qty.join(); var new_service_discount_type_string = new_service_discount_type.join(); var new_service_package_id_string = new_service_package_id.join(); var new_service_customer_string = new_service_customer.join(); var new_service_comm_reg_string = new_service_comm_reg.join(); var new_service_single_line_string = new_service_single_line.join(); // alert(delete_service_id); currentScript.setValue({ fieldId: 'extra_service_string', value: extra_service_string }); currentScript.setValue({ fieldId: 'extra_qty_string', value: extra_qty_string }); currentScript.setValue({ fieldId: 'extra_rate_string', value: extra_rate_string }); currentScript.setValue({ fieldId: 'delete_job_id_string', value: delete_job_id_string }); currentScript.setValue({ fieldId: 'delete_service_id_string', value: delete_service_id_string }); currentScript.setValue({ fieldId: 'new_jobs_service_id_string', value: new_jobs_service_id_string }); currentScript.setValue({ fieldId: 'new_jobs_rate_string', value: new_jobs_rate_string }); currentScript.setValue({ fieldId: 'new_jobs_qty_string', value: new_jobs_qty_string }); currentScript.setValue({ fieldId: 'new_jobs_cat_string', value: new_jobs_cat_string }); currentScript.setValue({ fieldId: 'new_jobs_descp_string', value: new_jobs_descp_string }); currentScript.setValue({ fieldId: 'new_jobs_package_id_string', value: new_jobs_package_id_string }); currentScript.setValue({ fieldId: 'new_jobs_single_line_string', value: new_jobs_single_line_string }); currentScript.setValue({ fieldId: 'new_service_type_string', value: new_service_type_string }); currentScript.setValue({ fieldId: 'new_service_name_string', value: new_service_name_string }); currentScript.setValue({ fieldId: 'new_service_price_string', value: new_service_price_string }); currentScript.setValue({ fieldId: 'new_service_qty_string', value: new_service_qty_string }); currentScript.setValue({ fieldId: 'new_service_discount_type_string', value: new_service_discount_type_string }); currentScript.setValue({ fieldId: 'new_service_package_id_string', value: new_service_package_id_string }); currentScript.setValue({ fieldId: 'new_service_customer_string', value: new_service_customer_string }); currentScript.setValue({ fieldId: 'new_service_comm_reg_string', value: new_service_comm_reg_string }); currentScript.setValue({ fieldId: 'new_service_single_line_string', value: new_service_single_line_string }); return true; } function adminFeesServiceCheck(customer_id, service_id, deleted_job_ids) { var searched_jobs = search.load({ id: 'customrecord_job', type: 'customsearch_job_inv_review_all' }); searched_jobs.filters.push(search.createFilter({ name: 'custrecord_job_customer', operator: search.Operator.IS, values: customer_id })); searched_jobs.filters.push(search.createFilter({ name: 'custrecord_job_service', operator: search.Operator.IS, values: service_id })); if (!isNullorEmpty(deleted_job_ids)) { searched_jobs.filters.push(search.createFilter({ name: 'internalid', operator: search.Operator.NONEOF, values: deleted_job_ids })); } var resultSet = searched_jobs.run(); var searchedJobsResult = resultSet.getRange({ start: 0, end: 1 }); return searchedJobsResult; } function searchAdminFeesService(customer_id, admin_fees) { var searched_services = search.load({ id: 'customrecord_service', type: 'customsearch_aic_review_services' }); searched_services.filters.push(search.createFilter({ name: 'custrecord_service_customer', operator: search.Operator.IS, values: customer_id })); searched_services.filters.push(search.createFilter({ name: 'custrecord_service', operator: search.Operator.IS, values: 22 })); searched_services.filters.push(search.createFilter({ name: 'custrecord_service_price', operator: search.Operator.EQUALTO, values: admin_fees })); var resultSet = searched_services.run(); var searchedServicesResult = resultSet.getRange({ start: 0, end: 2 }); return searchedServicesResult; } //FUNCTION TO CALCULATE THE TOTAL INVOICE FOR THE CUSTOMER function updateTotal() { var total_invoice = 0.0; var total_package_elem = document.getElementsByClassName("total_package_value"); var total_service_elem = document.getElementsByClassName("service_total"); var admin_fees_total_elem = document.getElementsByClassName("admin_fees_total"); var customer_admin_fees = document.getElementsByClassName("customer_admin_fees"); for (var i = 0; i < total_package_elem.length; ++i) { if (typeof total_package_elem[i].value !== "undefined") { total_invoice = total_invoice + parseFloat(total_package_elem[i].value); } } for (var i = 0; i < total_service_elem.length; ++i) { if (typeof total_service_elem[i].value !== "undefined") { total_invoice = total_invoice + parseFloat(total_service_elem[i].value); } } if (admin_fees_log == true || admin_fees_log == 'true') { for (var i = 0; i < admin_fees_total_elem.length; ++i) { // console.log(admin_fees_total_elem[i].value) if (typeof admin_fees_total_elem[i].value !== "undefined" && admin_fees_total_elem[i].value != "NaN") { total_invoice = total_invoice + parseFloat(admin_fees_total_elem[i].value); } } } $('.total_value').val(total_invoice); } function GetFormattedDate(stringDate) { var todayDate = format.parse({ value: stringDate, type: format.Type.DATE }); var month = pad(todayDate.getMonth() + 1); var day = pad(todayDate.getDate()); var year = (todayDate.getFullYear()); return year + "-" + month + "-" + day; } function pad(s) { return (s < 10) ? '0' + s : s; } function finalise_date(start_date) { var split_date = start_date.split('/'); var date = new Date(); var month = date.getMonth(); //Months 0 - 11 var today = date.getDate(); var year = date.getFullYear(); var lastDay = new Date(split_date[2], split_date[1], 0); var currentLastDay = new Date(year, (month + 1), 0); if (lastDay.getDay() == 0) { lastDay.setDate(lastDay.getDate() - 2); } else if (lastDay.getDay() == 6) { lastDay.setDate(lastDay.getDate() - 1); } var lastWorkingDay = lastDay.getDate(); var lastWorkingDayPlus5 = new Date(); lastDay.setDate(lastDay.getDate() + 5); var button = false; console.log(parseInt(year) === parseInt(split_date[2])); console.log(parseInt(split_date[1]) === parseInt(month + 1)); console.log(today < lastWorkingDay); //If allocator run on the first day of the month, it takes the last month as the filter if (parseInt(year) === parseInt(split_date[2]) && parseInt(split_date[1]) === parseInt(month + 1) && today < lastWorkingDay) { console.log('inside') } else if ((lastWorkingDay == today || today <= currentLastDay.getDate())) { console.log('inside 2') button = true; } return button; } function createServiceRecord(service_type, service_name, price, customer_id, commReg, package_id) { try { var new_service_record = record.create({ type: 'customrecord_service', isDynamic: true, }); new_service_record.setValue({ fieldId: 'custrecord_service', value: service_type }); new_service_record.setValue({ fieldId: 'name', value: service_name }); new_service_record.setValue({ fieldId: 'custrecord_service_price', value: price }); new_service_record.setValue({ fieldId: 'custrecord_service_customer', value: customer_id }); if (!isNullorEmpty(commReg)) { new_service_record.setValue({ fieldId: 'custrecord_service_comm_reg', value: commReg }); } if (!isNullorEmpty(package_id)) { new_service_record.setValue({ fieldId: 'custrecord_service_package', value: package_id }); } var service_id = new_service_record.save({ enableSourcing: true, ignoreMandatoryFields: true }); return service_id; } catch (e) { var message = ''; message += "Customer Internal ID: " + customer_id + "</br>"; message += "Customer: <a href ='https://1048144.app.netsuite.com/app/common/entity/custjob.nl?id=" + customer_id + "'> View Customer </a></br>"; message += "----------------------------------------------------------------------------------</br>"; message += "Service Type: <a href ='https://1048144.app.netsuite.com/app/common/custom/custrecordentry.nl?rectype=949&id=" + service_type + "'> View Service Type</a></br>"; message += "----------------------------------------------------------------------------------</br>"; message += e; email.send({ author: 409635, body: message, recipients: ['ankith.ravindran@mailplus.com.au', 'willian.suryadharma@mailplus.com.au'], subject: 'AIC Review Page - Service Creation - Unable to create Service', }); return false; } } function createJobRecord(customer_id, service_id, rate, qty, description, category, package_id, invoice_single_line, discount_type) { var currentScript = currentRecord.get(); try { // alert(package_id) var job_new_record = record.create({ type: 'customrecord_job', isDynamic: true, }); job_new_record.setValue({ fieldId: 'custrecord_job_customer', value: customer_id }); // job_new_record.setValue({ fieldId: 'custrecord_job_franchisee', value: zee }); job_new_record.setValue({ fieldId: 'custrecord_job_service', value: service_id }); job_new_record.setValue({ fieldId: 'custrecord_job_service_price', value: rate }); job_new_record.setValue({ fieldId: 'custrecord_job_extras_qty', value: qty }); job_new_record.setValue({ fieldId: 'custrecord_job_status', value: 3 }); job_new_record.setValue({ fieldId: 'custrecord_job_invoiceable', value: 1 }); job_new_record.setValue({ fieldId: 'custrecord_job_date_reviewed', value: getDate() }); job_new_record.setValue({ fieldId: 'custrecord_job_source', value: 5 }); job_new_record.setValue({ fieldId: 'custrecord_job_invoice_detail', value: description }); job_new_record.setValue({ fieldId: 'custrecord_job_date_scheduled', value: currentScript.getValue({ fieldId: 'end_date' }) }); if (category == '1') { job_new_record.setValue({ fieldId: 'custrecord_job_group_status', value: 'Completed' }); } if (!isNullorEmpty(package_id)) { job_new_record.setValue({ fieldId: 'custrecord_job_service_package', value: package_id }); job_new_record.setValue({ fieldId: 'custrecord_job_invoice_single_line_item', value: invoice_single_line }); } job_new_record.setValue({ fieldId: 'custrecord_job_service_category', value: category }); job_new_record.setValue({ fieldId: 'custrecord_job_discount_type', value: discount_type }); job_new_record.save({ enableSourcing: true, ignoreMandatoryFields: true }); } catch (e) { var message = ''; message += "Customer Internal ID: " + customer_id + "</br>"; message += "Customer: <a href ='https://1048144.app.netsuite.com/app/common/entity/custjob.nl?id=" + customer_id + "'> View Customer </a></br>"; message += "----------------------------------------------------------------------------------</br>"; if (!isNullorEmpty(service_id) || service_id != false) { message += "Service: <a href ='https://1048144.app.netsuite.com/app/common/custom/custrecordentry.nl?rectype=946&id=" + service_id + "'> View Service Type</a></br>"; message += "----------------------------------------------------------------------------------</br>"; } message += e; email.send({ author: 409635, body: message, recipients: ['ankith.ravindran@mailplus.com.au', 'willian.suryadharma@mailplus.com.au'], subject: 'AIC Review Page - Job Creation - Unable to create Job' }); // return false; } } function updateJobRecord(job_id, rate, qty, description, category, package_id, invoice_single_line, discount_type) { var job_record = record.load({ type: 'customrecord_job', id: job_id, }); job_record.setValue({ fieldId: 'custrecord_job_extras_qty', value: qty }); job_record.setValue({ fieldId: 'custrecord_job_source', value: 5 }); job_record.setValue({ fieldId: 'custrecord_job_invoice_detail', value: description }); if (!isNullorEmpty(package_id)) { job_record.setValue({ fieldId: 'custrecord_job_service_package', value: package_id }); } if (!isNullorEmpty(rate)) { job_record.setValue({ fieldId: 'custrecord_job_service_price', value: rate }); } job_record.setValue({ fieldId: 'custrecord_job_invoice_detail', value: description }); job_record.setValue({ fieldId: 'custrecord_job_invoice_single_line_item', value: invoice_single_line }); job_record.setValue({ fieldId: 'custrecord_job_discount_type', value: discount_type }); job_record.save({ enableSourcing: true, ignoreMandatoryFields: true }); } function removeDuplicateUsingFilter(arr) { var unique_array = []; for (var i = 0; i < arr.length; i++) { if (unique_array.indexOf(arr[i]) == -1) { unique_array.push(arr[i]); } } return unique_array } function isNullorEmpty(strVal) { return (strVal == null || strVal == '' || strVal == 'null' || strVal == undefined || strVal == 'undefined' || strVal == '- None -'); } return { pageInit: pageInit, saveRecord: saveRecord, onclick_review: onclick_review, onclick_summaryPage: onclick_summaryPage, onclick_reset: onclick_reset }; } );
975
[{"tag": "EMAIL", "value": "ankith.ravindran@mailplus.com.au", "start": 121039, "end": 121071}, {"tag": "EMAIL", "value": "willian.suryadharma@mailplus.com.au", "start": 121075, "end": 121110}, {"tag": "EMAIL", "value": "ankith.ravindran@mailplus.com.au", "start": 124686, "end": 124718}, {"tag": "EMAIL", "value": "willian.suryadharma@mailplus.com.au", "start": 124722, "end": 124757}]
true
4
/** * * @NApiVersion 2.0 * @NScriptType ClientScript * * Description: Client script that habndles all the validations and calculations of the review page. * @Last Modified by: Sruti Desai * */ define(['N/error', 'N/runtime', 'N/search', 'N/url', 'N/record', 'N/format', 'N/email', 'N/currentRecord'], function(error, runtime, search, url, record, format, email, currentRecord) { var baseURL = 'https://1048144.app.netsuite.com'; if (runtime.envType == "SANDBOX") { baseURL = 'https://1048144-sb3.app.netsuite.com'; } var role = runtime.getCurrentUser().role; var zee = 0; var ctx = runtime.getCurrentScript(); var deleted_service_ids = []; var deleted_job_ids = []; if (role == 1000) { //Franchisee zee = ctx.getCurrentUser(); } else if (role == 3) { //Administrator zee = 6; //test } else if (role == 1032) { // System Support zee = 425904; //test-AR } var global_customer; var global_locked = null; var admin_fees_log = false; /** * On page initialisation- collapse the App Qty fields and the Invoiceable Qty fields */ function pageInit() { var currentScript = currentRecord.get(); $(window).load(function() { // Animate loader off screen $(".se-pre-con").fadeOut("slow");; }); $("#NS_MENU_ID0-item0").css("background-color", "#CFE0CE"); $("#NS_MENU_ID0-item0 a").css("background-color", "#CFE0CE"); $("#body").css("background-color", "#CFE0CE"); $(document).ready(function() { $('[data-toggle="tooltip"]').tooltip(); }); $('.col_collapse_appqty').hide(); $('.header_collapse').hide(); $('.discount_collpase_appqty').hide(); $('.singleline_collpase_appqty').hide(); $('.total_collapse_appqty').hide(); $('.monthlytotal_collapse_appqty').hide(); $('.invoicetotalheader_collpase_appqty').hide(); $('.invoiceable_qty_collpase').hide(); $('.package_name_row').attr('colspan', 6); $('.header_invoiceable_qty_collpase').attr('colspan', 1); global_customer = currentScript.getValue({ fieldId: 'customer_id' }); var start_date = GetFormattedDate(currentScript.getValue({ fieldId: 'start_date' }) ); var end_date = GetFormattedDate(currentScript.getValue({ fieldId: 'end_date' }) ); $('.start_date').val(start_date); $('.end_date').val(end_date); admin_fees_log = currentScript.getValue({ fieldId: 'admin_fees_log' }); global_locked = currentScript.getValue({ fieldId: 'locked' }); document.getElementById('tdbody_reviewed').style = 'background-color: #125ab2 !important;color: white;'; if (global_locked == 'yes') { document.getElementById('tr_submitter').style.display = 'none'; document.getElementById('tdbody_reviewed').style.display = 'none'; $('.admin_fees_on').prop('disabled', true); $('.admin_fees_off').prop('disabled', true); $('.invoiceable_qty').prop('disabled', function(i, v) { return !v; }); $('.admin_fees_rate').prop('disabled', function(i, v) { return !v; }); $('.admin_fees_qty').prop('disabled', function(i, v) { return !v; }); $('.job_description').prop('disabled', function(i, v) { return !v; }); $('.single_job_description').prop('disabled', function(i, v) { return !v; }); $('.add_services').prop('disabled', function(i, v) { return !v; }); $('.fixed_discount_value').prop('disabled', function(i, v) { return !v; }); $('.fixed_discount_qty').prop('disabled', function(i, v) { return !v; }); $('.total_package_value').prop('disabled', function(i, v) { return !v; }); $('.customer_po').prop('disabled', function(i, v) { return !v; }); } var result = finalise_date(currentScript.getValue({ fieldId: 'start_date' })); // $(document).on('click', '.instruction_button', function(e) { // console.log("abc"); // $('.table_start').css("padding-top", "300px"); // $('.instruction_button').hide(); // }); $('.collapse').on('shown.bs.collapse', function() { $('.table_start').css("padding-top", "250px"); }) $('.collapse').on('hide.bs.collapse', function() { $('.table_start').css("padding-top", "0px"); }) $('#exampleModal').on('show.bs.modal', function(event) { var button = $(event).relatedTarget // Button that triggered the modal var recipient = button.data('whatever') // Extract info from data-* attributes // If necessary, you could initiate an AJAX request here (and then do the updating in a callback). // Update the modal's content. We'll use jQuery here, but you could use a data binding library or other methods instead. var modal = $(this) modal.find('.modal-title').text('New message to ' + recipient) modal.find('.modal-body input').val(recipient) }); $(document).ready(function() { $(".modal_display").click(function() { var link = $(this).data("whatever"); // console.log(link); $('.modal .modal-header').html('<div class="form-group"><h4><label class="control-label" for="inputError1">Information</label></h4></div>'); $('.modal .modal-body').html(""); $('.modal .modal-body').html(link); $('.modal .modal-footer').html('<button type="button" class="btn btn-default" data-dismiss="modal">Close</button>'); $('.modal').modal("show"); }); }); /** * [description] - On click of the '+', open up the App Qty fields */ $(document).on('click', '.collapse_appqty', function(e) { $('.col_collapse_appqty').show(); $('.header_collapse').show(); $('.discount_collpase_appqty').show(); $('.singleline_collpase_appqty').show(); $('.total_collapse_appqty').show(); $('.monthlytotal_collapse_appqty').show(); $('.invoicetotalheader_collpase_appqty').show(); $('.package_name_row').attr('colspan', 12); $('.admin_fees_collpase').attr('colspan', 5); // $('.collapse_appqty').removeClass('glyphicon-plus'); // $('.collapse_appqty').addClass('glyphicon-minus'); $('.collapse_appqty').addClass('invoiceableqty_collapse'); }); /** * [description] - On click of the '+' for the second time, show the invoiceable qty fields */ $(document).on('click', '.invoiceableqty_collapse', function(e) { $('.invoiceable_qty_collpase').show(); $('.invoiceableqty_collapse').hide(); // $('.package_name_row').attr('colspan',11); $('.header_invoiceable_qty_collpase').attr('colspan', 3); $('.admin_fees_collpase').attr('colspan', 7); }); /** * [description] - On click of the '-', collapse all the App Qty and Invoiceable Qty fields */ $(document).on('click', '.collapse_all', function(e) { $('.col_collapse_appqty').hide(); $('.collapse_appqty').show(); $('.invoiceable_qty_collpase').show(); $('.invoiceableqty_collapse').show(); $('.header_collapse').hide(); $('.discount_collpase_appqty').hide(); $('.singleline_collpase_appqty').hide(); $('.total_collapse_appqty').hide(); $('.monthlytotal_collapse_appqty').hide(); $('.invoicetotalheader_collpase_appqty').hide(); $('.invoiceable_qty_collpase').hide(); $('.package_name_row').attr('colspan', 6); $('.admin_fees_collpase').attr('colspan', 0); $('.header_invoiceable_qty_collpase').attr('colspan', 1); $('.collapse_appqty').removeClass('invoiceableqty_collapse'); }); //DO CALCULATIONS IF THE DISCUNT QTY IN THE DISCOUNT ROW IS CHANGED $(document).on('blur', '.discount_qty', function(e) { var discount_value = $(this).closest('tr').find('.discount_value').val(); var discount_qty = $(this).val(); var attr_fixed = $(this).attr('package-fixed'); var attr_packageid = $(this).attr('data-packageid'); var old_total_discount_value = $(this).closest('tr').find('.total_discount_value').val(); var old_total_value = $(this).closest('tr').next('tr').find('.total_package_value').val(); var package_value = $(this).closest('tr').next('tr').find('.package_value').val(); var discount_type = $(this).closest('tr').find('.discount_type').val(); var total_package = 0; var package_invoiceable_qty_elem = document.getElementsByClassName("package_invoiceable_qty"); var package_netsuite_qty_elem = document.getElementsByClassName("package_netsuite_qty"); var package_app_qty_elem = document.getElementsByClassName("package_app_qty"); var service_total_value_elem = document.getElementsByClassName("service_total_value"); var app_qty = []; for (var i = 0; i < package_app_qty_elem.length; ++i) { app_qty.push(parseInt(package_app_qty_elem[i].value)); } var max = Math.max.apply(null, app_qty); //CHECKING THE MAX QTY OF ALL THE APP QTY AND IF THE DISCOUNT QTY IS LESS THAN THE MAX APP QTY, THE DISCOUNT QTY IS CHANGED TO THE MAX APP QTY if (discount_qty < max) { discount_qty = max; $(this).val(max); } //ADJUST THE QTYS OF THE TOTAL INVOICEABLE QTY FOR ALL SERVICES FOR THAT PACKAGE for (var i = 0; i < package_invoiceable_qty_elem.length; ++i) { if (package_invoiceable_qty_elem[i].getAttribute("data-packageid") == attr_packageid) { var initial_changed_qty = package_invoiceable_qty_elem[i].value; var initial_load_qty = package_invoiceable_qty_elem[i].getAttribute("data-oldqty"); var netsuite_qty = package_netsuite_qty_elem[i].value; var app_qty = package_app_qty_elem[i].value; var rate = package_invoiceable_qty_elem[i].getAttribute("data-rate"); var total_inv_qty = parseFloat(app_qty) + parseFloat(netsuite_qty); if (discount_qty >= 0) { if (discount_qty == 0) { //IF DISCOUNT QTY ENTERED IS 0 if (app_qty > 0) { alert('Cannot reduce quantity below ' + app_qty); $(this).val(app_qty); return false; } else { package_netsuite_qty_elem[i].setAttribute("value", discount_qty); discount_qty = parseFloat(discount_qty) + parseFloat(app_qty); package_invoiceable_qty_elem[i].setAttribute("value", discount_qty); } } else { package_invoiceable_qty_elem[i].setAttribute("value", discount_qty); if (total_inv_qty != discount_qty) { var new_netsuite_qty = parseFloat(discount_qty) - parseFloat(total_inv_qty); new_netsuite_qty = parseFloat(netsuite_qty) + new_netsuite_qty; package_netsuite_qty_elem[i].setAttribute("value", new_netsuite_qty); } } // package_app_qty_elem[i].setAttribute("value", new_app_qty); var total_rate = updateServiceAmount(parseFloat(rate), parseFloat(discount_qty)); service_total_value_elem[i].setAttribute("value", roundTwoDec(total_rate)); total_package += total_rate; } else { alert('Wrong Quantity entered'); return false; } } } $(this).closest('tr').next('tr').find('.package_value').val(total_package); //CALCULATIONS FOR THE PACKAGE DISCOUNT VALUE BASED ON THE DISCOUNT TYPE if (discount_type == 1) { var total_discount_value = (parseFloat(discount_qty) * parseFloat(discount_value)); var new_total_value = parseFloat(total_package) - total_discount_value; } else { var total_discount_value = ((parseFloat(discount_value) / 100) * parseFloat(total_package)); var new_total_value = parseFloat(total_package) - total_discount_value; } //UPDATE THE TOTAL DISCOUNT VALUE AND THE TOTAL PACKAGE VALUE $(this).closest('tr').find('.total_discount_value').val(roundTwoDec(total_discount_value)); $(this).closest('tr').next('tr').next('tr').find('.total_package_value').val(roundTwoDec(new_total_value)); $(this).closest('tr').next('tr').next('tr').find('.total_package_value').focus(); //UPDATE THE INVOICE TOTAL BASED ON THE CHANGE updateTotal(); }); //ON CHANGE OF THE INVOICEABLE QTY FOR THE SERVICES AND EXTRAS SECTION $(document).on('blur', '.invoiceable_qty', function(e) { var invoiceable_qty = $(this).val(); if (isNullorEmpty(invoiceable_qty)) { invoiceable_qty = 0; $(this).val(0); } var old_qty = $(this).attr('data-oldqty'); var rate = $(this).attr('data-rate'); var app_qty = $(this).closest('tr').find('.app_qty').val(); var netsuite_qty = $(this).closest('tr').find('.package_netsuite_qty').val(); var total_inv_qty = parseFloat(app_qty) + parseFloat(netsuite_qty); if (invoiceable_qty >= 0) { if (invoiceable_qty == 0) { if (app_qty > 0) { alert('Cannot reduce quantity below ' + app_qty + '. \nTo reduce the quantity, please click on the App Jobs and set \"DO YOU WANT TO INVOICE JOB GROUP??\" to \"No\"'); $(this).val(app_qty); $(this).closest('tr').find('.package_netsuite_qty').val(0); var total_rate = updateServiceAmount(parseFloat(rate), parseFloat(app_qty)); $(this).closest('tr').find('.service_total_value').val(roundTwoDec(total_rate)); $(this).closest('tr').find('.service_total_value').focus(); $(this).closest('tr').find('.service_total').val((total_rate)); return false; } else { var new_netsuite_qty = parseFloat(invoiceable_qty); $(this).closest('tr').find('.package_netsuite_qty').val(new_netsuite_qty); var total_rate = updateServiceAmount(parseFloat(rate), parseFloat(invoiceable_qty)); $(this).closest('tr').find('.service_total_value').val(roundTwoDec(total_rate)); $(this).closest('tr').find('.service_total_value').focus(); $(this).closest('tr').find('.service_total').val((total_rate)); } } else { if (parseInt(app_qty) > invoiceable_qty) { alert('Cannot reduce quantity below ' + app_qty + '. \nTo reduce the quantity, please click on the App Jobs and set \"DO YOU WANT TO INVOICE JOB GROUP??\" to \"No\"'); $(this).val(app_qty); $(this).closest('tr').find('.package_netsuite_qty').val(0); var total_rate = updateServiceAmount(parseFloat(rate), parseFloat(app_qty)); $(this).closest('tr').find('.service_total_value').val(roundTwoDec(total_rate)); $(this).closest('tr').find('.service_total_value').focus(); $(this).closest('tr').find('.service_total').val((total_rate)); return false; } if (parseInt(total_inv_qty) != invoiceable_qty) { var new_netsuite_qty = parseFloat(invoiceable_qty) - parseFloat(total_inv_qty); new_netsuite_qty = parseFloat(netsuite_qty) + new_netsuite_qty; $(this).closest('tr').find('.package_netsuite_qty').val(new_netsuite_qty); var total_rate = updateServiceAmount(parseFloat(rate), parseFloat(invoiceable_qty)); $(this).closest('tr').find('.service_total_value').val((total_rate).toFixed(2)); $(this).closest('tr').find('.service_total_value').focus(); $(this).closest('tr').find('.service_total').val((total_rate).toFixed(2)); // $(this).closest('tr').find('.service_total_value').val((total_rate)); } } } else { alert('Cannot reduce quantity below ' + app_qty + '. \nTo reduce the quantity, please click on the App Jobs and set \"DO YOU WANT TO INVOICE JOB GROUP??\" to \"No\"'); $(this).val(app_qty); return false; } updateTotal(); }); $(document).on('blur', '.total_package_value', function(e) { var total_value = $(this).val(); // var old_total_discount_value = $(this).closest('tr').find('.total_discount_value').val(); var package_value = $(this).closest('tr').find('.package_value').val(); // var discount_type = $(this).closest('tr').find('.discount_type').val(); var discount_qty = $(this).closest('tr').prev('tr').prev('tr').find('.discount_qty').val(); var total_discount = parseFloat(total_value) - parseFloat(package_value); var per_discount = total_discount / parseFloat(discount_qty); $(this).closest('tr').prev('tr').prev('tr').find('.discount_value').val(roundTwoDec(parseFloat(per_discount))); $(this).closest('tr').prev('tr').prev('tr').find('.total_discount_value').val(roundTwoDec(parseFloat(total_discount))); }); //ON CHANGE OF THE FIXED RATE QTY $(document).on('blur', '.fixed_discount_qty', function(e) { var discount_value = $(this).closest('tr').find('.fixed_discount_value').val(); var discount_qty = $(this).val(); var attr_fixed = $(this).attr('package-fixed'); var attr_packageid = $(this).attr('data-packageid'); var old_total_discount_value = $(this).closest('tr').find('.total_discount_value').val(); var old_total_value = $(this).closest('tr').next('tr').find('.total_package_value').val(); var package_value = $(this).closest('tr').next('tr').find('.package_value').val(); var discount_type = $(this).closest('tr').find('.discount_type').val(); var total_package = 0; var package_invoiceable_qty_elem = document.getElementsByClassName("package_invoiceable_qty"); var package_netsuite_qty_elem = document.getElementsByClassName("package_netsuite_qty"); var package_app_qty_elem = document.getElementsByClassName("package_app_qty"); var service_total_value_elem = document.getElementsByClassName("service_total_value"); var app_qty = []; for (var i = 0; i < package_app_qty_elem.length; ++i) { var packageID = package_invoiceable_qty_elem[i].getAttribute("data-packageid"); if (attr_packageid == packageID) { app_qty.push(parseInt(package_app_qty_elem[i].value)); } } // console.log(app_qty); // return false; var max = Math.max.apply(null, app_qty); if (discount_qty < max) { discount_qty = max; $(this).val(max); } for (var i = 0; i < package_invoiceable_qty_elem.length; ++i) { if (package_invoiceable_qty_elem[i].getAttribute("data-packageid") == attr_packageid) { var initial_changed_qty = package_invoiceable_qty_elem[i].value; var initial_load_qty = package_invoiceable_qty_elem[i].getAttribute("data-oldqty"); var netsuite_qty = package_netsuite_qty_elem[i].value; var app_qty = package_app_qty_elem[i].value; var rate = package_invoiceable_qty_elem[i].getAttribute("data-rate"); var service_cat = package_netsuite_qty_elem[i].getAttribute("data-servicecat"); var total_inv_qty = parseFloat(app_qty) + parseFloat(netsuite_qty); if (service_cat == 1) { if (discount_qty >= 0) { if (discount_qty == 0) { if (app_qty > 0) { alert('Cannot reduce quantity below ' + app_qty); $(this).val(app_qty); return false; } else { package_netsuite_qty_elem[i].setAttribute("value", discount_qty); discount_qty = parseFloat(discount_qty) + parseFloat(app_qty); package_invoiceable_qty_elem[i].setAttribute("value", discount_qty); } } else { package_invoiceable_qty_elem[i].setAttribute("value", discount_qty); if (total_inv_qty != discount_qty) { var new_netsuite_qty = parseFloat(discount_qty) - parseFloat(total_inv_qty); new_netsuite_qty = parseFloat(netsuite_qty) + new_netsuite_qty; package_netsuite_qty_elem[i].setAttribute("value", new_netsuite_qty); } } // package_app_qty_elem[i].setAttribute("value", new_app_qty); var total_rate = updateServiceAmount(parseFloat(rate), parseFloat(discount_qty)); service_total_value_elem[i].setAttribute("value", total_rate); total_package += total_rate; } else { alert('Wrong Quantity entered'); return false; } } else { var total_rate = updateServiceAmount(parseFloat(rate), parseFloat(initial_changed_qty)); total_package += total_rate; } } } $(this).closest('tr').find('.package_value').val(total_package); var package_value = parseFloat(total_package); var total_discount_value = (parseFloat(discount_qty) * parseFloat(discount_value)); $(this).closest('tr').find('.total_package_value').val(roundTwoDec(total_discount_value)); $(this).closest('tr').find('.total_package_value').focus(); var new_discount = parseFloat(total_discount_value) - parseFloat(package_value); if (new_discount < 0) { $(this).closest('tr').prev('tr').prev('tr').find('.discount_dollar').addClass('has-error'); $(this).closest('tr').prev('tr').prev('tr').find('.discount_dollar').removeClass('has-success'); } else { $(this).closest('tr').prev('tr').prev('tr').find('.discount_dollar').addClass('has-success'); $(this).closest('tr').prev('tr').prev('tr').find('.discount_dollar').removeClass('has-error'); } $(this).closest('tr').prev('tr').find('.total_discount_value').val(roundTwoDec(new_discount)); var discount_rate = new_discount / parseFloat(discount_qty); $(this).closest('tr').prev('tr').prev('tr').find('.total_discount_value').val(roundTwoDec(new_discount)); $(this).closest('tr').prev('tr').prev('tr').find('.discount_value').val(roundTwoDec((new_discount / parseFloat(discount_qty)))); $(this).closest('tr').prev('tr').prev('tr').find('.discount_qty').val(discount_qty); updateTotal(); }); //GET THE OLD VALUE OF THE DISCOUNT VALUE. $(document).on('focusin', '.discount_value', function() { $(this).data('oldval', $(this).val()); }); //ON CHANGE OF THE DISCOUNT VALUE $(document).on('blur', '.discount_value', function(e) { var discount_qty = $(this).closest('tr').find('.discount_qty').val(); var discount_value = $(this).val(); var old_discount_value = $(this).data('oldval'); var attr_fixed = $(this).attr('package-fixed'); var attr_packageid = $(this).attr('data-packageid'); var old_total_discount_value = $(this).closest('tr').find('.total_discount_value').val(); var old_total_value = $(this).closest('tr').next('tr').next('tr').find('.total_package_value').val(); var package_value = $(this).closest('tr').next('tr').next('tr').find('.package_value').val(); var discount_type = $(this).closest('tr').find('.discount_type').val(); //IF THE DISCOUNT TYPE IS $ if (discount_type == 1) { var total_discount_value = (parseFloat(discount_qty) * parseFloat(discount_value)); //TO CHECK THE TOTAL DISCOUNT VALUE IS NOT GREATER THAN THE TOTAL PACKAGE OF ALL THE SERVICES if (total_discount_value < package_value) { $(this).closest('tr').find('.total_discount_value').val(roundTwoDec(total_discount_value)); } else { alert('Total value is greater than the total of the package'); $(this).val(old_discount_value); var total_discount_value = (parseFloat(discount_qty) * parseFloat(old_discount_value)); $(this).closest('tr').find('.total_package_value').val(roundTwoDec(total_discount_value)); $(this).closest('tr').find('.total_package_value').focus(); return false; } var new_total_value = parseFloat(package_value) - total_discount_value; } else { //IF DISCOUNT TYPE IS % var total_discount_value = ((parseFloat(discount_value) / 100) * parseFloat(package_value)); if (total_discount_value < package_value) { $(this).closest('tr').find('.total_discount_value').val(roundTwoDec(total_discount_value)); } else { alert('Total value is greater than the total of the package'); $(this).val(old_discount_value); var total_discount_value = (parseFloat(discount_qty) * parseFloat(old_discount_value)); $(this).closest('tr').find('.total_discount_value').val(roundTwoDec(total_discount_value)); return false; } var new_total_value = parseFloat(package_value) - total_discount_value; } // $(this).closest('tr').find('.total_discount_value').val(-(total_discount_value)); $(this).closest('tr').next('tr').next('tr').find('.total_package_value').val(roundTwoDec(new_total_value)); $(this).closest('tr').next('tr').next('tr').find('.total_package_value').focus(); updateTotal(); }); //GET THE OLD FIXED RATE $(document).on('focusin', '.fixed_discount_value', function() { $(this).data('oldval', $(this).val()); }); //ON CHANGE OF THE FIXED RATE VALUE $(document).on('blur', '.fixed_discount_value', function(e) { var discount_qty = $(this).closest('tr').find('.fixed_discount_qty').val(); var discount_value = $(this).val(); var old_discount_value = $(this).data('oldval'); var attr_fixed = $(this).attr('package-fixed'); var attr_packageid = $(this).attr('data-packageid'); var old_total_discount_value = $(this).closest('tr').find('.total_discount_value').val(); var old_total_value = $(this).closest('tr').next('tr').find('.total_package_value').val(); var package_value = $(this).closest('tr').next('tr').find('.package_value').val(); var discount_type = $(this).closest('tr').find('.discount_type').val(); var package_value = $(this).closest('tr').find('.package_value').val(); var total_discount_value = (parseFloat(discount_qty) * parseFloat(discount_value)); if (total_discount_value < package_value) { $(this).closest('tr').find('.total_package_value').val(roundTwoDec(total_discount_value)); $(this).closest('tr').find('.total_package_value').focus(); } else { alert('Total value is greater than the total of the package'); $(this).val(old_discount_value); var total_discount_value = (parseFloat(discount_qty) * parseFloat(old_discount_value)); $(this).closest('tr').find('.total_package_value').val(roundTwoDec(total_discount_value)); $(this).closest('tr').find('.total_package_value').focus(); return false; } var new_discount = parseFloat(total_discount_value) - parseFloat(package_value); if (new_discount < 0) { $(this).closest('tr').prev('tr').prev('tr').find('.discount_dollar').addClass('has-error'); $(this).closest('tr').prev('tr').prev('tr').find('.discount_dollar').removeClass('has-success'); } else { $(this).closest('tr').prev('tr').prev('tr').find('.discount_dollar').addClass('has-success'); $(this).closest('tr').prev('tr').prev('tr').find('.discount_dollar').removeClass('has-error'); } $(this).closest('tr').prev('tr').prev('tr').find('.total_discount_value').val(roundTwoDec(new_discount)); $(this).closest('tr').prev('tr').prev('tr').find('.discount_value').val(roundTwoDec(new_discount / parseFloat(discount_qty))); $(this).closest('tr').prev('tr').prev('tr').find('.discount_qty').val(roundTwoDec(discount_qty)); updateTotal(); }); //ON CHANGE OF THE DISCOUNT TYPE, HIDE OR SHOW THE DISCOUNT QTY $(document).on("change", ".discount_type", function(e) { var discount_type = $(this).val(); //IF THE DISCOUNT TYPE IS $, SHOW THE DISCOUNT QTY if (discount_type == 1) { $(this).closest('tr').find('.discount_qty').show(); } else { $(this).closest('tr').find('.discount_qty').hide(); } }); //ON CHANGE OF THE INVOICE SINGLE LINE $(document).on("change", ".invoice_single_line", function(e) { var packageid; $('option:selected', this).each(function() { packageid = ($(this).data('packageid')); }); var value = $(this).val(); var package_invoiceable_qty_elem = document.getElementsByClassName("package_invoiceable_qty"); var job_desciption_elem = document.getElementsByClassName("job_description"); for (var i = 0; i < package_invoiceable_qty_elem.length; ++i) { if (job_desciption_elem[i].getAttribute("data-packageid") == packageid) { //IF INVOICE SINGLE LINE IS SET TO YES, HIDE THE INVOICE DETAILS FIELDS FOR EACH OF THE SERVICES PRESENT IN THE PACKAGE if (value == 1) { $(this).closest('tr').find('.single_job_description').show(); job_desciption_elem[i].setAttribute('style', "display: none"); job_desciption_elem[i].setAttribute('value', ""); job_desciption_elem[i].setAttribute('data-singleline', "1"); } else { //HIDE THE INVOICE DETAIL SHOWN IN THE INVOICE DETAIL ROW AND SHOW THE INVOICE DETAIL FIELDS FOR EACH OF THE SERVICES PRESENT IN THE PACKAGE $(this).closest('tr').find('.single_job_description').hide(); $(this).closest('tr').find('.single_job_description').val(null); job_desciption_elem[i].setAttribute('style', "display: display"); job_desciption_elem[i].setAttribute('data-singleline', "2"); } } } if (value == 1) { $(this).closest('tr').find('.single_line_hidden').val("1"); } else { $(this).closest('tr').find('.single_line_hidden').val("2"); } }); $('.add_services').click(function() { console.log("clicked services btn"); var serv_param = $(this).attr("fnparam"); addService(serv_param); }); /** * [description] - To show the Invoice Preview modal */ $(document).on('click', '.preview_row', function(event) { console.log("prev clicked"); var currentScript = currentRecord.get(); var discount_type_elem = document.getElementsByClassName("discount_type"); var discount_value_elem = document.getElementsByClassName("discount_value"); var discount_qty_elem = document.getElementsByClassName("discount_qty"); var total_discount_elem = document.getElementsByClassName("total_discount_value"); var invoice_single_line_elem = document.getElementsByClassName("invoice_single_line"); var total_package_value = document.getElementsByClassName("total_package_value"); var single_line_hidden = document.getElementsByClassName("single_line_hidden"); var fixed_discount_value = document.getElementsByClassName("fixed_discount_value"); var job_description_elem = document.getElementsByClassName("job_description"); var single_job_description_elem = document.getElementsByClassName("single_job_description"); var admin_fees_rate_elem = document.getElementsByClassName("admin_fees_rate"); var admin_fees_qty_elem = document.getElementsByClassName("admin_fees_qty"); var gst_value = 0.1; var total_gst = 1.1; var sum_total = 0.0; var sum_gst = 0.0; var sum_gross_total = 0.0; var package_details = []; var invoice_line_items = []; var invoice_line_qty = []; var invoice_line_rate = []; var invoice_line_gst = []; preview_html = '<table class="table table-responsive table-striped"><thead><tr class="info"><th><b>ITEM</b></th><th><b>DETAILS</b></th><th style="text-align: right;"><b>QTY</b></th><th style="text-align: right;"><b>RATE</b></th><th style="text-align: right;"><b>TOTAL</b></th><th style="text-align: right;"><b>GST</b></th><th style="text-align: right;"><b>GROSS TOTAL</b></th></thead><tbody>'; if (!isNullorEmpty(total_discount_elem)) { for (var i = 0; i < total_discount_elem.length; ++i) { var job_id = total_discount_elem[i].getAttribute('data-netsuitejob'); var default_description_value = single_job_description_elem[i].getAttribute('default-value'); var description_value = single_job_description_elem[i].value; var default_total_discount_value = total_discount_elem[i].getAttribute('default-value'); var single_line_hidden_default = single_line_hidden[i].getAttribute('default-singleline'); var total_discount_value = total_discount_elem[i].value; var single_line_hidden_value = single_line_hidden[i].value; if (isNullorEmpty(single_line_hidden_value)) { single_line_hidden_value = single_line_hidden_default; } var package_id = null; var discount_period = null; if (total_discount_elem[i].hasAttribute("data-package")) { package_id = total_discount_elem[i].getAttribute('data-package'); package_record = record.load({ type: 'customrecord_service_package', id: package_id, }); discount_period = package_record.getValue({ fieldId: 'custrecord_service_package_disc_period' }); package_ns_item_id = package_record.getValue({ fieldId: 'custrecord_service_package_ns_item' }); if (isNullorEmpty(package_ns_item_id)) { package_ns_item = 'Fixed Charges'; package_ns_item_id = 66; } else { package_ns_item = search.lookupFields({ type: 'item', id: package_ns_item_id, columns: 'itemid' }); } package_details[package_id] = []; if (discount_period == 3) { invoice_line_items[invoice_line_items.length] = package_ns_item_id; invoice_line_qty[invoice_line_qty.length] = 1; invoice_line_rate[invoice_line_rate.length] = total_package_value[i].value; invoice_line_gst[invoice_line_gst.length] = 7; package_details[package_id][0] = "1"; package_details[package_id][1] = "1"; package_details[package_id][2] = total_package_value[i].value; preview_html += '<tr><td>' + package_ns_item + '</td><td>' + description_value + '</td><td style="text-align: right;">1</td><td style="text-align: right;">$' + parseFloat(total_package_value[i].value).toFixed(2) + '</td><td style="text-align: right;">$' + parseFloat(total_package_value[i].value).toFixed(2) + '</td><td style="text-align: right;">$' + parseFloat(total_package_value[i].value * gst_value).toFixed(2) + '</td style="text-align: right;"><td style="text-align: right;">$' + parseFloat(total_package_value[i].value * total_gst).toFixed(2) + '</td></tr>'; sum_total = parseFloat(sum_total + (total_package_value[i].value)); sum_gst = parseFloat(sum_gst + (total_package_value[i].value * gst_value)); sum_gross_total = parseFloat(sum_gross_total + (total_package_value[i].value * total_gst)); } else { if (single_line_hidden_value == 1) { invoice_line_items[invoice_line_items.length] = package_ns_item_id; invoice_line_qty[invoice_line_qty.length] = discount_qty_elem[i].value; invoice_line_rate[invoice_line_rate.length] = fixed_discount_value[i].value; invoice_line_gst[invoice_line_gst.length] = 7; package_details[package_id][0] = "1"; package_details[package_id][1] = discount_qty_elem[i].value; package_details[package_id][2] = fixed_discount_value[i].value; preview_html += '<tr><td>' + package_ns_item + '</td><td>' + description_value + '</td><td style="text-align: right;">' + discount_qty_elem[i].value + '</td><td style="text-align: right;">$' + parseFloat(fixed_discount_value[i].value).toFixed(2) + '</td><td style="text-align: right;">$' + parseFloat(fixed_discount_value[i].value * discount_qty_elem[i].value).toFixed(2) + '</td><td style="text-align: right;">$' + parseFloat(discount_qty_elem[i].value * fixed_discount_value[i].value * gst_value).toFixed(2) + '</td><td style="text-align: right;">$' + parseFloat(discount_qty_elem[i].value * fixed_discount_value[i].value * total_gst).toFixed(2) + '</td></tr>'; sum_total = parseFloat(sum_total + (fixed_discount_value[i].value * discount_qty_elem[i].value)); sum_gst = parseFloat(sum_gst + (discount_qty_elem[i].value * fixed_discount_value[i].value * gst_value)); sum_gross_total = parseFloat(sum_gross_total + (discount_qty_elem[i].value * fixed_discount_value[i].value * total_gst)); } else { package_details[package_id][0] = "2"; package_details[package_id][1] = discount_qty_elem[i].value; package_details[package_id][2] = discount_value_elem[i].value; } } } } } var package_invoiceable_qty_elem = document.getElementsByClassName("package_invoiceable_qty"); var old_package_id = null; for (var i = 0; i < package_invoiceable_qty_elem.length; ++i) { var qty = package_invoiceable_qty_elem[i].value; var rate = package_invoiceable_qty_elem[i].getAttribute("data-rate"); var item_name = package_invoiceable_qty_elem[i].getAttribute("data-nsitem"); var item_id = package_invoiceable_qty_elem[i].getAttribute("data-nsitemid"); var gst = package_invoiceable_qty_elem[i].getAttribute("data-gst"); // console.log(item_name); if (package_invoiceable_qty_elem[i].hasAttribute("data-packageid")) { var package_id = package_invoiceable_qty_elem[i].getAttribute("data-packageid"); if ((old_package_id == package_id && isNullorEmpty(old_package_id)) || old_package_id == package_id) { if (package_details[old_package_id] != undefined) { if (package_details[old_package_id][0] != "1") { // console.log('first if inside 2'); if (gst == 'Yes' || gst == '- None -') { invoice_line_items[invoice_line_items.length] = item_id; invoice_line_qty[invoice_line_qty.length] = qty; invoice_line_rate[invoice_line_rate.length] = rate; invoice_line_gst[invoice_line_gst.length] = 7; preview_html += '<tr><td>' + item_name + '</td><td>' + job_description_elem[i].value + '</td><td style="text-align: right;">' + qty + '</td><td style="text-align: right;">$' + parseFloat(rate).toFixed(2) + '</td><td style="text-align: right;">$' + parseFloat(qty * rate).toFixed(2) + '</td><td style="text-align: right;">$' + parseFloat(qty * rate * gst_value).toFixed(2) + '</td><td style="text-align: right;">$' + parseFloat(qty * rate * total_gst).toFixed(2) + '</td></tr>'; sum_total = parseFloat(sum_total + (qty * rate)); sum_gst = parseFloat(sum_gst + (qty * rate * gst_value)); sum_gross_total = parseFloat(sum_gross_total + (qty * rate * total_gst)); } else { invoice_line_items[invoice_line_items.length] = item_id; invoice_line_qty[invoice_line_qty.length] = qty; invoice_line_rate[invoice_line_rate.length] = rate; invoice_line_gst[invoice_line_gst.length] = 9; preview_html += '<tr><td>' + item_name + '</td><td>' + job_description_elem[i].value + '</td><td style="text-align: right;">' + qty + '</td><td style="text-align: right;">$' + parseFloat(rate).toFixed(2) + '</td><td style="text-align: right;">$' + parseFloat(qty * rate).toFixed(2) + '</td><td style="text-align: right;"></td><td style="text-align: right;">$' + parseFloat(qty * rate).toFixed(2) + '</td></tr>'; sum_total = parseFloat(sum_total + (qty * rate)); sum_gross_total = parseFloat(sum_gross_total + (qty * rate)); } } } } else { if (package_details[old_package_id] != undefined) { if (package_details[old_package_id][0] != "1") { var font_color = ''; if (package_details[old_package_id][2] < 0) { font_color = 'color:red;'; } invoice_line_items[invoice_line_items.length] = 97; invoice_line_qty[invoice_line_qty.length] = package_details[old_package_id][1]; invoice_line_rate[invoice_line_rate.length] = package_details[old_package_id][2]; invoice_line_gst[invoice_line_gst.length] = 7; preview_html += '<tr style="' + font_color + '"><td>Discount</td><td></td><td style="text-align: right;">' + package_details[old_package_id][1] + '</td><td style="text-align: right;">$' + parseFloat(package_details[old_package_id][2]).toFixed(2) + '</td><td style="text-align: right;">$' + parseFloat(package_details[old_package_id][1] * package_details[old_package_id][2]).toFixed(2) + '</td><td style="text-align: right;">$' + parseFloat(package_details[old_package_id][1] * package_details[old_package_id][2] * gst_value).toFixed(2) + '</td><td style="text-align: right;">$' + parseFloat(package_details[old_package_id][1] * package_details[old_package_id][2] * total_gst).toFixed(2) + '</td></tr>'; sum_total = parseFloat(sum_total + (package_details[old_package_id][1] * package_details[old_package_id][2])); sum_gst = parseFloat(sum_gst + (package_details[old_package_id][1] * package_details[old_package_id][2] * gst_value)); sum_gross_total = parseFloat(sum_gross_total + (package_details[old_package_id][1] * package_details[old_package_id][2] * total_gst)); } if (package_details[package_id][0] != "1") { // console.log('second if inside 3'); if (gst == 'Yes' || gst == '- None -') { invoice_line_items[invoice_line_items.length] = item_id; invoice_line_qty[invoice_line_qty.length] = qty; invoice_line_rate[invoice_line_rate.length] = rate; invoice_line_gst[invoice_line_gst.length] = 7; preview_html += '<tr><td>' + item_name + '</td><td>' + job_description_elem[i].value + '</td><td style="text-align: right;">' + qty + '</td><td style="text-align: right;">$' + parseFloat(rate).toFixed(2) + '</td><td style="text-align: right;">$' + parseFloat(qty * rate).toFixed(2) + '</td><td style="text-align: right;">$' + parseFloat(qty * rate * gst_value).toFixed(2) + '</td><td style="text-align: right;">$' + parseFloat(qty * rate * total_gst).toFixed(2) + '</td></tr>'; sum_total = parseFloat(sum_total + (qty * rate)); sum_gst = parseFloat(sum_gst + (qty * rate * gst_value)); sum_gross_total = parseFloat(sum_gross_total + (qty * rate * total_gst)); } else { invoice_line_items[invoice_line_items.length] = item_id; invoice_line_qty[invoice_line_qty.length] = qty; invoice_line_rate[invoice_line_rate.length] = rate; invoice_line_gst[invoice_line_gst.length] = 9; preview_html += '<tr><td>' + item_name + '</td><td>' + job_description_elem[i].value + '</td><td style="text-align: right;">' + qty + '</td><td style="text-align: right;">$' + parseFloat(rate).toFixed(2) + '</td><td style="text-align: right;">$' + parseFloat(qty * rate).toFixed(2) + '</td><td style="text-align: right;"></td><td style="text-align: right;">$' + parseFloat(qty * rate).toFixed(2) + '</td></tr>'; sum_total = parseFloat(sum_total + (qty * rate)); sum_gross_total = parseFloat(sum_gross_total + (qty * rate)); } } } } old_package_id = package_invoiceable_qty_elem[i].getAttribute("data-packageid"); } } if (!isNullorEmpty(old_package_id)) { if (package_details[old_package_id] != undefined) { if (package_details[old_package_id][0] != "1") { var font_color = ''; if (package_details[old_package_id][2] < 0) { font_color = 'color:red;'; } invoice_line_items[invoice_line_items.length] = 97; invoice_line_qty[invoice_line_qty.length] = package_details[old_package_id][1]; invoice_line_rate[invoice_line_rate.length] = package_details[old_package_id][2]; invoice_line_gst[invoice_line_gst.length] = 7; preview_html += '<tr style="' + font_color + '"><td>Discount</td><td></td><td style="text-align: right;">' + package_details[old_package_id][1] + '</td><td style="text-align: right;">$' + parseFloat(package_details[old_package_id][2]).toFixed(2) + '</td><td style="text-align: right;">$' + parseFloat(package_details[old_package_id][1] * package_details[old_package_id][2]).toFixed(2) + '</td><td style="text-align: right;">$' + parseFloat(package_details[old_package_id][1] * package_details[old_package_id][2] * gst_value).toFixed(2) + '</td><td style="text-align: right;">$' + parseFloat(package_details[old_package_id][1] * package_details[old_package_id][2] * total_gst).toFixed(2) + '</td></tr>'; sum_total = parseFloat(sum_total + (package_details[old_package_id][1] * package_details[old_package_id][2])); sum_gst = parseFloat(sum_gst + (package_details[old_package_id][1] * package_details[old_package_id][2] * gst_value)); sum_gross_total = parseFloat(sum_gross_total + (package_details[old_package_id][1] * package_details[old_package_id][2] * total_gst)); } } } var invoiceable_qty_elem = document.getElementsByClassName("invoiceable_qty"); var job_description_preview_elem = document.getElementsByClassName("job_description_preview"); for (var i = 0; i < invoiceable_qty_elem.length; ++i) { // var service_id = invoiceable_qty_elem[i].getAttribute("data-serviceid"); // var service_record = record.load({ type: 'customrecord_service', id: service_id }); // var item_id = service_record.getValue({ fieldId: 'custrecord_service_ns_item' }); // var item_name = search.lookupFields({ type: 'item', id: item_id, columns: 'itemid') }; var qty = invoiceable_qty_elem[i].value; var rate = invoiceable_qty_elem[i].getAttribute("data-rate"); var item_name = invoiceable_qty_elem[i].getAttribute("data-nsitem"); var item_id = invoiceable_qty_elem[i].getAttribute("data-nsitemid"); var gst = invoiceable_qty_elem[i].getAttribute("data-gst"); if (qty != 0) { var font_color = ''; if (item_id == 97) { font_color = 'color:red;'; } if (gst == 'Yes' || gst == '- None -') { invoice_line_items[invoice_line_items.length] = item_id; invoice_line_qty[invoice_line_qty.length] = qty; invoice_line_rate[invoice_line_rate.length] = rate; invoice_line_gst[invoice_line_gst.length] = 7; preview_html += '<tr style="' + font_color + '"><td>' + item_name + '</td><td>' + job_description_preview_elem[i].value + '</td><td style="text-align: right;">' + qty + '</td><td style="text-align: right;">$' + parseFloat(rate).toFixed(2) + '</td><td style="text-align: right;">$' + parseFloat(qty * rate).toFixed(2) + '</td><td style="text-align: right;">$' + parseFloat(qty * rate * gst_value).toFixed(2) + '</td><td style="text-align: right;">$' + parseFloat(qty * rate * total_gst).toFixed(2) + '</td></tr>'; sum_total = parseFloat(sum_total + (qty * rate)); sum_gst = parseFloat(sum_gst + (qty * rate * gst_value)); sum_gross_total = parseFloat(sum_gross_total + (qty * rate * total_gst)); } else { invoice_line_items[invoice_line_items.length] = item_id; invoice_line_qty[invoice_line_qty.length] = qty; invoice_line_rate[invoice_line_rate.length] = rate; invoice_line_gst[invoice_line_gst.length] = 9; preview_html += '<tr><td>' + item_name + '</td><td>' + job_description_preview_elem[i].value + '</td><td style="text-align: right;">' + qty + '</td><td style="text-align: right;">$' + parseFloat(rate).toFixed(2) + '</td><td style="text-align: right;">$' + parseFloat(qty * rate).toFixed(2) + '</td><td style="text-align: right;"></td><td style="text-align: right;">$' + parseFloat(qty * rate).toFixed(2) + '</td></tr>'; sum_total = parseFloat(sum_total + (qty * rate)); sum_gross_total = parseFloat(sum_gross_total + (qty * rate)); } } } if (admin_fees_log == true || admin_fees_log == 'true') { if (!isNullorEmpty(admin_fees_rate_elem)) { for (var i = 0; i < admin_fees_rate_elem.length; i++) { var rate = admin_fees_rate_elem[i].value; var qty = admin_fees_qty_elem[i].value; if (rate > 0 && qty > 0) { invoice_line_items[invoice_line_items.length] = 8729; invoice_line_qty[invoice_line_qty.length] = qty; invoice_line_rate[invoice_line_rate.length] = rate; invoice_line_gst[invoice_line_gst.length] = 7; preview_html += '<tr><td>Account Admin Fee</td><td></td><td style="text-align: right;">' + qty + '</td><td style="text-align: right;">$' + parseFloat(rate).toFixed(2) + '</td><td style="text-align: right;">$' + parseFloat(qty * rate).toFixed(2) + '</td><td style="text-align: right;">$' + parseFloat(qty * rate * gst_value).toFixed(2) + '</td><td style="text-align: right;">$' + parseFloat(qty * rate * total_gst).toFixed(2) + '</td></tr>'; sum_total = parseFloat(sum_total + (qty * rate)); sum_gst = parseFloat(sum_gst + (qty * rate * gst_value)); sum_gross_total = parseFloat(sum_gross_total + (qty * rate * total_gst)); } } } } var searchedJobsExtras = search.load({ id: 'customsearch_job_invoicing_summary', type: 'customrecord_job' }); searchedJobsExtras.filters.push(search.createFilter({ name: 'custrecord_job_date_inv_finalised', operator: search.Operator.ISEMPTY })); if (!isNullorEmpty(currentScript.getValue({ fieldId: 'start_date' })) && !isNullorEmpty(currentScript.getValue({ fieldId: 'end_date' }))) { searchedJobsExtras.filters.push(search.createFilter({ name: 'custrecord_job_date_scheduled', operator: search.Operator.ONORAFTER, values: currentScript.getValue({ fieldId: 'start_date' }) })); searchedJobsExtras.filters.push(search.createFilter({ name: 'custrecord_job_date_scheduled', operator: search.Operator.ONORBEFORE, values: currentScript.getValue({ fieldId: 'end_date' }) })); } var resultSetExtras = searchedJobsExtras.run(); var next_customer = null; var result = resultSetExtras.getRange({ start: 0, end: 1 }) if (!isNullorEmpty(result) && result.length != 0) { next_customer = result[0].getValue({ name: 'internalid', join: 'CUSTRECORD_JOB_CUSTOMER', summary: search.Summary.GROUP }); } preview_html += '<tr class="success" style="font-weight: bold;font-size: small;"><td>TOTAL</td><td></td><td></td><td></td><td style="text-align: right;">$' + parseFloat($('.total_value').val()).toFixed(2) + '</td><td style="text-align: right;">$' + sum_gst.toFixed(2) + '</td><td style="text-align: right;">$' + sum_gross_total.toFixed(2) + '</td></tr></tbody></table>'; var footer_html = ''; var result = finalise_date(currentScript.getValue({ fieldId: 'start_date' })); if ((global_locked == 'yes' || result == false) && role == 1000 && zee != 6 && zee != 425904) { footer_html = '<span class="col-sm-10"><b>"Create Custom Invoice"</b> functionality will only be available on or after the last day of the month</span><button type="button" class="btn btn-default" data-dismiss="modal">Close</button>'; } else { footer_html = '<a href="https://1048144.app.netsuite.com/app/accounting/transactions/custinvc.nl?compid=1048144&cf=116&entity=' + global_customer + '&itemids=' + invoice_line_items.toString() + '&qty=' + invoice_line_qty.toString() + '&rate=' + invoice_line_rate.toString() + '&gst=' + invoice_line_gst.toString() + '&next_customer=' + next_customer + '&start_date=' + currentScript.getValue({ fieldId: 'start_date' }) + '&end_date=' + currentScript.getValue({ fieldId: 'end_date' }) + '" class="btn btn-primary" value="">Create Custom Invoice</a><button type="button" class="btn btn-default" data-dismiss="modal">Close</button>'; } $('.modal .modal-header').html('<div class="form-group"><h4><label class="control-label" for="inputError1">Invoice Preview</label></h4></div>'); $('.modal .modal-footer').html(footer_html); $('.modal .modal-body').html(""); $('.modal .modal-body').html(preview_html); $('.modal').modal("show"); }); /** * [description] - To update the Admin Fees Total when the rate is changed */ $(document).on('blur', '.admin_fees_rate', function(e) { var admin_fees = $(this).val(); var serviceid = $(this).attr('data-serviceid'); var jobid = $(this).attr('data-jobid'); var old_admin_fees = $(this).attr('data-oldvalue'); if (admin_fees != old_admin_fees) { if (!isNullorEmpty(serviceid)) { deleted_service_ids[deleted_service_ids.length] = serviceid; $(this).attr('data-serviceid', null); if (!isNullorEmpty(jobid)) { deleted_job_ids[deleted_job_ids.length] = jobid; $(this).attr('data-jobid', null); } } var admin_fees_qty = $(this).closest('tr').find('.admin_fees_qty').val(); var admin_fees_total = (parseFloat(admin_fees) * parseFloat(admin_fees_qty)); $(this).closest('tr').find('.admin_fees_total').val(admin_fees_total); updateTotal(); } }); /** * [description] - To update the Admin Fees Total when the qty is changed */ $(document).on('blur', '.admin_fees_qty', function(e) { var admin_fees_qty = $(this).val(); var admin_fees = $(this).closest('tr').find('.admin_fees_rate').val(); var admin_fees_total = (parseFloat(admin_fees) * parseFloat(admin_fees_qty)); $(this).closest('tr').find('.admin_fees_total').val(admin_fees_total); updateTotal(); }); /** * [description] - Css and toggle between the On/Off Button for Admin Fee */ $('.btn-toggle').click(function() { // alert(currentScript.getValue({ fieldId: 'admin_fees_not_applicable' })); if (global_locked != 'yes' && currentScript.getValue({ fieldId: 'admin_fees_not_applicable' }) != '1') { $(this).find('.btn').toggleClass('active'); if ($(this).find('.btn-success').size() > 0) { $(this).find('.btn').toggleClass('btn-success'); } $(this).find('.btn').toggleClass('btn-default'); } return false; }); /** * [description] - To show the Admin Fee Row */ $('.admin_fees_on').click(function() { $('.admin_fees_row').show(); $('.no_extras_class').hide(); var jobid = $('.admin_fees_rate').attr('data-jobid'); var serviceid = $('.admin_fees_rate').attr('data-serviceid'); if (isNullorEmpty(jobid) && isNullorEmpty(serviceid)) { $('.admin_fees_rate').val(9); $('.admin_fees_qty').val(1); $('.admin_fees_total').val(9); } else { var service_old_record = record.load({ type: 'customrecord_service', id: serviceid, }); var admin_fees = parseFloat(service_old_record.getValue({ fieldId: 'custrecord_service_price' })); var admin_fees_qty = 1; if (!isNullorEmpty(jobid)) { var job_old_record = record.load({ type: 'customrecord_job', id: jobid, }); admin_fees_qty = parseFloat(job_old_record.getValue({ fieldId: 'custrecord_job_extras_qty' })); } $('.admin_fees_rate').val(admin_fees); $('.admin_fees_qty').val(admin_fees_qty); $('.admin_fees_total').val((admin_fees * admin_fees_qty)); } admin_fees_log = true; updateTotal(); }); /** * [description] - To hide the Admin Fee Row */ $('.admin_fees_off').click(function() { $('.admin_fees_row').hide(); // $('.admin_fees_rate').val(0); // $('.admin_fees_qty').val(0); var jobid = $('.admin_fees_rate').attr('data-jobid'); var serviceid = $('.admin_fees_rate').attr('data-serviceid'); // $('.admin_fees_total').val(0); admin_fees_log = false; if (!isNullorEmpty(jobid)) { deleted_job_ids[deleted_job_ids.length] = jobid; } if (!isNullorEmpty(serviceid)) { deleted_service_ids[deleted_service_ids.length] = serviceid; } updateTotal(); }); } //ON CLICK OF THE APP COMPELTED QTY function onclick_StatusComplete(internal_id, service_rate, service_id, job_group, status, category, package_id, assign_packge) { //setReviewDate(internal_id); //REVIEW DATE IS SET FOR ALL THE JOBS var currentScript = currentRecord.get(); if (status == null) { var upload_url = baseURL + url.resolveScript({ scriptId: 'customscript_sl_job_page_2', deploymentId: 'customdeploy_job_page_2' }) + '&customer_id=' + internal_id + '&rate=' + service_rate + '&service_id=' + service_id + '&job_group=' + job_group + '&category=' + category + '&package=' + package_id + '&start_date=' + currentScript.getValue({ fieldId: 'start_date' }) + '&end_date=' + currentScript.getValue({ fieldId: 'end_date' }) + '&assign_packge=' + assign_packge + '&locked=' + global_locked + '&sc=' + currentScript.getValue({ fieldId: 'scid' }) + '&zee=' + currentScript.getValue({ fieldId: 'zee_id' }); window.open(upload_url, "_self", "height=750,width=650,modal=yes,alwaysRaised=yes"); } else { var upload_url = baseURL + url.resolveScript({ scriptId: 'customscript_sl_job_page_2', deploymentId: 'customdeploy_job_page_2' }) + '&customer_id=' + internal_id + '&rate=' + service_rate + '&service_id=' + service_id + '&job_group=' + job_group + '&status=' + status + '&category=' + category + '&package=' + package_id + '&start_date=' + currentScript.getValue({ fieldId: 'start_date' }) + '&end_date=' + currentScript.getValue({ fieldId: 'end_date' }) + '&assign_packge=' + assign_packge + '&locked=' + global_locked + '&sc=' + currentScript.getValue({ fieldId: 'scid' }) + '&zee=' + currentScript.getValue({ fieldId: 'zee_id' }); window.open(upload_url, "_self", "height=750,width=650,modal=yes,alwaysRaised=yes"); } } //ON CLICK OF THE APP PARTIALLY COMPLETED QTY function onclick_StatusPartial(internal_id, service_rate, service_id, job_group, status, category, package_id) { var currentScript = currentRecord.get(); //setReviewDate(internal_id); var upload_url = baseURL + url.resolveScript({ scriptId: 'customscript_sl_job_page_2', deploymentId: 'customdeploy_job_page_2' }) + '&customer_id=' + internal_id + '&rate=' + service_rate + '&service_id=' + service_id + '&job_group=' + job_group + '&status=' + status + '&category=' + category + '&package=' + package_id + '&start_date=' + currentScript.getValue({ fieldId: 'start_date' }) + '&end_date=' + currentScript.getValue({ fieldId: 'end_date' }) + '&locked=' + global_locked + '&sc=' + currentScript.getValue({ fieldId: 'scid' }) + '&zee=' + currentScript.getValue({ fieldId: 'zee_id' }); window.open(upload_url, "_self", "height=750,width=650,modal=yes,alwaysRaised=yes"); } //ON CLICK OF THE APP INCOMPLETE QTY function onclick_StatusIncomplete(internal_id, service_rate, service_id, job_group, status, category, package_id) { var currentScript = currentRecord.get(); // setReviewDate(internal_id); var upload_url = baseURL + url.resolveScript({ scriptId: 'customscript_sl_job_page_2', deploymentId: 'customdeploy_job_page_2' }) + '&customer_id=' + internal_id + '&rate=' + service_rate + '&service_id=' + service_id + '&job_group=' + job_group + '&status=' + status + '&category=' + category + '&package=' + package_id + '&start_date=' + currentScript.getValue({ fieldId: 'start_date' }) + '&end_date=' + currentScript.getValue({ fieldId: 'end_date' }) + '&locked=' + global_locked + '&sc=' + currentScript.getValue({ fieldId: 'scid' }) + '&zee=' + currentScript.getValue({ fieldId: 'zee_id' }); window.open(upload_url, "_self", "height=750,width=650,modal=yes,alwaysRaised=yes"); } //ON CLICK OF THE BACK TO SUMMARY BUTTON function onclick_summaryPage() { var currentScript = currentRecord.get(); var upload_url = baseURL + url.resolveScript({ scriptId: 'customscript_sl_summary_page_2', deploymentId: 'customdeploy_summary_page_2' }) + '&start_date=' + currentScript.getValue({ fieldId: 'start_date' }) + '&end_date=' + currentScript.getValue({ fieldId: 'end_date' }) + '&zee=' + currentScript.getValue({ fieldId: 'zee_id' }); window.open(upload_url, "_self", "height=750,width=650,modal=yes,alwaysRaised=yes"); } function onclick_reset() { window.location.href = window.location.href; } //ON CLICK OF ADD SERVICES BUTTON function addService(service_cat) { var currentScript = currentRecord.get(); //setReviewDate(currentScript.getValue({ fieldId: 'customer_id')) }; var upload_url = baseURL + url.resolveScript({ scriptId: 'customscript_sl_add_service_2', deploymentId: 'customdeploy_sl_add_service_2' }) + '&custid=' + currentScript.getValue({ fieldId: 'customer_id' }) + '&unlayered=T&service_cat=' + service_cat + '&start_date=' + currentScript.getValue({ fieldId: 'start_date' }) + '&end_date=' + currentScript.getValue({ fieldId: 'end_date' }) + '&locked=' + global_locked + '&sc=' + currentScript.getValue({ fieldId: 'scid' }) + '&zee=' + currentScript.getValue({ fieldId: 'zee_id' }); window.open(upload_url, "_self", "height=750,width=650,modal=yes,alwaysRaised=yes"); } //SET REVIEW DATE FUNCTION function setReviewDate(internal_id) { var currentScript = currentRecord.get(); var searched_jobs = search.load({ id: 'customsearch_inv_review_jobs_uninv', type: 'customrecord_job' }); searched_jobs.filters.push(search.createFilter({ name: 'custrecord_job_customer', operator: search.Operator.IS, values: internal_id, })); var resultSet = searched_jobs.run(); resultSet.each(function(searchResult) { var job_record = record.load({ type: 'customrecord_job', id: searchResult.getValue('internalid') }); job_record.setValue({ fieldId: 'custrecord_job_date_reviewed', value: getDate() }); job_record.save({ enableSourcing: true, ignoreMandatoryFields: true }) return true; }); return true; } function onclick_AssignPackage(internal_id, service_rate, service_id, job_group, status, category, package_id) { var currentScript = currentRecord.get(); var upload_url = baseURL + url.resolveScript({ scriptId: 'customscript_sl_assign_package_2', deploymentId: 'customdeploy_sl_assign_package_2' }) + '&customer_id=' + internal_id + '&service_id=' + service_id + '&job_group=' + job_group + '&status=' + status + '&rate=' + service_rate + '&category=' + category + '&package=' + package_id + '&start_date=' + currentScript.getValue({ fieldId: 'start_date' }) + '&end_date=' + currentScript.getValue({ fieldId: 'end_date' }); window.open(upload_url, "_self", "height=750,width=650,modal=yes,alwaysRaised=yes"); } function submit_package() { var currentScript = currentRecord.get(); var url = baseURL + url.resolveScript({ scriptId: 'customscript_sl_services_main_page_2', deploymentId: 'customdeploy_sl_services_main_page_2' }) + '&customer_id=' + currentScript.getValue({ fieldId: 'customer_id' }) + '&start_date=' + currentScript.getValue({ fieldId: 'start_date' }) + '&end_date=' + currentScript.getValue({ fieldId: 'end_date' }); window.open(url, "_self", "height=680,width=640,modal=yes,alwaysRaised=yes"); } //FUNCTION TO CALCULATE THE TOTAL INVOICEABLE AMOUNT FOR EACH AND EVERY SERVICE AND EXTRA function updateServiceAmount(rate, qty) { return (rate * qty); } function onclick_review() { var currentScript = currentRecord.get(); currentScript.setValue({ fieldId: 'review_button', value: 'T' }); $('#submitter').trigger('click'); } //ON CLICK OF NEXT CUSTOMER BUTTON function saveRecord(context) { var currentScript = currentRecord.get(); var customer_id = currentScript.getValue({ fieldId: 'customer_id' }); //WS Edit: Get Zee Customer from hidden field in Suitelet var zee_cust = parseInt(currentScript.getValue({ fieldId: 'zee_cust' })); //WS Edit: Can be deferred to Admin Fee section //var customerRec = record.load({ type: 'customer', id: customer_id }); //WS Edit: zee (from global variable) instead of franchisee //var franchisee = customerRec.getValue({ fieldId: 'partner' }); var franchisee = parseInt(zee); /*-----------------Derive CommReg for new Service Creation-----------------*/ var commReg_search = search.load({ id: 'customsearch_service_commreg_assign', type: 'customrecord_commencement_register' }); //WS Edit: filterExpression unsets existing filter commReg_search.filters.push(search.createFilter({ name: 'custrecord_customer', operator: search.Operator.ANYOF, values: customer_id } )); commReg_search.filters.push(search.createFilter({ name: 'custrecord_franchisee', operator: search.Operator.ANYOF, values: franchisee } )); var comm_reg_results = commReg_search.run(); var count_commReg = 0; var commReg = null; comm_reg_results.each(function(searchResult) { count_commReg++; /** * [if description] - Only the latest comm Reg needs to be assigned */ if (count_commReg == 1) { commReg = searchResult.getValue('internalid'); } /** * [if description] - if more than one Comm Reg, error mail is sent */ if (count_commReg > 1) { //WS Comment: Needs error error.create({ message: 'More than 1 Active CommReg', name: 'Customer ID: ' + customer_id, }); return false; } return true; }); /*-----------------NS Qty-----------------*/ //Set the jobs for NS Qty items var package_invoiceable_qty_elem = document.getElementsByClassName("package_netsuite_qty"); var job_description_elem = document.getElementsByClassName("job_description"); var single_job_description_elem = document.getElementsByClassName("single_job_description"); var service_id_array = []; var service_descp_array = []; var extra_service_id = []; var extra_qty = []; var extra_rate = []; var delete_job_id = []; var delete_service_id = []; var new_jobs_service_id = []; var new_jobs_rate = []; var new_jobs_qty = []; var new_jobs_cat = []; var new_jobs_descp = []; var new_jobs_package_id = []; var new_jobs_single_line = []; var new_service_type = []; var new_service_name = []; var new_service_price = []; var new_service_qty = []; var new_service_package_id = []; var new_service_customer = []; var new_service_comm_reg = []; var new_service_discount_type = []; var new_service_single_line = []; /*-----------------NS Qty: Get Field Values from Suitelet-----------------*/ for (var i = 0; i < package_invoiceable_qty_elem.length; ++i) { console.log('saveRecord loop ' + i) var initial_changed_qty = package_invoiceable_qty_elem[i].value; console.log(initial_changed_qty) var initial_load_qty = package_invoiceable_qty_elem[i].getAttribute("data-oldqty"); console.log(initial_load_qty) var service_id = package_invoiceable_qty_elem[i].getAttribute("data-serviceid"); console.log(service_id) var service_rate = package_invoiceable_qty_elem[i].getAttribute("data-rate"); console.log(service_rate) var service_cat = package_invoiceable_qty_elem[i].getAttribute("data-servicecat"); console.log(service_cat) var package = package_invoiceable_qty_elem[i].getAttribute("data-packageid"); console.log(package) var job_id = package_invoiceable_qty_elem[i].getAttribute("data-netsuitejob"); console.log(job_id) var default_ns_qty = package_invoiceable_qty_elem[i].getAttribute("default-value"); console.log(default_ns_qty) var default_description; var default_single_line; var single_line; var description; console.log(job_description_elem[i]) if (!isNullorEmpty(job_description_elem[i])) { if (!isNullorEmpty(job_description_elem[i].value)) { var default_description = job_description_elem[i].getAttribute("default-value"); console.log(default_description) var default_single_line = job_description_elem[i].getAttribute("default-singleline"); console.log(default_single_line) var single_line = job_description_elem[i].getAttribute("data-singleline"); console.log(single_line) service_id_array.push(job_description_elem[i].getAttribute("data-serviceid")); console.log(job_description_elem[i].getAttribute("data-serviceid")) service_descp_array.push(job_description_elem[i].value); description = job_description_elem[i].value; } } // single_line.push(job_description_elem[i].getAttribute("data-singleline")) var jobs_to_create = parseFloat(initial_changed_qty); /*-----------------Package: Identify and Create Jobs-----------------*/ if (description != default_description || default_ns_qty != initial_changed_qty) { if (jobs_to_create > 0 || !isNullorEmpty(description)) { if (service_id != 242 && service_id != 243 && service_id != 1904 && service_id != 241) { if (isNullorEmpty(job_id) || job_id == 'null') { if (zee == zee_cust) { createJobRecord(customer_id, service_id, service_rate, jobs_to_create, description, service_cat, package, single_line, null); } else { new_jobs_service_id[new_jobs_service_id.length] = service_id; new_jobs_rate[new_jobs_rate.length] = service_rate; new_jobs_qty[new_jobs_qty.length] = jobs_to_create; new_jobs_cat[new_jobs_cat.length] = service_cat; new_jobs_descp[new_jobs_descp.length] = description; new_jobs_single_line[new_jobs_single_line.length] = single_line; if (!isNullorEmpty(package)) { new_jobs_package_id[new_jobs_package_id.length] = package; } } } else { updateJobRecord(job_id, null, jobs_to_create, description, null, null, null, null); } } else { extra_service_id[extra_service_id.length] = service_id; extra_qty[extra_qty.length] = jobs_to_create; extra_rate[extra_rate.length] = service_rate; } } else if (jobs_to_create == 0 && isNullorEmpty(description)) { if (!isNullorEmpty(job_id) && job_id != 'null') { delete_job_id[delete_job_id.length] = job_id; // nlapiDeleteRecord('customrecord_job', job_id); } } } } var discount_type_elem = document.getElementsByClassName("discount_type"); var discount_value_elem = document.getElementsByClassName("discount_value"); var discount_qty_elem = document.getElementsByClassName("discount_qty"); var total_discount_elem = document.getElementsByClassName("total_discount_value"); var invoice_single_line_elem = document.getElementsByClassName("invoice_single_line"); var total_package_value = document.getElementsByClassName("total_package_value"); var single_line_hidden = document.getElementsByClassName("single_line_hidden"); var fixed_discount_value = document.getElementsByClassName("fixed_discount_value"); /*-----------------Package: Identify and Create Discount Services + Jobs-----------------*/ if (!isNullorEmpty(total_discount_elem)) { for (var i = 0; i < total_discount_elem.length; ++i) { var job_id = total_discount_elem[i].getAttribute('data-netsuitejob'); var default_description_value = single_job_description_elem[i].getAttribute('default-value'); var description_value = single_job_description_elem[i].value; var default_total_discount_value = total_discount_elem[i].getAttribute('default-value'); var single_line_hidden_default = single_line_hidden[i].getAttribute('default-singleline'); var total_discount_value = total_discount_elem[i].value; var single_line_hidden_value = single_line_hidden[i].value; if (isNullorEmpty(single_line_hidden_value)) { single_line_hidden_value = single_line_hidden_default; } if (isNullorEmpty(job_id) || job_id == 'null') { if (total_discount_elem[i].hasAttribute("data-package")) { var package_id = total_discount_elem[i].getAttribute('data-package'); } var package_record = record.load({ type: 'customrecord_service_package', id: package_id, }); var discount_period = package_record.getValue({ fieldId: 'custrecord_service_package_disc_period' }); if (zee == zee_cust) { var service_price; if (discount_period == 3) { service_price = total_package_value[i].value; } else { if (single_line_hidden_value == 1) { service_price = fixed_discount_value[i].value; } else { service_price = discount_value_elem[i].value; } } // alert(package_id); var service_id = createServiceRecord(17, 'Discount', service_price, customer_id, commReg, package_id); var service_rate; var service_qty; var discount_type; if (discount_period == 3) { service_rate = total_package_value[i].value; service_qty = 1; } else { if (single_line_hidden_value == 1) { service_rate = fixed_discount_value[i].value; } else { service_rate = discount_value_elem[i].value; } service_qty = discount_qty_elem[i].value; if (!isNullorEmpty(discount_type_elem[i])) { if (isNullorEmpty(discount_type_elem[i].getAttribute('data-value'))) { discount_type = null; } else { discount_type = discount_type_elem[i].getAttribute('data-value'); } } } createJobRecord(customer_id, service_id, service_rate, service_qty, description, 2, package_id, invoice_single_line_elem[i].value, discount_type); } else { if (discount_period == 3) { new_service_price[new_service_price.length] = total_package_value[i].value; new_service_qty[new_service_qty.length] = 1; } else { if (single_line_hidden_value == 1) { new_service_price[new_service_price.length] = fixed_discount_value[i].value; } else { new_service_price[new_service_price.length] = discount_value_elem[i].value; } new_service_qty[new_service_qty.length] = discount_qty_elem[i].value; if (!isNullorEmpty(discount_type_elem[i])) { if (isNullorEmpty(discount_type_elem[i].getAttribute('data-value'))) { new_service_discount_type[new_service_discount_type.length] = null; } else { new_service_discount_type[new_service_discount_type.length] = discount_type_elem[i].getAttribute('data-value'); } } } if (!isNullorEmpty(package_id)) { new_service_package_id[new_service_package_id.length] = package_id; } if (!isNullorEmpty(commReg)) { new_service_comm_reg[new_service_comm_reg.length] = commReg; } new_service_customer[new_service_customer.length] = customer_id; new_service_type[new_service_type.length] = 17; new_service_name[new_service_name.length] = 'Discount'; new_service_single_line[new_service_single_line.length] = invoice_single_line_elem[i].value; } } else { var job_new_record = record.load({ type: 'customrecord_job', id: job_id }); var service_id = job_new_record.getValue({ fieldId: 'custrecord_job_service' }); if (total_discount_elem[i].hasAttribute("data-package")) { var package_id = total_discount_elem[i].getAttribute('data-package'); } var package_record = record.load({ type: 'customrecord_service_package', id: package_id }); var discount_period = package_record.getValue({ fieldId: 'custrecord_service_package_disc_period' }); var service_record = record.load({ type: 'customrecord_service', id: service_id }); if (discount_period == 3) { service_record.setValue({ fieldId: 'custrecord_service_price', value: total_package_value[i].value }); } else { if (single_line_hidden_value == 1) { service_record.setValue({ fieldId: 'custrecord_service_price', value: fixed_discount_value[i].value }); } else { service_record.setValue({ fieldId: 'custrecord_service_price', value: discount_value_elem[i].value }); } } if (!isNullorEmpty(package_id)) { service_record.setValue({ fieldId: 'custrecord_service_package', value: package_id }); } service_record.save({ enableSourcing: true, ignoreMandatoryFields: true }); var service_rate; var service_qty; var discount_type; if (discount_period == 3) { service_rate = total_package_value[i].value; service_qty = 1; } else { if (single_line_hidden_value == 1) { service_rate = fixed_discount_value[i].value; } else { service_rate = discount_value_elem[i].value; } service_qty = discount_qty_elem[i].value; if (!isNullorEmpty(discount_type_elem[i])) { if (isNullorEmpty(discount_type_elem[i].getAttribute('data-value'))) { discount_type = null; } else { discount_type = discount_type_elem[i].getAttribute('data-value'); } } } updateJobRecord(job_id, service_rate, service_qty, single_job_description_elem[i].value, null, package_id, invoice_single_line_elem[i].value, discount_type); } } } /*-----------------Admin Fees-----------------*/ //WS Edit: Only allow adjustments on Admin fee to be made by Customer Zee. Other Zee cannot update Admin fee arrangements. if (zee == zee_cust) { var customerRec = record.load({ type: 'customer', id: customer_id }); var admin_fees_rate_elem = document.getElementsByClassName("admin_fees_rate"); var admin_fees_qty_elem = document.getElementsByClassName("admin_fees_qty"); /*-----------------Admin Fees: NO-----------------*/ if (admin_fees_log == false || admin_fees_log == 'false') { if (!isNullorEmpty(deleted_service_ids)) { // alert(deleted_service_ids); for (var i = 0; i < deleted_service_ids.length; i++) { var searchedJobsResult = adminFeesServiceCheck(customer_id, deleted_service_ids[i], deleted_job_ids); if (isNullorEmpty(searchedJobsResult)) { delete_service_id[delete_service_id.length] = deleted_service_ids[i]; } else { if (searchedJobsResult.length == 1) { var service_old_record = record.load({ type: 'customrecord_service', id: deleted_service_ids }[i]); service_old_record.setValue({ fieldId: 'isinactive', value: 'T' }); service_old_record.save({ enableSourcing: true, ignoreMandatoryFields: true }); // delete_service_id[delete_service_id.length] = deleted_service_ids[i]; } } } } if (!isNullorEmpty(deleted_job_ids)) { for (var i = 0; i < deleted_job_ids.length; i++) { delete_job_id[delete_job_id.length] = deleted_job_ids[i]; // nlapiDeleteRecord('customrecord_job', deleted_job_ids[i]); } } $('.admin_fees_rate').val(0); $('.admin_fees_qty').val(0); customerRec.setValue({ fieldId: 'custentity_admin_fees', value: null }); } console.log('Before admin') /*-----------------Admin Fees: YES-----------------*/ /** * To capture the Admin Fee information */ if (admin_fees_log == true || admin_fees_log == 'true') { for (var i = 0; i < admin_fees_rate_elem.length; ++i) { var jobid = (admin_fees_rate_elem[i].getAttribute("data-jobid")); var serviceid = (admin_fees_rate_elem[i].getAttribute("data-serviceid")); var old_admin_fees = admin_fees_rate_elem[i].getAttribute("data-oldvalue"); var admin_fees = admin_fees_rate_elem[i].value; var admin_qty = admin_fees_qty_elem[i].value; if (isNullorEmpty(admin_fees) || admin_fees == 0 || isNullorEmpty(admin_qty) || admin_qty == 0) { customerRec.setValue({ fieldId: 'custentity_admin_fees', value: null }); if (!isNullorEmpty(jobid)) { delete_job_id[delete_job_id.length] = jobid; // nlapiDeleteRecord('customrecord_job', jobid); } if (!isNullorEmpty(serviceid)) { var searchedJobsResult = adminFeesServiceCheck(customer_id, serviceid, delete_job_id); if (isNullorEmpty(searchedJobsResult)) { delete_service_id[delete_service_id.length] = serviceid; } else { if (searchedJobsResult.length == 1) { var service_old_record = record.load({ type: 'customrecord_service', id: serviceid }); service_old_record.setValue({ fieldId: 'isinactive', value: 'T' }); service_old_record.save({ enableSourcing: true, ignoreMandatoryFields: true }); // delete_service_id[delete_service_id.length] = deleted_service_ids[i]; } } } } else { if (!isNullorEmpty(deleted_service_ids)) { for (var i = 0; i < deleted_service_ids.length; i++) { var searchedJobsResult = adminFeesServiceCheck(customer_id, deleted_service_ids[i], deleted_job_ids); if (isNullorEmpty(searchedJobsResult)) { delete_service_id[delete_service_id.length] = deleted_service_ids[i]; } else { if (searchedJobsResult.length == 1) { var service_old_record = record.load({ type: 'customrecord_service', id: deleted_service_ids }[i]); service_old_record.setValue({ fieldId: 'isinactive', value: 'T' }); service_old_record.save({ enableSourcing: true, ignoreMandatoryFields: true }); // delete_service_id[delete_service_id.length] = deleted_service_ids[i]; } } } } if (!isNullorEmpty(deleted_job_ids)) { for (var i = 0; i < deleted_job_ids.length; i++) { delete_job_id[delete_job_id.length] = deleted_job_ids[i]; // nlapiDeleteRecord('customrecord_job', deleted_job_ids[i]); } } if (isNullorEmpty(serviceid)) { //Put code to check if the Admin Fee Service with the Same Price exists or not. If it exists and is Inactive, activate it and update. If no service exists, create a new service var searchedServicesResult = searchAdminFeesService(customer_id, admin_fees); if (isNullorEmpty(searchedServicesResult)) { var service_record = record.create({ type: 'customrecord_service', isDynamic: true, }); service_record.setValue({ fieldId: 'custrecord_service', value: 22 }); service_record.setValue({ fieldId: 'name', value: search.lookupFields({ type: 'customrecord_service_type', id: 22, columns: 'name' }) }); //WS Edit: cannot set franchisee in Client. //service_record.setValue({ fieldId: 'custrecord_service_franchisee', value: zee); service_record.setValue({ fieldId: 'custrecord_service_customer', value: customer_id }); //WS } Edit: Need to deal with null commReg. //service_record.setValue({ fieldId: 'custrecord_service_comm_reg', value: commReg); if (!isNullorEmpty(commReg)) { service_record.setValue({ fieldId: 'custrecord_service_comm_reg', value: commReg }); } } else { if (searchedServicesResult.length == 1) { var service_record = record.load({ type: 'customrecord_service', id: searchedServicesResult[0].getValue('internalid') }); service_record.setValue({ fieldId: 'isinactive', value: 'F' }); } else { //Throw Error } } } else { var service_record = record.load({ type: 'customrecord_service', id: serviceid }); } service_record.setValue({ fieldId: 'custrecord_service_price', value: admin_fees }); var new_service_id = service_record.save({ enableSourcing: true, ignoreMandatoryFields: true }); if (isNullorEmpty(jobid)) { var job_record = record.create({ type: 'customrecord_job', isDynamic: true, }); job_record.setValue({ fieldId: 'custrecord_job_status', value: 3 }); job_record.setValue({ fieldId: 'custrecord_job_invoiceable', value: 1 }); job_record.setValue({ fieldId: 'custrecord_job_date_reviewed', value: getDate() }); job_record.setValue({ fieldId: 'custrecord_job_source', value: 5 }); job_record.setValue({ fieldId: 'custrecord_job_service_category', value: 2 }); job_record.setValue({ fieldId: 'custrecord_job_customer', value: customer_id }); // } job_record.setValue({ fieldId: 'custrecord_job_franchisee', value: zee); } else { var job_record = record.load({ type: 'customrecord_job', id: jobid }); } job_record.setValue({ fieldId: 'custrecord_job_service', value: new_service_id }); job_record.setValue({ fieldId: 'custrecord_job_extras_qty', value: admin_qty }); job_record.setValue({ fieldId: 'custrecord_job_service_price', value: admin_fees}); job_record.setValue({ fieldId: 'custrecord_job_date_scheduled', value: currentScript.getValue({ fieldId: 'end_date' }) }); job_record.save({ enableSourcing: true, ignoreMandatoryFields: true }); customerRec.setValue({ fieldId: 'custentity_admin_fees', value: admin_fees }); } } } console.log('after admin') customerRec.setValue({ fieldId: 'custentity11', value: $('.customer_po').val() }); customerRec.save({ enableSourcing: true, ignoreMandatoryFields: true }); } var extra_service_string = extra_service_id.join(); var extra_qty_string = extra_qty.join(); var extra_rate_string = extra_rate.join(); console.log(delete_job_id); var unique_delete_jobs = removeDuplicateUsingFilter(delete_job_id); var unique_delete_services = removeDuplicateUsingFilter(delete_service_id); console.log(unique_delete_jobs); var delete_job_id_string = unique_delete_jobs.join(); var delete_service_id_string = unique_delete_services.join(); var new_jobs_service_id_string = new_jobs_service_id.join(); var new_jobs_rate_string = new_jobs_rate.join(); var new_jobs_qty_string = new_jobs_qty.join(); var new_jobs_cat_string = new_jobs_cat.join(); var new_jobs_descp_string = new_jobs_descp.join(); var new_jobs_package_id_string = new_jobs_package_id.join(); var new_jobs_single_line_string = new_jobs_single_line.join(); var new_service_type_string = new_service_type.join(); var new_service_name_string = new_service_name.join(); var new_service_price_string = new_service_price.join(); var new_service_qty_string = new_service_qty.join(); var new_service_discount_type_string = new_service_discount_type.join(); var new_service_package_id_string = new_service_package_id.join(); var new_service_customer_string = new_service_customer.join(); var new_service_comm_reg_string = new_service_comm_reg.join(); var new_service_single_line_string = new_service_single_line.join(); // alert(delete_service_id); currentScript.setValue({ fieldId: 'extra_service_string', value: extra_service_string }); currentScript.setValue({ fieldId: 'extra_qty_string', value: extra_qty_string }); currentScript.setValue({ fieldId: 'extra_rate_string', value: extra_rate_string }); currentScript.setValue({ fieldId: 'delete_job_id_string', value: delete_job_id_string }); currentScript.setValue({ fieldId: 'delete_service_id_string', value: delete_service_id_string }); currentScript.setValue({ fieldId: 'new_jobs_service_id_string', value: new_jobs_service_id_string }); currentScript.setValue({ fieldId: 'new_jobs_rate_string', value: new_jobs_rate_string }); currentScript.setValue({ fieldId: 'new_jobs_qty_string', value: new_jobs_qty_string }); currentScript.setValue({ fieldId: 'new_jobs_cat_string', value: new_jobs_cat_string }); currentScript.setValue({ fieldId: 'new_jobs_descp_string', value: new_jobs_descp_string }); currentScript.setValue({ fieldId: 'new_jobs_package_id_string', value: new_jobs_package_id_string }); currentScript.setValue({ fieldId: 'new_jobs_single_line_string', value: new_jobs_single_line_string }); currentScript.setValue({ fieldId: 'new_service_type_string', value: new_service_type_string }); currentScript.setValue({ fieldId: 'new_service_name_string', value: new_service_name_string }); currentScript.setValue({ fieldId: 'new_service_price_string', value: new_service_price_string }); currentScript.setValue({ fieldId: 'new_service_qty_string', value: new_service_qty_string }); currentScript.setValue({ fieldId: 'new_service_discount_type_string', value: new_service_discount_type_string }); currentScript.setValue({ fieldId: 'new_service_package_id_string', value: new_service_package_id_string }); currentScript.setValue({ fieldId: 'new_service_customer_string', value: new_service_customer_string }); currentScript.setValue({ fieldId: 'new_service_comm_reg_string', value: new_service_comm_reg_string }); currentScript.setValue({ fieldId: 'new_service_single_line_string', value: new_service_single_line_string }); return true; } function adminFeesServiceCheck(customer_id, service_id, deleted_job_ids) { var searched_jobs = search.load({ id: 'customrecord_job', type: 'customsearch_job_inv_review_all' }); searched_jobs.filters.push(search.createFilter({ name: 'custrecord_job_customer', operator: search.Operator.IS, values: customer_id })); searched_jobs.filters.push(search.createFilter({ name: 'custrecord_job_service', operator: search.Operator.IS, values: service_id })); if (!isNullorEmpty(deleted_job_ids)) { searched_jobs.filters.push(search.createFilter({ name: 'internalid', operator: search.Operator.NONEOF, values: deleted_job_ids })); } var resultSet = searched_jobs.run(); var searchedJobsResult = resultSet.getRange({ start: 0, end: 1 }); return searchedJobsResult; } function searchAdminFeesService(customer_id, admin_fees) { var searched_services = search.load({ id: 'customrecord_service', type: 'customsearch_aic_review_services' }); searched_services.filters.push(search.createFilter({ name: 'custrecord_service_customer', operator: search.Operator.IS, values: customer_id })); searched_services.filters.push(search.createFilter({ name: 'custrecord_service', operator: search.Operator.IS, values: 22 })); searched_services.filters.push(search.createFilter({ name: 'custrecord_service_price', operator: search.Operator.EQUALTO, values: admin_fees })); var resultSet = searched_services.run(); var searchedServicesResult = resultSet.getRange({ start: 0, end: 2 }); return searchedServicesResult; } //FUNCTION TO CALCULATE THE TOTAL INVOICE FOR THE CUSTOMER function updateTotal() { var total_invoice = 0.0; var total_package_elem = document.getElementsByClassName("total_package_value"); var total_service_elem = document.getElementsByClassName("service_total"); var admin_fees_total_elem = document.getElementsByClassName("admin_fees_total"); var customer_admin_fees = document.getElementsByClassName("customer_admin_fees"); for (var i = 0; i < total_package_elem.length; ++i) { if (typeof total_package_elem[i].value !== "undefined") { total_invoice = total_invoice + parseFloat(total_package_elem[i].value); } } for (var i = 0; i < total_service_elem.length; ++i) { if (typeof total_service_elem[i].value !== "undefined") { total_invoice = total_invoice + parseFloat(total_service_elem[i].value); } } if (admin_fees_log == true || admin_fees_log == 'true') { for (var i = 0; i < admin_fees_total_elem.length; ++i) { // console.log(admin_fees_total_elem[i].value) if (typeof admin_fees_total_elem[i].value !== "undefined" && admin_fees_total_elem[i].value != "NaN") { total_invoice = total_invoice + parseFloat(admin_fees_total_elem[i].value); } } } $('.total_value').val(total_invoice); } function GetFormattedDate(stringDate) { var todayDate = format.parse({ value: stringDate, type: format.Type.DATE }); var month = pad(todayDate.getMonth() + 1); var day = pad(todayDate.getDate()); var year = (todayDate.getFullYear()); return year + "-" + month + "-" + day; } function pad(s) { return (s < 10) ? '0' + s : s; } function finalise_date(start_date) { var split_date = start_date.split('/'); var date = new Date(); var month = date.getMonth(); //Months 0 - 11 var today = date.getDate(); var year = date.getFullYear(); var lastDay = new Date(split_date[2], split_date[1], 0); var currentLastDay = new Date(year, (month + 1), 0); if (lastDay.getDay() == 0) { lastDay.setDate(lastDay.getDate() - 2); } else if (lastDay.getDay() == 6) { lastDay.setDate(lastDay.getDate() - 1); } var lastWorkingDay = lastDay.getDate(); var lastWorkingDayPlus5 = new Date(); lastDay.setDate(lastDay.getDate() + 5); var button = false; console.log(parseInt(year) === parseInt(split_date[2])); console.log(parseInt(split_date[1]) === parseInt(month + 1)); console.log(today < lastWorkingDay); //If allocator run on the first day of the month, it takes the last month as the filter if (parseInt(year) === parseInt(split_date[2]) && parseInt(split_date[1]) === parseInt(month + 1) && today < lastWorkingDay) { console.log('inside') } else if ((lastWorkingDay == today || today <= currentLastDay.getDate())) { console.log('inside 2') button = true; } return button; } function createServiceRecord(service_type, service_name, price, customer_id, commReg, package_id) { try { var new_service_record = record.create({ type: 'customrecord_service', isDynamic: true, }); new_service_record.setValue({ fieldId: 'custrecord_service', value: service_type }); new_service_record.setValue({ fieldId: 'name', value: service_name }); new_service_record.setValue({ fieldId: 'custrecord_service_price', value: price }); new_service_record.setValue({ fieldId: 'custrecord_service_customer', value: customer_id }); if (!isNullorEmpty(commReg)) { new_service_record.setValue({ fieldId: 'custrecord_service_comm_reg', value: commReg }); } if (!isNullorEmpty(package_id)) { new_service_record.setValue({ fieldId: 'custrecord_service_package', value: package_id }); } var service_id = new_service_record.save({ enableSourcing: true, ignoreMandatoryFields: true }); return service_id; } catch (e) { var message = ''; message += "Customer Internal ID: " + customer_id + "</br>"; message += "Customer: <a href ='https://1048144.app.netsuite.com/app/common/entity/custjob.nl?id=" + customer_id + "'> View Customer </a></br>"; message += "----------------------------------------------------------------------------------</br>"; message += "Service Type: <a href ='https://1048144.app.netsuite.com/app/common/custom/custrecordentry.nl?rectype=949&id=" + service_type + "'> View Service Type</a></br>"; message += "----------------------------------------------------------------------------------</br>"; message += e; email.send({ author: 409635, body: message, recipients: ['upchh@example.com', 'ychag@example.com'], subject: 'AIC Review Page - Service Creation - Unable to create Service', }); return false; } } function createJobRecord(customer_id, service_id, rate, qty, description, category, package_id, invoice_single_line, discount_type) { var currentScript = currentRecord.get(); try { // alert(package_id) var job_new_record = record.create({ type: 'customrecord_job', isDynamic: true, }); job_new_record.setValue({ fieldId: 'custrecord_job_customer', value: customer_id }); // job_new_record.setValue({ fieldId: 'custrecord_job_franchisee', value: zee }); job_new_record.setValue({ fieldId: 'custrecord_job_service', value: service_id }); job_new_record.setValue({ fieldId: 'custrecord_job_service_price', value: rate }); job_new_record.setValue({ fieldId: 'custrecord_job_extras_qty', value: qty }); job_new_record.setValue({ fieldId: 'custrecord_job_status', value: 3 }); job_new_record.setValue({ fieldId: 'custrecord_job_invoiceable', value: 1 }); job_new_record.setValue({ fieldId: 'custrecord_job_date_reviewed', value: getDate() }); job_new_record.setValue({ fieldId: 'custrecord_job_source', value: 5 }); job_new_record.setValue({ fieldId: 'custrecord_job_invoice_detail', value: description }); job_new_record.setValue({ fieldId: 'custrecord_job_date_scheduled', value: currentScript.getValue({ fieldId: 'end_date' }) }); if (category == '1') { job_new_record.setValue({ fieldId: 'custrecord_job_group_status', value: 'Completed' }); } if (!isNullorEmpty(package_id)) { job_new_record.setValue({ fieldId: 'custrecord_job_service_package', value: package_id }); job_new_record.setValue({ fieldId: 'custrecord_job_invoice_single_line_item', value: invoice_single_line }); } job_new_record.setValue({ fieldId: 'custrecord_job_service_category', value: category }); job_new_record.setValue({ fieldId: 'custrecord_job_discount_type', value: discount_type }); job_new_record.save({ enableSourcing: true, ignoreMandatoryFields: true }); } catch (e) { var message = ''; message += "Customer Internal ID: " + customer_id + "</br>"; message += "Customer: <a href ='https://1048144.app.netsuite.com/app/common/entity/custjob.nl?id=" + customer_id + "'> View Customer </a></br>"; message += "----------------------------------------------------------------------------------</br>"; if (!isNullorEmpty(service_id) || service_id != false) { message += "Service: <a href ='https://1048144.app.netsuite.com/app/common/custom/custrecordentry.nl?rectype=946&id=" + service_id + "'> View Service Type</a></br>"; message += "----------------------------------------------------------------------------------</br>"; } message += e; email.send({ author: 409635, body: message, recipients: ['upchh@example.com', 'ychag@example.com'], subject: 'AIC Review Page - Job Creation - Unable to create Job' }); // return false; } } function updateJobRecord(job_id, rate, qty, description, category, package_id, invoice_single_line, discount_type) { var job_record = record.load({ type: 'customrecord_job', id: job_id, }); job_record.setValue({ fieldId: 'custrecord_job_extras_qty', value: qty }); job_record.setValue({ fieldId: 'custrecord_job_source', value: 5 }); job_record.setValue({ fieldId: 'custrecord_job_invoice_detail', value: description }); if (!isNullorEmpty(package_id)) { job_record.setValue({ fieldId: 'custrecord_job_service_package', value: package_id }); } if (!isNullorEmpty(rate)) { job_record.setValue({ fieldId: 'custrecord_job_service_price', value: rate }); } job_record.setValue({ fieldId: 'custrecord_job_invoice_detail', value: description }); job_record.setValue({ fieldId: 'custrecord_job_invoice_single_line_item', value: invoice_single_line }); job_record.setValue({ fieldId: 'custrecord_job_discount_type', value: discount_type }); job_record.save({ enableSourcing: true, ignoreMandatoryFields: true }); } function removeDuplicateUsingFilter(arr) { var unique_array = []; for (var i = 0; i < arr.length; i++) { if (unique_array.indexOf(arr[i]) == -1) { unique_array.push(arr[i]); } } return unique_array } function isNullorEmpty(strVal) { return (strVal == null || strVal == '' || strVal == 'null' || strVal == undefined || strVal == 'undefined' || strVal == '- None -'); } return { pageInit: pageInit, saveRecord: saveRecord, onclick_review: onclick_review, onclick_summaryPage: onclick_summaryPage, onclick_reset: onclick_reset }; } );
true
/** * * @NApiVersion 2.0 * @NScriptType ClientScript * * Description: Client script that habndles all the validations and calculations of the review page. * @Last Modified by: Sruti Desai * */ define(['N/error', 'N/runtime', 'N/search', 'N/url', 'N/record', 'N/format', 'N/email', 'N/currentRecord'], function(error, runtime, search, url, record, format, email, currentRecord) { var baseURL = 'https://1048144.app.netsuite.com'; if (runtime.envType == "SANDBOX") { baseURL = 'https://1048144-sb3.app.netsuite.com'; } var role = runtime.getCurrentUser().role; var zee = 0; var ctx = runtime.getCurrentScript(); var deleted_service_ids = []; var deleted_job_ids = []; if (role == 1000) { //Franchisee zee = ctx.getCurrentUser(); } else if (role == 3) { //Administrator zee = 6; //test } else if (role == 1032) { // System Support zee = 425904; //test-AR } var global_customer; var global_locked = null; var admin_fees_log = false; /** * On page initialisation- collapse the App Qty fields and the Invoiceable Qty fields */ function pageInit() { var currentScript = currentRecord.get(); $(window).load(function() { // Animate loader off screen $(".se-pre-con").fadeOut("slow");; }); $("#NS_MENU_ID0-item0").css("background-color", "#CFE0CE"); $("#NS_MENU_ID0-item0 a").css("background-color", "#CFE0CE"); $("#body").css("background-color", "#CFE0CE"); $(document).ready(function() { $('[data-toggle="tooltip"]').tooltip(); }); $('.col_collapse_appqty').hide(); $('.header_collapse').hide(); $('.discount_collpase_appqty').hide(); $('.singleline_collpase_appqty').hide(); $('.total_collapse_appqty').hide(); $('.monthlytotal_collapse_appqty').hide(); $('.invoicetotalheader_collpase_appqty').hide(); $('.invoiceable_qty_collpase').hide(); $('.package_name_row').attr('colspan', 6); $('.header_invoiceable_qty_collpase').attr('colspan', 1); global_customer = currentScript.getValue({ fieldId: 'customer_id' }); var start_date = GetFormattedDate(currentScript.getValue({ fieldId: 'start_date' }) ); var end_date = GetFormattedDate(currentScript.getValue({ fieldId: 'end_date' }) ); $('.start_date').val(start_date); $('.end_date').val(end_date); admin_fees_log = currentScript.getValue({ fieldId: 'admin_fees_log' }); global_locked = currentScript.getValue({ fieldId: 'locked' }); document.getElementById('tdbody_reviewed').style = 'background-color: #125ab2 !important;color: white;'; if (global_locked == 'yes') { document.getElementById('tr_submitter').style.display = 'none'; document.getElementById('tdbody_reviewed').style.display = 'none'; $('.admin_fees_on').prop('disabled', true); $('.admin_fees_off').prop('disabled', true); $('.invoiceable_qty').prop('disabled', function(i, v) { return !v; }); $('.admin_fees_rate').prop('disabled', function(i, v) { return !v; }); $('.admin_fees_qty').prop('disabled', function(i, v) { return !v; }); $('.job_description').prop('disabled', function(i, v) { return !v; }); $('.single_job_description').prop('disabled', function(i, v) { return !v; }); $('.add_services').prop('disabled', function(i, v) { return !v; }); $('.fixed_discount_value').prop('disabled', function(i, v) { return !v; }); $('.fixed_discount_qty').prop('disabled', function(i, v) { return !v; }); $('.total_package_value').prop('disabled', function(i, v) { return !v; }); $('.customer_po').prop('disabled', function(i, v) { return !v; }); } var result = finalise_date(currentScript.getValue({ fieldId: 'start_date' })); // $(document).on('click', '.instruction_button', function(e) { // console.log("abc"); // $('.table_start').css("padding-top", "300px"); // $('.instruction_button').hide(); // }); $('.collapse').on('shown.bs.collapse', function() { $('.table_start').css("padding-top", "250px"); }) $('.collapse').on('hide.bs.collapse', function() { $('.table_start').css("padding-top", "0px"); }) $('#exampleModal').on('show.bs.modal', function(event) { var button = $(event).relatedTarget // Button that triggered the modal var recipient = button.data('whatever') // Extract info from data-* attributes // If necessary, you could initiate an AJAX request here (and then do the updating in a callback). // Update the modal's content. We'll use jQuery here, but you could use a data binding library or other methods instead. var modal = $(this) modal.find('.modal-title').text('New message to ' + recipient) modal.find('.modal-body input').val(recipient) }); $(document).ready(function() { $(".modal_display").click(function() { var link = $(this).data("whatever"); // console.log(link); $('.modal .modal-header').html('<div class="form-group"><h4><label class="control-label" for="inputError1">Information</label></h4></div>'); $('.modal .modal-body').html(""); $('.modal .modal-body').html(link); $('.modal .modal-footer').html('<button type="button" class="btn btn-default" data-dismiss="modal">Close</button>'); $('.modal').modal("show"); }); }); /** * [description] - On click of the '+', open up the App Qty fields */ $(document).on('click', '.collapse_appqty', function(e) { $('.col_collapse_appqty').show(); $('.header_collapse').show(); $('.discount_collpase_appqty').show(); $('.singleline_collpase_appqty').show(); $('.total_collapse_appqty').show(); $('.monthlytotal_collapse_appqty').show(); $('.invoicetotalheader_collpase_appqty').show(); $('.package_name_row').attr('colspan', 12); $('.admin_fees_collpase').attr('colspan', 5); // $('.collapse_appqty').removeClass('glyphicon-plus'); // $('.collapse_appqty').addClass('glyphicon-minus'); $('.collapse_appqty').addClass('invoiceableqty_collapse'); }); /** * [description] - On click of the '+' for the second time, show the invoiceable qty fields */ $(document).on('click', '.invoiceableqty_collapse', function(e) { $('.invoiceable_qty_collpase').show(); $('.invoiceableqty_collapse').hide(); // $('.package_name_row').attr('colspan',11); $('.header_invoiceable_qty_collpase').attr('colspan', 3); $('.admin_fees_collpase').attr('colspan', 7); }); /** * [description] - On click of the '-', collapse all the App Qty and Invoiceable Qty fields */ $(document).on('click', '.collapse_all', function(e) { $('.col_collapse_appqty').hide(); $('.collapse_appqty').show(); $('.invoiceable_qty_collpase').show(); $('.invoiceableqty_collapse').show(); $('.header_collapse').hide(); $('.discount_collpase_appqty').hide(); $('.singleline_collpase_appqty').hide(); $('.total_collapse_appqty').hide(); $('.monthlytotal_collapse_appqty').hide(); $('.invoicetotalheader_collpase_appqty').hide(); $('.invoiceable_qty_collpase').hide(); $('.package_name_row').attr('colspan', 6); $('.admin_fees_collpase').attr('colspan', 0); $('.header_invoiceable_qty_collpase').attr('colspan', 1); $('.collapse_appqty').removeClass('invoiceableqty_collapse'); }); //DO CALCULATIONS IF THE DISCUNT QTY IN THE DISCOUNT ROW IS CHANGED $(document).on('blur', '.discount_qty', function(e) { var discount_value = $(this).closest('tr').find('.discount_value').val(); var discount_qty = $(this).val(); var attr_fixed = $(this).attr('package-fixed'); var attr_packageid = $(this).attr('data-packageid'); var old_total_discount_value = $(this).closest('tr').find('.total_discount_value').val(); var old_total_value = $(this).closest('tr').next('tr').find('.total_package_value').val(); var package_value = $(this).closest('tr').next('tr').find('.package_value').val(); var discount_type = $(this).closest('tr').find('.discount_type').val(); var total_package = 0; var package_invoiceable_qty_elem = document.getElementsByClassName("package_invoiceable_qty"); var package_netsuite_qty_elem = document.getElementsByClassName("package_netsuite_qty"); var package_app_qty_elem = document.getElementsByClassName("package_app_qty"); var service_total_value_elem = document.getElementsByClassName("service_total_value"); var app_qty = []; for (var i = 0; i < package_app_qty_elem.length; ++i) { app_qty.push(parseInt(package_app_qty_elem[i].value)); } var max = Math.max.apply(null, app_qty); //CHECKING THE MAX QTY OF ALL THE APP QTY AND IF THE DISCOUNT QTY IS LESS THAN THE MAX APP QTY, THE DISCOUNT QTY IS CHANGED TO THE MAX APP QTY if (discount_qty < max) { discount_qty = max; $(this).val(max); } //ADJUST THE QTYS OF THE TOTAL INVOICEABLE QTY FOR ALL SERVICES FOR THAT PACKAGE for (var i = 0; i < package_invoiceable_qty_elem.length; ++i) { if (package_invoiceable_qty_elem[i].getAttribute("data-packageid") == attr_packageid) { var initial_changed_qty = package_invoiceable_qty_elem[i].value; var initial_load_qty = package_invoiceable_qty_elem[i].getAttribute("data-oldqty"); var netsuite_qty = package_netsuite_qty_elem[i].value; var app_qty = package_app_qty_elem[i].value; var rate = package_invoiceable_qty_elem[i].getAttribute("data-rate"); var total_inv_qty = parseFloat(app_qty) + parseFloat(netsuite_qty); if (discount_qty >= 0) { if (discount_qty == 0) { //IF DISCOUNT QTY ENTERED IS 0 if (app_qty > 0) { alert('Cannot reduce quantity below ' + app_qty); $(this).val(app_qty); return false; } else { package_netsuite_qty_elem[i].setAttribute("value", discount_qty); discount_qty = parseFloat(discount_qty) + parseFloat(app_qty); package_invoiceable_qty_elem[i].setAttribute("value", discount_qty); } } else { package_invoiceable_qty_elem[i].setAttribute("value", discount_qty); if (total_inv_qty != discount_qty) { var new_netsuite_qty = parseFloat(discount_qty) - parseFloat(total_inv_qty); new_netsuite_qty = parseFloat(netsuite_qty) + new_netsuite_qty; package_netsuite_qty_elem[i].setAttribute("value", new_netsuite_qty); } } // package_app_qty_elem[i].setAttribute("value", new_app_qty); var total_rate = updateServiceAmount(parseFloat(rate), parseFloat(discount_qty)); service_total_value_elem[i].setAttribute("value", roundTwoDec(total_rate)); total_package += total_rate; } else { alert('Wrong Quantity entered'); return false; } } } $(this).closest('tr').next('tr').find('.package_value').val(total_package); //CALCULATIONS FOR THE PACKAGE DISCOUNT VALUE BASED ON THE DISCOUNT TYPE if (discount_type == 1) { var total_discount_value = (parseFloat(discount_qty) * parseFloat(discount_value)); var new_total_value = parseFloat(total_package) - total_discount_value; } else { var total_discount_value = ((parseFloat(discount_value) / 100) * parseFloat(total_package)); var new_total_value = parseFloat(total_package) - total_discount_value; } //UPDATE THE TOTAL DISCOUNT VALUE AND THE TOTAL PACKAGE VALUE $(this).closest('tr').find('.total_discount_value').val(roundTwoDec(total_discount_value)); $(this).closest('tr').next('tr').next('tr').find('.total_package_value').val(roundTwoDec(new_total_value)); $(this).closest('tr').next('tr').next('tr').find('.total_package_value').focus(); //UPDATE THE INVOICE TOTAL BASED ON THE CHANGE updateTotal(); }); //ON CHANGE OF THE INVOICEABLE QTY FOR THE SERVICES AND EXTRAS SECTION $(document).on('blur', '.invoiceable_qty', function(e) { var invoiceable_qty = $(this).val(); if (isNullorEmpty(invoiceable_qty)) { invoiceable_qty = 0; $(this).val(0); } var old_qty = $(this).attr('data-oldqty'); var rate = $(this).attr('data-rate'); var app_qty = $(this).closest('tr').find('.app_qty').val(); var netsuite_qty = $(this).closest('tr').find('.package_netsuite_qty').val(); var total_inv_qty = parseFloat(app_qty) + parseFloat(netsuite_qty); if (invoiceable_qty >= 0) { if (invoiceable_qty == 0) { if (app_qty > 0) { alert('Cannot reduce quantity below ' + app_qty + '. \nTo reduce the quantity, please click on the App Jobs and set \"DO YOU WANT TO INVOICE JOB GROUP??\" to \"No\"'); $(this).val(app_qty); $(this).closest('tr').find('.package_netsuite_qty').val(0); var total_rate = updateServiceAmount(parseFloat(rate), parseFloat(app_qty)); $(this).closest('tr').find('.service_total_value').val(roundTwoDec(total_rate)); $(this).closest('tr').find('.service_total_value').focus(); $(this).closest('tr').find('.service_total').val((total_rate)); return false; } else { var new_netsuite_qty = parseFloat(invoiceable_qty); $(this).closest('tr').find('.package_netsuite_qty').val(new_netsuite_qty); var total_rate = updateServiceAmount(parseFloat(rate), parseFloat(invoiceable_qty)); $(this).closest('tr').find('.service_total_value').val(roundTwoDec(total_rate)); $(this).closest('tr').find('.service_total_value').focus(); $(this).closest('tr').find('.service_total').val((total_rate)); } } else { if (parseInt(app_qty) > invoiceable_qty) { alert('Cannot reduce quantity below ' + app_qty + '. \nTo reduce the quantity, please click on the App Jobs and set \"DO YOU WANT TO INVOICE JOB GROUP??\" to \"No\"'); $(this).val(app_qty); $(this).closest('tr').find('.package_netsuite_qty').val(0); var total_rate = updateServiceAmount(parseFloat(rate), parseFloat(app_qty)); $(this).closest('tr').find('.service_total_value').val(roundTwoDec(total_rate)); $(this).closest('tr').find('.service_total_value').focus(); $(this).closest('tr').find('.service_total').val((total_rate)); return false; } if (parseInt(total_inv_qty) != invoiceable_qty) { var new_netsuite_qty = parseFloat(invoiceable_qty) - parseFloat(total_inv_qty); new_netsuite_qty = parseFloat(netsuite_qty) + new_netsuite_qty; $(this).closest('tr').find('.package_netsuite_qty').val(new_netsuite_qty); var total_rate = updateServiceAmount(parseFloat(rate), parseFloat(invoiceable_qty)); $(this).closest('tr').find('.service_total_value').val((total_rate).toFixed(2)); $(this).closest('tr').find('.service_total_value').focus(); $(this).closest('tr').find('.service_total').val((total_rate).toFixed(2)); // $(this).closest('tr').find('.service_total_value').val((total_rate)); } } } else { alert('Cannot reduce quantity below ' + app_qty + '. \nTo reduce the quantity, please click on the App Jobs and set \"DO YOU WANT TO INVOICE JOB GROUP??\" to \"No\"'); $(this).val(app_qty); return false; } updateTotal(); }); $(document).on('blur', '.total_package_value', function(e) { var total_value = $(this).val(); // var old_total_discount_value = $(this).closest('tr').find('.total_discount_value').val(); var package_value = $(this).closest('tr').find('.package_value').val(); // var discount_type = $(this).closest('tr').find('.discount_type').val(); var discount_qty = $(this).closest('tr').prev('tr').prev('tr').find('.discount_qty').val(); var total_discount = parseFloat(total_value) - parseFloat(package_value); var per_discount = total_discount / parseFloat(discount_qty); $(this).closest('tr').prev('tr').prev('tr').find('.discount_value').val(roundTwoDec(parseFloat(per_discount))); $(this).closest('tr').prev('tr').prev('tr').find('.total_discount_value').val(roundTwoDec(parseFloat(total_discount))); }); //ON CHANGE OF THE FIXED RATE QTY $(document).on('blur', '.fixed_discount_qty', function(e) { var discount_value = $(this).closest('tr').find('.fixed_discount_value').val(); var discount_qty = $(this).val(); var attr_fixed = $(this).attr('package-fixed'); var attr_packageid = $(this).attr('data-packageid'); var old_total_discount_value = $(this).closest('tr').find('.total_discount_value').val(); var old_total_value = $(this).closest('tr').next('tr').find('.total_package_value').val(); var package_value = $(this).closest('tr').next('tr').find('.package_value').val(); var discount_type = $(this).closest('tr').find('.discount_type').val(); var total_package = 0; var package_invoiceable_qty_elem = document.getElementsByClassName("package_invoiceable_qty"); var package_netsuite_qty_elem = document.getElementsByClassName("package_netsuite_qty"); var package_app_qty_elem = document.getElementsByClassName("package_app_qty"); var service_total_value_elem = document.getElementsByClassName("service_total_value"); var app_qty = []; for (var i = 0; i < package_app_qty_elem.length; ++i) { var packageID = package_invoiceable_qty_elem[i].getAttribute("data-packageid"); if (attr_packageid == packageID) { app_qty.push(parseInt(package_app_qty_elem[i].value)); } } // console.log(app_qty); // return false; var max = Math.max.apply(null, app_qty); if (discount_qty < max) { discount_qty = max; $(this).val(max); } for (var i = 0; i < package_invoiceable_qty_elem.length; ++i) { if (package_invoiceable_qty_elem[i].getAttribute("data-packageid") == attr_packageid) { var initial_changed_qty = package_invoiceable_qty_elem[i].value; var initial_load_qty = package_invoiceable_qty_elem[i].getAttribute("data-oldqty"); var netsuite_qty = package_netsuite_qty_elem[i].value; var app_qty = package_app_qty_elem[i].value; var rate = package_invoiceable_qty_elem[i].getAttribute("data-rate"); var service_cat = package_netsuite_qty_elem[i].getAttribute("data-servicecat"); var total_inv_qty = parseFloat(app_qty) + parseFloat(netsuite_qty); if (service_cat == 1) { if (discount_qty >= 0) { if (discount_qty == 0) { if (app_qty > 0) { alert('Cannot reduce quantity below ' + app_qty); $(this).val(app_qty); return false; } else { package_netsuite_qty_elem[i].setAttribute("value", discount_qty); discount_qty = parseFloat(discount_qty) + parseFloat(app_qty); package_invoiceable_qty_elem[i].setAttribute("value", discount_qty); } } else { package_invoiceable_qty_elem[i].setAttribute("value", discount_qty); if (total_inv_qty != discount_qty) { var new_netsuite_qty = parseFloat(discount_qty) - parseFloat(total_inv_qty); new_netsuite_qty = parseFloat(netsuite_qty) + new_netsuite_qty; package_netsuite_qty_elem[i].setAttribute("value", new_netsuite_qty); } } // package_app_qty_elem[i].setAttribute("value", new_app_qty); var total_rate = updateServiceAmount(parseFloat(rate), parseFloat(discount_qty)); service_total_value_elem[i].setAttribute("value", total_rate); total_package += total_rate; } else { alert('Wrong Quantity entered'); return false; } } else { var total_rate = updateServiceAmount(parseFloat(rate), parseFloat(initial_changed_qty)); total_package += total_rate; } } } $(this).closest('tr').find('.package_value').val(total_package); var package_value = parseFloat(total_package); var total_discount_value = (parseFloat(discount_qty) * parseFloat(discount_value)); $(this).closest('tr').find('.total_package_value').val(roundTwoDec(total_discount_value)); $(this).closest('tr').find('.total_package_value').focus(); var new_discount = parseFloat(total_discount_value) - parseFloat(package_value); if (new_discount < 0) { $(this).closest('tr').prev('tr').prev('tr').find('.discount_dollar').addClass('has-error'); $(this).closest('tr').prev('tr').prev('tr').find('.discount_dollar').removeClass('has-success'); } else { $(this).closest('tr').prev('tr').prev('tr').find('.discount_dollar').addClass('has-success'); $(this).closest('tr').prev('tr').prev('tr').find('.discount_dollar').removeClass('has-error'); } $(this).closest('tr').prev('tr').find('.total_discount_value').val(roundTwoDec(new_discount)); var discount_rate = new_discount / parseFloat(discount_qty); $(this).closest('tr').prev('tr').prev('tr').find('.total_discount_value').val(roundTwoDec(new_discount)); $(this).closest('tr').prev('tr').prev('tr').find('.discount_value').val(roundTwoDec((new_discount / parseFloat(discount_qty)))); $(this).closest('tr').prev('tr').prev('tr').find('.discount_qty').val(discount_qty); updateTotal(); }); //GET THE OLD VALUE OF THE DISCOUNT VALUE. $(document).on('focusin', '.discount_value', function() { $(this).data('oldval', $(this).val()); }); //ON CHANGE OF THE DISCOUNT VALUE $(document).on('blur', '.discount_value', function(e) { var discount_qty = $(this).closest('tr').find('.discount_qty').val(); var discount_value = $(this).val(); var old_discount_value = $(this).data('oldval'); var attr_fixed = $(this).attr('package-fixed'); var attr_packageid = $(this).attr('data-packageid'); var old_total_discount_value = $(this).closest('tr').find('.total_discount_value').val(); var old_total_value = $(this).closest('tr').next('tr').next('tr').find('.total_package_value').val(); var package_value = $(this).closest('tr').next('tr').next('tr').find('.package_value').val(); var discount_type = $(this).closest('tr').find('.discount_type').val(); //IF THE DISCOUNT TYPE IS $ if (discount_type == 1) { var total_discount_value = (parseFloat(discount_qty) * parseFloat(discount_value)); //TO CHECK THE TOTAL DISCOUNT VALUE IS NOT GREATER THAN THE TOTAL PACKAGE OF ALL THE SERVICES if (total_discount_value < package_value) { $(this).closest('tr').find('.total_discount_value').val(roundTwoDec(total_discount_value)); } else { alert('Total value is greater than the total of the package'); $(this).val(old_discount_value); var total_discount_value = (parseFloat(discount_qty) * parseFloat(old_discount_value)); $(this).closest('tr').find('.total_package_value').val(roundTwoDec(total_discount_value)); $(this).closest('tr').find('.total_package_value').focus(); return false; } var new_total_value = parseFloat(package_value) - total_discount_value; } else { //IF DISCOUNT TYPE IS % var total_discount_value = ((parseFloat(discount_value) / 100) * parseFloat(package_value)); if (total_discount_value < package_value) { $(this).closest('tr').find('.total_discount_value').val(roundTwoDec(total_discount_value)); } else { alert('Total value is greater than the total of the package'); $(this).val(old_discount_value); var total_discount_value = (parseFloat(discount_qty) * parseFloat(old_discount_value)); $(this).closest('tr').find('.total_discount_value').val(roundTwoDec(total_discount_value)); return false; } var new_total_value = parseFloat(package_value) - total_discount_value; } // $(this).closest('tr').find('.total_discount_value').val(-(total_discount_value)); $(this).closest('tr').next('tr').next('tr').find('.total_package_value').val(roundTwoDec(new_total_value)); $(this).closest('tr').next('tr').next('tr').find('.total_package_value').focus(); updateTotal(); }); //GET THE OLD FIXED RATE $(document).on('focusin', '.fixed_discount_value', function() { $(this).data('oldval', $(this).val()); }); //ON CHANGE OF THE FIXED RATE VALUE $(document).on('blur', '.fixed_discount_value', function(e) { var discount_qty = $(this).closest('tr').find('.fixed_discount_qty').val(); var discount_value = $(this).val(); var old_discount_value = $(this).data('oldval'); var attr_fixed = $(this).attr('package-fixed'); var attr_packageid = $(this).attr('data-packageid'); var old_total_discount_value = $(this).closest('tr').find('.total_discount_value').val(); var old_total_value = $(this).closest('tr').next('tr').find('.total_package_value').val(); var package_value = $(this).closest('tr').next('tr').find('.package_value').val(); var discount_type = $(this).closest('tr').find('.discount_type').val(); var package_value = $(this).closest('tr').find('.package_value').val(); var total_discount_value = (parseFloat(discount_qty) * parseFloat(discount_value)); if (total_discount_value < package_value) { $(this).closest('tr').find('.total_package_value').val(roundTwoDec(total_discount_value)); $(this).closest('tr').find('.total_package_value').focus(); } else { alert('Total value is greater than the total of the package'); $(this).val(old_discount_value); var total_discount_value = (parseFloat(discount_qty) * parseFloat(old_discount_value)); $(this).closest('tr').find('.total_package_value').val(roundTwoDec(total_discount_value)); $(this).closest('tr').find('.total_package_value').focus(); return false; } var new_discount = parseFloat(total_discount_value) - parseFloat(package_value); if (new_discount < 0) { $(this).closest('tr').prev('tr').prev('tr').find('.discount_dollar').addClass('has-error'); $(this).closest('tr').prev('tr').prev('tr').find('.discount_dollar').removeClass('has-success'); } else { $(this).closest('tr').prev('tr').prev('tr').find('.discount_dollar').addClass('has-success'); $(this).closest('tr').prev('tr').prev('tr').find('.discount_dollar').removeClass('has-error'); } $(this).closest('tr').prev('tr').prev('tr').find('.total_discount_value').val(roundTwoDec(new_discount)); $(this).closest('tr').prev('tr').prev('tr').find('.discount_value').val(roundTwoDec(new_discount / parseFloat(discount_qty))); $(this).closest('tr').prev('tr').prev('tr').find('.discount_qty').val(roundTwoDec(discount_qty)); updateTotal(); }); //ON CHANGE OF THE DISCOUNT TYPE, HIDE OR SHOW THE DISCOUNT QTY $(document).on("change", ".discount_type", function(e) { var discount_type = $(this).val(); //IF THE DISCOUNT TYPE IS $, SHOW THE DISCOUNT QTY if (discount_type == 1) { $(this).closest('tr').find('.discount_qty').show(); } else { $(this).closest('tr').find('.discount_qty').hide(); } }); //ON CHANGE OF THE INVOICE SINGLE LINE $(document).on("change", ".invoice_single_line", function(e) { var packageid; $('option:selected', this).each(function() { packageid = ($(this).data('packageid')); }); var value = $(this).val(); var package_invoiceable_qty_elem = document.getElementsByClassName("package_invoiceable_qty"); var job_desciption_elem = document.getElementsByClassName("job_description"); for (var i = 0; i < package_invoiceable_qty_elem.length; ++i) { if (job_desciption_elem[i].getAttribute("data-packageid") == packageid) { //IF INVOICE SINGLE LINE IS SET TO YES, HIDE THE INVOICE DETAILS FIELDS FOR EACH OF THE SERVICES PRESENT IN THE PACKAGE if (value == 1) { $(this).closest('tr').find('.single_job_description').show(); job_desciption_elem[i].setAttribute('style', "display: none"); job_desciption_elem[i].setAttribute('value', ""); job_desciption_elem[i].setAttribute('data-singleline', "1"); } else { //HIDE THE INVOICE DETAIL SHOWN IN THE INVOICE DETAIL ROW AND SHOW THE INVOICE DETAIL FIELDS FOR EACH OF THE SERVICES PRESENT IN THE PACKAGE $(this).closest('tr').find('.single_job_description').hide(); $(this).closest('tr').find('.single_job_description').val(null); job_desciption_elem[i].setAttribute('style', "display: display"); job_desciption_elem[i].setAttribute('data-singleline', "2"); } } } if (value == 1) { $(this).closest('tr').find('.single_line_hidden').val("1"); } else { $(this).closest('tr').find('.single_line_hidden').val("2"); } }); $('.add_services').click(function() { console.log("clicked services btn"); var serv_param = $(this).attr("fnparam"); addService(serv_param); }); /** * [description] - To show the Invoice Preview modal */ $(document).on('click', '.preview_row', function(event) { console.log("prev clicked"); var currentScript = currentRecord.get(); var discount_type_elem = document.getElementsByClassName("discount_type"); var discount_value_elem = document.getElementsByClassName("discount_value"); var discount_qty_elem = document.getElementsByClassName("discount_qty"); var total_discount_elem = document.getElementsByClassName("total_discount_value"); var invoice_single_line_elem = document.getElementsByClassName("invoice_single_line"); var total_package_value = document.getElementsByClassName("total_package_value"); var single_line_hidden = document.getElementsByClassName("single_line_hidden"); var fixed_discount_value = document.getElementsByClassName("fixed_discount_value"); var job_description_elem = document.getElementsByClassName("job_description"); var single_job_description_elem = document.getElementsByClassName("single_job_description"); var admin_fees_rate_elem = document.getElementsByClassName("admin_fees_rate"); var admin_fees_qty_elem = document.getElementsByClassName("admin_fees_qty"); var gst_value = 0.1; var total_gst = 1.1; var sum_total = 0.0; var sum_gst = 0.0; var sum_gross_total = 0.0; var package_details = []; var invoice_line_items = []; var invoice_line_qty = []; var invoice_line_rate = []; var invoice_line_gst = []; preview_html = '<table class="table table-responsive table-striped"><thead><tr class="info"><th><b>ITEM</b></th><th><b>DETAILS</b></th><th style="text-align: right;"><b>QTY</b></th><th style="text-align: right;"><b>RATE</b></th><th style="text-align: right;"><b>TOTAL</b></th><th style="text-align: right;"><b>GST</b></th><th style="text-align: right;"><b>GROSS TOTAL</b></th></thead><tbody>'; if (!isNullorEmpty(total_discount_elem)) { for (var i = 0; i < total_discount_elem.length; ++i) { var job_id = total_discount_elem[i].getAttribute('data-netsuitejob'); var default_description_value = single_job_description_elem[i].getAttribute('default-value'); var description_value = single_job_description_elem[i].value; var default_total_discount_value = total_discount_elem[i].getAttribute('default-value'); var single_line_hidden_default = single_line_hidden[i].getAttribute('default-singleline'); var total_discount_value = total_discount_elem[i].value; var single_line_hidden_value = single_line_hidden[i].value; if (isNullorEmpty(single_line_hidden_value)) { single_line_hidden_value = single_line_hidden_default; } var package_id = null; var discount_period = null; if (total_discount_elem[i].hasAttribute("data-package")) { package_id = total_discount_elem[i].getAttribute('data-package'); package_record = record.load({ type: 'customrecord_service_package', id: package_id, }); discount_period = package_record.getValue({ fieldId: 'custrecord_service_package_disc_period' }); package_ns_item_id = package_record.getValue({ fieldId: 'custrecord_service_package_ns_item' }); if (isNullorEmpty(package_ns_item_id)) { package_ns_item = 'Fixed Charges'; package_ns_item_id = 66; } else { package_ns_item = search.lookupFields({ type: 'item', id: package_ns_item_id, columns: 'itemid' }); } package_details[package_id] = []; if (discount_period == 3) { invoice_line_items[invoice_line_items.length] = package_ns_item_id; invoice_line_qty[invoice_line_qty.length] = 1; invoice_line_rate[invoice_line_rate.length] = total_package_value[i].value; invoice_line_gst[invoice_line_gst.length] = 7; package_details[package_id][0] = "1"; package_details[package_id][1] = "1"; package_details[package_id][2] = total_package_value[i].value; preview_html += '<tr><td>' + package_ns_item + '</td><td>' + description_value + '</td><td style="text-align: right;">1</td><td style="text-align: right;">$' + parseFloat(total_package_value[i].value).toFixed(2) + '</td><td style="text-align: right;">$' + parseFloat(total_package_value[i].value).toFixed(2) + '</td><td style="text-align: right;">$' + parseFloat(total_package_value[i].value * gst_value).toFixed(2) + '</td style="text-align: right;"><td style="text-align: right;">$' + parseFloat(total_package_value[i].value * total_gst).toFixed(2) + '</td></tr>'; sum_total = parseFloat(sum_total + (total_package_value[i].value)); sum_gst = parseFloat(sum_gst + (total_package_value[i].value * gst_value)); sum_gross_total = parseFloat(sum_gross_total + (total_package_value[i].value * total_gst)); } else { if (single_line_hidden_value == 1) { invoice_line_items[invoice_line_items.length] = package_ns_item_id; invoice_line_qty[invoice_line_qty.length] = discount_qty_elem[i].value; invoice_line_rate[invoice_line_rate.length] = fixed_discount_value[i].value; invoice_line_gst[invoice_line_gst.length] = 7; package_details[package_id][0] = "1"; package_details[package_id][1] = discount_qty_elem[i].value; package_details[package_id][2] = fixed_discount_value[i].value; preview_html += '<tr><td>' + package_ns_item + '</td><td>' + description_value + '</td><td style="text-align: right;">' + discount_qty_elem[i].value + '</td><td style="text-align: right;">$' + parseFloat(fixed_discount_value[i].value).toFixed(2) + '</td><td style="text-align: right;">$' + parseFloat(fixed_discount_value[i].value * discount_qty_elem[i].value).toFixed(2) + '</td><td style="text-align: right;">$' + parseFloat(discount_qty_elem[i].value * fixed_discount_value[i].value * gst_value).toFixed(2) + '</td><td style="text-align: right;">$' + parseFloat(discount_qty_elem[i].value * fixed_discount_value[i].value * total_gst).toFixed(2) + '</td></tr>'; sum_total = parseFloat(sum_total + (fixed_discount_value[i].value * discount_qty_elem[i].value)); sum_gst = parseFloat(sum_gst + (discount_qty_elem[i].value * fixed_discount_value[i].value * gst_value)); sum_gross_total = parseFloat(sum_gross_total + (discount_qty_elem[i].value * fixed_discount_value[i].value * total_gst)); } else { package_details[package_id][0] = "2"; package_details[package_id][1] = discount_qty_elem[i].value; package_details[package_id][2] = discount_value_elem[i].value; } } } } } var package_invoiceable_qty_elem = document.getElementsByClassName("package_invoiceable_qty"); var old_package_id = null; for (var i = 0; i < package_invoiceable_qty_elem.length; ++i) { var qty = package_invoiceable_qty_elem[i].value; var rate = package_invoiceable_qty_elem[i].getAttribute("data-rate"); var item_name = package_invoiceable_qty_elem[i].getAttribute("data-nsitem"); var item_id = package_invoiceable_qty_elem[i].getAttribute("data-nsitemid"); var gst = package_invoiceable_qty_elem[i].getAttribute("data-gst"); // console.log(item_name); if (package_invoiceable_qty_elem[i].hasAttribute("data-packageid")) { var package_id = package_invoiceable_qty_elem[i].getAttribute("data-packageid"); if ((old_package_id == package_id && isNullorEmpty(old_package_id)) || old_package_id == package_id) { if (package_details[old_package_id] != undefined) { if (package_details[old_package_id][0] != "1") { // console.log('first if inside 2'); if (gst == 'Yes' || gst == '- None -') { invoice_line_items[invoice_line_items.length] = item_id; invoice_line_qty[invoice_line_qty.length] = qty; invoice_line_rate[invoice_line_rate.length] = rate; invoice_line_gst[invoice_line_gst.length] = 7; preview_html += '<tr><td>' + item_name + '</td><td>' + job_description_elem[i].value + '</td><td style="text-align: right;">' + qty + '</td><td style="text-align: right;">$' + parseFloat(rate).toFixed(2) + '</td><td style="text-align: right;">$' + parseFloat(qty * rate).toFixed(2) + '</td><td style="text-align: right;">$' + parseFloat(qty * rate * gst_value).toFixed(2) + '</td><td style="text-align: right;">$' + parseFloat(qty * rate * total_gst).toFixed(2) + '</td></tr>'; sum_total = parseFloat(sum_total + (qty * rate)); sum_gst = parseFloat(sum_gst + (qty * rate * gst_value)); sum_gross_total = parseFloat(sum_gross_total + (qty * rate * total_gst)); } else { invoice_line_items[invoice_line_items.length] = item_id; invoice_line_qty[invoice_line_qty.length] = qty; invoice_line_rate[invoice_line_rate.length] = rate; invoice_line_gst[invoice_line_gst.length] = 9; preview_html += '<tr><td>' + item_name + '</td><td>' + job_description_elem[i].value + '</td><td style="text-align: right;">' + qty + '</td><td style="text-align: right;">$' + parseFloat(rate).toFixed(2) + '</td><td style="text-align: right;">$' + parseFloat(qty * rate).toFixed(2) + '</td><td style="text-align: right;"></td><td style="text-align: right;">$' + parseFloat(qty * rate).toFixed(2) + '</td></tr>'; sum_total = parseFloat(sum_total + (qty * rate)); sum_gross_total = parseFloat(sum_gross_total + (qty * rate)); } } } } else { if (package_details[old_package_id] != undefined) { if (package_details[old_package_id][0] != "1") { var font_color = ''; if (package_details[old_package_id][2] < 0) { font_color = 'color:red;'; } invoice_line_items[invoice_line_items.length] = 97; invoice_line_qty[invoice_line_qty.length] = package_details[old_package_id][1]; invoice_line_rate[invoice_line_rate.length] = package_details[old_package_id][2]; invoice_line_gst[invoice_line_gst.length] = 7; preview_html += '<tr style="' + font_color + '"><td>Discount</td><td></td><td style="text-align: right;">' + package_details[old_package_id][1] + '</td><td style="text-align: right;">$' + parseFloat(package_details[old_package_id][2]).toFixed(2) + '</td><td style="text-align: right;">$' + parseFloat(package_details[old_package_id][1] * package_details[old_package_id][2]).toFixed(2) + '</td><td style="text-align: right;">$' + parseFloat(package_details[old_package_id][1] * package_details[old_package_id][2] * gst_value).toFixed(2) + '</td><td style="text-align: right;">$' + parseFloat(package_details[old_package_id][1] * package_details[old_package_id][2] * total_gst).toFixed(2) + '</td></tr>'; sum_total = parseFloat(sum_total + (package_details[old_package_id][1] * package_details[old_package_id][2])); sum_gst = parseFloat(sum_gst + (package_details[old_package_id][1] * package_details[old_package_id][2] * gst_value)); sum_gross_total = parseFloat(sum_gross_total + (package_details[old_package_id][1] * package_details[old_package_id][2] * total_gst)); } if (package_details[package_id][0] != "1") { // console.log('second if inside 3'); if (gst == 'Yes' || gst == '- None -') { invoice_line_items[invoice_line_items.length] = item_id; invoice_line_qty[invoice_line_qty.length] = qty; invoice_line_rate[invoice_line_rate.length] = rate; invoice_line_gst[invoice_line_gst.length] = 7; preview_html += '<tr><td>' + item_name + '</td><td>' + job_description_elem[i].value + '</td><td style="text-align: right;">' + qty + '</td><td style="text-align: right;">$' + parseFloat(rate).toFixed(2) + '</td><td style="text-align: right;">$' + parseFloat(qty * rate).toFixed(2) + '</td><td style="text-align: right;">$' + parseFloat(qty * rate * gst_value).toFixed(2) + '</td><td style="text-align: right;">$' + parseFloat(qty * rate * total_gst).toFixed(2) + '</td></tr>'; sum_total = parseFloat(sum_total + (qty * rate)); sum_gst = parseFloat(sum_gst + (qty * rate * gst_value)); sum_gross_total = parseFloat(sum_gross_total + (qty * rate * total_gst)); } else { invoice_line_items[invoice_line_items.length] = item_id; invoice_line_qty[invoice_line_qty.length] = qty; invoice_line_rate[invoice_line_rate.length] = rate; invoice_line_gst[invoice_line_gst.length] = 9; preview_html += '<tr><td>' + item_name + '</td><td>' + job_description_elem[i].value + '</td><td style="text-align: right;">' + qty + '</td><td style="text-align: right;">$' + parseFloat(rate).toFixed(2) + '</td><td style="text-align: right;">$' + parseFloat(qty * rate).toFixed(2) + '</td><td style="text-align: right;"></td><td style="text-align: right;">$' + parseFloat(qty * rate).toFixed(2) + '</td></tr>'; sum_total = parseFloat(sum_total + (qty * rate)); sum_gross_total = parseFloat(sum_gross_total + (qty * rate)); } } } } old_package_id = package_invoiceable_qty_elem[i].getAttribute("data-packageid"); } } if (!isNullorEmpty(old_package_id)) { if (package_details[old_package_id] != undefined) { if (package_details[old_package_id][0] != "1") { var font_color = ''; if (package_details[old_package_id][2] < 0) { font_color = 'color:red;'; } invoice_line_items[invoice_line_items.length] = 97; invoice_line_qty[invoice_line_qty.length] = package_details[old_package_id][1]; invoice_line_rate[invoice_line_rate.length] = package_details[old_package_id][2]; invoice_line_gst[invoice_line_gst.length] = 7; preview_html += '<tr style="' + font_color + '"><td>Discount</td><td></td><td style="text-align: right;">' + package_details[old_package_id][1] + '</td><td style="text-align: right;">$' + parseFloat(package_details[old_package_id][2]).toFixed(2) + '</td><td style="text-align: right;">$' + parseFloat(package_details[old_package_id][1] * package_details[old_package_id][2]).toFixed(2) + '</td><td style="text-align: right;">$' + parseFloat(package_details[old_package_id][1] * package_details[old_package_id][2] * gst_value).toFixed(2) + '</td><td style="text-align: right;">$' + parseFloat(package_details[old_package_id][1] * package_details[old_package_id][2] * total_gst).toFixed(2) + '</td></tr>'; sum_total = parseFloat(sum_total + (package_details[old_package_id][1] * package_details[old_package_id][2])); sum_gst = parseFloat(sum_gst + (package_details[old_package_id][1] * package_details[old_package_id][2] * gst_value)); sum_gross_total = parseFloat(sum_gross_total + (package_details[old_package_id][1] * package_details[old_package_id][2] * total_gst)); } } } var invoiceable_qty_elem = document.getElementsByClassName("invoiceable_qty"); var job_description_preview_elem = document.getElementsByClassName("job_description_preview"); for (var i = 0; i < invoiceable_qty_elem.length; ++i) { // var service_id = invoiceable_qty_elem[i].getAttribute("data-serviceid"); // var service_record = record.load({ type: 'customrecord_service', id: service_id }); // var item_id = service_record.getValue({ fieldId: 'custrecord_service_ns_item' }); // var item_name = search.lookupFields({ type: 'item', id: item_id, columns: 'itemid') }; var qty = invoiceable_qty_elem[i].value; var rate = invoiceable_qty_elem[i].getAttribute("data-rate"); var item_name = invoiceable_qty_elem[i].getAttribute("data-nsitem"); var item_id = invoiceable_qty_elem[i].getAttribute("data-nsitemid"); var gst = invoiceable_qty_elem[i].getAttribute("data-gst"); if (qty != 0) { var font_color = ''; if (item_id == 97) { font_color = 'color:red;'; } if (gst == 'Yes' || gst == '- None -') { invoice_line_items[invoice_line_items.length] = item_id; invoice_line_qty[invoice_line_qty.length] = qty; invoice_line_rate[invoice_line_rate.length] = rate; invoice_line_gst[invoice_line_gst.length] = 7; preview_html += '<tr style="' + font_color + '"><td>' + item_name + '</td><td>' + job_description_preview_elem[i].value + '</td><td style="text-align: right;">' + qty + '</td><td style="text-align: right;">$' + parseFloat(rate).toFixed(2) + '</td><td style="text-align: right;">$' + parseFloat(qty * rate).toFixed(2) + '</td><td style="text-align: right;">$' + parseFloat(qty * rate * gst_value).toFixed(2) + '</td><td style="text-align: right;">$' + parseFloat(qty * rate * total_gst).toFixed(2) + '</td></tr>'; sum_total = parseFloat(sum_total + (qty * rate)); sum_gst = parseFloat(sum_gst + (qty * rate * gst_value)); sum_gross_total = parseFloat(sum_gross_total + (qty * rate * total_gst)); } else { invoice_line_items[invoice_line_items.length] = item_id; invoice_line_qty[invoice_line_qty.length] = qty; invoice_line_rate[invoice_line_rate.length] = rate; invoice_line_gst[invoice_line_gst.length] = 9; preview_html += '<tr><td>' + item_name + '</td><td>' + job_description_preview_elem[i].value + '</td><td style="text-align: right;">' + qty + '</td><td style="text-align: right;">$' + parseFloat(rate).toFixed(2) + '</td><td style="text-align: right;">$' + parseFloat(qty * rate).toFixed(2) + '</td><td style="text-align: right;"></td><td style="text-align: right;">$' + parseFloat(qty * rate).toFixed(2) + '</td></tr>'; sum_total = parseFloat(sum_total + (qty * rate)); sum_gross_total = parseFloat(sum_gross_total + (qty * rate)); } } } if (admin_fees_log == true || admin_fees_log == 'true') { if (!isNullorEmpty(admin_fees_rate_elem)) { for (var i = 0; i < admin_fees_rate_elem.length; i++) { var rate = admin_fees_rate_elem[i].value; var qty = admin_fees_qty_elem[i].value; if (rate > 0 && qty > 0) { invoice_line_items[invoice_line_items.length] = 8729; invoice_line_qty[invoice_line_qty.length] = qty; invoice_line_rate[invoice_line_rate.length] = rate; invoice_line_gst[invoice_line_gst.length] = 7; preview_html += '<tr><td>Account Admin Fee</td><td></td><td style="text-align: right;">' + qty + '</td><td style="text-align: right;">$' + parseFloat(rate).toFixed(2) + '</td><td style="text-align: right;">$' + parseFloat(qty * rate).toFixed(2) + '</td><td style="text-align: right;">$' + parseFloat(qty * rate * gst_value).toFixed(2) + '</td><td style="text-align: right;">$' + parseFloat(qty * rate * total_gst).toFixed(2) + '</td></tr>'; sum_total = parseFloat(sum_total + (qty * rate)); sum_gst = parseFloat(sum_gst + (qty * rate * gst_value)); sum_gross_total = parseFloat(sum_gross_total + (qty * rate * total_gst)); } } } } var searchedJobsExtras = search.load({ id: 'customsearch_job_invoicing_summary', type: 'customrecord_job' }); searchedJobsExtras.filters.push(search.createFilter({ name: 'custrecord_job_date_inv_finalised', operator: search.Operator.ISEMPTY })); if (!isNullorEmpty(currentScript.getValue({ fieldId: 'start_date' })) && !isNullorEmpty(currentScript.getValue({ fieldId: 'end_date' }))) { searchedJobsExtras.filters.push(search.createFilter({ name: 'custrecord_job_date_scheduled', operator: search.Operator.ONORAFTER, values: currentScript.getValue({ fieldId: 'start_date' }) })); searchedJobsExtras.filters.push(search.createFilter({ name: 'custrecord_job_date_scheduled', operator: search.Operator.ONORBEFORE, values: currentScript.getValue({ fieldId: 'end_date' }) })); } var resultSetExtras = searchedJobsExtras.run(); var next_customer = null; var result = resultSetExtras.getRange({ start: 0, end: 1 }) if (!isNullorEmpty(result) && result.length != 0) { next_customer = result[0].getValue({ name: 'internalid', join: 'CUSTRECORD_JOB_CUSTOMER', summary: search.Summary.GROUP }); } preview_html += '<tr class="success" style="font-weight: bold;font-size: small;"><td>TOTAL</td><td></td><td></td><td></td><td style="text-align: right;">$' + parseFloat($('.total_value').val()).toFixed(2) + '</td><td style="text-align: right;">$' + sum_gst.toFixed(2) + '</td><td style="text-align: right;">$' + sum_gross_total.toFixed(2) + '</td></tr></tbody></table>'; var footer_html = ''; var result = finalise_date(currentScript.getValue({ fieldId: 'start_date' })); if ((global_locked == 'yes' || result == false) && role == 1000 && zee != 6 && zee != 425904) { footer_html = '<span class="col-sm-10"><b>"Create Custom Invoice"</b> functionality will only be available on or after the last day of the month</span><button type="button" class="btn btn-default" data-dismiss="modal">Close</button>'; } else { footer_html = '<a href="https://1048144.app.netsuite.com/app/accounting/transactions/custinvc.nl?compid=1048144&cf=116&entity=' + global_customer + '&itemids=' + invoice_line_items.toString() + '&qty=' + invoice_line_qty.toString() + '&rate=' + invoice_line_rate.toString() + '&gst=' + invoice_line_gst.toString() + '&next_customer=' + next_customer + '&start_date=' + currentScript.getValue({ fieldId: 'start_date' }) + '&end_date=' + currentScript.getValue({ fieldId: 'end_date' }) + '" class="btn btn-primary" value="">Create Custom Invoice</a><button type="button" class="btn btn-default" data-dismiss="modal">Close</button>'; } $('.modal .modal-header').html('<div class="form-group"><h4><label class="control-label" for="inputError1">Invoice Preview</label></h4></div>'); $('.modal .modal-footer').html(footer_html); $('.modal .modal-body').html(""); $('.modal .modal-body').html(preview_html); $('.modal').modal("show"); }); /** * [description] - To update the Admin Fees Total when the rate is changed */ $(document).on('blur', '.admin_fees_rate', function(e) { var admin_fees = $(this).val(); var serviceid = $(this).attr('data-serviceid'); var jobid = $(this).attr('data-jobid'); var old_admin_fees = $(this).attr('data-oldvalue'); if (admin_fees != old_admin_fees) { if (!isNullorEmpty(serviceid)) { deleted_service_ids[deleted_service_ids.length] = serviceid; $(this).attr('data-serviceid', null); if (!isNullorEmpty(jobid)) { deleted_job_ids[deleted_job_ids.length] = jobid; $(this).attr('data-jobid', null); } } var admin_fees_qty = $(this).closest('tr').find('.admin_fees_qty').val(); var admin_fees_total = (parseFloat(admin_fees) * parseFloat(admin_fees_qty)); $(this).closest('tr').find('.admin_fees_total').val(admin_fees_total); updateTotal(); } }); /** * [description] - To update the Admin Fees Total when the qty is changed */ $(document).on('blur', '.admin_fees_qty', function(e) { var admin_fees_qty = $(this).val(); var admin_fees = $(this).closest('tr').find('.admin_fees_rate').val(); var admin_fees_total = (parseFloat(admin_fees) * parseFloat(admin_fees_qty)); $(this).closest('tr').find('.admin_fees_total').val(admin_fees_total); updateTotal(); }); /** * [description] - Css and toggle between the On/Off Button for Admin Fee */ $('.btn-toggle').click(function() { // alert(currentScript.getValue({ fieldId: 'admin_fees_not_applicable' })); if (global_locked != 'yes' && currentScript.getValue({ fieldId: 'admin_fees_not_applicable' }) != '1') { $(this).find('.btn').toggleClass('active'); if ($(this).find('.btn-success').size() > 0) { $(this).find('.btn').toggleClass('btn-success'); } $(this).find('.btn').toggleClass('btn-default'); } return false; }); /** * [description] - To show the Admin Fee Row */ $('.admin_fees_on').click(function() { $('.admin_fees_row').show(); $('.no_extras_class').hide(); var jobid = $('.admin_fees_rate').attr('data-jobid'); var serviceid = $('.admin_fees_rate').attr('data-serviceid'); if (isNullorEmpty(jobid) && isNullorEmpty(serviceid)) { $('.admin_fees_rate').val(9); $('.admin_fees_qty').val(1); $('.admin_fees_total').val(9); } else { var service_old_record = record.load({ type: 'customrecord_service', id: serviceid, }); var admin_fees = parseFloat(service_old_record.getValue({ fieldId: 'custrecord_service_price' })); var admin_fees_qty = 1; if (!isNullorEmpty(jobid)) { var job_old_record = record.load({ type: 'customrecord_job', id: jobid, }); admin_fees_qty = parseFloat(job_old_record.getValue({ fieldId: 'custrecord_job_extras_qty' })); } $('.admin_fees_rate').val(admin_fees); $('.admin_fees_qty').val(admin_fees_qty); $('.admin_fees_total').val((admin_fees * admin_fees_qty)); } admin_fees_log = true; updateTotal(); }); /** * [description] - To hide the Admin Fee Row */ $('.admin_fees_off').click(function() { $('.admin_fees_row').hide(); // $('.admin_fees_rate').val(0); // $('.admin_fees_qty').val(0); var jobid = $('.admin_fees_rate').attr('data-jobid'); var serviceid = $('.admin_fees_rate').attr('data-serviceid'); // $('.admin_fees_total').val(0); admin_fees_log = false; if (!isNullorEmpty(jobid)) { deleted_job_ids[deleted_job_ids.length] = jobid; } if (!isNullorEmpty(serviceid)) { deleted_service_ids[deleted_service_ids.length] = serviceid; } updateTotal(); }); } //ON CLICK OF THE APP COMPELTED QTY function onclick_StatusComplete(internal_id, service_rate, service_id, job_group, status, category, package_id, assign_packge) { //setReviewDate(internal_id); //REVIEW DATE IS SET FOR ALL THE JOBS var currentScript = currentRecord.get(); if (status == null) { var upload_url = baseURL + url.resolveScript({ scriptId: 'customscript_sl_job_page_2', deploymentId: 'customdeploy_job_page_2' }) + '&customer_id=' + internal_id + '&rate=' + service_rate + '&service_id=' + service_id + '&job_group=' + job_group + '&category=' + category + '&package=' + package_id + '&start_date=' + currentScript.getValue({ fieldId: 'start_date' }) + '&end_date=' + currentScript.getValue({ fieldId: 'end_date' }) + '&assign_packge=' + assign_packge + '&locked=' + global_locked + '&sc=' + currentScript.getValue({ fieldId: 'scid' }) + '&zee=' + currentScript.getValue({ fieldId: 'zee_id' }); window.open(upload_url, "_self", "height=750,width=650,modal=yes,alwaysRaised=yes"); } else { var upload_url = baseURL + url.resolveScript({ scriptId: 'customscript_sl_job_page_2', deploymentId: 'customdeploy_job_page_2' }) + '&customer_id=' + internal_id + '&rate=' + service_rate + '&service_id=' + service_id + '&job_group=' + job_group + '&status=' + status + '&category=' + category + '&package=' + package_id + '&start_date=' + currentScript.getValue({ fieldId: 'start_date' }) + '&end_date=' + currentScript.getValue({ fieldId: 'end_date' }) + '&assign_packge=' + assign_packge + '&locked=' + global_locked + '&sc=' + currentScript.getValue({ fieldId: 'scid' }) + '&zee=' + currentScript.getValue({ fieldId: 'zee_id' }); window.open(upload_url, "_self", "height=750,width=650,modal=yes,alwaysRaised=yes"); } } //ON CLICK OF THE APP PARTIALLY COMPLETED QTY function onclick_StatusPartial(internal_id, service_rate, service_id, job_group, status, category, package_id) { var currentScript = currentRecord.get(); //setReviewDate(internal_id); var upload_url = baseURL + url.resolveScript({ scriptId: 'customscript_sl_job_page_2', deploymentId: 'customdeploy_job_page_2' }) + '&customer_id=' + internal_id + '&rate=' + service_rate + '&service_id=' + service_id + '&job_group=' + job_group + '&status=' + status + '&category=' + category + '&package=' + package_id + '&start_date=' + currentScript.getValue({ fieldId: 'start_date' }) + '&end_date=' + currentScript.getValue({ fieldId: 'end_date' }) + '&locked=' + global_locked + '&sc=' + currentScript.getValue({ fieldId: 'scid' }) + '&zee=' + currentScript.getValue({ fieldId: 'zee_id' }); window.open(upload_url, "_self", "height=750,width=650,modal=yes,alwaysRaised=yes"); } //ON CLICK OF THE APP INCOMPLETE QTY function onclick_StatusIncomplete(internal_id, service_rate, service_id, job_group, status, category, package_id) { var currentScript = currentRecord.get(); // setReviewDate(internal_id); var upload_url = baseURL + url.resolveScript({ scriptId: 'customscript_sl_job_page_2', deploymentId: 'customdeploy_job_page_2' }) + '&customer_id=' + internal_id + '&rate=' + service_rate + '&service_id=' + service_id + '&job_group=' + job_group + '&status=' + status + '&category=' + category + '&package=' + package_id + '&start_date=' + currentScript.getValue({ fieldId: 'start_date' }) + '&end_date=' + currentScript.getValue({ fieldId: 'end_date' }) + '&locked=' + global_locked + '&sc=' + currentScript.getValue({ fieldId: 'scid' }) + '&zee=' + currentScript.getValue({ fieldId: 'zee_id' }); window.open(upload_url, "_self", "height=750,width=650,modal=yes,alwaysRaised=yes"); } //ON CLICK OF THE BACK TO SUMMARY BUTTON function onclick_summaryPage() { var currentScript = currentRecord.get(); var upload_url = baseURL + url.resolveScript({ scriptId: 'customscript_sl_summary_page_2', deploymentId: 'customdeploy_summary_page_2' }) + '&start_date=' + currentScript.getValue({ fieldId: 'start_date' }) + '&end_date=' + currentScript.getValue({ fieldId: 'end_date' }) + '&zee=' + currentScript.getValue({ fieldId: 'zee_id' }); window.open(upload_url, "_self", "height=750,width=650,modal=yes,alwaysRaised=yes"); } function onclick_reset() { window.location.href = window.location.href; } //ON CLICK OF ADD SERVICES BUTTON function addService(service_cat) { var currentScript = currentRecord.get(); //setReviewDate(currentScript.getValue({ fieldId: 'customer_id')) }; var upload_url = baseURL + url.resolveScript({ scriptId: 'customscript_sl_add_service_2', deploymentId: 'customdeploy_sl_add_service_2' }) + '&custid=' + currentScript.getValue({ fieldId: 'customer_id' }) + '&unlayered=T&service_cat=' + service_cat + '&start_date=' + currentScript.getValue({ fieldId: 'start_date' }) + '&end_date=' + currentScript.getValue({ fieldId: 'end_date' }) + '&locked=' + global_locked + '&sc=' + currentScript.getValue({ fieldId: 'scid' }) + '&zee=' + currentScript.getValue({ fieldId: 'zee_id' }); window.open(upload_url, "_self", "height=750,width=650,modal=yes,alwaysRaised=yes"); } //SET REVIEW DATE FUNCTION function setReviewDate(internal_id) { var currentScript = currentRecord.get(); var searched_jobs = search.load({ id: 'customsearch_inv_review_jobs_uninv', type: 'customrecord_job' }); searched_jobs.filters.push(search.createFilter({ name: 'custrecord_job_customer', operator: search.Operator.IS, values: internal_id, })); var resultSet = searched_jobs.run(); resultSet.each(function(searchResult) { var job_record = record.load({ type: 'customrecord_job', id: searchResult.getValue('internalid') }); job_record.setValue({ fieldId: 'custrecord_job_date_reviewed', value: getDate() }); job_record.save({ enableSourcing: true, ignoreMandatoryFields: true }) return true; }); return true; } function onclick_AssignPackage(internal_id, service_rate, service_id, job_group, status, category, package_id) { var currentScript = currentRecord.get(); var upload_url = baseURL + url.resolveScript({ scriptId: 'customscript_sl_assign_package_2', deploymentId: 'customdeploy_sl_assign_package_2' }) + '&customer_id=' + internal_id + '&service_id=' + service_id + '&job_group=' + job_group + '&status=' + status + '&rate=' + service_rate + '&category=' + category + '&package=' + package_id + '&start_date=' + currentScript.getValue({ fieldId: 'start_date' }) + '&end_date=' + currentScript.getValue({ fieldId: 'end_date' }); window.open(upload_url, "_self", "height=750,width=650,modal=yes,alwaysRaised=yes"); } function submit_package() { var currentScript = currentRecord.get(); var url = baseURL + url.resolveScript({ scriptId: 'customscript_sl_services_main_page_2', deploymentId: 'customdeploy_sl_services_main_page_2' }) + '&customer_id=' + currentScript.getValue({ fieldId: 'customer_id' }) + '&start_date=' + currentScript.getValue({ fieldId: 'start_date' }) + '&end_date=' + currentScript.getValue({ fieldId: 'end_date' }); window.open(url, "_self", "height=680,width=640,modal=yes,alwaysRaised=yes"); } //FUNCTION TO CALCULATE THE TOTAL INVOICEABLE AMOUNT FOR EACH AND EVERY SERVICE AND EXTRA function updateServiceAmount(rate, qty) { return (rate * qty); } function onclick_review() { var currentScript = currentRecord.get(); currentScript.setValue({ fieldId: 'review_button', value: 'T' }); $('#submitter').trigger('click'); } //ON CLICK OF NEXT CUSTOMER BUTTON function saveRecord(context) { var currentScript = currentRecord.get(); var customer_id = currentScript.getValue({ fieldId: 'customer_id' }); //WS Edit: Get Zee Customer from hidden field in Suitelet var zee_cust = parseInt(currentScript.getValue({ fieldId: 'zee_cust' })); //WS Edit: Can be deferred to Admin Fee section //var customerRec = record.load({ type: 'customer', id: customer_id }); //WS Edit: zee (from global variable) instead of franchisee //var franchisee = customerRec.getValue({ fieldId: 'partner' }); var franchisee = parseInt(zee); /*-----------------Derive CommReg for new Service Creation-----------------*/ var commReg_search = search.load({ id: 'customsearch_service_commreg_assign', type: 'customrecord_commencement_register' }); //WS Edit: filterExpression unsets existing filter commReg_search.filters.push(search.createFilter({ name: 'custrecord_customer', operator: search.Operator.ANYOF, values: customer_id } )); commReg_search.filters.push(search.createFilter({ name: 'custrecord_franchisee', operator: search.Operator.ANYOF, values: franchisee } )); var comm_reg_results = commReg_search.run(); var count_commReg = 0; var commReg = null; comm_reg_results.each(function(searchResult) { count_commReg++; /** * [if description] - Only the latest comm Reg needs to be assigned */ if (count_commReg == 1) { commReg = searchResult.getValue('internalid'); } /** * [if description] - if more than one Comm Reg, error mail is sent */ if (count_commReg > 1) { //WS Comment: Needs error error.create({ message: 'More than 1 Active CommReg', name: 'Customer ID: ' + customer_id, }); return false; } return true; }); /*-----------------NS Qty-----------------*/ //Set the jobs for NS Qty items var package_invoiceable_qty_elem = document.getElementsByClassName("package_netsuite_qty"); var job_description_elem = document.getElementsByClassName("job_description"); var single_job_description_elem = document.getElementsByClassName("single_job_description"); var service_id_array = []; var service_descp_array = []; var extra_service_id = []; var extra_qty = []; var extra_rate = []; var delete_job_id = []; var delete_service_id = []; var new_jobs_service_id = []; var new_jobs_rate = []; var new_jobs_qty = []; var new_jobs_cat = []; var new_jobs_descp = []; var new_jobs_package_id = []; var new_jobs_single_line = []; var new_service_type = []; var new_service_name = []; var new_service_price = []; var new_service_qty = []; var new_service_package_id = []; var new_service_customer = []; var new_service_comm_reg = []; var new_service_discount_type = []; var new_service_single_line = []; /*-----------------NS Qty: Get Field Values from Suitelet-----------------*/ for (var i = 0; i < package_invoiceable_qty_elem.length; ++i) { console.log('saveRecord loop ' + i) var initial_changed_qty = package_invoiceable_qty_elem[i].value; console.log(initial_changed_qty) var initial_load_qty = package_invoiceable_qty_elem[i].getAttribute("data-oldqty"); console.log(initial_load_qty) var service_id = package_invoiceable_qty_elem[i].getAttribute("data-serviceid"); console.log(service_id) var service_rate = package_invoiceable_qty_elem[i].getAttribute("data-rate"); console.log(service_rate) var service_cat = package_invoiceable_qty_elem[i].getAttribute("data-servicecat"); console.log(service_cat) var package = package_invoiceable_qty_elem[i].getAttribute("data-packageid"); console.log(package) var job_id = package_invoiceable_qty_elem[i].getAttribute("data-netsuitejob"); console.log(job_id) var default_ns_qty = package_invoiceable_qty_elem[i].getAttribute("default-value"); console.log(default_ns_qty) var default_description; var default_single_line; var single_line; var description; console.log(job_description_elem[i]) if (!isNullorEmpty(job_description_elem[i])) { if (!isNullorEmpty(job_description_elem[i].value)) { var default_description = job_description_elem[i].getAttribute("default-value"); console.log(default_description) var default_single_line = job_description_elem[i].getAttribute("default-singleline"); console.log(default_single_line) var single_line = job_description_elem[i].getAttribute("data-singleline"); console.log(single_line) service_id_array.push(job_description_elem[i].getAttribute("data-serviceid")); console.log(job_description_elem[i].getAttribute("data-serviceid")) service_descp_array.push(job_description_elem[i].value); description = job_description_elem[i].value; } } // single_line.push(job_description_elem[i].getAttribute("data-singleline")) var jobs_to_create = parseFloat(initial_changed_qty); /*-----------------Package: Identify and Create Jobs-----------------*/ if (description != default_description || default_ns_qty != initial_changed_qty) { if (jobs_to_create > 0 || !isNullorEmpty(description)) { if (service_id != 242 && service_id != 243 && service_id != 1904 && service_id != 241) { if (isNullorEmpty(job_id) || job_id == 'null') { if (zee == zee_cust) { createJobRecord(customer_id, service_id, service_rate, jobs_to_create, description, service_cat, package, single_line, null); } else { new_jobs_service_id[new_jobs_service_id.length] = service_id; new_jobs_rate[new_jobs_rate.length] = service_rate; new_jobs_qty[new_jobs_qty.length] = jobs_to_create; new_jobs_cat[new_jobs_cat.length] = service_cat; new_jobs_descp[new_jobs_descp.length] = description; new_jobs_single_line[new_jobs_single_line.length] = single_line; if (!isNullorEmpty(package)) { new_jobs_package_id[new_jobs_package_id.length] = package; } } } else { updateJobRecord(job_id, null, jobs_to_create, description, null, null, null, null); } } else { extra_service_id[extra_service_id.length] = service_id; extra_qty[extra_qty.length] = jobs_to_create; extra_rate[extra_rate.length] = service_rate; } } else if (jobs_to_create == 0 && isNullorEmpty(description)) { if (!isNullorEmpty(job_id) && job_id != 'null') { delete_job_id[delete_job_id.length] = job_id; // nlapiDeleteRecord('customrecord_job', job_id); } } } } var discount_type_elem = document.getElementsByClassName("discount_type"); var discount_value_elem = document.getElementsByClassName("discount_value"); var discount_qty_elem = document.getElementsByClassName("discount_qty"); var total_discount_elem = document.getElementsByClassName("total_discount_value"); var invoice_single_line_elem = document.getElementsByClassName("invoice_single_line"); var total_package_value = document.getElementsByClassName("total_package_value"); var single_line_hidden = document.getElementsByClassName("single_line_hidden"); var fixed_discount_value = document.getElementsByClassName("fixed_discount_value"); /*-----------------Package: Identify and Create Discount Services + Jobs-----------------*/ if (!isNullorEmpty(total_discount_elem)) { for (var i = 0; i < total_discount_elem.length; ++i) { var job_id = total_discount_elem[i].getAttribute('data-netsuitejob'); var default_description_value = single_job_description_elem[i].getAttribute('default-value'); var description_value = single_job_description_elem[i].value; var default_total_discount_value = total_discount_elem[i].getAttribute('default-value'); var single_line_hidden_default = single_line_hidden[i].getAttribute('default-singleline'); var total_discount_value = total_discount_elem[i].value; var single_line_hidden_value = single_line_hidden[i].value; if (isNullorEmpty(single_line_hidden_value)) { single_line_hidden_value = single_line_hidden_default; } if (isNullorEmpty(job_id) || job_id == 'null') { if (total_discount_elem[i].hasAttribute("data-package")) { var package_id = total_discount_elem[i].getAttribute('data-package'); } var package_record = record.load({ type: 'customrecord_service_package', id: package_id, }); var discount_period = package_record.getValue({ fieldId: 'custrecord_service_package_disc_period' }); if (zee == zee_cust) { var service_price; if (discount_period == 3) { service_price = total_package_value[i].value; } else { if (single_line_hidden_value == 1) { service_price = fixed_discount_value[i].value; } else { service_price = discount_value_elem[i].value; } } // alert(package_id); var service_id = createServiceRecord(17, 'Discount', service_price, customer_id, commReg, package_id); var service_rate; var service_qty; var discount_type; if (discount_period == 3) { service_rate = total_package_value[i].value; service_qty = 1; } else { if (single_line_hidden_value == 1) { service_rate = fixed_discount_value[i].value; } else { service_rate = discount_value_elem[i].value; } service_qty = discount_qty_elem[i].value; if (!isNullorEmpty(discount_type_elem[i])) { if (isNullorEmpty(discount_type_elem[i].getAttribute('data-value'))) { discount_type = null; } else { discount_type = discount_type_elem[i].getAttribute('data-value'); } } } createJobRecord(customer_id, service_id, service_rate, service_qty, description, 2, package_id, invoice_single_line_elem[i].value, discount_type); } else { if (discount_period == 3) { new_service_price[new_service_price.length] = total_package_value[i].value; new_service_qty[new_service_qty.length] = 1; } else { if (single_line_hidden_value == 1) { new_service_price[new_service_price.length] = fixed_discount_value[i].value; } else { new_service_price[new_service_price.length] = discount_value_elem[i].value; } new_service_qty[new_service_qty.length] = discount_qty_elem[i].value; if (!isNullorEmpty(discount_type_elem[i])) { if (isNullorEmpty(discount_type_elem[i].getAttribute('data-value'))) { new_service_discount_type[new_service_discount_type.length] = null; } else { new_service_discount_type[new_service_discount_type.length] = discount_type_elem[i].getAttribute('data-value'); } } } if (!isNullorEmpty(package_id)) { new_service_package_id[new_service_package_id.length] = package_id; } if (!isNullorEmpty(commReg)) { new_service_comm_reg[new_service_comm_reg.length] = commReg; } new_service_customer[new_service_customer.length] = customer_id; new_service_type[new_service_type.length] = 17; new_service_name[new_service_name.length] = 'Discount'; new_service_single_line[new_service_single_line.length] = invoice_single_line_elem[i].value; } } else { var job_new_record = record.load({ type: 'customrecord_job', id: job_id }); var service_id = job_new_record.getValue({ fieldId: 'custrecord_job_service' }); if (total_discount_elem[i].hasAttribute("data-package")) { var package_id = total_discount_elem[i].getAttribute('data-package'); } var package_record = record.load({ type: 'customrecord_service_package', id: package_id }); var discount_period = package_record.getValue({ fieldId: 'custrecord_service_package_disc_period' }); var service_record = record.load({ type: 'customrecord_service', id: service_id }); if (discount_period == 3) { service_record.setValue({ fieldId: 'custrecord_service_price', value: total_package_value[i].value }); } else { if (single_line_hidden_value == 1) { service_record.setValue({ fieldId: 'custrecord_service_price', value: fixed_discount_value[i].value }); } else { service_record.setValue({ fieldId: 'custrecord_service_price', value: discount_value_elem[i].value }); } } if (!isNullorEmpty(package_id)) { service_record.setValue({ fieldId: 'custrecord_service_package', value: package_id }); } service_record.save({ enableSourcing: true, ignoreMandatoryFields: true }); var service_rate; var service_qty; var discount_type; if (discount_period == 3) { service_rate = total_package_value[i].value; service_qty = 1; } else { if (single_line_hidden_value == 1) { service_rate = fixed_discount_value[i].value; } else { service_rate = discount_value_elem[i].value; } service_qty = discount_qty_elem[i].value; if (!isNullorEmpty(discount_type_elem[i])) { if (isNullorEmpty(discount_type_elem[i].getAttribute('data-value'))) { discount_type = null; } else { discount_type = discount_type_elem[i].getAttribute('data-value'); } } } updateJobRecord(job_id, service_rate, service_qty, single_job_description_elem[i].value, null, package_id, invoice_single_line_elem[i].value, discount_type); } } } /*-----------------Admin Fees-----------------*/ //WS Edit: Only allow adjustments on Admin fee to be made by Customer Zee. Other Zee cannot update Admin fee arrangements. if (zee == zee_cust) { var customerRec = record.load({ type: 'customer', id: customer_id }); var admin_fees_rate_elem = document.getElementsByClassName("admin_fees_rate"); var admin_fees_qty_elem = document.getElementsByClassName("admin_fees_qty"); /*-----------------Admin Fees: NO-----------------*/ if (admin_fees_log == false || admin_fees_log == 'false') { if (!isNullorEmpty(deleted_service_ids)) { // alert(deleted_service_ids); for (var i = 0; i < deleted_service_ids.length; i++) { var searchedJobsResult = adminFeesServiceCheck(customer_id, deleted_service_ids[i], deleted_job_ids); if (isNullorEmpty(searchedJobsResult)) { delete_service_id[delete_service_id.length] = deleted_service_ids[i]; } else { if (searchedJobsResult.length == 1) { var service_old_record = record.load({ type: 'customrecord_service', id: deleted_service_ids }[i]); service_old_record.setValue({ fieldId: 'isinactive', value: 'T' }); service_old_record.save({ enableSourcing: true, ignoreMandatoryFields: true }); // delete_service_id[delete_service_id.length] = deleted_service_ids[i]; } } } } if (!isNullorEmpty(deleted_job_ids)) { for (var i = 0; i < deleted_job_ids.length; i++) { delete_job_id[delete_job_id.length] = deleted_job_ids[i]; // nlapiDeleteRecord('customrecord_job', deleted_job_ids[i]); } } $('.admin_fees_rate').val(0); $('.admin_fees_qty').val(0); customerRec.setValue({ fieldId: 'custentity_admin_fees', value: null }); } console.log('Before admin') /*-----------------Admin Fees: YES-----------------*/ /** * To capture the Admin Fee information */ if (admin_fees_log == true || admin_fees_log == 'true') { for (var i = 0; i < admin_fees_rate_elem.length; ++i) { var jobid = (admin_fees_rate_elem[i].getAttribute("data-jobid")); var serviceid = (admin_fees_rate_elem[i].getAttribute("data-serviceid")); var old_admin_fees = admin_fees_rate_elem[i].getAttribute("data-oldvalue"); var admin_fees = admin_fees_rate_elem[i].value; var admin_qty = admin_fees_qty_elem[i].value; if (isNullorEmpty(admin_fees) || admin_fees == 0 || isNullorEmpty(admin_qty) || admin_qty == 0) { customerRec.setValue({ fieldId: 'custentity_admin_fees', value: null }); if (!isNullorEmpty(jobid)) { delete_job_id[delete_job_id.length] = jobid; // nlapiDeleteRecord('customrecord_job', jobid); } if (!isNullorEmpty(serviceid)) { var searchedJobsResult = adminFeesServiceCheck(customer_id, serviceid, delete_job_id); if (isNullorEmpty(searchedJobsResult)) { delete_service_id[delete_service_id.length] = serviceid; } else { if (searchedJobsResult.length == 1) { var service_old_record = record.load({ type: 'customrecord_service', id: serviceid }); service_old_record.setValue({ fieldId: 'isinactive', value: 'T' }); service_old_record.save({ enableSourcing: true, ignoreMandatoryFields: true }); // delete_service_id[delete_service_id.length] = deleted_service_ids[i]; } } } } else { if (!isNullorEmpty(deleted_service_ids)) { for (var i = 0; i < deleted_service_ids.length; i++) { var searchedJobsResult = adminFeesServiceCheck(customer_id, deleted_service_ids[i], deleted_job_ids); if (isNullorEmpty(searchedJobsResult)) { delete_service_id[delete_service_id.length] = deleted_service_ids[i]; } else { if (searchedJobsResult.length == 1) { var service_old_record = record.load({ type: 'customrecord_service', id: deleted_service_ids }[i]); service_old_record.setValue({ fieldId: 'isinactive', value: 'T' }); service_old_record.save({ enableSourcing: true, ignoreMandatoryFields: true }); // delete_service_id[delete_service_id.length] = deleted_service_ids[i]; } } } } if (!isNullorEmpty(deleted_job_ids)) { for (var i = 0; i < deleted_job_ids.length; i++) { delete_job_id[delete_job_id.length] = deleted_job_ids[i]; // nlapiDeleteRecord('customrecord_job', deleted_job_ids[i]); } } if (isNullorEmpty(serviceid)) { //Put code to check if the Admin Fee Service with the Same Price exists or not. If it exists and is Inactive, activate it and update. If no service exists, create a new service var searchedServicesResult = searchAdminFeesService(customer_id, admin_fees); if (isNullorEmpty(searchedServicesResult)) { var service_record = record.create({ type: 'customrecord_service', isDynamic: true, }); service_record.setValue({ fieldId: 'custrecord_service', value: 22 }); service_record.setValue({ fieldId: 'name', value: search.lookupFields({ type: 'customrecord_service_type', id: 22, columns: 'name' }) }); //WS Edit: cannot set franchisee in Client. //service_record.setValue({ fieldId: 'custrecord_service_franchisee', value: zee); service_record.setValue({ fieldId: 'custrecord_service_customer', value: customer_id }); //WS } Edit: Need to deal with null commReg. //service_record.setValue({ fieldId: 'custrecord_service_comm_reg', value: commReg); if (!isNullorEmpty(commReg)) { service_record.setValue({ fieldId: 'custrecord_service_comm_reg', value: commReg }); } } else { if (searchedServicesResult.length == 1) { var service_record = record.load({ type: 'customrecord_service', id: searchedServicesResult[0].getValue('internalid') }); service_record.setValue({ fieldId: 'isinactive', value: 'F' }); } else { //Throw Error } } } else { var service_record = record.load({ type: 'customrecord_service', id: serviceid }); } service_record.setValue({ fieldId: 'custrecord_service_price', value: admin_fees }); var new_service_id = service_record.save({ enableSourcing: true, ignoreMandatoryFields: true }); if (isNullorEmpty(jobid)) { var job_record = record.create({ type: 'customrecord_job', isDynamic: true, }); job_record.setValue({ fieldId: 'custrecord_job_status', value: 3 }); job_record.setValue({ fieldId: 'custrecord_job_invoiceable', value: 1 }); job_record.setValue({ fieldId: 'custrecord_job_date_reviewed', value: getDate() }); job_record.setValue({ fieldId: 'custrecord_job_source', value: 5 }); job_record.setValue({ fieldId: 'custrecord_job_service_category', value: 2 }); job_record.setValue({ fieldId: 'custrecord_job_customer', value: customer_id }); // } job_record.setValue({ fieldId: 'custrecord_job_franchisee', value: zee); } else { var job_record = record.load({ type: 'customrecord_job', id: jobid }); } job_record.setValue({ fieldId: 'custrecord_job_service', value: new_service_id }); job_record.setValue({ fieldId: 'custrecord_job_extras_qty', value: admin_qty }); job_record.setValue({ fieldId: 'custrecord_job_service_price', value: admin_fees}); job_record.setValue({ fieldId: 'custrecord_job_date_scheduled', value: currentScript.getValue({ fieldId: 'end_date' }) }); job_record.save({ enableSourcing: true, ignoreMandatoryFields: true }); customerRec.setValue({ fieldId: 'custentity_admin_fees', value: admin_fees }); } } } console.log('after admin') customerRec.setValue({ fieldId: 'custentity11', value: $('.customer_po').val() }); customerRec.save({ enableSourcing: true, ignoreMandatoryFields: true }); } var extra_service_string = extra_service_id.join(); var extra_qty_string = extra_qty.join(); var extra_rate_string = extra_rate.join(); console.log(delete_job_id); var unique_delete_jobs = removeDuplicateUsingFilter(delete_job_id); var unique_delete_services = removeDuplicateUsingFilter(delete_service_id); console.log(unique_delete_jobs); var delete_job_id_string = unique_delete_jobs.join(); var delete_service_id_string = unique_delete_services.join(); var new_jobs_service_id_string = new_jobs_service_id.join(); var new_jobs_rate_string = new_jobs_rate.join(); var new_jobs_qty_string = new_jobs_qty.join(); var new_jobs_cat_string = new_jobs_cat.join(); var new_jobs_descp_string = new_jobs_descp.join(); var new_jobs_package_id_string = new_jobs_package_id.join(); var new_jobs_single_line_string = new_jobs_single_line.join(); var new_service_type_string = new_service_type.join(); var new_service_name_string = new_service_name.join(); var new_service_price_string = new_service_price.join(); var new_service_qty_string = new_service_qty.join(); var new_service_discount_type_string = new_service_discount_type.join(); var new_service_package_id_string = new_service_package_id.join(); var new_service_customer_string = new_service_customer.join(); var new_service_comm_reg_string = new_service_comm_reg.join(); var new_service_single_line_string = new_service_single_line.join(); // alert(delete_service_id); currentScript.setValue({ fieldId: 'extra_service_string', value: extra_service_string }); currentScript.setValue({ fieldId: 'extra_qty_string', value: extra_qty_string }); currentScript.setValue({ fieldId: 'extra_rate_string', value: extra_rate_string }); currentScript.setValue({ fieldId: 'delete_job_id_string', value: delete_job_id_string }); currentScript.setValue({ fieldId: 'delete_service_id_string', value: delete_service_id_string }); currentScript.setValue({ fieldId: 'new_jobs_service_id_string', value: new_jobs_service_id_string }); currentScript.setValue({ fieldId: 'new_jobs_rate_string', value: new_jobs_rate_string }); currentScript.setValue({ fieldId: 'new_jobs_qty_string', value: new_jobs_qty_string }); currentScript.setValue({ fieldId: 'new_jobs_cat_string', value: new_jobs_cat_string }); currentScript.setValue({ fieldId: 'new_jobs_descp_string', value: new_jobs_descp_string }); currentScript.setValue({ fieldId: 'new_jobs_package_id_string', value: new_jobs_package_id_string }); currentScript.setValue({ fieldId: 'new_jobs_single_line_string', value: new_jobs_single_line_string }); currentScript.setValue({ fieldId: 'new_service_type_string', value: new_service_type_string }); currentScript.setValue({ fieldId: 'new_service_name_string', value: new_service_name_string }); currentScript.setValue({ fieldId: 'new_service_price_string', value: new_service_price_string }); currentScript.setValue({ fieldId: 'new_service_qty_string', value: new_service_qty_string }); currentScript.setValue({ fieldId: 'new_service_discount_type_string', value: new_service_discount_type_string }); currentScript.setValue({ fieldId: 'new_service_package_id_string', value: new_service_package_id_string }); currentScript.setValue({ fieldId: 'new_service_customer_string', value: new_service_customer_string }); currentScript.setValue({ fieldId: 'new_service_comm_reg_string', value: new_service_comm_reg_string }); currentScript.setValue({ fieldId: 'new_service_single_line_string', value: new_service_single_line_string }); return true; } function adminFeesServiceCheck(customer_id, service_id, deleted_job_ids) { var searched_jobs = search.load({ id: 'customrecord_job', type: 'customsearch_job_inv_review_all' }); searched_jobs.filters.push(search.createFilter({ name: 'custrecord_job_customer', operator: search.Operator.IS, values: customer_id })); searched_jobs.filters.push(search.createFilter({ name: 'custrecord_job_service', operator: search.Operator.IS, values: service_id })); if (!isNullorEmpty(deleted_job_ids)) { searched_jobs.filters.push(search.createFilter({ name: 'internalid', operator: search.Operator.NONEOF, values: deleted_job_ids })); } var resultSet = searched_jobs.run(); var searchedJobsResult = resultSet.getRange({ start: 0, end: 1 }); return searchedJobsResult; } function searchAdminFeesService(customer_id, admin_fees) { var searched_services = search.load({ id: 'customrecord_service', type: 'customsearch_aic_review_services' }); searched_services.filters.push(search.createFilter({ name: 'custrecord_service_customer', operator: search.Operator.IS, values: customer_id })); searched_services.filters.push(search.createFilter({ name: 'custrecord_service', operator: search.Operator.IS, values: 22 })); searched_services.filters.push(search.createFilter({ name: 'custrecord_service_price', operator: search.Operator.EQUALTO, values: admin_fees })); var resultSet = searched_services.run(); var searchedServicesResult = resultSet.getRange({ start: 0, end: 2 }); return searchedServicesResult; } //FUNCTION TO CALCULATE THE TOTAL INVOICE FOR THE CUSTOMER function updateTotal() { var total_invoice = 0.0; var total_package_elem = document.getElementsByClassName("total_package_value"); var total_service_elem = document.getElementsByClassName("service_total"); var admin_fees_total_elem = document.getElementsByClassName("admin_fees_total"); var customer_admin_fees = document.getElementsByClassName("customer_admin_fees"); for (var i = 0; i < total_package_elem.length; ++i) { if (typeof total_package_elem[i].value !== "undefined") { total_invoice = total_invoice + parseFloat(total_package_elem[i].value); } } for (var i = 0; i < total_service_elem.length; ++i) { if (typeof total_service_elem[i].value !== "undefined") { total_invoice = total_invoice + parseFloat(total_service_elem[i].value); } } if (admin_fees_log == true || admin_fees_log == 'true') { for (var i = 0; i < admin_fees_total_elem.length; ++i) { // console.log(admin_fees_total_elem[i].value) if (typeof admin_fees_total_elem[i].value !== "undefined" && admin_fees_total_elem[i].value != "NaN") { total_invoice = total_invoice + parseFloat(admin_fees_total_elem[i].value); } } } $('.total_value').val(total_invoice); } function GetFormattedDate(stringDate) { var todayDate = format.parse({ value: stringDate, type: format.Type.DATE }); var month = pad(todayDate.getMonth() + 1); var day = pad(todayDate.getDate()); var year = (todayDate.getFullYear()); return year + "-" + month + "-" + day; } function pad(s) { return (s < 10) ? '0' + s : s; } function finalise_date(start_date) { var split_date = start_date.split('/'); var date = new Date(); var month = date.getMonth(); //Months 0 - 11 var today = date.getDate(); var year = date.getFullYear(); var lastDay = new Date(split_date[2], split_date[1], 0); var currentLastDay = new Date(year, (month + 1), 0); if (lastDay.getDay() == 0) { lastDay.setDate(lastDay.getDate() - 2); } else if (lastDay.getDay() == 6) { lastDay.setDate(lastDay.getDate() - 1); } var lastWorkingDay = lastDay.getDate(); var lastWorkingDayPlus5 = new Date(); lastDay.setDate(lastDay.getDate() + 5); var button = false; console.log(parseInt(year) === parseInt(split_date[2])); console.log(parseInt(split_date[1]) === parseInt(month + 1)); console.log(today < lastWorkingDay); //If allocator run on the first day of the month, it takes the last month as the filter if (parseInt(year) === parseInt(split_date[2]) && parseInt(split_date[1]) === parseInt(month + 1) && today < lastWorkingDay) { console.log('inside') } else if ((lastWorkingDay == today || today <= currentLastDay.getDate())) { console.log('inside 2') button = true; } return button; } function createServiceRecord(service_type, service_name, price, customer_id, commReg, package_id) { try { var new_service_record = record.create({ type: 'customrecord_service', isDynamic: true, }); new_service_record.setValue({ fieldId: 'custrecord_service', value: service_type }); new_service_record.setValue({ fieldId: 'name', value: service_name }); new_service_record.setValue({ fieldId: 'custrecord_service_price', value: price }); new_service_record.setValue({ fieldId: 'custrecord_service_customer', value: customer_id }); if (!isNullorEmpty(commReg)) { new_service_record.setValue({ fieldId: 'custrecord_service_comm_reg', value: commReg }); } if (!isNullorEmpty(package_id)) { new_service_record.setValue({ fieldId: 'custrecord_service_package', value: package_id }); } var service_id = new_service_record.save({ enableSourcing: true, ignoreMandatoryFields: true }); return service_id; } catch (e) { var message = ''; message += "Customer Internal ID: " + customer_id + "</br>"; message += "Customer: <a href ='https://1048144.app.netsuite.com/app/common/entity/custjob.nl?id=" + customer_id + "'> View Customer </a></br>"; message += "----------------------------------------------------------------------------------</br>"; message += "Service Type: <a href ='https://1048144.app.netsuite.com/app/common/custom/custrecordentry.nl?rectype=949&id=" + service_type + "'> View Service Type</a></br>"; message += "----------------------------------------------------------------------------------</br>"; message += e; email.send({ author: 409635, body: message, recipients: ['PI:EMAIL:upchh@example.comEND_PI', 'PI:EMAIL:ychag@example.comEND_PI'], subject: 'AIC Review Page - Service Creation - Unable to create Service', }); return false; } } function createJobRecord(customer_id, service_id, rate, qty, description, category, package_id, invoice_single_line, discount_type) { var currentScript = currentRecord.get(); try { // alert(package_id) var job_new_record = record.create({ type: 'customrecord_job', isDynamic: true, }); job_new_record.setValue({ fieldId: 'custrecord_job_customer', value: customer_id }); // job_new_record.setValue({ fieldId: 'custrecord_job_franchisee', value: zee }); job_new_record.setValue({ fieldId: 'custrecord_job_service', value: service_id }); job_new_record.setValue({ fieldId: 'custrecord_job_service_price', value: rate }); job_new_record.setValue({ fieldId: 'custrecord_job_extras_qty', value: qty }); job_new_record.setValue({ fieldId: 'custrecord_job_status', value: 3 }); job_new_record.setValue({ fieldId: 'custrecord_job_invoiceable', value: 1 }); job_new_record.setValue({ fieldId: 'custrecord_job_date_reviewed', value: getDate() }); job_new_record.setValue({ fieldId: 'custrecord_job_source', value: 5 }); job_new_record.setValue({ fieldId: 'custrecord_job_invoice_detail', value: description }); job_new_record.setValue({ fieldId: 'custrecord_job_date_scheduled', value: currentScript.getValue({ fieldId: 'end_date' }) }); if (category == '1') { job_new_record.setValue({ fieldId: 'custrecord_job_group_status', value: 'Completed' }); } if (!isNullorEmpty(package_id)) { job_new_record.setValue({ fieldId: 'custrecord_job_service_package', value: package_id }); job_new_record.setValue({ fieldId: 'custrecord_job_invoice_single_line_item', value: invoice_single_line }); } job_new_record.setValue({ fieldId: 'custrecord_job_service_category', value: category }); job_new_record.setValue({ fieldId: 'custrecord_job_discount_type', value: discount_type }); job_new_record.save({ enableSourcing: true, ignoreMandatoryFields: true }); } catch (e) { var message = ''; message += "Customer Internal ID: " + customer_id + "</br>"; message += "Customer: <a href ='https://1048144.app.netsuite.com/app/common/entity/custjob.nl?id=" + customer_id + "'> View Customer </a></br>"; message += "----------------------------------------------------------------------------------</br>"; if (!isNullorEmpty(service_id) || service_id != false) { message += "Service: <a href ='https://1048144.app.netsuite.com/app/common/custom/custrecordentry.nl?rectype=946&id=" + service_id + "'> View Service Type</a></br>"; message += "----------------------------------------------------------------------------------</br>"; } message += e; email.send({ author: 409635, body: message, recipients: ['PI:EMAIL:upchh@example.comEND_PI', 'PI:EMAIL:ychag@example.comEND_PI'], subject: 'AIC Review Page - Job Creation - Unable to create Job' }); // return false; } } function updateJobRecord(job_id, rate, qty, description, category, package_id, invoice_single_line, discount_type) { var job_record = record.load({ type: 'customrecord_job', id: job_id, }); job_record.setValue({ fieldId: 'custrecord_job_extras_qty', value: qty }); job_record.setValue({ fieldId: 'custrecord_job_source', value: 5 }); job_record.setValue({ fieldId: 'custrecord_job_invoice_detail', value: description }); if (!isNullorEmpty(package_id)) { job_record.setValue({ fieldId: 'custrecord_job_service_package', value: package_id }); } if (!isNullorEmpty(rate)) { job_record.setValue({ fieldId: 'custrecord_job_service_price', value: rate }); } job_record.setValue({ fieldId: 'custrecord_job_invoice_detail', value: description }); job_record.setValue({ fieldId: 'custrecord_job_invoice_single_line_item', value: invoice_single_line }); job_record.setValue({ fieldId: 'custrecord_job_discount_type', value: discount_type }); job_record.save({ enableSourcing: true, ignoreMandatoryFields: true }); } function removeDuplicateUsingFilter(arr) { var unique_array = []; for (var i = 0; i < arr.length; i++) { if (unique_array.indexOf(arr[i]) == -1) { unique_array.push(arr[i]); } } return unique_array } function isNullorEmpty(strVal) { return (strVal == null || strVal == '' || strVal == 'null' || strVal == undefined || strVal == 'undefined' || strVal == '- None -'); } return { pageInit: pageInit, saveRecord: saveRecord, onclick_review: onclick_review, onclick_summaryPage: onclick_summaryPage, onclick_reset: onclick_reset }; } );