Adding currency as default value on record initialization on vendor payment record using suitescript to get the correct apply sublist data

I am trying to create a vendorpayment record using script. This is my script.

var transactionId = '11111';
var vendorId = '222';
var subsidiaryId = '2';
var apAccountId = '333'
var inputAmount = 1000;
var currencyId = '4'; //USD

var make_billPayment_record = record.create({
    type: 'vendorpayment',
    defaultValues: { entity: vendorId, subsidiary: subsidiaryId, apacct: apAccountId }
});
if(!!currencyId){make_billPayment_record.setValue({ fieldId: 'currency', value: currencyId });}; //Currency
if(!!bankAccountId){make_billPayment_record.setValue({ fieldId: 'account', value: bankAccountId });}; //Account
if(!!departmentId){make_billPayment_record.setValue({ fieldId: 'department', value: departmentId });}; //Department
if(!!classId){make_billPayment_record.setValue({ fieldId: 'class', value: classId });}; //Cash Flow Segment
if(!!exchangeRate){make_billPayment_record.setValue({ fieldId: 'exchangerate', value: parseFloat(exchangeRate) });}; //Exchange Rate
make_billPayment_record.setValue({ fieldId: 'custbody_9997_is_for_ep_eft', value: true }); //For Electronic Bank Payment

var apply_numLines = make_billPayment_record.getLineCount({sublistId: 'apply'});

for(i = 0; i < apply_numLines; i++){
    var lineTxnId = make_billPayment_record.getSublistValue({
        sublistId: 'apply',
        fieldId: 'internalid',
        line: i
    });
    if(parseFloat(lineTxnId) == parseFloat(transactionId)){
        make_billPayment_record.setSublistValue({
            sublistId: 'apply',
            fieldId: 'apply',
            line: i,
            value: true
        });
        make_billPayment_record.setSublistValue({
            sublistId: 'apply',
            fieldId: 'amount',
            line: i,
            value: parseFloat(inputAmount)
        });
    }
};

var created_bp_id = make_billPayment_record.save({ enableSourcing: true, ignoreMandatoryFields: true });

I am aware that you cannot create a list on vendorpayment, it is preloaded based on the vendor, subsidiary and currency and you have to iterate each line and apply the transaction. The thing that I am having trouble with is initializing that list. When I do record.create with default values, the initialized sublist data does not contain the apply line that I am looking for because the default currency being set is different. When I add currency as a default value on my record.create, Netsuite is giving me an error {“name”:”INVALID_RCRD_INITIALIZE”,”message”:”You have entered an invalid default value for this record initialize operation.”}. I also tried creating a vendorpayment record without applying any transactions first but Netsuite is also giving me an error “You must enter at least one line item for this transaction.”

If I can’t initialize record.create with currencyId, I can’t get the correct apply sublist data.

If initializing record with currencyId is not possible, is there a way for me to get the correct apply sublist? Or is there a different way to achieve what I am trying to do?
Any help would be appreciated, thanks.

Winston optionally include label

So I am writing up Node.js Express.js API that utilizes winston for logging. I was hoping if I could achieve a log that looks like this:

[Timestamp] [label] [level]: message

So far I have been able to have the timestamp, level, and messsage. Can anyone help me with how I need to modify the code?

.utilslogger.js

const { createLogger, format, transports } = require('winston')
const config = require('../configs/app.conf')

const devFormat = format.printf(({ timestamp, level, message }) => `${timestamp} ${level}: ${message}`)
const prodFormat = format.printf(({ level, message }) => `${level}: ${message}`)

const logger = createLogger({
    level: 'debug',
    format: format.combine(
        format.timestamp({ format: 'YYYY-MM-DD HH:mm:ss' }),
        format.errors({ stack: true }),
        format.splat(),
        format.json()
    ),
    transports: [
        new transports.Console({
            format: format.combine(
                format.colorize(),
                config.env === 'development' ? devFormat : prodFormat
            )
        }),
        new transports.File({ filename: 'logs/error.log', level: 'error' }),
        new transports.File({ filename: 'logs/combined.log' })
    ]
})

module.exports = logger

.index.js

const express = require('express')
const cors = require('cors')
const useragent = require('express-useragent')
const cookieParser = require('cookie-parser')
const app = express()
const logger = require('./utils/logger')
const errorHandler = require('./middlewares/ErrorHandler')
const config = require('./configs/app.conf')
const { connectDB } = require('./db/database')

