aboutsummaryrefslogtreecommitdiff
path: root/jb-ui/src/pages/Preview.tsx
blob: bb7520acb5474fc1c12240862db79b44033d90a9 (plain)
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
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
import {
  Leaderboard,
  LeaderboardApi,
  LeaderboardCode,
  LeaderboardFrequency,
  LeaderboardRow,
} from "@/api_fsb";
import { useAppSelector } from "@/hooks";
import { bpid, formatCentsToUSD, truncate } from "@/lib/utils";
import { activeSurveys, activeUsers, maxPayout } from "@/models/grlStatsSlice";
import { clsx } from "clsx";
import moment from "moment";
import { FormEvent, useEffect, useState } from "react";

const showSmartRank = (
  item: LeaderboardRow,
  index: number,
  items: LeaderboardRow[] | undefined,
): boolean => {
  /**
   * Smart rank calculation - this determines if we should show the rank
   *  value. It's confusing to show people that multiple individuals ranked
   *  in the same place, so this will only display the next ranked value, eg:
   *
   *  - 1st
   *  - ___
   *  - 3rd
   *  - ___
   *  - ___
   *  - 6th
   *
   * @returns number
   */
  if (!items) return false;

  const thisRank = item.rank;
  if (index >= 1) {
    const prevRank = items[index - 1].rank;
    if (thisRank === prevRank) {
      return false;
    }
  }
  return true;
};

interface FrequencyButtonsProps {
  selected: LeaderboardFrequency;
  onChange: (frequency: LeaderboardFrequency) => void;
}

const frequency_map = [
  { label: "Day", value: LeaderboardFrequency.Daily },
  { label: "Week", value: LeaderboardFrequency.Weekly },
  { label: "Month", value: LeaderboardFrequency.Monthly },
];

const ThreeButtonToggle = ({ selected, onChange }: FrequencyButtonsProps) => {
  return (
    <div className="inline-flex rounded shadow-sm" role="group">
      {frequency_map.map((button, idx) => (
        <button
          type="button"
          key={button.value}
          onClick={() => onChange(button.value)}
          className={clsx(
            "px-2 py-1 text-[10px] font-medium",
            "border-t border-b border-gray-200",
            "hover:cursor-pointer hover:bg-zinc-200 hover:text-zinc-950",
            idx === 0 && "rounded-l",
            idx === frequency_map.length - 1 && "rounded-r",
            selected === button.value
              ? "text-zinc-50 bg-zinc-400"
              : "text-zinc-950 bg-zinc-50",
          )}
        >
          {button.label}
        </button>
      ))}
    </div>
  );
};

// Leaderboards Component
export const Leaderboards = () => {
  /**
   * Leaderboards do not do any caching, or better state management. This is okay because
   * the API is handled to take it. However, it can easily handled better client
   * side rather than making the
   * **/

  const [frequency, setFrequency] = useState<LeaderboardFrequency>(
    LeaderboardFrequency.Daily,
  );

  const [payouts, setPayouts] = useState<Leaderboard | null>(null);
  const [completes, setCompletes] = useState<Leaderboard | null>(null);

  const bpuid = undefined;

  useEffect(() => {
    new LeaderboardApi()
      .timespanLeaderboardProductIdLeaderboardTimespanBoardCodeGet(
        bpid,
        LeaderboardCode.CompleteCount,
        frequency,
        "us",
        bpuid,
        undefined, // within_time
        10,
      )
      .then((res) => {
        setCompletes(res.data.leaderboard as Leaderboard);
      });

    new LeaderboardApi()
      .timespanLeaderboardProductIdLeaderboardTimespanBoardCodeGet(
        bpid,
        LeaderboardCode.SumUserPayout,
        frequency,
        "us",
        bpuid,
        undefined,
        10,
      )
      .then((res) => {
        setPayouts(res.data.leaderboard as Leaderboard);
      });
  }, [frequency]);

  let dateRange = " - ";
  if (completes) {
    const start = moment(completes?.start_timestamp * 1000).format(
      "MMM Do, ha",
    );
    const end = moment(completes?.end_timestamp * 1000).format(
      "MMM Do, h:mm:ssa",
    );
    //dateRange = `${start} – ${end} (${completes?.timezone_name})`;
    dateRange = `${start} – ${end}`;
  }

  const freq_label = frequency_map
    .find((f) => f.value === frequency)
    ?.label.toLocaleLowerCase();

  return (
    <div className="my-2 mx-4 py-0">
      <div className="w-full flex items-center justify-between my-1">
        {/* Left spacer (hidden on small screens) */}
        <div className="hidden md:block md:w-1/3"></div>

        {/* Centered text */}
        <h3 className="text-center flex-1 md:1/3">Leaderboards</h3>

        {/* Right-aligned button group */}
        <div className="flex md:w-1/3 justify-end">
          <ThreeButtonToggle selected={frequency} onChange={setFrequency} />
        </div>
      </div>

      <div className="grid grid-cols-1 mb-2 text-zinc-700">
        <p className="text-center text-[10px] font-thin">{dateRange}</p>
      </div>

      <div
        className="grid grid-cols-1 gap-4 px-12 md:px-0
            md:grid-cols-2"
      >
        <table className="border-collapse text-emerald-950 text-[8px] md:text-sm">
          <caption className="caption-top text-xs font-semibold">
            Most earned in the past {freq_label}.
          </caption>
          <thead>
            <tr
              className="
                            font-mono font-semibold text-center
                            border border-zinc-150"
            >
              <th>Rank</th>
              <th>Bonus</th>
              <th>User</th>
            </tr>
          </thead>
          <tbody className="font-mono">
            {payouts?.rows?.map((dataItem: LeaderboardRow) => (
              <tr
                key={dataItem.bpuid}
                className="
                            text-center 
                            border border-zinc-100"
              >
                <td className="font-medium">{dataItem.rank}</td>
                <td className="font-semibold">
                  {formatCentsToUSD(dataItem.value)}
                </td>
                <td className="font-light">
                  {truncate(dataItem.bpuid, 6, "*****").toUpperCase()}
                </td>
              </tr>
            ))}
          </tbody>
        </table>

        <table
          className="border-collapse border border-gray-400
                text-emerald-950 text-[8px] md:text-sm"
        >
          <caption className="caption-top text-xs font-semibold">
            Top completes in the past {freq_label}.
          </caption>
          <thead>
            <tr
              className="
                            font-mono font-semibold text-center
                            border border-zinc-150 rounded"
            >
              <th>Rank</th>
              <th>Completes</th>
              <th>User</th>
            </tr>
          </thead>
          <tbody className="font-mono">
            {completes?.rows?.map((dataItem: LeaderboardRow, index: number) => (
              <tr
                key={dataItem.bpuid}
                className="
                            text-center
                            border border-zinc-100"
              >
                <td className="font-medium">
                  {dataItem.rank ??
                    showSmartRank(dataItem, index, completes?.rows)}
                </td>
                <td className="font-semibold">{dataItem.value}</td>
                <td className="font-light">
                  {truncate(dataItem.bpuid, 6, "*****").toUpperCase()}
                </td>
              </tr>
            ))}
          </tbody>
        </table>
      </div>
    </div>
  );
};

