File size: 14,144 Bytes
83a59ca
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
package handlers

import (
	"context"
	"fmt"

	"github.com/NdoleStudio/httpsms/pkg/entities"
	"github.com/NdoleStudio/httpsms/pkg/repositories"
	"github.com/NdoleStudio/httpsms/pkg/requests"
	"github.com/NdoleStudio/httpsms/pkg/services"
	"github.com/NdoleStudio/httpsms/pkg/telemetry"
	"github.com/NdoleStudio/httpsms/pkg/validators"
	"github.com/NdoleStudio/stacktrace"
	"github.com/davecgh/go-spew/spew"
	"github.com/gofiber/fiber/v3"
	"github.com/google/uuid"
)

// ContactHandler handles contact http requests.
type ContactHandler struct {
	handler
	logger             telemetry.Logger
	tracer             telemetry.Tracer
	validator          *validators.ContactHandlerValidator
	service            *services.ContactService
	entitlementService *services.EntitlementService
}

// NewContactHandler creates a new ContactHandler.
func NewContactHandler(
	logger telemetry.Logger,
	tracer telemetry.Tracer,
	validator *validators.ContactHandlerValidator,
	service *services.ContactService,
	entitlementService *services.EntitlementService,
) (h *ContactHandler) {
	return &ContactHandler{
		logger:             logger.WithService(fmt.Sprintf("%T", h)),
		tracer:             tracer,
		validator:          validator,
		service:            service,
		entitlementService: entitlementService,
	}
}

// RegisterRoutes registers the routes for the ContactHandler.
func (h *ContactHandler) RegisterRoutes(router fiber.Router, middlewares ...fiber.Handler) {
	h.register(router, fiber.MethodGet, "/v1/contacts", middlewares, h.Index)
	h.register(router, fiber.MethodPost, "/v1/contacts", middlewares, h.Store)
	h.register(router, fiber.MethodPost, "/v1/contacts/upload", middlewares, h.Upload)
	h.register(router, fiber.MethodPut, "/v1/contacts/:contactID", middlewares, h.Update)
	h.register(router, fiber.MethodDelete, "/v1/contacts/:contactID", middlewares, h.Delete)
}

// Index lists contacts for the authenticated user.
// @Summary      List contacts
// @Description  Returns the paginated list of contacts for the authenticated user. The top-level "total" field is the number of contacts matching the query filter, independent of skip/limit, so clients can drive server-side pagination.
// @Security	 ApiKeyAuth
// @Tags         Contacts
// @Accept       json
// @Produce      json
// @Param        skip	query  int  	false	"number of contacts to skip"	minimum(0)
// @Param        query	query  string  	false 	"filter contacts containing query"
// @Param        sort_by	query  string  	false 	"field to sort contacts by" Enums(name, updated_at)
// @Param        sort_descending	query  bool  	false 	"sort contacts in descending order"
// @Param        limit	query  int  	false	"number of contacts to return"	minimum(1)	maximum(100)
// @Success      200 	{object}	responses.ContactsResponse
// @Failure      400	{object}	responses.BadRequest
// @Failure 	 401    {object}	responses.Unauthorized
// @Failure      422	{object}	responses.UnprocessableEntity
// @Failure      500	{object}	responses.InternalServerError
// @Router       /contacts [get]
func (h *ContactHandler) Index(c fiber.Ctx) error {
	ctx, span, ctxLogger := h.tracer.StartFromFiberCtxWithLogger(c, h.logger)
	defer span.End()

	var request requests.ContactIndex
	if err := c.Bind().Query(&request); err != nil {
		ctxLogger.Warn(stacktrace.Propagatef(err, "cannot marshall params [%s] into %T", c.OriginalURL(), request))
		return h.responseBadRequest(c, err)
	}

	sanitized := request.Sanitize()
	if errors := h.validator.ValidateIndex(ctx, sanitized); len(errors) != 0 {
		ctxLogger.Warn(stacktrace.NewErrorf("validation errors [%s], while listing contacts [%+#v]", spew.Sdump(errors), sanitized))
		return h.responseUnprocessableEntity(c, errors, "validation errors while listing contacts")
	}

	userID := h.userIDFomContext(c)
	params := sanitized.ToIndexParams()
	contacts, err := h.service.Index(ctx, userID, params)
	if err != nil {
		ctxLogger.Error(stacktrace.Propagatef(err, "cannot list contacts for user [%s]", userID))
		return h.responseInternalServerError(c)
	}

	total, err := h.service.Count(ctx, userID, params)
	if err != nil {
		ctxLogger.Error(stacktrace.Propagatef(err, "cannot count contacts for user [%s]", userID))
		return h.responseInternalServerError(c)
	}

	return h.responseOKWithTotal(c, fmt.Sprintf("fetched %d %s", len(*contacts), h.pluralize("contact", len(*contacts))), contacts, total)
}

