Skip to content

Commit

Permalink
Merge branch 'main' into ji/gh-action-build
Browse files Browse the repository at this point in the history
  • Loading branch information
jonathan-irvin committed Sep 9, 2024
2 parents 05d7b75 + d55ba30 commit 4244fd1
Show file tree
Hide file tree
Showing 14 changed files with 513 additions and 374 deletions.
36 changes: 36 additions & 0 deletions .github/workflows/codeql.yml
Original file line number Diff line number Diff line change
@@ -0,0 +1,36 @@
---
name: "Code Quality Analysis"

on:
push:
pull_request:

jobs:
analyze:
name: Analyze (${{ matrix.language }})

runs-on: 'ubuntu-latest'
permissions:
security-events: write

strategy:
fail-fast: false
matrix:
include:
- language: javascript-typescript
build-mode: none

steps:
- name: Checkout repository
uses: actions/checkout@v4

- name: Initialize CodeQL
uses: github/codeql-action/init@v3
with:
languages: ${{ matrix.language }}
build-mode: ${{ matrix.build-mode }}

- name: Perform CodeQL Analysis
uses: github/codeql-action/analyze@v3
with:
category: "/language:${{matrix.language}}"
47 changes: 47 additions & 0 deletions .github/workflows/eslint.yaml
Original file line number Diff line number Diff line change
@@ -0,0 +1,47 @@
---
name: ESLint

on:
push:
pull_request:

jobs:
eslint:
name: Run eslint scanning
runs-on: ubuntu-latest
permissions:
contents: read
security-events: write
actions: read # only required for a private repository by github/codeql-action/upload-sarif to get the Action run status
strategy:
matrix:
service: ["backend", "frontend"]
steps:
- name: Checkout code
uses: actions/checkout@v4

- name: Setup node
uses: actions/setup-node@v4
with:
node-version: '20'
cache: 'npm'
cache-dependency-path: |
**/package-lock.json
- name: Install ESLint
run: |
npm install eslint
npm install @microsoft/eslint-formatter-sarif@2.1.7
- name: Run ESLint
run: npx eslint apps/${{ matrix.service }}/
--config apps/${{ matrix.service }}/.eslintrc.json
--format @microsoft/eslint-formatter-sarif
--output-file apps/${{ matrix.service }}/eslint-results.sarif
continue-on-error: true

