Why my redirect function works good on my local server in next.js 12 but not working after deploy my code to the live server?

  • Why does my redirect function work well on my local server in Next.js 12, but not after deploying my code to the live server? I want to prepend ‘www’ to my site URL when a user clicks on the site URL in the search bar. I have also tried all possible ways to add a .htaccess file with all functionalities, but it didn’t work.
  • Here is my redirection function code:

module.exports = {
trailingSlash: true,
webpack: (config, options) => {
config.module.rules.push({
test: /.(html)$/,
use: {
loader: ‘html-loader’,
},
});
return config;
},

redirects: async () => {
    return [
        {
            source: "/(.*)",
            destination: "https://www.googgle.com",
            permanent: false,
        },
    ];
},

};

This redirects function works fine on my localhost, but why doesn’t it work after deploying it on the server?

I want to prepend ‘www’ to my site URL when a user clicks on the site URL in the search bar.

is there a way to automate the setup of a server made by a bot?

I have been trying to create a bot that can clone a discord server.
the clone would include the server’s name, server image/banner, categories, channels (including settings), roles, up to 10 past messages per channel with timestamp and user credit, and re-invite bots.

I can already have the bot create a discord server and do various things with it such as adding channels, roles, etc. even as much as inviting users and transferring ownership but even with the level of server owner, I still can’t figure out how or if I can have it invite other bots.

what I am asking here is if it’s possible to re-add the bots automatically or if the most I can do is sent the appropriate link for each bot like I’ve done already.

Calculate Tiered Pecentage of Completion Based on Quantity in JavaScript

I’m currently working on a JavaScript task where I have an array discounts containing objects representing discount tiers, each with properties like quantity and discount. My goal is to generate an array of discount objects with percentage of completion based on totalCartItems.

Original Array:

const discounts = [
  { "discountBasedOn": "QUANTITY", "quantity": 5, "discount": 20 },
  { "discountBasedOn": "QUANTITY", "quantity": 8, "discount": 30 },
  { "discountBasedOn": "QUANTITY", "quantity": 10, "discount": 40 },
  { "discountBasedOn": "QUANTITY", "quantity": 12, "discount": 50 },
  { "discountBasedOn": "QUANTITY", "quantity": 15, "discount": 60 }
]

Transform Array Based on Total Cart Items

If totalCartItems = 4:
[
  { "discountBasedOn": "QUANTITY", "quantity": 5, "discount": 20, "percentageCompleted": 80 },
  { "discountBasedOn": "QUANTITY", "quantity": 8, "discount": 30, "percentageCompleted": 0 },
  { "discountBasedOn": "QUANTITY", "quantity": 10, "discount": 40, "percentageCompleted": 0 },
  { "discountBasedOn": "QUANTITY", "quantity": 12, "discount": 50, "percentageCompleted": 0 },
  { "discountBasedOn": "QUANTITY", "quantity": 15, "discount": 60, "percentageCompleted": 0 }
]

If totalCartItems = 5:

[
  { "discountBasedOn": "QUANTITY", "quantity": 5, "discount": 20, "percentageCompleted": 100 },
  { "discountBasedOn": "QUANTITY", "quantity": 8, "discount": 30, "percentageCompleted": 62.5 },
  { "discountBasedOn": "QUANTITY", "quantity": 10, "discount": 40, "percentageCompleted": 0 },
  { "discountBasedOn": "QUANTITY", "quantity": 12, "discount": 50, "percentageCompleted": 0 },
  { "discountBasedOn": "QUANTITY", "quantity": 15, "discount": 60, "percentageCompleted": 0 }
]
If totalCartItems = 6:

[
  { "discountBasedOn": "QUANTITY", "quantity": 5, "discount": 20, "percentageCompleted": 100 },
  { "discountBasedOn": "QUANTITY", "quantity": 8, "discount": 30, "percentageCompleted": 75 },
  { "discountBasedOn": "QUANTITY", "quantity": 10, "discount": 40, "percentageCompleted": 0 },
  { "discountBasedOn": "QUANTITY", "quantity": 12, "discount": 50, "percentageCompleted": 0 },
  { "discountBasedOn": "QUANTITY", "quantity": 15, "discount": 60, "percentageCompleted": 0 }
]

