Switch component is not working after switching from Checkbox

I was using Ant Design Checkbox earlier to check and publish the comments and it was working fine with no errors.

<Checkbox
  key={record.id}
  checked={Publish[record?.id]?.["ispublish"] == 'true' ? true : false}
  onChange={(e) => Update(e.target.checked, record)}
/> 

I want to use Switch instead.

<Switch
  key={record.id}
  checked={Publish[record?.id]?.["ispublish"] == 'true' ? true : false}
  onChange={(e) => Update(e.target.checked, record)}
/> 

I am getting error:

cannot read properties of undefined (reading ‘checked)

I want Switch to work.

why json file value is not displayed (javascript)

  <script>
        // Fetch JSON data
        fetch('dat.json')
               .then(response => response.json())
            .then(data => {
                const tbody = document.querySelector('#dataTable tbody');
                data.forEach(item => {
                    const row = document.createElement('tr');
                    row.innerHTML = `
                        <td>${item.name}</td>
                        <td>${item.age}</td>
                        <td>${item.city}</td>
                    `;
                      tbody.appendChild(row);
                });
            })
                .catch(error =>console.error('Error fetching the data:', error));
    </script>

why json file value is not displayed the code i took from chatgpt i tried vscode and notepad +++ too none of them work.

How can I find the default rules for phone numbers in the google-libphonenumber NPM package?

I’m using the google-libphonenumber NPM package to format and parse phone numbers, specifically for New Zealand. I want to understand which default rules are applied when parsing and formatting phone numbers. Is there a way to access or view the rules used by the library for a specific region, like New Zealand?

Example:

When parsing, what are the default formatting rules applied by google-libphonenumber?
Any help would be appreciated!

How to remove styling if the heght of the screen less than the element height

I have centered the element by the height of the screen using absolute positioning.
However, when the height of the screen is less than the element width, it is cutting the part of the element making its top unreachable. How can I add and remove styling if the height of the screen is less than the height of the element?

https://codepen.io/alena-chuyankova/pen/YzmWYKZ


.wrap {
    position: absolute;
    top: 50%;
    transform: translate(0, -50%);
    background-color: white;
    gap: 1rem;
    width: 45%;
    box-shadow: rgba(50, 50, 93, 0.25) 0px 13px 27px -5px, rgba(0, 0, 0, 0.3) 0px 8px 16px -8px;
    display: flex;
    flex-direction: column;
    padding: 4rem;
    
}

“Issue with Swiper.js: Cards Disappearing When Swiping Right

I am experiencing an issue while implementing Swiper.js in my project. When I swipe to the right, the cards disappear, and they only reappear when I swipe to the left. I can’t understand what might be causing this problem.

Here is the html, css and JS:

html:

<!-- Slider main container -->
<div class="swiper flex flex-wrap justify-center gap-6 mt-8 mb-64 px-4 md:mt-0">
    <!-- Additional required wrapper -->
    <div class="swiper-wrapper">
        <div class="swiper-slide">
            <a href="./políticas.html">
                <h3 class="text-2xl text-white mb-4">Public Policies</h3>
                <p class="text-base text-green-200">Understand the public policies that directly impact the Atlantic Forest and conservation actions.</p>
                <hr>
            </a>
        </div>
        <div class="swiper-slide">
            <h3 class="text-2xl text-white mb-4">Environmental Management</h3>
            <p class="text-base text-green-200">Learn about the practices and processes involved in sustainable management of this biome.</p>
        </div>
        <div class="swiper-slide">
            <h3 class="text-2xl text-white mb-4">Legislation</h3>
            <p class="text-base text-green-200">Discover the laws and regulations aimed at protecting the Atlantic Forest and its ecosystems.</p>
        </div>
        <div class="swiper-slide">
            <h3 class="text-2xl text-white mb-4">Conservation</h3>
            <p class="text-base text-green-200">Explore conservation initiatives and how we can preserve biodiversity.</p>
        </div>
    </div>
    <!-- If we need pagination -->
    <div class="swiper-pagination"></div>

    <!-- If we need navigation buttons -->
    <div class="swiper-button-prev"></div>
    <div class="swiper-button-next"></div>
</div>

CSS:

.swiper-slide {
    background: rgba(0, 0, 0, 0.6); /* Semi-transparent background */
    padding: 20px;
    border-radius: 8px;
    width: 100%; /* Change to 100% to ensure the slides take the full space */
    max-width: 300px; /* Set a limit for the size of the card */
    height: auto; /* Automatic height to let content dictate size */
    transition: transform 0.3s ease, box-shadow 0.3s ease;
    margin: 0 15px; /* Margin to space out the slides */
}

