send all files

This commit is contained in:
2024-07-21 00:15:14 -03:00
parent 1e8cda0139
commit c9464c4a6f
72 changed files with 6335 additions and 0 deletions
+24
View File
@@ -0,0 +1,24 @@
package authmodule
import (
authdto "api/application/auth/dto"
"api/models/api"
)
type Controller interface {
Authorization(data *authdto.AuthDto) (*api.Response, int, error)
}
type controller struct {
AuthService
}
func newController(service AuthService) Controller {
return &controller{
AuthService: service,
}
}
func (c *controller) Authorization(data *authdto.AuthDto) (*api.Response, int, error) {
return c.AuthService.Authorization(data)
}
+34
View File
@@ -0,0 +1,34 @@
package authdto
import (
"api/libs/logger"
"errors"
"github.com/go-playground/validator/v10"
)
type AuthDto struct {
Username string `json:"username" validate:"required"`
Password string `json:"password" validate:"required"`
}
func (d *AuthDto) Validate() error {
validate := validator.New()
err := validate.Struct(d)
if err != nil {
// this check is only needed when your code could produce
// an invalid value for validation such as interface with nil
// value most including myself do not usually have code like this.
if _, ok := err.(*validator.InvalidValidationError); ok {
logger.Development.Info(err.Error())
}
for _, e := range err.(validator.ValidationErrors) {
err = errors.New(e.Field() + " " + e.Tag())
}
}
return err
}
+10
View File
@@ -0,0 +1,10 @@
package authmodule
import "github.com/gofiber/fiber/v2"
// apply routes in app fiber, with controllers and services defined
func AuthModuleDecorator(app *fiber.App) {
s := newService()
c := newController(s)
newRoutes(c, app)
}
+51
View File
@@ -0,0 +1,51 @@
package authmodule
import (
authdto "api/application/auth/dto"
"api/libs/logger"
"api/models/api"
"github.com/gofiber/fiber/v2"
)
func newRoutes(c Controller, app *fiber.App) {
app.Post("/authorization", authorization(c))
}
func authorization(controller Controller) func(*fiber.Ctx) error {
return func(c *fiber.Ctx) error {
auth := &authdto.AuthDto{}
err := c.BodyParser(auth)
if err != nil {
logger.Production.Info(err.Error())
c.Status(fiber.StatusBadRequest)
return c.JSON(api.Response{
Error: true,
ErrorMessage: err.Error(),
})
}
err = auth.Validate()
if err != nil {
logger.Production.Info(err.Error())
c.Status(fiber.StatusBadRequest)
return c.JSON(api.Response{
Error: true,
ErrorMessage: err.Error(),
})
}
response, statusCode, err := controller.Authorization(auth)
if err != nil {
logger.Production.Info(err.Error())
c.Status(statusCode)
return c.JSON(api.Response{
Error: true,
ErrorMessage: err.Error(),
})
}
return c.Status(statusCode).JSON(response)
}
}
+69
View File
@@ -0,0 +1,69 @@
package authmodule
import (
authdto "api/application/auth/dto"
"api/libs/jwt"
"api/libs/postgres"
"api/models/api"
"api/models/users"
"context"
"github.com/alexedwards/argon2id"
"github.com/gofiber/fiber/v2"
)
type AuthService interface {
Authorization(data *authdto.AuthDto) (*api.Response, int, error)
}
type authService struct {
userRepository *users.Queries
ctx context.Context
}
func newService() AuthService {
return &authService{
userRepository: users.New(postgres.Pool),
ctx: context.Background(),
}
}
func (a *authService) Authorization(data *authdto.AuthDto) (*api.Response, int, error) {
userL, err := a.userRepository.GetUser(a.ctx, data.Username)
if err != nil {
return &api.Response{Error: true, ErrorMessage: err.Error()}, fiber.StatusUnauthorized, err
}
match, err := argon2id.ComparePasswordAndHash(data.Password, userL.Password)
if err != nil {
return &api.Response{Error: true, ErrorMessage: err.Error()}, fiber.StatusUnauthorized, err
}
if match {
dic := map[string]interface{}{
"id": userL.User,
}
token, err := jwt.EncodeJwt(dic)
if err != nil {
return &api.Response{Error: true, ErrorMessage: err.Error()}, fiber.StatusInternalServerError, err
}
payload := struct {
User struct {
Id string `json:"id"`
Username string `json:"username"`
} `json:"user"`
Token string `json:"token"`
}{}
payload.User.Username = userL.Username
payload.User.Id = userL.User
payload.Token = token
return &api.Response{Error: false, Payload: payload}, fiber.StatusOK, err
}
return nil, fiber.StatusUnauthorized, nil
}
+45
View File
@@ -0,0 +1,45 @@
package productsmodule
import (
productdto "api/application/products/dto"
"api/models/api"
)
// Controller defines the methods to be exposed in Controller layer
type Controller interface {
CreateProduct(userId string, data *productdto.ProductDto) (*api.Response, int, error)
UpdateProduct(userId string, data *productdto.ProductDto) (*api.Response, int, error)
VerifyCode(data *productdto.ValidateCodeDto) (*api.Response, int, error)
GetProducts() (*api.Response, int, error)
DeleteProduct(data *productdto.DeleteProductDto) (*api.Response, int, error)
}
type controller struct {
ProductsService
}
func newController(service ProductsService) Controller {
return &controller{
ProductsService: service,
}
}
func (c *controller) CreateProduct(userId string, data *productdto.ProductDto) (*api.Response, int, error) {
return c.ProductsService.CreateProduct(userId, data)
}
func (c *controller) UpdateProduct(userId string, data *productdto.ProductDto) (*api.Response, int, error) {
return c.ProductsService.UpdateProduct(userId, data)
}
func (c *controller) VerifyCode(data *productdto.ValidateCodeDto) (*api.Response, int, error) {
return c.ProductsService.VerifyCode(data)
}
func (c *controller) GetProducts() (*api.Response, int, error) {
return c.ProductsService.GetProducts()
}
func (c *controller) DeleteProduct(data *productdto.DeleteProductDto) (*api.Response, int, error) {
return c.ProductsService.DeleteProduct(data)
}
@@ -0,0 +1,28 @@
package productdto
import (
"api/libs/logger"
"errors"
"github.com/go-playground/validator/v10"
)
type DeleteProductDto struct {
Codigo string `json:"codigo" validate:"required"`
}
func (d *DeleteProductDto) Validate() error {
validate := validator.New()
err := validate.Struct(d)
if err != nil {
if _, ok := err.(*validator.InvalidValidationError); ok {
logger.Development.Info(err.Error())
}
for _, e := range err.(validator.ValidationErrors) {
err = errors.New(e.Field() + " " + e.Tag())
}
}
return err
}
@@ -0,0 +1,38 @@
package productdto
import (
"api/libs/logger"
"errors"
"github.com/go-playground/validator/v10"
)
type ProductDto struct {
Nome string `json:"nome" validate:"required"`
Codigo string `json:"codigo" validate:"required"`
EstoqueTotal int64 `json:"estoqueTotal" validate:"required"`
EstoqueCorte int64 `json:"estoqueCorte" validate:"required"`
PrecoDe float32 `json:"precoDe" validate:"required"`
PrecoPor float32 `json:"precoPor" validate:"required"`
}
func (d *ProductDto) Validate() error {
validate := validator.New()
err := validate.Struct(d)
if err != nil {
if _, ok := err.(*validator.InvalidValidationError); ok {
logger.Development.Info(err.Error())
}
for _, e := range err.(validator.ValidationErrors) {
err = errors.New(e.Field() + " " + e.Tag())
}
}
if d.PrecoPor > d.PrecoDe {
err = errors.New(`o "preço de" não pode ser inferior ao "preço por"`)
}
return err
}
@@ -0,0 +1,28 @@
package productdto
import (
"api/libs/logger"
"errors"
"github.com/go-playground/validator/v10"
)
type ValidateCodeDto struct {
Codigo string `json:"codigo" validate:"required"`
}
func (d *ValidateCodeDto) Validate() error {
validate := validator.New()
err := validate.Struct(d)
if err != nil {
if _, ok := err.(*validator.InvalidValidationError); ok {
logger.Development.Info(err.Error())
}
for _, e := range err.(validator.ValidationErrors) {
err = errors.New(e.Field() + " " + e.Tag())
}
}
return err
}
+10
View File
@@ -0,0 +1,10 @@
package productsmodule
import "github.com/gofiber/fiber/v2"
// apply routes in app fiber, with controllers and services defined
func ProductstModuleDecorator(app *fiber.App) {
s := newService()
c := newController(s)
newRoutes(c, app)
}
+193
View File
@@ -0,0 +1,193 @@
package productsmodule
import (
productdto "api/application/products/dto"
"api/libs/jwt"
"api/libs/logger"
"api/models/api"
"github.com/gofiber/fiber/v2"
)
func newRoutes(c Controller, app *fiber.App) {
app.Post("/product", jwt.JwtProtected(), createProduct(c))
app.Put("/product", jwt.JwtProtected(), updateProduct(c))
app.Post("/product/validate", jwt.JwtProtected(), validateCode(c))
app.Get("/products", jwt.JwtProtected(), getProducts(c))
app.Delete("/product", jwt.JwtProtected(), deleteProduct(c))
}
func getProducts(controller Controller) func(*fiber.Ctx) error {
return func(c *fiber.Ctx) error {
response, statusCode, err := controller.GetProducts()
if err != nil {
logger.Production.Info(err.Error())
c.Status(fiber.StatusInternalServerError)
return c.JSON(api.Response{
Error: true,
ErrorMessage: err.Error(),
})
}
return c.Status(statusCode).JSON(response)
}
}
func createProduct(controller Controller) func(*fiber.Ctx) error {
return func(c *fiber.Ctx) error {
userId := jwt.DecodeJwtSingleKey(c, "id").(string)
product := &productdto.ProductDto{}
err := c.BodyParser(product)
if err != nil {
logger.Production.Info(err.Error())
c.Status(fiber.StatusBadRequest)
return c.JSON(api.Response{
Error: true,
ErrorMessage: err.Error(),
})
}
err = product.Validate()
if err != nil {
logger.Production.Info(err.Error())
c.Status(fiber.StatusBadRequest)
return c.JSON(api.Response{
Error: true,
ErrorMessage: err.Error(),
})
}
response, statusCode, err := controller.CreateProduct(userId, product)
if err != nil {
logger.Production.Info(err.Error())
c.Status(fiber.StatusInternalServerError)
return c.JSON(api.Response{
Error: true,
ErrorMessage: err.Error(),
})
}
return c.Status(statusCode).JSON(response)
}
}
func updateProduct(controller Controller) func(*fiber.Ctx) error {
return func(c *fiber.Ctx) error {
userId := jwt.DecodeJwtSingleKey(c, "id").(string)
product := &productdto.ProductDto{}
err := c.BodyParser(product)
if err != nil {
logger.Production.Info(err.Error())
c.Status(fiber.StatusBadRequest)
return c.JSON(api.Response{
Error: true,
ErrorMessage: err.Error(),
})
}
err = product.Validate()
if err != nil {
logger.Production.Info(err.Error())
c.Status(fiber.StatusBadRequest)
return c.JSON(api.Response{
Error: true,
ErrorMessage: err.Error(),
})
}
response, statusCode, err := controller.UpdateProduct(userId, product)
if err != nil {
logger.Production.Info(err.Error())
c.Status(fiber.StatusInternalServerError)
return c.JSON(api.Response{
Error: true,
ErrorMessage: err.Error(),
})
}
return c.Status(statusCode).JSON(response)
}
}
func validateCode(controller Controller) func(*fiber.Ctx) error {
return func(c *fiber.Ctx) error {
codeValidate := &productdto.ValidateCodeDto{}
err := c.BodyParser(codeValidate)
if err != nil {
logger.Production.Info(err.Error())
c.Status(fiber.StatusBadRequest)
return c.JSON(api.Response{
Error: true,
ErrorMessage: err.Error(),
})
}
err = codeValidate.Validate()
if err != nil {
logger.Production.Info(err.Error())
c.Status(fiber.StatusBadRequest)
return c.JSON(api.Response{
Error: true,
ErrorMessage: err.Error(),
})
}
response, statusCode, err := controller.VerifyCode(codeValidate)
if err != nil {
logger.Production.Info(err.Error())
c.Status(fiber.StatusInternalServerError)
return c.JSON(api.Response{
Error: true,
ErrorMessage: err.Error(),
})
}
return c.Status(statusCode).JSON(response)
}
}
func deleteProduct(controller Controller) func(*fiber.Ctx) error {
return func(c *fiber.Ctx) error {
delete := &productdto.DeleteProductDto{}
err := c.BodyParser(delete)
if err != nil {
logger.Production.Info(err.Error())
c.Status(fiber.StatusBadRequest)
return c.JSON(api.Response{
Error: true,
ErrorMessage: err.Error(),
})
}
err = delete.Validate()
if err != nil {
logger.Production.Info(err.Error())
c.Status(fiber.StatusBadRequest)
return c.JSON(api.Response{
Error: true,
ErrorMessage: err.Error(),
})
}
response, statusCode, err := controller.DeleteProduct(delete)
if err != nil {
logger.Production.Info(err.Error())
c.Status(fiber.StatusInternalServerError)
return c.JSON(api.Response{
Error: true,
ErrorMessage: err.Error(),
})
}
return c.Status(statusCode).JSON(response)
}
}
+112
View File
@@ -0,0 +1,112 @@
package productsmodule
import (
productdto "api/application/products/dto"
"api/libs/logger"
"api/libs/postgres"
"api/models/api"
"api/models/products"
"context"
"github.com/gofiber/fiber/v2"
"github.com/jackc/pgx/v5"
)
type ProductsService interface {
CreateProduct(userId string, data *productdto.ProductDto) (*api.Response, int, error)
UpdateProduct(userId string, data *productdto.ProductDto) (*api.Response, int, error)
VerifyCode(data *productdto.ValidateCodeDto) (*api.Response, int, error)
GetProducts() (*api.Response, int, error)
DeleteProduct(data *productdto.DeleteProductDto) (*api.Response, int, error)
}
type productsService struct {
productsRepository *products.Queries
ctx context.Context
}
func newService() ProductsService {
return &productsService{
productsRepository: products.New(postgres.Pool),
ctx: context.Background(),
}
}
func (p *productsService) CreateProduct(userId string, data *productdto.ProductDto) (*api.Response, int, error) {
estoqueDisponivel := data.EstoqueTotal - data.EstoqueCorte
newProduct, err := p.productsRepository.CreateProduct(p.ctx, userId, products.CreateProductParams{
Nome: data.Nome,
Codigo: data.Codigo,
EstoqueTotal: data.EstoqueTotal,
EstoqueCorte: data.EstoqueCorte,
EstoqueDisponivel: estoqueDisponivel,
PrecoDe: data.PrecoDe,
PrecoPor: data.PrecoPor,
})
if err != nil {
logger.Production.Info(err.Error())
return &api.Response{Error: true, ErrorMessage: err.Error(), Payload: "error insert product"}, fiber.StatusInternalServerError, err
}
return &api.Response{Error: false, Payload: newProduct}, fiber.StatusOK, nil
}
func (p *productsService) VerifyCode(data *productdto.ValidateCodeDto) (*api.Response, int, error) {
_, err := p.productsRepository.GetProduct(p.ctx, data.Codigo)
if err != nil {
if err == pgx.ErrNoRows {
return &api.Response{Error: false, Payload: false}, fiber.StatusOK, nil
}
logger.Production.Info(err.Error())
return &api.Response{Error: true, ErrorMessage: err.Error(), Payload: "error verify code product"}, fiber.StatusInternalServerError, err
}
return &api.Response{Error: false, Payload: true}, fiber.StatusOK, nil
}
func (p *productsService) UpdateProduct(userId string, data *productdto.ProductDto) (*api.Response, int, error) {
estoqueDisponivel := data.EstoqueTotal - data.EstoqueCorte
err := p.productsRepository.UpdateProduct(p.ctx, userId, products.UpdateProductParams{
Nome: data.Nome,
Codigo: data.Codigo,
EstoqueTotal: data.EstoqueTotal,
EstoqueCorte: data.EstoqueCorte,
EstoqueDisponivel: estoqueDisponivel,
PrecoDe: data.PrecoDe,
PrecoPor: data.PrecoPor,
})
if err != nil {
logger.Production.Info(err.Error())
return &api.Response{Error: true, ErrorMessage: err.Error(), Payload: "error update product"}, fiber.StatusInternalServerError, err
}
return &api.Response{Error: false, Payload: nil}, fiber.StatusOK, nil
}
func (p *productsService) GetProducts() (*api.Response, int, error) {
products, err := p.productsRepository.ListProducts(p.ctx)
if err != nil {
logger.Production.Info(err.Error())
return &api.Response{Error: true, ErrorMessage: err.Error(), Payload: "error get products"}, fiber.StatusInternalServerError, err
}
return &api.Response{Error: false, Payload: products}, fiber.StatusOK, nil
}
func (p *productsService) DeleteProduct(data *productdto.DeleteProductDto) (*api.Response, int, error) {
err := p.productsRepository.DeleteProduct(p.ctx, data.Codigo)
if err != nil {
logger.Production.Info(err.Error())
return &api.Response{Error: true, ErrorMessage: err.Error(), Payload: "error delete product"}, fiber.StatusInternalServerError, err
}
return &api.Response{Error: false, Payload: nil}, fiber.StatusOK, nil
}