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

633 event post type #1140

Draft
wants to merge 20 commits into
base: master
Choose a base branch
from
Draft
Show file tree
Hide file tree
Changes from all commits
Commits
Show all changes
20 commits
Select commit Hold shift + click to select a range
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
41 changes: 39 additions & 2 deletions api/resolvers/item.js
Original file line number Diff line number Diff line change
Expand Up @@ -14,7 +14,7 @@ import {
import { msatsToSats } from '@/lib/format'
import { parse } from 'tldts'
import uu from 'url-unshort'
import { actSchema, advSchema, bountySchema, commentSchema, discussionSchema, jobSchema, linkSchema, pollSchema, ssValidate } from '@/lib/validate'
import { actSchema, advSchema, bountySchema, eventSchema, commentSchema, discussionSchema, jobSchema, linkSchema, pollSchema, ssValidate } from '@/lib/validate'
import { notifyItemParents, notifyUserSubscribers, notifyZapped, notifyTerritorySubscribers, notifyMention, notifyItemMention } from '@/lib/webPush'
import { defaultCommentSort, isJob, deleteItemByAuthor, getDeleteCommand, hasDeleteCommand, getReminderCommand, hasReminderCommand } from '@/lib/item'
import { datePivot, whenRange } from '@/lib/time'
Expand Down Expand Up @@ -605,6 +605,35 @@ export default {
}

return await models.item.count({ where }) + 1
},

events: async (parent, { startDate, endDate }, { models }) => {
try {
const events = await models.item.findMany({
where: {
eventDate: {
gte: new Date(startDate),
lte: new Date(endDate)
},
// Ensure we're only fetching events
eventLocation: {
not: null
}
},
select: {
id: true,
title: true,
eventDate: true,
eventLocation: true
}
})
return events
} catch (error) {
console.error('Error fetching events:', error)
throw new GraphQLError('Failed to fetch events', {
extensions: { code: 'INTERNAL_SERVER_ERROR' }
})
}
}
},