.swiper-wrapper {
    display: flex; /* Maintain this for flexible layout */
    gap: 20px; /* Space between cards */
}

.swiper {
    height: 700px; /* Ensure swiper height is set correctly */
}

Javascript

var swiper = new Swiper('.swiper', {
    loop: true,
    navigation: {
        nextEl: '.swiper-button-next',
        prevEl: '.swiper-button-prev',
    },
    pagination: {
        el: '.swiper-pagination',
    },
});

Has anyone encountered a similar issue or knows what could be causing this behavior? Any help would be greatly appreciated!

I tried changing the gap between the cards, but it didn’t solve anything.

prevent from consuming touch and scroll event on VictoryChart in React

when using this code in web browser and web app, cannot scroll on VictoryChart component
it consumes all event and so scroll not working
plz check the code below

import { useContext, useEffect, useRef, useState } from 'react';
import "../styles/global-style.css";
import colors from "../assets/values/Colors";
import TextWithSubNoun from '../component/TextWithSubNoun';
import { VictoryChart } from 'victory-chart';
import { VictoryAxis, VictoryBar, VictoryContainer, VictoryLabel, VictoryLine, VictoryTheme } from 'victory';
import { getSummary } from '../api/Service';
import { AppContext } from '../App';

const weekOrder = ["일요일","월요일","화요일","수요일","목요일","금요일","토요일"];