If totalCartItems = 8:
[
  { "discountBasedOn": "QUANTITY", "quantity": 5, "discount": 20, "percentageCompleted": 100 },
  { "discountBasedOn": "QUANTITY", "quantity": 8, "discount": 30, "percentageCompleted": 100 },
  { "discountBasedOn": "QUANTITY", "quantity": 10, "discount": 40, "percentageCompleted": 80 },
  { "discountBasedOn": "QUANTITY", "quantity": 12, "discount": 50, "percentageCompleted": 0 },
  { "discountBasedOn": "QUANTITY", "quantity": 15, "discount": 60, "percentageCompleted": 0 }
]

If totalCartItems = 9:
[
  { "discountBasedOn": "QUANTITY", "quantity": 5, "discount": 20, "percentageCompleted": 100 },
  { "discountBasedOn": "QUANTITY", "quantity": 8, "discount": 30, "percentageCompleted": 100 },
  { "discountBasedOn": "QUANTITY", "quantity": 10, "discount": 40, "percentageCompleted": 100 },
  { "discountBasedOn": "QUANTITY", "quantity": 12, "discount": 50, "percentageCompleted": 25 },
  { "discountBasedOn": "QUANTITY", "quantity": 15, "discount": 60, "percentageCompleted": 0 }
]

Until Complete Current Tier (100%) Next Tier will be show as 0

i have tried this problem is here each milestone is dependent on previous one. i want to something like independent. no one will rely on others is it possible? because in future i can add feature based on Amount alongside with quantity.

disocunts && disocunts.map((item, index, items) => {
const isLastMilestoneReached = index === 0 ? true : items[index - 1].quantity <= totalBundleItems;
  const calculateProgress = (totalBundleItems, quantity) => {
    const progress = (totalBundleItems / quantity) * 100;
    return Math.min(progress, 100);
  };

  const currentTierProgress = calculateProgress(totalBundleItems, item.quantity) || 0;
})```


How create HyperLink to local bookmark with JS in OnlyOffice pugin? (href=#bookmarkname)

friends. I am unable to create a valid bookmark link in the document.

ApiRange.AddHyperlink(sLink, sScreenTipText) → { ApiHyperlink | null }

with sLink = ‘#bookmarkname’ not create correct link.

I tried to make a hyperlink out of the highlighted text

const makeBookmark = (bookmarkName, text, document) => {
    const range = document.Search(text, false)[0];
    range.AddBookmark(bookmarkName);
    const currentSelect = oDocument.GetRangeBySelect();
    currentSelect.AddHyperlink(`#${bookmarkName}`, `#${bookmarkName}`);
                        
}

When clicking on this link, the cursor does not move to the bookmark.

using react query to send value to server and cant get new values in my component

import { apiRequest } from './apiRequest';

export async function createEditItem(data, id) {
    const apiUrl = 'http://localhost:8080/pos';
    const requestHeaders = {
        'Content-Type': 'application/json',
    };

    if (!id) {
        try {
            const res = await apiRequest(
                `${apiUrl}/item`,
                'POST',
                requestHeaders,
                data
            );
            return res;
        } catch (err) {
            console.error(err);
        }
    }
}

import { useMutation, useQueryClient } from '@tanstack/react-query';
import { createEditItem } from '../../api/item';
import { apiRequest } from '../../api/apiRequest';
import { useState } from 'react';

export function useCreateItem () {
    const queryClient = useQueryClient();

    const {
        isLoading,
        mutate: createItem,
        error,
        data,
    } = useMutation({
        mutationFn: createEditItem,
        onSuccess: (data) => {
            queryClient.invalidateQueries(['Item']);
            console.log(data);
        },
        onError: (err) => {
            console.error(err);
        },
    });

    return { data, isLoading, error, createItem};
}

import { useCreateItem } from './useCreateItem';

export default function FormComponent() {
    const { createItem, data: dataItem} = useCreateItem();

    useEffect(() => {
        if (dataItem) {
            console.log(JSON.stringify(dataItem, null, 2));
        }
    }, [dataItem]);

    async function onSubmit (data){

        dataNewItem = 'value2';
        await createItem(dataNewItem);

        if(!dataItem) return;
        
        console.log(JSON.stringify(dataItem, null, 2));
        data.newItem = dataItem;
    }

    return (
        <Form
            onSubmit={handleSubmit(onSubmit, onError)}
        >
            ...form element
            <button type='submit'>Send Item to server !</button>
            .....
        </Form>
    );
}

