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

Comments fully implemented #186

Merged
merged 8 commits into from
Jan 29, 2024
Merged
Show file tree
Hide file tree
Changes from 6 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
28 changes: 28 additions & 0 deletions backend/controller/comments.controller.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,28 @@
const { createComment, getAllComments } = require('../service/comments.service')

const getAllCommentsController = (req, res) => {
const ticketID = req.params.id
getAllComments(ticketID)
.then((data) => res.send(data))
.catch((err) => {
res.status(500).send(err)
console.log(err)
})
}

const createCommentController = (req, res) => {
createComment(req.body)
.then((data) => {
console.log(data)
res.send(data)
})
.catch((error) => {
console.log(error)
res.status(500).send(error)
})
}

module.exports = {
createCommentController,
getAllCommentsController,
}
10 changes: 7 additions & 3 deletions backend/models/comment.model.js
Original file line number Diff line number Diff line change
@@ -1,11 +1,15 @@
const mongoose = require('mongoose')
const { Schema } = mongoose

const Mixed = Schema.Types.Mixed

//sort by new -> old for parent comments, old -> new for replies
willi-li-am marked this conversation as resolved.
Show resolved Hide resolved
const CommentSchema = new Schema(
{
// reference_code would be parent ticket here
reference_code: { type: String, index: true },
commment: { type: String },
// reference_code would be parent ticket/parent comment here
reference_code: { type: String, index: true, required: true },
comment: { type: [Mixed], required: true },
author_id: { type: String, required: true },
},
{
timestamps: true,
Expand Down
15 changes: 15 additions & 0 deletions backend/routes/comments.routes.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,15 @@
const router = require('express').Router()
const { authenticateUser } = require('../auth/middleware')
const {
createCommentController,
getAllCommentsController,
} = require('../controller/comments.controller')

router.route('/:id').get(authenticateUser, getAllCommentsController)

router.route('/').post(authenticateUser, createCommentController)

//delete, edit and others can come later
willi-li-am marked this conversation as resolved.
Show resolved Hide resolved
//shouldn't be too hard can just fully replace the comment part

module.exports = router
2 changes: 2 additions & 0 deletions backend/server.js
Original file line number Diff line number Diff line change
Expand Up @@ -31,6 +31,7 @@ const UWFinancePurchaseRouter = require('./routes/uwfinancepurchases.routes')
const usersRouter = require('./routes/users.routes')
const groupRouter = require('./routes/googlegroup.routes')
const filesRouter = require('./routes/files.routes')
const commentRouter = require('./routes/comments.routes')

app.use(express.json())
app.use('/fundingitems', fundingItemsRouter)
Expand All @@ -40,6 +41,7 @@ app.use('/uwfinancepurchases', UWFinancePurchaseRouter)
app.use('/users', usersRouter)
app.use('/googlegroups', groupRouter)
app.use('/files', filesRouter)
app.use('/comments', commentRouter)

app.listen(port, async () => {
console.log(`Server is running on port: ${port}`)
Expand Down
47 changes: 47 additions & 0 deletions backend/service/comments.service.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,47 @@
const Comment = require('../models/comment.model')

const createComment = async (body) => {
const comment = new Comment(body)
const newComment = await comment.save()
return newComment
}

const getAllComments = async (code) => {
//add reply aggregation, sortby
const res = await Comment.aggregate([
{
$match: {
reference_code: code,
},
},
{
$lookup: {
willi-li-am marked this conversation as resolved.
Show resolved Hide resolved
from: 'comments',
let: { idStr: { $toString: '$_id' } }, // Define variable for use in the pipeline
pipeline: [
{
$match: {
$expr: { $eq: ['$reference_code', '$$idStr'] }, // Use the variable to match documents
},
},
{ $sort: { createdAt: 1 } }, // Sort matching documents in ascending order
],
as: 'replies',
},
},
{
$sort: { createdAt: -1 },
},
{
$set: {
replies: '$replies',
},
},
])
return res
}

module.exports = {
createComment,
getAllComments,
}
2 changes: 1 addition & 1 deletion frontend/public/index.html
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
<!DOCTYPE html>
<!doctype html>

Check failure on line 1 in frontend/public/index.html

View workflow job for this annotation

GitHub Actions / Prettier

frontend/public/index.html#L1

There are issues with this file's formatting, please run Prettier to fix the errors
willi-li-am marked this conversation as resolved.
Show resolved Hide resolved
<html lang="en">
<head>
<meta charset="utf-8" />
Expand Down
186 changes: 186 additions & 0 deletions frontend/src/components/CommentInput.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,186 @@
import { useCallback, useMemo, useState } from 'react'
import isHotkey from 'is-hotkey'
import { Editable, withReact, Slate } from 'slate-react'
import { createEditor } from 'slate'
import { withHistory } from 'slate-history'
import { useAuth } from '../contexts/AuthContext'
import { axiosPreset } from '../axiosConfig'
import { Box, Button } from '@chakra-ui/react'

import {
BlockButton,
Element,
Leaf,
MarkButton,
Toolbar,
toggleMark,
} from './SlateComponents'

const HOTKEYS = {
'mod+b': 'bold',
'mod+i': 'italic',
'mod+u': 'underline',
}

const cleanInput = (val) => {
willi-li-am marked this conversation as resolved.
Show resolved Hide resolved
const res = []
let l = 0
let r = val.length - 1
while (l <= r) {
if (val[l]['children'][0]['text'] == '') {
l += 1
}
if (val[r]['children'][0]['text'] == '') {
r += -1
}

if (
val[l]['children'][0]['text'] != '' &&
val[r]['children'][0]['text'] != ''
) {
break
}
}
for (let i = l; i <= r; i++) {
res.push(val[i])
}
return res
}

const invalidInput = (val) => {
if (val.length === 0) {
willi-li-am marked this conversation as resolved.
Show resolved Hide resolved
return true
}

for (let i = 0; i < val.length; i++) {
if (val[i]['children'][0]['text'] != '') {
return false
}
}
return true
}

const CommentInput = ({ code, getComments, reply, onClose, ticket }) => {
const renderElement = useCallback((props) => <Element {...props} />, [])
const renderLeaf = useCallback((props) => <Leaf {...props} />, [])
const editor = useMemo(() => withHistory(withReact(createEditor())), [])
const [loading, setLoading] = useState(false)
const auth = useAuth()
const [val, setVal] = useState(editor.children)
const handleSubmit = (ref, ticket) => {
setLoading(true)
const comment = cleanInput(val)
if (comment.length === 0) {
console.log('EMPTY')
willi-li-am marked this conversation as resolved.
Show resolved Hide resolved
return
}
const payload = {
author_id: auth.currentUser.uid,
comment: comment,
reference_code: ref,
}
axiosPreset
.post('/comments', payload)
.then(() => getComments(ticket).then(() => setLoading(false)))

.catch(() => setLoading(false))
}

return (
<Slate
editor={editor}
initialValue={initialValue}
onChange={() => {
setVal([...editor.children])
}}
>
<Editable
style={{
marginTop: '10px',
padding: '20px',
paddingLeft: '30px',
minHeight: '150px',
border: '2px #f0f0f0 solid',
borderRadius: '10px',
}}
renderElement={renderElement}
renderLeaf={renderLeaf}
spellCheck
autoFocus={reply}
onKeyDown={(event) => {
for (const hotkey in HOTKEYS) {
if (isHotkey(hotkey, event)) {
event.preventDefault()
const mark = HOTKEYS[hotkey]
toggleMark(editor, mark)
}
}
}}
/>
<Box
display="flex"
width="100%"
justifyContent="space-between"
paddingLeft="5px"
>
<Toolbar>
<MarkButton format="bold" icon="format_bold" />
<MarkButton format="italic" icon="format_italic" />
<MarkButton format="underline" icon="format_underlined" />
<BlockButton format="block-quote" icon="format_quote" />
<BlockButton
format="numbered-list"
icon="format_list_numbered"
/>
<BlockButton
format="bulleted-list"
icon="format_list_bulleted"
/>
</Toolbar>
<Box
display="flex"
gap="10px"
marginTop="5px"
paddingRight="5px"
>
{reply && (
<Button
onClick={onClose}
padding="10px"
height="32px"
colorScheme="red"
>
Cancel
</Button>
)}
<Button
isLoading={loading}
disabled={val.length === 0 || invalidInput(val)}
padding="10px"
height="32px"
colorScheme="blue"
onClick={() => {
handleSubmit(code, ticket)
}}
>
{reply ? 'Reply' : 'Comment'}
</Button>
</Box>
</Box>
</Slate>
)
}

// example taken from https://github.com/ianstormtaylor/slate/blob/main/site/components.tsx
// remove once dynamically fetched from backend
const initialValue = [
{
type: 'paragraph',
children: [{ text: '' }],
},
]

export default CommentInput

//make a function that removes white lines in the start
//parses data to make it look nice
Loading
Loading