Skip to content

Commit

Permalink
Ajout export produits et promotions vers Excel
Browse files Browse the repository at this point in the history
  • Loading branch information
corentin703 committed Nov 6, 2021
1 parent 0a9d8be commit 166de89
Show file tree
Hide file tree
Showing 7 changed files with 253 additions and 24 deletions.
71 changes: 71 additions & 0 deletions app/components/dashboard/articles/ExportArticles.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,71 @@
import { useQuery } from 'blitz'

import TableChartIcon from '@mui/icons-material/TableChart'
import { Button } from '@mui/material'
import xlsx from 'xlsx'
import getArticlesWithStats from '../../../entities/articles/queries/getArticlesWithStats'

export default function ExportArticles() {
const [{ articles }] = useQuery<any>(getArticlesWithStats, {})

const exportToExcel = () => {
const date = new Date(Date.now())

const workBook = xlsx.utils.book_new()

workBook.Props = {
Title: 'BDE ISIMA - Utilisateurs',
Subject: 'Liste des utilisateurs',
CreatedDate: date,
}

workBook.SheetNames.push('Articles')

console.log(articles)
console.log(articles[24].name)
console.log(articles[24].totalCount)

const workSheetData = [
[
'Nom',
'Prix',
'Prix cotisants',
'Visible',
'Ajouté le',
'Nombre vente dernière semaine',
'Nombre vente dernier mois',
'Nombre vente dernière année',
'Nombre vente total',
],
...articles.map((article) => [
article.name,
article.price,
article.member_price ?? article.price,
article.is_enabled ? 'Oui' : 'Non',
new Date(article.createdAt).toLocaleDateString('fr'),
article.weekCount ?? 0,
article.monthCount ?? 0,
article.yearCount ?? 0,
article.totalCount ?? 0,
]),
]

const workSheet = xlsx.utils.aoa_to_sheet(workSheetData)
workBook.Sheets['Articles'] = workSheet

workSheet['!autofilter'] = { ref: 'A1:I1' }

xlsx.writeFile(
workBook,
`bde_isima_articles-${date.getFullYear()}-${
date.getMonth() + 1
}-${date.getDate()}_${date.getHours()}-${date.getMinutes()}.xlsx`
)
}

return (
<Button endIcon={<TableChartIcon />} variant={'contained'} onClick={exportToExcel}>
Exporter vers Excel
</Button>
)
}
63 changes: 63 additions & 0 deletions app/components/dashboard/promotions/ExportPromotions.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,63 @@
import { useQuery } from 'blitz'

import TableChartIcon from '@mui/icons-material/TableChart'
import { Button } from '@mui/material'
import xlsx from 'xlsx'
import getPromotions from '../../../entities/promotions/queries/getPromotions'

export default function ExportPromotions() {
const [{ promotions }] = useQuery<any>(getPromotions, {
include: {
_count: {
select: {
User: true,
},
},
},
orderBy: {
year: 'asc',
},
})

const exportToExcel = () => {
const date = new Date(Date.now())

const workBook = xlsx.utils.book_new()

workBook.Props = {
Title: 'BDE ISIMA - Utilisateurs',
Subject: 'Liste des utilisateurs',
CreatedDate: date,
}

workBook.SheetNames.push('Promotions')

const workSheetData = [
['Année', 'ID Groupe Facebook', 'Liste de diffusion', "Nombre d'utilisateurs"],
...promotions.map((promotion) => [
promotion.year,
promotion.fb_group_id,
promotion.list_email,
promotion._count.User,
]),
]

const workSheet = xlsx.utils.aoa_to_sheet(workSheetData)
workBook.Sheets['Promotions'] = workSheet

workSheet['!autofilter'] = { ref: 'A1:D1' }

xlsx.writeFile(
workBook,
`bde_isima_promotions-${date.getFullYear()}-${
date.getMonth() + 1
}-${date.getDate()}_${date.getHours()}-${date.getMinutes()}.xlsx`
)
}

return (
<Button endIcon={<TableChartIcon />} variant={'contained'} onClick={exportToExcel}>
Exporter vers Excel
</Button>
)
}
16 changes: 12 additions & 4 deletions app/components/dashboard/users/ExportUsers.tsx
Original file line number Diff line number Diff line change
@@ -1,11 +1,12 @@
import { useQuery } from 'blitz'