app.use(cors({
    origin: [
        'http://localhost:5173',
        'https://localhost:5173',
    ],
    methods: 'GET,POST,DELETE,PUT,PATCH',
    allowedHeaders: 'Content-Type,Accept,Authorization,x-requested-with',
    credentials: true,
}))

app.use(express.json())
app.use(express.urlencoded({ extended: true }))
app.use(useragent.express())
app.use(cookieParser())
app.set('trust proxy', true)

app.use('/user', require('./routes/userRoutes'))

app.use(errorHandler)

const startServer = async () => {
    try {
        await connectDB()

        app.listen(config.port, () => logger.info(`Server running in ${config.env} mode at port ${config.port}`))
    }
    catch (error) {
        logger.error(error.message)
        process.exit(1)
    }
}

startServer()

.middlewaresErrorHandler.js

const logger = require('../utils/logger')

const errorHandler = (err, req, res) => {
    const statusCode = res.statusCode || 500

    logger.error(`[${statusCode}] ${err.message}`, {
        method: req.method,
        path: req.originalUrl,
        ip: req.ip,
        userAgent: req.headers['user-agent'],
        stack: err.stack
    })

    res.status(statusCode).json({
        title: getErrorTitle(statusCode),
        message: err.message,
        stackTrace: err.stack
    })
}

const getErrorTitle = (statusCode) => {
    const titles = {
        400: "Bad Request",
        401: "Unauthorized",
        403: "Forbidden",
        404: "Not Found",
        405: "Method Not Allowed",
        406: "Not Acceptable",
        408: "Request Timeout",
        409: "Conflict",
        410: "Gone",
        413: "Payload Too Large",
        414: "URI Too Long",
        415: "Unsupported Media Type",
        422: "Unprocessable Entity",
        429: "Too Many Requests",
        500: "Internal Server Error",
        502: "Bad Gateway",
        503: "Service Unavailable",
        504: "Gateway Timeout"
    }

    return titles[statusCode] || "Unexpected Error"
}

module.exports = errorHandler

.dbdatabase.js

const { MongoClient, ServerApiVersion } = require('mongodb')
const logger = require('../utils/logger')
const config = require('../configs/app.conf')

let client

const connectDB = async () => {
    if (!client) {
        try {
            client = await MongoClient.connect(config.db_url, {
                serverApi: {
                    version: ServerApiVersion.v1,
                    strict: true,
                    deprecationErrors: true
                }
            })
            logger.info('Connected to MongoDB')
        }
        catch (error) {
            throw new Error(error.message)
        }
    }

    return client.db()
}

module.exports = { connectDB }

I was hoping to achieve like for example in the database, if I log the success message, I could somehow make it timestamp [MongoDB] info: Successfully connected to database when logged. Another would be in the index.js when it successfully starts the server, I want it to be timestamp [Server] info: success message. And if I did not indicate a label in the log, it will just default to ‘App’, such that: timestamp [App] info: message. Any ideas on how to achieve this?

Node.js + TypeScript – Files Executing Out of Order [duplicate]

I’m working on a Node.js + Express project using TypeScript with the "module": "nodenext" option in tsconfig.json. The issue is that my files execute out of order
Project Setup

tsconfig.json:

{
  "compilerOptions": {
    "target": "ESNext",
    "module": "nodenext",
    "moduleResolution": "nodenext",
    "outDir": "dist",
    "rootDir": "./",
    "strict": true,
    "esModuleInterop": true,
    "allowSyntheticDefaultImports": true,
    "skipLibCheck": true,
    "baseUrl": "./",
    "typeRoots": ["./node_modules/@types", "./src/@types"],
    "types": ["node", "express"],
    "paths": {
      "#src/*": ["src/*"]
    }
  },
  "include": ["**/*.ts"],
  "exclude": ["node_modules", "dist"]
}

package.json

{
...
"main": "server.ts",
  "type": "module",
  "scripts": {
    "lint": "eslint src --ext .ts",
    "lint:fix": "eslint src --ext .ts --fix",
    "dev": "nodemon --watch . --ext ts --exec tsx server.ts",
    "build": "tsc",
    "start": "node server.js"
  },
  "license": "ISC",
  "dependencies": {....},
  "devDependencies": {....},
  "imports": {
    "#src/*": "./src/*"
  }
}

./server.ts (Entry Point)

console.log('server.ts is executing');

import dotenv from 'dotenv';
dotenv.config({ path: './config.env' });

console.log('ENV:', process.env.NODE_ENV);

