1199 lines
37 KiB
Go
1199 lines
37 KiB
Go
package calendar
|
|
|
|
import (
|
|
"crypto/rand"
|
|
"encoding/hex"
|
|
"errors"
|
|
"io"
|
|
"net/http"
|
|
"os"
|
|
"path/filepath"
|
|
"strconv"
|
|
"strings"
|
|
"time"
|
|
|
|
"mira/backend/internal/auth"
|
|
"mira/backend/internal/users"
|
|
|
|
"github.com/gin-gonic/gin"
|
|
)
|
|
|
|
type Routes struct {
|
|
store Store
|
|
provider Provider
|
|
commemorative CommemorativeProvider
|
|
chatEvents *ChatEventHub
|
|
uploadMaxSizeBytes int64
|
|
uploadAllowedMIMEs map[string]bool
|
|
storageDriver string
|
|
storageLocalPath string
|
|
}
|
|
|
|
type RouteOptions struct {
|
|
UploadMaxSizeMB int
|
|
UploadAllowedMIMEs []string
|
|
StorageDriver string
|
|
StorageLocalPath string
|
|
}
|
|
|
|
func NewRoutes(store Store, provider Provider, commemorative CommemorativeProvider, options RouteOptions) Routes {
|
|
allowedMIMEs := make(map[string]bool, len(options.UploadAllowedMIMEs))
|
|
for _, mime := range options.UploadAllowedMIMEs {
|
|
allowedMIMEs[strings.TrimSpace(mime)] = true
|
|
}
|
|
if options.UploadMaxSizeMB <= 0 {
|
|
options.UploadMaxSizeMB = 10
|
|
}
|
|
if options.StorageDriver == "" {
|
|
options.StorageDriver = "local"
|
|
}
|
|
if options.StorageLocalPath == "" {
|
|
options.StorageLocalPath = "/var/lib/mira/uploads"
|
|
}
|
|
|
|
return Routes{
|
|
store: store,
|
|
provider: provider,
|
|
commemorative: commemorative,
|
|
chatEvents: NewChatEventHub(),
|
|
uploadMaxSizeBytes: int64(options.UploadMaxSizeMB) * 1024 * 1024,
|
|
uploadAllowedMIMEs: allowedMIMEs,
|
|
storageDriver: options.StorageDriver,
|
|
storageLocalPath: options.StorageLocalPath,
|
|
}
|
|
}
|
|
|
|
func (r Routes) Register(router *gin.RouterGroup, requireAuth gin.HandlerFunc) {
|
|
router.Use(requireAuth)
|
|
|
|
router.GET("/week", func(c *gin.Context) {
|
|
c.JSON(http.StatusNotImplemented, gin.H{"message": "Dashboard semanal ainda nao implementado."})
|
|
})
|
|
|
|
router.GET("/holidays", r.holidays)
|
|
router.GET("/custom-dates", r.customDates)
|
|
router.POST("/custom-dates", r.createCustomDate)
|
|
router.PATCH("/custom-dates/:customDateId", r.updateCustomDate)
|
|
router.DELETE("/custom-dates/:customDateId", r.deleteCustomDate)
|
|
router.GET("/items", r.calendarItems)
|
|
router.POST("/items", r.createCalendarItem)
|
|
router.GET("/items/:itemId", r.getCalendarItem)
|
|
router.PATCH("/items/:itemId", r.updateCalendarItem)
|
|
router.DELETE("/items/:itemId", r.cancelCalendarItem)
|
|
router.GET("/items/:itemId/attachments", r.listAttachments)
|
|
router.POST("/items/:itemId/attachments", r.uploadAttachment)
|
|
router.GET("/items/:itemId/chat", r.listChatMessages)
|
|
router.GET("/items/:itemId/chat/stream", r.streamChatMessages)
|
|
router.POST("/items/:itemId/chat", r.createChatMessage)
|
|
router.PATCH("/chat/messages/:messageId", r.updateChatMessage)
|
|
router.DELETE("/chat/messages/:messageId", r.deleteChatMessage)
|
|
router.POST("/chat/messages/:messageId/attachments", r.uploadChatAttachment)
|
|
router.GET("/chat/attachments/:attachmentId/download", r.downloadChatAttachment)
|
|
router.GET("/attachments/:attachmentId/download", r.downloadAttachment)
|
|
router.DELETE("/attachments/:attachmentId", r.deleteAttachment)
|
|
}
|
|
|
|
func (r Routes) holidays(c *gin.Context) {
|
|
year := time.Now().Year()
|
|
if value := c.Query("year"); value != "" {
|
|
parsed, err := strconv.Atoi(value)
|
|
if err != nil || parsed < 1900 || parsed > 2199 {
|
|
c.JSON(http.StatusBadRequest, gin.H{"message": "Ano invalido."})
|
|
return
|
|
}
|
|
year = parsed
|
|
}
|
|
|
|
holidays, err := r.store.ListHolidaysByYear(c.Request.Context(), year)
|
|
if err != nil {
|
|
c.JSON(http.StatusInternalServerError, gin.H{"message": "Nao foi possivel carregar feriados."})
|
|
return
|
|
}
|
|
|
|
if len(holidays) == 0 {
|
|
imported, err := r.provider.NationalHolidays(c.Request.Context(), year)
|
|
if err != nil {
|
|
c.JSON(http.StatusBadGateway, gin.H{"message": "Nao foi possivel consultar os feriados nacionais."})
|
|
return
|
|
}
|
|
|
|
if err := r.store.UpsertHolidays(c.Request.Context(), "brasilapi", imported); err != nil {
|
|
c.JSON(http.StatusInternalServerError, gin.H{"message": "Nao foi possivel salvar feriados."})
|
|
return
|
|
}
|
|
|
|
holidays, err = r.store.ListHolidaysByYear(c.Request.Context(), year)
|
|
if err != nil {
|
|
c.JSON(http.StatusInternalServerError, gin.H{"message": "Nao foi possivel carregar feriados."})
|
|
return
|
|
}
|
|
}
|
|
|
|
c.JSON(http.StatusOK, gin.H{"holidays": holidays})
|
|
}
|
|
|
|
func (r Routes) customDates(c *gin.Context) {
|
|
claims, ok := auth.ClaimsFromContext(c)
|
|
if !ok {
|
|
c.JSON(http.StatusUnauthorized, gin.H{"message": "Autenticacao obrigatoria."})
|
|
return
|
|
}
|
|
|
|
year := time.Now().Year()
|
|
if value := c.Query("year"); value != "" {
|
|
parsed, err := strconv.Atoi(value)
|
|
if err != nil || parsed < 1900 || parsed > 2199 {
|
|
c.JSON(http.StatusBadRequest, gin.H{"message": "Ano invalido."})
|
|
return
|
|
}
|
|
year = parsed
|
|
}
|
|
|
|
viewerUserID := ""
|
|
if claims.Role == users.RoleClientViewer {
|
|
viewerUserID = claims.UserID
|
|
}
|
|
|
|
if r.commemorative != nil {
|
|
initialDates, err := r.store.ListCustomDatesByYear(c.Request.Context(), year, "", viewerUserID)
|
|
if err != nil {
|
|
c.JSON(http.StatusInternalServerError, gin.H{"message": "Nao foi possivel carregar datas personalizadas."})
|
|
return
|
|
}
|
|
hasImported := false
|
|
for _, date := range initialDates {
|
|
if date.Category == "feriados-brasil" {
|
|
hasImported = true
|
|
break
|
|
}
|
|
}
|
|
if !hasImported {
|
|
imported, err := r.commemorative.CommemorativeDates(c.Request.Context(), year)
|
|
if err == nil && len(imported) > 0 {
|
|
_ = r.store.UpsertExternalCommemorativeDates(c.Request.Context(), imported)
|
|
}
|
|
}
|
|
}
|
|
|
|
dates, err := r.store.ListCustomDatesByYear(c.Request.Context(), year, c.Query("client_id"), viewerUserID)
|
|
if err != nil {
|
|
c.JSON(http.StatusInternalServerError, gin.H{"message": "Nao foi possivel carregar datas personalizadas."})
|
|
return
|
|
}
|
|
|
|
c.JSON(http.StatusOK, gin.H{"custom_dates": dates})
|
|
}
|
|
|
|
type createCustomDateRequest struct {
|
|
ClientID string `json:"client_id"`
|
|
Name string `json:"name" binding:"required,min=2"`
|
|
Description string `json:"description"`
|
|
Date string `json:"date" binding:"required"`
|
|
RecursAnnually bool `json:"recurs_annually"`
|
|
Visibility string `json:"visibility"`
|
|
Category string `json:"category"`
|
|
}
|
|
|
|
func (r Routes) createCustomDate(c *gin.Context) {
|
|
claims, ok := auth.ClaimsFromContext(c)
|
|
if !ok || (claims.Role != users.RoleSuperAdmin && claims.Role != users.RoleAgencyUser) {
|
|
c.JSON(http.StatusForbidden, gin.H{"message": "Permissao insuficiente."})
|
|
return
|
|
}
|
|
|
|
var input createCustomDateRequest
|
|
if err := c.ShouldBindJSON(&input); err != nil {
|
|
c.JSON(http.StatusBadRequest, gin.H{"message": "Informe os dados da data personalizada."})
|
|
return
|
|
}
|
|
|
|
if _, err := time.Parse("2006-01-02", input.Date); err != nil {
|
|
c.JSON(http.StatusBadRequest, gin.H{"message": "Data invalida. Use o formato YYYY-MM-DD."})
|
|
return
|
|
}
|
|
|
|
visibility := strings.TrimSpace(input.Visibility)
|
|
if visibility == "" {
|
|
visibility = "agency"
|
|
}
|
|
if visibility != "agency" && visibility != "client" {
|
|
c.JSON(http.StatusBadRequest, gin.H{"message": "Visibilidade invalida."})
|
|
return
|
|
}
|
|
|
|
category := strings.TrimSpace(input.Category)
|
|
if category == "" {
|
|
category = "custom"
|
|
}
|
|
|
|
date, err := r.store.CreateCustomDate(c.Request.Context(), CreateCustomDateInput{
|
|
ClientID: strings.TrimSpace(input.ClientID),
|
|
Name: strings.TrimSpace(input.Name),
|
|
Description: strings.TrimSpace(input.Description),
|
|
Date: input.Date,
|
|
RecursAnnually: input.RecursAnnually,
|
|
Visibility: visibility,
|
|
Category: category,
|
|
CreatedBy: claims.UserID,
|
|
})
|
|
if err != nil {
|
|
c.JSON(http.StatusInternalServerError, gin.H{"message": "Nao foi possivel criar a data personalizada."})
|
|
return
|
|
}
|
|
|
|
_ = r.store.RecordAudit(c.Request.Context(), claims.UserID, "custom_date.created", "commemorative_date", date.ID, map[string]any{
|
|
"name": date.Name,
|
|
"client_id": date.ClientID,
|
|
})
|
|
|
|
c.JSON(http.StatusCreated, gin.H{"custom_date": date})
|
|
}
|
|
|
|
type updateCustomDateRequest struct {
|
|
ClientID string `json:"client_id"`
|
|
Name string `json:"name" binding:"required,min=2"`
|
|
Description string `json:"description"`
|
|
Date string `json:"date" binding:"required"`
|
|
RecursAnnually bool `json:"recurs_annually"`
|
|
Visibility string `json:"visibility"`
|
|
}
|
|
|
|
func (r Routes) updateCustomDate(c *gin.Context) {
|
|
claims, ok := auth.ClaimsFromContext(c)
|
|
if !ok || (claims.Role != users.RoleSuperAdmin && claims.Role != users.RoleAgencyUser) {
|
|
c.JSON(http.StatusForbidden, gin.H{"message": "Permissao insuficiente."})
|
|
return
|
|
}
|
|
|
|
var input updateCustomDateRequest
|
|
if err := c.ShouldBindJSON(&input); err != nil {
|
|
c.JSON(http.StatusBadRequest, gin.H{"message": "Informe os dados da data personalizada."})
|
|
return
|
|
}
|
|
|
|
if _, err := time.Parse("2006-01-02", input.Date); err != nil {
|
|
c.JSON(http.StatusBadRequest, gin.H{"message": "Data invalida. Use o formato YYYY-MM-DD."})
|
|
return
|
|
}
|
|
|
|
visibility := strings.TrimSpace(input.Visibility)
|
|
if visibility == "" {
|
|
visibility = "agency"
|
|
}
|
|
if visibility != "agency" && visibility != "client" {
|
|
c.JSON(http.StatusBadRequest, gin.H{"message": "Visibilidade invalida."})
|
|
return
|
|
}
|
|
|
|
date, err := r.store.UpdateCustomDate(c.Request.Context(), UpdateCustomDateInput{
|
|
ID: c.Param("customDateId"),
|
|
ClientID: strings.TrimSpace(input.ClientID),
|
|
Name: strings.TrimSpace(input.Name),
|
|
Description: strings.TrimSpace(input.Description),
|
|
Date: input.Date,
|
|
RecursAnnually: input.RecursAnnually,
|
|
Visibility: visibility,
|
|
})
|
|
if errors.Is(err, ErrCustomDateNotFound) {
|
|
c.JSON(http.StatusNotFound, gin.H{"message": "Data personalizada nao encontrada."})
|
|
return
|
|
}
|
|
if err != nil {
|
|
c.JSON(http.StatusInternalServerError, gin.H{"message": "Nao foi possivel atualizar a data personalizada."})
|
|
return
|
|
}
|
|
|
|
_ = r.store.RecordAudit(c.Request.Context(), claims.UserID, "custom_date.updated", "commemorative_date", date.ID, map[string]any{
|
|
"name": date.Name,
|
|
"client_id": date.ClientID,
|
|
})
|
|
|
|
c.JSON(http.StatusOK, gin.H{"custom_date": date})
|
|
}
|
|
|
|
func (r Routes) deleteCustomDate(c *gin.Context) {
|
|
claims, ok := auth.ClaimsFromContext(c)
|
|
if !ok || (claims.Role != users.RoleSuperAdmin && claims.Role != users.RoleAgencyUser) {
|
|
c.JSON(http.StatusForbidden, gin.H{"message": "Permissao insuficiente."})
|
|
return
|
|
}
|
|
|
|
err := r.store.DeleteCustomDate(c.Request.Context(), c.Param("customDateId"))
|
|
if errors.Is(err, ErrCustomDateNotFound) {
|
|
c.JSON(http.StatusNotFound, gin.H{"message": "Data personalizada nao encontrada."})
|
|
return
|
|
}
|
|
if err != nil {
|
|
c.JSON(http.StatusInternalServerError, gin.H{"message": "Nao foi possivel excluir a data personalizada."})
|
|
return
|
|
}
|
|
|
|
_ = r.store.RecordAudit(c.Request.Context(), claims.UserID, "custom_date.deleted", "commemorative_date", c.Param("customDateId"), nil)
|
|
c.JSON(http.StatusOK, gin.H{"message": "Data personalizada excluida."})
|
|
}
|
|
|
|
func (r Routes) calendarItems(c *gin.Context) {
|
|
claims, ok := auth.ClaimsFromContext(c)
|
|
if !ok {
|
|
c.JSON(http.StatusUnauthorized, gin.H{"message": "Autenticacao obrigatoria."})
|
|
return
|
|
}
|
|
|
|
from := strings.TrimSpace(c.Query("from"))
|
|
to := strings.TrimSpace(c.Query("to"))
|
|
|
|
if from == "" || to == "" {
|
|
year := time.Now().Year()
|
|
if value := c.Query("year"); value != "" {
|
|
parsed, err := strconv.Atoi(value)
|
|
if err != nil || parsed < 1900 || parsed > 2199 {
|
|
c.JSON(http.StatusBadRequest, gin.H{"message": "Ano invalido."})
|
|
return
|
|
}
|
|
year = parsed
|
|
}
|
|
|
|
from = time.Date(year, 1, 1, 0, 0, 0, 0, time.UTC).Format("2006-01-02")
|
|
to = time.Date(year, 12, 31, 0, 0, 0, 0, time.UTC).Format("2006-01-02")
|
|
}
|
|
|
|
if _, err := time.Parse("2006-01-02", from); err != nil {
|
|
c.JSON(http.StatusBadRequest, gin.H{"message": "Data inicial invalida. Use o formato YYYY-MM-DD."})
|
|
return
|
|
}
|
|
if _, err := time.Parse("2006-01-02", to); err != nil {
|
|
c.JSON(http.StatusBadRequest, gin.H{"message": "Data final invalida. Use o formato YYYY-MM-DD."})
|
|
return
|
|
}
|
|
|
|
viewerUserID := ""
|
|
if claims.Role == users.RoleClientViewer {
|
|
viewerUserID = claims.UserID
|
|
}
|
|
|
|
items, err := r.store.ListCalendarItems(c.Request.Context(), ListCalendarItemsFilter{
|
|
ClientID: strings.TrimSpace(c.Query("client_id")),
|
|
ViewerUserID: viewerUserID,
|
|
From: from,
|
|
To: to,
|
|
})
|
|
if err != nil {
|
|
c.JSON(http.StatusInternalServerError, gin.H{"message": "Nao foi possivel carregar postagens."})
|
|
return
|
|
}
|
|
|
|
c.JSON(http.StatusOK, gin.H{"items": items})
|
|
}
|
|
|
|
type createCalendarItemRequest struct {
|
|
ClientID string `json:"client_id" binding:"required"`
|
|
Title string `json:"title" binding:"required,min=2"`
|
|
Description string `json:"description"`
|
|
ContentType string `json:"content_type"`
|
|
Status string `json:"status"`
|
|
ScheduledDate string `json:"scheduled_date" binding:"required"`
|
|
CopyText string `json:"copy_text"`
|
|
InternalNotes string `json:"internal_notes"`
|
|
ClientNotes string `json:"client_notes"`
|
|
}
|
|
|
|
func (r Routes) createCalendarItem(c *gin.Context) {
|
|
claims, ok := auth.ClaimsFromContext(c)
|
|
if !ok || (claims.Role != users.RoleSuperAdmin && claims.Role != users.RoleAgencyUser) {
|
|
c.JSON(http.StatusForbidden, gin.H{"message": "Permissao insuficiente."})
|
|
return
|
|
}
|
|
|
|
var input createCalendarItemRequest
|
|
if err := c.ShouldBindJSON(&input); err != nil {
|
|
c.JSON(http.StatusBadRequest, gin.H{"message": "Informe os dados da postagem."})
|
|
return
|
|
}
|
|
|
|
if _, err := time.Parse("2006-01-02", input.ScheduledDate); err != nil {
|
|
c.JSON(http.StatusBadRequest, gin.H{"message": "Data invalida. Use o formato YYYY-MM-DD."})
|
|
return
|
|
}
|
|
|
|
contentType := strings.TrimSpace(input.ContentType)
|
|
if contentType == "" {
|
|
contentType = "post"
|
|
}
|
|
|
|
status := strings.TrimSpace(input.Status)
|
|
if status == "" {
|
|
status = "rascunho"
|
|
}
|
|
if !isValidCalendarItemStatus(status) {
|
|
c.JSON(http.StatusBadRequest, gin.H{"message": "Status invalido."})
|
|
return
|
|
}
|
|
|
|
item, err := r.store.CreateCalendarItem(c.Request.Context(), CreateCalendarItemInput{
|
|
ClientID: strings.TrimSpace(input.ClientID),
|
|
Title: strings.TrimSpace(input.Title),
|
|
Description: strings.TrimSpace(input.Description),
|
|
ContentType: contentType,
|
|
Status: status,
|
|
ScheduledDate: input.ScheduledDate,
|
|
CopyText: strings.TrimSpace(input.CopyText),
|
|
InternalNotes: strings.TrimSpace(input.InternalNotes),
|
|
ClientNotes: strings.TrimSpace(input.ClientNotes),
|
|
CreatedBy: claims.UserID,
|
|
})
|
|
if err != nil {
|
|
c.JSON(http.StatusInternalServerError, gin.H{"message": "Nao foi possivel criar a postagem."})
|
|
return
|
|
}
|
|
|
|
_ = r.store.RecordAudit(c.Request.Context(), claims.UserID, "calendar_item.created", "calendar_item", item.ID, map[string]any{
|
|
"title": item.Title,
|
|
"client_id": item.ClientID,
|
|
"status": item.Status,
|
|
})
|
|
|
|
c.JSON(http.StatusCreated, gin.H{"item": item})
|
|
}
|
|
|
|
func (r Routes) getCalendarItem(c *gin.Context) {
|
|
claims, ok := auth.ClaimsFromContext(c)
|
|
if !ok {
|
|
c.JSON(http.StatusUnauthorized, gin.H{"message": "Autenticacao obrigatoria."})
|
|
return
|
|
}
|
|
|
|
viewerUserID := ""
|
|
if claims.Role == users.RoleClientViewer {
|
|
viewerUserID = claims.UserID
|
|
}
|
|
|
|
item, err := r.store.FindCalendarItem(c.Request.Context(), c.Param("itemId"), viewerUserID)
|
|
if errors.Is(err, ErrCalendarItemNotFound) {
|
|
c.JSON(http.StatusNotFound, gin.H{"message": "Postagem nao encontrada."})
|
|
return
|
|
}
|
|
if err != nil {
|
|
c.JSON(http.StatusInternalServerError, gin.H{"message": "Nao foi possivel carregar a postagem."})
|
|
return
|
|
}
|
|
|
|
c.JSON(http.StatusOK, gin.H{"item": item})
|
|
}
|
|
|
|
type updateCalendarItemRequest struct {
|
|
Title *string `json:"title"`
|
|
Description *string `json:"description"`
|
|
Status *string `json:"status"`
|
|
ScheduledDate *string `json:"scheduled_date"`
|
|
CopyText *string `json:"copy_text"`
|
|
InternalNotes *string `json:"internal_notes"`
|
|
ClientNotes *string `json:"client_notes"`
|
|
}
|
|
|
|
func (r Routes) updateCalendarItem(c *gin.Context) {
|
|
claims, ok := auth.ClaimsFromContext(c)
|
|
if !ok || (claims.Role != users.RoleSuperAdmin && claims.Role != users.RoleAgencyUser) {
|
|
c.JSON(http.StatusForbidden, gin.H{"message": "Permissao insuficiente."})
|
|
return
|
|
}
|
|
|
|
var input updateCalendarItemRequest
|
|
if err := c.ShouldBindJSON(&input); err != nil {
|
|
c.JSON(http.StatusBadRequest, gin.H{"message": "Dados invalidos."})
|
|
return
|
|
}
|
|
|
|
update := UpdateCalendarItemInput{ID: c.Param("itemId")}
|
|
if input.Title != nil {
|
|
update.UpdateTitle = true
|
|
update.Title = strings.TrimSpace(*input.Title)
|
|
if update.Title == "" {
|
|
c.JSON(http.StatusBadRequest, gin.H{"message": "Titulo invalido."})
|
|
return
|
|
}
|
|
}
|
|
if input.Description != nil {
|
|
update.UpdateDescription = true
|
|
update.Description = strings.TrimSpace(*input.Description)
|
|
}
|
|
if input.Status != nil {
|
|
update.UpdateStatus = true
|
|
update.Status = strings.TrimSpace(*input.Status)
|
|
if !isValidCalendarItemStatus(update.Status) {
|
|
c.JSON(http.StatusBadRequest, gin.H{"message": "Status invalido."})
|
|
return
|
|
}
|
|
}
|
|
if input.ScheduledDate != nil {
|
|
update.UpdateScheduledDate = true
|
|
update.ScheduledDate = strings.TrimSpace(*input.ScheduledDate)
|
|
if _, err := time.Parse("2006-01-02", update.ScheduledDate); err != nil {
|
|
c.JSON(http.StatusBadRequest, gin.H{"message": "Data invalida. Use o formato YYYY-MM-DD."})
|
|
return
|
|
}
|
|
}
|
|
if input.CopyText != nil {
|
|
update.UpdateCopyText = true
|
|
update.CopyText = strings.TrimSpace(*input.CopyText)
|
|
}
|
|
if input.InternalNotes != nil {
|
|
update.UpdateInternalNotes = true
|
|
update.InternalNotes = strings.TrimSpace(*input.InternalNotes)
|
|
}
|
|
if input.ClientNotes != nil {
|
|
update.UpdateClientNotes = true
|
|
update.ClientNotes = strings.TrimSpace(*input.ClientNotes)
|
|
}
|
|
|
|
item, err := r.store.UpdateCalendarItem(c.Request.Context(), update)
|
|
if errors.Is(err, ErrCalendarItemNotFound) {
|
|
c.JSON(http.StatusNotFound, gin.H{"message": "Postagem nao encontrada."})
|
|
return
|
|
}
|
|
if err != nil {
|
|
c.JSON(http.StatusInternalServerError, gin.H{"message": "Nao foi possivel atualizar a postagem."})
|
|
return
|
|
}
|
|
|
|
_ = r.store.RecordAudit(c.Request.Context(), claims.UserID, "calendar_item.updated", "calendar_item", item.ID, map[string]any{
|
|
"title": item.Title,
|
|
"status": item.Status,
|
|
})
|
|
|
|
c.JSON(http.StatusOK, gin.H{"item": item})
|
|
}
|
|
|
|
func (r Routes) cancelCalendarItem(c *gin.Context) {
|
|
claims, ok := auth.ClaimsFromContext(c)
|
|
if !ok || (claims.Role != users.RoleSuperAdmin && claims.Role != users.RoleAgencyUser) {
|
|
c.JSON(http.StatusForbidden, gin.H{"message": "Permissao insuficiente."})
|
|
return
|
|
}
|
|
|
|
item, err := r.store.FindCalendarItem(c.Request.Context(), c.Param("itemId"), "")
|
|
if errors.Is(err, ErrCalendarItemNotFound) {
|
|
c.JSON(http.StatusNotFound, gin.H{"message": "Postagem nao encontrada."})
|
|
return
|
|
}
|
|
if err != nil {
|
|
c.JSON(http.StatusInternalServerError, gin.H{"message": "Nao foi possivel carregar a postagem."})
|
|
return
|
|
}
|
|
|
|
if err := r.store.DeleteCalendarItem(c.Request.Context(), item.ID); err != nil {
|
|
c.JSON(http.StatusInternalServerError, gin.H{"message": "Nao foi possivel excluir a postagem."})
|
|
return
|
|
}
|
|
|
|
_ = r.store.RecordAudit(c.Request.Context(), claims.UserID, "calendar_item.deleted", "calendar_item", item.ID, map[string]any{
|
|
"title": item.Title,
|
|
"status": item.Status,
|
|
})
|
|
|
|
c.JSON(http.StatusOK, gin.H{"message": "Postagem excluida."})
|
|
}
|
|
|
|
func (r Routes) listAttachments(c *gin.Context) {
|
|
claims, ok := auth.ClaimsFromContext(c)
|
|
if !ok {
|
|
c.JSON(http.StatusUnauthorized, gin.H{"message": "Autenticacao obrigatoria."})
|
|
return
|
|
}
|
|
|
|
viewerUserID := ""
|
|
if claims.Role == users.RoleClientViewer {
|
|
viewerUserID = claims.UserID
|
|
}
|
|
|
|
attachments, err := r.store.ListAttachments(c.Request.Context(), c.Param("itemId"), viewerUserID)
|
|
if err != nil {
|
|
c.JSON(http.StatusInternalServerError, gin.H{"message": "Nao foi possivel carregar anexos."})
|
|
return
|
|
}
|
|
|
|
c.JSON(http.StatusOK, gin.H{"attachments": attachments})
|
|
}
|
|
|
|
func (r Routes) listChatMessages(c *gin.Context) {
|
|
claims, ok := auth.ClaimsFromContext(c)
|
|
if !ok {
|
|
c.JSON(http.StatusUnauthorized, gin.H{"message": "Autenticacao obrigatoria."})
|
|
return
|
|
}
|
|
|
|
channel := strings.TrimSpace(c.Query("channel"))
|
|
if channel == "" {
|
|
channel = ChatChannelExternal
|
|
}
|
|
if !isValidChatChannel(channel) {
|
|
c.JSON(http.StatusBadRequest, gin.H{"message": "Canal de chat invalido."})
|
|
return
|
|
}
|
|
if channel == ChatChannelInternal && claims.Role == users.RoleClientViewer {
|
|
c.JSON(http.StatusForbidden, gin.H{"message": "Permissao insuficiente."})
|
|
return
|
|
}
|
|
|
|
viewerUserID := ""
|
|
if claims.Role == users.RoleClientViewer {
|
|
viewerUserID = claims.UserID
|
|
}
|
|
|
|
item, err := r.store.FindCalendarItem(c.Request.Context(), c.Param("itemId"), viewerUserID)
|
|
if errors.Is(err, ErrCalendarItemNotFound) {
|
|
c.JSON(http.StatusNotFound, gin.H{"message": "Postagem nao encontrada."})
|
|
return
|
|
}
|
|
if err != nil {
|
|
c.JSON(http.StatusInternalServerError, gin.H{"message": "Nao foi possivel carregar a postagem."})
|
|
return
|
|
}
|
|
|
|
messages, err := r.store.ListChatMessages(c.Request.Context(), item.ID, channel)
|
|
if err != nil {
|
|
c.JSON(http.StatusInternalServerError, gin.H{"message": "Nao foi possivel carregar mensagens."})
|
|
return
|
|
}
|
|
|
|
c.JSON(http.StatusOK, gin.H{"messages": messages})
|
|
}
|
|
|
|
func (r Routes) streamChatMessages(c *gin.Context) {
|
|
claims, ok := auth.ClaimsFromContext(c)
|
|
if !ok {
|
|
c.JSON(http.StatusUnauthorized, gin.H{"message": "Autenticacao obrigatoria."})
|
|
return
|
|
}
|
|
|
|
channel := strings.TrimSpace(c.Query("channel"))
|
|
if channel == "" {
|
|
channel = ChatChannelExternal
|
|
}
|
|
if !isValidChatChannel(channel) {
|
|
c.JSON(http.StatusBadRequest, gin.H{"message": "Canal de chat invalido."})
|
|
return
|
|
}
|
|
if channel == ChatChannelInternal && claims.Role == users.RoleClientViewer {
|
|
c.JSON(http.StatusForbidden, gin.H{"message": "Permissao insuficiente."})
|
|
return
|
|
}
|
|
|
|
viewerUserID := ""
|
|
if claims.Role == users.RoleClientViewer {
|
|
viewerUserID = claims.UserID
|
|
}
|
|
|
|
item, err := r.store.FindCalendarItem(c.Request.Context(), c.Param("itemId"), viewerUserID)
|
|
if errors.Is(err, ErrCalendarItemNotFound) {
|
|
c.JSON(http.StatusNotFound, gin.H{"message": "Postagem nao encontrada."})
|
|
return
|
|
}
|
|
if err != nil {
|
|
c.JSON(http.StatusInternalServerError, gin.H{"message": "Nao foi possivel carregar a postagem."})
|
|
return
|
|
}
|
|
|
|
events, unsubscribe := r.chatEvents.Subscribe(item.ID, channel)
|
|
defer unsubscribe()
|
|
|
|
c.Header("Content-Type", "text/event-stream")
|
|
c.Header("Cache-Control", "no-cache")
|
|
c.Header("Connection", "keep-alive")
|
|
c.Header("X-Accel-Buffering", "no")
|
|
|
|
flusher, ok := c.Writer.(http.Flusher)
|
|
if !ok {
|
|
c.JSON(http.StatusInternalServerError, gin.H{"message": "Streaming nao suportado."})
|
|
return
|
|
}
|
|
|
|
_, _ = c.Writer.Write([]byte("event: ready\ndata: ok\n\n"))
|
|
flusher.Flush()
|
|
|
|
heartbeat := time.NewTicker(25 * time.Second)
|
|
defer heartbeat.Stop()
|
|
|
|
for {
|
|
select {
|
|
case <-c.Request.Context().Done():
|
|
return
|
|
case <-events:
|
|
_, _ = c.Writer.Write([]byte("event: chat\ndata: refresh\n\n"))
|
|
flusher.Flush()
|
|
case <-heartbeat.C:
|
|
_, _ = c.Writer.Write([]byte("event: ping\ndata: keepalive\n\n"))
|
|
flusher.Flush()
|
|
}
|
|
}
|
|
}
|
|
|
|
type createChatMessageRequest struct {
|
|
Channel string `json:"channel"`
|
|
Body string `json:"body" binding:"max=4000"`
|
|
}
|
|
|
|
func (r Routes) createChatMessage(c *gin.Context) {
|
|
claims, ok := auth.ClaimsFromContext(c)
|
|
if !ok {
|
|
c.JSON(http.StatusUnauthorized, gin.H{"message": "Autenticacao obrigatoria."})
|
|
return
|
|
}
|
|
|
|
var input createChatMessageRequest
|
|
if err := c.ShouldBindJSON(&input); err != nil {
|
|
c.JSON(http.StatusBadRequest, gin.H{"message": "Informe uma mensagem valida."})
|
|
return
|
|
}
|
|
|
|
channel := strings.TrimSpace(input.Channel)
|
|
if channel == "" {
|
|
channel = ChatChannelExternal
|
|
}
|
|
if !isValidChatChannel(channel) {
|
|
c.JSON(http.StatusBadRequest, gin.H{"message": "Canal de chat invalido."})
|
|
return
|
|
}
|
|
if channel == ChatChannelInternal && claims.Role == users.RoleClientViewer {
|
|
c.JSON(http.StatusForbidden, gin.H{"message": "Permissao insuficiente."})
|
|
return
|
|
}
|
|
|
|
body := strings.TrimSpace(input.Body)
|
|
if body == "" {
|
|
c.JSON(http.StatusBadRequest, gin.H{"message": "Informe uma mensagem valida."})
|
|
return
|
|
}
|
|
|
|
viewerUserID := ""
|
|
if claims.Role == users.RoleClientViewer {
|
|
viewerUserID = claims.UserID
|
|
}
|
|
|
|
item, err := r.store.FindCalendarItem(c.Request.Context(), c.Param("itemId"), viewerUserID)
|
|
if errors.Is(err, ErrCalendarItemNotFound) {
|
|
c.JSON(http.StatusNotFound, gin.H{"message": "Postagem nao encontrada."})
|
|
return
|
|
}
|
|
if err != nil {
|
|
c.JSON(http.StatusInternalServerError, gin.H{"message": "Nao foi possivel carregar a postagem."})
|
|
return
|
|
}
|
|
|
|
message, err := r.store.CreateChatMessage(c.Request.Context(), CreateChatMessageInput{
|
|
CalendarItemID: item.ID,
|
|
Channel: channel,
|
|
Body: body,
|
|
CreatedBy: claims.UserID,
|
|
})
|
|
if err != nil {
|
|
c.JSON(http.StatusInternalServerError, gin.H{"message": "Nao foi possivel enviar a mensagem."})
|
|
return
|
|
}
|
|
|
|
_ = r.store.RecordAudit(c.Request.Context(), claims.UserID, "chat_message.created", "calendar_item", item.ID, map[string]any{
|
|
"channel": channel,
|
|
})
|
|
|
|
r.chatEvents.Publish(item.ID, channel)
|
|
|
|
c.JSON(http.StatusCreated, gin.H{"message": message})
|
|
}
|
|
|
|
type updateChatMessageRequest struct {
|
|
Body string `json:"body" binding:"required,min=1,max=4000"`
|
|
}
|
|
|
|
func (r Routes) updateChatMessage(c *gin.Context) {
|
|
claims, ok := auth.ClaimsFromContext(c)
|
|
if !ok {
|
|
c.JSON(http.StatusUnauthorized, gin.H{"message": "Autenticacao obrigatoria."})
|
|
return
|
|
}
|
|
|
|
var input updateChatMessageRequest
|
|
if err := c.ShouldBindJSON(&input); err != nil {
|
|
c.JSON(http.StatusBadRequest, gin.H{"message": "Informe uma mensagem valida."})
|
|
return
|
|
}
|
|
|
|
message, err := r.authorizedChatMessage(c, claims, c.Param("messageId"), true)
|
|
if err != nil {
|
|
return
|
|
}
|
|
if message.DeletedAt != nil {
|
|
c.JSON(http.StatusNotFound, gin.H{"message": "Mensagem nao encontrada."})
|
|
return
|
|
}
|
|
if len(message.Attachments) > 0 {
|
|
c.JSON(http.StatusBadRequest, gin.H{"message": "Mensagens com anexos nao podem ser editadas."})
|
|
return
|
|
}
|
|
|
|
updated, err := r.store.UpdateChatMessage(c.Request.Context(), message.ID, strings.TrimSpace(input.Body))
|
|
if errors.Is(err, ErrChatMessageNotFound) {
|
|
c.JSON(http.StatusNotFound, gin.H{"message": "Mensagem nao encontrada."})
|
|
return
|
|
}
|
|
if err != nil {
|
|
c.JSON(http.StatusInternalServerError, gin.H{"message": "Nao foi possivel editar a mensagem."})
|
|
return
|
|
}
|
|
|
|
r.chatEvents.Publish(updated.CalendarItemID, updated.Channel)
|
|
|
|
c.JSON(http.StatusOK, gin.H{"message": updated})
|
|
}
|
|
|
|
func (r Routes) deleteChatMessage(c *gin.Context) {
|
|
claims, ok := auth.ClaimsFromContext(c)
|
|
if !ok {
|
|
c.JSON(http.StatusUnauthorized, gin.H{"message": "Autenticacao obrigatoria."})
|
|
return
|
|
}
|
|
|
|
message, err := r.authorizedChatMessage(c, claims, c.Param("messageId"), true)
|
|
if err != nil {
|
|
return
|
|
}
|
|
if message.DeletedAt != nil {
|
|
c.JSON(http.StatusNotFound, gin.H{"message": "Mensagem nao encontrada."})
|
|
return
|
|
}
|
|
|
|
deleted, err := r.store.DeleteChatMessage(c.Request.Context(), message.ID)
|
|
if errors.Is(err, ErrChatMessageNotFound) {
|
|
c.JSON(http.StatusNotFound, gin.H{"message": "Mensagem nao encontrada."})
|
|
return
|
|
}
|
|
if err != nil {
|
|
c.JSON(http.StatusInternalServerError, gin.H{"message": "Nao foi possivel excluir a mensagem."})
|
|
return
|
|
}
|
|
|
|
r.chatEvents.Publish(deleted.CalendarItemID, deleted.Channel)
|
|
|
|
c.JSON(http.StatusOK, gin.H{"message": deleted})
|
|
}
|
|
|
|
func (r Routes) uploadChatAttachment(c *gin.Context) {
|
|
claims, ok := auth.ClaimsFromContext(c)
|
|
if !ok {
|
|
c.JSON(http.StatusUnauthorized, gin.H{"message": "Autenticacao obrigatoria."})
|
|
return
|
|
}
|
|
|
|
message, err := r.authorizedChatMessage(c, claims, c.Param("messageId"), false)
|
|
if err != nil {
|
|
return
|
|
}
|
|
if message.DeletedAt != nil {
|
|
c.JSON(http.StatusNotFound, gin.H{"message": "Mensagem nao encontrada."})
|
|
return
|
|
}
|
|
if message.CreatedBy == nil || *message.CreatedBy != claims.UserID {
|
|
c.JSON(http.StatusForbidden, gin.H{"message": "Permissao insuficiente."})
|
|
return
|
|
}
|
|
|
|
upload, err := r.saveUploadedFile(c, filepath.Join("chat", message.ID))
|
|
if err != nil {
|
|
return
|
|
}
|
|
|
|
attachment, err := r.store.CreateChatAttachment(c.Request.Context(), CreateChatAttachmentInput{
|
|
ChatMessageID: message.ID,
|
|
OriginalFilename: upload.originalFilename,
|
|
StoredFilename: upload.storedFilename,
|
|
MimeType: upload.mimeType,
|
|
SizeBytes: upload.sizeBytes,
|
|
StorageDriver: r.storageDriver,
|
|
StoragePath: upload.storagePath,
|
|
CreatedBy: claims.UserID,
|
|
})
|
|
if err != nil {
|
|
_ = os.Remove(upload.storagePath)
|
|
c.JSON(http.StatusInternalServerError, gin.H{"message": "Nao foi possivel registrar o anexo."})
|
|
return
|
|
}
|
|
|
|
r.chatEvents.Publish(message.CalendarItemID, message.Channel)
|
|
|
|
c.JSON(http.StatusCreated, gin.H{"attachment": attachment})
|
|
}
|
|
|
|
func (r Routes) downloadChatAttachment(c *gin.Context) {
|
|
claims, ok := auth.ClaimsFromContext(c)
|
|
if !ok {
|
|
c.JSON(http.StatusUnauthorized, gin.H{"message": "Autenticacao obrigatoria."})
|
|
return
|
|
}
|
|
|
|
viewerUserID := ""
|
|
if claims.Role == users.RoleClientViewer {
|
|
viewerUserID = claims.UserID
|
|
}
|
|
|
|
attachment, err := r.store.FindChatAttachment(c.Request.Context(), c.Param("attachmentId"), viewerUserID)
|
|
if errors.Is(err, ErrAttachmentNotFound) {
|
|
c.JSON(http.StatusNotFound, gin.H{"message": "Anexo nao encontrado."})
|
|
return
|
|
}
|
|
if err != nil {
|
|
c.JSON(http.StatusInternalServerError, gin.H{"message": "Nao foi possivel carregar o anexo."})
|
|
return
|
|
}
|
|
|
|
c.Header("Content-Type", attachment.MimeType)
|
|
c.Header("Content-Disposition", `attachment; filename="`+strings.ReplaceAll(attachment.OriginalFilename, `"`, "")+`"`)
|
|
c.File(attachment.StoragePath)
|
|
}
|
|
|
|
func (r Routes) authorizedChatMessage(c *gin.Context, claims auth.Claims, messageID string, requireOwner bool) (ChatMessage, error) {
|
|
message, err := r.store.FindChatMessage(c.Request.Context(), messageID)
|
|
if errors.Is(err, ErrChatMessageNotFound) {
|
|
c.JSON(http.StatusNotFound, gin.H{"message": "Mensagem nao encontrada."})
|
|
return ChatMessage{}, err
|
|
}
|
|
if err != nil {
|
|
c.JSON(http.StatusInternalServerError, gin.H{"message": "Nao foi possivel carregar a mensagem."})
|
|
return ChatMessage{}, err
|
|
}
|
|
if message.Channel == ChatChannelInternal && claims.Role == users.RoleClientViewer {
|
|
c.JSON(http.StatusForbidden, gin.H{"message": "Permissao insuficiente."})
|
|
return ChatMessage{}, errors.New("forbidden")
|
|
}
|
|
|
|
viewerUserID := ""
|
|
if claims.Role == users.RoleClientViewer {
|
|
viewerUserID = claims.UserID
|
|
}
|
|
if _, err := r.store.FindCalendarItem(c.Request.Context(), message.CalendarItemID, viewerUserID); err != nil {
|
|
if errors.Is(err, ErrCalendarItemNotFound) {
|
|
c.JSON(http.StatusNotFound, gin.H{"message": "Postagem nao encontrada."})
|
|
} else {
|
|
c.JSON(http.StatusInternalServerError, gin.H{"message": "Nao foi possivel carregar a postagem."})
|
|
}
|
|
return ChatMessage{}, err
|
|
}
|
|
|
|
if requireOwner && claims.Role != users.RoleSuperAdmin && (message.CreatedBy == nil || *message.CreatedBy != claims.UserID) {
|
|
c.JSON(http.StatusForbidden, gin.H{"message": "Permissao insuficiente."})
|
|
return ChatMessage{}, errors.New("forbidden")
|
|
}
|
|
|
|
return message, nil
|
|
}
|
|
|
|
func (r Routes) uploadAttachment(c *gin.Context) {
|
|
claims, ok := auth.ClaimsFromContext(c)
|
|
if !ok || (claims.Role != users.RoleSuperAdmin && claims.Role != users.RoleAgencyUser) {
|
|
c.JSON(http.StatusForbidden, gin.H{"message": "Permissao insuficiente."})
|
|
return
|
|
}
|
|
|
|
upload, err := r.saveUploadedFile(c, c.Param("itemId"))
|
|
if err != nil {
|
|
return
|
|
}
|
|
|
|
attachment, err := r.store.CreateAttachment(c.Request.Context(), CreateAttachmentInput{
|
|
CalendarItemID: c.Param("itemId"),
|
|
OriginalFilename: upload.originalFilename,
|
|
StoredFilename: upload.storedFilename,
|
|
MimeType: upload.mimeType,
|
|
SizeBytes: upload.sizeBytes,
|
|
StorageDriver: r.storageDriver,
|
|
StoragePath: upload.storagePath,
|
|
CreatedBy: claims.UserID,
|
|
})
|
|
if err != nil {
|
|
_ = os.Remove(upload.storagePath)
|
|
c.JSON(http.StatusInternalServerError, gin.H{"message": "Nao foi possivel registrar o anexo."})
|
|
return
|
|
}
|
|
|
|
_ = r.store.RecordAudit(c.Request.Context(), claims.UserID, "attachment.created", "calendar_item_attachment", attachment.ID, map[string]any{
|
|
"calendar_item_id": attachment.CalendarItemID,
|
|
"filename": attachment.OriginalFilename,
|
|
"mime_type": attachment.MimeType,
|
|
"size_bytes": attachment.SizeBytes,
|
|
})
|
|
|
|
c.JSON(http.StatusCreated, gin.H{"attachment": attachment})
|
|
}
|
|
|
|
type savedUpload struct {
|
|
originalFilename string
|
|
storedFilename string
|
|
mimeType string
|
|
sizeBytes int64
|
|
storagePath string
|
|
}
|
|
|
|
func (r Routes) saveUploadedFile(c *gin.Context, relativeDir string) (savedUpload, error) {
|
|
c.Request.Body = http.MaxBytesReader(c.Writer, c.Request.Body, r.uploadMaxSizeBytes)
|
|
file, header, err := c.Request.FormFile("file")
|
|
if err != nil {
|
|
c.JSON(http.StatusBadRequest, gin.H{"message": "Envie um arquivo valido."})
|
|
return savedUpload{}, err
|
|
}
|
|
defer file.Close()
|
|
|
|
if header.Size > r.uploadMaxSizeBytes {
|
|
c.JSON(http.StatusBadRequest, gin.H{"message": "Arquivo acima do limite permitido."})
|
|
return savedUpload{}, errors.New("file too large")
|
|
}
|
|
|
|
head := make([]byte, 512)
|
|
n, err := file.Read(head)
|
|
if err != nil && err != io.EOF {
|
|
c.JSON(http.StatusBadRequest, gin.H{"message": "Nao foi possivel ler o arquivo."})
|
|
return savedUpload{}, err
|
|
}
|
|
if _, err := file.Seek(0, io.SeekStart); err != nil {
|
|
c.JSON(http.StatusInternalServerError, gin.H{"message": "Nao foi possivel processar o arquivo."})
|
|
return savedUpload{}, err
|
|
}
|
|
|
|
mimeType := normalizeUploadMimeType(http.DetectContentType(head[:n]), header.Filename)
|
|
if len(r.uploadAllowedMIMEs) > 0 && !r.uploadAllowedMIMEs[mimeType] {
|
|
c.JSON(http.StatusBadRequest, gin.H{"message": "Tipo de arquivo nao permitido."})
|
|
return savedUpload{}, errors.New("invalid mime")
|
|
}
|
|
|
|
storedFilename, err := randomStoredFilename(header.Filename)
|
|
if err != nil {
|
|
c.JSON(http.StatusInternalServerError, gin.H{"message": "Nao foi possivel preparar o arquivo."})
|
|
return savedUpload{}, err
|
|
}
|
|
|
|
storageDir := filepath.Join(r.storageLocalPath, filepath.Clean(relativeDir))
|
|
if err := os.MkdirAll(storageDir, 0o750); err != nil {
|
|
c.JSON(http.StatusInternalServerError, gin.H{"message": "Nao foi possivel preparar o armazenamento."})
|
|
return savedUpload{}, err
|
|
}
|
|
|
|
storagePath := filepath.Join(storageDir, storedFilename)
|
|
destination, err := os.OpenFile(storagePath, os.O_CREATE|os.O_EXCL|os.O_WRONLY, 0o640)
|
|
if err != nil {
|
|
c.JSON(http.StatusInternalServerError, gin.H{"message": "Nao foi possivel salvar o arquivo."})
|
|
return savedUpload{}, err
|
|
}
|
|
defer destination.Close()
|
|
|
|
sizeBytes, err := io.Copy(destination, file)
|
|
if err != nil {
|
|
_ = os.Remove(storagePath)
|
|
c.JSON(http.StatusInternalServerError, gin.H{"message": "Nao foi possivel salvar o arquivo."})
|
|
return savedUpload{}, err
|
|
}
|
|
|
|
return savedUpload{
|
|
originalFilename: filepath.Base(header.Filename),
|
|
storedFilename: storedFilename,
|
|
mimeType: mimeType,
|
|
sizeBytes: sizeBytes,
|
|
storagePath: storagePath,
|
|
}, nil
|
|
}
|
|
|
|
func normalizeUploadMimeType(detected string, filename string) string {
|
|
switch strings.ToLower(filepath.Ext(filename)) {
|
|
case ".docx":
|
|
if detected == "application/zip" || detected == "application/octet-stream" {
|
|
return "application/vnd.openxmlformats-officedocument.wordprocessingml.document"
|
|
}
|
|
case ".doc":
|
|
if detected == "application/octet-stream" {
|
|
return "application/msword"
|
|
}
|
|
}
|
|
|
|
return detected
|
|
}
|
|
|
|
func (r Routes) downloadAttachment(c *gin.Context) {
|
|
claims, ok := auth.ClaimsFromContext(c)
|
|
if !ok {
|
|
c.JSON(http.StatusUnauthorized, gin.H{"message": "Autenticacao obrigatoria."})
|
|
return
|
|
}
|
|
|
|
viewerUserID := ""
|
|
if claims.Role == users.RoleClientViewer {
|
|
viewerUserID = claims.UserID
|
|
}
|
|
|
|
attachment, err := r.store.FindAttachment(c.Request.Context(), c.Param("attachmentId"), viewerUserID)
|
|
if errors.Is(err, ErrAttachmentNotFound) {
|
|
c.JSON(http.StatusNotFound, gin.H{"message": "Anexo nao encontrado."})
|
|
return
|
|
}
|
|
if err != nil {
|
|
c.JSON(http.StatusInternalServerError, gin.H{"message": "Nao foi possivel carregar o anexo."})
|
|
return
|
|
}
|
|
|
|
c.Header("Content-Type", attachment.MimeType)
|
|
c.Header("Content-Disposition", `attachment; filename="`+strings.ReplaceAll(attachment.OriginalFilename, `"`, "")+`"`)
|
|
c.File(attachment.StoragePath)
|
|
}
|
|
|
|
func (r Routes) deleteAttachment(c *gin.Context) {
|
|
claims, ok := auth.ClaimsFromContext(c)
|
|
if !ok || (claims.Role != users.RoleSuperAdmin && claims.Role != users.RoleAgencyUser) {
|
|
c.JSON(http.StatusForbidden, gin.H{"message": "Permissao insuficiente."})
|
|
return
|
|
}
|
|
|
|
attachment, err := r.store.DeleteAttachment(c.Request.Context(), c.Param("attachmentId"))
|
|
if errors.Is(err, ErrAttachmentNotFound) {
|
|
c.JSON(http.StatusNotFound, gin.H{"message": "Anexo nao encontrado."})
|
|
return
|
|
}
|
|
if err != nil {
|
|
c.JSON(http.StatusInternalServerError, gin.H{"message": "Nao foi possivel excluir o anexo."})
|
|
return
|
|
}
|
|
|
|
if attachment.StorageDriver == "local" {
|
|
_ = os.Remove(attachment.StoragePath)
|
|
}
|
|
|
|
_ = r.store.RecordAudit(c.Request.Context(), claims.UserID, "attachment.deleted", "calendar_item_attachment", attachment.ID, map[string]any{
|
|
"calendar_item_id": attachment.CalendarItemID,
|
|
"filename": attachment.OriginalFilename,
|
|
"mime_type": attachment.MimeType,
|
|
"size_bytes": attachment.SizeBytes,
|
|
})
|
|
|
|
c.JSON(http.StatusOK, gin.H{"attachment": attachment})
|
|
}
|
|
|
|
func randomStoredFilename(original string) (string, error) {
|
|
bytes := make([]byte, 16)
|
|
if _, err := rand.Read(bytes); err != nil {
|
|
return "", err
|
|
}
|
|
extension := strings.ToLower(filepath.Ext(original))
|
|
return hex.EncodeToString(bytes) + extension, nil
|
|
}
|
|
|
|
func isValidCalendarItemStatus(status string) bool {
|
|
switch status {
|
|
case "rascunho", "planejado", "em_producao", "em_revisao", "aprovado", "publicado", "cancelado":
|
|
return true
|
|
default:
|
|
return false
|
|
}
|
|
}
|
|
|
|
func isValidChatChannel(channel string) bool {
|
|
switch channel {
|
|
case ChatChannelExternal, ChatChannelInternal:
|
|
return true
|
|
default:
|
|
return false
|
|
}
|
|
}
|