export const SettlementSummaryTab = () => {

    const { userId,setUserId } = useContext(AppContext);

    const [ isZoomedIn,setIsZoomedIn ] =useState(false);

    const [weekSum, setWeekSum] = useState(0);
    const [weekInfo, setWeekInfo] = useState([]);
    const [monthSum, setMonthSum] = useState(0);
    const [monthInfo, setMonthInfo] = useState([]);

    const chartRef = useRef(null);

    useEffect (()=> {
        getInfo();

        const logEvent= (event) => {
    

            console.log(`이벤트: ${event.type}`);
            console.log(`이벤트타겟: `+event.target);
            console.log(`이벤트현재타겟: `+event.currentTarget);
            
            console.log(`이벤트경로: `+event.composedPath?.() || event.path);
        
        };

        window.addEventListener('scroll', logEvent,true);
        window.addEventListener('touchstart', logEvent,true);
        window.addEventListener('wheel', logEvent,true);

        return () => {
            window.removeEventListener('scroll', logEvent,true);
            window.removeEventListener('touchstart', logEvent,true);
            window.removeEventListener('wheel', logEvent,true);

        }


    },[])

    const getInfo = async() => {

        try {
  
            const response = await getSummary(userId);
  
            const weekData = response.weekInfo_;

            weekData.sort((a,b) => {
                return weekOrder.indexOf(a.dayOfWeek) - weekOrder.indexOf(b.dayOfWeek);
            })
                

            setWeekSum(parseInt(response.weekSum_,10));
            setWeekInfo(weekData.map ( item => ({
                ...item,
                amount:parseInt(item.amount,10),
                count:parseInt(item.count,10),
            })));
            
            const monthData= response.monthInfo_.sort((a,b) => a.month-b.month);

            setMonthSum(parseInt(monthData[6].amount,10));
            setMonthInfo(monthData.map ( item => ({
                ...item,
                amount:parseInt(item.amount,10),
                count:parseInt(item.count,10),
            })));
              
        } catch (err) {
  
            console.log("fail :"+err);
        }
    }

    return ( 

        <div className='layout-vertical'>
            <div className='box-rounded-vertical'> 
                
                <div className='layout-horizontal-spacebetween'> 

                    {/* Label - 이번주 매출*/}
                    <span style={{ 
                        
                        color:colors.gray500,
                        alignItems:'flex-end',
                        fontFamily:'PretendardVariable',
                        fontSize:'18px',
                        fontWeight:400,
                        margin:'20px 0px 0px 20px'

                    }}>이번주 매출</span> 
                    {/*Label - 이번주 매출*/}
                    
                </div>

                <div className='layout-horizontal'> 

                    {/*이번주 매출 금액*/}
                    <TextWithSubNoun 
                        text={weekSum.toLocaleString()}
                        textColor={colors.black}
                        textSize='30px'
                        subNoun={'원'}
                        subNounColor={colors.gray600}
                        subNounSize='16px'
                        margin='10px 0px 0px 20px'
                    /> 
                    {/*이번주 매출 금액*/}
                    
                    {/*상승하락 퍼센트*/}
                    <span style={{ 
                        
                        color:colors.gray500,
                        alignItems:'flex-end',
                        fontFamily:'PretendardVariable',
                        fontSize:'18px',
                        fontWeight:400,
                        margin:'10px'

                    }}></span> 
                    {/*상승하락 퍼센트*/}

                </div>

                <div
                    style={{
                        display:isZoomedIn? 'none':'flex',
                        width:'100%',
                    }}>

                    <VictoryChart

                        theme= { VictoryTheme.grayscale }
                        domainPadding={30}
                        style={{
                            pointerEvents:'none',
                        }}
                    
                    >

                        <VictoryAxis 
                            tickValues={[1,2,3,4,5,6,7]}
                            tickFormat={weekInfo.map(data => `${data.dayOfWeek.charAt(0)} n ${
                                data.date.substring(4).charAt(0) === '0' ?
                                data.date.substring(4).charAt(1)+'/'+data.date.substring(6):
                                data.date.substring(4).substring(0,2)+'/'+data.date.substring(6)

                            }`) }
                            
                            tickLabelComponent={
                                <VictoryLabel
                                    lineHeight={[1,1.28]}
                                    style={[{fill:colors.gray700, fontSize:'14.8px',fontFamily:'PretendardVariable'},{fill:colors.gray700, fontFamily:'PretendardVariable'}]}   
                                />
                            }

                            style={{
                                pointerEvents:'none',
                                axis:{ stroke:colors.gray200 }
                            }}
                            />


                        <VictoryAxis
                            dependentAxis
                            tickFormat={(value)=>
                                {   
                                    if(value<0.1) {
                                        return [];
                                    }
                                    return (`${value/10000}만`);
                                }
                                    
                                }
                            tickLabelComponent={
                                <VictoryLabel
                                    style={{
                                        pointerEvents:'none',
                                        fill:colors.gray700, 
                                        fontSize:'13.8px',
                                        fontFamily:'PretendardVariable'}}   
                                />
                            }

                            style={{
                                pointerEvents:'none',
                                axis:{ stroke:colors.gray200 }
                            }}/>
                            

                        <VictoryBar
                            data={weekInfo}
                            x="dayOfWeek"
                            y="amount"
                            barRatio={0.8}
                            cornerRadius={5}
                            labels={({datum}) => datum.amount === 0 ? null:`${datum.count}건`}
                            labelComponent={
                                <VictoryLabel
                                    lineHeight={1}
                                    style={{
                                        pointerEvents:'none',
                                        fill:colors.tint, 
                                        fontFamily:'PretendardVariable'
                                    }}   
                                />
                            }
                            style={{
                                pointerEvents:'none',
                                data:{fill:'rgba(89,183,164,0.4)'}
                            }}
                        />


                        



                    </VictoryChart>



                </div>

                


            </div>

            <div 
                className='box-rounded-vertical'
                style={{margin:'28px 0 0 0'}}
            > 
                
                <div className='layout-horizontal-spacebetween'> 

                    {/* Label - 이번달 매출*/}
                    <span style={{ 
                        
                        color:colors.gray500,
                        alignItems:'flex-end',
                        fontFamily:'PretendardVariable',
                        fontSize:'18px',
                        fontWeight:400,
                        margin:'20px 0px 0px 20px'

                    }}>이번달 매출</span> 
                    {/*Label - 이번달 매출*/}
                    
                </div>

                <div className='layout-horizontal'> 

                    {/*이번달 매출 금액*/}
                    <TextWithSubNoun 
                        text={monthSum}
                        textColor={colors.black}
                        textSize='30px'
                        subNoun={'원'}
                        subNounColor={colors.gray600}
                        subNounSize='16px'
                        margin='10px 0px 0px 20px'
                    /> 
                    {/*이번달 매출 금액*/}
                    
                    {/*상승하락 퍼센트*/}
                    <span style={{ 
                        
                        color:colors.gray500,
                        alignItems:'flex-end',
                        fontFamily:'PretendardVariable',
                        fontSize:'14px',
                        fontWeight:400,
                        margin:'10px'

                    }}></span> 
                    {/*상승하락 퍼센트*/}

                </div>

                <div
                    style={{
                        display:isZoomedIn? 'none':'flex',
                        width:'100%', 
                        paddingLeft:'10px'
                    }}>

                    <VictoryChart
                        theme= { VictoryTheme.grayscale }
                        domainPadding={30}>

                        <VictoryAxis
                            tickValues={[1,2,3,4,5,6,7]}
                            tickFormat={monthInfo.map(data => ` ${
                                data.month.charAt(4) === '0' ?
                                data.month.substring(5)+'월':
                                data.month.substring(4)+'월'

                            }`) }
                        
                            tickLabelComponent={
                                <VictoryLabel
                                    style={{fill:colors.gray700, fontSize:'16.8px',fontFamily:'PretendardVariable'}}   
                                />
                            }

                            style={{

                                axis:{ stroke:colors.gray200 }
                            }}/>


                        <VictoryAxis
                            dependentAxis
                            tickFormat={(value)=>
                                {   
                                    if(value<0.1) {
                                        return [];
                                    }
                                    return (`${value/10000}만`);
                                }
                                    
                                }
                            tickLabelComponent={
                                <VictoryLabel
                                    style={{fill:colors.gray700, fontSize:'13.8px',fontFamily:'PretendardVariable'}}   
                                />
                            }

                            style={{

                                axis:{ stroke:colors.gray200 }
                            }}/>

                        <VictoryLine
                            data={monthInfo}
                            x="month"
                            y="amount"
                        
                            labels={({datum}) => datum.amount === 0 ? null:`${datum.count}건`}
                            labelComponent={
                                <VictoryLabel
                                    renderInPortal dy={-20}
                                    lineHeight={1}
                                    style={{fill:colors.gray700,fontSize:'17px', fontFamily:'PretendardVariable'}}   
                                />
                            }
                            style={{
                                data:{stroke:'rgba(89,183,164,0.6)'},
                                parent:{border:`1px solid ${colors.gray400}`}
                            }}/>
                            

                        

                    </VictoryChart>



                </div>

                


            </div>

        </div>


    )

}

