No tax for companies from foreign Countries in WooCommerce

I need to set a different tax class for company whose field nip is different than polish in WooCommerce

I have in my checkout field nip, and I want the tax to change to 0% after entering the tax number, e.g. RO123456789. I have 2 class tax Standard and zero rate if I have nip PL123456789 I want the rate to be standard.

i have this code and this didn’t work and I don’t know why.Any guidance on resolving this issue would be highly appreciated.

// Add the Tax Identification Number field at checkout
add_action( 'woocommerce_after_order_notes', 'custom_add_nip_field' );

function custom_add_nip_field( $checkout ) {
    echo '<div id="custom_nip_field"><h2>' . __('Dane firmy') . '</h2>';

    woocommerce_form_field( 'vat_nip', array(
        'type'          => 'text',
        'class'         => array('vat-nip-field form-row-wide'),
        'label'         => __('Numer NIP (dla firm z UE)'),
        'placeholder'   => __('Wpisz numer VAT UE'),
    ), $checkout->get_value( 'vat_nip' ));

    echo '</div>';
}

// NIP from field to checkout
add_action( 'woocommerce_checkout_update_order_meta', 'custom_save_nip_field' );

function custom_save_nip_field( $order_id ) {
    if ( ! empty( $_POST['vat_nip'] ) ) {
        update_post_meta( $order_id, '_vat_nip', sanitize_text_field( $_POST['vat_nip'] ) );
    }
}
// Apply 0% VAT for companies from outside Poland based on the NIP number
add_action( 'woocommerce_cart_calculate_fees', 'custom_apply_vat_exemption_based_on_nip' );

function custom_apply_vat_exemption_based_on_nip() {
    if ( is_admin() && ! defined( 'DOING_AJAX' ) ) {
        return;
    }

    // Download the Tax Identification Number from the field at the checkout
    $vat_nip = isset( $_POST['vat_nip'] ) ? sanitize_text_field( $_POST['vat_nip'] ) : '';

    // Check if the NIP does not start with "PL"
    if ( ! empty( $vat_nip ) && substr( $vat_nip, 0, 2 ) !== 'PL' ) {
        // Assign a 'zero rate' tax class to the products in your cart
        foreach ( WC()->cart->get_cart() as $cart_item_key => $cart_item ) {
            $cart_item['data']->set_tax_class( 'zero rate' ); // set tax zero rate (0% VAT)
        }
    }
}

I try some plugins but didn’t work as I expect.

Invoke logout function when device’s network changes (i.e. connect to other wifi network or so)

I’m trying to call a logout function when the network changes in my React application. However, as soon as I log in, my useEffect hook automatically triggers, causing an unintended logout, even though the network hasn’t actually changed. I’d like the logout function to be called only when there’s a genuine network change (such as a disconnect or reconnect event), not on minor variations or when the app initially loads.

I am testing this on chrome browser. I am using navigator api in my useEffect with event listener in my App.jsx file but its not working out. It randomly logs out the user.

const { handleLogout } = useLogout()

  const whenUserIsIdle = () => {
    if (isUserAuthenticated)
      handleLogout()
  }

  useIdleTimer({
    onIdle: whenUserIsIdle,
    timeout: 300000, //5 minutes
    throttle: 500, // checks after 500ms
  });
 useEffect(() => {
    const handleNetworkChange = () => {
      console.log('connection network change effect',connection);
      if (localStorage.getItem('authToken')) {
        const connection = navigator.connection || navigator.mozConnection || navigator.webkitConnection;

        // Perform a condition check to prevent unnecessary logouts
        if (connection && connection.downlink > 0) { // for example, checking if downlink speed is above 0
          handleLogout();
        }
      }
    };

    const connection = navigator.connection || navigator.mozConnection || navigator.webkitConnection;
    if (connection) {
      connection.addEventListener('change', handleNetworkChange);
    }

    return () => {
      if (connection) {
        connection.removeEventListener('change', handleNetworkChange);
      }
    };
  }, [handleLogout]);

my custom logout hook:

