Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Export schedule to XLSX!! #124

Merged
merged 4 commits into from
Jun 3, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Binary file modified bun.lockb
Binary file not shown.
1 change: 1 addition & 0 deletions package.json
Original file line number Diff line number Diff line change
Expand Up @@ -50,6 +50,7 @@
"uuid": "^9.0.1",
"wouter": "^2.12.1",
"xlsx": "https://cdn.sheetjs.com/xlsx-0.20.2/xlsx-0.20.2.tgz",
"xlsx-js-style": "^1.2.0",
"yup": "^1.3.2"
},
"devDependencies": {
Expand Down
98 changes: 96 additions & 2 deletions src/events/page/schedule/EventSchedule.tsx
Original file line number Diff line number Diff line change
@@ -1,12 +1,12 @@
import { Box, Button, Card, Link, Typography } from '@mui/material'
import { Box, Button, Card, Dialog, Link, Typography } from '@mui/material'
import * as React from 'react'
import { useRef, useState } from 'react'
import { Event, Session } from '../../../types'
import { useSessions } from '../../../services/hooks/useSessions'
import { FirestoreQueryLoaderAndErrorDisplay } from '../../../components/FirestoreQueryLoaderAndErrorDisplay'
import { NoDatesSessionsPicker } from './NoDatesSessionsPicker'
import './eventschedule.css'
import { diffDays } from '../../../utils/dates/diffDays'
import { diffDays, getIndividualDays } from '../../../utils/dates/diffDays'
import { DateTime } from 'luxon'
import { EventSourceInput } from '@fullcalendar/core'
import { onFullCalendarEventChange } from './eventScheduleFunctions'
Expand All @@ -18,6 +18,9 @@ import { getSessionBackgroundColor } from './components/getSessionBackgroundColo
import { hexOpacity } from '../../../utils/colors/hexOpacity'
import { hexDarken } from '../../../utils/colors/hexDarken'
import { TemplateCardContent } from './components/TemplateCardContent'
import { downloadOrCopyFullCalendarToExcel } from './components/xlsx/getFullCalendarToExcel'
import { Resource } from '@fullcalendar/resource/internal'
import { useNotification } from '../../../hooks/notificationHook'

export type EventScheduleProps = {
event: Event
Expand All @@ -30,6 +33,8 @@ export const EventSchedule = ({ event }: EventScheduleProps) => {
const sessions = useSessions(event)
const sessionsTemplate = useSessionTemplate(event)
const [daysToDisplay, setDaysToDisplay] = useState<number>(1)
const [exportDialogOpen, setExportDialogOpen] = useState(false)
const { createNotification } = useNotification()

if (numberOfDays <= 0 || !event.dates.start || !event.dates.end) {
return (
Expand Down Expand Up @@ -64,6 +69,19 @@ export const EventSchedule = ({ event }: EventScheduleProps) => {
const sessionsTemplateArray = sessionsTemplate.data || []
const startTime = DateTime.fromJSDate(event.dates.start).toFormat('HH:mm')

if (!sessionsWithDates.length) {
return (
<Card sx={{ paddingX: 2 }}>
<Typography fontWeight="600" mt={2}>
The event does not have any session with dates.
</Typography>
<Button component={Link} href="/sessions">
Add a session here
</Button>
</Card>
)
}

const customButtons = {
allDays: {
text: 'Display all days',
Expand Down Expand Up @@ -94,6 +112,34 @@ export const EventSchedule = ({ event }: EventScheduleProps) => {
setLocation(`/schedule/template`)
},
},
export: {
text: 'Export',
click: () => {
setExportDialogOpen(true)
},
},
}

const getExportParameters = (): [Event, EventSourceInput, string, Partial<Resource>[]] => {
return [
event,
sessionsWithDates.map((s: Session) => ({
title: s.title,
id: s.id,
start: s.dates?.start?.toISO(),
end: s.dates?.end?.toISO(),
speakers: (s.speakersData || []).map((speaker) => speaker.name).join(', '),
resourceId: s.trackId,
extendedProps: s,
backgroundColor: getSessionBackgroundColor(s),
})) as EventSourceInput,
'00:05',
event.tracks.map((t, index) => ({
id: t.id,
title: t.name,
order: index,
})),
]
}

return (
Expand Down Expand Up @@ -196,6 +242,54 @@ export const EventSchedule = ({ event }: EventScheduleProps) => {
/>
</Box>
)}

<Dialog open={exportDialogOpen} onClose={() => setExportDialogOpen(false)}>
<Box sx={{ padding: 2 }}>
<Typography variant="h6">Export</Typography>
<Button
variant={'contained'}
sx={{ mt: 1 }}
onClick={() => {
// @ts-ignore
downloadOrCopyFullCalendarToExcel(...getExportParameters(), false)
}}>
Download Excel/XLSX
</Button>

<br />

{Array.from(Array(numberOfDays).keys()).map((day) => {
return (
<Button
key={day}
variant="outlined"
sx={{ mt: 1, mr: 1 }}
onClick={() => {
const dayOfTheMonth = getIndividualDays(event.dates.start, event.dates.end)[day]
downloadOrCopyFullCalendarToExcel(
// @ts-ignore
...getExportParameters(),
true,
dayOfTheMonth.start.toJSDate().getDay()
)
createNotification('Table copied to clipboard')
}}>
Copy table for day {day + 1}
</Button>
)
})}
<br />

<Button
sx={{ mt: 4 }}
variant={'contained'}
onClick={() => {
setExportDialogOpen(false)
}}>
Close
</Button>
</Box>
</Dialog>
</Box>
</>
)
Expand Down
6 changes: 4 additions & 2 deletions src/events/page/schedule/components/FullCalendarBase.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -20,6 +20,8 @@ type FullCalendarBaseProps = {
eventClassNames?: string
}

export const FullCalendarSlotLabelInterval = '00:15'

export const FullCalendarBase = ({
forwardRef,
event,
Expand All @@ -46,7 +48,7 @@ export const FullCalendarBase = ({
nowIndicator
headerToolbar={{
right: 'prev,next',
left: 'allDays,changeTemplate',
left: 'allDays,changeTemplate,export',
center: 'title',
}}
customButtons={customButtons}
Expand All @@ -69,7 +71,7 @@ export const FullCalendarBase = ({
}}
locale="fr"
slotDuration="00:05:00"
slotLabelInterval="00:15"
slotLabelInterval={FullCalendarSlotLabelInterval}
height="auto"
resourceOrder="order"
resources={event.tracks.map((t, index) => ({
Expand Down
155 changes: 155 additions & 0 deletions src/events/page/schedule/components/xlsx/getFullCalendarToExcel.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,155 @@
import { EventSourceInput } from '@fullcalendar/core'
import { utils, writeFile } from 'xlsx-js-style'
import { FullCalendarSlotLabelInterval } from '../FullCalendarBase'
import { convertTableToExcelWorkSheet } from './htmlToExcel'
import { getIndividualDays } from '../../../../../utils/dates/diffDays'
import { Event } from '../../../../../types'

type Resource = {
id: string
title: string
order: number
}

type Events = {
title: string
id: string
start: string
end: string
speakers: string
resourceId: string
backgroundColor: string
}

export const downloadOrCopyFullCalendarToExcel = (
event: Event,
events: EventSourceInput | Events[],
slotLabelInterval = '00:15',
resources: Resource[],
copyToClipboard = false,
selectedDayOfTheMonth?: number // only for copy
) => {
const workbook = getFullCalendarToExcelWorkbook(event, events, slotLabelInterval, resources)
if (copyToClipboard) {
const htmlTable = convertFullCalendarToHtml(events, slotLabelInterval, resources, selectedDayOfTheMonth)
const clipboardItem = new ClipboardItem({ 'text/html': new Blob([htmlTable.outerHTML], { type: 'text/html' }) })
navigator.clipboard.write([clipboardItem])
} else {
writeFile(workbook, `${event.name} schedule.xlsx`)
}
}

export const getFullCalendarToExcelWorkbook = (
event: Event,
events: EventSourceInput | Events[],
slotLabelInterval = '00:15',
resources: Resource[]
) => {
const days = getIndividualDays(event.dates.start, event.dates.end)

const worksheets = days.map((day) => {
const selectedDayOfTheMonth = day.start.toJSDate().getDate()
return convertFullCalendarToHtml(events, slotLabelInterval, resources, selectedDayOfTheMonth)
})

const workbook = utils.book_new()
worksheets.forEach((worksheet, index) => {
const worksheetName = `Day ${index + 1}`
const worksheetXLSX = convertTableToExcelWorkSheet(worksheet)
utils.book_append_sheet(workbook, worksheetXLSX, worksheetName)
})

return workbook
}

const getRow = (time: Date, endTime: Date, resources: Resource[], eventsArray: Events[]) => {
const row = document.createElement('tr')
const timeCell = document.createElement('td')
timeCell.textContent =
time.toLocaleTimeString([], {
hour: '2-digit',
minute: '2-digit',
}) +
' - ' +
endTime.toLocaleTimeString([], { hour: '2-digit', minute: '2-digit' })
row.appendChild(timeCell)

resources.forEach((resource) => {
const cell = document.createElement('td')
const event = eventsArray.find(
(e) => e.resourceId === resource.id && new Date(e.start) <= time && new Date(e.end) > time
)
if (event) {
cell.textContent = event.title + ' - ' + event.speakers
cell.style.backgroundColor = event.backgroundColor
}
row.appendChild(cell)
})

return row
}

export const convertFullCalendarToHtml = (
events: EventSourceInput | Events[],
slotLabelInterval = FullCalendarSlotLabelInterval,
resources: Resource[],
selectedDayOfTheMonth?: number
) => {
const table = document.createElement('table')
const thead = document.createElement('thead')
const tbody = document.createElement('tbody')

const headerRow = document.createElement('tr')
const emptyHeaderCell = document.createElement('th')
headerRow.appendChild(emptyHeaderCell)
resources.sort((a, b) => a.order - b.order)
resources.forEach((resource) => {
const headerCell = document.createElement('th')
headerCell.textContent = resource.title
headerRow.appendChild(headerCell)
})
thead.appendChild(headerRow)
table.appendChild(thead)

// Create table body
const eventsArrayBase = events as Events[]
const eventsArrayAllDay = eventsArrayBase.sort((a, b) => new Date(a.start).getTime() - new Date(b.start).getTime())
const dayOfTheMonthToExport = selectedDayOfTheMonth || new Date(eventsArrayAllDay[0].start).getDate()
const eventsArray = eventsArrayAllDay.filter((e) => new Date(e.start).getDate() === dayOfTheMonthToExport)

const startTime = new Date(eventsArray[0].start)
const endTime = new Date(eventsArray[eventsArray.length - 1].end)

const slotDuration = parseInt(slotLabelInterval.split(':')[1], 10)

let currentTime = new Date(startTime)

while (currentTime <= endTime) {
const row = getRow(currentTime, new Date(currentTime.getTime() + slotDuration * 60000), resources, eventsArray)

// check if row cell are identical to last row, if so, update the last row first cell end time
const lastChildCells = tbody.lastChild?.childNodes
const rowCells = row.childNodes
// compare all cells except the first one
let identical = true
for (let i = 1; i < rowCells.length; i++) {
if (lastChildCells && lastChildCells[i].textContent !== rowCells[i].textContent) {
identical = false
break
}
}
if (identical && lastChildCells) {
const newFirstCellTextContent = rowCells[0].textContent!.split(' - ')[1]
lastChildCells[0].textContent =
lastChildCells[0].textContent!.split(' - ')[0] + ' - ' + newFirstCellTextContent
} else {
tbody.appendChild(row)
}

currentTime = new Date(currentTime.getTime() + slotDuration * 60000)
}

table.appendChild(tbody)

return table
}
53 changes: 53 additions & 0 deletions src/events/page/schedule/components/xlsx/htmlToExcel.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,53 @@
import { CellObject, utils, WorkSheet } from 'xlsx-js-style'

const rgbToHex = (tdElement: HTMLTableCellElement): string => {
const rgb = tdElement.style.backgroundColor

// Extract RGB values from the string
const match = rgb.match(/^rgb\((\d+),\s*(\d+),\s*(\d+)\)$/)

if (match) {
const [_, r, g, b] = match

// Convert RGB values to hex
const toHex = (value: string) => {
const hex = Number(value).toString(16)
return hex.length === 1 ? '0' + hex : hex
}

return `${toHex(r)}${toHex(g)}${toHex(b)}`
}

return 'FFFFFF'
}

export const convertTableToExcelWorkSheet = (table: HTMLTableElement): WorkSheet => {
const worksheet = utils.aoa_to_sheet([])

const rows = table.rows
for (let i = 0; i < rows.length; i++) {
const row = rows[i]
const cells = row.cells
const rowData = []

for (let j = 0; j < cells.length; j++) {
const cell = cells[j] as HTMLTableCellElement
const cellValue = cell.innerText

const cellObject: Partial<CellObject> = {
v: cellValue,
s: {
fill: {
fgColor: { rgb: rgbToHex(cell) },
},
},
}

rowData.push(cellObject)
}

utils.sheet_add_aoa(worksheet, [rowData], { origin: -1 })
}

return worksheet
}
Loading