export default SettlementSummaryTab;

log result below when touching and scrolling on VictoryChart

이벤트: touchstart
이벤트타겟: [object SVGSVGElement]
이벤트현재타겟: [object Window]
이벤트경로: [object SVGSVGElement],[object HTMLDivElement],[object HTMLDivElement],[object HTMLDivElement],[object HTMLDivElement],[object HTMLDivElement],[object HTMLDivElement],[object HTMLDivElement],[object HTMLDivElement],[object HTMLDivElement],[object HTMLDivElement],[object HTMLBodyElement],[object HTMLHtmlElement],[object HTMLDocument],[object Window]

when touching on VictoryChart, scroll working

Typescript – Is it possible to extract a list of types from a constant object?

I’m trying to read from a data file where everything is stored in arrays, and transfer that to the equivalent Javascript object.

What I want to be able to do with typescript is create a system that automatically reads the arrays, and stores them in corresponding object, but also is able to verify that the types are correct in order to avoid hard to debug errors.

What I’d like to be able to do is something like the following


//Template that will specify types of Typescript, but also allow me to use the keys with javascript
const SaveDataTemplate = {
    id: Number(),
    name: String(),
    someBool: Boolean(),
}

//Type to allow for type-checking the save data input/output
type tSaveData = GetKeyTypesFrom<SaveDataTemplate>; //Theoretically would return constant array type of [number, string, boolean];

//Takes in array from save data and returns key/value object
function fromSaveData(data: tSaveData): typeof SaveDataTemplate {
    const returnObj = {};
    let idx = 0;
    
    for (const key in SaveDataTemplate){
        returnObj[key] = data[idx++];
    }
    
    return returnObj as any;
}

//Takes in object which contains keys which are in SaveDataTemplate and returns array in specific format
function toSaveData(data: typeof SaveDataTemplate): tSaveData {
    const returnArr = [];
    
    for (const key in data){
        returnArr.push(data[key]);
    }
    
    return returnArr as any;
}

In a language like C++ Structs would make this easy, but since Jvascript doesn’t have those it’s turning out to be pretty difficult to find a workaround.

How to use a variable in place of “event ID” in Eventbrite embedded checkout

I am trying to embed an eventbrite checkout within a dynamic page of my Wix site. Each page needs to have a checkout element for a different show. Very new to HTML, but, if I am understanding correctly, I need to assign the “eventID” within the createWidget method to a variable rather than a string constant. I am currently passing the eventID from my page code using the postMessage() function, but when I try to assign that data to a variable in the HTML, something seems to be going wrong. Here is what I have included in my page (Velo) code:

$w("#eventbriteSales").postMessage(964311781497);