const useLogout = () => {
    const dispatch = useDispatch();
    const handleNavigateToRoot = useNavigatetoRoot();


    // Define the function to handle successful logout
    const onSuccessfullLogout = (response) => {
        handleNavigateToRoot()
    };

    // Get mutate function from the usePostDataToServer hook
    const { mutate } = usePostDataToServer({
        onPostReqSuccess: onSuccessfullLogout,
        dispatch,
    });

    // Define a function to handle logout
    const handleLogout = () => {
        const API_URL = `${BASE_URL}${ENDPOINTS.LOGOUT}`;
        mutate({ API_URL, dispatch });
    };

    return { handleLogout };
};

export default useLogout;

Opengraph works on page but doesnt show on share, @vercel/og

Summary

So i am using Next.js 13 pages router, i want to implement a dynamic og:image on my meta tags. I created an API handler that generates the image from id that i get from searchParams.

It all worked flawlessly on my browser (see image-1), but when i deployed it to vercel, and tried to share the link or use Facebook’s Meta Debugger, it doesn’t show the values.

image-1

Code

This is my simplified implementation for both of the [id]/page.tsx:

// client

export default function Product() {
  const router = useRouter();
  const { id } = router.query;
  const { property, isLoading } = useProperty(Number(id));

  const title = property ? `${NAME} | ${property.name_formatted}` : `${NAME}`;
  const description = property ? property.description : "Empty property description";
  const currentUrl = `${BASE_URL}/api/og?id=${id}`;

  return (
    <>
      <NextSeo
        title={title}
        description={description}
        openGraph={{
          title,
          description,
          images: [
            {
              url: currentUrl,
              width: 1200,
              height: 630,
              alt: title,
            },
          ],
          siteName: NAME,
        }}
      />
      {/* Additional Codes */}
    </>
  );
}

And for /api/og.tsx:

// api handler

import { ImageResponse } from "@vercel/og";
import { NextRequest } from "next/server";

export const config = { runtime: "edge" };

async function fetchProperty(id) {
  const response = await fetch(`${BASE_API_URL}/properties/${id}`);
  return response.json();
}

export default async function handler(req: NextRequest) {
  const id = req.nextUrl.searchParams.get("id");
  if (!id) return new Response("Missing ID", { status: 400 });

  const property = await fetchProperty(id);
  if (!property) return new Response("Property not found", { status: 404 });

  return new ImageResponse(
    <div style={{ display: "flex", flexDirection: "column", padding: "24px" }}>
      <h1>{property.name}</h1>
      <img src={property.imageUrl} alt={property.name} />
    </div>,
    { width: 1200, height: 630 }
  );
}

What I’ve Tried

I implemented next-seo but it didn’t work, I think it’s because of the [id]/page.tsx being a client-side file, the og:image is only loaded on the browser instead of the server

can’t insert block in editorjs

I am using Editor.js. I’ve tried adding a new block to the editor but it doesn’t work

<html>
    <script src="https://cdn.jsdelivr.net/npm/@editorjs/[email protected]/dist/editorjs.umd.js" type="text/javascript"></script>
</head>
<body>
    <div id="editorjs" class="editor-holder"></div>

    <script>
        var editor = new EditorJS({
      holder: 'editorjs',
      autofocus: true,
      data: {
        "time": 1550476186479,
        "blocks": [{
            type: 'paragraph',
            data: {
             text: 'Hello world'
            }}
        ]}
    })

    const newBlock = {
      type: 'paragraph',
      data: {
          text: 'Hello world'
      }
    };

    editor.blocks.insert(newBlock.type, newBlock.data);

    </script>

</body>

I’m facing the following error:

Uncaught TypeError: Cannot read properties of undefined (reading 'insert')

I’ve also tried following:

editor.blocks.insert(newBlock);
editor.configuration.data.blocks.push(newBlock); 
editor.api.blocks.insert(newBlock);

but I get errors

Upgraded crypto-js from 3.1.9-1 to 4.2.0 in my react frontend project, my old code is throwing malformed UTF-8 error and not working as expected