import mongoose, { MongooseError } from 'mongoose';
import { server } from '#src/app.js';
......

./src/controllers/socketController.ts

console.log('socketMessageController.ts is executing');

import appConfig from '#src/config/appConfig.js';
import userSockets from '#src/helper/socketMap.js';
.....

Issue
When I run the project using: npm run dev

The output is:

enter image description here

This means socketMessageController.ts is executing before server.ts, causing process.env to be undefined in that file. Right now, I am hardcoding environment variables as a workaround.

Expected Behavior:
server.ts should execute first, loading environment variables before any other files that depend on them.
Other modules should get process.env properly populated.

CORS problem while sending request to netlify dev server

I’m working on a chrome devtools panels extension. In it I have:

const toDbBtn = document.getElementById("toDbBtn");

toDbBtn.addEventListener("click", async () => {
  const dbName = document.getElementById("textBox").value;

  // const result = await chrome.storage.local.get(["yourKey"]);

  const storedJSON = await chrome.storage.local.get(["yourKey"]);
  console.log("Result from storage:", storedJSON);

  if (storedJSON.yourKey) {

    const parsedArray = JSON.parse(storedJSON.yourKey);
    console.log("Parsed Array:", parsedArray);
    const partArray = parsedArray.slice(0, 30);
    console.log("partArray", partArray);
    const data = {
      dbName: dbName,
      savedArray: partArray,
    };

    const postable = JSON.stringify(data);
    console.log("postable", postable);
    // http://localhost:8888/.netlify/functions//updateCollection.js

    const response = await fetch(
      "http://localhost:8888/.netlify/functions/updateCollection",
      {
        method: "POST",
        headers: {
          "Content-Type": "application/json",
          // "Access-Control-Allow-Origin": "*",
          // "Access-Control-Allow-Methods": "POST",
          // "Access-Control-Allow-Headers": "Content-Type",
        },
        body: postable,
      }
    );

    const result = await response.json();
    console.log("Response from server:", result);
  } else {
    console.log("Value not found in storage for key: yourKey");
  }
});

I’m planning to send some data to a netlify function, and so decided to test locally using “NTL DEV” command.

my target ntl function is:

exports.handler = async function (event, context) {
  const obj = JSON.parse(event.body);
  console.log("obj: ", obj);   
  const collectionName = obj.dbName;
  const objArray = obj.savedArray;
  console.log("objArray: ", objArray);
  console.log("collectionName: ", collectionName);

  return {
    statusCode: 200,
    body: JSON.stringify({
      message: data,
    }),
  };
};

When I push the devtools button, I get:

Request from ::ffff:127.0.0.1: OPTIONS /.netlify/functions/updateCollection

based on CORS error while sending request from Browser to play server even after sending CORS header , I assume that the browser starts of by sending a OPTIONS request. But I’m not sure based on https://cli.netlify.com/commands/dev/ how to set a cors header like “Access-Control-Allow-Origin”: “*” . How can I get this working?

Backtracking confusion

Concerning Javascript, I’ve been trying to understand backtracking lately and it’s really confusing. Specifically, I’ve been trying to understand the permutation problem, which when given an array, we want all of the possible permutations of that array:

function permute(nums) {
    let result = [];
    function backtrack(temp = []) {
        if (temp.length === nums.length) {
            result.push([...temp]);  
            return;
    }
        for (let i = 0; i < nums.length; i++) {
            if (temp.includes(nums[i])) continue;  
            temp.push(nums[i]);       
            backtrack(temp);          
            temp.pop();               
    }
  }
  backtrack();
  return result;
}

Let’s consider nums = [1,2] for simplicity.

From what I understand, we start at temp=[], at i=0 temp -> [1], and backtrack is supposed to search for the other possible values (just 2). It ignores the deletion of the supposed value in temp.pop() and goes back to the loop where i=1 now and temp [1] -> [1,2] and now that it satisfies the condition of length, a copy of this temp array is appended to the result array. So my question is, what happens after this appending?

Supposedly, the code provided above does return [[1,2],[2,1]], which is correct but I don’t understand why. After the appending, apparently we pop the final value from temp, now it’s at [1] and we restart the loop in i, since we finished it to obtain [1,2]. We go through i=0 again, but temp already has the value 1 so we continue. Then it gets added 2 again, and the backtrack sends this result to check the initial condition of length, isn’t it? Apparently, it must pop twice and start the loop at i=1 for the backtrack to have backtrack([2]) and then search for the missing 1.