And below is my HTML code contained within the embedded element:
`

<div id="eventbrite-widget-container-964311781497"></div>

<script src="https://www.eventbrite.com/static/widgets/eb_widgets.js"></script>

<script type="text/javascript">
  let EventbriteID = "0"
  window.onmessage = (event) => {
      if (event.data) {
         EventbriteID = event.data;
      }
  };
    var exampleCallback = function() {
        console.log('Order complete!');
    };

    window.EBWidgets.createWidget({
        // Required
        widgetType: 'checkout',
        eventId: EventbriteID,
        iframeContainerId: 'eventbrite-widget-container-964311781497',

        // Optional
        iframeContainerHeight: 425,  // Widget height in pixels. Defaults to a minimum of 425px if not provided
        onOrderComplete: exampleCallback  // Method called when an order has successfully completed
    });
</script>`

Empty Character issue when using InnerHTML

I create DOM Inner HTML with this code below:

var popupVhc1 = L.DomUtil.create('div', 'popup-vhcmap');
tablepopupVhc1 = L.DomUtil.create('table','table table-infopopup',popupVhc1);
trpopupVhc1 = L.DomUtil.create('tr','',tablepopupVhc1);
tdiconpopupVhc1 = L.DomUtil.create('td','col-1 align-midle bg-popup-gre',trpopupVhc1);
infoiconpopupVhc1 = L.DomUtil.create('i','bi bi-car-front-fill text-icon-popup',tdiconpopupVhc1);
tdcontentpopupVhc1 = L.DomUtil.create('td','col-6 td-content-popup',trpopupVhc1);

tdcontentpopupVhc1.innerHTML += '<b>B 8384 UCR</b><br>';
tdcontentpopupVhc1.innerHTML += 'Moving - 84 Kph - 25<sup>o</sup><br>';
tdcontentpopupVhc1.innerHTML += '24-09-2024 20:38:32';
div.popup-vhcmap {
  font-size: 0.75rem;
  width: 200px;
  height: 80px;
  box-shadow: 0 0 1px 1px #6d6d6d;
  border-radius: 3px;
  text-align: center;
}

table.table-infopopup {
  height: 100%;
  width: 99%;
}

td.bg-popup-gre {
  background-color: #03b420;
  text-align: center;
}

td.td-content-popup {
  background-color: #fff;
  text-align: left;
  padding-left: 5px;
  line-height: 1.5;
}

i.text-icon-popup {
  font-weight: bold;
  color: #fff;
}

I have found issue about spacing (empty character) in my result as picture below:

Attention on red line

What’s wrong? If I remove tag b or sup, empty spacing will be removed, but this isn’t the result that I want.

if tag

What I want is like this

B 8384 UCR
Moving- 84 Kph – 25o
24-09-2024 20:38:32

not:

….B 8384 UCR
Moving- 84 Kph – 25 o
24-09-2024 20:38:32

also not:

B 8384 UCR
Moving- 84 Kph – 25o
24-09-2024 20:38:32

PS:

I tried with add "span" like this:

tdcontentpopupVhc1.innerHTML += '<span><b>B 8384 UCR</b></span><br>';
tdcontentpopupVhc1.innerHTML += '<span>Moving - 84 Kph - 25<sup>o</sup></span><br>';
tdcontentpopupVhc1.innerHTML += '<span>24-09-2024 20:38:32</span>'

and the result is below:

enter image description here

Routing in React App renders extra components on page

Let me start by disclosing that this is part of the capstone project for a React course I am taking in Coursera. I am not interested in the answer per se. I just want someone to tell me what is wrong and why. If later on I cannot figure it out, I will edit this question with what I did to attempt to fix the issue based on the feedback I received. For now, all I need is someone to point me in the right direction.

Right now, the home page renders correctly, as far as I can tell, because haven’t defined the routing. When I try to set the routing to the home page, the same issue shown in the picture below occurs. What I want is to set the routing so that when I go to a page, only the contents of that page is shown and nothing else. Right now it seems like, no matter what I do, the contents of the App component gets mixed up with whichever page I navigate to. When I navigate to the home page, it seems the contents of the app doubles. The picture below is an example of what the BookingPage looks like when I click on “Reservations” link. When the Route is not defined, it appears as if the contents of the App component renders normally.

import { Routes, Route, Link } from "react-router-dom";
import BookingPage from "./BookinPage";
import AboutUs from "./AboutUs";
import Menu from "./Menu";

function Nav () {
  return(
    <div>
      <nav>
        <ul>
          <li><Link to="/" className="link">Home</Link></li>
          <li><Link to="/about" className="link">About</Link></li>
          <li><Link to="/menu" className="link">Menu</Link></li>
          <li><Link to="/booking" className="link">Reservations</Link></li>
          <li><Link to="/" className="link">Order Online</Link></li>
          <li><Link to="/" className="link">Login</Link></li>
        </ul> 
      </nav>
      <Routes> 
        <Route path="/menu" element={<Menu />} />
        <Route path="/booking" element={<BookingPage />} />
      </Routes>
    </div>
  );
}