// Store creates one or many contacts.
// @Summary      Create one or many contacts
// @Description  Creates a single contact or a batch of contacts. Accepts a JSON array or an object with a "contacts" array.
// @Security	 ApiKeyAuth
// @Tags         Contacts
// @Accept       json
// @Produce      json
// @Param        payload   body 		requests.ContactStoreRequest 	true 	"Contact(s) to create"
// @Success      201 	{object}	responses.ContactsCreatedResponse
// @Failure      400	{object}	responses.BadRequest
// @Failure 	 401    {object}	responses.Unauthorized
// @Failure 	 402	{object}	responses.PaymentRequired
// @Failure      422	{object}	responses.UnprocessableEntity
// @Failure      500	{object}	responses.InternalServerError
// @Router       /contacts [post]
func (h *ContactHandler) Store(c fiber.Ctx) error {
	ctx, span, ctxLogger := h.tracer.StartFromFiberCtxWithLogger(c, h.logger)
	defer span.End()

	var request requests.ContactStoreRequest
	if err := c.Bind().Body(&request); err != nil {
		ctxLogger.Warn(stacktrace.Propagatef(err, "cannot marshall body [%s] into %T", c.Body(), request))
		return h.responseBadRequest(c, err)
	}

	sanitized := request.Sanitize()
	if errors := h.validator.ValidateStore(ctx, sanitized); len(errors) != 0 {
		ctxLogger.Warn(stacktrace.NewErrorf("validation errors [%s], while creating contacts", spew.Sdump(errors)))
		return h.responseUnprocessableEntity(c, errors, "validation errors while creating contacts")
	}

	userID := h.userIDFomContext(c)
	contacts := sanitized.ToContacts(userID)
	result, err := h.checkCreateEntitlement(ctx, userID, len(contacts))
	if err != nil {
		ctxLogger.Error(stacktrace.Propagatef(err, "cannot check contact entitlement for user [%s]", userID))
		return h.responseInternalServerError(c)
	}
	if !result.Allowed {
		return h.responsePaymentRequired(c, result.Message)
	}

	if err := h.service.CreateMany(ctx, userID, contacts); err != nil {
		ctxLogger.Error(stacktrace.Propagatef(err, "cannot create [%d] contacts for user [%s]", len(contacts), userID))
		return h.responseInternalServerError(c)
	}

	return h.responseCreated(c, fmt.Sprintf("created %d %s", len(contacts), h.pluralize("contact", len(contacts))), contacts)
}