import TableChartIcon from '@mui/icons-material/TableChart'
import getUsers from '../../../entities/users/queries/getUsers'
import { Button } from '@mui/material'
import xlsx from 'xlsx'

export default function ExportUsers() {
const [{ users }] = useQuery(getUsers, {
const [{ users }] = useQuery<any>(getUsers, {
include: {
promotion: {
select: {
Expand All @@ -22,12 +23,14 @@ export default function ExportUsers() {
})

const exportToExcel = () => {
const date = new Date(Date.now())

const workBook = xlsx.utils.book_new()

workBook.Props = {
Title: 'BDE ISIMA - Utilisateurs',
Subject: 'Liste des utilisateurs',
CreatedDate: new Date(Date.now()),
CreatedDate: date,
}

workBook.SheetNames.push('Utilisateurs')
Expand All @@ -50,11 +53,16 @@ export default function ExportUsers() {

workSheet['!autofilter'] = { ref: 'A1:G1' }

xlsx.writeFile(workBook, 'bde_isima_utilisateurs.xlsx')
xlsx.writeFile(
workBook,
`bde_isima_utilisateurs-${date.getFullYear()}-${
date.getMonth() + 1
}-${date.getDate()}_${date.getHours()}-${date.getMinutes()}.xlsx`
)
}

return (
<Button variant={'contained'} onClick={exportToExcel}>
<Button endIcon={<TableChartIcon />} variant={'contained'} onClick={exportToExcel}>
Exporter vers Excel
</Button>
)
Expand Down
75 changes: 75 additions & 0 deletions app/entities/articles/queries/getArticlesWithStats.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,75 @@
import { resolver } from 'blitz'

import db, { Prisma } from 'db'

type GetArticlesInput = Pick<
Prisma.ArticleFindManyArgs,
'include' | 'where' | 'orderBy' | 'skip' | 'take'
>

export default resolver.pipe(resolver.authorize(['*', 'bde']), async () => {
const todayDate = new Date(Date.now())
const lastWeekDate = new Date(
todayDate.getFullYear(),
todayDate.getMonth(),
todayDate.getDate() - 7
)
const lastMonthDate = new Date(
todayDate.getFullYear(),
todayDate.getMonth() - 1,
todayDate.getDate()
)
const lastYearDate = new Date(
todayDate.getFullYear() - 1,
todayDate.getMonth(),
todayDate.getDate()
)

const articles = await db.$queryRaw<any>`
SELECT
"Article"."id",
"Article"."name",
"Article"."price",
"Article"."member_price",
"Article"."image",
"Article"."is_enabled",
"Article"."createdAt",
"Article"."updatedAt",
week.count AS "weekCount",
month.count AS "monthCount",
year.count AS "yearCount",
total.count AS "totalCount"
FROM "Article"
LEFT JOIN (
SELECT "Transaction"."articleId", COUNT("Transaction"."id") AS count FROM "Transaction"
GROUP BY "Transaction"."articleId"
) total ON "Article"."id" = total."articleId"
LEFT JOIN (
SELECT "Transaction"."articleId", COUNT("Transaction"."id") AS count FROM "Transaction"
WHERE "Transaction"."createdAt" >= ${lastWeekDate}::date AND "Transaction"."createdAt" <= ${todayDate}::date
GROUP BY "Transaction"."articleId"
) week ON "Article".id = "week"."articleId"
LEFT JOIN (
SELECT "Transaction"."articleId", COUNT("Transaction"."id") AS count FROM "Transaction"
WHERE "Transaction"."createdAt" >= ${lastMonthDate}::date AND "Transaction"."createdAt" <= ${todayDate}::date
GROUP BY "Transaction"."articleId"
) month ON "Article".id = "month"."articleId"
LEFT JOIN (
SELECT "Transaction"."articleId", COUNT("Transaction"."id") FROM "Transaction"
WHERE "Transaction"."createdAt" >= ${lastYearDate}::date AND "Transaction"."createdAt" <= ${todayDate}::date
GROUP BY "Transaction"."articleId"
) year ON "Article".id = "year"."articleId"
ORDER BY "Article"."name"
`

const count = articles.length ?? 0
const hasMore = false
const nextPage = null

return {
articles,
nextPage,
hasMore,
count,
}
})
8 changes: 6 additions & 2 deletions app/entities/promotions/queries/getPromotions.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,12 +2,16 @@ import { resolver } from 'blitz'

import db, { Prisma } from 'db'

type GetPromotionsInput = Pick<Prisma.PromotionFindManyArgs, 'where' | 'orderBy' | 'skip' | 'take'>
type GetPromotionsInput = Pick<
Prisma.PromotionFindManyArgs,
'include' | 'where' | 'orderBy' | 'skip' | 'take'
>

export default resolver.pipe(
resolver.authorize(['*', 'bde']),
async ({ where, orderBy, skip = 0, take }: GetPromotionsInput) => {
async ({ include, where, orderBy, skip = 0, take }: GetPromotionsInput) => {
const promotions = await db.promotion.findMany({
include,
where,
orderBy,
take,
Expand Down
22 changes: 13 additions & 9 deletions app/pages/dashboard/articles.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -8,18 +8,22 @@ import upsertArticle from 'app/entities/articles/mutations/upsertArticle'
import getDashboardNav from 'app/components/nav/dashboard/getDashboardNav'
import { redirectAuthenticatedTo } from 'app/components/nav/dashboard/bde-config'
import deleteManyArticles from 'app/entities/articles/mutations/deleteManyArticles'
import ExportArticles from '../../components/dashboard/articles/ExportArticles'

const Articles: BlitzPage = () => {
return (
<Table
title="Marché"
columns={columns}
queryKey="articles"
getQuery={getArticles}
upsertQuery={upsertArticle}
deleteQuery={deleteManyArticles}
FormComponent={ArticleForm}
/>
<>
<Table
title="Marché"
columns={columns}
queryKey="articles"
getQuery={getArticles}
upsertQuery={upsertArticle}
deleteQuery={deleteManyArticles}
FormComponent={ArticleForm}
/>
<ExportArticles />
</>
)
}

Expand Down
22 changes: 13 additions & 9 deletions app/pages/dashboard/promotions.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -7,18 +7,22 @@ import PromotionForm from 'app/components/dashboard/promotions/PromotionForm'
import upsertPromotion from 'app/entities/promotions/mutations/upsertPromotion'
import { redirectAuthenticatedTo } from 'app/components/nav/dashboard/bde-config'
import deleteManyPromotions from 'app/entities/promotions/mutations/deleteManyPromotions'
import ExportPromotions from '../../components/dashboard/promotions/ExportPromotions'

const Promotions: BlitzPage = () => {
return (
<Table
title="Promotions"
columns={columns}
queryKey="promotions"
getQuery={getPromotions}
upsertQuery={upsertPromotion}
deleteQuery={deleteManyPromotions}
FormComponent={PromotionForm}
/>
<>
<Table
title="Promotions"
columns={columns}
queryKey="promotions"
getQuery={getPromotions}
upsertQuery={upsertPromotion}
deleteQuery={deleteManyPromotions}
FormComponent={PromotionForm}
/>
<ExportPromotions />
</>
)
}

Expand Down

0 comments on commit 166de89

Please sign in to comment.