export default Nav;
import './App.css';
import Header from './Header';
import Main from './Main';
import Nav from './Nav';
import "@fontsource/karla"
import "@fontsource/markazi-text";


function App() {
  return (
    <>
      <div className="banner">
        <Header />
        <Nav />
      </div>
      <Main />
    </>
  );
}

export default App;

The Header component contains the logo and the Main component contains the different sections of the home page. Here are the code for those two components:

import logo from './assets/images/little_lemon_logo(sm).jpg'

function Header () {
  return (
    <header>
      <meta name="description" content="The Little Lemon restaurant website"/>
      <meta name="og:title" content="Little Lemon"/>
      <meta name="og:image" content="https://unsplash.com/photos/focus-photography-of-pumpkin-V1dae2Jj6-0"/>
      <img src={logo} alt="Little Lemon's logo" />
    </header>
  );
}

export default Header;
import Hero from "./Hero";
import Homepage from "./Homepage";
import Testimonials from "./Testimonials";
import AboutUs from "./AboutUs";
import Footer from "./Footer";

function Main () {
  return (
    <>
      <Homepage />
      <Hero />
      <Testimonials />
      <AboutUs />
      <Footer />
    </>
  );
}

export default Main;

Also, rather than posting all the code, I will add the link to the project location in GitHub: Little Lemon capstone project

enter image description here

Why Isn’t My Complete Case Working Anymore? It Used to Work

I’m stuck with an issue in my Laravel application. My form submission process used to work perfectly, but now it’s giving me issues

here is my controller for decline and approved cases

<?php

namespace AppHttpControllers;


use IlluminateHttpRequest;
use AppModelsdeclinecases;
use AppModelspendingcases;
use AppModelsfullfillmentcases;
use AppModelsreceived;
use AppModelsRequestOrderModel;
use IlluminateSupportFacadesSession;

class CaseController extends Controller
{
    public function fulfillment(Request $request) {

     

      Log::info('Fulfillment route hit with data:', $request->all());
 
      $receivedQuantities = $request->input('receivedQuantities');
      
      
      foreach ($receivedQuantities as $receivedQuantity) {
        $family_id = $receivedQuantity['familyId'];

        $requestOrderId = $receivedQuantity['requestOrderId'];

        $requestedItem = $receivedQuantity['requestedItem'];

        $receivedQty = (int) ($receivedQuantity['receivedQuantity']);
    
      $received = new received();
        $received->family_id = $family_id;
        $received->requestorder_id = $requestOrderId;
        $received->reev = $receivedQty;
        $received->requestedItem = $requestedItem;
        $received->save();
    }



    // if the case will be approved then the the first step is to delete the case from pending case and transfer it to fullfill case table
  
   

    $caseID = $request ->input('caseID');

   
    

    // Retrieve the case from the pending cases table 
    $pendingCase = pendingcases::find($caseID);
   
    if($pendingCase) {
      $fulfillmentCase = new fullfillmentcases();

      // transfer data from pending cases to fulfillment table

      $fulfillmentCase -> family_id = $pendingCase ->family_id;
      $fulfillmentCase -> firstname = $pendingCase ->firstname;
      $fulfillmentCase -> lastname  = $pendingCase ->lastname;
      $fulfillmentCase -> phone     = $pendingCase ->phone;
      $fulfillmentCase -> address   = $pendingCase ->address;
      $fulfillmentCase -> receivedDate = $pendingCase -> receivedDate;
      $fulfillmentCase -> MoveInDate = $pendingCase -> MoveInDate;
      $fulfillmentCase -> daterequested = $pendingCase ->daterequested;

      $fulfillmentCase->approval_date = now(); // the date the case was approved 

       // Delete the case from the pending cases table
       $pendingCase->delete();

    
      $fulfillmentCase->save();
     
      return response() -> json([
        'success' => true,
        'message' => 'Case Approved'
    ]);

  } else {
    return response() -> json([
      'success' => false,
      'message' => 'An error occurred'
  ]);
  }

  }