This is my code and it was working fine with old version of crypto-js. With the upgrade the encrypted string from frontend is not getting decrypted in my java springboot backend. The encrypted string from backend is not getting decrypted in frontend and giving malformed UTF-8 error.

const iterationCount=1000;
const keySize= 128/32;

function generateKey(salt, passPhrase) {
  const key = CryptoJS.PBKDF2(
    passPhrase,
    CryptoJS.enc.Hex.parse(salt),
    { keySize, iterations: iterationCount });
  return key;
}

function encrypt(salt, iv, plainText) {
  const passPhrase = process.env.ENCRYPT_SECRET;
  const key = this.generateKey(salt, passPhrase);
  const encrypted = CryptoJS.AES.encrypt(
    plainText,
    key,
    {
      iv: CryptoJS.enc.Hex.parse(iv),
      mode: CryptoJS.mode.CTR,
      padding: CryptoJS.pad.NoPadding
    });
  return encrypted.ciphertext.toString(CryptoJS.enc.Base64);
}

function decrypt(salt, iv, cipherText) {
  const passPhrase = process.env.DECRYPT_SECRET;
  const key = this.generateKey(salt, passPhrase);
  const decrypted = CryptoJS.AES.decrypt(
    cipherText,
    key,
    {
      iv: CryptoJS.enc.Hex.parse(iv),
      mode: CryptoJS.mode.CTR,
      padding: CryptoJS.pad.NoPadding
    });
  return decrypted.toString(CryptoJS.enc.Utf8);
}

I tried multiple ways of resolving this but nothing worked so far. Anyone faced a similar issue?

POST requests in Project IDX (Express and Nodejs)

I’m currently building a Gemini web application using the online IDE Google IDX. However, when trying to send POST requests from the frontend(JS) to the backend(ExpressJS server), I keep getting this error:

has been blocked by CORS policy: Response to preflight request doesn't pass access control check: The value of the 'Access-Control-Allow-Credentials' header in the response is '' which must be 'true' when the request's credentials mode is 'include'

I have tried setting permissions within the server file such as:

app.use(cors({
    origin: function (origin, callback) {
        callback(null, true);  
    },
    credentials: true
}));

Because there is no way that I know of to reference Project IDX frontend files like backend files.
The same error still occurs using this method and even when using ‘*’ to accept all origins.
If anybody has any knowledge about how I could bypass this issue it would be greatly appreciated.

Minified js file using BuildBundlerMinifier Package

I am trying to minified highcharts.src.js using bundleconfig.json in asp.net core using BuildBundlerMinifier Package for that I have written the below code in bundleconfig.json

[
    {
        "outputFileName": "wwwroot/js/highchart2.min.js",
        "inputFiles": [
            "wwwroot/lib/highcharts/highcharts.src.js"
        ],
        "minify": {
            "enabled": true,
            "renameLocals": false
        }
    }
]

but when I build the application it will display the error Object reference not set to an instance of an object. Just want to know is it possible to minified highcharts.src.js using BuildBundlerMinifier Package?

Get Absolute Path of files using .NET Core 8 and JS

How can I get absolute path of a file using .NET Core 8 and Vanilla Javascript?

Issue: I need to send absolute path of a to a service for which I need to use only .NET Core 8 Web app and Vanilla JS to allow user to pick a file in file dialogbox and I need to capture it and send the absolute path to that service.

Attempt: I cannot get the absolute path of files using JS as it’s not possible due to security reasons and I also tried to trigger a ajax call to a action method to show OpenDialogBox and compiling the app to windows application, But this scenario won’t work for hosting and deploying scenarios.

Question: How can I get absolute path of files of user choosing? This can be of any possible way within the tech stack I provided.

Streamlit Javascript integration

I can’t get any js function in streamlit to work, the return value is always 0, no matter how I tried to write it. For instance

anonymous = st_javascript("""
    (() => {
        return 2;
    })()
""")

st.write(f"JavaScript returned: {anonymous}")

