How to build a nestjs reminder function

In nestjs i have a POST api to add a Date object which is the date and time to send a notification to mobile app.

So i need to check for all users, which all reminders are reached so that i need to trigger a reminder to my mobile app.

This is my function in nestjs

import { Injectable } from '@nestjs/common'
import { UserRepository } from '../auth/repositories/user.repository'
import { User } from '@vitabotx/common/entities/auth/user.entity'

@Injectable()
export class NotificationsCronService {
    constructor(private readonly userRepository: UserRepository) {}

    async sleepReminderCron() {
        const users: User[] =
            await this.userRepository.getAllUsersForSleepReminder()

        // Set up interval to check reminders continuously
        const interval = setInterval(async () => {
            const currentDate = new Date()

            for (const user of users) {
                for (const reminder of user.userReminder) {
                    if (currentDate >= reminder.time) {
                        console.log(
                            `User ${user.id} should receive sleep reminder.`
                        )
                    }
                }
            }
        }, 1000)

        setTimeout(
            () => {
                clearInterval(interval)
            },
            59 * 60 * 1000
        )
    }
}

So i thought of running a setInterval and settimeout to check every second when the time is reached or not instead of querying the DB every minute or so.

Is there any recommended way how everyother projects achieve this kind of scenario?

Cannot add to cart

function updateUserOrder(productId,action) {
    console.log('user logged in, success add')
    var url = '/update_item/'
    fetch(url,{
        method: 'POST',
        headers: {
            'Content-Type': 'application/json',
            'X-CSRFToken': csrftoken
        },
        body: JSON.stringify({'productId':productId,'action':action })
    })
    .then((response) =>{
        return response.json()
    })
    .then((data) =>{
        console.log('data',data)
        location.reload()
    })  
} 

cart.js

def updateItem(request):
    data = json.loads(request.body)
    productId = data['productId']
    action = data['action']
    customer = request.user.customer
    product = Product.objects.get(id = productId)
    order, created = Order.objects.get_or_create(customer =customer,complete=False)
    orderItem, created = OrderItem.objects.get_or_create(order =order,product=product)
    if action =='add': 
        orderItem.quantity +=1
    elif action =='remove':
        orderItem.quantity -=1
    orderItem.save()
    if orderItem.quantity<=0:
        orderItem.delete()

    return JsonResponse('added',safe=False)

views.py

console
productId 8 action add
cart.js:8 user: admin
cart.js:12 user logged in, success add

I have tried many sources but none of them solve the problem. I hope my add to cart function works.

Issue when populate dropdown value in UI

Using STS (Spring Tool Suite) for our development.
We have a dropdown – Sectoral Concentration of Credit Exposures.
Drop down values are

  1. 1 – <200% TCE
  2. 2 – Between 200% & 500% TCE
  3. 3 – >500% TCE or n/a

We are successfully able to save this value in DB and also populated on the UI When select option 1) ‘1 – <200% TCE’. Our issue is when select option 2) ‘2 – Between 200% & 500% TCE’, the value is successfully saved in Database but not able to display on the UI. When we print this value in log file from daoimp, we noticed the value gets trimmed to 20 characters: ‘2 – Between 200% & 5’. Declared VARCHAR2(250 BYTE) in DB.

Did anyone face this issue earlier ? Please help. Thanks in advance.

Please let me know how to display this option 2 value correctly on the UI.

No me funciona este código en wordle [closed]