    public function decline(Request $req) {

     $reason = $req->input('reason'); // reason why case is being declined 
     $receivedQuantities = $req->input('receivedQuantities');


     foreach ($receivedQuantities as $receivedQuantity) {
      $family_id = $receivedQuantity['familyId'];
     
      $requestOrderId = $receivedQuantity['requestOrderId'];
     
      $requestedItem = $receivedQuantity['requestedItem'];
      // ask Mrs susan if she wants to have an automatic 0 since is decline or ask her if she wants to put it manually
      $receivedQty = (int) ($receivedQuantity['receivedQuantity']);
     
      $received = new received();
      $received->family_id = $family_id;
      $received->requestorder_id = $requestOrderId;
      $received->reev = 0; // $receivedQty we put a 0 because we want it to automatically add 0 to any because it is a disqualified case 
      $received->requestedItem = $requestedItem;
      $received->save();
     }

    

    $caseID = $req->input('caseID');



    // Retrieve the case from the pending cases table 
     $pendingCase = pendingcases::find($caseID);

     if($pendingCase) {

      $decline = new declinecases();

      // transfer data from pending case to decline case

      $decline -> family_id = $pendingCase ->family_id;
      $decline -> firstname = $pendingCase ->firstname;
      $decline -> lastname  = $pendingCase ->lastname;
      $decline -> phone     = $pendingCase ->phone;
      $decline ->address    = $pendingCase ->address;
      $decline -> daterequested = $pendingCase ->daterequested;

      $decline -> datedeclined = now(); // the date the case was declined 
      $decline -> reason =  $reason;  // reason for decline 

      // delete case from the pending case table

      $pendingCase ->delete();

      //save the declined case in the declined case table

      $decline ->save();

      return response() -> json([

        'success' => true,
        'message' => 'Case Sucessfully Declined'
      ]);
     } else {
        return response() -> json([
          'sucess' => false,
          'message' => 'An error occured'
        ]);
     }
  }
  
    
    
}

HTML and submit button

   </tr>
        {{-- Loop through remaining categories --}}
        @foreach ($requestorders as $key => $ro)
            @if ($key > 0)
                <tr>
                    <td>{{ $ro->category }} @if($ro->substitute) <br> --SUBSTITUTED @endif</td>
                    <!-- <td>{{ $ro->categoryTotal }}</td> -->
                    <td>{{ $ro->requestedItem }}  @if ($ro->substitute_product) <br> (substituted: {{ $ro->substitute_product }}) @endif </td>
                    <td>{{ $ro->amountNeeded }}   @if (isset($ro->substitute_quantity)) <br> (substituted: {{ $ro->substitute_quantity }}) @endif</td>
                    <td><input type="number" name="reev[]" id="reev" data-request-order-id="{{ $ro->id }}" min="0" class="form-control"></td>
                    <td><button type="button" class="btn btn-primary" data-toggle="modal" data-target=".substitute-modal" data-category="{{ $ro ->category }}" data-product="{{ $ro->requestedItem }}" data-request-order-id="{{ $ro->id }}">Substitute</button></td> <!-- this doesnt work  -->
                </tr>
            @endif
        @endforeach
    </tbody>
                                    </table>
                                </div>

                            </div>
                            <button id="submitButton" class="btn btn-primary" data-case-id="{{$pendingcases->id}}"  type="submit" onclick="submitForm()" >Complete Order</button>

                        </div>
                     </div>

JS


<script>

    
function showNotificationModal(type, message) {
  const modal = $('#notificationModal');
  const notificationMessage = modal.find('.modal-body');

  // Set the message and color based on the notification type
  //notificationMessage.text(message);
  if (type === 'success') {
    notificationMessage.html('<div class="alert alert-success">' + message + '</div>');
  } else {
    notificationMessage.html('<div class="alert alert-danger">' + message + '</div>');
  } 

  // Show the modal
  modal.modal('show');
}




