Parcourir la source

Fix showing incorrect stats

poeti8 il y a 6 ans
Parent
commit
2a53bf0921

+ 6 - 6
client/components/Stats/StatsCharts/Area.js

@@ -1,8 +1,8 @@
 import React from 'react';
 import PropTypes from 'prop-types';
-import subHours from 'date-fns/sub_hours';
-import subDays from 'date-fns/sub_days';
-import subMonths from 'date-fns/sub_months';
+import subHours from 'date-fns/subHours';
+import subDays from 'date-fns/subDays';
+import subMonths from 'date-fns/subMonths';
 import formatDate from 'date-fns/format';
 import {
   AreaChart,
@@ -20,13 +20,13 @@ const ChartArea = ({ data: rawData, period }) => {
   const getDate = index => {
     switch (period) {
       case 'allTime':
-        return formatDate(subMonths(now, rawData.length - index), 'MMM YY');
+        return formatDate(subMonths(now, rawData.length - index - 1), 'MMM yyy');
       case 'lastDay':
-        return formatDate(subHours(now, rawData.length - index), 'HH:00');
+        return formatDate(subHours(now, rawData.length - index - 1), 'HH:00');
       case 'lastMonth':
       case 'lastWeek':
       default:
-        return formatDate(subDays(now, rawData.length - index), 'MMM DD');
+        return formatDate(subDays(now, rawData.length - index - 1), 'MMM dd');
     }
   };
   const data = rawData.map((view, index) => ({

+ 2 - 2
client/components/Stats/StatsCharts/StatsCharts.js

@@ -45,13 +45,13 @@ const StatsCharts = ({ stats, period, updatedAt }) => {
   const periodText = period.includes('last')
     ? `the last ${period.replace('last', '').toLocaleLowerCase()}`
     : 'all time';
-  const hasView = stats.views.filter(view => view > 0);
+  const hasView = stats.views.some(view => view > 0);
   return (
     <ChartsWrapper>
       <Row>
         <Area data={stats.views} period={period} updatedAt={updatedAt} periodText={periodText} />
       </Row>
-      {hasView.length
+      {hasView
         ? [
             <Row key="second-row">
               <Pie data={stats.stats.referrer} updatedAt={updatedAt} title="Referrals" />

+ 1 - 1
client/components/Stats/StatsCharts/withTitle.js

@@ -49,7 +49,7 @@ const withTitle = ChartComponent => {
           {props.periodText ? ` tracked clicks in ${props.periodText}` : props.title}.
         </Title>
         {props.periodText && props.updatedAt && (
-          <SubTitle>Last update in {formatDate(props.updatedAt, 'dddd, hh:mm aa')}.</SubTitle>
+          <SubTitle>Last update in {formatDate(new Date(props.updatedAt), 'dddd, hh:mm aa')}.</SubTitle>
         )}
         <ChartComponent {...props} />
       </Wrapper>

+ 2 - 2
client/components/Table/TBody/TBody.js

@@ -2,7 +2,7 @@ import React from 'react';
 import PropTypes from 'prop-types';
 import { connect } from 'react-redux';
 import styled, { css } from 'styled-components';
-import distanceInWordsToNow from 'date-fns/distance_in_words_to_now';
+import distanceInWordsToNow from 'date-fns/formatDistanceToNow';
 import TBodyShortUrl from './TBodyShortUrl';
 import TBodyCount from './TBodyCount';
 
@@ -93,7 +93,7 @@ const TableBody = ({ copiedIndex, handleCopy, tableLoading, showModal, urls }) =
         <a href={url.target}>{url.target}</a>
       </Td>
       <Td flex="1" date>
-        {`${distanceInWordsToNow(url.created_at)} ago`}
+        {`${distanceInWordsToNow(new Date(url.created_at))} ago`}
       </Td>
       <Td flex="1" withFade>
         <TBodyShortUrl index={index} copiedIndex={copiedIndex} handleCopy={handleCopy} url={url} />

+ 0 - 1
client/components/Table/TableOptions.js

@@ -128,7 +128,6 @@ class TableOptions extends Component {
     return (e) => {
       const { active } = e.target.dataset;
       if (active === 'false') return null;
-      console.log({ page: this.props.url.page, num });
       return this.props.getUrlsList({ page: this.props.url.page + num });
     }
   }

+ 1 - 1
client/pages/settings.js

@@ -7,7 +7,7 @@ import Footer from '../components/Footer';
 import { authUser } from '../actions';
 import Settings from '../components/Settings';
 
-const SettingsPage = ({ auth, isAuthenticated }) => console.log({auth}) || (
+const SettingsPage = ({ auth, isAuthenticated }) => (
   <BodyWrapper>
     {isAuthenticated ? <Settings /> : <PageLoading />}
     <Footer />

+ 2 - 2
server/controllers/validateBodyController.ts

@@ -128,7 +128,7 @@ export const cooldownCheck = async (user: User) => {
       throw new Error("Too much malware requests. You are now banned.");
     }
     const hasCooldownNow = user.cooldowns.some(cooldown =>
-      isAfter(subHours(new Date(), 12), cooldown)
+      isAfter(subHours(new Date(), 12), new Date(cooldown))
     );
     if (hasCooldownNow) {
       throw new Error("Cooldown because of a malware URL. Wait 12h");
@@ -142,7 +142,7 @@ export const ipCooldownCheck: RequestHandler = async (req, res, next) => {
   const ip = await getIP(req.realIP);
   if (ip) {
     const timeToWait =
-      cooldownConfig - differenceInMinutes(new Date(), ip.created_at);
+      cooldownConfig - differenceInMinutes(new Date(), new Date(ip.created_at));
     return res.status(400).json({
       error:
         `Non-logged in users are limited. Wait ${timeToWait} ` +

+ 1 - 1
server/db/ip.ts

@@ -1,4 +1,4 @@
-import subMinutes from "date-fns/sub_minutes";
+import { subMinutes } from "date-fns";
 
 import knex from "../knex";
 

+ 12 - 5
server/db/link.ts

@@ -1,5 +1,5 @@
 import bcrypt from "bcryptjs";
-import { isAfter, subDays } from "date-fns";
+import { isAfter, subDays, set } from "date-fns";
 import knex from "../knex";
 import * as redis from "../redis";
 import {
@@ -340,7 +340,10 @@ export const getStats = async (link: Link, domain: Domain) => {
 
   for await (const visit of visitsStream as Visit[]) {
     STATS_PERIODS.forEach(([days, type]) => {
-      const isIncluded = isAfter(visit.created_at, subDays(nowUTC, days));
+      const isIncluded = isAfter(
+        new Date(visit.created_at),
+        subDays(nowUTC, days)
+      );
       if (isIncluded) {
         const diffFunction = getDifferenceFunction(type);
         const diff = diffFunction(now, visit.created_at);
@@ -392,7 +395,11 @@ export const getStats = async (link: Link, domain: Domain) => {
 
     const allTime = stats.allTime.stats;
     const diffFunction = getDifferenceFunction("allTime");
-    const diff = diffFunction(now, visit.created_at);
+    const diff = diffFunction(
+      set(new Date(), { date: 1 }),
+      set(new Date(visit.created_at), { date: 1 })
+    );
+    console.log(diff);
     const index = stats.allTime.views.length - diff - 1;
     const view = stats.allTime.views[index];
     stats.allTime.stats = {
@@ -448,8 +455,8 @@ export const getStats = async (link: Link, domain: Domain) => {
       views: stats.lastDay.views
     },
     lastMonth: {
-      stats: statsObjectToArray(stats.lastDay.stats),
-      views: stats.lastDay.views
+      stats: statsObjectToArray(stats.lastMonth.stats),
+      views: stats.lastMonth.views
     },
     lastWeek: {
       stats: statsObjectToArray(stats.lastWeek.stats),

+ 1 - 1
server/db/user.ts

@@ -1,7 +1,7 @@
 import bcrypt from "bcryptjs";
 import nanoid from "nanoid";
 import uuid from "uuid/v4";
-import addMinutes from "date-fns/add_minutes";
+import { addMinutes } from "date-fns";
 
 import knex from "../knex";
 import * as redis from "../redis";