I don’t understand where my flaw is but I know there is some misinterpretation somewhere, I just don’t understand where.

How to activate the middle mouse button on a page with likes in instagram?

The page https://www.instagram.com/your_activity/interactions/likes/ contains my likes. There are no tags or any mention of shortcode in the HTML. The link to the post looks like this: https://www.instagram.com/p/DH61Qm7t-cR , where DH61Qm7t-cR is the shortcode. DH61Qm7t-cR is not mentioned anywhere on the page. Each block is a div, clicking on which will open the post.

However, if you execute this code
JSON.parse = ((parse) => function() {
  const parsed = parse.apply(this, arguments);
  if (arguments[0]?.includes('DH61Qm7t-cR')))
    console.log('JSON.parse', parsed);
  return parsed;
})(JSON.parse);

and left click on the post, then I will get a JSON array with our shortcode at this address: payload.payload.payload.result.route_match_infos[0].instanceParams.shortcode

That is, the shortcode appears after clicking on the post with the left mouse button. Could you please tell me how I can activate the middle key so that when I click on it, the current page is not refreshed and the post I am interested in is opened in a new tab (i.e. I want to get the default action when the middle mouse button is pressed)?

All candidate resources failed to load. Media load paused

I wrote a script to display mp4 clips FTP’d to the web server from a Reolink CCTV recorder. There could be hundreds sometimes over thousand of these clips along with their jpeg pictures displayed by date and time.

By default I use preload="none" not to overwhelm the browser on page load. I click some of those videos to determine if I should keep or delete. However, after about 20-40 video loads I get this error in FireFox console All candidate resources failed to load. Media load paused.

After this error the browser will not play anymore videos until it is refreshed/reloaded. Sometimes ajax delete function will also stop working. When I refresh the page all of the selections to delete will go away rendering my time reviewing the videos useless.

<video width="320" height="240" controls preload="none">
   <source src="/path/to/video.mp4" type="video/mp4" onerror="playerError()">
</video>

After adding onerror="playerError()" extended the number of videos I can play before the browser stops working. This function gets triggered few times before the browser stops working.

function playerError() {
    console.log('playerError function triggered'); 
} 

Is there any jquery/javascript code that can be added to this function to make the browser continue to work? Basically is there a way to reset Media load paused situation?

In my opinion FireFox works best with html5 video tags, better than chrome and safari. I can try other browser if it may work better.