[text](

let intentos = 6;

let lista = [“barco”,”Cobra”, “barca”, “carga”, “cofre”,”cabra”];

let posicion = Math.floor(Math.random() * lista.length);

let palabra = lista[posicion];

console.log(palabra);

const INPUT = document.getElementById(“guess-input”);

const BUTTON = document.getElementById(“guess-button”);

BUTTON.addEventListener(“click”, intentar);

function intentar() {

const intento = leerIntento();

console.log(intento);

const GRID = document.getElementById(“grid”);

const ROW = document.createElement(“div”);

ROW.className = “row”;

for(let pos in palabra) {

const SPAN = document.createElement("span")

SPAN.className = "letter";

if(intento[pos]===palabra[pos]){

SPAN.innerHTML = intento[pos];

conaole.log(intento[pos], "verde");

SPAN.style.backgroundColor = “#79b851”;

}else if(palabra.includes(intento[pos])) {

SPAN.innerHTML = intento[pos];

console.log(intento[pos], "amarillo");

SPAN.style.backgroundColor = "#f3c237";

}else {

SPAN.innerHTML = intento[pos];

console.log(intento[pos], "gris");

SPAN.style.backgroundColor = "#a4aeca";

}

ROW.appendChild(SPAN)

}

GRID.appendChild(ROW);

GRID.appendChild(ROW);

intentos–;

console.log(“te quedan” + intentos);

if(intento === palabra) {

terminar ("<h1>GANASTE!</h1>")

}

if(intentos == 0) {

terminar("<h1>PERDISTE</h1>");

}

}

function leerIntento() {

let intento = document.getElementById("guess-input");

intento = intento.value;

intento = intento.toUpperCase();

console.log("leerintento" + intento);

return intento;

}

function terminar(mensaje) {

const INPUT = document.getElementById("guess-input");

INPUT.disabled = true;

BUTTON.disabled = true;

let contenedor = document.getElementById("guesses");

contenedor.innerHTML = mensaje;

})

Probé en la web el intento y me salió que perdí

Tracking user behaviour with link visit error

In this code I tried to track user behaviour by using AI by given Command and example code from internet
`

User Behavior Tracker

.visited { background-color: green !important; } /* Added !important to override Bootstrap styles */
.failed { background-color: red; }

Link List

Link 1
Link 2
Reward Link

  <script>
const links = document.querySelectorAll('.link-list a:not(#rewardLink)');
const rewardLink = document.getElementById('rewardLink');
const visitedLinks = new Array(links.length).fill(false); // Initialize visitedLinks array

links.forEach((link, index) => {
  link.addEventListener('click', () => {
    const newWindow = window.open(link.href, `linkWindow_${index}`, "width=400,height=300");

    // Mark link as visited after 5 seconds
    const visitTimeout = setTimeout(() => {
      visitedLinks[index] = true;
      link.classList.add('visited');
      checkUnlock();
    }, 5000);

    // Close the opened window after 5 seconds
    setTimeout(() => {
      newWindow.close();
    }, 5000);

    // Handle user moving to another tab or closing the window
    const handleVisibilityChange = () => {
      if (document.visibilityState === 'hidden') {
        clearTimeout(visitTimeout);
        link.classList.add('failed');
        checkUnlock();
      }
    };

        document.addEventListener('visibilitychange', handleVisibilityChange);

    newWindow.onbeforeunload =     () => {
      clearTimeout(visitTimeout);
      document.removeEventListener('visibilitychange', handleVisibilityChange);
      link.classList.add('failed');
      checkUnlock();
    };
  });
});

function checkUnlock() {
  if (visitedLinks.every(visited => visited)) {
    rewardLink.classList.remove('disabled');
    rewardLink.textContent = 'Reward Link (Unlocked)';
  }
}
  </script> 
</body>
</html>`

Not working.If I visit the link for 5 seconds it does not close the opened tab, if links visited for 5 sec showing red error also but it has to Show green. What is the problem with this code please help me.

May someone help me to built this.

how to solve the viewport problem in parallax effect?

I’m currently learning how to implement a parallax effect on my website. Despite following a tutorial closely, I’m encountering an issue with the positioning and movement of the images.The problem I’m facing is that when I scroll down, the burjkhalifa image scrolls out of the viewport. Despite trying to adjust the image size and positioning, the issue persists. In the tutorial I followed, the image stayed within the viewport while scrolling.

Can anyone help me troubleshoot this issue and ensure that the images fit well for the parallax effect without scrolling out of view?

How to get the top most level object in a nested structure in Angular component

I am trying to build a query builder using Angular similar to JQuery builder.I am facing an issue with respect to emitting the data.

When I click the addGroup, addRule buttons then the new group is getting added to the array at the specified level. Now I want the entire object structure including the one which got pushed. How to get that from HTML to component ?

For example, If the Initial structure is :