type RequestState = "idle" | "working" | "failed";

interface LoginFormProps {
  onSubmitSuccess: () => void;
}

const LoginForm = function ({ onSubmitSuccess }: LoginFormProps) {
  const [email, setEmail] = useState("");
  const [state, setState] = useState<RequestState>("idle");

  // const dispatch = useAppDispatch();
  const submit = async (event: FormEvent<HTMLFormElement>) => {
    event.preventDefault();
    setState("working");

    try {
      const response = await fetch("/auth/magic-link/request/", {
        method: "POST",
        credentials: "include",
        headers: { "Content-Type": "application/json" },
        body: JSON.stringify({
          email: email,
        }),
      });

      if (!response.ok) throw new Error("Account-link request failed");
      const body = (await response.json()) as { magic_link?: string };
      console.log(body.magic_link ?? null);
      onSubmitSuccess();
    } catch {
      setState("failed");
    }
  };

  return (
    <>
      <form className="w-full" onSubmit={submit}>
        <div className="flex items-center border-b-4  border-blue-700 py-2">
          <input
            className="appearance-none bg-transparent border-none w-full text-gray-700 mr-3 py-1 px-2 leading-tight focus:outline-none font-semibold"
            type="email"
            autoComplete="email"
            required
            value={email}
            onChange={(event) => setEmail(event.target.value)}
            placeholder="hello@jamesbillings67.com"
            aria-label="Email address"
          />

          <button
            className="flex-shrink-0 bg-blue-700 hover:bg-blue-800 text-white py-1 px-2 rounded cursor-pointer font-semibold"
            type="submit"
            disabled={state === "working"}
          >
            {state === "working" ? "Sending…" : "Login / Signup"}
          </button>
        </div>
      </form>

      {state === "failed" && <p>Unable to send the link. Please try again.</p>}
    </>
  );
};

const LoginSent = function () {
  return (
    <div className="my-1">
      <h2
        className="
                    bg-emerald-400 rounded py-2
                    text-white text-l font-semibold text-center"
      >
        Please check your email.
      </h2>
      <p className="text-slate-800 text-xs font-semibold text-center my-1 py-2">
        If you don't recieve anything, please check your spam folder, or try
        again shortly.
      </p>
    </div>
  );
};

const Login = () => {
  const [submitted, setSubmitted] = useState(false);

  return (
    <>
      {submitted ? (
        <LoginSent />
      ) : (
        <LoginForm onSubmitSuccess={() => setSubmitted(true)} />
      )}
    </>
  );
};

// Preview Component
const Preview = () => {
  /**
   *
   * @returns {JSX.Element}
   */

  const users = useAppSelector((state) => activeUsers(state));
  const users_f: string = users?.toLocaleString() ?? " – ";

  const surveys = useAppSelector((state) => activeSurveys(state));
  const surveys_f: string = surveys?.toLocaleString() ?? " – ";

  const survey_max_cpi = useAppSelector((state) => maxPayout(state));
  const formatter = new Intl.NumberFormat("en-US", {
    style: "currency",
    currency: "USD",
  });
  const survey_max_cpi_f: string = formatter.format(
    (survey_max_cpi ?? 0) / 100,
  );

  return (
    <>
      <Login />

      <div className="max-h-[calc(100vh-10rem)] overflow-y-auto">
        <div className="bg-zinc-100 rounded py-2 m-0">
          <p className="text-center text-sm italic text-zinc-600">
            {users_f} people are actively attempting {surveys_f} available
            surveys right now.
          </p>
        </div>

        <Leaderboards />

        <div className="bg-zinc-100 rounded py-2 px-6 m-0 text-xs text-center">
          <p className="py-1">
            Get paid to take surveys. Our algorithm attempts to pair you with
            the highest paying survey available at the moment (right now, the
            highest paying survey is {survey_max_cpi_f}) that you are eligible
            for. Try as many as you can, our system will self regulate you: we
            want to ensure you have a high chance of being paired with a survey
            based on what surveys are available, as their availability
            constantly changes.
          </p>
        </div>
      </div>
    </>
  );
};
export default Preview;