What am I doing wrong here? Chatgpt and claude couldn’t help, nor did I see any helpfull posts here.

Can someone provide the correct syntax?

How can I create a new random shape for a Tetris-like game?

I want to have new tetris pieces to appear in the game the longer you play and it doesn’t work, it makes new shapes but the shapes aren’t centered, they aren’t continuous (like the shape might look like 2 shapes because they aren’t touching), and it sometimes adds a shape that’s already part of the shapes array. Each shape has a max squares of 12 and must fit in a 4×4 space
Here’s my code so far:

function randomShape(score) {
  const maxSize = 12; // Max number of squares per shape
  const centerOffset = 1; // Offset to center the shape
  const maxComplexity = Math.min(Math.floor(score / 100), 6); // Max complexity based on score

  let shape;

  do {
    shape = Array.from({ length: 4 }, () => Array(4).fill(0)); // Create an empty 4x4 shape
    const size = Math.max(1, Math.floor(Math.random() * (maxComplexity + 1))); // Shape size varies based on complexity

    let squaresToPlace = Math.min(size, maxSize); // Limit the squares placed to maxSize

    // Fill the shape with random positions of 1s based on size
    while (squaresToPlace > 0) {
      const x = Math.floor(Math.random() * 4);
      const y = Math.floor(Math.random() * 4);

      // Only place a 1 if the spot is empty
      if (shape[y][x] === 0) {
        shape[y][x] = 1;
        squaresToPlace--;
      }
    }
  } while (!shape.flat(5).includes(1)); // Retry if the shape is empty

  // Centering logic
  const centeredShape = Array.from({ length: 4 }, () => Array(4).fill(0));

  // Get the positions of all filled cells
  const filledPositions = [];
  for (let r = 0; r < 4; r++) {
    for (let c = 0; c < 4; c++) {
      if (shape[r][c] === 1) {
        filledPositions.push({ r, c });
      }
    }
  }

  let amount = 0;
  shape.flat(5).forEach((s) => {
    if (s === 1) amount++;
  });
  if (amount === 1) {
    return [
      [0, 0, 0, 0],
      [0, 0, 0, 0],
      [0, 0, 1, 0],
      [0, 0, 0, 0],
    ];
  }

  // Determine how to center the shape
  const minRow = Math.min(...filledPositions.map((p) => p.r));
  const maxRow = Math.max(...filledPositions.map((p) => p.r));
  const minCol = Math.min(...filledPositions.map((p) => p.c));
  const maxCol = Math.max(...filledPositions.map((p) => p.c));

  // Calculate the offsets needed to center the shape
  const height = maxRow - minRow + 1;
  const width = maxCol - minCol + 1;

  // Calculate vertical and horizontal offsets
  const rowOffset = Math.floor((4 - height) / 2); // Center vertically
  const colOffset = Math.floor((4 - width) / 2); // Center horizontally

  // Place the shape in the centered position
  filledPositions.forEach(({ r, c }) => {
    // Ensure we're placing the piece within bounds
    const newRow = r + rowOffset;
    const newCol = c + colOffset;
    if (newRow >= 0 && newRow < 4 && newCol >= 0 && newCol < 4) {
      centeredShape[newRow][newCol] = 1;
    }
  });

  return centeredShape;
}

I tried to add new random shapes that were supposed to look normal and be centered, but they were broken and uncentered and sometimes dupes.

How to get min and max vAxis and vAxis ticks using mm:ss in Google Charts API?

As is typical in my experience, times and durations are causing me trouble with graphs and Javascript. I’m graphing duration in mm:ss on the vAxis and date on the hAxis and trying to expand the min and max of the graph, so that it goes beyond the data points, above and below. For example, I’d like to have a min of 11:00 and a max of 14:00. However, I’m unable to do this. I read on one suggestion (cannot recall the URL and if it was stackoverflow and can’t find right now) that I could convert the mm:ss to just seconds as a whole number, and use that for max and min. When I do that, I get this error: ‘a.getTime is not a function’. I’m guessing that my numbers are not being carried over from my google sheet as a time duration…and maybe just a string. Of course when I use a colon in the max/min, I get an error that it’s not expecting a ‘:’. Thanks for any assistance.