{
  "condition": "AND",
  "rules": [
    {
      "id": "price",
      "field": "price",
      "type": "double",
      "input": "number",
      "operator": "less",
      "value": 10.25
    },
   
  ],
  "valid": true
}

And I have added the newGroup now, so the latest structure is:

{
  "condition": "AND",
  "rules": [
    {
      "id": "price",
      "field": "price",
      "type": "double",
      "input": "number",
      "operator": "less",
      "value": 10.25
    },
    {
      "condition": "OR",
      "rules": [
        {
          "id": "category",
          "field": "category",
          "type": "integer",
          "input": "select",
          "operator": "equal",
          "value": 2
        },
        {
          "id": "category",
          "field": "category",
          "type": "integer",
          "input": "select",
          "operator": "equal",
          "value": 1
        }
      ]
    }
  ],
  "valid": true
}

I want this entire object to be available in component in addGroup method.There can be n number of nested levels and I want the entire object.

Working Code:text

Resolving CORS issue while sending request from Local File [duplicate]

I have the following HTML and JS file:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Project Tasks Viewer</title>
</head>
<body>
    <h1>Enter the Project ID to Get Tasks</h1>
    <input type="number" id="projectId" placeholder="Enter project id">
    <button onclick="getProjectTasks()">Get Tasks</button>
    <div id="tasksResponse"></div>

    <script>
async function getProjectTasks() {
    const projectId = document.getElementById('projectId').value;
    if (!projectId) {
        alert('Please enter a project ID');
        return;
    }

const myHeaders = new Headers();
myHeaders.append("Authorization", "Token my token here");


const requestOptions = {
  method: "GET",
  headers: myHeaders,
  redirect: "follow"
};

fetch("https://example.com/api/v2/projects/52/tasks/", requestOptions)
  .then((response) => response.text())
  .then((result) => console.log(result))
  .catch((error) => console.error(error));
}


</script>
</body>
</html>

Whenever i try to send a request to it, it ends up with the following error:
without-no-cors error

When i add a mode:no-cors in the request, it ends up with the following error:
Here is the no-cors mode updated part:

const requestOptions = {
  method: "GET",
  mode:"no-cors",
  headers: myHeaders,
  redirect: "follow"
};

no-cors

I have tried installing some extentions in the browser that prevent the error but it does not work with the extentions as well. I do not have access to the server and the code can not be changed there for now.

If i try to send the request using POSTMAN, it works fine. Why is it giving the 401 error while using no-cors in the request? I can confirm that the authorization token is correct.

I need to use the response from the api in my rest of the code. Does no-cors allow that?

How to sort an array with dropdown menu while only showing 10 results per page?

I’m creating a search result page, and I’m trying to sort/filter the results using a dropdown menu. However, I also want for my code to still only show 10 results per page. I tried sorting results using an if statement, but I have no idea how to actually sort the results on the page.

There’s more code than listed, but I got rid of some unnecessary things so I can be more clear about my problem. The result array include objects that have a name, description, website, categories, upvotes, and downvotes. The code below only includes the name.

Basically, I want the results to be sorted and only 10 results to show up on the page at a time. How do I do that?

//imports


const results = [...]