Blazor WebAssembly SyntaxError: Unexpected token ‘{‘

We are using Blazor WebAssembly .NET 9. Our app has stopped working on iOS 15.8 and we found this issue that seems to be the same issue but for Blazor Server. I tried to start editing the javascript as described in that post but got stuck quickly on mismatches server and wasm. Has anyone solved to run a .NET 9 Blazor WebAssembly on iOS 15.8 and could give guidance on this? I am not sure what we can do to get our app running on iOS 15.8 again. The console error is the same as that post

Unexpected token '{'

p5js move in camera direction

Blockquote

I am trying to make a first person player controller. I can make the camera pan/tilt on mouse movement, but I am having problems trying to make the player move in the direction the camera is facing. Right now it just moves in the normal axes and the movement is not associated with the camera movement. I tried using the camPan variable to move it but so far I haven’t had any luck.
Code:

let cam;
let x = 0;
let y = -50;
let z = 0;
let camPan = 0; // Camera rotation around Y axis
let camTilt = 0; // Camera rotation around X axis
let speed = 1;
let sensitivity = 4;
let moveDir = 0; // Direction of movement


function setup() {
    createCanvas(windowWidth, windowHeight, WEBGL);
    background(100);
    cam = createCamera();
    debugMode();
}

function draw() {
    background(100);
    controller();
    cam.setPosition(x, y, z);
    cam.pan(camPan);
    cam.tilt(camTilt);
}

function mousePressed() {
    requestPointerLock(); // Lock cursor on click
}

function controller() {
    if (keyIsDown(87)) { // Forward
        z -= speed;
    }
    if (keyIsDown(83)) { // Backward
        z += speed;
    } 
    if (keyIsDown(65)) { // Left
        x -= speed;
    }
    if (keyIsDown(68)) { // Right
        x += speed;
    }
}

function mouseMoved() {
    camPan = -movedX / width / 2 * sensitivity;
    camTilt = movedY / height / 2 * sensitivity;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/p5.js/1.9.0/p5.js"></script>

I also noticed that the camera would drift occasionally. I don’t know if that was a problem with the trackpad that I was using or something, but if you know why, it would be useful.

Buttons On Click Functioning with same ID different and different attributes

I have an HTML webpage with a sample of buttons as shown part of a Django Application that fills in the name and town after inserting the values:

{% for person in page_obj %}
       <button id="NotifyBtn" name="person.FName" town="person.LName">Press Me</button>
{% endfor %}
<button id="NotifyBtn" name="Billy" town="Bob">Press Me</button>
<button id="NotifyBtn" name="Timmy" town="Tawin">Press Me</button>
<button id="NotifyBtn" name="Milly" town="House">Press Me</button>

Then I have a JS that does the following:

document.getElementById("NotifyBtn").addEventListener("click", function(){
            var name = this.getAttribute("name");
            var town = this.getAttribute("town");
            fetch("{% url 'alert_via_JSON_Response' %}", {
                method: "POST",
                headers: {
                    "X-CSRFToken": "{{ csrf_token }}",
                    "Content-Type": "application/json"
                },
                body: JSON.stringify({ message: "Hi there: " + `${name} born in ${town}`
                 })
                }).then(response => response.json())
                    .then(data => alert(data.status));
        });

In my Django application I have the following:

def alert_via_JSON_Response(request):
    if request.method == 'POST':
        data = json.loads(request.body)
        message = data.get('message', "Error in sending email")
        return JsonResponse({"status": f"{message}"})
    return JsonResponse({"status": f"No Message"})

Right now, when I click on the webpage, only one button works and sends a JSON response to the webpage, it doesn’t work if I press another button after pressing the first button. Is there a way to press each button when needed and display the JSON response for each button?

Download Link Needs to Show Timer Before Redirecting Not Working

I’ve got a slight issue with my download link, it displays the link out but the timer is not showing the link just disappears instead of showing the timer after the link has been clicked example “start download” then a time will appear from 10 seconds then they will get redirected to the download page.

var i = 0;

function myFunction(url) {
  var tt = setInterval(function() {
    i = i + 1;
    var counter = 6 - i;
    button.innerHTML = 'Download will start in:' + counter;
    if (counter === 0) {
      clearInterval(tt);
      window.location = url //redirect here
    }
  }, 1000);
};
<button id="button">
  <a href="#" class="card-price" id="button1"       onclick="myFunction('download1.zip')">Click To Download</a>
 </button>

How to mock History API using Sinon, Mocha and JSDOM?

I’ve writing a simple single-page application from scratch, and it has a simple router class. It works fine, and now is time to create unit tests for router. For testing, I use Mocha + Chai + JSDOM.

Router have back() and forward() functions, which are just calling window.history.back() and window.history.forward(). Unit test for that functions looks pretty simple:

import { expect } from "chai";
import { Router } from "./router.ts";

describe('Router test', () => {
    let router;
    let elementConstructor;
    let window = globalThis.window;

   function createRouter() {
       return new Router();
   }

   beforeEach(()=>{
       router = createRouter();
   })

   it('Router can go forward', () => {
       window.history.pushState({page: 'messages'}, '', 'messages.html');
       window.history.pushState({page: 'index'}, '', 'index.html');
       window.history.pushState({page: 'login'}, '', 'login.html');
       router.back();
       router.back();
       router.forward();
       expect(window.history.state['page']).to.eq('index');
   });
})

But… JSDOM doesn’t support history API, so this calls just doing nothiing and test always falling. It seems that Sinon library can mock History API, but I failed to find some useful documentation for this case. Does anybody know, where I can to read about mocking history API via Sinon?

Web technology information technology [closed]

Using your HTML, CSS, and JavaScript skills, create a web application to display the 2025 election results for the specified political parties. The application should feature a pie chart with clearly labeled, color-coded sections representing DAD (45%), PPP (5%), CCCC (27%), and MCD (23%). Ensure each segment is distinguishable with unique colors.

The series points show below the x axis when multiple y axis are added

I have requirement to have multiple y axis and series but only one y axis is visible at the time. But when i change the visibility of other y axis to false, then the series data shows below the x axis. If I set setClipping(false), data gets cut off but i do need to display that above x axis.

I could create the issue in the example – https://lightningchart.com/js-charts/interactive-examples/edit/lcjs-example-0007-sharedAxis.html?isList=false

Just add axisY2.setVisible(false); below line 85.
Can you please help me find the right solution to the problem ?