Receive regular updates every week for an entire month using Javascript

How can I calculate the number of check-ins per week in a month using Javascript? I have been unable to find relevant code for this task.

Specifically, I am interested in determining the total count of user check-ins on a weekly basis. For example, if a user makes 1 or 4 check-ins during the week from 10/29/23 to 11/04/23 (defining a week as starting on Sunday and ending on Saturday).

In cases where a user exceeds a limit of 3 check-ins within a 7-day period, the system should prevent additional check-ins. However, there may be scenarios where check-ins across 'broken' weeks need to be managed. For instance, if Tom checks in on 10/30, 10/31, and 11/1, how can we ensure that all check-ins are accurately recorded?

The challenge emerges when the week boundary intersects with the change of months, causing some check-ins to fall out of the scope of the current week. How can this issue be addressed effectively?

S  M  T  W  R  F  S
         1  2  3  4
5  6  7  8  9  10 11
12 13 14 15 16 17 18
19 20 21 22 23 24 25
26 27 28 29 30 31 

When a user checks in on the first two days of the week, the system captures the data correctly. However, challenges arise when transitioning between months, affecting the accuracy of weekly check-in counts. What strategies can be employed to overcome this obstacle?

const checkInOnWeek = await this.checkInsRepository.findByPlayerIdOnWeek(
      player_id,
      check_in_date,
    );

    const week = [];
    const current = new Date();
    // Starting Sunday not Monday
    current.setDate(current.getDate() - current.getDay());
    for (let i = 0; i < 7; i++) {
      week.push(new Date(current));
      current.setDate(current.getDate() + 1);
    }

    const datascheckin = week.map(date => {
      const firstdayFormatted = format(date, 'dd/MM');

      return firstdayFormatted;
    });

    const dataFormatada = format(check_in_date, 'dd/MM');

    const a = datascheckin.some(data => {
      return data === dataFormatada;
    });

    if (checkInOnWeek.length > 3) {
      console.log(
        `Qtd de checkins semanal atingida,
        ${checkInOnWeek[0].check_in_date}, Id ${checkInOnWeek[1].player_id}`,
      );
      throw new AppError('Weekly scheduling limit reached!', 400);
    }


    const countCheckInDate = await this.checkInsRepository.countSpacesRemaining(
      check_in_date,
    );


     const checkIn = await this.checkInsRepository.create({
       player_id,
       check_in_date,
     });

     return checkIn;

Result obtained

Answer №1

One possible approach is to compare the number of days in the first and last day of the month to determine if the week includes days from both the previous and next month. It may be worth exploring alternative methods as well.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Is the npm mqtt module continuously running but not performing any tasks?

I'm relatively new to the world of JS, node.js, and npm. I am attempting to incorporate a mqtt broker into a project for one of my classes. To gain a better understanding of how it functions, I installed the mqtt module from npm. However, when I tried ...

Customize the appearance of the Material UI expansion panel when it is in its expanded

Is there a way to customize the height of an expanded expansion panel summary? Specifically, I am looking to remove the min-height property and set the summary panel's height to 40px instead of the default 64px. I have attempted to make this change in ...

Navigating between multiple Angular applications using Express

In my project, I am facing an issue with the file structure. I have a server folder and a client folder which includes two Angular apps: one for the website and one for the dashboard. If you want to check out the code, it's available at this link. A ...

Tips on Modifying JSON Objects with JavaScript

In the code I'm working with, there's a generated line that creates an animated sidebar using a div. The width of this sidebar is controlled by the 'v' parameter, currently set to 85. <div id="sidebar" class="inner-element uib_w_5 ...

I must add and display a tab for permissions

I am currently using the material UI tab for my project. My goal is to display the tab only when the permission is set to true. I have successfully achieved this functionality, but the issue arises when the permission is false. It results in an error that ...

Optimizing Midnight UTC+0 Setting in JavaScript Date Functions