function submitForm() {
  $(document).ready(function() {
    $('#submitButton').click(function(e) {
      e.preventDefault();

      // Get the form values
      const decision = $('#decisionDropdown').val();
      const reason = $('#val-skill option:selected').text();
      const caseId = $(this).data('case-id');

      // Prepare the data to be sent
      const formData = {
        decision: decision,
        reason: reason,
        caseID: caseId,
        receivedQuantities: $('input[name="reev[]"]').map(function() {
          const familyId = document.getElementById('familyId').textContent;
          const requestOrderId = $(this).data('request-order-id');
          const receivedQuantity = $(this).val();
          const requestedItem = $(this).closest('tr').find('td:eq(3)').text().trim();
          return {
            familyId: familyId,
            requestOrderId: requestOrderId,
            receivedQuantity: receivedQuantity,
            requestedItem: requestedItem
          };
        }).get()
      };

      const csrfToken = $('meta[name="csrf-token"]').attr('content');
      const headers = {
        'X-CSRF-TOKEN': csrfToken
      };

      if (decision === 'APPROVE') {
        // Perform the AJAX request for fulfillment
        $.ajax({
          url: '/fulfillment',
          type: 'POST',
          data: formData,
          dataType: 'json',
          headers: headers,

          success: function(response) {
            console.log('Form submission successful:', response);
            if (response.success) {
              showNotificationModal('success', 'Case approved');
              // Additional logic for fulfilled cases
              window.location.href = '/dashboard';
            } else {
              showNotificationModal('error', response.message);
            }
          },
          error: function(xhr,status, error) {
            console.error('Form submission failed RIGHT ERE:', xhr.responseText, status, error);
            showNotificationModal('error', 'An error occurred');
          }
        });
      } else if (decision === 'DECLINE') {
        // Perform the AJAX request for decline
        $.ajax({
          url: '/decline',
          type: 'POST',
          data: formData,
          dataType: 'json',
          headers: headers,

          success: function(response) {
            console.log('Decline request successful:', response);
            // Handle success response for decline request here
            window.location.href = '/dashboard';
          },
          error: function(error) {
            console.error('Decline request failed:', error);
            // Handle error response for decline request here
          }
        });
      } else {
        // Handle cases where the decision is neither 'Approved' nor 'declined'
        console.error('Invalid decision:', decision);
        showNotificationModal('error', 'Invalid decision');
      }
    });
  });
 }




    // the following function toggles the decision and reason dropdown
    // if the user select decline then reason drop down will appear
    //if the user select approve the the reason dropdown will disappear
     function toggleReasonDropdown() {
      var decisionDropdown = document.getElementById("decisionDropdown");
      var reasonDropdown = document.getElementById("reasonDropdown");
    

      // Check if "DECLINE" is selected
      if (decisionDropdown.value === "DECLINE") {
        // Show the reason dropdown
        reasonDropdown.style.display = "block";

     
      } else {
        // Hide the reason dropdown
        reasonDropdown.style.display = "none";
     
      }
    }

</script>

case options

                                                     <div class="form-group row">
  <div class="col-lg-8">
    <div class="d-flex align-items-center">
      <h4 class="text-primary mr-2">DECISION:</h4>
      <select class="form-control" id="decisionDropdown" name="decisionDropdown" onchange="toggleReasonDropdown()" >
        <option value="OPTION">Please select</option>
        <option value="APPROVE">APPROVE</option>
        <option value="DECLINE">DECLINE</option>
      </select>
    </div>
  </div>
</div>

when I want to approved it just show as if a modal wants to appear but nothing and decline does nothing it used to work. could it be I used to many submit button

the above code used to work . I expect this code to send a case to decline table or fullfillment table based on the decision

I dont know if I may have to other submit button but they are unique

Module not found: Error: Can’t resolve ‘react-native’ in ‘C: blah blah blah file location’

I’m looking to implement stack navigation and bottom navigation bar in my new react application. I was initially using a Router to navigate from Log In screen to Sign Up screen but needed to switch once my app got more complex. I am getting about 48 errors from my new strategy and believe it stems from my dependencies or node_modules.

Please let me know if anyone has encountered similar issues. I’ve seen other people posting about this and none of the solutions seem to work. Thanks!

I reinstalled npm multiple times and have single handedly gone through each dependency. This is the exact error I’m getting and they are all similar:

ERROR in ./node_modules/@react-navigation/bottom-tabs/lib/module/utils/useIsKeyboardShown.js 2:0-50

TailwindCSS – avoid purge of generative classes

I would like to prevent Tailwind from purging some classes. They are generated in the component eg.

className=`text-${size}`

Tailwind does not know it will result in text-sm, text-base and text-lg even if size variable is a union of

type Size = "sm" | "base" | "lg";

Is it possible to achieve that without using full classes elsewhere in the code?
The only solution I managed to find is:

const sizeClass = size === "sm" ? "text-sm" : size === "lg" ? "text-lg" : "text-base";
(...)
className={sizeClass}

Simple assignment versus push method in prototypal inheritance [duplicate]

Say I have this block of code:

let hamster = {
  stomach: [],

  eat(food) {
    this.stomach.push(food);
  }
};

let speedy = {
  __proto__: hamster
};

let lazy = {
  __proto__: hamster
};

speedy.eat("apple");
alert( speedy.stomach ); // apple
.
alert( lazy.stomach ); // apple

Both speedy and lazy objects share the same stomach array, but when I instead use a simple assignment for the eat function :

  eat(food) {
    // assign to this.stomach instead of this.stomach.push
    this.stomach = [food];
  }
};

For the simple assignment hey have different stomach arrays.

Both cases behave differently but why is that? Yet both use the ‘this’ keyword.