export default function SearchResults() {
    const [page, setPage] = useState(0); 

    const List = () => {
        return (
            <>
            {
                results.slice(page * 10, page * 10 + 10).map((result) => {
                    return (
                        <div className="bg-gray-800 shadow-lg shadow-red-500 m-5">
                            <div className="flex flex-row gap-4 p-5">
                                <div className="flex flex-col w-1/2">
                                    <div className="flex flex-row gap-4">
                                        <p className="text-lg font-bold">{result.name}</p>
                                    </div>
                                </div>
                            </div>
                        </div>
                    )
                })
            }
            </>
        )
    }

    const prevPage = () => {...}

    const nextPage = () => {...}

    const arrangeResults = () => {
        if (orderResults?.value === "A-Z") {
            results.sort((a, b) => a.name.localeCompare(b.name));
        } else if (orderResults?.value === "Z-A") {
            results.sort((a, b) => b.name.localeCompare(a.name));
        } else if (orderResults?.value === "Popular") {
            results.sort((a, b) => b.upvotes - a.upvotes);
        } else if (orderResults?.value === "New") {
            // Add functiionality for newest results
        }
    }

    const orderResults = window.document.getElementById("order-results") as HTMLSelectElement;
    orderResults?.addEventListener("change", arrangeResults);

    const PaginationNumbers = () => {...}

    const NOP = () => {...}

    return (
        <div className="flex flex-col justify-center items-center">
            <div>
                <Search/>
            </div>
            <div className="flex flex-row justify-center">
                <div className="w-1/2">
                    <List/>
                </div>
                <div className="w-1/3 m-2 p-2 flex flex-col h-fit items-center bg-gray-800">
                    <select name="order-results" id="order-results" className="bg-gray-900 text-white text-sm rounded-lg focus:ring-red-500 focus:border-red-500 block w-full p-2.5">
                        <option value="A-Z" selected>A-Z</option>
                        <option value="Z-A">Z-A</option>
                        <option value="Popular">Popular</option>
                        <option value="New">New</option>
                    </select>
                </div>
            </div>
            <div className="flex flex-row justify-center items-center flex-wrap w-2/3">
                <button onClick={prevPage} className="bg-gray-800 text-white m-2 p-2 hover:bg-white hover:text-black rounded-lg">Prev</button>
                <PaginationNumbers/>
                <button onClick={nextPage} className="bg-gray-800 text-white m-2 p-2 hover:bg-white hover:text-black rounded-lg">Next</button>
            </div>
        </div>
    )
}

Async Await is the same as blocking? [duplicate]

An example from the “Learning React” book:

  1. In the past we had to wait until some method completed
  2. Then, we invented fetch() which returns a Promise, which doesn’t block a thread so a code execution can be continued, and the results from fetch() get retrieved where they needed
  3. Then we created async/await. Quote: “This makes it an asynchronous function that can wait for promises to resolve before executing the code any further

So basically we went back to step 1, where we had to wait until the function was completed.
What is the purpose of async/await if we have to wait until the function completes, similar to the synchronous approach?

*ngFor and @for input decorator and casting closure

I am having different levels of closure using *ngFor directive and the new @for block. I have a parent component that creates multiple child components using a for loop:

        <app-active-problem class="panel" *ngFor="let activeProblem of summary.activeProblems" [activeProblem] = "activeProblem" (update)="updateActiveProblem($event);"></app-active-problem>
        <!--
        @for (activeProblem of summary.activeProblems; track $index) {
            <app-active-problem class="panel" [activeProblem] = "activeProblem" (update)="updateActiveProblem($event);"></app-active-problem>
        }-->
      </ng-container>

In the child component I accept the [activeProblem] input as either a ProblemGroup | NarrativeProblem class. In order to effectively distinguish between the two and render a view. I create two instance variables

  problemGroup?: ProblemGroup;
  narrativeProblem?: NarrativeProblem;

  ngOnInit(): void {
    if (this.activeProblem instanceof ProblemGroup) {
      this.problemGroup = this.activeProblem as ProblemGroup;
    } else {
      this.narrativeProblem = this.activeProblem;
    }
  }

Within this same view I have a click event handler that toggles the value under the problem group (essentially mutating the object).

            <input
              clrCheckbox
              type="checkbox"
              [checked]="p.value"
              (change)="toggle($event, $index)"
            />

If I have rendered the child component using @for when assigning activeProblem to problemGroup it loses it’s reference, effectively creating a copy of the object. So any mutations I do in the child component is not reflected in the original object.

If I have rendered the child component using *ngFor directive, then it works as expected, any mutations I make to problemGroup effectively points to activeProblem.

I am hoping I can get some clarity on why this is happening?

How to get the dimensions of an Image when it is ‘resized’ using JavaScript?

I’m not very experienced with JavaScript and I already googled this but didn’t get the answer.

I just need to get the dimensions of an image when it enlarges or shrinks. :/

Apparently the ‘resize’ event only works with the window, or I didn’t do proper testing. I also don’t know if there is already a specific event for this, if so please guide me.

I also saw that I could use an “observer” to observe the image’s width/height attributes, I think it’s too complicated a solution, so I’m looking for a more lazy solution