I am using an MUI Datepicker that allows me to choose a day without specifying the time. For example, if I select 01.09.1970, in the console log it displays as Tue Sep 01 1970 00:00:00 GMT+0100 (Central European Standard Time). This indicates that even tho ...

What is the best way to determine the type of a key within an array of objects

Suppose I have the following code snippet: type PageInfo = { title: string key: string } const PAGES: PageInfo[] = [ { key: 'trip_itinerary', title: "Trip Itinerary", }, { key: 'trip_det ...

Troubleshooting form submission issues in Angular 4

I am encountering a few issues with my search form. It is supposed to function as a search tool with one input field and one button. However, something seems amiss. I am utilizing an API that returns values based on the string inputted. When an empty value ...

The HTTP GET request is failing to trigger

I'm currently working on building a basic messageboard using MongoDB, Angular, NODE.js and Express. Oddly enough, everything works fine the first time I call getMessages(). But when I try to call getMessages() after posting a message with postMessage ...

Failure occurs when attempting to send an object with an empty array using jQuery ajax

Looking to use jQuery Ajax PUT to send an object with an empty array `{value: {tags: []}}` to a Node.js express server, encountering the issue where `req.body.value` is undefined in the express `app.put()` handler. While suspecting jQuery as the culprit af ...

Merge the JSON data with the Node.js/Express.js response

Whenever I input somedomain.com/some_api_url?_var1=1 in a browser, the response that I receive is {"1":"descriptive string"}. In this JSON response, the index 1 can vary from 1 to n, and the "descriptive string" summarizes what the index represents. I am ...

Using JSON data in an ArrayBuffer with TypeScript

I am currently struggling with converting the received ArrayBuffer data from a server via Websocket into another format. Below is the WebSocket code snippet: let ws = new WebSocket('wss://api.example.com/websocket'); ws.binaryType = 'arrayb ...

Using ExpressJS route parameters as variables within the main application

In my application, I have configured two routes: app.get('/', routes.index); app.get('/:name', routes.index); I want to set it up so that if no parameter is specified, for example, when visiting appurl.com (localhost:3000), a default ...

creating a nested JavaScript object within another object

I need to create an object using the angular.forEach() function and then push another object while initializing all values to false. However, the current approach is causing errors. How can I achieve this correctly? Using "item.id" and "index.id" does not ...

Steps to duplicate the package.json to the dist or build directory while executing the TypeScript compiler (tsc)

I am facing an issue with my TypeScript React component and the package.json file when transpiling it to es5 using tsc. The package.json file does not get copied automatically to the dist folder, as shown in the provided screenshot. I had to manually copy ...

What could be causing the issue where only the latest data is being shown

When I use ajax to retrieve data from my database, the console.log displays all the results correctly, but in my HTML, only the last result is shown. What could be causing this issue? Any help would be appreciated! Thanks! Please keep your response simple ...

The Material-ui DatePicker seems to be malfunctioning and as a result, the entire form is not

Struggling to get my DateTimePicker component (could be DatePicker) working after following installation instructions from various sources. I've spent a day and a half attempting to make it functional without success. If you can help me create a separ ...

SaxonJS - Stop Server from Reloading Upon Stylesheet Alterations

I have been using Saxon-JS to convert an XML file into an XSL-FO format. Following the instructions in the documentation, I utilize the xslt3 command to compile an XSL file into a sef file as shown below: "compile": "xslt3 -xsl:./src/styles/ ...

Node.js encountered an abrupt conclusion in the JSON input that was not anticipated

Upon receiving Json data as post data in my node.js server, I encountered an issue with parsing the string. Here is a snippet of my node.js server code: res.header("Access-Control-Allow-Origin", "*"); req.on('data',function(data) { var ...

Is requesting transclusion in an Angular directive necessary?

An issue has cropped up below and I'm struggling to figure out the reason behind it. Any suggestions? html, <button ng-click="loadForm()">Load Directive Form</button> <div data-my-form></div> angular, app.directive(&apos ...