when i onSubmit my form i call createItem. this createItem will send ‘value2’ to server to insert into DB and then if success give it back the ‘value2’ and with new id to the client.
i can see the success of this process when i see this line of code in my hook and in my useEffect. i can see the ‘value2’ with new id.

   onSuccess: (data) => {
      queryClient.invalidateQueries(['Item']);
      console.log(data);
    },

and this too

 useEffect(() => {
     if (dataItem) {
     console.log(JSON.stringify(dataItem, null, 2));
   }
 }, [dataItem]);

the problem is why i cant get the new value (‘value2’). i cant get directly the new value and this code below will return old value the ‘value1’

   console.log(JSON.stringify(dataItem, null, 2));
   data.newItem = dataItem;

Jquery multiselect not working when very large number of options

I have to load total 50000 record into select2 but its take too much time to load and also browser hangup. So can you please give me a solution for how to solve this issue or any alternate solution regarding this.

<link rel="stylesheet" type="text/css" href="https://homesweb.staah.net/common/groups/css/jquery.multiselect.css"/>
<link href="https://homesweb.staah.net/common/css/bootstrap-multiselect.css" rel="stylesheet">
<script src="https://homesweb.staah.net/common/js/jquery-1.9.1.min.js"></script>
<script type="text/javascript" src="https://homesweb.staah.net/common/js/jquery.multiselect.js"></script>

<select name="rateplan[]" id="rateplan" multiple="multiple" class="form-control">
</select>
<script>
    
    jQuery(document).ready(function(){    
        var data = '{"ChannelRate":{"1846525":{"id":"1846525","channelId":"131","ratePlanName":"1 Bedroom","channelsName":"tbo"},"1645656":{"id":"1645656","channelId":"53","ratePlanName":"2 Bedroom","channelsName":"Agodaycs"},"1646346":{"id":"1646346","channelId":"53","ratePlanName":"3 Bedroom","channelsName":"Agodaycs"},"1423011":{"id":"1423011","channelId":"248","ratePlanName":"4 Bedroom","channelsName":"airasia"},"1423305":{"id":"1423305","channelId":"248","ratePlanName":"5 Bedroom","channelsName":"airasia"},"1778094":{"id":"1778094","channelId":"108","ratePlanName":"6 Bedroom","channelsName":"DOTW"}}}';
        inputdata = JSON.parse(data);

        var rateplanhtml = '';
            if(typeof inputdata.ChannelRate != 'undefined' && inputdata.ChannelRate != 'null' && inputdata.ChannelRate != null) {                
            $.each(inputdata.ChannelRate, function (package, pdata) {
                rateplanhtml += '<option value="'+ pdata.id +'" class="'+ pdata.channelId +'">'+ pdata.ratePlanName + '-' + pdata.channelsName+ '</option>';
            });
            }            
        $('#rateplan').html(rateplanhtml);
        $('#rateplan').multiselect({
            includeSelectAllOption: true,
            enableFiltering: true,
            enableCaseInsensitiveFiltering: true,
            selectAll: true,
            search: true,
        });
    });
</script>

Can you please anyone suggest me to fill large number of options in multi select?

How to Implement Auto-Printing Without Print Dialog for a Web Application?

I am developing a web application where I need to automatically print a specific part of the page (div with id=”printableArea”) when a user submits a form. Here’s the relevant HTML and JavaScript.

Currently, this code triggers the browser’s print dialog. However, for this specific feature, I need to bypass the print dialog and print directly to the default printer without any user interaction.

I understand that browsers generally restrict silent printing for security reasons, but this feature is intended for a controlled environment (e.g., a point-of-sale system in a restaurant) where such functionality is crucial.

**html form
**

  <form action="{{ route('vendor.pos.order') }}?restaurant_id={{ isset($restaurant_data) ? $restaurant_data-       >id : '' }}"
    id='order_place' method="post">
    @csrf
    <input type="hidden" name="user_id" id="customer_id">
    <div class="box p-3">
       
        <div class="row button--bottom-fixed g-1 bg-white">
            <div class="col-sm-6">
                <button type="submit" onclick="printDiv('printableArea')" class="btn  btn--primary btn-sm btn-block">{{ translate('place_order') }}
                </button>
            </div>
         
        </div>
    </div>