// Upload imports contacts from a CSV file.
// @Summary      Import contacts from CSV
// @Description  Uploads a CSV file (multipart field "document") of contacts. Columns: Name, Emails, PhoneNumbers (multi-values separated by ";").
// @Security	 ApiKeyAuth
// @Tags         Contacts
// @Accept       multipart/form-data
// @Produce      json
// @Param        document	formData	file	true	"CSV file of contacts"
// @Success      201 	{object}	responses.ContactsCreatedResponse
// @Failure      400	{object}	responses.BadRequest
// @Failure 	 401    {object}	responses.Unauthorized
// @Failure 	 402	{object}	responses.PaymentRequired
// @Failure      422	{object}	responses.UnprocessableEntity
// @Failure      500	{object}	responses.InternalServerError
// @Router       /contacts/upload [post]
func (h *ContactHandler) Upload(c fiber.Ctx) error {
	ctx, span, ctxLogger := h.tracer.StartFromFiberCtxWithLogger(c, h.logger)
	defer span.End()

	file, err := c.FormFile("document")
	if err != nil {
		ctxLogger.Warn(stacktrace.Propagatef(err, "cannot fetch file with name [%s] from request", "document"))
		return h.responseBadRequest(c, err)
	}

	userID := h.userIDFomContext(c)
	items, errors := h.validator.ValidateUpload(ctx, userID, file)
	if len(errors) != 0 {
		ctxLogger.Warn(stacktrace.NewErrorf("validation errors [%s], while importing contacts from CSV [%s]", spew.Sdump(errors), file.Filename))
		return h.responseUnprocessableEntity(c, errors, "validation errors while importing contacts")
	}

	// items are already sanitized by ValidateUpload (SanitizeContactItem), so
	// build the persistable records directly without re-sanitizing.
	request := requests.ContactStoreRequest{Contacts: items}
	contacts := request.ToContacts(userID)
	result, err := h.checkCreateEntitlement(ctx, userID, len(contacts))
	if err != nil {
		ctxLogger.Error(stacktrace.Propagatef(err, "cannot check contact entitlement for user [%s]", userID))
		return h.responseInternalServerError(c)
	}
	if !result.Allowed {
		return h.responsePaymentRequired(c, result.Message)
	}

	if err = h.service.CreateMany(ctx, userID, contacts); err != nil {
		ctxLogger.Error(stacktrace.Propagatef(err, "cannot import [%d] contacts for user [%s]", len(contacts), userID))
		return h.responseInternalServerError(c)
	}

	return h.responseCreated(c, fmt.Sprintf("imported %d %s", len(contacts), h.pluralize("contact", len(contacts))), contacts)
}

// Update updates a single contact.
// @Summary      Update a contact
// @Description  Updates the details of a single contact.
// @Security	 ApiKeyAuth
// @Tags         Contacts
// @Accept       json
// @Produce      json
// @Param 		 contactID	path		string 							true 	"ID of the contact"
// @Param        payload   	body 		requests.ContactUpdateRequest 	true 	"Contact details to update"
// @Success      200 		{object}	responses.ContactResponse
// @Failure      400		{object}	responses.BadRequest
// @Failure 	 401    	{object}	responses.Unauthorized
// @Failure      404		{object}	responses.NotFound
// @Failure      422		{object}	responses.UnprocessableEntity
// @Failure      500		{object}	responses.InternalServerError
// @Router       /contacts/{contactID} [put]
func (h *ContactHandler) Update(c fiber.Ctx) error {
	ctx, span, ctxLogger := h.tracer.StartFromFiberCtxWithLogger(c, h.logger)
	defer span.End()

	contactID := c.Params("contactID")
	if errors := h.validator.ValidateUUID(contactID, "contactID"); len(errors) != 0 {
		ctxLogger.Warn(stacktrace.NewErrorf("validation errors [%s], while updating contact [%s]", spew.Sdump(errors), contactID))
		return h.responseUnprocessableEntity(c, errors, "validation errors while updating contact")
	}

	var request requests.ContactUpdateRequest
	if err := c.Bind().Body(&request); err != nil {
		ctxLogger.Warn(stacktrace.Propagatef(err, "cannot marshall body into %T", request))
		return h.responseBadRequest(c, err)
	}

	sanitized := request.Sanitize()
	if errors := h.validator.ValidateUpdate(ctx, sanitized); len(errors) != 0 {
		ctxLogger.Warn(stacktrace.NewErrorf("validation errors [%s], while updating contact [%s]", spew.Sdump(errors), contactID))
		return h.responseUnprocessableEntity(c, errors, "validation errors while updating contact")
	}

	userID := h.userIDFomContext(c)
	contact, err := h.service.Get(ctx, userID, uuid.MustParse(contactID))
	if stacktrace.GetCode(err) == repositories.ErrCodeNotFound {
		return h.responseNotFound(c, fmt.Sprintf("cannot find contact with ID [%s]", contactID))
	}
	if err != nil {
		ctxLogger.Error(stacktrace.Propagatef(err, "cannot load contact [%s] for user [%s]", contactID, userID))
		return h.responseInternalServerError(c)
	}

	previousPhoneNumbers := append([]string{}, contact.PhoneNumbers...)
	sanitized.ApplyTo(contact)
	if err = h.service.Update(ctx, contact, previousPhoneNumbers); err != nil {
		ctxLogger.Error(stacktrace.Propagatef(err, "cannot update contact [%s] for user [%s]", contactID, userID))
		return h.responseInternalServerError(c)
	}

	return h.responseOK(c, "contact updated successfully", contact)
}