Here’s the code, which has already been assisted by this site once. It works fine if the “viewWindow” portion is removed.

var query = new google.visualization.Query(queryUri + queryString);

// run query
query.send(function (response) {
// determine if error occurred
if (response.isError()) {
  alert('Error in query: ' + response.getMessage() + ' ' + response.getDetailedMessage());
  return;
}

// extract data from response
var data = response.getDataTable();


// need to create dataview to use column as annotation
var view = new google.visualization.DataView(data);
view.setColumns([0, 1, {
  calc: 'stringify',
  sourceColumn: 2,
  type: 'string',
  role: 'annotation'
}]);

// create options
var options = {
  title: 'L's 2024 Cross Country Run Times',
  width: 900,
  height: 500,
  trendlines: {
    0: {
      color: 'blue'
    }
  },
  vAxis: {
    format: 'mm:ss',
    viewWindow : {min : 660,max : 840}
  }
};

// draw chart
var chart = new google.visualization.ScatterChart(document.getElementById('chart_div'));
chart.draw(view, options);
});
}
</script>
</head>
<body>
<div id="chart_div" style="width: 100%; height: 500px;"></div>
</body>
</html>

Back Button Appends Source Page to Bottom of Destination Page

I am doing React programming with JavaScript.

I use the history.push function from react-router-dom (v5.2.0) to open a new page. Here is part of the code:

{activeRequests?.map((item, index) => {
  return (
    <tr
      className={styles.tr}
      key={index}
      onClick={() => {
        history.push(`AssetManagement/Default/Edit/${item.assetId}`);
        window.location.reload();
      }}
    >

It opens the new page (which happens to be in Knockout) as expected in the same browser tab.

Something odd happens, however, when I use the Back button to return to the page on which I originally clicked the above link. I see the original page. But then, if I scroll down, I see the page on which I clicked the Back button appended to the bottom.

Call them, let’s say, Page One (where I clicked the link) and Page Two (where I clicked the Back button). Is there anything I can do on Page One to prevent this behavior? (Meaning, of course, I don’t want to see Page Two at the bottom of Page One.) Or do I need to add some sort of unmounting function to Page Two? I would prefer to modify Page One, since I am more familiar with React than Knockout.

Page Loader Stuck When Clicking Browser Back Button in .NET MVC Website

I’m developing a website using .NET MVC, which can be accessed at https://gengecmimarlik.com . The site uses a page loader animation that works as expected during normal navigation through the navbar links. However, I encounter an issue when using the browser’s back button.

Problem:
When I navigate to a different page (e.g., /TumProjeler or /iletisim) and then press the back button on the browser (Chrome or Edge), the loader animation appears but stays stuck, preventing the page from loading properly. The site doesn’t crash or throw any errors, but the loader does not disappear, and the page content doesn’t show up.
If I remove the preloader, the problem disappears, but I need to keep it for design purposes.

Key Details:

  • I’m not using any AJAX calls for page transitions; the navigation is
    straightforward.
  • All routes and navigation links are configured properly.
  • Here is a sample of how the links are set up in the navbar:
<a class="rd-nav-link" asp-controller="Home" asp-action="Index">Ana Sayfa</a>
<a class="rd-nav-link" asp-controller="Home" asp-action="AllProjects">Tüm Projeler</a>
<a class="rd-nav-link" href="@Url.Action("Index", "Home")#ekibimiz">Ekibimiz</a>
<a class="rd-nav-link" asp-controller="Home" asp-action="Contact">İletişim</a>
  • I’m using a preloader that runs when the page loads. However, it
    seems to get stuck when navigating back using the browser’s back
    button.
    What could be causing the page loader to get stuck when the back button is pressed? Are there specific .NET MVC behaviors or browser caching settings that I need to adjust? How can I ensure that the loader doesn’t hang and the content loads properly when users go back to the previous page?

Any advice or suggestions would be greatly appreciated. Thank you!