</form>`
<div id="printableArea">Hello world</div>

**javascipt **

 function printDiv(divName) {
            var printContents = document.getElementById(divName).innerHTML;
            var originalContents = document.body.innerHTML;
            document.body.innerHTML = printContents;
            window.print();
            document.body.innerHTML = originalContents;
        }

error while export data to csv from mysql in nodejs

i want to export data to excel from mysql using nodejs currently i have 5M+ records in database and throw error kill but when i have around 1.7M records at that time this is working so i think i need to handle using stream so i have try using stream also but it is not working.

exports.exportdatatocsv = async (req, res) => {
  con.query(
    "SELECT sender_name, table_name FROM sender_tbl",
    function (error, data) {
      if (error) {
        console.error(error);
        res.status(500).send("Internal Server Error");
        return;
      }

      var mysqlData = JSON.parse(JSON.stringify(data));
      var workbook = new ExcelJS.stream.xlsx.WorkbookWriter({ stream: res });

      mysqlData.forEach((sender, index) => {
        var worksheet = workbook.addWorksheet(
          sender.sender_name.substring(0, 31)
        );

        con.query(
          `SELECT * FROM ${sender.table_name} ORDER BY id DESC`,
          function (error, tableData) {
            if (error) {
              console.error(error);
              res.status(500).send("Internal Server Error");
              return;
            }

            var fileHeader = [
              "message",
              "info",
              "credit/debit",
              "amount",
              "netbal",
            ];
            worksheet.addRow(fileHeader);

            tableData.forEach((row) => {
              worksheet.addRow([
                row.message,
                row.info,
                row.isdebit ? "debit" : "credit",
                row.amount,
                row.netbal,
              ]);
            });

            if (index === mysqlData.length - 1) {
              workbook
                .commit()
                .then(function () {
                  res.status(200).end();
                })
                .catch(function (err) {
                  console.error(err);
                  res
                    .status(500)
                    .send("Error occurred while generating Excel file");
                });
            }
          }
        );
      });
    }
  );
};

How can I display unique data associated with param on individual pages in SvelteKit using slug/parameter routing

I’m currently working on a SvelteKit project where I have a list of cards representing different law firms. Each card is linked to a unique page using slug/parameter routing. I’ve managed to fetch the titles of the law firms dynamically, ensuring they are unique. However, I’m struggling with displaying specific data associated with each law firm on its respective page, particularly a table allocated to that law firm.

Here’s what I’ve tried so far:

Successfully implemented slug/parameter routing to dynamically generate unique pages for each law firm.

Fetched and displayed the titles of the law firms on their respective pages.

However, I’m unsure about how to proceed with displaying specific data, like a table, allocated to each law firm based on the slug/parameter.

I’m using Supabase as the backend.

Any help would be appreciated, thanks!

This is the card page

<script>
    import { onMount } from 'svelte';
    import { paginate, LightPaginationNav } from 'svelte-paginate';
    export let data;

    let search = '';
    let visibleLawFirms = [];
    let currentPage = 1;
    let pageSize = 12;

    // Recalculate paginatedItems whenever visibleLawFirms changes
    $: paginatedItems = paginate({ items: visibleLawFirms, pageSize, currentPage });

    // component mounts to dom before search is performed
    onMount(() => {
        updateVisibleLawFirms();
    });

    function updateVisibleLawFirms() {
        if (search) {
            visibleLawFirms = data.lawfirm.filter((lawF) => {
                return lawF.lawfirmname.toLowerCase().includes(search);
            });
        } else {
            visibleLawFirms = data.lawfirm;
        }
    }

    function updateSearch(e) {
        search = e.target.value.toLowerCase();
        updateVisibleLawFirms();
    }

    function handlePageChange(e) {
        currentPage = e.detail.page;
    }
</script>

<div class="flexLawSearch">
    <h1 class="leftAlign">Law Firms</h1>
    <div class="searchAndAdd">
        <input
            class="searchBox"
            type="text"
            placeholder="Search Law Firms..."
            bind:value={search}
            on:input={updateSearch}
        />
        <a href="addfirm"><button class="defaultBlue">+ New Firm</button></a>
    </div>
</div>

<ul class="flexCards">
    {#each paginatedItems as LawF}
        <a href="/lawfirms/{encodeURIComponent(LawF.lawfirmname)}">
            <li class="cardShape">
                <h3>{LawF.lawfirmname}</h3>
            </li>
        </a>
    {/each}
</ul>

This is the page where I’m struggling with fetching the unique data

<script>
    import { page } from '$app/stores';
    export let data;
    console.log(data);

    const lawfirmId = $page.params.lawfirmId;
</script>

<div class="lawFirmBanner">
    <h1>{decodeURIComponent(lawfirmId)}</h1>
</div>

{#if data.lawfirm}
    <div class="lawFirmInfo">
        <p>{data.lawfirm[3].lawfirmname}</p>  <!-- Figure out how to match the param for unique data for each firm-->
    
    </div>
{/if}

number found in the range , create Pass result

I am facing Issue how to create Pass and fail result

<input type="number" id="numInput">

if I type any number in the id=”numInput” and this number in the range <td id="range"></td>

create Pass Result in the id=”result”
<p id="result"></p>

 <table width="100%;">
      <td class="myTable" id="toggleindexdata" contenteditable="true">22,014</td>
      <td id="range"></td>
</table>

      <td id="range"></td>
<input type="range" id="interestRate" name="interestRate" min="09" max="500" step="10" value="5" oninput="updateInterestRate(this.value)">
 <span id="interestRateValue">4.5%</span>
</div>
<input type="number" id="numInput">
<p id="result"></p>
<script>
  var myTables = document.getElementsByClassName("myTable");

  for (var i = 0; i < myTables.length; i++) {
    myTables[i].addEventListener("input", updateRange);
  }

  function calculateRange(baseline, interestRate) {
    var min = (baseline - (baseline * (interestRate / 100))).toFixed(2);
    var max = (baseline + (baseline * (interestRate / 100))).toFixed(2);
    return [parseFloat(max), parseFloat(min)];
  }

  function updateRange() {
    var baseline = this.textContent.replace(/,/g, '');
    baseline = parseFloat(baseline);

    if (isNaN(baseline)) {
      return;
    }

    var interestRate = document.getElementById("interestRate").value / 100;
    var range = calculateRange(baseline, interestRate);
    var options = { minimumFractionDigits: 0, maximumFractionDigits: 0 };
    var formattedRange = range.map(function(value) {
      return value.toLocaleString('en-US', options);
    });
    document.getElementById("range").textContent = formattedRange[0] + " to " + formattedRange[1];

    // Calculate and display the difference in percentage
    var exact = parseFloat(document.getElementById("toggleindexdata").textContent.replace(/,/g, ''));
    var closingRange = parseFloat(formattedRange[0].replace(/,/g, ''));
    var difference = closingRange - exact;
    var percentDifference = (difference / exact) * 100;
    document.getElementById("differencePercentage").textContent = percentDifference.toFixed(2);
  }

  function updateInterestRate(value) {
    document.getElementById("interestRateValue").textContent = value + "%";
    updateRange.call(myTables[0]);
  }
  
  function updateInterestRate(value) {
  const halfValue = value / 2;
  document.getElementById("interestRateValue").textContent = halfValue + "%";
  updateRange.call(myTables[0]);
}

  for (var i = 0; i < myTables.length; i++) {
    updateRange.call(myTables[i]);
  }
</script>

Example 1 : 22,034 to 21,994 and I type 22,014 in the <input type="number" id="numInput"> Create Pass Result because 22,014 in the range

Example 2 : 22,034 to 21,994 and I type 22,014 in the <input type="number" id="numInput"> Create Pass Result because 22,034 in the range

If I Increases slider bar : range number also update I want Auto update

Thank You for Your Time

the browser blocks pop-ups when the page is closed (onbeforeunload event) I want to display a confirm window

the browser displays an error in the console: Blocked confirm(“Close?”) during beforeunload

my code:

JavaScript

    window.onbeforeunload = function () {
        if (confirm('Вы действительно хотите закрыть эту вкладку?')) {
            window.location.href = 'https://www.example.com/';
        }
        return "Вы точно хотите уйти без сохранение?";

    }

What should I do to prevent the browser from blocking my code?

How to group only only the columns having some condition

Here is my data grid code for preimium. I have a field boolean on the basis of that boolean field I want to show the expand group otherwise want to show it inline without grouping.

const apiRef = useGridApiRef();

const initialState = useKeepGroupedColumnsHidden({
  apiRef,
  initialState: {
    sorting: {
      sortModel: [{ field: "__row_group_by_columns_group__", sort: "asc" }],
    },
    rowGrouping: {
      model: ["myGroupingField"],
    },
  },
});
<DataGridPremium
    rows={data}
    columns={[
        { field: 'myGroupingField', align: 'left', headerName: 'Group Id', width: 180, headerAlign: 'left' }
    ]}
    apiRef={apiRef}
    loading={loading}
    disableRowSelectionOnClick
    initialState={initialState}
    slots={{ toolbar: CustomToolbarWithButton }}
/>

Please help me here