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

Enable patching a document's owner #644

Merged
merged 3 commits into from
Mar 12, 2024
Merged
Show file tree
Hide file tree
Changes from 2 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
109 changes: 109 additions & 0 deletions internal/api/v2/documents.go
Original file line number Diff line number Diff line change
Expand Up @@ -24,6 +24,7 @@ type DocumentPatchRequest struct {
Approvers *[]string `json:"approvers,omitempty"`
Contributors *[]string `json:"contributors,omitempty"`
CustomFields *[]document.CustomField `json:"customFields,omitempty"`
Owner *string `json:"owner,omitempty"`
Status *string `json:"status,omitempty"`
Summary *string `json:"summary,omitempty"`
// Tags []string `json:"tags,omitempty"`
Expand Down Expand Up @@ -522,6 +523,24 @@ func DocumentHandler(srv server.Server) http.Handler {
}
}
}
// Owner.
if req.Owner != nil {
doc.Owners = []string{*req.Owner}

// Give new owner edit access to the document.
if err := srv.GWService.ShareFile(
docID, *req.Owner, "writer"); err != nil {
srv.Logger.Error("error sharing file with new owner",
"error", err,
"method", r.Method,
"path", r.URL.Path,
"doc_id", docID,
"new_owner", *req.Owner)
http.Error(w, "Error patching document",
http.StatusInternalServerError)
return
}
}
// Status.
if req.Status != nil {
doc.Status = *req.Status
Expand Down Expand Up @@ -700,6 +719,13 @@ func DocumentHandler(srv server.Server) http.Handler {
// Document modified time.
model.DocumentModifiedAt = time.Unix(doc.ModifiedTime, 0)

// Owner.
if req.Owner != nil {
model.Owner = &models.User{
EmailAddress: *req.Owner,
}
}

// Status.
if req.Status != nil {
switch *req.Status {
Expand All @@ -722,6 +748,89 @@ func DocumentHandler(srv server.Server) http.Handler {
model.Title = *req.Title
}

// Send email to new owner.
if srv.Config.Email != nil && srv.Config.Email.Enabled &&
req.Owner != nil {
// Get document URL.
docURL, err := getDocumentURL(srv.Config.BaseURL, docID)
if err != nil {
srv.Logger.Error("error getting document URL",
"error", err,
"doc_id", docID,
"method", r.Method,
"path", r.URL.Path,
)
http.Error(w, "Error patching document",
http.StatusInternalServerError)
return
}

// Get name of new document owner.
newOwner := email.User{
EmailAddress: *req.Owner,
}
ppl, err := srv.GWService.SearchPeople(
*req.Owner, "emailAddresses,names")
if err != nil {
srv.Logger.Warn("error searching directory for new owner",
"error", err,
"method", r.Method,
"path", r.URL.Path,
"doc_id", docID,
"person", doc.Owners[0],
)
}
if len(ppl) == 1 && ppl[0].Names != nil {
newOwner.Name = ppl[0].Names[0].DisplayName
}

// Get name of old document owner.
oldOwner := email.User{
EmailAddress: userEmail,
}
ppl, err = srv.GWService.SearchPeople(
userEmail, "emailAddresses,names")
if err != nil {
srv.Logger.Warn("error searching directory for old owner",
"error", err,
"method", r.Method,
"path", r.URL.Path,
"doc_id", docID,
"person", doc.Owners[0],
)
}
if len(ppl) == 1 && ppl[0].Names != nil {
oldOwner.Name = ppl[0].Names[0].DisplayName
}

if err := email.SendNewOwnerEmail(
email.NewOwnerEmailData{
BaseURL: srv.Config.BaseURL,
DocumentShortName: doc.DocNumber,
DocumentStatus: doc.Status,
DocumentTitle: doc.Title,
DocumentType: doc.DocType,
DocumentURL: docURL,
NewDocumentOwner: newOwner,
OldDocumentOwner: oldOwner,
Product: doc.Product,
},
[]string{doc.Owners[0]},
srv.Config.Email.FromAddress,
srv.GWService,
); err != nil {
srv.Logger.Error("error sending new owner email",
"error", err,
"method", r.Method,
"path", r.URL.Path,
"doc_id", docID,
)
http.Error(w, "Error patching document",
http.StatusInternalServerError)
return
}
}

// Send emails to new approvers.
if srv.Config.Email != nil && srv.Config.Email.Enabled {
if len(approversToEmail) > 0 {
Expand Down
117 changes: 116 additions & 1 deletion internal/api/v2/drafts.go
Original file line number Diff line number Diff line change
Expand Up @@ -14,6 +14,7 @@ import (
"github.com/algolia/algoliasearch-client-go/v3/algolia/opt"
"github.com/algolia/algoliasearch-client-go/v3/algolia/search"
"github.com/hashicorp-forge/hermes/internal/config"
"github.com/hashicorp-forge/hermes/internal/email"
"github.com/hashicorp-forge/hermes/internal/server"
"github.com/hashicorp-forge/hermes/pkg/document"
gw "github.com/hashicorp-forge/hermes/pkg/googleworkspace"
Expand Down Expand Up @@ -42,6 +43,7 @@ type DraftsPatchRequest struct {
Approvers *[]string `json:"approvers,omitempty"`
Contributors *[]string `json:"contributors,omitempty"`
CustomFields *[]document.CustomField `json:"customFields,omitempty"`
Owner *string `json:"owner,omitempty"`
Product *string `json:"product,omitempty"`
Summary *string `json:"summary,omitempty"`
// Tags []string `json:"tags,omitempty"`
Expand Down Expand Up @@ -172,6 +174,7 @@ func DraftsHandler(srv server.Server) http.Handler {
"drafts_folder", srv.Config.GoogleWorkspace.DraftsFolder,
"temporary_drafts_folder", srv.Config.GoogleWorkspace.
TemporaryDraftsFolder,
"user", userEmail,
)
http.Error(w, "Error creating document draft",
http.StatusInternalServerError)
Expand Down Expand Up @@ -959,6 +962,14 @@ func DraftsDocumentHandler(srv server.Server) http.Handler {
}

case "PATCH":
// Authorize request.
if !isOwner {
http.Error(w,
"Only owners can patch a draft document",
http.StatusUnauthorized)
return
}

// Decode request. The request struct validates that the request only
// contains fields that are allowed to be patched.
var req DraftsPatchRequest
Expand Down Expand Up @@ -1299,6 +1310,28 @@ func DraftsDocumentHandler(srv server.Server) http.Handler {
// Document modified time.
model.DocumentModifiedAt = time.Unix(doc.ModifiedTime, 0)

// Owner.
if req.Owner != nil {
doc.Owners = []string{*req.Owner}
model.Owner = &models.User{
EmailAddress: *req.Owner,
}

// Share file with new owner.
if err := srv.GWService.ShareFile(
docID, *req.Owner, "writer"); err != nil {
srv.Logger.Error("error sharing file with new owner",
"error", err,
"method", r.Method,
"path", r.URL.Path,
"doc_id", docID,
"new_owner", *req.Owner)
http.Error(w, "Error patching document draft",
http.StatusInternalServerError)
return
}
}

// Product.
if req.Product != nil {
doc.Product = *req.Product
Expand All @@ -1315,7 +1348,6 @@ func DraftsDocumentHandler(srv server.Server) http.Handler {
// Summary.
if req.Summary != nil {
doc.Summary = *req.Summary
// model.Summary = *req.Summary
model.Summary = req.Summary
}

Expand All @@ -1325,6 +1357,89 @@ func DraftsDocumentHandler(srv server.Server) http.Handler {
model.Title = *req.Title
}

// Send email to new owner.
if srv.Config.Email != nil && srv.Config.Email.Enabled &&
req.Owner != nil {
// Get document URL.
docURL, err := getDocumentURL(srv.Config.BaseURL, docID)
if err != nil {
srv.Logger.Error("error getting document URL",
"error", err,
"doc_id", docID,
"method", r.Method,
"path", r.URL.Path,
)
http.Error(w, "Error updating document draft",
http.StatusInternalServerError)
return
}

// Get name of new document owner.
newOwner := email.User{
EmailAddress: *req.Owner,
}
ppl, err := srv.GWService.SearchPeople(
*req.Owner, "emailAddresses,names")
if err != nil {
srv.Logger.Warn("error searching directory for new owner",
"error", err,
"method", r.Method,
"path", r.URL.Path,
"doc_id", docID,
"person", doc.Owners[0],
)
}
if len(ppl) == 1 && ppl[0].Names != nil {
newOwner.Name = ppl[0].Names[0].DisplayName
}

// Get name of old document owner.
oldOwner := email.User{
EmailAddress: userEmail,
}
ppl, err = srv.GWService.SearchPeople(
userEmail, "emailAddresses,names")
if err != nil {
srv.Logger.Warn("error searching directory for old owner",
"error", err,
"method", r.Method,
"path", r.URL.Path,
"doc_id", docID,
"person", doc.Owners[0],
)
}
if len(ppl) == 1 && ppl[0].Names != nil {
oldOwner.Name = ppl[0].Names[0].DisplayName
}

if err := email.SendNewOwnerEmail(
email.NewOwnerEmailData{
BaseURL: srv.Config.BaseURL,
DocumentShortName: doc.DocNumber,
DocumentStatus: doc.Status,
DocumentTitle: doc.Title,
DocumentType: doc.DocType,
DocumentURL: docURL,
NewDocumentOwner: newOwner,
OldDocumentOwner: oldOwner,
Product: doc.Product,
},
[]string{doc.Owners[0]},
srv.Config.Email.FromAddress,
srv.GWService,
); err != nil {
srv.Logger.Error("error sending new owner email",
"error", err,
"method", r.Method,
"path", r.URL.Path,
"doc_id", docID,
)
http.Error(w, "Error updating document draft",
http.StatusInternalServerError)
return
}
}

// Update document in the database.
if err := model.Upsert(srv.DB); err != nil {
srv.Logger.Error("error updating document in the database",
Expand Down
72 changes: 72 additions & 0 deletions internal/email/email.go
Original file line number Diff line number Diff line change
Expand Up @@ -35,6 +35,20 @@ type DocumentApprovedEmailData struct {
Product string
}

type NewOwnerEmailData struct {
BaseURL string
CurrentYear int
DocumentShortName string
DocumentStatus string
DocumentStatusClass string
DocumentTitle string
DocumentType string
DocumentURL string
NewDocumentOwner User
OldDocumentOwner User
Product string
}

type ReviewRequestedEmailData struct {
BaseURL string
CurrentYear int
Expand Down Expand Up @@ -121,6 +135,64 @@ func SendDocumentApprovedEmail(
return err
}

func SendNewOwnerEmail(
data NewOwnerEmailData,
to []string,
from string,
svc *gw.Service,
) error {
// Validate data.
if err := validation.ValidateStruct(&data,
validation.Field(&data.BaseURL, validation.Required),
validation.Field(&data.DocumentShortName, validation.Required),
validation.Field(&data.DocumentStatus, validation.Required),
validation.Field(&data.DocumentTitle, validation.Required),
validation.Field(&data.DocumentType, validation.Required),
validation.Field(&data.DocumentURL, validation.Required),
validation.Field(&data.NewDocumentOwner, validation.Required),
validation.Field(&data.OldDocumentOwner, validation.Required),
validation.Field(&data.Product, validation.Required),
); err != nil {
return fmt.Errorf("error validating email data: %w", err)
}
if err := validation.ValidateStruct(&data.NewDocumentOwner,
validation.Field(&data.NewDocumentOwner.EmailAddress, validation.Required),
); err != nil {
return fmt.Errorf("error validating new document owner: %w", err)
}
if err := validation.ValidateStruct(&data.OldDocumentOwner,
validation.Field(&data.OldDocumentOwner.EmailAddress, validation.Required),
); err != nil {
return fmt.Errorf("error validating old document owner: %w", err)
}

// Apply template.
var body bytes.Buffer
tmpl, err := template.ParseFS(tmplFS, "templates/new-owner.html")
if err != nil {
return fmt.Errorf("error parsing template: %w", err)
}

// Set current year.
data.CurrentYear = time.Now().Year()

// Set status class.
data.DocumentStatusClass = dasherizeStatus(data.DocumentStatus)

if err := tmpl.Execute(&body, data); err != nil {
return fmt.Errorf("error executing template: %w", err)
}

// Send email.
_, err = svc.SendEmail(
to,
from,
fmt.Sprintf("%s transferred to you", data.DocumentShortName),
body.String(),
)
return err
}

func SendReviewRequestedEmail(
d ReviewRequestedEmailData,
to []string,
Expand Down
Loading
Loading