Very new to programming, wondering how to change background colour on nav bar element when it is active? CSS HTML JAVASCRIPT

Tried solving this first using online resources. Couldn’t manage to figure it out. Just looking to make nav bar background colour change when I click on it and it is active once the new page loads.

A couple solutions that made the most sense to me but I couldn’t figure out how to implement.

I am very new to this and it is a bit of a passion project so any other advice on my code is always appreciated.

Cheers!

Javascript:

// Get the container element
var btnContainer = document.getElementById("myDIV");

// Get all buttons with class="btn" inside the container
var btns = btnContainer.getElementsByClassName("btn");

// Loop through the buttons and add the active class to the current/clicked button
for (var i = 0; i < btns.length; i++) {
  btns[i].addEventListener("click", function() {
    var current = document.getElementsByClassName("active");
    current[0].className = current[0].className.replace(" active", "");
    this.className += " active";
  });
}

jQuery:

    <script>
        $(document).ready(function () {
            $('ul.navbar-nav > li').click(function (e) {
                $('ul.navbar-nav > li').css('background-color', 'transparent');
                $(this).css('background-color', '#c0c0c0');
            });
        });
    </script>

Here is my code

HTML:

<!DOCTYPE html>
<html>
    
    <head>
        <script type="text/javascript" src="website.js"></script>
        <link rel="stylesheet" type="text/css" href="css.css" />
        <title> Why So Serious </title>
    </head>
    <body>
        <header>
            <h1><span> Why So Serious</span></h1>
        </header>
    </body>
    <nav class="navbar">
        <ul>
            <li><a href="goodnews.html">Goodnews</a></li>
            <li><a href="sport.html">Sport</a></li>
            <li><a href="style.html">Style</a></li>
            <li><a href="forum.html">Forum</a></li>
        </ul>
    </nav>

    


</html>

CSS:

* {
    margin: 0;
    padding: 0;
  }


h1 {text-align: center;
    font-size: 600% ;
    font-style: itaic;
    background: #33ACFF ;
    min-width: 100%;
    margin: 0%;
    padding: 0%;

}

/* top nav bar style and location */
.navbar ul {
    list-style-type: none;
    padding: 0%;
    margin: 0%;
    text-align: center;
    padding-top: 10px;
    padding-bottom: 10px;
    border-bottom: 3px solid black;
}

/* top nav bar options styling */
.navbar a {
    color: black;
    text-decoration: none;
    padding: 10px;
    font-family: sans-serif;
    text-transform: uppercase;
   
}

.navbar a:hover{
    background-color: black;
    color: white;

}

.navbar .active{
    background-color: black;
    color:white;
}
.navbar li{
    display: inline;
    
}

Prisma, search for two userId in a list

i am making a web app using NextJs, in which i’m currently making the chat rooms.
When a user want to start a conversation the website will check in the db is there is an existing room for these two users. If yes redirect, if no create it then redirect.

My issue here is with the prisma query, i want to select row of rooms where participants are for exemple: [user1 && user2].

Here my schema:

model User {
  userId    Int       @id @default(autoincrement())
  email     String
  username  String
  password  String
  regdate   DateTime  @default(now())
  messages  Message[]
  token     String
  rooms     Room[]

  friends   User[] @relation("friends")
  friendsRelation User[] @relation("friends")

  friendsPending   User[] @relation("friendStatus")
  friendRequests User[] @relation("friendStatus")
}

model Message {
  messageId Int       @id @default(autoincrement())
  content   String
  senddate  DateTime  @default(now())
  author    User?     @relation(fields: [authorId], references: [userId])
  authorId  Int?
  room     Room[]
}

model Room {
  roomId          Int       @id @default(autoincrement())
  isGroup         Boolean   @default(false)
  roomName        String    @default("")
  nameAuto        Boolean   @default(true)
  roomMessages    Message[]
  roomUsers       User[] **WANT TO GET USERS FROM HERE**
}

I tried this query but have issues:

        const room = await prisma.room.findMany({
            where: {
                isGroup: false, // ignore, it's just for excluding groupes
                roomUsers: {
                    userId: [userId, targetUser]
                }
            }
        });  

Hope that someone can help me, thanks in advance.