- name: Upload analysis results to GitHub
uses: github/codeql-action/upload-sarif@v3
with:
sarif_file: apps/${{ matrix.service }}/eslint-results.sarif
wait-for-processing: true
15 changes: 7 additions & 8 deletions apps/backend/src/api/routes/posts.controller.ts
Original file line number Diff line number Diff line change
Expand Up @@ -48,19 +48,18 @@ export class PostsController {
@GetOrgFromRequest() org: Organization,
@Query() query: GetPostsDto
) {
const [posts, comments] = await Promise.all([
const [posts] = await Promise.all([
this._postsService.getPosts(org.id, query),
this._commentsService.getAllCommentsByWeekYear(
org.id,
query.year,
query.week,
query.isIsoWeek === 'true'
),
// this._commentsService.getAllCommentsByWeekYear(
// org.id,
// query.year,
// query.week
// ),
]);

return {
posts,
comments,
// comments,
};
}

Expand Down
2 changes: 1 addition & 1 deletion apps/frontend/src/app/colors.scss
Original file line number Diff line number Diff line change
Expand Up @@ -34,7 +34,7 @@
--color-custom20: #121b2c;
--color-custom21: #506490;
--color-custom22: #b91c1c;
--color-custom23: #06080d;
--color-custom23: #000000;
--color-custom24: #eaff00;
--color-custom25: #2e3336;
--color-custom26: #1d9bf0;
Expand Down
13 changes: 5 additions & 8 deletions apps/frontend/src/components/launches/add.edit.model.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -12,7 +12,6 @@ import React, {
import dayjs from 'dayjs';
import { Integrations } from '@gitroom/frontend/components/launches/calendar.context';
import clsx from 'clsx';
import { commands } from '@uiw/react-md-editor';
import { usePreventWindowUnload } from '@gitroom/react/helpers/use.prevent.window.unload';
import { deleteDialog } from '@gitroom/react/helpers/delete.dialog';
import { useModals } from '@mantine/modals';
Expand All @@ -27,16 +26,14 @@ import {
import { useFetch } from '@gitroom/helpers/utils/custom.fetch';
import { useMoveToIntegration } from '@gitroom/frontend/components/launches/helpers/use.move.to.integration';
import { useExistingData } from '@gitroom/frontend/components/launches/helpers/use.existing.data';
import { newImage } from '@gitroom/frontend/components/launches/helpers/new.image.component';
import { MultiMediaComponent } from '@gitroom/frontend/components/media/media.component';
import { useExpend } from '@gitroom/frontend/components/launches/helpers/use.expend';
import { TopTitle } from '@gitroom/frontend/components/launches/helpers/top.title.component';
import { PickPlatforms } from '@gitroom/frontend/components/launches/helpers/pick.platform.component';
import { ProvidersOptions } from '@gitroom/frontend/components/launches/providers.options';
import { v4 as uuidv4 } from 'uuid';
import useSWR, { useSWRConfig } from 'swr';
import useSWR from 'swr';
import { useToaster } from '@gitroom/react/toaster/toaster';
import { postSelector } from '@gitroom/frontend/components/post-url-selector/post.url.selector';
import { UpDownArrow } from '@gitroom/frontend/components/launches/up.down.arrow';
import { DatePicker } from '@gitroom/frontend/components/launches/helpers/date.picker';
import { arrayMoveImmutable } from 'array-move';
Expand All @@ -56,10 +53,10 @@ export const AddEditModal: FC<{
date: dayjs.Dayjs;
integrations: Integrations[];
reopenModal: () => void;
mutate: () => void;
}> = (props) => {
const { date, integrations, reopenModal } = props;
const { date, integrations, reopenModal, mutate } = props;
const [dateState, setDateState] = useState(date);
const { mutate } = useSWRConfig();

// hook to open a new modal
const modal = useModals();
Expand Down Expand Up @@ -246,7 +243,7 @@ export const AddEditModal: FC<{
await fetch(`/posts/${existingData.group}`, {
method: 'DELETE',
});
mutate('/posts');
mutate();
modal.closeAll();
return;
}
Expand Down Expand Up @@ -324,7 +321,7 @@ export const AddEditModal: FC<{

existingData.group = uuidv4();

mutate('/posts');
mutate();
toaster.show(
!existingData.integration
? 'Added successfully'
Expand Down
145 changes: 82 additions & 63 deletions apps/frontend/src/components/launches/calendar.context.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -17,16 +17,33 @@ import { useFetch } from '@gitroom/helpers/utils/custom.fetch';
import { Post, Integration } from '@prisma/client';
import { useRouter, useSearchParams } from 'next/navigation';
import { isGeneral } from '@gitroom/react/helpers/is.general';
import isoWeek from 'dayjs/plugin/isoWeek';
import weekOfYear from 'dayjs/plugin/weekOfYear';

dayjs.extend(isoWeek);
dayjs.extend(weekOfYear);

const CalendarContext = createContext({
currentWeek: dayjs().week(),
currentYear: dayjs().year(),
currentMonth: dayjs().month(),
comments: [] as Array<{ date: string; total: number }>,
integrations: [] as Integrations[],
trendings: [] as string[],
posts: [] as Array<Post & { integration: Integration }>,
setFilters: (filters: { currentWeek: number; currentYear: number }) => {},
changeDate: (id: string, date: dayjs.Dayjs) => {},
reloadCalendarView: () => {/** empty **/},
display: 'week',
setFilters: (filters: {
currentWeek: number;
currentYear: number;
currentMonth: number;
display: 'week' | 'month';
}) => {
/** empty **/
},
changeDate: (id: string, date: dayjs.Dayjs) => {
/** empty **/
},
});

export interface Integrations {
Expand All @@ -40,28 +57,21 @@ export interface Integrations {
}

function getWeekNumber(date: Date) {
// Copy date so don't modify original
const targetDate = new Date(Date.UTC(date.getFullYear(), date.getMonth(), date.getDate()));
// Set to nearest Thursday: current date + 4 - current day number
// Make Sunday's day number 7
targetDate.setUTCDate(targetDate.getUTCDate() + 4 - (targetDate.getUTCDay() || 7));
// Get first day of year
const yearStart = new Date(Date.UTC(targetDate.getUTCFullYear(), 0, 1));
// Calculate full weeks to nearest Thursday
return Math.ceil((((targetDate.getTime() - yearStart.getTime()) / 86400000) + 1) / 7);
}

function isISOWeek(date: Date, weekNumber: number): boolean {
// Copy date so don't modify original
const targetDate = new Date(Date.UTC(date.getFullYear(), date.getMonth(), date.getDate()));
// Set to nearest Thursday: current date + 4 - current day number
// Make Sunday's day number 7
targetDate.setUTCDate(targetDate.getUTCDate() + 4 - (targetDate.getUTCDay() || 7));
// Get first day of year
const yearStart = new Date(Date.UTC(targetDate.getUTCFullYear(), 0, 1));
// Calculate full weeks to nearest Thursday
const isoWeekNo = Math.ceil((((targetDate.getTime() - yearStart.getTime()) / 86400000) + 1) / 7);
return isoWeekNo === weekNumber;
// Copy date so don't modify original
const targetDate = new Date(
Date.UTC(date.getFullYear(), date.getMonth(), date.getDate())
);
// Set to nearest Thursday: current date + 4 - current day number
// Make Sunday's day number 7
targetDate.setUTCDate(
targetDate.getUTCDate() + 4 - (targetDate.getUTCDay() || 7)
);
// Get first day of year
const yearStart = new Date(Date.UTC(targetDate.getUTCFullYear(), 0, 1));
// Calculate full weeks to nearest Thursday
return Math.ceil(
((targetDate.getTime() - yearStart.getTime()) / 86400000 + 1) / 7
);
}

export const CalendarWeekProvider: FC<{
Expand All @@ -70,64 +80,72 @@ export const CalendarWeekProvider: FC<{
}> = ({ children, integrations }) => {
const fetch = useFetch();
const [internalData, setInternalData] = useState([] as any[]);
const [trendings, setTrendings] = useState<string[]>([]);
const { mutate } = useSWRConfig();
const [trendings] = useState<string[]>([]);
const searchParams = useSearchParams();
const router = useRouter();

useEffect(() => {
(async () => {
if (isGeneral()) {
return [];
}
setTrendings(await (await fetch('/posts/predict-trending')).json());
})();
}, []);

const display = searchParams.get('month') ? 'month' : 'week';
const [filters, setFilters] = useState({
currentWeek: +(searchParams.get('week') || getWeekNumber(new Date())),
currentWeek:
display === 'week'
? +(searchParams.get('week') || getWeekNumber(new Date()))
: 0,
currentMonth:
display === 'week' ? 0 : +(searchParams.get('month') || dayjs().month()),
currentYear: +(searchParams.get('year') || dayjs().year()),
display,
});

const isIsoWeek = useMemo(() => {
return isISOWeek(new Date(), filters.currentWeek);
}, [filters]);

const setFiltersWrapper = useCallback(
(filters: { currentWeek: number; currentYear: number }) => {
setFilters(filters);
router.replace(
`/launches?week=${filters.currentWeek}&year=${filters.currentYear}`
);
setTimeout(() => {
mutate('/posts');
});
},
[filters]
);

const params = useMemo(() => {
return new URLSearchParams({
week: filters.currentWeek.toString(),
year: filters.currentYear.toString(),
isIsoWeek: isIsoWeek.toString(),
}).toString();
return new URLSearchParams(
filters.currentWeek
? {
week: filters.currentWeek.toString(),
year: filters.currentYear.toString(),
}
: {
year: filters.currentYear.toString(),
month: (filters.currentMonth + 1).toString(),
}
).toString();
}, [filters]);

const loadData = useCallback(
async (url: string) => {
const data = (await fetch(`${url}?${params}`)).json();
async () => {
const data = (await fetch(`/posts?${params}`)).json();
return data;
},
[filters]
[filters, params]
);

const swr = useSWR(`/posts`, loadData, {
const swr = useSWR(`/posts-${params}`, loadData, {
refreshInterval: 3600000,
refreshWhenOffline: false,
refreshWhenHidden: false,
revalidateOnFocus: false,
});

const setFiltersWrapper = useCallback(
(filters: {
currentWeek: number;
currentYear: number;
currentMonth: number;
display: 'week' | 'month';
}) => {
setFilters(filters);
setInternalData([]);
window.history.replaceState(
null,
'',
`/launches?${
filters.currentWeek
? `week=${filters.currentWeek}`
: `month=${filters.currentMonth}`
}&year=${filters.currentYear}`
);
},
[filters, swr.mutate]
);

const { isLoading } = swr;
const { posts, comments } = swr?.data || { posts: [], comments: [] };

Expand Down Expand Up @@ -158,6 +176,7 @@ export const CalendarWeekProvider: FC<{
<CalendarContext.Provider
value={{
trendings,
reloadCalendarView: swr.mutate,
...filters,
posts: isLoading ? [] : internalData,
integrations,
Expand Down
Loading

0 comments on commit 4244fd1

Please sign in to comment.