Expand Down Expand Up @@ -758,6 +787,14 @@ export default {
return await createItem(parent, item, { me, models, lnd, hash, hmac })
}
},
upsertEvent: async (parent, { id, hash, hmac, ...item }, { me, models }) => {
await ssValidate(eventSchema, item, { models, me })
if (id) {
return await updateItem(parent, { id, ...item }, { me, models, hash, hmac })
} else {
return await createItem(parent, item, { me, models, hash, hmac })
}
},
upsertPoll: async (parent, { id, hash, hmac, ...item }, { me, models, lnd }) => {
const numExistingChoices = id
? await models.pollOption.count({
Expand Down Expand Up @@ -1507,7 +1544,7 @@ export const SELECT =
"Item"."rootId", "Item".upvotes, "Item".company, "Item".location, "Item".remote, "Item"."deletedAt",
"Item"."subName", "Item".status, "Item"."uploadId", "Item"."pollCost", "Item".boost, "Item".msats,
"Item".ncomments, "Item"."commentMsats", "Item"."lastCommentAt", "Item"."weightedVotes",
"Item"."weightedDownVotes", "Item".freebie, "Item".bio, "Item"."otsHash", "Item"."bountyPaidTo",
"Item"."weightedDownVotes", "Item".freebie, "Item".bio, "Item"."otsHash", "Item"."bountyPaidTo", "Item"."eventDate", "Item"."eventLocation",
ltree2text("Item"."path") AS "path", "Item"."weightedComments", "Item"."imgproxyUrls", "Item".outlawed,
"Item"."pollExpiresAt", "Item"."apiKey"`

Expand Down
7 changes: 6 additions & 1 deletion api/typeDefs/item.js
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,7 @@ export default gql`
search(q: String, sub: String, cursor: String, what: String, sort: String, when: String, from: String, to: String): Items
auctionPosition(sub: String, id: ID, bid: Int!): Int!
itemRepetition(parentId: ID): Int!
events(startDate: Date!, endDate: Date!): [Item!]!
}

type TitleUnshorted {
Expand All @@ -33,8 +34,9 @@ export default gql`
upsertDiscussion(id: ID, sub: String, title: String!, text: String, boost: Int, forward: [ItemForwardInput], hash: String, hmac: String): Item!
upsertBounty(id: ID, sub: String, title: String!, text: String, bounty: Int, hash: String, hmac: String, boost: Int, forward: [ItemForwardInput]): Item!
upsertJob(id: ID, sub: String!, title: String!, company: String!, location: String, remote: Boolean,
text: String!, url: String!, maxBid: Int!, status: String, logo: Int, hash: String, hmac: String): Item!
text: String!, url: String!, maxBid: Int!, status: String, logo: Int, hash: String, hmac: String): Item!
upsertPoll(id: ID, sub: String, title: String!, text: String, options: [String!]!, boost: Int, forward: [ItemForwardInput], hash: String, hmac: String, pollExpiresAt: Date): Item!
upsertEvent(id: ID, sub: String, title: String!, eventDate: Date!, eventLocation: String!, text: String, boost: Int, forward: [ItemForwardInput], hash: String, hmac: String): Item!
updateNoteId(id: ID!, noteId: String!): Item!
upsertComment(id:ID, text: String!, parentId: ID, hash: String, hmac: String): Item!
act(id: ID!, sats: Int, act: String, idempotent: Boolean, hash: String, hmac: String): ItemActResult!
Expand Down Expand Up @@ -124,11 +126,14 @@ export default gql`
forwards: [ItemForward]
imgproxyUrls: JSONObject
rel: String
eventDate: Date
eventLocation: String
apiKey: Boolean
}

input ItemForwardInput {
nym: String!
pct: Int!
}

`
139 changes: 139 additions & 0 deletions components/event-calendar.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,139 @@
import React, { useState } from 'react'
import { Button } from 'react-bootstrap'
import { useQuery, gql } from '@apollo/client'
import Link from 'next/link'
import styles from '../styles/event-calendar.module.css'

const GET_EVENTS = gql`
query GetEvents($startDate: Date!, $endDate: Date!) {
events(startDate: $startDate, endDate: $endDate) {
id
title
eventDate
eventLocation
}
}
`

const EventCalendar = () => {
const [currentDate, setCurrentDate] = useState(new Date())
const [selectedDate, setSelectedDate] = useState(null)

const startDate = new Date(currentDate.getFullYear(), currentDate.getMonth(), 1)
const endDate = new Date(currentDate.getFullYear(), currentDate.getMonth() + 1, 0)

const { loading, error, data } = useQuery(GET_EVENTS, {
variables: { startDate, endDate }
})

const daysOfWeek = ['Sun', 'Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat']
const months = [
'January', 'February', 'March', 'April', 'May', 'June',
'July', 'August', 'September', 'October', 'November', 'December'
]

const getDaysInMonth = () => {
const year = currentDate.getFullYear()
const month = currentDate.getMonth()
return new Date(year, month + 1, 0).getDate()
}

const handleDayClick = (day) => {
if (day !== '') {
setSelectedDate(new Date(currentDate.getFullYear(), currentDate.getMonth(), day))
}
}

const handleMonthChange = (direction) => {
const newMonth = currentDate.getMonth() + direction
setCurrentDate(new Date(currentDate.getFullYear(), newMonth, 1))
setSelectedDate(null)
}

const getEventsForDay = (day) => {
if (!data || !data.events) return []
const date = new Date(currentDate.getFullYear(), currentDate.getMonth(), day)
return data.events.filter(event => new Date(event.eventDate).toDateString() === date.toDateString())
}

const generateCalendar = () => {
const daysInMonth = getDaysInMonth()
const month = months[currentDate.getMonth()]
const year = currentDate.getFullYear()
const firstDay = new Date(year, currentDate.getMonth(), 1)
const dayOfWeek = firstDay.getDay()

const days = []
for (let i = 0; i < dayOfWeek; i++) {
days.push('')
}
for (let i = 1; i <= daysInMonth; i++) {
days.push(i)
}
while (days.length % 7 !== 0) {
days.push('')
}

const weeks = []
let week = []
for (let i = 0; i < days.length; i++) {
week.push(days[i])
if ((i + 1) % 7 === 0) {
weeks.push(week)
week = []
}
}

return (
<div className={styles.calendarContainer}>
<h2 className={styles.calendarHeader}>
{month} {year}
</h2>
<div className={styles.calendarGrid}>
{daysOfWeek.map((day, index) => (
<div key={`header-${index}`} className={styles.calendarHeaderCell}>
{day}
</div>
))}
{weeks.flat().map((day, index) => (
<div
key={`day-${index}`}
className={`${styles.calendarCell} ${selectedDate && selectedDate.getDate() === day ? styles.selectedDay : ''} ${day === '' ? styles.emptyCell : ''}`}
onClick={() => handleDayClick(day)}
>
{day !== '' && (
<>
<div className={styles.dayNumber}>{day}</div>
<div className={styles.eventContainer}>
{getEventsForDay(day).map((event, eventIndex) => (
<Link key={event.id} href={`/items/${event.id}`}>
<div className={styles.event} title={event.title}>
{event.title}
</div>
</Link>
))}
</div>
</>
)}
</div>
))}
</div>
<div className={styles.buttonContainer}>
<Button variant='primary' onClick={() => handleMonthChange(-1)}>
Previous
</Button>
<Button variant='primary' onClick={() => handleMonthChange(1)}>
Next
</Button>
</div>
</div>
)
}

if (loading) return <p>Loading...</p>
if (error) return <p>Error: {error.message}</p>

return generateCalendar()
}

export default EventCalendar
156 changes: 156 additions & 0 deletions components/event-form.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,156 @@
import { Form, Input, MarkdownInput, DateTimeInput } from '@/components/form'
import { useRouter } from 'next/router'
import { gql, useApolloClient, useMutation } from '@apollo/client'
import AdvPostForm, { AdvPostInitial } from './adv-post-form'
import useCrossposter from './use-crossposter'
import { eventSchema } from '@/lib/validate'
import { SubSelectInitial } from './sub-select'
import { useCallback } from 'react'
import { normalizeForwards, toastDeleteScheduled } from '@/lib/form'
import { MAX_TITLE_LENGTH } from '@/lib/constants'
import { useMe } from './me'
import { useToast } from './toast'
import { ItemButtonBar } from './post'
import Countdown from './countdown'

export function EventForm ({
item,
sub,
editThreshold,
titleLabel = 'Title',
dateLabel = 'Date',
locationLabel = 'Location',
textLabel = 'Description',
handleSubmit,
children
}) {
const router = useRouter()
const client = useApolloClient()
const me = useMe()
const toaster = useToast()
const crossposter = useCrossposter()
const schema = eventSchema({ client, me })
const [upsertEvent] = useMutation(
gql`
mutation upsertEvent(
$sub: String
$id: ID
$title: String!
$eventDate: Date!
$eventLocation: String!
$text: String
$boost: Int
$forward: [ItemForwardInput]
$hash: String
$hmac: String
) {
upsertEvent(
sub: $sub
id: $id
title: $title
eventDate: $eventDate
eventLocation: $eventLocation
text: $text
boost: $boost
forward: $forward
hash: $hash
hmac: $hmac
) {
id
deleteScheduledAt
}
}
`
)

const onSubmit = useCallback(
async ({ crosspost, boost, ...values }) => {
const { data, error } = await upsertEvent({
variables: {
sub: item?.subName || sub?.name,
id: item?.id,
boost: boost ? Number(boost) : undefined,
...values,
forward: normalizeForwards(values.forward)
}
})
if (error) {
throw new Error({ message: error.toString() })
}

const eventId = data?.upsertEvent?.id

if (crosspost && eventId) {
await crossposter(eventId)
}

if (item) {
await router.push(`/items/${item.id}`)
} else {
const prefix = sub?.name ? `/~${sub.name}` : ''
await router.push(prefix + '/recent')
}
toastDeleteScheduled(toaster, data, 'upsertEvent', !!item, values.text)
}, [upsertEvent, router]
)

return (
<Form
initial={{
title: item?.title || '',
eventDate: item?.eventDate || '',
eventLocation: item?.eventLocation || '',
text: item?.text || '',
crosspost: item ? !!item.noteId : me?.privates?.nostrCrossposting,
...AdvPostInitial({ forward: normalizeForwards(item?.forwards), boost: item?.boost }),
...SubSelectInitial({ sub: item?.subName || sub?.name })
}}
schema={schema}
invoiceable={{ requireSession: true }}
onSubmit={
handleSubmit ||
onSubmit
}
storageKeyPrefix={item ? undefined : 'event'}
>
{children}
<DateTimeInput
label={dateLabel}
name='eventDate'
className='pr-4'
required
/>
<Input
label={titleLabel}
name='title'
required
autoFocus
clear
maxLength={MAX_TITLE_LENGTH}
/>

<Input
label={locationLabel}
name='eventLocation'
required
/>
<MarkdownInput
topLevel
label={textLabel}
name='text'
minRows={6}
hint={
editThreshold
? (
<div className='text-muted fw-bold'>
<Countdown date={editThreshold} />
</div>
)
: null
}
/>
<AdvPostForm edit={!!item} item={item} />
<ItemButtonBar itemId={item?.id} canDelete={false} />
</Form>
)
}
Loading
Loading