diff options
author | Vidhu Kant Sharma <vidhukant@vidhukant.com> | 2023-09-03 22:02:56 +0530 |
---|---|---|
committer | Vidhu Kant Sharma <vidhukant@vidhukant.com> | 2023-09-03 22:02:56 +0530 |
commit | c6bc8d0c6d1c1ab5d26b9e47e0248002d22ecf8f (patch) | |
tree | a80b66210b6f45aaa8b3c0c39baeda451b38f765 /customer/validators.go | |
parent | 6922e09f46a24b7bd70db5e78ab1c4a77e59303c (diff) |
moved contact details to customer model for simplicity
Diffstat (limited to 'customer/validators.go')
-rw-r--r-- | customer/validators.go | 59 |
1 files changed, 40 insertions, 19 deletions
diff --git a/customer/validators.go b/customer/validators.go index bfd244f..2a37394 100644 --- a/customer/validators.go +++ b/customer/validators.go @@ -29,8 +29,9 @@ import ( func validateContactField(field, value string, userId uint) error { if value != "" { var count int64 - err := db.Model(&CustomerContact{}). - Where(field + " = ? and user_id = ?", value, userId). + err := db.Model(&Customer{}). + //Select(""). + Where("user_id = ? and " + field + " = ?", userId, value). Count(&count). Error @@ -55,29 +56,15 @@ func validateContactField(field, value string, userId uint) error { return nil } -func (c *CustomerContact) validate() error { +func (c *Customer) validate() error { // trim whitespaces c.Name = strings.TrimSpace(c.Name) + c.Gstin = strings.TrimSpace(c.Gstin) + c.ContactName = strings.TrimSpace(c.Name) c.Phone = strings.TrimSpace(c.Phone) c.Email = strings.TrimSpace(c.Email) c.Website = strings.TrimSpace(c.Website) - var err error - for _, i := range [][]string{{"phone", c.Phone}, {"email", c.Email}, {"website", c.Website}} { - err = validateContactField(i[0], i[1], c.UserID) - if err != nil { - return err - } - } - - return nil -} - -func (c *Customer) validate() error { - // trim whitespaces - c.Name = strings.TrimSpace(c.Name) - c.Gstin = strings.TrimSpace(c.Gstin) - // don't validate if GSTIN is empty if c.Gstin != "" { // GSTIN regex validation @@ -103,5 +90,39 @@ func (c *Customer) validate() error { } } + var err error + for _, i := range [][]string{{"phone", c.Phone}, {"email", c.Email}, {"website", c.Website}} { + err = validateContactField(i[0], i[1], c.UserID) + if err != nil { + return err + } + } + + return nil +} + +func checkCustomerOwnership(customerId, userId uint) error { + var customer Customer + err := db. + Select("id", "user_id"). + Where("id = ?", customerId). + Find(&customer). + Error + + // TODO: handle potential errors + if err != nil { + return err + } + + // customer doesn't exist + if customer.ID == 0 { + return errors.ErrNotFound + } + + // user doesn't own this customer + if customer.UserID != userId { + return errors.ErrForbidden + } + return nil } |