// Delete removes a single contact.
// @Summary      Delete a contact
// @Description  Deletes a single contact from the database.
// @Security	 ApiKeyAuth
// @Tags         Contacts
// @Accept       json
// @Produce      json
// @Param 		 contactID	path		string 	true	"ID of the contact"
// @Success      204  	{object} 	responses.NoContent
// @Failure      400  	{object}  	responses.BadRequest
// @Failure 	 401    {object}	responses.Unauthorized
// @Failure 	 404	{object}	responses.NotFound
// @Failure      422  	{object} 	responses.UnprocessableEntity
// @Failure      500  	{object}  	responses.InternalServerError
// @Router       /contacts/{contactID} [delete]
func (h *ContactHandler) Delete(c fiber.Ctx) error {
	ctx, span, ctxLogger := h.tracer.StartFromFiberCtxWithLogger(c, h.logger)
	defer span.End()

	contactID := c.Params("contactID")
	if errors := h.validator.ValidateUUID(contactID, "contactID"); len(errors) != 0 {
		ctxLogger.Warn(stacktrace.NewErrorf("validation errors [%s], while deleting contact [%s]", spew.Sdump(errors), contactID))
		return h.responseUnprocessableEntity(c, errors, "validation errors while deleting contact")
	}

	userID := h.userIDFomContext(c)

	// Load first so a missing contact for the authenticated user returns 404
	// instead of silently succeeding via a 0-row DELETE. This also prevents
	// leaking whether another user's contact exists.
	if _, err := h.service.Get(ctx, userID, uuid.MustParse(contactID)); err != nil {
		if stacktrace.GetCode(err) == repositories.ErrCodeNotFound {
			return h.responseNotFound(c, fmt.Sprintf("cannot find contact with ID [%s]", contactID))
		}
		ctxLogger.Error(stacktrace.Propagatef(err, "cannot load contact [%s] for user [%s]", contactID, userID))
		return h.responseInternalServerError(c)
	}

	if err := h.service.Delete(ctx, userID, uuid.MustParse(contactID)); err != nil {
		ctxLogger.Error(stacktrace.Propagatef(err, "cannot delete contact [%s] for user [%s]", contactID, userID))
		return h.responseInternalServerError(c)
	}

	return h.responseNoContent(c, "contact deleted successfully")
}

func (h *ContactHandler) checkCreateEntitlement(
	ctx context.Context,
	userID entities.UserID,
	additionalCount int,
) (*services.EntitlementCheckResult, error) {
	return h.entitlementService.CheckAdditional(ctx, userID, entities.EntityNameContact, additionalCount, func() (int, error) {
		count, err := h.service.Count(ctx, userID, repositories.IndexParams{})
		return int(count), err
	})
}