init project
This commit is contained in:
@@ -0,0 +1,48 @@
|
||||
package app
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
|
||||
"github.com/gin-gonic/gin"
|
||||
"github.com/gofrs/uuid"
|
||||
|
||||
"furtuna-be/internal/middlewares"
|
||||
)
|
||||
|
||||
func NewServer() *Server {
|
||||
gin.SetMode(gin.ReleaseMode)
|
||||
|
||||
server := &Server{
|
||||
gin.New(),
|
||||
}
|
||||
|
||||
server.Use(middlewares.Cors())
|
||||
server.Use(middlewares.LogCorsError())
|
||||
server.Use(middlewares.Trace())
|
||||
server.Use(middlewares.Logger())
|
||||
server.Use(middlewares.RequestMiddleware())
|
||||
|
||||
return server
|
||||
}
|
||||
|
||||
type Server struct {
|
||||
*gin.Engine
|
||||
}
|
||||
|
||||
func (*Server) GenerateUUID() (string, error) {
|
||||
id, err := uuid.NewV4()
|
||||
if err != nil {
|
||||
return "", err
|
||||
}
|
||||
|
||||
return id.String(), nil
|
||||
}
|
||||
|
||||
func (s Server) Listen(address string) error {
|
||||
fmt.Printf("API server listening at: %s\n\n", address)
|
||||
return s.Run(address)
|
||||
}
|
||||
|
||||
func (s Server) StartScheduler() {
|
||||
fmt.Printf("Scheduler started\n")
|
||||
}
|
||||
@@ -0,0 +1,5 @@
|
||||
package database
|
||||
|
||||
type Config interface {
|
||||
ConnString() string
|
||||
}
|
||||
@@ -0,0 +1,52 @@
|
||||
package db
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
|
||||
_ "github.com/lib/pq"
|
||||
"go.uber.org/zap"
|
||||
_ "gopkg.in/yaml.v3"
|
||||
"gorm.io/driver/postgres"
|
||||
"gorm.io/gorm"
|
||||
|
||||
"furtuna-be/config"
|
||||
)
|
||||
|
||||
func NewPostgres(c config.Database) (*gorm.DB, error) {
|
||||
dialector := postgres.New(postgres.Config{
|
||||
DSN: c.DSN(),
|
||||
})
|
||||
|
||||
db, err := gorm.Open(dialector, &gorm.Config{})
|
||||
|
||||
//db, err := gorm.Open(dialector, &gorm.Config{
|
||||
// Logger: logger.Default.LogMode(logger.Info), // Enable GORM logging
|
||||
//})
|
||||
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
zapCfg := zap.NewProductionConfig()
|
||||
zapCfg.Level = zap.NewAtomicLevelAt(zap.DebugLevel) // whatever minimum level
|
||||
zapCfg.DisableCaller = true
|
||||
// logger, _ := zapCfg.Build()
|
||||
// db = gorm.Open(sqldblogger.New(logger), db)
|
||||
|
||||
// ping the database to test the connection
|
||||
sqlDB, err := db.DB()
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if err := sqlDB.Ping(); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
sqlDB.SetMaxIdleConns(c.MaxIdleConnectionsInSecond)
|
||||
sqlDB.SetMaxOpenConns(c.MaxOpenConnectionsInSecond)
|
||||
sqlDB.SetConnMaxLifetime(c.ConnectionMaxLifetime())
|
||||
|
||||
fmt.Println("Successfully connected to PostgreSQL database")
|
||||
|
||||
return db, nil
|
||||
}
|
||||
@@ -0,0 +1,49 @@
|
||||
package errors
|
||||
|
||||
import "net/http"
|
||||
|
||||
const (
|
||||
Success Code = "20000"
|
||||
ServerError Code = "50000"
|
||||
BadRequest Code = "40000"
|
||||
InvalidRequest Code = "40001"
|
||||
Unauthorized Code = "40100"
|
||||
Forbidden Code = "40300"
|
||||
Timeout Code = "50400"
|
||||
)
|
||||
|
||||
type Code string
|
||||
|
||||
var (
|
||||
codeMap = map[Code]string{
|
||||
Success: "Success",
|
||||
BadRequest: "Bad or invalid request",
|
||||
Unauthorized: "Unauthorized Token",
|
||||
Timeout: "Gateway Timeout",
|
||||
ServerError: "Internal Server Error",
|
||||
Forbidden: "Forbidden",
|
||||
InvalidRequest: "Invalid Request",
|
||||
}
|
||||
|
||||
codeHTTPMap = map[Code]int{
|
||||
Success: http.StatusOK,
|
||||
BadRequest: http.StatusBadRequest,
|
||||
Unauthorized: http.StatusUnauthorized,
|
||||
Timeout: http.StatusGatewayTimeout,
|
||||
ServerError: http.StatusInternalServerError,
|
||||
Forbidden: http.StatusForbidden,
|
||||
InvalidRequest: http.StatusUnprocessableEntity,
|
||||
}
|
||||
)
|
||||
|
||||
func (c Code) GetMessage() string {
|
||||
return codeMap[c]
|
||||
}
|
||||
|
||||
func (c Code) GetHTTPCode() int {
|
||||
return codeHTTPMap[c]
|
||||
}
|
||||
|
||||
func (c Code) GetCode() string {
|
||||
return string(c)
|
||||
}
|
||||
@@ -0,0 +1,95 @@
|
||||
package errors
|
||||
|
||||
import "net/http"
|
||||
|
||||
type ErrType string
|
||||
|
||||
const (
|
||||
errRequestTimeOut ErrType = "Request Timeout to 3rd Party"
|
||||
errConnectTimeOut ErrType = "Connect Timeout to 3rd Party"
|
||||
errFailedExternalCall ErrType = "Failed response from 3rd Party call"
|
||||
errExternalCall ErrType = "error on 3rd Party call"
|
||||
errInvalidRequest ErrType = "Invalid Request"
|
||||
errBadRequest ErrType = "Bad Request"
|
||||
errOrderNotFound ErrType = "Astria order is not found"
|
||||
errCheckoutIDNotDefined ErrType = "Checkout client id not found"
|
||||
errInternalServer ErrType = "Internal Server error"
|
||||
errUserIsNotFound ErrType = "User is not found"
|
||||
errInvalidLogin ErrType = "User email or password is invalid"
|
||||
errUnauthorized ErrType = "Unauthorized"
|
||||
)
|
||||
|
||||
var (
|
||||
ErrorBadRequest = NewServiceException(errBadRequest)
|
||||
ErrorInvalidRequest = NewServiceException(errInvalidRequest)
|
||||
ErrorUnauthorized = NewServiceException(errUnauthorized)
|
||||
ErrorOrderNotFound = NewServiceException(errOrderNotFound)
|
||||
ErrorClientIDNotDefined = NewServiceException(errCheckoutIDNotDefined)
|
||||
ErrorRequestTimeout = NewServiceException(errRequestTimeOut)
|
||||
ErrorExternalCall = NewServiceException(errExternalCall)
|
||||
ErrorFailedExternalCall = NewServiceException(errFailedExternalCall)
|
||||
ErrorConnectionTimeOut = NewServiceException(errConnectTimeOut)
|
||||
ErrorInternalServer = NewServiceException(errInternalServer)
|
||||
ErrorUserIsNotFound = NewServiceException(errUserIsNotFound)
|
||||
ErrorUserInvalidLogin = NewServiceException(errInvalidLogin)
|
||||
)
|
||||
|
||||
type Error interface {
|
||||
ErrorType() ErrType
|
||||
MapErrorsToHTTPCode() int
|
||||
MapErrorsToCode() Code
|
||||
error
|
||||
}
|
||||
|
||||
type ServiceException struct {
|
||||
errorType ErrType
|
||||
message string
|
||||
}
|
||||
|
||||
func NewServiceException(errType ErrType) *ServiceException {
|
||||
return &ServiceException{
|
||||
errorType: errType,
|
||||
message: string(errType),
|
||||
}
|
||||
}
|
||||
|
||||
func (s *ServiceException) ErrorType() ErrType {
|
||||
return s.errorType
|
||||
}
|
||||
|
||||
func (s *ServiceException) Error() string {
|
||||
return s.message
|
||||
}
|
||||
|
||||
func (s *ServiceException) MapErrorsToHTTPCode() int {
|
||||
switch s.ErrorType() {
|
||||
case errBadRequest:
|
||||
return http.StatusBadRequest
|
||||
|
||||
case errInvalidRequest:
|
||||
return http.StatusBadRequest
|
||||
|
||||
case errInvalidLogin:
|
||||
return http.StatusBadRequest
|
||||
|
||||
default:
|
||||
return http.StatusInternalServerError
|
||||
}
|
||||
}
|
||||
|
||||
func (s *ServiceException) MapErrorsToCode() Code {
|
||||
switch s.ErrorType() {
|
||||
|
||||
case errUnauthorized:
|
||||
return Unauthorized
|
||||
|
||||
case errConnectTimeOut:
|
||||
return Timeout
|
||||
|
||||
case errBadRequest:
|
||||
return BadRequest
|
||||
|
||||
default:
|
||||
return ServerError
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,46 @@
|
||||
package http
|
||||
|
||||
import (
|
||||
"context"
|
||||
"fmt"
|
||||
"io/ioutil"
|
||||
"net/http"
|
||||
"time"
|
||||
|
||||
"go.uber.org/zap"
|
||||
|
||||
"furtuna-be/internal/common/logger"
|
||||
)
|
||||
|
||||
type HttpClient struct {
|
||||
Client *http.Client
|
||||
}
|
||||
|
||||
func NewHttpClient() *HttpClient {
|
||||
return &HttpClient{
|
||||
Client: &http.Client{},
|
||||
}
|
||||
}
|
||||
|
||||
func (c *HttpClient) Do(ctx context.Context, req *http.Request) (int, []byte, error) {
|
||||
start := time.Now()
|
||||
logger.ContextLogger(ctx).Info(fmt.Sprintf("Sending request: %v %v", req.Method, req.URL))
|
||||
resp, err := c.Client.Do(req)
|
||||
if err != nil {
|
||||
logger.ContextLogger(ctx).Error(" Failed to send request:", zap.Error(err))
|
||||
return 0, nil, err
|
||||
}
|
||||
|
||||
logger.ContextLogger(ctx).Info(fmt.Sprintf("Received Response: : %v", resp.StatusCode))
|
||||
|
||||
defer resp.Body.Close()
|
||||
body, err := ioutil.ReadAll(resp.Body)
|
||||
if err != nil {
|
||||
logger.ContextLogger(ctx).Error(" Failed to read response:", zap.Error(err))
|
||||
return 0, nil, err
|
||||
}
|
||||
|
||||
logger.ContextLogger(ctx).Info(fmt.Sprintf("Latency : %v", time.Since(start)))
|
||||
|
||||
return resp.StatusCode, body, nil
|
||||
}
|
||||
@@ -0,0 +1,56 @@
|
||||
package logger
|
||||
|
||||
import (
|
||||
"context"
|
||||
"fmt"
|
||||
"furtuna-be/internal/constants"
|
||||
"sync"
|
||||
|
||||
"go.uber.org/zap"
|
||||
)
|
||||
|
||||
var mainLogger *zap.Logger = nil
|
||||
|
||||
var mainLoggerInit sync.Once
|
||||
|
||||
func NewMainLoggerSingleton() *zap.Logger {
|
||||
mainLoggerInit.Do(func() {
|
||||
logger, err := zap.NewProduction()
|
||||
if err != nil {
|
||||
logger.Error("logger initialization failed", zap.Any("error", err))
|
||||
panic(fmt.Sprintf("logger initialization failed %v", err))
|
||||
}
|
||||
logger.Info("logger started")
|
||||
mainLogger = logger
|
||||
})
|
||||
|
||||
return mainLogger
|
||||
}
|
||||
|
||||
func NewMainNoOpLoggerSingleton() *zap.Logger {
|
||||
mainLoggerInit.Do(func() {
|
||||
logger := zap.NewNop()
|
||||
logger.Info("logger started")
|
||||
mainLogger = logger
|
||||
})
|
||||
|
||||
return mainLogger
|
||||
}
|
||||
|
||||
func NewNoOp() *zap.Logger {
|
||||
return zap.NewNop()
|
||||
}
|
||||
|
||||
func GetLogger() *zap.Logger {
|
||||
return mainLogger
|
||||
}
|
||||
|
||||
func ContextLogger(ctx context.Context) *zap.Logger {
|
||||
logger := GetLogger()
|
||||
|
||||
if ctxRqID, ok := ctx.Value(constants.ContextRequestID).(string); ok {
|
||||
return logger.With(zap.String(constants.ContextRequestID, ctxRqID))
|
||||
}
|
||||
|
||||
return logger
|
||||
}
|
||||
@@ -0,0 +1,48 @@
|
||||
package mycontext
|
||||
|
||||
import (
|
||||
"context"
|
||||
"furtuna-be/internal/constants/role"
|
||||
"furtuna-be/internal/entity"
|
||||
)
|
||||
|
||||
type ContextKey string
|
||||
|
||||
type Context interface {
|
||||
context.Context
|
||||
|
||||
RequestedBy() int64
|
||||
IsSuperAdmin() bool
|
||||
}
|
||||
|
||||
type MyContextImpl struct {
|
||||
context.Context
|
||||
|
||||
requestedBy int64
|
||||
requestID string
|
||||
branchID int64
|
||||
roleID int
|
||||
}
|
||||
|
||||
func (m *MyContextImpl) RequestedBy() int64 {
|
||||
return m.requestedBy
|
||||
}
|
||||
|
||||
func (m *MyContextImpl) IsSuperAdmin() bool {
|
||||
return m.roleID == int(role.SuperAdmin)
|
||||
}
|
||||
|
||||
func NewMyContext(parent context.Context, claims *entity.JWTAuthClaims) (*MyContextImpl, error) {
|
||||
return &MyContextImpl{
|
||||
Context: parent,
|
||||
requestedBy: claims.UserID,
|
||||
branchID: claims.BranchID,
|
||||
roleID: claims.Role,
|
||||
}, nil
|
||||
}
|
||||
|
||||
func NewContext(parent context.Context) *MyContextImpl {
|
||||
return &MyContextImpl{
|
||||
Context: parent,
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,53 @@
|
||||
package request
|
||||
|
||||
import (
|
||||
"context"
|
||||
"github.com/gin-gonic/gin"
|
||||
)
|
||||
|
||||
const (
|
||||
ReqInfoKey reqInfoKeyType = "request-info"
|
||||
)
|
||||
|
||||
func SetTraceId(c *gin.Context, traceId string) {
|
||||
info, exists := c.Get(ReqInfoKey)
|
||||
if exists {
|
||||
parsedInfo := info.(RequestInfo)
|
||||
parsedInfo.TraceId = traceId
|
||||
|
||||
c.Set(ReqInfoKey, parsedInfo)
|
||||
|
||||
return
|
||||
}
|
||||
c.Set(ReqInfoKey, RequestInfo{TraceId: traceId})
|
||||
}
|
||||
|
||||
func SetUserId(c *gin.Context, userId int64) {
|
||||
info, exists := c.Get(ReqInfoKey)
|
||||
if exists {
|
||||
parsedInfo := info.(RequestInfo)
|
||||
parsedInfo.UserId = userId
|
||||
|
||||
c.Set(ReqInfoKey, parsedInfo)
|
||||
|
||||
return
|
||||
}
|
||||
|
||||
c.Set(ReqInfoKey, RequestInfo{UserId: userId})
|
||||
}
|
||||
|
||||
func SetUserContext(c *gin.Context, payload map[string]interface{}) {
|
||||
c.Set(ReqInfoKey, RequestInfo{
|
||||
UserId: int64(payload["userId"].(float64)),
|
||||
Role: payload["role"].(string),
|
||||
})
|
||||
}
|
||||
|
||||
func ContextWithReqInfo(c *gin.Context) context.Context {
|
||||
info, ok := c.Get(ReqInfoKey)
|
||||
if ok {
|
||||
return WithRequestInfo(c, info.(RequestInfo))
|
||||
}
|
||||
|
||||
return WithRequestInfo(c, RequestInfo{})
|
||||
}
|
||||
@@ -0,0 +1,40 @@
|
||||
package request
|
||||
|
||||
import "context"
|
||||
|
||||
type requestInfoKey int
|
||||
|
||||
const (
|
||||
key requestInfoKey = iota
|
||||
)
|
||||
|
||||
type RequestInfo struct {
|
||||
UserId int64
|
||||
TraceId string
|
||||
Permissions map[string]bool
|
||||
Role string
|
||||
}
|
||||
|
||||
func WithRequestInfo(ctx context.Context, info RequestInfo) context.Context {
|
||||
return context.WithValue(ctx, key, info)
|
||||
}
|
||||
|
||||
func GetRequestInfo(ctx context.Context) (requestInfo RequestInfo, ok bool) {
|
||||
requestInfo, ok = ctx.Value(key).(RequestInfo)
|
||||
return
|
||||
}
|
||||
|
||||
type reqInfoKeyType = string
|
||||
|
||||
const (
|
||||
reqInfoKey reqInfoKeyType = "request-info"
|
||||
)
|
||||
|
||||
func GetReqInfo(c context.Context) RequestInfo {
|
||||
info := c.Value(reqInfoKey)
|
||||
if info != nil {
|
||||
return info.(RequestInfo)
|
||||
}
|
||||
|
||||
return RequestInfo{}
|
||||
}
|
||||
@@ -0,0 +1,12 @@
|
||||
package branch
|
||||
|
||||
type BranchStatus string
|
||||
|
||||
const (
|
||||
Active BranchStatus = "Active"
|
||||
Inactive BranchStatus = "Inactive"
|
||||
)
|
||||
|
||||
func (b BranchStatus) toString() string {
|
||||
return string(b)
|
||||
}
|
||||
@@ -0,0 +1,11 @@
|
||||
package constants
|
||||
|
||||
const (
|
||||
ContextRequestID string = "requestId"
|
||||
)
|
||||
|
||||
type UserType string
|
||||
|
||||
func (u UserType) toString() string {
|
||||
return string(u)
|
||||
}
|
||||
@@ -0,0 +1,12 @@
|
||||
package device
|
||||
|
||||
type DeviceStatus string
|
||||
|
||||
const (
|
||||
On DeviceStatus = "On"
|
||||
Off DeviceStatus = "Off"
|
||||
)
|
||||
|
||||
func (b DeviceStatus) toString() string {
|
||||
return string(b)
|
||||
}
|
||||
@@ -0,0 +1,12 @@
|
||||
package device
|
||||
|
||||
type DeviceConnectionStatus string
|
||||
|
||||
const (
|
||||
Connected DeviceConnectionStatus = "Connected"
|
||||
Disconnected DeviceConnectionStatus = "Disconnected"
|
||||
)
|
||||
|
||||
func (b DeviceConnectionStatus) toString() string {
|
||||
return string(b)
|
||||
}
|
||||
@@ -0,0 +1,79 @@
|
||||
package order
|
||||
|
||||
type OrderStatus string
|
||||
|
||||
const (
|
||||
New OrderStatus = "NEW"
|
||||
Paid OrderStatus = "PAID"
|
||||
Cancel OrderStatus = "CANCEL"
|
||||
)
|
||||
|
||||
func (b OrderStatus) toString() string {
|
||||
return string(b)
|
||||
}
|
||||
|
||||
func (i *OrderStatus) IsNew() bool {
|
||||
if i == nil {
|
||||
return false
|
||||
}
|
||||
|
||||
if *i == New {
|
||||
return true
|
||||
}
|
||||
|
||||
return false
|
||||
}
|
||||
|
||||
type ItemType string
|
||||
|
||||
const (
|
||||
Product ItemType = "PRODUCT"
|
||||
Studio ItemType = "STUDIO"
|
||||
)
|
||||
|
||||
func (b ItemType) toString() string {
|
||||
return string(b)
|
||||
}
|
||||
|
||||
func (i *ItemType) IsProduct() bool {
|
||||
if i == nil {
|
||||
return false
|
||||
}
|
||||
|
||||
if *i == Product {
|
||||
return true
|
||||
}
|
||||
|
||||
return false
|
||||
}
|
||||
|
||||
func (i *ItemType) IsStudio() bool {
|
||||
if i == nil {
|
||||
return false
|
||||
}
|
||||
|
||||
if *i == Studio {
|
||||
return true
|
||||
}
|
||||
|
||||
return false
|
||||
}
|
||||
|
||||
type OrderSearchStatus string
|
||||
|
||||
const (
|
||||
Active OrderSearchStatus = "ACTIVE"
|
||||
Inactive OrderSearchStatus = "INACTIVE"
|
||||
)
|
||||
|
||||
func (i *OrderSearchStatus) IsActive() bool {
|
||||
if i == nil {
|
||||
return false
|
||||
}
|
||||
|
||||
if *i == Active {
|
||||
return true
|
||||
}
|
||||
|
||||
return false
|
||||
}
|
||||
@@ -0,0 +1,9 @@
|
||||
package constants
|
||||
|
||||
const (
|
||||
OssLogLevelLogOff = "LogOff"
|
||||
OssLogLevelDebug = "Debug"
|
||||
OssLogLevelError = "Error"
|
||||
OssLogLevelWarn = "Warn"
|
||||
OssLogLevelInfo = "Info"
|
||||
)
|
||||
@@ -0,0 +1,58 @@
|
||||
package product
|
||||
|
||||
type ProductStatus string
|
||||
|
||||
const (
|
||||
Active ProductStatus = "Active"
|
||||
Inactive ProductStatus = "Inactive"
|
||||
)
|
||||
|
||||
func (b ProductStatus) toString() string {
|
||||
return string(b)
|
||||
}
|
||||
|
||||
type ProductType string
|
||||
|
||||
const (
|
||||
Food ProductType = "FOOD"
|
||||
Beverage ProductType = "BEVERAGE"
|
||||
)
|
||||
|
||||
func (b ProductType) toString() string {
|
||||
return string(b)
|
||||
}
|
||||
|
||||
type ProductStock string
|
||||
|
||||
const (
|
||||
Available ProductStock = "AVAILABLE"
|
||||
Unavailable ProductStock = "UNAVAILABLE"
|
||||
)
|
||||
|
||||
func (b ProductStock) toString() string {
|
||||
return string(b)
|
||||
}
|
||||
|
||||
func (i *ProductStock) IsAvailable() bool {
|
||||
if i == nil {
|
||||
return false
|
||||
}
|
||||
|
||||
if *i == Available {
|
||||
return true
|
||||
}
|
||||
|
||||
return false
|
||||
}
|
||||
|
||||
func (i *ProductStock) IsUnavailable() bool {
|
||||
if i == nil {
|
||||
return false
|
||||
}
|
||||
|
||||
if *i == Unavailable {
|
||||
return true
|
||||
}
|
||||
|
||||
return false
|
||||
}
|
||||
@@ -0,0 +1,9 @@
|
||||
package role
|
||||
|
||||
type Role int64
|
||||
|
||||
const (
|
||||
SuperAdmin Role = 1
|
||||
BranchAdmin Role = 2
|
||||
CasheerAdmin Role = 3
|
||||
)
|
||||
@@ -0,0 +1,12 @@
|
||||
package studio
|
||||
|
||||
type StudioStatus string
|
||||
|
||||
const (
|
||||
Active StudioStatus = "Active"
|
||||
Inactive StudioStatus = "Inactive"
|
||||
)
|
||||
|
||||
func (b StudioStatus) toString() string {
|
||||
return string(b)
|
||||
}
|
||||
@@ -0,0 +1,26 @@
|
||||
package transaction
|
||||
|
||||
type PaymentStatus string
|
||||
|
||||
const (
|
||||
New PaymentStatus = "NEW"
|
||||
Paid PaymentStatus = "PAID"
|
||||
Cancel PaymentStatus = "CANCEL"
|
||||
)
|
||||
|
||||
func (b PaymentStatus) toString() string {
|
||||
return string(b)
|
||||
}
|
||||
|
||||
type PaymentMethod string
|
||||
|
||||
const (
|
||||
Cash PaymentMethod = "CASH"
|
||||
Debit PaymentMethod = "DEBIT"
|
||||
Transfer PaymentMethod = "TRANSFER"
|
||||
QRIS PaymentMethod = "QRIS"
|
||||
)
|
||||
|
||||
func (b PaymentMethod) toString() string {
|
||||
return string(b)
|
||||
}
|
||||
@@ -0,0 +1,12 @@
|
||||
package userstatus
|
||||
|
||||
type UserStatus string
|
||||
|
||||
const (
|
||||
Active UserStatus = "Active"
|
||||
Inactive UserStatus = "Inactive"
|
||||
)
|
||||
|
||||
func (u UserStatus) toString() string {
|
||||
return string(u)
|
||||
}
|
||||
@@ -0,0 +1,143 @@
|
||||
package entity
|
||||
|
||||
import (
|
||||
"furtuna-be/internal/constants/role"
|
||||
"furtuna-be/internal/constants/userstatus"
|
||||
"time"
|
||||
)
|
||||
|
||||
type AuthData struct {
|
||||
Token string `json:"token"`
|
||||
UserID int64 `gorm:"column:user_id"`
|
||||
RoleID int `gorm:"column:role_id"`
|
||||
OrganizationID int64 `gorm:"column:organization_id"`
|
||||
}
|
||||
|
||||
type UserDB struct {
|
||||
ID int64 `gorm:"primary_key;column:id" json:"id"`
|
||||
Name string `gorm:"column:name" json:"name"`
|
||||
Email string `gorm:"column:email" json:"email"`
|
||||
Password string `gorm:"column:password" json:"-"`
|
||||
Status userstatus.UserStatus `gorm:"column:status" json:"status"`
|
||||
UserType string `gorm:"column:user_type" json:"user_type"`
|
||||
PhoneNumber string `gorm:"column:phone_number" json:"phone_number"`
|
||||
NIK string `gorm:"column:nik" json:"nik"`
|
||||
RoleID int64 `gorm:"column:role_id" json:"role_id"`
|
||||
RoleName string `gorm:"column:role_name" json:"role_name"`
|
||||
BranchID *int64 `gorm:"column:partner_id" json:"partner_id"`
|
||||
BranchName string `gorm:"column:partner_name" json:"partner_name"`
|
||||
CreatedAt time.Time `gorm:"column:created_at" json:"created_at"`
|
||||
UpdatedAt time.Time `gorm:"column:updated_at" json:"updated_at"`
|
||||
DeletedAt *time.Time `gorm:"column:deleted_at" json:"deleted_at"`
|
||||
CreatedBy int64 `gorm:"column:created_by" json:"created_by"`
|
||||
UpdatedBy int64 `gorm:"column:updated_by" json:"updated_by"`
|
||||
}
|
||||
|
||||
func (u *UserDB) ToUser() *User {
|
||||
if u == nil {
|
||||
return &User{}
|
||||
}
|
||||
|
||||
userEntity := &User{
|
||||
ID: u.ID,
|
||||
Name: u.Name,
|
||||
Email: u.Email,
|
||||
Status: u.Status,
|
||||
CreatedAt: u.CreatedAt,
|
||||
UpdatedAt: u.UpdatedAt,
|
||||
RoleID: role.Role(u.RoleID),
|
||||
RoleName: u.RoleName,
|
||||
PartnerID: u.BranchID,
|
||||
BranchName: u.BranchName,
|
||||
}
|
||||
|
||||
return userEntity
|
||||
}
|
||||
|
||||
func (u *UserDB) ToUserRoleDB() *UserRoleDB {
|
||||
if u == nil {
|
||||
return &UserRoleDB{}
|
||||
}
|
||||
|
||||
userRole := &UserRoleDB{
|
||||
ID: 0,
|
||||
UserID: u.ID,
|
||||
RoleID: u.RoleID,
|
||||
PartnerID: u.BranchID,
|
||||
CreatedAt: u.CreatedAt,
|
||||
UpdatedAt: u.UpdatedAt,
|
||||
}
|
||||
|
||||
return userRole
|
||||
}
|
||||
|
||||
func (UserDB) TableName() string {
|
||||
return "users"
|
||||
}
|
||||
|
||||
func (u *UserDB) ToUserAuthenticate(signedToken string) *AuthenticateUser {
|
||||
return &AuthenticateUser{
|
||||
Token: signedToken,
|
||||
Name: u.Name,
|
||||
RoleID: role.Role(u.RoleID),
|
||||
RoleName: u.RoleName,
|
||||
BranchID: u.BranchID,
|
||||
BranchName: u.BranchName,
|
||||
}
|
||||
}
|
||||
|
||||
type UserSearch struct {
|
||||
Search string
|
||||
Name string
|
||||
RoleID int64
|
||||
PartnerID int64
|
||||
Limit int
|
||||
Offset int
|
||||
}
|
||||
|
||||
type UserList []*UserDB
|
||||
|
||||
func (b *UserList) ToUserList() []*User {
|
||||
var users []*User
|
||||
for _, user := range *b {
|
||||
users = append(users, user.ToUser())
|
||||
}
|
||||
return users
|
||||
}
|
||||
|
||||
func (u *UserDB) ToUpdatedUser(req User) error {
|
||||
|
||||
if req.Name != "" {
|
||||
u.Name = req.Name
|
||||
}
|
||||
|
||||
if req.Email != "" {
|
||||
u.Email = req.Email
|
||||
}
|
||||
|
||||
if *req.PartnerID > 0 {
|
||||
u.BranchID = req.PartnerID
|
||||
}
|
||||
|
||||
if req.RoleID > 0 {
|
||||
u.RoleID = int64(req.RoleID)
|
||||
}
|
||||
|
||||
if req.Password != "" {
|
||||
hashedPassword, err := req.HashedPassword(req.Password)
|
||||
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
u.Password = hashedPassword
|
||||
}
|
||||
|
||||
return nil
|
||||
}
|
||||
|
||||
func (o *UserDB) SetDeleted(updatedby int64) {
|
||||
currentTime := time.Now()
|
||||
o.DeletedAt = ¤tTime
|
||||
o.UpdatedBy = updatedby
|
||||
o.Status = userstatus.Inactive
|
||||
}
|
||||
@@ -0,0 +1,83 @@
|
||||
package entity
|
||||
|
||||
import (
|
||||
"furtuna-be/internal/constants/branch"
|
||||
"time"
|
||||
)
|
||||
|
||||
type Branch struct {
|
||||
ID int64
|
||||
Name string
|
||||
Status branch.BranchStatus
|
||||
Location string
|
||||
CreatedAt time.Time
|
||||
UpdatedAt time.Time
|
||||
DeletedAt *time.Time
|
||||
CreatedBy int64
|
||||
UpdatedBy int64
|
||||
}
|
||||
|
||||
type BranchSearch struct {
|
||||
Search string
|
||||
Name string
|
||||
Limit int
|
||||
Offset int
|
||||
}
|
||||
|
||||
type BranchList []*BranchDB
|
||||
|
||||
type BranchDB struct {
|
||||
Branch
|
||||
}
|
||||
|
||||
func (b *Branch) ToBranchDB() *BranchDB {
|
||||
return &BranchDB{
|
||||
Branch: *b,
|
||||
}
|
||||
}
|
||||
|
||||
func (BranchDB) TableName() string {
|
||||
return "branches"
|
||||
}
|
||||
|
||||
func (e *BranchDB) ToBranch() *Branch {
|
||||
return &Branch{
|
||||
ID: e.ID,
|
||||
Name: e.Name,
|
||||
Status: e.Status,
|
||||
Location: e.Location,
|
||||
CreatedAt: e.CreatedAt,
|
||||
UpdatedAt: e.UpdatedAt,
|
||||
CreatedBy: e.CreatedBy,
|
||||
}
|
||||
}
|
||||
|
||||
func (b *BranchList) ToBranchList() []*Branch {
|
||||
var branches []*Branch
|
||||
for _, branch := range *b {
|
||||
branches = append(branches, branch.ToBranch())
|
||||
}
|
||||
return branches
|
||||
}
|
||||
|
||||
func (o *BranchDB) ToUpdatedBranch(updatedby int64, req Branch) {
|
||||
o.UpdatedBy = updatedby
|
||||
|
||||
if req.Name != "" {
|
||||
o.Name = req.Name
|
||||
}
|
||||
|
||||
if req.Status != "" {
|
||||
o.Status = req.Status
|
||||
}
|
||||
|
||||
if req.Location != "" {
|
||||
o.Location = req.Location
|
||||
}
|
||||
}
|
||||
|
||||
func (o *BranchDB) SetDeleted(updatedby int64) {
|
||||
currentTime := time.Now()
|
||||
o.DeletedAt = ¤tTime
|
||||
o.UpdatedBy = updatedby
|
||||
}
|
||||
@@ -0,0 +1,158 @@
|
||||
package entity
|
||||
|
||||
import (
|
||||
"database/sql/driver"
|
||||
"errors"
|
||||
"strings"
|
||||
"time"
|
||||
)
|
||||
|
||||
type Status string
|
||||
|
||||
type Event struct {
|
||||
ID int64
|
||||
Name string
|
||||
Description string
|
||||
StartDate time.Time
|
||||
EndDate time.Time
|
||||
Location string
|
||||
Level string
|
||||
Included StringArray `gorm:"type:text[]"`
|
||||
Price float64
|
||||
Paid bool
|
||||
LocationID *int64
|
||||
Status Status
|
||||
CreatedAt time.Time
|
||||
UpdatedAt time.Time
|
||||
DeletedAt *time.Time
|
||||
}
|
||||
|
||||
type StringArray []string
|
||||
|
||||
func (a StringArray) Value() (driver.Value, error) {
|
||||
if a == nil {
|
||||
return nil, nil
|
||||
}
|
||||
|
||||
joined := "{" + strings.Join(a, ",") + "}"
|
||||
|
||||
return []byte(joined), nil
|
||||
}
|
||||
|
||||
func (a *StringArray) Scan(src interface{}) error {
|
||||
if src == nil {
|
||||
*a = nil
|
||||
return nil
|
||||
}
|
||||
|
||||
srcStr, ok := src.(string)
|
||||
if !ok {
|
||||
return errors.New("failed to scan StringArray")
|
||||
}
|
||||
|
||||
// Remove the curly braces and split the string into elements
|
||||
if len(srcStr) < 2 || srcStr[0] != '{' || srcStr[len(srcStr)-1] != '}' {
|
||||
return errors.New("invalid format for StringArray")
|
||||
}
|
||||
srcStr = srcStr[1 : len(srcStr)-1]
|
||||
|
||||
*a = strings.Split(srcStr, ",")
|
||||
|
||||
return nil
|
||||
}
|
||||
|
||||
type EventSearch struct {
|
||||
Name string
|
||||
Limit int
|
||||
Offset int
|
||||
}
|
||||
|
||||
type EventList []*EventDB
|
||||
|
||||
type EventDB struct {
|
||||
Event
|
||||
}
|
||||
|
||||
func (e *Event) ToEventDB() *EventDB {
|
||||
return &EventDB{
|
||||
Event: *e,
|
||||
}
|
||||
}
|
||||
|
||||
func (e *EventDB) ToEvent() *Event {
|
||||
return &Event{
|
||||
ID: e.ID,
|
||||
Name: e.Name,
|
||||
Description: e.Description,
|
||||
StartDate: e.StartDate,
|
||||
EndDate: e.EndDate,
|
||||
Location: e.Location,
|
||||
Level: e.Level,
|
||||
Included: e.Included,
|
||||
Price: e.Price,
|
||||
Paid: e.Paid,
|
||||
LocationID: e.LocationID,
|
||||
CreatedAt: e.CreatedAt,
|
||||
UpdatedAt: e.UpdatedAt,
|
||||
Status: e.Status,
|
||||
}
|
||||
}
|
||||
|
||||
func (e *EventList) ToEventList() []*Event {
|
||||
var events []*Event
|
||||
for _, event := range *e {
|
||||
events = append(events, event.ToEvent())
|
||||
}
|
||||
return events
|
||||
}
|
||||
|
||||
func (EventDB) TableName() string {
|
||||
return "events"
|
||||
}
|
||||
|
||||
func (o *EventDB) ToUpdatedEvent(req Event) {
|
||||
if req.Name != "" {
|
||||
o.Name = req.Name
|
||||
}
|
||||
|
||||
if req.Description != "" {
|
||||
o.Description = req.Description
|
||||
}
|
||||
|
||||
if !req.StartDate.IsZero() {
|
||||
o.StartDate = req.StartDate
|
||||
}
|
||||
|
||||
if !req.EndDate.IsZero() {
|
||||
o.EndDate = req.EndDate
|
||||
}
|
||||
|
||||
if req.Location != "" {
|
||||
o.Location = req.Location
|
||||
}
|
||||
|
||||
if req.Level != "" {
|
||||
o.Level = req.Level
|
||||
}
|
||||
|
||||
if req.Included != nil && len(req.Included) > 0 {
|
||||
o.Included = req.Included
|
||||
}
|
||||
|
||||
if req.Price != 0 {
|
||||
o.Price = req.Price
|
||||
}
|
||||
|
||||
if req.LocationID != nil {
|
||||
o.LocationID = req.LocationID
|
||||
}
|
||||
|
||||
if req.Status != "" {
|
||||
o.Status = req.Status
|
||||
}
|
||||
}
|
||||
|
||||
func (o *EventDB) SetDeleted() {
|
||||
currentTime := time.Now()
|
||||
o.DeletedAt = ¤tTime
|
||||
}
|
||||
@@ -0,0 +1,12 @@
|
||||
package entity
|
||||
|
||||
import "github.com/golang-jwt/jwt"
|
||||
|
||||
type JWTAuthClaims struct {
|
||||
UserID int64 `json:"id"`
|
||||
Name string `json:"name"`
|
||||
Email string `json:"email"`
|
||||
Role int `json:"role"`
|
||||
BranchID int64 `json:"branch_id"`
|
||||
jwt.StandardClaims
|
||||
}
|
||||
@@ -0,0 +1,166 @@
|
||||
package entity
|
||||
|
||||
import (
|
||||
"furtuna-be/internal/constants/order"
|
||||
"time"
|
||||
)
|
||||
|
||||
type Order struct {
|
||||
ID int64
|
||||
BranchID int64
|
||||
BranchName string
|
||||
Status order.OrderStatus
|
||||
Amount float64
|
||||
CustomerName string `gorm:"column:customer_name" json:"customer_name"`
|
||||
CustomerPhone string `gorm:"column:customer_phone" json:"customer_phone"`
|
||||
Pax int `gorm:"column:pax" json:"pax"`
|
||||
CreatedAt time.Time
|
||||
UpdatedAt time.Time
|
||||
CreatedBy int64
|
||||
UpdatedBy int64
|
||||
Transaction Transaction
|
||||
OrderItem []OrderItem
|
||||
}
|
||||
|
||||
type OrderSearch struct {
|
||||
Search string
|
||||
StatusActive order.OrderSearchStatus
|
||||
Status order.OrderStatus
|
||||
BranchID int64
|
||||
Limit int
|
||||
Offset int
|
||||
}
|
||||
|
||||
type OrderTotalRevenueSearch struct {
|
||||
Year int
|
||||
Month int
|
||||
BranchID int64
|
||||
DateStart *time.Time
|
||||
DateEnd *time.Time
|
||||
}
|
||||
|
||||
type OrderYearlyRevenueList []OrderYearlyRevenue
|
||||
type OrderYearlyRevenue struct {
|
||||
ItemType string `gorm:"column:item_type"`
|
||||
Month int `gorm:"column:month_number"`
|
||||
Amount float64 `gorm:"column:total_amount"`
|
||||
}
|
||||
|
||||
type OrderBranchRevenueSearch struct {
|
||||
DateStart *time.Time
|
||||
DateEnd *time.Time
|
||||
}
|
||||
|
||||
type OrderBranchRevenueList []OrderBranchRevenue
|
||||
type OrderBranchRevenue struct {
|
||||
BranchID string `gorm:"column:branch_id"`
|
||||
BranchName string `gorm:"column:name"`
|
||||
BranchLocation string `gorm:"column:location"`
|
||||
TotalTransaction int `gorm:"column:total_trans"`
|
||||
TotalAmount float64 `gorm:"column:total_amount"`
|
||||
}
|
||||
|
||||
type OrderList []*OrderDB
|
||||
|
||||
type OrderDB struct {
|
||||
Order
|
||||
}
|
||||
|
||||
func (b *Order) ToOrderDB() *OrderDB {
|
||||
var amount float64
|
||||
for _, i := range b.OrderItem {
|
||||
amount = amount + (i.Price * float64(i.Qty))
|
||||
}
|
||||
b.Amount = amount
|
||||
b.Transaction.Amount = amount
|
||||
|
||||
return &OrderDB{
|
||||
Order: *b,
|
||||
}
|
||||
}
|
||||
|
||||
func (OrderDB) TableName() string {
|
||||
return "orders"
|
||||
}
|
||||
|
||||
func (e *OrderDB) ToOrder() *Order {
|
||||
return &Order{
|
||||
ID: e.ID,
|
||||
Status: e.Status,
|
||||
BranchID: e.BranchID,
|
||||
BranchName: e.BranchName,
|
||||
Amount: e.Amount,
|
||||
CustomerName: e.CustomerName,
|
||||
CustomerPhone: e.CustomerPhone,
|
||||
Pax: e.Pax,
|
||||
Transaction: e.Transaction,
|
||||
OrderItem: e.OrderItem,
|
||||
CreatedAt: e.CreatedAt,
|
||||
UpdatedAt: e.UpdatedAt,
|
||||
CreatedBy: e.CreatedBy,
|
||||
UpdatedBy: e.UpdatedBy,
|
||||
}
|
||||
}
|
||||
|
||||
func (b *OrderList) ToOrderList() []*Order {
|
||||
var Orders []*Order
|
||||
for _, order := range *b {
|
||||
Orders = append(Orders, order.ToOrder())
|
||||
}
|
||||
return Orders
|
||||
}
|
||||
|
||||
func (o *OrderDB) ToUpdatedOrder(updatedby int64, req Order) {
|
||||
o.UpdatedBy = updatedby
|
||||
|
||||
if req.Amount > 0 {
|
||||
o.Amount = req.Amount
|
||||
}
|
||||
|
||||
if req.Status != "" {
|
||||
o.Status = req.Status
|
||||
}
|
||||
}
|
||||
|
||||
type OrderItem struct {
|
||||
OrderItemID int64
|
||||
OrderID int64
|
||||
ItemID int64
|
||||
ItemType order.ItemType
|
||||
ItemName string
|
||||
Price float64
|
||||
Qty int64
|
||||
CreatedAt time.Time
|
||||
UpdatedAt time.Time
|
||||
CreatedBy int64
|
||||
UpdatedBy int64
|
||||
}
|
||||
|
||||
type OrderItemDB struct {
|
||||
OrderItem
|
||||
}
|
||||
|
||||
func (b *OrderItem) ToOrderItemDB() *OrderItemDB {
|
||||
return &OrderItemDB{
|
||||
OrderItem: *b,
|
||||
}
|
||||
}
|
||||
|
||||
func (OrderItemDB) TableName() string {
|
||||
return "order_items"
|
||||
}
|
||||
|
||||
func (e *OrderItemDB) ToOrderItem() *OrderItem {
|
||||
return &OrderItem{
|
||||
OrderItemID: e.OrderItemID,
|
||||
OrderID: e.OrderID,
|
||||
ItemID: e.ItemID,
|
||||
ItemType: e.ItemType,
|
||||
Price: e.Price,
|
||||
Qty: e.Qty,
|
||||
CreatedAt: e.CreatedAt,
|
||||
UpdatedAt: e.UpdatedAt,
|
||||
CreatedBy: e.CreatedBy,
|
||||
UpdatedBy: e.UpdatedBy,
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,24 @@
|
||||
package entity
|
||||
|
||||
import "mime/multipart"
|
||||
|
||||
type UploadFileRequest struct {
|
||||
FileHeader *multipart.FileHeader
|
||||
FolderName string
|
||||
FileSize int64 `validate:"max=10000000"` // 10Mb = 10000000 byte
|
||||
Ext string `validate:"oneof=.png .jpeg .jpg .pdf .xlsx .csv"`
|
||||
}
|
||||
|
||||
type DownloadFileRequest struct {
|
||||
FileName string `query:"file_name" validate:"required"`
|
||||
FolderName string `query:"folder_name" validate:"required"`
|
||||
}
|
||||
|
||||
type UploadFileResponse struct {
|
||||
FilePath string `json:"file_path"`
|
||||
FileUrl string `json:"file_url"`
|
||||
}
|
||||
|
||||
type DownloadFileResponse struct {
|
||||
FileUrl string `json:"file_url"`
|
||||
}
|
||||
@@ -0,0 +1,82 @@
|
||||
package entity
|
||||
|
||||
import (
|
||||
"time"
|
||||
)
|
||||
|
||||
type Partner struct {
|
||||
ID int64
|
||||
Name string
|
||||
Status string
|
||||
Address string
|
||||
CreatedAt time.Time
|
||||
UpdatedAt time.Time
|
||||
DeletedAt *time.Time
|
||||
CreatedBy int64
|
||||
UpdatedBy int64
|
||||
}
|
||||
|
||||
type PartnerSearch struct {
|
||||
Search string
|
||||
Name string
|
||||
Limit int
|
||||
Offset int
|
||||
}
|
||||
|
||||
type PartnerList []*PartnerDB
|
||||
|
||||
type PartnerDB struct {
|
||||
Partner
|
||||
}
|
||||
|
||||
func (p *Partner) ToPartnerDB() *PartnerDB {
|
||||
return &PartnerDB{
|
||||
Partner: *p,
|
||||
}
|
||||
}
|
||||
|
||||
func (PartnerDB) TableName() string {
|
||||
return "partners"
|
||||
}
|
||||
|
||||
func (e *PartnerDB) ToPartner() *Partner {
|
||||
return &Partner{
|
||||
ID: e.ID,
|
||||
Name: e.Name,
|
||||
Status: e.Status,
|
||||
Address: e.Address,
|
||||
CreatedAt: e.CreatedAt,
|
||||
UpdatedAt: e.UpdatedAt,
|
||||
CreatedBy: e.CreatedBy,
|
||||
}
|
||||
}
|
||||
|
||||
func (p *PartnerList) ToPartnerList() []*Partner {
|
||||
var partners []*Partner
|
||||
for _, partner := range *p {
|
||||
partners = append(partners, partner.ToPartner())
|
||||
}
|
||||
return partners
|
||||
}
|
||||
|
||||
func (o *PartnerDB) ToUpdatedPartner(updatedBy int64, req Partner) {
|
||||
o.UpdatedBy = updatedBy
|
||||
|
||||
if req.Name != "" {
|
||||
o.Name = req.Name
|
||||
}
|
||||
|
||||
if req.Status != "" {
|
||||
o.Status = req.Status
|
||||
}
|
||||
|
||||
if req.Address != "" {
|
||||
o.Address = req.Address
|
||||
}
|
||||
}
|
||||
|
||||
func (o *PartnerDB) SetDeleted(updatedBy int64) {
|
||||
currentTime := time.Now()
|
||||
o.DeletedAt = ¤tTime
|
||||
o.UpdatedBy = updatedBy
|
||||
}
|
||||
@@ -0,0 +1,114 @@
|
||||
package entity
|
||||
|
||||
import (
|
||||
"furtuna-be/internal/constants/product"
|
||||
"time"
|
||||
)
|
||||
|
||||
type Product struct {
|
||||
ID int64
|
||||
Name string
|
||||
Type product.ProductType
|
||||
Price float64
|
||||
Status product.ProductStatus
|
||||
Description string
|
||||
Image string
|
||||
BranchID int64
|
||||
StockQty int64
|
||||
CreatedAt time.Time
|
||||
UpdatedAt time.Time
|
||||
DeletedAt *time.Time
|
||||
CreatedBy int64
|
||||
UpdatedBy int64
|
||||
}
|
||||
|
||||
type ProductSearch struct {
|
||||
Search string
|
||||
Name string
|
||||
Type product.ProductType
|
||||
BranchID int64
|
||||
Available product.ProductStock
|
||||
Limit int
|
||||
Offset int
|
||||
}
|
||||
|
||||
type ProductList []*ProductDB
|
||||
|
||||
type ProductDB struct {
|
||||
Product
|
||||
}
|
||||
|
||||
func (b *Product) ToProductDB() *ProductDB {
|
||||
return &ProductDB{
|
||||
Product: *b,
|
||||
}
|
||||
}
|
||||
|
||||
func (ProductDB) TableName() string {
|
||||
return "products"
|
||||
}
|
||||
|
||||
func (e *ProductDB) ToProduct() *Product {
|
||||
return &Product{
|
||||
ID: e.ID,
|
||||
Name: e.Name,
|
||||
Type: e.Type,
|
||||
Price: e.Price,
|
||||
Status: e.Status,
|
||||
Description: e.Description,
|
||||
Image: e.Image,
|
||||
BranchID: e.BranchID,
|
||||
StockQty: e.StockQty,
|
||||
CreatedAt: e.CreatedAt,
|
||||
UpdatedAt: e.UpdatedAt,
|
||||
DeletedAt: e.DeletedAt,
|
||||
CreatedBy: e.CreatedBy,
|
||||
UpdatedBy: e.UpdatedBy,
|
||||
}
|
||||
}
|
||||
|
||||
func (b *ProductList) ToProductList() []*Product {
|
||||
var Products []*Product
|
||||
for _, product := range *b {
|
||||
Products = append(Products, product.ToProduct())
|
||||
}
|
||||
return Products
|
||||
}
|
||||
|
||||
func (o *ProductDB) ToUpdatedProduct(updatedby int64, req Product) {
|
||||
o.UpdatedBy = updatedby
|
||||
|
||||
if req.Name != "" {
|
||||
o.Name = req.Name
|
||||
}
|
||||
|
||||
if req.Type != "" {
|
||||
o.Type = req.Type
|
||||
}
|
||||
|
||||
if req.Price > 0 {
|
||||
o.Price = req.Price
|
||||
}
|
||||
|
||||
if req.Status != "" {
|
||||
o.Status = req.Status
|
||||
}
|
||||
|
||||
if req.Description != "" {
|
||||
o.Description = req.Description
|
||||
}
|
||||
|
||||
if req.Image != "" {
|
||||
o.Image = req.Image
|
||||
}
|
||||
|
||||
if req.StockQty > 0 {
|
||||
o.StockQty = req.StockQty
|
||||
}
|
||||
}
|
||||
|
||||
func (o *ProductDB) SetDeleted(updatedby int64) {
|
||||
currentTime := time.Now()
|
||||
o.DeletedAt = ¤tTime
|
||||
o.UpdatedBy = updatedby
|
||||
}
|
||||
@@ -0,0 +1,95 @@
|
||||
package entity
|
||||
|
||||
import (
|
||||
"furtuna-be/internal/constants/studio"
|
||||
"time"
|
||||
)
|
||||
|
||||
type Studio struct {
|
||||
ID int64
|
||||
BranchId int64
|
||||
Name string
|
||||
Status studio.StudioStatus
|
||||
Price float64
|
||||
Metadata []byte `gorm:"type:jsonb"` // Use jsonb data type for JSON data
|
||||
CreatedAt time.Time
|
||||
UpdatedAt time.Time
|
||||
CreatedBy int64
|
||||
UpdatedBy int64
|
||||
}
|
||||
|
||||
func (s *Studio) TableName() string {
|
||||
return "studios"
|
||||
}
|
||||
|
||||
func (s *Studio) NewStudiosDB() *StudioDB {
|
||||
return &StudioDB{
|
||||
Studio: *s,
|
||||
}
|
||||
}
|
||||
|
||||
type StudioList []*StudioDB
|
||||
|
||||
type StudioDB struct {
|
||||
Studio
|
||||
}
|
||||
|
||||
func (s *StudioDB) ToStudio() *Studio {
|
||||
return &Studio{
|
||||
ID: s.ID,
|
||||
BranchId: s.BranchId,
|
||||
Name: s.Name,
|
||||
Status: s.Status,
|
||||
Price: s.Price,
|
||||
Metadata: s.Metadata,
|
||||
CreatedAt: s.CreatedAt,
|
||||
UpdatedAt: s.UpdatedAt,
|
||||
CreatedBy: s.CreatedBy,
|
||||
UpdatedBy: s.UpdatedBy,
|
||||
}
|
||||
}
|
||||
|
||||
func (s *StudioList) ToStudioList() []*Studio {
|
||||
var studios []*Studio
|
||||
for _, studio := range *s {
|
||||
studios = append(studios, studio.ToStudio())
|
||||
}
|
||||
return studios
|
||||
}
|
||||
|
||||
func (s *StudioDB) ToUpdatedStudio(updatedBy int64, req Studio) {
|
||||
s.UpdatedBy = updatedBy
|
||||
|
||||
if req.BranchId != 0 {
|
||||
s.BranchId = req.BranchId
|
||||
}
|
||||
|
||||
if req.Name != "" {
|
||||
s.Name = req.Name
|
||||
}
|
||||
|
||||
if req.Status != "" {
|
||||
s.Status = req.Status
|
||||
}
|
||||
|
||||
if req.Price != 0 {
|
||||
s.Price = req.Price
|
||||
}
|
||||
|
||||
if req.Metadata != nil {
|
||||
s.Metadata = req.Metadata
|
||||
}
|
||||
}
|
||||
|
||||
func (s *StudioDB) ToStudioDB() *StudioDB {
|
||||
return s
|
||||
}
|
||||
|
||||
type StudioSearch struct {
|
||||
Id int64
|
||||
Name string
|
||||
Status studio.StudioStatus
|
||||
BranchId int64
|
||||
Limit int
|
||||
Offset int
|
||||
}
|
||||
@@ -0,0 +1,35 @@
|
||||
package entity
|
||||
|
||||
import (
|
||||
"furtuna-be/internal/constants/transaction"
|
||||
"time"
|
||||
)
|
||||
|
||||
type Transaction struct {
|
||||
ID int64
|
||||
BranchID int64
|
||||
Status transaction.PaymentStatus
|
||||
Amount float64
|
||||
OrderID int64
|
||||
PaymentMethod transaction.PaymentMethod
|
||||
CustomerName string
|
||||
CustomerPhone string
|
||||
CreatedAt time.Time
|
||||
UpdatedAt time.Time
|
||||
CreatedBy int64
|
||||
UpdatedBy int64
|
||||
}
|
||||
|
||||
type TransactionDB struct {
|
||||
Transaction
|
||||
}
|
||||
|
||||
func (b *Transaction) ToTransactionDB() *TransactionDB {
|
||||
return &TransactionDB{
|
||||
Transaction: *b,
|
||||
}
|
||||
}
|
||||
|
||||
func (TransactionDB) TableName() string {
|
||||
return "transactions"
|
||||
}
|
||||
@@ -0,0 +1,78 @@
|
||||
package entity
|
||||
|
||||
import (
|
||||
"errors"
|
||||
"furtuna-be/internal/constants/role"
|
||||
"furtuna-be/internal/constants/userstatus"
|
||||
"time"
|
||||
|
||||
"golang.org/x/crypto/bcrypt"
|
||||
)
|
||||
|
||||
type User struct {
|
||||
ID int64
|
||||
Name string
|
||||
Email string
|
||||
Password string
|
||||
Status userstatus.UserStatus
|
||||
NIK string
|
||||
CreatedAt time.Time
|
||||
UpdatedAt time.Time
|
||||
RoleID role.Role
|
||||
RoleName string
|
||||
PartnerID *int64
|
||||
BranchName string
|
||||
}
|
||||
|
||||
type AuthenticateUser struct {
|
||||
Token string
|
||||
Name string
|
||||
RoleID role.Role
|
||||
RoleName string
|
||||
BranchID *int64
|
||||
BranchName string
|
||||
}
|
||||
|
||||
type UserRoleDB struct {
|
||||
ID int64 `gorm:"primary_key;column:user_role_id" `
|
||||
UserID int64 `gorm:"column:user_id"`
|
||||
RoleID int64 `gorm:"column:role_id"`
|
||||
PartnerID *int64 `gorm:"column:partner_id"`
|
||||
CreatedAt time.Time `gorm:"column:created_at"`
|
||||
UpdatedAt time.Time `gorm:"column:updated_at"`
|
||||
}
|
||||
|
||||
func (UserRoleDB) TableName() string {
|
||||
return "user_roles"
|
||||
}
|
||||
|
||||
func (u *User) ToUserDB(createdBy int64) (*UserDB, error) {
|
||||
hashedPassword, err := u.HashedPassword(u.Password)
|
||||
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
if u.RoleID == role.BranchAdmin && u.PartnerID == nil {
|
||||
return nil, errors.New("invalid request")
|
||||
}
|
||||
|
||||
return &UserDB{
|
||||
Name: u.Name,
|
||||
Email: u.Email,
|
||||
Password: hashedPassword,
|
||||
RoleID: int64(u.RoleID),
|
||||
BranchID: u.PartnerID,
|
||||
Status: userstatus.Active,
|
||||
CreatedBy: createdBy,
|
||||
}, nil
|
||||
}
|
||||
|
||||
func (u User) HashedPassword(password string) (string, error) {
|
||||
hashedPassword, err := bcrypt.GenerateFromPassword([]byte(password), bcrypt.DefaultCost)
|
||||
if err != nil {
|
||||
return "", err
|
||||
}
|
||||
|
||||
return string(hashedPassword), nil
|
||||
}
|
||||
@@ -0,0 +1,79 @@
|
||||
package auth
|
||||
|
||||
import (
|
||||
"furtuna-be/internal/constants/role"
|
||||
"net/http"
|
||||
|
||||
"github.com/gin-gonic/gin"
|
||||
|
||||
"furtuna-be/internal/common/errors"
|
||||
auth2 "furtuna-be/internal/handlers/request"
|
||||
"furtuna-be/internal/handlers/response"
|
||||
"furtuna-be/internal/services"
|
||||
)
|
||||
|
||||
type AuthHandler struct {
|
||||
service services.Auth
|
||||
}
|
||||
|
||||
func (a *AuthHandler) Route(group *gin.RouterGroup, jwt gin.HandlerFunc) {
|
||||
authRoute := group.Group("/auth")
|
||||
authRoute.POST("/login", a.AuthLogin)
|
||||
}
|
||||
|
||||
func NewAuthHandler(service services.Auth) *AuthHandler {
|
||||
return &AuthHandler{
|
||||
service: service,
|
||||
}
|
||||
}
|
||||
|
||||
// AuthLogin handles the authentication process for user login.
|
||||
// @Summary User login
|
||||
// @Description Authenticates a user based on the provided credentials and returns a JWT token.
|
||||
// @Accept json
|
||||
// @Produce json
|
||||
// @Param bodyParam body auth2.LoginRequest true "User login credentials"
|
||||
// @Success 200 {object} response.BaseResponse{data=response.LoginResponse} "Login successful"
|
||||
// @Failure 400 {object} response.BaseResponse{data=errors.Error} "Bad request"
|
||||
// @Failure 401 {object} response.BaseResponse{data=errors.Error} "Unauthorized"
|
||||
// @Router /api/v1/auth/login [post]
|
||||
// @Tags Auth Login API's
|
||||
func (h *AuthHandler) AuthLogin(c *gin.Context) {
|
||||
var bodyParam auth2.LoginRequest
|
||||
if err := c.ShouldBindJSON(&bodyParam); err != nil {
|
||||
response.ErrorWrapper(c, errors.ErrorBadRequest)
|
||||
return
|
||||
}
|
||||
|
||||
authUser, err := h.service.AuthenticateUser(c, bodyParam.Email, bodyParam.Password)
|
||||
if err != nil {
|
||||
response.ErrorWrapper(c, err)
|
||||
return
|
||||
}
|
||||
|
||||
var branch *response.Branch
|
||||
|
||||
if authUser.RoleID != role.SuperAdmin {
|
||||
branch = &response.Branch{
|
||||
ID: authUser.BranchID,
|
||||
Name: authUser.BranchName,
|
||||
}
|
||||
}
|
||||
|
||||
resp := response.LoginResponse{
|
||||
Token: authUser.Token,
|
||||
Branch: branch,
|
||||
Name: authUser.Name,
|
||||
Role: response.Role{
|
||||
ID: int64(authUser.RoleID),
|
||||
Role: authUser.RoleName,
|
||||
},
|
||||
}
|
||||
|
||||
c.JSON(http.StatusOK, response.BaseResponse{
|
||||
Success: true,
|
||||
Status: http.StatusOK,
|
||||
Message: "Login Success",
|
||||
Data: resp,
|
||||
})
|
||||
}
|
||||
@@ -0,0 +1,264 @@
|
||||
package branch
|
||||
|
||||
import (
|
||||
"furtuna-be/internal/common/errors"
|
||||
"furtuna-be/internal/entity"
|
||||
"furtuna-be/internal/handlers/request"
|
||||
"furtuna-be/internal/handlers/response"
|
||||
"furtuna-be/internal/services"
|
||||
"net/http"
|
||||
"strconv"
|
||||
"time"
|
||||
|
||||
"github.com/gin-gonic/gin"
|
||||
"github.com/go-playground/validator/v10"
|
||||
)
|
||||
|
||||
type Handler struct {
|
||||
service services.Branch
|
||||
}
|
||||
|
||||
func (h *Handler) Route(group *gin.RouterGroup, jwt gin.HandlerFunc) {
|
||||
route := group.Group("/branch")
|
||||
|
||||
route.POST("/", jwt, h.Create)
|
||||
route.GET("/list", jwt, h.GetAll)
|
||||
route.PUT("/:id", jwt, h.Update)
|
||||
route.GET("/:id", jwt, h.GetByID)
|
||||
route.DELETE("/:id", jwt, h.Delete)
|
||||
}
|
||||
|
||||
func NewHandler(service services.Branch) *Handler {
|
||||
return &Handler{
|
||||
service: service,
|
||||
}
|
||||
}
|
||||
|
||||
// Create handles the creation of a new branch.
|
||||
// @Summary Create a new branch
|
||||
// @Description Create a new branch based on the provided data.
|
||||
// @Accept json
|
||||
// @Produce json
|
||||
// @Param Authorization header string true "JWT token"
|
||||
// @Param req body request.Branch true "New branch details"
|
||||
// @Success 200 {object} response.BaseResponse{data=response.Branch} "Branch created successfully"
|
||||
// @Failure 400 {object} response.BaseResponse{data=errors.Error} "Bad request"
|
||||
// @Failure 401 {object} response.BaseResponse{data=errors.Error} "Unauthorized"
|
||||
// @Router /api/v1/branch [post]
|
||||
// @Tags Branch APIs
|
||||
func (h *Handler) Create(c *gin.Context) {
|
||||
ctx := request.GetMyContext(c)
|
||||
|
||||
var req request.Branch
|
||||
if err := c.ShouldBindJSON(&req); err != nil {
|
||||
response.ErrorWrapper(c, errors.ErrorBadRequest)
|
||||
return
|
||||
}
|
||||
|
||||
validate := validator.New()
|
||||
if err := validate.Struct(req); err != nil {
|
||||
response.ErrorWrapper(c, err)
|
||||
return
|
||||
}
|
||||
|
||||
res, err := h.service.Create(ctx, req.ToEntity())
|
||||
|
||||
if err != nil {
|
||||
response.ErrorWrapper(c, err)
|
||||
return
|
||||
}
|
||||
|
||||
c.JSON(http.StatusOK, response.BaseResponse{
|
||||
Success: true,
|
||||
Status: http.StatusOK,
|
||||
Data: h.toBranchResponse(res),
|
||||
})
|
||||
}
|
||||
|
||||
// Update handles the update of an existing branch.
|
||||
// @Summary Update an existing branch
|
||||
// @Description Update the details of an existing branch based on the provided ID.
|
||||
// @Accept json
|
||||
// @Produce json
|
||||
// @Param Authorization header string true "JWT token"
|
||||
// @Param id path int64 true "Branch ID to update"
|
||||
// @Param req body request.Branch true "Updated branch details"
|
||||
// @Success 200 {object} response.BaseResponse{data=response.Branch} "Branch updated successfully"
|
||||
// @Failure 400 {object} response.BaseResponse{data=errors.Error} "Bad request"
|
||||
// @Failure 401 {object} response.BaseResponse{data=errors.Error} "Unauthorized"
|
||||
// @Router /api/v1/branch/{id} [put]
|
||||
// @Tags Branch APIs
|
||||
func (h *Handler) Update(c *gin.Context) {
|
||||
ctx := request.GetMyContext(c)
|
||||
|
||||
id := c.Param("id")
|
||||
|
||||
branchID, err := strconv.ParseInt(id, 10, 64)
|
||||
if err != nil {
|
||||
response.ErrorWrapper(c, errors.ErrorBadRequest)
|
||||
return
|
||||
}
|
||||
|
||||
var req request.Branch
|
||||
if err := c.ShouldBindJSON(&req); err != nil {
|
||||
response.ErrorWrapper(c, errors.ErrorBadRequest)
|
||||
return
|
||||
}
|
||||
|
||||
validate := validator.New()
|
||||
if err := validate.Struct(req); err != nil {
|
||||
response.ErrorWrapper(c, err)
|
||||
return
|
||||
}
|
||||
|
||||
updatedBranch, err := h.service.Update(ctx, branchID, req.ToEntity())
|
||||
if err != nil {
|
||||
response.ErrorWrapper(c, err)
|
||||
return
|
||||
}
|
||||
|
||||
c.JSON(http.StatusOK, response.BaseResponse{
|
||||
Success: true,
|
||||
Status: http.StatusOK,
|
||||
Data: h.toBranchResponse(updatedBranch),
|
||||
})
|
||||
}
|
||||
|
||||
// GetAll retrieves a list of branches.
|
||||
// @Summary Get a list of branches
|
||||
// @Description Get a paginated list of branches based on query parameters.
|
||||
// @Accept json
|
||||
// @Produce json
|
||||
// @Param Authorization header string true "JWT token"
|
||||
// @Param Limit query int false "Number of items to retrieve (default 10)"
|
||||
// @Param Offset query int false "Offset for pagination (default 0)"
|
||||
// @Success 200 {object} response.BaseResponse{data=response.BranchList} "List of branches"
|
||||
// @Failure 400 {object} response.BaseResponse{data=errors.Error} "Bad request"
|
||||
// @Failure 401 {object} response.BaseResponse{data=errors.Error} "Unauthorized"
|
||||
// @Router /api/v1/branch/list [get]
|
||||
// @Tags Branch APIs
|
||||
func (h *Handler) GetAll(c *gin.Context) {
|
||||
var req request.BranchParam
|
||||
if err := c.ShouldBindQuery(&req); err != nil {
|
||||
response.ErrorWrapper(c, errors.ErrorBadRequest)
|
||||
return
|
||||
}
|
||||
|
||||
branchs, total, err := h.service.GetAll(c.Request.Context(), req.ToEntity())
|
||||
if err != nil {
|
||||
response.ErrorWrapper(c, err)
|
||||
return
|
||||
}
|
||||
|
||||
c.JSON(http.StatusOK, response.BaseResponse{
|
||||
Success: true,
|
||||
Status: http.StatusOK,
|
||||
Data: h.toBranchResponseList(branchs, int64(total), req),
|
||||
})
|
||||
}
|
||||
|
||||
// Delete handles the deletion of a branch by ID.
|
||||
// @Summary Delete a branch by ID
|
||||
// @Description Delete a branch based on the provided ID.
|
||||
// @Accept json
|
||||
// @Produce json
|
||||
// @Param Authorization header string true "JWT token"
|
||||
// @Param id path int64 true "Branch ID to delete"
|
||||
// @Success 200 {object} response.BaseResponse "Branch deleted successfully"
|
||||
// @Failure 400 {object} response.BaseResponse{data=errors.Error} "Bad request"
|
||||
// @Failure 401 {object} response.BaseResponse{data=errors.Error} "Unauthorized"
|
||||
// @Router /api/v1/branch/{id} [delete]
|
||||
// @Tags Branch APIs
|
||||
func (h *Handler) Delete(c *gin.Context) {
|
||||
ctx := request.GetMyContext(c)
|
||||
id := c.Param("id")
|
||||
|
||||
// Parse the ID into a uint
|
||||
branchID, err := strconv.ParseInt(id, 10, 64)
|
||||
if err != nil {
|
||||
response.ErrorWrapper(c, errors.ErrorBadRequest)
|
||||
return
|
||||
}
|
||||
|
||||
err = h.service.Delete(ctx, branchID)
|
||||
if err != nil {
|
||||
c.JSON(http.StatusInternalServerError, response.BaseResponse{
|
||||
Success: false,
|
||||
Status: http.StatusInternalServerError,
|
||||
Message: err.Error(),
|
||||
Data: nil,
|
||||
})
|
||||
return
|
||||
}
|
||||
|
||||
c.JSON(http.StatusOK, response.BaseResponse{
|
||||
Success: true,
|
||||
Status: http.StatusOK,
|
||||
Data: nil,
|
||||
})
|
||||
}
|
||||
|
||||
// GetByID retrieves details of a specific branch by ID.
|
||||
// @Summary Get details of a branch by ID
|
||||
// @Description Get details of a branch based on the provided ID.
|
||||
// @Accept json
|
||||
// @Produce json
|
||||
// @Param Authorization header string true "JWT token"
|
||||
// @Param id path int64 true "Branch ID to retrieve"
|
||||
// @Success 200 {object} response.BaseResponse{data=response.Branch} "Branch details"
|
||||
// @Failure 400 {object} response.BaseResponse{data=errors.Error} "Bad request"
|
||||
// @Failure 401 {object} response.BaseResponse{data=errors.Error} "Unauthorized"
|
||||
// @Router /api/v1/branch/{id} [get]
|
||||
// @Tags Branch APIs
|
||||
func (h *Handler) GetByID(c *gin.Context) {
|
||||
id := c.Param("id")
|
||||
|
||||
// Parse the ID into a uint
|
||||
branchID, err := strconv.ParseInt(id, 10, 64)
|
||||
if err != nil {
|
||||
response.ErrorWrapper(c, errors.ErrorBadRequest)
|
||||
return
|
||||
}
|
||||
|
||||
res, err := h.service.GetByID(c.Request.Context(), branchID)
|
||||
if err != nil {
|
||||
c.JSON(http.StatusInternalServerError, response.BaseResponse{
|
||||
Success: false,
|
||||
Status: http.StatusInternalServerError,
|
||||
Message: err.Error(),
|
||||
Data: nil,
|
||||
})
|
||||
return
|
||||
}
|
||||
|
||||
c.JSON(http.StatusOK, response.BaseResponse{
|
||||
Success: true,
|
||||
Status: http.StatusOK,
|
||||
Data: h.toBranchResponse(res),
|
||||
})
|
||||
}
|
||||
|
||||
func (h *Handler) toBranchResponse(resp *entity.Branch) response.Branch {
|
||||
return response.Branch{
|
||||
ID: &resp.ID,
|
||||
Name: resp.Name,
|
||||
Status: string(resp.Status),
|
||||
Location: resp.Location,
|
||||
CreatedAt: resp.CreatedAt.Format(time.RFC3339),
|
||||
UpdatedAt: resp.CreatedAt.Format(time.RFC3339),
|
||||
}
|
||||
}
|
||||
|
||||
func (h *Handler) toBranchResponseList(resp []*entity.Branch, total int64, req request.BranchParam) response.BranchList {
|
||||
var branches []response.Branch
|
||||
for _, b := range resp {
|
||||
branches = append(branches, h.toBranchResponse(b))
|
||||
}
|
||||
|
||||
return response.BranchList{
|
||||
Branches: branches,
|
||||
Total: total,
|
||||
Limit: req.Limit,
|
||||
Offset: req.Offset,
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,205 @@
|
||||
package event
|
||||
|
||||
import (
|
||||
"net/http"
|
||||
"strconv"
|
||||
"time"
|
||||
|
||||
"github.com/gin-gonic/gin"
|
||||
|
||||
"furtuna-be/internal/common/errors"
|
||||
"furtuna-be/internal/entity"
|
||||
"furtuna-be/internal/handlers/request"
|
||||
"furtuna-be/internal/handlers/response"
|
||||
"furtuna-be/internal/services"
|
||||
)
|
||||
|
||||
type Handler struct {
|
||||
service services.Event
|
||||
}
|
||||
|
||||
func (h *Handler) Route(group *gin.RouterGroup, jwt gin.HandlerFunc) {
|
||||
route := group.Group("/event")
|
||||
|
||||
route.POST("/", jwt, h.Create)
|
||||
route.GET("/list", jwt, h.GetAll)
|
||||
route.PUT("/:id", jwt, h.Update)
|
||||
route.GET("/:id", jwt, h.GetByID)
|
||||
route.DELETE("/:id", jwt, h.Delete)
|
||||
}
|
||||
|
||||
func NewHandler(service services.Event) *Handler {
|
||||
return &Handler{
|
||||
service: service,
|
||||
}
|
||||
}
|
||||
|
||||
func (h *Handler) Create(c *gin.Context) {
|
||||
var req request.Event
|
||||
if err := c.ShouldBindJSON(&req); err != nil {
|
||||
response.ErrorWrapper(c, errors.ErrorBadRequest)
|
||||
return
|
||||
}
|
||||
|
||||
if err := req.Validate(); err != nil {
|
||||
response.ErrorWrapper(c, errors.ErrorInvalidRequest)
|
||||
return
|
||||
}
|
||||
|
||||
res, err := h.service.Create(c.Request.Context(), req.ToEntity())
|
||||
|
||||
if err != nil {
|
||||
response.ErrorWrapper(c, err)
|
||||
return
|
||||
}
|
||||
|
||||
c.JSON(http.StatusOK, response.BaseResponse{
|
||||
Success: true,
|
||||
Status: http.StatusOK,
|
||||
Data: h.toEventResponse(res),
|
||||
})
|
||||
}
|
||||
|
||||
func (h *Handler) Update(c *gin.Context) {
|
||||
id := c.Param("id")
|
||||
|
||||
eventID, err := strconv.ParseInt(id, 10, 64)
|
||||
if err != nil {
|
||||
response.ErrorWrapper(c, errors.ErrorBadRequest)
|
||||
return
|
||||
}
|
||||
|
||||
var req request.Event
|
||||
if err := c.ShouldBindJSON(&req); err != nil {
|
||||
response.ErrorWrapper(c, errors.ErrorBadRequest)
|
||||
return
|
||||
}
|
||||
|
||||
if err := req.Validate(); err != nil {
|
||||
response.ErrorWrapper(c, errors.ErrorBadRequest)
|
||||
return
|
||||
}
|
||||
|
||||
updatedEvent, err := h.service.Update(c.Request.Context(), eventID, req.ToEntity())
|
||||
if err != nil {
|
||||
response.ErrorWrapper(c, err)
|
||||
return
|
||||
}
|
||||
|
||||
c.JSON(http.StatusOK, response.BaseResponse{
|
||||
Success: true,
|
||||
Status: http.StatusOK,
|
||||
Data: h.toEventResponse(updatedEvent),
|
||||
})
|
||||
}
|
||||
|
||||
func (h *Handler) GetAll(c *gin.Context) {
|
||||
var req request.EventParam
|
||||
if err := c.ShouldBindQuery(&req); err != nil {
|
||||
response.ErrorWrapper(c, errors.ErrorBadRequest)
|
||||
return
|
||||
}
|
||||
|
||||
events, total, err := h.service.GetAll(c.Request.Context(), req.ToEntity())
|
||||
if err != nil {
|
||||
response.ErrorWrapper(c, err)
|
||||
return
|
||||
}
|
||||
|
||||
c.JSON(http.StatusOK, response.BaseResponse{
|
||||
Success: true,
|
||||
Status: http.StatusOK,
|
||||
Data: h.toEventResponseList(events, int64(total), req),
|
||||
})
|
||||
}
|
||||
|
||||
func (h *Handler) Delete(c *gin.Context) {
|
||||
id := c.Param("id")
|
||||
|
||||
// Parse the ID into a uint
|
||||
eventID, err := strconv.ParseInt(id, 10, 64)
|
||||
if err != nil {
|
||||
response.ErrorWrapper(c, errors.ErrorBadRequest)
|
||||
return
|
||||
}
|
||||
|
||||
err = h.service.Delete(c.Request.Context(), eventID)
|
||||
if err != nil {
|
||||
c.JSON(http.StatusInternalServerError, response.BaseResponse{
|
||||
Success: false,
|
||||
Status: http.StatusInternalServerError,
|
||||
Message: err.Error(),
|
||||
Data: nil,
|
||||
})
|
||||
return
|
||||
}
|
||||
|
||||
c.JSON(http.StatusOK, response.BaseResponse{
|
||||
Success: true,
|
||||
Status: http.StatusOK,
|
||||
Data: nil,
|
||||
})
|
||||
}
|
||||
|
||||
func (h *Handler) GetByID(c *gin.Context) {
|
||||
id := c.Param("id")
|
||||
|
||||
// Parse the ID into a uint
|
||||
eventID, err := strconv.ParseInt(id, 10, 64)
|
||||
if err != nil {
|
||||
response.ErrorWrapper(c, errors.ErrorBadRequest)
|
||||
return
|
||||
}
|
||||
|
||||
res, err := h.service.GetByID(c.Request.Context(), eventID)
|
||||
if err != nil {
|
||||
c.JSON(http.StatusInternalServerError, response.BaseResponse{
|
||||
Success: false,
|
||||
Status: http.StatusInternalServerError,
|
||||
Message: err.Error(),
|
||||
Data: nil,
|
||||
})
|
||||
return
|
||||
}
|
||||
|
||||
c.JSON(http.StatusOK, response.BaseResponse{
|
||||
Success: true,
|
||||
Status: http.StatusOK,
|
||||
Data: h.toEventResponse(res),
|
||||
})
|
||||
}
|
||||
|
||||
func (h *Handler) toEventResponse(resp *entity.Event) response.Event {
|
||||
return response.Event{
|
||||
ID: resp.ID,
|
||||
Name: resp.Name,
|
||||
Description: resp.Description,
|
||||
StartDate: resp.StartDate.Format("2006-01-02"),
|
||||
EndDate: resp.EndDate.Format("2006-01-02"),
|
||||
StartTime: resp.StartDate.Format("15:04:05"),
|
||||
EndTime: resp.EndDate.Format("15:04:05"),
|
||||
Location: resp.Location,
|
||||
Level: resp.Level,
|
||||
Included: resp.Included,
|
||||
Price: resp.Price,
|
||||
Paid: resp.Paid,
|
||||
LocationID: resp.LocationID,
|
||||
CreatedAt: resp.CreatedAt.Format(time.RFC3339),
|
||||
UpdatedAt: resp.CreatedAt.Format(time.RFC3339),
|
||||
Status: string(resp.Status),
|
||||
}
|
||||
}
|
||||
|
||||
func (h *Handler) toEventResponseList(resp []*entity.Event, total int64, req request.EventParam) response.EventList {
|
||||
var events []response.Event
|
||||
for _, evt := range resp {
|
||||
events = append(events, h.toEventResponse(evt))
|
||||
}
|
||||
|
||||
return response.EventList{
|
||||
Events: events,
|
||||
Total: total,
|
||||
Limit: req.Limit,
|
||||
Offset: req.Offset,
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,409 @@
|
||||
package order
|
||||
|
||||
import (
|
||||
"furtuna-be/internal/common/errors"
|
||||
"furtuna-be/internal/entity"
|
||||
"furtuna-be/internal/handlers/request"
|
||||
"furtuna-be/internal/handlers/response"
|
||||
"furtuna-be/internal/services"
|
||||
"net/http"
|
||||
"strconv"
|
||||
"time"
|
||||
|
||||
"github.com/gin-gonic/gin"
|
||||
"github.com/go-playground/validator/v10"
|
||||
)
|
||||
|
||||
type Handler struct {
|
||||
service services.Order
|
||||
}
|
||||
|
||||
func (h *Handler) Route(group *gin.RouterGroup, jwt gin.HandlerFunc) {
|
||||
route := group.Group("/order")
|
||||
|
||||
route.POST("/", jwt, h.Create)
|
||||
route.GET("/list", jwt, h.GetAll)
|
||||
route.GET("/:id", jwt, h.GetByID)
|
||||
route.GET("/total-revenue", jwt, h.GetTotalRevenue)
|
||||
route.GET("/yearly-revenue/:year", jwt, h.GetYearlyRevenue)
|
||||
route.GET("/branch-revenue", jwt, h.GetBranchRevenue)
|
||||
route.PUT("/update-status/:id", jwt, h.UpdateStatus)
|
||||
}
|
||||
|
||||
func NewHandler(service services.Order) *Handler {
|
||||
return &Handler{
|
||||
service: service,
|
||||
}
|
||||
}
|
||||
|
||||
// Create handles the creation of a new order.
|
||||
// @Summary Create a new order
|
||||
// @Description Create a new order with the provided details.
|
||||
// @Accept json
|
||||
// @Produce json
|
||||
// @Param Authorization header string true "JWT token"
|
||||
// @Param order body request.Order true "Order details"
|
||||
// @Success 200 {object} response.BaseResponse "Order created successfully"
|
||||
// @Failure 400 {object} response.BaseResponse{data=errors.Error} "Bad request"
|
||||
// @Failure 401 {object} response.BaseResponse{data=errors.Error} "Unauthorized"
|
||||
// @Router /api/v1/order [post]
|
||||
// @Tag Order APIs
|
||||
func (h *Handler) Create(c *gin.Context) {
|
||||
ctx := request.GetMyContext(c)
|
||||
|
||||
var req request.Order
|
||||
if err := c.ShouldBindJSON(&req); err != nil {
|
||||
response.ErrorWrapper(c, errors.ErrorBadRequest)
|
||||
return
|
||||
}
|
||||
|
||||
validate := validator.New()
|
||||
if err := validate.Struct(req); err != nil {
|
||||
response.ErrorWrapper(c, err)
|
||||
return
|
||||
}
|
||||
|
||||
err := h.service.Create(ctx, req.ToEntity())
|
||||
|
||||
if err != nil {
|
||||
response.ErrorWrapper(c, err)
|
||||
return
|
||||
}
|
||||
|
||||
c.JSON(http.StatusOK, response.BaseResponse{
|
||||
Success: true,
|
||||
Status: http.StatusOK,
|
||||
})
|
||||
}
|
||||
|
||||
// UpdateStatus handles the update of the order status.
|
||||
// @Summary Update the status of an order
|
||||
// @Description Update the status of the specified order with the provided details.
|
||||
// @Accept json
|
||||
// @Produce json
|
||||
// @Param Authorization header string true "JWT token"
|
||||
// @Param id path string true "Order ID"
|
||||
// @Param status body request.UpdateStatus true "Status details"
|
||||
// @Success 200 {object} response.BaseResponse{data=response.Order} "Order status updated successfully"
|
||||
// @Failure 400 {object} response.BaseResponse{data=errors.Error} "Bad request"
|
||||
// @Failure 401 {object} response.BaseResponse{data=errors.Error} "Unauthorized"
|
||||
// @Failure 500 {object} response.BaseResponse "Internal server error"
|
||||
// @Router /api/v1/order/update-status/{id} [put]
|
||||
// @Tag Order APIs
|
||||
func (h *Handler) UpdateStatus(c *gin.Context) {
|
||||
ctx := request.GetMyContext(c)
|
||||
|
||||
var req request.UpdateStatus
|
||||
if err := c.ShouldBindJSON(&req); err != nil {
|
||||
response.ErrorWrapper(c, errors.ErrorBadRequest)
|
||||
return
|
||||
}
|
||||
|
||||
id := c.Param("id")
|
||||
|
||||
// Parse the ID into a uint
|
||||
orderID, err := strconv.ParseInt(id, 10, 64)
|
||||
if err != nil {
|
||||
response.ErrorWrapper(c, errors.ErrorBadRequest)
|
||||
return
|
||||
}
|
||||
|
||||
res, err := h.service.UpdateStatus(ctx, orderID, req.ToEntity())
|
||||
if err != nil {
|
||||
c.JSON(http.StatusInternalServerError, response.BaseResponse{
|
||||
Success: false,
|
||||
Status: http.StatusInternalServerError,
|
||||
Message: err.Error(),
|
||||
Data: nil,
|
||||
})
|
||||
return
|
||||
}
|
||||
|
||||
c.JSON(http.StatusOK, response.BaseResponse{
|
||||
Success: true,
|
||||
Status: http.StatusOK,
|
||||
Data: h.toOrderResponse(res),
|
||||
})
|
||||
}
|
||||
|
||||
// GetByID retrieves the details of a specific order by ID.
|
||||
// @Summary Get details of an order by ID
|
||||
// @Description Retrieve the details of the specified order by ID.
|
||||
// @Accept json
|
||||
// @Produce json
|
||||
// @Param Authorization header string true "JWT token"
|
||||
// @Param id path string true "Order ID"
|
||||
// @Success 200 {object} response.BaseResponse{data=response.Order} "Order details retrieved successfully"
|
||||
// @Failure 400 {object} response.BaseResponse{data=errors.Error} "Bad request"
|
||||
// @Failure 401 {object} response.BaseResponse{data=errors.Error} "Unauthorized"
|
||||
// @Failure 500 {object} response.BaseResponse "Internal server error"
|
||||
// @Router /api/v1/order/{id} [get]
|
||||
// @Tag Order APIs
|
||||
func (h *Handler) GetByID(c *gin.Context) {
|
||||
id := c.Param("id")
|
||||
|
||||
// Parse the ID into a uint
|
||||
orderID, err := strconv.ParseInt(id, 10, 64)
|
||||
if err != nil {
|
||||
response.ErrorWrapper(c, errors.ErrorBadRequest)
|
||||
return
|
||||
}
|
||||
|
||||
res, err := h.service.GetByID(c.Request.Context(), orderID)
|
||||
if err != nil {
|
||||
c.JSON(http.StatusInternalServerError, response.BaseResponse{
|
||||
Success: false,
|
||||
Status: http.StatusInternalServerError,
|
||||
Message: err.Error(),
|
||||
Data: nil,
|
||||
})
|
||||
return
|
||||
}
|
||||
|
||||
c.JSON(http.StatusOK, response.BaseResponse{
|
||||
Success: true,
|
||||
Status: http.StatusOK,
|
||||
Data: h.toOrderResponse(res),
|
||||
})
|
||||
}
|
||||
|
||||
// GetAll retrieves a list of orders based on the specified parameters.
|
||||
// @Summary Get a list of orders
|
||||
// @Description Retrieve a list of orders based on the specified parameters.
|
||||
// @Accept json
|
||||
// @Produce json
|
||||
// @Param Authorization header string true "JWT token"
|
||||
// @Param limit query int false "Number of items to retrieve (default: 10)"
|
||||
// @Param offset query int false "Number of items to skip (default: 0)"
|
||||
// @Success 200 {object} response.BaseResponse{data=response.OrderList} "List of orders retrieved successfully"
|
||||
// @Failure 400 {object} response.BaseResponse{data=errors.Error} "Bad request"
|
||||
// @Failure 401 {object} response.BaseResponse{data=errors.Error} "Unauthorized"
|
||||
// @Failure 500 {object} response.BaseResponse "Internal server error"
|
||||
// @Router /api/v1/order/list [get]
|
||||
// @Tag Order APIs
|
||||
func (h *Handler) GetAll(c *gin.Context) {
|
||||
var req request.OrderParam
|
||||
if err := c.ShouldBindQuery(&req); err != nil {
|
||||
response.ErrorWrapper(c, errors.ErrorBadRequest)
|
||||
return
|
||||
}
|
||||
|
||||
orders, total, err := h.service.GetAll(c.Request.Context(), req.ToEntity())
|
||||
if err != nil {
|
||||
response.ErrorWrapper(c, err)
|
||||
return
|
||||
}
|
||||
|
||||
c.JSON(http.StatusOK, response.BaseResponse{
|
||||
Success: true,
|
||||
Status: http.StatusOK,
|
||||
Data: h.toOrderResponseList(orders, int64(total), req),
|
||||
})
|
||||
}
|
||||
|
||||
// GetTotalRevenue retrieves the total revenue and number of transactions for orders.
|
||||
// @Summary Get total revenue and number of transactions for orders
|
||||
// @Description Retrieve the total revenue and number of transactions for orders based on the specified parameters.
|
||||
// @Accept json
|
||||
// @Produce json
|
||||
// @Param Authorization header string true "JWT token"
|
||||
// @Param start_date query string false "Start date for filtering (format: 'YYYY-MM-DD')"
|
||||
// @Param end_date query string false "End date for filtering (format: 'YYYY-MM-DD')"
|
||||
// @Success 200 {object} response.BaseResponse{data=response.OrderMonthlyRevenue} "Total revenue and transactions retrieved successfully"
|
||||
// @Failure 400 {object} response.BaseResponse{data=errors.Error} "Bad request"
|
||||
// @Failure 401 {object} response.BaseResponse{data=errors.Error} "Unauthorized"
|
||||
// @Failure 500 {object} response.BaseResponse "Internal server error"
|
||||
// @Router /api/v1/order/total-revenue [get]
|
||||
// @Tag Order APIs
|
||||
func (h *Handler) GetTotalRevenue(c *gin.Context) {
|
||||
var req request.OrderTotalRevenueParam
|
||||
if err := c.ShouldBindQuery(&req); err != nil {
|
||||
response.ErrorWrapper(c, errors.ErrorBadRequest)
|
||||
return
|
||||
}
|
||||
|
||||
rev, trans, err := h.service.GetTotalRevenue(c.Request.Context(), req.ToEntity())
|
||||
if err != nil {
|
||||
c.JSON(http.StatusInternalServerError, response.BaseResponse{
|
||||
Success: false,
|
||||
Status: http.StatusInternalServerError,
|
||||
Message: err.Error(),
|
||||
Data: nil,
|
||||
})
|
||||
return
|
||||
}
|
||||
|
||||
c.JSON(http.StatusOK, response.BaseResponse{
|
||||
Success: true,
|
||||
Status: http.StatusOK,
|
||||
Data: h.toOrderTotalRevenueResponse(rev, trans),
|
||||
})
|
||||
}
|
||||
|
||||
// GetYearlyRevenue retrieves the yearly revenue for orders.
|
||||
// @Summary Get yearly revenue for orders
|
||||
// @Description Retrieve the yearly revenue for orders based on the specified year.
|
||||
// @Accept json
|
||||
// @Produce json
|
||||
// @Param Authorization header string true "JWT token"
|
||||
// @Param year path int true "Year for filtering"
|
||||
// @Success 200 {object} response.BaseResponse{data=map[int]map[string]float64} "Yearly revenue retrieved successfully"
|
||||
// @Failure 400 {object} response.BaseResponse{data=errors.Error} "Bad request"
|
||||
// @Failure 401 {object} response.BaseResponse{data=errors.Error} "Unauthorized"
|
||||
// @Failure 500 {object} response.BaseResponse "Internal server error"
|
||||
// @Router /api/v1/order/yearly-revenue/{year} [get]
|
||||
// @Tag Order APIs
|
||||
func (h *Handler) GetYearlyRevenue(c *gin.Context) {
|
||||
yearParam := c.Param("year")
|
||||
|
||||
// Parse the ID into a uint
|
||||
year, err := strconv.Atoi(yearParam)
|
||||
if err != nil {
|
||||
response.ErrorWrapper(c, errors.ErrorBadRequest)
|
||||
return
|
||||
}
|
||||
|
||||
rev, err := h.service.GetYearlyRevenue(c.Request.Context(), year)
|
||||
if err != nil {
|
||||
c.JSON(http.StatusInternalServerError, response.BaseResponse{
|
||||
Success: false,
|
||||
Status: http.StatusInternalServerError,
|
||||
Message: err.Error(),
|
||||
Data: nil,
|
||||
})
|
||||
return
|
||||
}
|
||||
|
||||
c.JSON(http.StatusOK, response.BaseResponse{
|
||||
Success: true,
|
||||
Status: http.StatusOK,
|
||||
Data: h.toOrderYearlyRevenueResponse(rev),
|
||||
})
|
||||
}
|
||||
|
||||
// GetBranchRevenue retrieves the branch-wise revenue for orders.
|
||||
// @Summary Get branch-wise revenue for orders
|
||||
// @Description Retrieve the branch-wise revenue for orders based on the specified parameters.
|
||||
// @Accept json
|
||||
// @Produce json
|
||||
// @Param Authorization header string true "JWT token"
|
||||
// @Param branch_id query int false "Branch ID for filtering"
|
||||
// @Param start_date query string false "Start date for filtering (format: 'YYYY-MM-DD')"
|
||||
// @Param end_date query string false "End date for filtering (format: 'YYYY-MM-DD')"
|
||||
// @Success 200 {object} response.BaseResponse{data=[]response.OrderBranchRevenue} "Branch-wise revenue retrieved successfully"
|
||||
// @Failure 400 {object} response.BaseResponse{data=errors.Error} "Bad request"
|
||||
// @Failure 401 {object} response.BaseResponse{data=errors.Error} "Unauthorized"
|
||||
// @Failure 500 {object} response.BaseResponse "Internal server error"
|
||||
// @Router /api/v1/order/branch-revenue [get]
|
||||
// @Tag Order APIs
|
||||
func (h *Handler) GetBranchRevenue(c *gin.Context) {
|
||||
var req request.OrderBranchRevenueParam
|
||||
if err := c.ShouldBindQuery(&req); err != nil {
|
||||
response.ErrorWrapper(c, errors.ErrorBadRequest)
|
||||
return
|
||||
}
|
||||
|
||||
rev, err := h.service.GetBranchRevenue(c.Request.Context(), req.ToEntity())
|
||||
if err != nil {
|
||||
c.JSON(http.StatusInternalServerError, response.BaseResponse{
|
||||
Success: false,
|
||||
Status: http.StatusInternalServerError,
|
||||
Message: err.Error(),
|
||||
Data: nil,
|
||||
})
|
||||
return
|
||||
}
|
||||
|
||||
c.JSON(http.StatusOK, response.BaseResponse{
|
||||
Success: true,
|
||||
Status: http.StatusOK,
|
||||
Data: h.toOrderBranchRevenueResponse(rev),
|
||||
})
|
||||
}
|
||||
|
||||
func (h *Handler) toOrderResponse(resp *entity.Order) response.Order {
|
||||
orderItems := []response.OrderItem{}
|
||||
for _, i := range resp.OrderItem {
|
||||
orderItems = append(orderItems, response.OrderItem{
|
||||
OrderItemID: i.OrderItemID,
|
||||
ItemID: i.ItemID,
|
||||
ItemType: i.ItemType,
|
||||
ItemName: i.ItemName,
|
||||
Price: i.Price,
|
||||
Qty: i.Qty,
|
||||
CreatedAt: i.CreatedAt.Format(time.RFC3339),
|
||||
UpdatedAt: i.CreatedAt.Format(time.RFC3339),
|
||||
})
|
||||
}
|
||||
|
||||
return response.Order{
|
||||
ID: resp.ID,
|
||||
BranchID: resp.BranchID,
|
||||
BranchName: resp.BranchName,
|
||||
Amount: resp.Amount,
|
||||
OrderItem: orderItems,
|
||||
Status: resp.Status,
|
||||
CustomerName: resp.CustomerName,
|
||||
CustomerPhone: resp.CustomerPhone,
|
||||
Pax: resp.Pax,
|
||||
PaymentMethod: resp.Transaction.PaymentMethod,
|
||||
CreatedAt: resp.CreatedAt.Format(time.RFC3339),
|
||||
UpdatedAt: resp.CreatedAt.Format(time.RFC3339),
|
||||
}
|
||||
}
|
||||
|
||||
func (h *Handler) toOrderResponseList(resp []*entity.Order, total int64, req request.OrderParam) response.OrderList {
|
||||
var orders []response.Order
|
||||
for _, b := range resp {
|
||||
orders = append(orders, h.toOrderResponse(b))
|
||||
}
|
||||
|
||||
return response.OrderList{
|
||||
Orders: orders,
|
||||
Total: total,
|
||||
Limit: req.Limit,
|
||||
Offset: req.Offset,
|
||||
}
|
||||
}
|
||||
|
||||
func (h *Handler) toOrderTotalRevenueResponse(rev float64, trans int64) response.OrderMonthlyRevenue {
|
||||
return response.OrderMonthlyRevenue{
|
||||
TotalRevenue: rev,
|
||||
TotalTransaction: trans,
|
||||
}
|
||||
}
|
||||
|
||||
func (h *Handler) toOrderYearlyRevenueResponse(data entity.OrderYearlyRevenueList) map[int]map[string]float64 {
|
||||
result := make(map[int]map[string]float64)
|
||||
|
||||
// Initialize result map with 0 values for all months and item types
|
||||
for i := 1; i <= 12; i++ {
|
||||
result[i] = map[string]float64{
|
||||
"PRODUCT": 0,
|
||||
"STUDIO": 0,
|
||||
}
|
||||
}
|
||||
|
||||
// Populate result map with actual data
|
||||
for _, v := range data {
|
||||
result[v.Month][v.ItemType] = v.Amount
|
||||
}
|
||||
|
||||
return result
|
||||
}
|
||||
|
||||
func (h *Handler) toOrderBranchRevenueResponse(data entity.OrderBranchRevenueList) []response.OrderBranchRevenue {
|
||||
var resp []response.OrderBranchRevenue
|
||||
|
||||
for _, v := range data {
|
||||
resp = append(resp, response.OrderBranchRevenue{
|
||||
BranchID: v.BranchID,
|
||||
BranchName: v.BranchName,
|
||||
BranchLocation: v.BranchLocation,
|
||||
TotalTransaction: v.TotalTransaction,
|
||||
TotalAmount: v.TotalAmount,
|
||||
})
|
||||
}
|
||||
|
||||
return resp
|
||||
}
|
||||
@@ -0,0 +1,92 @@
|
||||
package oss
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"furtuna-be/internal/entity"
|
||||
"furtuna-be/internal/handlers/response"
|
||||
"furtuna-be/internal/services"
|
||||
"mime/multipart"
|
||||
"net/http"
|
||||
|
||||
"github.com/gin-gonic/gin"
|
||||
)
|
||||
|
||||
const _oneMB = 1 << 20 // 1MB
|
||||
const _maxUploadSizeMB = 2 * _oneMB
|
||||
const _folderName = "/file"
|
||||
|
||||
type OssHandler struct {
|
||||
ossService services.OSSService
|
||||
}
|
||||
|
||||
func (h *OssHandler) Route(group *gin.RouterGroup, jwt gin.HandlerFunc) {
|
||||
route := group.Group("/file")
|
||||
|
||||
route.POST("/upload", h.UploadFile, jwt)
|
||||
}
|
||||
|
||||
func NewOssHandler(ossService services.OSSService) *OssHandler {
|
||||
return &OssHandler{
|
||||
ossService: ossService,
|
||||
}
|
||||
}
|
||||
|
||||
// UploadFile handles the uploading of a file to OSS.
|
||||
// @Summary Upload a file to OSS
|
||||
// @Description Upload a file to Alibaba Cloud OSS with the provided details.
|
||||
// @Accept mpfd
|
||||
// @Produce json
|
||||
// @Param Authorization header string true "JWT token"
|
||||
// @Param file formData file true "File to upload (max size: 2MB)"
|
||||
// @Success 200 {object} response.BaseResponse{data=entity.UploadFileResponse} "File uploaded successfully"
|
||||
// @Failure 400 {object} response.BaseResponse{data=errors.Error} "Bad request"
|
||||
// @Failure 401 {object} response.BaseResponse{data=errors.Error} "Unauthorized"
|
||||
// @Tags File Upload API
|
||||
// @Router /api/v1/file/upload [post]
|
||||
func (h *OssHandler) UploadFile(c *gin.Context) {
|
||||
// Get the oss file from the request form
|
||||
file, err := c.FormFile("file")
|
||||
if err != nil {
|
||||
c.JSON(http.StatusBadRequest, response.BaseResponse{
|
||||
ErrorMessage: "Failed to retrieve the file",
|
||||
})
|
||||
return
|
||||
}
|
||||
|
||||
// Check if the uploaded file is an image (photo)
|
||||
//if !isPDFFile(file) {
|
||||
// c.JSON(http.StatusBadRequest, response.BaseResponse{
|
||||
// ErrorMessage: "Only image files are allowed",
|
||||
// })
|
||||
// return
|
||||
//}
|
||||
|
||||
// Check if the file size is not greater than the maximum allowed size
|
||||
if file.Size > _maxUploadSizeMB {
|
||||
c.JSON(http.StatusBadRequest, response.BaseResponse{
|
||||
ErrorMessage: fmt.Sprintf("The file is too big. The maximum size is %d", _maxUploadSizeMB/_oneMB),
|
||||
})
|
||||
return
|
||||
}
|
||||
|
||||
// Call the service to oss the file to Alibaba Cloud OSS
|
||||
ret, err := h.ossService.UploadFile(c, &entity.UploadFileRequest{
|
||||
FileHeader: file,
|
||||
FolderName: _folderName,
|
||||
})
|
||||
|
||||
if err != nil {
|
||||
response.ErrorWrapper(c, err)
|
||||
return
|
||||
}
|
||||
|
||||
c.JSON(http.StatusOK, response.BaseResponse{
|
||||
Data: ret,
|
||||
Success: true,
|
||||
})
|
||||
}
|
||||
|
||||
func isPDFFile(file *multipart.FileHeader) bool {
|
||||
contentType := file.Header.Get("Content-Type")
|
||||
return contentType == "application/pdf"
|
||||
}
|
||||
@@ -0,0 +1,265 @@
|
||||
package partner
|
||||
|
||||
import (
|
||||
"furtuna-be/internal/common/errors"
|
||||
"furtuna-be/internal/entity"
|
||||
"furtuna-be/internal/handlers/request"
|
||||
"furtuna-be/internal/handlers/response"
|
||||
"furtuna-be/internal/middlewares"
|
||||
"furtuna-be/internal/services"
|
||||
"net/http"
|
||||
"strconv"
|
||||
"time"
|
||||
|
||||
"github.com/gin-gonic/gin"
|
||||
"github.com/go-playground/validator/v10"
|
||||
)
|
||||
|
||||
type Handler struct {
|
||||
service services.Partner
|
||||
}
|
||||
|
||||
func (h *Handler) Route(group *gin.RouterGroup, jwt gin.HandlerFunc) {
|
||||
route := group.Group("/partner")
|
||||
isSuperAdmin := middlewares.SuperAdminMiddleware()
|
||||
|
||||
route.POST("/", jwt, isSuperAdmin, h.Create)
|
||||
route.GET("/list", jwt, isSuperAdmin, h.GetAll)
|
||||
route.PUT("/:id", jwt, isSuperAdmin, h.Update)
|
||||
route.GET("/:id", jwt, isSuperAdmin, h.GetByID)
|
||||
route.DELETE("/:id", jwt, isSuperAdmin, h.Delete)
|
||||
}
|
||||
|
||||
func NewHandler(service services.Partner) *Handler {
|
||||
return &Handler{
|
||||
service: service,
|
||||
}
|
||||
}
|
||||
|
||||
// Create handles the creation of a new Partner.
|
||||
// @Summary Create a new Partner
|
||||
// @Description Create a new Partner based on the provided data.
|
||||
// @Accept json
|
||||
// @Produce json
|
||||
// @Param Authorization header string true "JWT token"
|
||||
// @Param req body request.Partner true "New Partner details"
|
||||
// @Success 200 {object} response.BaseResponse{data=response.Partner} "Partner created successfully"
|
||||
// @Failure 400 {object} response.BaseResponse{data=errors.Error} "Bad request"
|
||||
// @Failure 401 {object} response.BaseResponse{data=errors.Error} "Unauthorized"
|
||||
// @Router /api/v1/Partner [post]
|
||||
// @Tags Partner APIs
|
||||
func (h *Handler) Create(c *gin.Context) {
|
||||
ctx := request.GetMyContext(c)
|
||||
|
||||
var req request.Partner
|
||||
if err := c.ShouldBindJSON(&req); err != nil {
|
||||
response.ErrorWrapper(c, errors.ErrorBadRequest)
|
||||
return
|
||||
}
|
||||
|
||||
validate := validator.New()
|
||||
if err := validate.Struct(req); err != nil {
|
||||
response.ErrorWrapper(c, err)
|
||||
return
|
||||
}
|
||||
|
||||
res, err := h.service.Create(ctx, req.ToEntity())
|
||||
|
||||
if err != nil {
|
||||
response.ErrorWrapper(c, err)
|
||||
return
|
||||
}
|
||||
|
||||
c.JSON(http.StatusOK, response.BaseResponse{
|
||||
Success: true,
|
||||
Status: http.StatusOK,
|
||||
Data: h.toPartnerResponse(res),
|
||||
})
|
||||
}
|
||||
|
||||
// Update handles the update of an existing Partner.
|
||||
// @Summary Update an existing Partner
|
||||
// @Description Update the details of an existing Partner based on the provided ID.
|
||||
// @Accept json
|
||||
// @Produce json
|
||||
// @Param Authorization header string true "JWT token"
|
||||
// @Param id path int64 true "Partner ID to update"
|
||||
// @Param req body request.Partner true "Updated Partner details"
|
||||
// @Success 200 {object} response.BaseResponse{data=response.Partner} "Partner updated successfully"
|
||||
// @Failure 400 {object} response.BaseResponse{data=errors.Error} "Bad request"
|
||||
// @Failure 401 {object} response.BaseResponse{data=errors.Error} "Unauthorized"
|
||||
// @Router /api/v1/Partner/{id} [put]
|
||||
// @Tags Partner APIs
|
||||
func (h *Handler) Update(c *gin.Context) {
|
||||
ctx := request.GetMyContext(c)
|
||||
|
||||
id := c.Param("id")
|
||||
|
||||
PartnerID, err := strconv.ParseInt(id, 10, 64)
|
||||
if err != nil {
|
||||
response.ErrorWrapper(c, errors.ErrorBadRequest)
|
||||
return
|
||||
}
|
||||
|
||||
var req request.Partner
|
||||
if err := c.ShouldBindJSON(&req); err != nil {
|
||||
response.ErrorWrapper(c, errors.ErrorBadRequest)
|
||||
return
|
||||
}
|
||||
|
||||
validate := validator.New()
|
||||
if err := validate.Struct(req); err != nil {
|
||||
response.ErrorWrapper(c, err)
|
||||
return
|
||||
}
|
||||
|
||||
updatedPartner, err := h.service.Update(ctx, PartnerID, req.ToEntity())
|
||||
if err != nil {
|
||||
response.ErrorWrapper(c, err)
|
||||
return
|
||||
}
|
||||
|
||||
c.JSON(http.StatusOK, response.BaseResponse{
|
||||
Success: true,
|
||||
Status: http.StatusOK,
|
||||
Data: h.toPartnerResponse(updatedPartner),
|
||||
})
|
||||
}
|
||||
|
||||
// GetAll retrieves a list of Partneres.
|
||||
// @Summary Get a list of Partneres
|
||||
// @Description Get a paginated list of Partneres based on query parameters.
|
||||
// @Accept json
|
||||
// @Produce json
|
||||
// @Param Authorization header string true "JWT token"
|
||||
// @Param Limit query int false "Number of items to retrieve (default 10)"
|
||||
// @Param Offset query int false "Offset for pagination (default 0)"
|
||||
// @Success 200 {object} response.BaseResponse{data=response.PartnerList} "List of Partneres"
|
||||
// @Failure 400 {object} response.BaseResponse{data=errors.Error} "Bad request"
|
||||
// @Failure 401 {object} response.BaseResponse{data=errors.Error} "Unauthorized"
|
||||
// @Router /api/v1/Partner/list [get]
|
||||
// @Tags Partner APIs
|
||||
func (h *Handler) GetAll(c *gin.Context) {
|
||||
var req request.PartnerParam
|
||||
if err := c.ShouldBindQuery(&req); err != nil {
|
||||
response.ErrorWrapper(c, errors.ErrorBadRequest)
|
||||
return
|
||||
}
|
||||
|
||||
Partners, total, err := h.service.GetAll(c.Request.Context(), req.ToEntity())
|
||||
if err != nil {
|
||||
response.ErrorWrapper(c, err)
|
||||
return
|
||||
}
|
||||
|
||||
c.JSON(http.StatusOK, response.BaseResponse{
|
||||
Success: true,
|
||||
Status: http.StatusOK,
|
||||
Data: h.toPartnerResponseList(Partners, int64(total), req),
|
||||
})
|
||||
}
|
||||
|
||||
// Delete handles the deletion of a Partner by ID.
|
||||
// @Summary Delete a Partner by ID
|
||||
// @Description Delete a Partner based on the provided ID.
|
||||
// @Accept json
|
||||
// @Produce json
|
||||
// @Param Authorization header string true "JWT token"
|
||||
// @Param id path int64 true "Partner ID to delete"
|
||||
// @Success 200 {object} response.BaseResponse "Partner deleted successfully"
|
||||
// @Failure 400 {object} response.BaseResponse{data=errors.Error} "Bad request"
|
||||
// @Failure 401 {object} response.BaseResponse{data=errors.Error} "Unauthorized"
|
||||
// @Router /api/v1/Partner/{id} [delete]
|
||||
// @Tags Partner APIs
|
||||
func (h *Handler) Delete(c *gin.Context) {
|
||||
ctx := request.GetMyContext(c)
|
||||
id := c.Param("id")
|
||||
|
||||
// Parse the ID into a uint
|
||||
PartnerID, err := strconv.ParseInt(id, 10, 64)
|
||||
if err != nil {
|
||||
response.ErrorWrapper(c, errors.ErrorBadRequest)
|
||||
return
|
||||
}
|
||||
|
||||
err = h.service.Delete(ctx, PartnerID)
|
||||
if err != nil {
|
||||
c.JSON(http.StatusInternalServerError, response.BaseResponse{
|
||||
Success: false,
|
||||
Status: http.StatusInternalServerError,
|
||||
Message: err.Error(),
|
||||
Data: nil,
|
||||
})
|
||||
return
|
||||
}
|
||||
|
||||
c.JSON(http.StatusOK, response.BaseResponse{
|
||||
Success: true,
|
||||
Status: http.StatusOK,
|
||||
Data: nil,
|
||||
})
|
||||
}
|
||||
|
||||
// GetByID retrieves details of a specific Partner by ID.
|
||||
// @Summary Get details of a Partner by ID
|
||||
// @Description Get details of a Partner based on the provided ID.
|
||||
// @Accept json
|
||||
// @Produce json
|
||||
// @Param Authorization header string true "JWT token"
|
||||
// @Param id path int64 true "Partner ID to retrieve"
|
||||
// @Success 200 {object} response.BaseResponse{data=response.Partner} "Partner details"
|
||||
// @Failure 400 {object} response.BaseResponse{data=errors.Error} "Bad request"
|
||||
// @Failure 401 {object} response.BaseResponse{data=errors.Error} "Unauthorized"
|
||||
// @Router /api/v1/Partner/{id} [get]
|
||||
// @Tags Partner APIs
|
||||
func (h *Handler) GetByID(c *gin.Context) {
|
||||
id := c.Param("id")
|
||||
|
||||
// Parse the ID into a uint
|
||||
PartnerID, err := strconv.ParseInt(id, 10, 64)
|
||||
if err != nil {
|
||||
response.ErrorWrapper(c, errors.ErrorBadRequest)
|
||||
return
|
||||
}
|
||||
|
||||
res, err := h.service.GetByID(c.Request.Context(), PartnerID)
|
||||
if err != nil {
|
||||
c.JSON(http.StatusInternalServerError, response.BaseResponse{
|
||||
Success: false,
|
||||
Status: http.StatusInternalServerError,
|
||||
Message: err.Error(),
|
||||
Data: nil,
|
||||
})
|
||||
return
|
||||
}
|
||||
|
||||
c.JSON(http.StatusOK, response.BaseResponse{
|
||||
Success: true,
|
||||
Status: http.StatusOK,
|
||||
Data: h.toPartnerResponse(res),
|
||||
})
|
||||
}
|
||||
|
||||
func (h *Handler) toPartnerResponse(resp *entity.Partner) response.Partner {
|
||||
return response.Partner{
|
||||
ID: &resp.ID,
|
||||
Name: resp.Name,
|
||||
Status: resp.Status,
|
||||
CreatedAt: resp.CreatedAt.Format(time.RFC3339),
|
||||
UpdatedAt: resp.CreatedAt.Format(time.RFC3339),
|
||||
}
|
||||
}
|
||||
|
||||
func (h *Handler) toPartnerResponseList(resp []*entity.Partner, total int64, req request.PartnerParam) response.PartnerList {
|
||||
var Partneres []response.Partner
|
||||
for _, b := range resp {
|
||||
Partneres = append(Partneres, h.toPartnerResponse(b))
|
||||
}
|
||||
|
||||
return response.PartnerList{
|
||||
Partners: Partneres,
|
||||
Total: total,
|
||||
Limit: req.Limit,
|
||||
Offset: req.Offset,
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,269 @@
|
||||
package product
|
||||
|
||||
import (
|
||||
"furtuna-be/internal/common/errors"
|
||||
"furtuna-be/internal/entity"
|
||||
"furtuna-be/internal/handlers/request"
|
||||
"furtuna-be/internal/handlers/response"
|
||||
"furtuna-be/internal/services"
|
||||
"net/http"
|
||||
"strconv"
|
||||
"time"
|
||||
|
||||
"github.com/gin-gonic/gin"
|
||||
"github.com/go-playground/validator/v10"
|
||||
)
|
||||
|
||||
type Handler struct {
|
||||
service services.Product
|
||||
}
|
||||
|
||||
func (h *Handler) Route(group *gin.RouterGroup, jwt gin.HandlerFunc) {
|
||||
route := group.Group("/product")
|
||||
|
||||
route.POST("/", jwt, h.Create)
|
||||
route.GET("/list", jwt, h.GetAll)
|
||||
route.PUT("/:id", jwt, h.Update)
|
||||
route.GET("/:id", jwt, h.GetByID)
|
||||
route.DELETE("/:id", jwt, h.Delete)
|
||||
}
|
||||
|
||||
func NewHandler(service services.Product) *Handler {
|
||||
return &Handler{
|
||||
service: service,
|
||||
}
|
||||
}
|
||||
|
||||
// Create handles the creation of a new product.
|
||||
// @Summary Create a new product
|
||||
// @Description Create a new product with the provided details.
|
||||
// @Accept json
|
||||
// @Produce json
|
||||
// @Param Authorization header string true "JWT token"
|
||||
// @Param req body request.Product true "Product details to create"
|
||||
// @Success 200 {object} response.BaseResponse{data=response.Product} "Product created successfully"
|
||||
// @Failure 400 {object} response.BaseResponse{data=errors.Error} "Bad request"
|
||||
// @Failure 401 {object} response.BaseResponse{data=errors.Error} "Unauthorized"
|
||||
// @Tags Product APIs
|
||||
// @Router /api/v1/product/ [post]
|
||||
func (h *Handler) Create(c *gin.Context) {
|
||||
ctx := request.GetMyContext(c)
|
||||
|
||||
var req request.Product
|
||||
if err := c.ShouldBindJSON(&req); err != nil {
|
||||
response.ErrorWrapper(c, errors.ErrorBadRequest)
|
||||
return
|
||||
}
|
||||
|
||||
validate := validator.New()
|
||||
if err := validate.Struct(req); err != nil {
|
||||
response.ErrorWrapper(c, err)
|
||||
return
|
||||
}
|
||||
|
||||
res, err := h.service.Create(ctx, req.ToEntity())
|
||||
|
||||
if err != nil {
|
||||
response.ErrorWrapper(c, err)
|
||||
return
|
||||
}
|
||||
|
||||
c.JSON(http.StatusOK, response.BaseResponse{
|
||||
Success: true,
|
||||
Status: http.StatusOK,
|
||||
Data: h.toProductResponse(res),
|
||||
})
|
||||
}
|
||||
|
||||
// Update handles the update of an existing product.
|
||||
// @Summary Update an existing product
|
||||
// @Description Update the details of an existing product based on the provided ID.
|
||||
// @Accept json
|
||||
// @Produce json
|
||||
// @Param Authorization header string true "JWT token"
|
||||
// @Param id path int64 true "Product ID to update"
|
||||
// @Param req body request.Product true "Updated product details"
|
||||
// @Success 200 {object} response.BaseResponse{data=response.Product} "Product updated successfully"
|
||||
// @Failure 400 {object} response.BaseResponse{data=errors.Error} "Bad request"
|
||||
// @Failure 401 {object} response.BaseResponse{data=errors.Error} "Unauthorized"
|
||||
// @Tags Product APIs
|
||||
// @Router /api/v1/product/{id} [put]
|
||||
func (h *Handler) Update(c *gin.Context) {
|
||||
ctx := request.GetMyContext(c)
|
||||
|
||||
id := c.Param("id")
|
||||
|
||||
productID, err := strconv.ParseInt(id, 10, 64)
|
||||
if err != nil {
|
||||
response.ErrorWrapper(c, errors.ErrorBadRequest)
|
||||
return
|
||||
}
|
||||
|
||||
var req request.Product
|
||||
if err := c.ShouldBindJSON(&req); err != nil {
|
||||
response.ErrorWrapper(c, errors.ErrorBadRequest)
|
||||
return
|
||||
}
|
||||
|
||||
validate := validator.New()
|
||||
if err := validate.Struct(req); err != nil {
|
||||
response.ErrorWrapper(c, err)
|
||||
return
|
||||
}
|
||||
|
||||
updatedProduct, err := h.service.Update(ctx, productID, req.ToEntity())
|
||||
if err != nil {
|
||||
response.ErrorWrapper(c, err)
|
||||
return
|
||||
}
|
||||
|
||||
c.JSON(http.StatusOK, response.BaseResponse{
|
||||
Success: true,
|
||||
Status: http.StatusOK,
|
||||
Data: h.toProductResponse(updatedProduct),
|
||||
})
|
||||
}
|
||||
|
||||
// GetAll retrieves a list of products.
|
||||
// @Summary Get a list of products
|
||||
// @Description Get a paginated list of products based on query parameters.
|
||||
// @Accept json
|
||||
// @Produce json
|
||||
// @Param Authorization header string true "JWT token"
|
||||
// @Param Limit query int false "Number of items to retrieve (default 10)"
|
||||
// @Param Offset query int false "Offset for pagination (default 0)"
|
||||
// @Success 200 {object} response.BaseResponse{data=response.ProductList} "List of products"
|
||||
// @Failure 400 {object} response.BaseResponse{data=errors.Error} "Bad request"
|
||||
// @Failure 401 {object} response.BaseResponse{data=errors.Error} "Unauthorized"
|
||||
// @Router /api/v1/product/list [get]
|
||||
// @Tags Product APIs
|
||||
func (h *Handler) GetAll(c *gin.Context) {
|
||||
var req request.ProductParam
|
||||
if err := c.ShouldBindQuery(&req); err != nil {
|
||||
response.ErrorWrapper(c, errors.ErrorBadRequest)
|
||||
return
|
||||
}
|
||||
|
||||
products, total, err := h.service.GetAll(c.Request.Context(), req.ToEntity())
|
||||
if err != nil {
|
||||
response.ErrorWrapper(c, err)
|
||||
return
|
||||
}
|
||||
|
||||
c.JSON(http.StatusOK, response.BaseResponse{
|
||||
Success: true,
|
||||
Status: http.StatusOK,
|
||||
Data: h.toProductResponseList(products, int64(total), req),
|
||||
})
|
||||
}
|
||||
|
||||
// Delete handles the deletion of a product by ID.
|
||||
// @Summary Delete a product by ID
|
||||
// @Description Delete a product based on the provided ID.
|
||||
// @Accept json
|
||||
// @Produce json
|
||||
// @Param Authorization header string true "JWT token"
|
||||
// @Param id path int64 true "Product ID to delete"
|
||||
// @Success 200 {object} response.BaseResponse "Product deleted successfully"
|
||||
// @Failure 400 {object} response.BaseResponse{data=errors.Error} "Bad request"
|
||||
// @Failure 401 {object} response.BaseResponse{data=errors.Error} "Unauthorized"
|
||||
// @Router /api/v1/product/{id} [delete]
|
||||
// @Tags Product APIs
|
||||
func (h *Handler) Delete(c *gin.Context) {
|
||||
ctx := request.GetMyContext(c)
|
||||
id := c.Param("id")
|
||||
|
||||
// Parse the ID into a uint
|
||||
productID, err := strconv.ParseInt(id, 10, 64)
|
||||
if err != nil {
|
||||
response.ErrorWrapper(c, errors.ErrorBadRequest)
|
||||
return
|
||||
}
|
||||
|
||||
err = h.service.Delete(ctx, productID)
|
||||
if err != nil {
|
||||
c.JSON(http.StatusInternalServerError, response.BaseResponse{
|
||||
Success: false,
|
||||
Status: http.StatusInternalServerError,
|
||||
Message: err.Error(),
|
||||
Data: nil,
|
||||
})
|
||||
return
|
||||
}
|
||||
|
||||
c.JSON(http.StatusOK, response.BaseResponse{
|
||||
Success: true,
|
||||
Status: http.StatusOK,
|
||||
Data: nil,
|
||||
})
|
||||
}
|
||||
|
||||
// GetByID retrieves details of a specific product by ID.
|
||||
// @Summary Get details of a product by ID
|
||||
// @Description Get details of a product based on the provided ID.
|
||||
// @Accept json
|
||||
// @Produce json
|
||||
// @Param Authorization header string true "JWT token"
|
||||
// @Param id path int64 true "Product ID to retrieve"
|
||||
// @Success 200 {object} response.BaseResponse{data=response.Product} "Product details"
|
||||
// @Failure 400 {object} response.BaseResponse{data=errors.Error} "Bad request"
|
||||
// @Failure 401 {object} response.BaseResponse{data=errors.Error} "Unauthorized"
|
||||
// @Router /api/v1/product/{id} [get]
|
||||
// @Tags Product APIs
|
||||
func (h *Handler) GetByID(c *gin.Context) {
|
||||
id := c.Param("id")
|
||||
|
||||
// Parse the ID into a uint
|
||||
productID, err := strconv.ParseInt(id, 10, 64)
|
||||
if err != nil {
|
||||
response.ErrorWrapper(c, errors.ErrorBadRequest)
|
||||
return
|
||||
}
|
||||
|
||||
res, err := h.service.GetByID(c.Request.Context(), productID)
|
||||
if err != nil {
|
||||
c.JSON(http.StatusInternalServerError, response.BaseResponse{
|
||||
Success: false,
|
||||
Status: http.StatusInternalServerError,
|
||||
Message: err.Error(),
|
||||
Data: nil,
|
||||
})
|
||||
return
|
||||
}
|
||||
|
||||
c.JSON(http.StatusOK, response.BaseResponse{
|
||||
Success: true,
|
||||
Status: http.StatusOK,
|
||||
Data: h.toProductResponse(res),
|
||||
})
|
||||
}
|
||||
|
||||
func (h *Handler) toProductResponse(resp *entity.Product) response.Product {
|
||||
return response.Product{
|
||||
ID: resp.ID,
|
||||
Name: resp.Name,
|
||||
Type: resp.Type,
|
||||
Price: resp.Price,
|
||||
Status: resp.Status,
|
||||
Description: resp.Description,
|
||||
Image: resp.Image,
|
||||
BranchID: resp.BranchID,
|
||||
StockQty: resp.StockQty,
|
||||
CreatedAt: resp.CreatedAt.Format(time.RFC3339),
|
||||
UpdatedAt: resp.CreatedAt.Format(time.RFC3339),
|
||||
}
|
||||
}
|
||||
|
||||
func (h *Handler) toProductResponseList(resp []*entity.Product, total int64, req request.ProductParam) response.ProductList {
|
||||
var products []response.Product
|
||||
for _, b := range resp {
|
||||
products = append(products, h.toProductResponse(b))
|
||||
}
|
||||
|
||||
return response.ProductList{
|
||||
Products: products,
|
||||
Total: total,
|
||||
Limit: req.Limit,
|
||||
Offset: req.Offset,
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,232 @@
|
||||
package studio
|
||||
|
||||
import (
|
||||
"encoding/json"
|
||||
"furtuna-be/internal/common/errors"
|
||||
"furtuna-be/internal/entity"
|
||||
"furtuna-be/internal/handlers/request"
|
||||
"furtuna-be/internal/handlers/response"
|
||||
"furtuna-be/internal/services"
|
||||
"net/http"
|
||||
"strconv"
|
||||
"time"
|
||||
|
||||
"github.com/gin-gonic/gin"
|
||||
"github.com/go-playground/validator/v10"
|
||||
)
|
||||
|
||||
type StudioHandler struct {
|
||||
service services.Studio
|
||||
}
|
||||
|
||||
func (h *StudioHandler) Route(group *gin.RouterGroup, jwt gin.HandlerFunc) {
|
||||
route := group.Group("/studio")
|
||||
|
||||
route.POST("/", jwt, h.Create)
|
||||
route.PUT("/:id", jwt, h.Update)
|
||||
route.GET("/:id", jwt, h.GetByID)
|
||||
route.GET("/search", jwt, h.Search)
|
||||
}
|
||||
|
||||
func NewStudioHandler(service services.Studio) *StudioHandler {
|
||||
return &StudioHandler{
|
||||
service: service,
|
||||
}
|
||||
}
|
||||
|
||||
// Create handles the creation of a new studio.
|
||||
// @Summary Create a new studio
|
||||
// @Description Create a new studio based on the provided details.
|
||||
// @Accept json
|
||||
// @Produce json
|
||||
// @Param Authorization header string true "JWT token"
|
||||
// @Param req body request.Studio true "New studio details"
|
||||
// @Success 200 {object} response.BaseResponse{data=response.Studio} "Studio created successfully"
|
||||
// @Failure 400 {object} response.BaseResponse{data=errors.Error} "Bad request"
|
||||
// @Failure 401 {object} response.BaseResponse{data=errors.Error} "Unauthorized"
|
||||
// @Router /api/v1/studio [post]
|
||||
// @Tags Studio APIs
|
||||
func (h *StudioHandler) Create(c *gin.Context) {
|
||||
ctx := request.GetMyContext(c)
|
||||
|
||||
var req request.Studio
|
||||
if err := c.ShouldBindJSON(&req); err != nil {
|
||||
response.ErrorWrapper(c, errors.ErrorBadRequest)
|
||||
return
|
||||
}
|
||||
|
||||
validate := validator.New()
|
||||
if err := validate.Struct(req); err != nil {
|
||||
response.ErrorWrapper(c, err)
|
||||
return
|
||||
}
|
||||
|
||||
res, err := h.service.Create(ctx, req.ToEntity())
|
||||
|
||||
if err != nil {
|
||||
response.ErrorWrapper(c, err)
|
||||
return
|
||||
}
|
||||
|
||||
c.JSON(http.StatusOK, response.BaseResponse{
|
||||
Success: true,
|
||||
Status: http.StatusOK,
|
||||
Data: h.toStudioResponse(res),
|
||||
})
|
||||
}
|
||||
|
||||
// Update handles the update of an existing studio.
|
||||
// @Summary Update an existing studio
|
||||
// @Description Update the details of an existing studio based on the provided ID.
|
||||
// @Accept json
|
||||
// @Produce json
|
||||
// @Param Authorization header string true "JWT token"
|
||||
// @Param id path int64 true "Studio ID to update"
|
||||
// @Param req body request.Studio true "Updated studio details"
|
||||
// @Success 200 {object} response.BaseResponse{data=response.Studio} "Studio updated successfully"
|
||||
// @Failure 400 {object} response.BaseResponse{data=errors.Error} "Bad request"
|
||||
// @Failure 401 {object} response.BaseResponse{data=errors.Error} "Unauthorized"
|
||||
// @Router /api/v1/studio/{id} [put]
|
||||
// @Tags Studio APIs
|
||||
func (h *StudioHandler) Update(c *gin.Context) {
|
||||
ctx := request.GetMyContext(c)
|
||||
|
||||
id := c.Param("id")
|
||||
|
||||
studioID, err := strconv.ParseInt(id, 10, 64)
|
||||
if err != nil {
|
||||
response.ErrorWrapper(c, errors.ErrorBadRequest)
|
||||
return
|
||||
}
|
||||
|
||||
var req request.Studio
|
||||
if err := c.ShouldBindJSON(&req); err != nil {
|
||||
response.ErrorWrapper(c, errors.ErrorBadRequest)
|
||||
return
|
||||
}
|
||||
|
||||
validate := validator.New()
|
||||
if err := validate.Struct(req); err != nil {
|
||||
response.ErrorWrapper(c, err)
|
||||
return
|
||||
}
|
||||
|
||||
updatedStudio, err := h.service.Update(ctx, studioID, req.ToEntity())
|
||||
if err != nil {
|
||||
response.ErrorWrapper(c, err)
|
||||
return
|
||||
}
|
||||
|
||||
c.JSON(http.StatusOK, response.BaseResponse{
|
||||
Success: true,
|
||||
Status: http.StatusOK,
|
||||
Data: h.toStudioResponse(updatedStudio),
|
||||
})
|
||||
}
|
||||
|
||||
// Search retrieves a list of studios based on search criteria.
|
||||
// @Summary Search for studios
|
||||
// @Description Search for studios based on query parameters.
|
||||
// @Accept json
|
||||
// @Produce json
|
||||
// @Param Authorization header string true "JWT token"
|
||||
// @Param Name query string false "Studio name for search"
|
||||
// @Param Status query string false "Studio status for search"
|
||||
// @Param Limit query int false "Number of items to retrieve (default 10)"
|
||||
// @Param Offset query int false "Offset for pagination (default 0)"
|
||||
// @Success 200 {object} response.BaseResponse{data=response.StudioList} "List of studios"
|
||||
// @Failure 400 {object} response.BaseResponse{data=errors.Error} "Bad request"
|
||||
// @Failure 401 {object} response.BaseResponse{data=errors.Error} "Unauthorized"
|
||||
// @Router /api/v1/studio/search [get]
|
||||
// @Tags Studio APIs
|
||||
func (h *StudioHandler) Search(c *gin.Context) {
|
||||
var req request.StudioParam
|
||||
if err := c.ShouldBindQuery(&req); err != nil {
|
||||
response.ErrorWrapper(c, errors.ErrorBadRequest)
|
||||
return
|
||||
}
|
||||
|
||||
studios, total, err := h.service.Search(c.Request.Context(), req.ToEntity())
|
||||
if err != nil {
|
||||
response.ErrorWrapper(c, err)
|
||||
return
|
||||
}
|
||||
|
||||
c.JSON(http.StatusOK, response.BaseResponse{
|
||||
Success: true,
|
||||
Status: http.StatusOK,
|
||||
Data: h.toStudioResponseList(studios, int64(total), req),
|
||||
})
|
||||
}
|
||||
|
||||
// GetByID retrieves details of a specific studio by ID.
|
||||
// @Summary Get details of a studio by ID
|
||||
// @Description Get details of a studio based on the provided ID.
|
||||
// @Accept json
|
||||
// @Produce json
|
||||
// @Param Authorization header string true "JWT token"
|
||||
// @Param id path int64 true "Studio ID to retrieve"
|
||||
// @Success 200 {object} response.BaseResponse{data=response.Studio} "Studio details"
|
||||
// @Failure 400 {object} response.BaseResponse{data=errors.Error} "Bad request"
|
||||
// @Failure 401 {object} response.BaseResponse{data=errors.Error} "Unauthorized"
|
||||
// @Router /api/v1/studio/{id} [get]
|
||||
// @Tags Studio APIs
|
||||
func (h *StudioHandler) GetByID(c *gin.Context) {
|
||||
id := c.Param("id")
|
||||
|
||||
studioID, err := strconv.ParseInt(id, 10, 64)
|
||||
if err != nil {
|
||||
response.ErrorWrapper(c, errors.ErrorBadRequest)
|
||||
return
|
||||
}
|
||||
|
||||
res, err := h.service.GetByID(c.Request.Context(), studioID)
|
||||
if err != nil {
|
||||
c.JSON(http.StatusInternalServerError, response.BaseResponse{
|
||||
Success: false,
|
||||
Status: http.StatusInternalServerError,
|
||||
Message: err.Error(),
|
||||
Data: nil,
|
||||
})
|
||||
return
|
||||
}
|
||||
|
||||
c.JSON(http.StatusOK, response.BaseResponse{
|
||||
Success: true,
|
||||
Status: http.StatusOK,
|
||||
Data: h.toStudioResponse(res),
|
||||
})
|
||||
}
|
||||
|
||||
func (h *StudioHandler) toStudioResponse(resp *entity.Studio) response.Studio {
|
||||
metadata := make(map[string]interface{})
|
||||
if err := json.Unmarshal(resp.Metadata, &metadata); err != nil {
|
||||
//TODO taufanvps
|
||||
// Handle the error if the metadata cannot be unmarshaled.
|
||||
}
|
||||
|
||||
return response.Studio{
|
||||
ID: &resp.ID,
|
||||
BranchId: &resp.BranchId,
|
||||
Name: resp.Name,
|
||||
Status: string(resp.Status),
|
||||
Price: resp.Price,
|
||||
Metadata: metadata,
|
||||
CreatedAt: resp.CreatedAt.Format(time.RFC3339),
|
||||
UpdatedAt: resp.CreatedAt.Format(time.RFC3339),
|
||||
}
|
||||
}
|
||||
|
||||
func (h *StudioHandler) toStudioResponseList(resp []*entity.Studio, total int64, req request.StudioParam) response.StudioList {
|
||||
var studios []response.Studio
|
||||
for _, b := range resp {
|
||||
studios = append(studios, h.toStudioResponse(b))
|
||||
}
|
||||
|
||||
return response.StudioList{
|
||||
Studios: studios,
|
||||
Total: total,
|
||||
Limit: req.Limit,
|
||||
Offset: req.Offset,
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,288 @@
|
||||
package user
|
||||
|
||||
import (
|
||||
"net/http"
|
||||
"strconv"
|
||||
"time"
|
||||
|
||||
"github.com/gin-gonic/gin"
|
||||
"github.com/go-playground/validator/v10"
|
||||
|
||||
"furtuna-be/internal/common/errors"
|
||||
"furtuna-be/internal/entity"
|
||||
"furtuna-be/internal/handlers/request"
|
||||
"furtuna-be/internal/handlers/response"
|
||||
"furtuna-be/internal/services"
|
||||
)
|
||||
|
||||
type Handler struct {
|
||||
service services.User
|
||||
}
|
||||
|
||||
func (h *Handler) Route(group *gin.RouterGroup, jwt gin.HandlerFunc) {
|
||||
route := group.Group("/user")
|
||||
|
||||
route.POST("/", jwt, h.Create)
|
||||
route.GET("/list", jwt, h.GetAll)
|
||||
route.GET("/:id", jwt, h.GetByID)
|
||||
route.PUT("/:id", jwt, h.Update)
|
||||
route.DELETE("/:id", jwt, h.Delete)
|
||||
}
|
||||
|
||||
func NewHandler(service services.User) *Handler {
|
||||
return &Handler{
|
||||
service: service,
|
||||
}
|
||||
}
|
||||
|
||||
// Create handles the creation of a new user.
|
||||
// @Summary Create a new user
|
||||
// @Description Create a new user based on the provided data.
|
||||
// @Accept json
|
||||
// @Produce json
|
||||
// @Param Authorization header string true "JWT token"
|
||||
// @Param req body request.User true "New user details"
|
||||
// @Success 200 {object} response.BaseResponse{data=response.User} "User created successfully"
|
||||
// @Failure 400 {object} response.BaseResponse{data=errors.Error} "Bad request"
|
||||
// @Failure 401 {object} response.BaseResponse{data=errors.Error} "Unauthorized"
|
||||
// @Router /api/v1/user [post]
|
||||
// @Tags User APIs
|
||||
func (h *Handler) Create(c *gin.Context) {
|
||||
ctx := request.GetMyContext(c)
|
||||
|
||||
var req request.User
|
||||
if err := c.ShouldBindJSON(&req); err != nil {
|
||||
response.ErrorWrapper(c, errors.ErrorBadRequest)
|
||||
return
|
||||
}
|
||||
|
||||
if err := req.Validate(); err != nil {
|
||||
response.ErrorWrapper(c, errors.ErrorInvalidRequest)
|
||||
return
|
||||
}
|
||||
|
||||
res, err := h.service.Create(ctx, req.ToEntity())
|
||||
|
||||
if err != nil {
|
||||
response.ErrorWrapper(c, err)
|
||||
return
|
||||
}
|
||||
|
||||
resp := response.User{
|
||||
ID: res.ID,
|
||||
Name: res.Name,
|
||||
Email: res.Email,
|
||||
RoleID: int64(res.RoleID),
|
||||
PartnerID: res.PartnerID,
|
||||
Status: string(res.Status),
|
||||
}
|
||||
|
||||
c.JSON(http.StatusOK, response.BaseResponse{
|
||||
Success: true,
|
||||
Status: http.StatusOK,
|
||||
Data: resp,
|
||||
})
|
||||
}
|
||||
|
||||
// Update handles the update of an existing user.
|
||||
// @Summary Update an existing user
|
||||
// @Description Update the details of an existing user based on the provided ID.
|
||||
// @Accept json
|
||||
// @Produce json
|
||||
// @Param Authorization header string true "JWT token"
|
||||
// @Param id path int64 true "User ID to update"
|
||||
// @Param req body request.User true "Updated user details"
|
||||
// @Success 200 {object} response.BaseResponse{data=response.User} "User updated successfully"
|
||||
// @Failure 400 {object} response.BaseResponse{data=errors.Error} "Bad request"
|
||||
// @Failure 401 {object} response.BaseResponse{data=errors.Error} "Unauthorized"
|
||||
// @Router /api/v1/user/{id} [put]
|
||||
// @Tags User APIs
|
||||
func (h *Handler) Update(c *gin.Context) {
|
||||
ctx := request.GetMyContext(c)
|
||||
|
||||
if !ctx.IsSuperAdmin() {
|
||||
response.ErrorWrapper(c, errors.ErrorUnauthorized)
|
||||
return
|
||||
}
|
||||
|
||||
id := c.Param("id")
|
||||
|
||||
userID, err := strconv.ParseInt(id, 10, 64)
|
||||
if err != nil {
|
||||
response.ErrorWrapper(c, errors.ErrorBadRequest)
|
||||
return
|
||||
}
|
||||
|
||||
var req request.User
|
||||
if err := c.ShouldBindJSON(&req); err != nil {
|
||||
response.ErrorWrapper(c, errors.ErrorBadRequest)
|
||||
return
|
||||
}
|
||||
|
||||
validate := validator.New()
|
||||
if err := validate.Struct(req); err != nil {
|
||||
response.ErrorWrapper(c, err)
|
||||
return
|
||||
}
|
||||
|
||||
updatedUser, err := h.service.Update(ctx, userID, req.ToEntity())
|
||||
if err != nil {
|
||||
response.ErrorWrapper(c, err)
|
||||
return
|
||||
}
|
||||
|
||||
c.JSON(http.StatusOK, response.BaseResponse{
|
||||
Success: true,
|
||||
Status: http.StatusOK,
|
||||
Data: h.toUserResponse(updatedUser),
|
||||
})
|
||||
}
|
||||
|
||||
// GetAll retrieves a list of users.
|
||||
// @Summary Get a list of users
|
||||
// @Description Get a paginated list of users based on query parameters.
|
||||
// @Accept json
|
||||
// @Produce json
|
||||
// @Param Authorization header string true "JWT token"
|
||||
// @Param Limit query int false "Number of items to retrieve (default 10)"
|
||||
// @Param Offset query int false "Offset for pagination (default 0)"
|
||||
// @Success 200 {object} response.BaseResponse{data=response.UserList} "List of users"
|
||||
// @Failure 400 {object} response.BaseResponse{data=errors.Error} "Bad request"
|
||||
// @Failure 401 {object} response.BaseResponse{data=errors.Error} "Unauthorized"
|
||||
// @Router /api/v1/user/list [get]
|
||||
// @Tags User APIs
|
||||
func (h *Handler) GetAll(c *gin.Context) {
|
||||
ctx := request.GetMyContext(c)
|
||||
var req request.UserParam
|
||||
if err := c.ShouldBindQuery(&req); err != nil {
|
||||
|
||||
}
|
||||
|
||||
if !ctx.IsSuperAdmin() {
|
||||
response.ErrorWrapper(c, errors.ErrorUnauthorized)
|
||||
return
|
||||
}
|
||||
|
||||
users, total, err := h.service.GetAll(ctx, req.ToEntity())
|
||||
if err != nil {
|
||||
response.ErrorWrapper(c, err)
|
||||
return
|
||||
}
|
||||
|
||||
c.JSON(http.StatusOK, response.BaseResponse{
|
||||
Success: true,
|
||||
Status: http.StatusOK,
|
||||
Data: h.toUserResponseList(users, int64(total), req),
|
||||
})
|
||||
}
|
||||
|
||||
// GetByID retrieves details of a specific user by ID.
|
||||
// @Summary Get details of a user by ID
|
||||
// @Description Get details of a user based on the provided ID.
|
||||
// @Accept json
|
||||
// @Produce json
|
||||
// @Param Authorization header string true "JWT token"
|
||||
// @Param id path int64 true "User ID to retrieve"
|
||||
// @Success 200 {object} response.BaseResponse{data=response.User} "User details"
|
||||
// @Failure 400 {object} response.BaseResponse{data=errors.Error} "Bad request"
|
||||
// @Failure 401 {object} response.BaseResponse{data=errors.Error} "Unauthorized"
|
||||
// @Router /api/v1/user/{id} [get]
|
||||
// @Tags User APIs
|
||||
func (h *Handler) GetByID(c *gin.Context) {
|
||||
ctx := request.GetMyContext(c)
|
||||
id := c.Param("id")
|
||||
|
||||
// Parse the ID into a uint
|
||||
userID, err := strconv.ParseInt(id, 10, 64)
|
||||
if err != nil {
|
||||
response.ErrorWrapper(c, errors.ErrorBadRequest)
|
||||
return
|
||||
}
|
||||
|
||||
res, err := h.service.GetByID(ctx, userID)
|
||||
if err != nil {
|
||||
c.JSON(http.StatusInternalServerError, response.BaseResponse{
|
||||
Success: false,
|
||||
Status: http.StatusInternalServerError,
|
||||
Message: err.Error(),
|
||||
Data: nil,
|
||||
})
|
||||
return
|
||||
}
|
||||
|
||||
c.JSON(http.StatusOK, response.BaseResponse{
|
||||
Success: true,
|
||||
Status: http.StatusOK,
|
||||
Data: h.toUserResponse(res),
|
||||
})
|
||||
}
|
||||
|
||||
// Delete handles the deletion of a user by ID.
|
||||
// @Summary Delete a user by ID
|
||||
// @Description Delete a user based on the provided ID.
|
||||
// @Accept json
|
||||
// @Produce json
|
||||
// @Param Authorization header string true "JWT token"
|
||||
// @Param id path int64 true "User ID to delete"
|
||||
// @Success 200 {object} response.BaseResponse "User deleted successfully"
|
||||
// @Failure 400 {object} response.BaseResponse{data=errors.Error} "Bad request"
|
||||
// @Failure 401 {object} response.BaseResponse{data=errors.Error} "Unauthorized"
|
||||
// @Router /api/v1/user/{id} [delete]
|
||||
// @Tags User APIs
|
||||
func (h *Handler) Delete(c *gin.Context) {
|
||||
ctx := request.GetMyContext(c)
|
||||
id := c.Param("id")
|
||||
|
||||
// Parse the ID into a uint
|
||||
userID, err := strconv.ParseInt(id, 10, 64)
|
||||
if err != nil {
|
||||
response.ErrorWrapper(c, errors.ErrorBadRequest)
|
||||
return
|
||||
}
|
||||
|
||||
err = h.service.Delete(ctx, userID)
|
||||
if err != nil {
|
||||
c.JSON(http.StatusInternalServerError, response.BaseResponse{
|
||||
Success: false,
|
||||
Status: http.StatusInternalServerError,
|
||||
Message: err.Error(),
|
||||
Data: nil,
|
||||
})
|
||||
return
|
||||
}
|
||||
|
||||
c.JSON(http.StatusOK, response.BaseResponse{
|
||||
Success: true,
|
||||
Status: http.StatusOK,
|
||||
Data: nil,
|
||||
})
|
||||
}
|
||||
|
||||
func (h *Handler) toUserResponse(resp *entity.User) response.User {
|
||||
return response.User{
|
||||
ID: resp.ID,
|
||||
Name: resp.Name,
|
||||
Email: resp.Email,
|
||||
Status: string(resp.Status),
|
||||
RoleID: int64(resp.RoleID),
|
||||
RoleName: resp.RoleName,
|
||||
PartnerID: resp.PartnerID,
|
||||
BranchName: resp.BranchName,
|
||||
CreatedAt: resp.CreatedAt.Format(time.RFC3339),
|
||||
UpdatedAt: resp.CreatedAt.Format(time.RFC3339),
|
||||
}
|
||||
}
|
||||
|
||||
func (h *Handler) toUserResponseList(resp []*entity.User, total int64, req request.UserParam) response.UserList {
|
||||
var users []response.User
|
||||
for _, b := range resp {
|
||||
users = append(users, h.toUserResponse(b))
|
||||
}
|
||||
|
||||
return response.UserList{
|
||||
Users: users,
|
||||
Total: total,
|
||||
Limit: req.Limit,
|
||||
Offset: req.Offset,
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,15 @@
|
||||
package request
|
||||
|
||||
type LoginRequest struct {
|
||||
Email string `json:"email"`
|
||||
Password string `json:"password"`
|
||||
}
|
||||
|
||||
type ResetPasswordRequest struct {
|
||||
Email string `json:"email" validate:"required,email"`
|
||||
}
|
||||
|
||||
type ResetPasswordChangeRequest struct {
|
||||
Token string `json:"token" validate:"required"`
|
||||
Password string `json:"password" validate:"required"`
|
||||
}
|
||||
@@ -0,0 +1,36 @@
|
||||
package request
|
||||
|
||||
import (
|
||||
"furtuna-be/internal/constants/branch"
|
||||
"furtuna-be/internal/entity"
|
||||
)
|
||||
|
||||
type BranchParam struct {
|
||||
Search string `form:"search" json:"search" example:"Ketua Umum"`
|
||||
Name string `form:"name" json:"name" example:"Ketua Umum"`
|
||||
Limit int `form:"limit" json:"limit" example:"10"`
|
||||
Offset int `form:"offset" json:"offset" example:"0"`
|
||||
}
|
||||
|
||||
func (p *BranchParam) ToEntity() entity.BranchSearch {
|
||||
return entity.BranchSearch{
|
||||
Search: p.Search,
|
||||
Name: p.Name,
|
||||
Limit: p.Limit,
|
||||
Offset: p.Offset,
|
||||
}
|
||||
}
|
||||
|
||||
type Branch struct {
|
||||
Name string `json:"name" validate:"required"`
|
||||
Location string `json:"location" validate:"required"`
|
||||
Status branch.BranchStatus `json:"status"`
|
||||
}
|
||||
|
||||
func (e *Branch) ToEntity() *entity.Branch {
|
||||
return &entity.Branch{
|
||||
Name: e.Name,
|
||||
Location: e.Location,
|
||||
Status: e.Status,
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,21 @@
|
||||
package request
|
||||
|
||||
import (
|
||||
"furtuna-be/internal/common/mycontext"
|
||||
"github.com/gin-gonic/gin"
|
||||
)
|
||||
|
||||
func GetMyContext(c *gin.Context) mycontext.Context {
|
||||
rawCtx, exists := c.Get("myCtx")
|
||||
if !exists {
|
||||
// handle missing context
|
||||
return mycontext.NewContext(c)
|
||||
}
|
||||
|
||||
myCtx, ok := rawCtx.(mycontext.Context)
|
||||
if !ok {
|
||||
return mycontext.NewContext(c)
|
||||
}
|
||||
|
||||
return myCtx
|
||||
}
|
||||
@@ -0,0 +1,86 @@
|
||||
package request
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"time"
|
||||
|
||||
"github.com/go-playground/validator/v10"
|
||||
|
||||
"furtuna-be/internal/entity"
|
||||
)
|
||||
|
||||
type EventParam struct {
|
||||
Name string `form:"name" json:"name" example:"Ketua Umum"`
|
||||
Limit int `form:"limit" json:"limit" example:"10"`
|
||||
Offset int `form:"offset" json:"offset" example:"0"`
|
||||
}
|
||||
|
||||
func (p *EventParam) ToEntity() entity.EventSearch {
|
||||
return entity.EventSearch{
|
||||
Name: p.Name,
|
||||
Limit: p.Limit,
|
||||
Offset: p.Offset,
|
||||
}
|
||||
}
|
||||
|
||||
type Event struct {
|
||||
Name string `json:"name" validate:"required"`
|
||||
Description string `json:"description"`
|
||||
StartDate string `json:"start_date" validate:"required"`
|
||||
StartTime string `json:"start_time"`
|
||||
EndDate string `json:"end_date" validate:"required"`
|
||||
EndTime string `json:"end_time"`
|
||||
Location string `json:"location" validate:"required"`
|
||||
Level string `json:"level" validate:"required"`
|
||||
Included []string `json:"included"`
|
||||
Price float64 `json:"price"`
|
||||
Paid bool `json:"paid"`
|
||||
Status entity.Status `json:"status"`
|
||||
LocationID int64 `json:"location_id"`
|
||||
startDateTime time.Time
|
||||
endDateTime time.Time
|
||||
}
|
||||
|
||||
func (e *Event) ToEntity() *entity.Event {
|
||||
return &entity.Event{
|
||||
Name: e.Name,
|
||||
Description: e.Description,
|
||||
StartDate: e.startDateTime,
|
||||
EndDate: e.endDateTime,
|
||||
Location: e.Location,
|
||||
Level: e.Level,
|
||||
Included: e.Included,
|
||||
Price: e.Price,
|
||||
Paid: e.Paid,
|
||||
LocationID: &e.LocationID,
|
||||
Status: e.Status,
|
||||
}
|
||||
}
|
||||
|
||||
func (e *Event) Validate() error {
|
||||
validate := validator.New()
|
||||
if err := validate.Struct(e); err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
startDateTimeStr := e.StartDate + "T" + e.StartTime + "Z"
|
||||
endDateTimeStr := e.EndDate + "T" + e.EndTime + "Z"
|
||||
|
||||
startDateTime, err := time.Parse(time.RFC3339, startDateTimeStr)
|
||||
if err != nil {
|
||||
fmt.Println("Error parsing start date-time:", err)
|
||||
return err
|
||||
}
|
||||
|
||||
e.startDateTime = startDateTime
|
||||
|
||||
endDateTime, err := time.Parse(time.RFC3339, endDateTimeStr)
|
||||
if err != nil {
|
||||
fmt.Println("Error parsing end date-time:", err)
|
||||
return err
|
||||
}
|
||||
|
||||
e.endDateTime = endDateTime
|
||||
|
||||
return nil
|
||||
}
|
||||
@@ -0,0 +1,116 @@
|
||||
package request
|
||||
|
||||
import (
|
||||
"furtuna-be/internal/constants/order"
|
||||
"furtuna-be/internal/constants/transaction"
|
||||
"furtuna-be/internal/entity"
|
||||
"time"
|
||||
)
|
||||
|
||||
type Order struct {
|
||||
BranchID int64 `json:"branch_id" validate:"required"`
|
||||
Amount float64 `json:"amount" validate:"required"`
|
||||
CustomerName string `json:"customer_name" validate:"required"`
|
||||
CustomerPhone string `json:"customer_phone" validate:"required"`
|
||||
Pax int `json:"pax" validate:"required"`
|
||||
PaymentMethod transaction.PaymentMethod `json:"payment_method" validate:"required"`
|
||||
OrderItem []OrderItem `json:"order_items" validate:"required"`
|
||||
}
|
||||
|
||||
type OrderItem struct {
|
||||
ItemID int64 `json:"item_id" validate:"required"`
|
||||
ItemType order.ItemType `json:"item_type" validate:"required"`
|
||||
Price float64 `json:"price" validate:"required"`
|
||||
Qty int64 `json:"qty" validate:"required"`
|
||||
}
|
||||
|
||||
type OrderParam struct {
|
||||
Search string `form:"search" json:"search" example:"name,branch_name,item_name"`
|
||||
StatusActive order.OrderSearchStatus `form:"status_active" json:"status_active" example:"active,inactive"`
|
||||
Status order.OrderStatus `form:"status" json:"status" example:"NEW,PAID,CANCEL"`
|
||||
BranchID int64 `form:"branch_id" json:"branch_id" example:"1"`
|
||||
Limit int `form:"limit" json:"limit" example:"10"`
|
||||
Offset int `form:"offset" json:"offset" example:"0"`
|
||||
}
|
||||
|
||||
func (p *OrderParam) ToEntity() entity.OrderSearch {
|
||||
return entity.OrderSearch{
|
||||
Search: p.Search,
|
||||
StatusActive: p.StatusActive,
|
||||
Status: p.Status,
|
||||
BranchID: p.BranchID,
|
||||
Limit: p.Limit,
|
||||
Offset: p.Offset,
|
||||
}
|
||||
}
|
||||
|
||||
func (o *Order) ToEntity() *entity.Order {
|
||||
var ordItems []entity.OrderItem
|
||||
if len(o.OrderItem) > 0 {
|
||||
for _, i := range o.OrderItem {
|
||||
ordItems = append(ordItems, entity.OrderItem{
|
||||
ItemID: i.ItemID,
|
||||
ItemType: i.ItemType,
|
||||
Price: i.Price,
|
||||
Qty: i.Qty,
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
transaction := entity.Transaction{
|
||||
BranchID: o.BranchID,
|
||||
CustomerName: o.CustomerName,
|
||||
CustomerPhone: o.CustomerPhone,
|
||||
PaymentMethod: o.PaymentMethod,
|
||||
}
|
||||
|
||||
return &entity.Order{
|
||||
BranchID: o.BranchID,
|
||||
Amount: o.Amount,
|
||||
CustomerName: o.CustomerName,
|
||||
CustomerPhone: o.CustomerPhone,
|
||||
Pax: o.Pax,
|
||||
Transaction: transaction,
|
||||
OrderItem: ordItems,
|
||||
}
|
||||
}
|
||||
|
||||
type OrderTotalRevenueParam struct {
|
||||
Year int `form:"year" json:"year" example:"1,2,3"`
|
||||
Month int `form:"month" json:"month" example:"1,2,3"`
|
||||
BranchID int64 `form:"branch_id" json:"branch_id" example:"1"`
|
||||
DateStart *time.Time `form:"date_start" json:"date_start" example:"2024-01-01" time_format:"2006-1-2"`
|
||||
DateEnd *time.Time `form:"date_end" json:"date_end" example:"2024-01-01" time_format:"2006-1-2"`
|
||||
}
|
||||
|
||||
func (p *OrderTotalRevenueParam) ToEntity() entity.OrderTotalRevenueSearch {
|
||||
return entity.OrderTotalRevenueSearch{
|
||||
Year: p.Year,
|
||||
Month: p.Month,
|
||||
BranchID: p.BranchID,
|
||||
DateStart: p.DateStart,
|
||||
DateEnd: p.DateEnd,
|
||||
}
|
||||
}
|
||||
|
||||
type OrderBranchRevenueParam struct {
|
||||
DateStart *time.Time `form:"date_start" json:"date_start" example:"2024-01-01" time_format:"2006-1-2"`
|
||||
DateEnd *time.Time `form:"date_end" json:"date_end" example:"2024-01-01" time_format:"2006-1-2"`
|
||||
}
|
||||
|
||||
func (p *OrderBranchRevenueParam) ToEntity() entity.OrderBranchRevenueSearch {
|
||||
return entity.OrderBranchRevenueSearch{
|
||||
DateStart: p.DateStart,
|
||||
DateEnd: p.DateEnd,
|
||||
}
|
||||
}
|
||||
|
||||
type UpdateStatus struct {
|
||||
Status order.OrderStatus `form:"status" json:"status" example:"NEW,PAID,CANCEL"`
|
||||
}
|
||||
|
||||
func (o *UpdateStatus) ToEntity() *entity.Order {
|
||||
return &entity.Order{
|
||||
Status: o.Status,
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,35 @@
|
||||
package request
|
||||
|
||||
import (
|
||||
"furtuna-be/internal/entity"
|
||||
)
|
||||
|
||||
type PartnerParam struct {
|
||||
Search string `form:"search" json:"search" example:"Ketua Umum"`
|
||||
Name string `form:"name" json:"name" example:"Ketua Umum"`
|
||||
Limit int `form:"limit" json:"limit" example:"10"`
|
||||
Offset int `form:"offset" json:"offset" example:"0"`
|
||||
}
|
||||
|
||||
func (p *PartnerParam) ToEntity() entity.PartnerSearch {
|
||||
return entity.PartnerSearch{
|
||||
Search: p.Search,
|
||||
Name: p.Name,
|
||||
Limit: p.Limit,
|
||||
Offset: p.Offset,
|
||||
}
|
||||
}
|
||||
|
||||
type Partner struct {
|
||||
Name string `json:"name" validate:"required"`
|
||||
Address string `json:"address" validate:"required"`
|
||||
Status string `json:"status"`
|
||||
}
|
||||
|
||||
func (e *Partner) ToEntity() *entity.Partner {
|
||||
return &entity.Partner{
|
||||
Name: e.Name,
|
||||
Address: e.Address,
|
||||
Status: e.Status,
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,52 @@
|
||||
package request
|
||||
|
||||
import (
|
||||
"furtuna-be/internal/constants/product"
|
||||
"furtuna-be/internal/entity"
|
||||
)
|
||||
|
||||
type ProductParam struct {
|
||||
Search string `form:"search" json:"search" example:"Nasi Goreng"`
|
||||
Name string `form:"name" json:"name" example:"Nasi Goreng"`
|
||||
Type product.ProductType `form:"type" json:"type" example:"FOOD/BEVERAGE"`
|
||||
BranchID int64 `form:"branch_id" json:"branch_id" example:"1"`
|
||||
Available product.ProductStock `form:"available" json:"available" example:"1" example:"AVAILABLE/UNAVAILABLE"`
|
||||
Limit int `form:"limit" json:"limit" example:"10"`
|
||||
Offset int `form:"offset" json:"offset" example:"0"`
|
||||
}
|
||||
|
||||
func (p *ProductParam) ToEntity() entity.ProductSearch {
|
||||
return entity.ProductSearch{
|
||||
Search: p.Search,
|
||||
Name: p.Name,
|
||||
Type: p.Type,
|
||||
BranchID: p.BranchID,
|
||||
Available: p.Available,
|
||||
Limit: p.Limit,
|
||||
Offset: p.Offset,
|
||||
}
|
||||
}
|
||||
|
||||
type Product struct {
|
||||
Name string `json:"name" validate:"required"`
|
||||
Type product.ProductType `json:"type" validate:"required"`
|
||||
Price float64 `json:"price" validate:"required"`
|
||||
Status product.ProductStatus `json:"status" validate:"required"`
|
||||
Description string `json:"description" `
|
||||
Image string `json:"image" `
|
||||
BranchID int64 `json:"branch_id" validate:"required"`
|
||||
StockQty int64 `json:"stock_qty" `
|
||||
}
|
||||
|
||||
func (e *Product) ToEntity() *entity.Product {
|
||||
return &entity.Product{
|
||||
Name: e.Name,
|
||||
Type: e.Type,
|
||||
Price: e.Price,
|
||||
Status: e.Status,
|
||||
Description: e.Description,
|
||||
Image: e.Image,
|
||||
BranchID: e.BranchID,
|
||||
StockQty: e.StockQty,
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,53 @@
|
||||
package request
|
||||
|
||||
import (
|
||||
"encoding/json"
|
||||
"furtuna-be/internal/constants/studio"
|
||||
"furtuna-be/internal/entity"
|
||||
)
|
||||
|
||||
type StudioParam struct {
|
||||
Id string `form:"id" json:"id" example:"1"`
|
||||
Name string `form:"name" json:"name" example:"Studio A"`
|
||||
Status studio.StudioStatus `form:"status" json:"status" example:"Active"`
|
||||
BranchId int64 `form:"branch_id" json:"branch_id" example:"1"`
|
||||
Limit int `form:"limit" json:"limit" example:"10"`
|
||||
Offset int `form:"offset" json:"offset" example:"0"`
|
||||
}
|
||||
|
||||
func (p *StudioParam) ToEntity() entity.StudioSearch {
|
||||
return entity.StudioSearch{
|
||||
Name: p.Name,
|
||||
Status: p.Status,
|
||||
BranchId: p.BranchId,
|
||||
Limit: p.Limit,
|
||||
Offset: p.Offset,
|
||||
}
|
||||
}
|
||||
|
||||
type Studio struct {
|
||||
Name string `json:"name" validate:"required"`
|
||||
BranchId int64 `json:"branch_id" validate:"required"`
|
||||
Status studio.StudioStatus `json:"status"`
|
||||
Price float64 `json:"price" validate:"required"`
|
||||
Metadata map[string]interface{} `json:"metadata"`
|
||||
}
|
||||
|
||||
func (e *Studio) ToEntity() *entity.Studio {
|
||||
studioEntity := &entity.Studio{
|
||||
BranchId: e.BranchId,
|
||||
Name: e.Name,
|
||||
Status: e.Status,
|
||||
Price: e.Price,
|
||||
}
|
||||
|
||||
if e.Metadata != nil {
|
||||
jsonData, err := json.Marshal(e.Metadata)
|
||||
if err != nil {
|
||||
//TODO @taufanvps
|
||||
}
|
||||
studioEntity.Metadata = jsonData
|
||||
}
|
||||
|
||||
return studioEntity
|
||||
}
|
||||
@@ -0,0 +1,9 @@
|
||||
package request
|
||||
|
||||
import (
|
||||
"furtuna-be/internal/constants/transaction"
|
||||
)
|
||||
|
||||
type Transaction struct {
|
||||
PaymentMethod transaction.PaymentMethod
|
||||
}
|
||||
@@ -0,0 +1,58 @@
|
||||
package request
|
||||
|
||||
import (
|
||||
"furtuna-be/internal/constants/role"
|
||||
"furtuna-be/internal/entity"
|
||||
|
||||
"github.com/go-playground/validator/v10"
|
||||
)
|
||||
|
||||
type User struct {
|
||||
Name string `json:"name" validate:"required"`
|
||||
Email string `json:"email" validate:"required"`
|
||||
Password string `json:"password" validate:"required"`
|
||||
PartnerID *int64 `json:"partner_id"`
|
||||
RoleID int64 `json:"role_id" validate:"required"`
|
||||
NIK string `json:"nik"`
|
||||
UserType string `json:"user_type"`
|
||||
PhoneNumber string `json:"phone_number"`
|
||||
}
|
||||
|
||||
func (e *User) Validate() error {
|
||||
validate := validator.New()
|
||||
if err := validate.Struct(e); err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
return nil
|
||||
}
|
||||
|
||||
func (u *User) ToEntity() *entity.User {
|
||||
return &entity.User{
|
||||
Name: u.Name,
|
||||
Email: u.Email,
|
||||
Password: u.Password,
|
||||
RoleID: role.Role(u.RoleID),
|
||||
PartnerID: u.PartnerID,
|
||||
}
|
||||
}
|
||||
|
||||
type UserParam struct {
|
||||
Search string `form:"search" json:"search" example:"admin,branch1"`
|
||||
Name string `form:"name" json:"name" example:"Admin 1"`
|
||||
RoleID int64 `form:"role_id" json:"role_id" example:"1"`
|
||||
PartnerID int64 `form:"partner_id" json:"partner_id" example:"1"`
|
||||
Limit int `form:"limit,default=10" json:"limit" example:"10"`
|
||||
Offset int `form:"offset,default=0" json:"offset" example:"0"`
|
||||
}
|
||||
|
||||
func (p *UserParam) ToEntity() entity.UserSearch {
|
||||
return entity.UserSearch{
|
||||
Search: p.Search,
|
||||
Name: p.Name,
|
||||
RoleID: p.RoleID,
|
||||
PartnerID: p.PartnerID,
|
||||
Limit: p.Limit,
|
||||
Offset: p.Offset,
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,13 @@
|
||||
package response
|
||||
|
||||
type LoginResponse struct {
|
||||
Token string `json:"token"`
|
||||
Name string `json:"name"`
|
||||
Role Role `json:"role"`
|
||||
Branch *Branch `json:"branch"`
|
||||
}
|
||||
|
||||
type Role struct {
|
||||
ID int64 `json:"id"`
|
||||
Role string `json:"role_name"`
|
||||
}
|
||||
@@ -0,0 +1,12 @@
|
||||
package response
|
||||
|
||||
type BaseResponse struct {
|
||||
Success bool `json:"success"`
|
||||
Code string `json:"response_code,omitempty"`
|
||||
Status int `json:"-"`
|
||||
Message string `json:"message,omitempty"`
|
||||
ErrorMessage string `json:"error_message,omitempty"`
|
||||
ErrorDetail interface{} `json:"error_detail,omitempty"`
|
||||
Data interface{} `json:"data,omitempty"`
|
||||
PagingMeta *PagingMeta `json:"meta,omitempty"`
|
||||
}
|
||||
@@ -0,0 +1,17 @@
|
||||
package response
|
||||
|
||||
type Branch struct {
|
||||
ID *int64 `json:"id"`
|
||||
Name string `json:"name"`
|
||||
Status string `json:"status"`
|
||||
Location string `json:"location"`
|
||||
CreatedAt string `json:"created_at"`
|
||||
UpdatedAt string `json:"updated_at"`
|
||||
}
|
||||
|
||||
type BranchList struct {
|
||||
Branches []Branch `json:"branches"`
|
||||
Total int64 `json:"total"`
|
||||
Limit int `json:"limit"`
|
||||
Offset int `json:"offset"`
|
||||
}
|
||||
@@ -0,0 +1,27 @@
|
||||
package response
|
||||
|
||||
type Event struct {
|
||||
ID int64 `json:"id"`
|
||||
Name string `json:"name"`
|
||||
Status string `json:"status"`
|
||||
Description string `json:"description"`
|
||||
StartDate string `json:"start_date"`
|
||||
EndDate string `json:"end_date"`
|
||||
StartTime string `json:"start_time"`
|
||||
EndTime string `json:"end_time"`
|
||||
Location string `json:"location"`
|
||||
Level string `json:"level"`
|
||||
Included []string `json:"included"`
|
||||
Price float64 `json:"price"`
|
||||
Paid bool `json:"paid"`
|
||||
LocationID *int64 `json:"location_id"`
|
||||
CreatedAt string `json:"created_at"`
|
||||
UpdatedAt string `json:"updated_at"`
|
||||
}
|
||||
|
||||
type EventList struct {
|
||||
Events []Event `json:"events"`
|
||||
Total int64 `json:"total"`
|
||||
Limit int `json:"limit"`
|
||||
Offset int `json:"offset"`
|
||||
}
|
||||
@@ -0,0 +1,38 @@
|
||||
package response
|
||||
|
||||
import (
|
||||
"github.com/gin-gonic/gin"
|
||||
|
||||
"furtuna-be/internal/common/errors"
|
||||
)
|
||||
|
||||
type response struct {
|
||||
Status int `json:"status"`
|
||||
Meta interface{} `json:"meta,omitempty"`
|
||||
Message string `json:"message"`
|
||||
Data interface{} `json:"data"`
|
||||
Success bool `json:"success,omitempty"`
|
||||
}
|
||||
|
||||
func ErrorWrapper(c *gin.Context, err error) {
|
||||
var customError errors.Error
|
||||
customError = errors.ErrorInternalServer
|
||||
|
||||
status := customError.MapErrorsToHTTPCode()
|
||||
code := customError.MapErrorsToCode()
|
||||
message := err.Error()
|
||||
|
||||
if validErr, ok := err.(errors.Error); ok {
|
||||
status = validErr.MapErrorsToHTTPCode()
|
||||
code = validErr.MapErrorsToCode()
|
||||
message = code.GetMessage()
|
||||
}
|
||||
|
||||
resp := BaseResponse{
|
||||
ErrorMessage: err.Error(),
|
||||
Code: code.GetCode(),
|
||||
Message: message,
|
||||
}
|
||||
|
||||
c.JSON(status, resp)
|
||||
}
|
||||
@@ -0,0 +1,52 @@
|
||||
package response
|
||||
|
||||
import (
|
||||
"furtuna-be/internal/constants/order"
|
||||
"furtuna-be/internal/constants/transaction"
|
||||
)
|
||||
|
||||
type Order struct {
|
||||
ID int64 `json:"id" `
|
||||
BranchID int64 `json:"branch_id" `
|
||||
BranchName string `json:"branch_name" `
|
||||
Amount float64 `json:"amount" `
|
||||
Status order.OrderStatus `json:"status" `
|
||||
CustomerName string `json:"customer_name" `
|
||||
CustomerPhone string `json:"customer_phone" `
|
||||
Pax int `json:"pax" `
|
||||
PaymentMethod transaction.PaymentMethod `json:"payment_method" `
|
||||
OrderItem []OrderItem `json:"order_items" `
|
||||
CreatedAt string `json:"created_at"`
|
||||
UpdatedAt string `json:"updated_at"`
|
||||
}
|
||||
|
||||
type OrderItem struct {
|
||||
OrderItemID int64 `json:"order_item_id" `
|
||||
ItemID int64 `json:"item_id" `
|
||||
ItemType order.ItemType `json:"item_type" `
|
||||
ItemName string `json:"item_name" `
|
||||
Price float64 `json:"price" `
|
||||
Qty int64 `json:"qty" `
|
||||
CreatedAt string `json:"created_at"`
|
||||
UpdatedAt string `json:"updated_at"`
|
||||
}
|
||||
|
||||
type OrderList struct {
|
||||
Orders []Order `json:"orders"`
|
||||
Total int64 `json:"total"`
|
||||
Limit int `json:"limit"`
|
||||
Offset int `json:"offset"`
|
||||
}
|
||||
|
||||
type OrderMonthlyRevenue struct {
|
||||
TotalRevenue float64 `json:"total_revenue"`
|
||||
TotalTransaction int64 `json:"total_transaction"`
|
||||
}
|
||||
|
||||
type OrderBranchRevenue struct {
|
||||
BranchID string `json:"branch_id"`
|
||||
BranchName string `json:"name"`
|
||||
BranchLocation string `json:"location"`
|
||||
TotalTransaction int `json:"total_trans"`
|
||||
TotalAmount float64 `json:"total_amount"`
|
||||
}
|
||||
@@ -0,0 +1,7 @@
|
||||
package response
|
||||
|
||||
type PagingMeta struct {
|
||||
Page int `json:"page"`
|
||||
Limit int `json:"limit"`
|
||||
Total int64 `json:"total_data"`
|
||||
}
|
||||
@@ -0,0 +1,17 @@
|
||||
package response
|
||||
|
||||
type Partner struct {
|
||||
ID *int64 `json:"id"`
|
||||
Name string `json:"name"`
|
||||
Status string `json:"status"`
|
||||
Address string `json:"address"`
|
||||
CreatedAt string `json:"created_at"`
|
||||
UpdatedAt string `json:"updated_at"`
|
||||
}
|
||||
|
||||
type PartnerList struct {
|
||||
Partners []Partner `json:"partners"`
|
||||
Total int64 `json:"total"`
|
||||
Limit int `json:"limit"`
|
||||
Offset int `json:"offset"`
|
||||
}
|
||||
@@ -0,0 +1,24 @@
|
||||
package response
|
||||
|
||||
import "furtuna-be/internal/constants/product"
|
||||
|
||||
type Product struct {
|
||||
ID int64 `json:"id"`
|
||||
Name string `json:"name"`
|
||||
Type product.ProductType `json:"type"`
|
||||
Price float64 `json:"price"`
|
||||
Status product.ProductStatus `json:"status"`
|
||||
Description string `json:"description" `
|
||||
Image string `json:"image" `
|
||||
BranchID int64 `json:"branch_id"`
|
||||
StockQty int64 `json:"stock_qty"`
|
||||
CreatedAt string `json:"created_at"`
|
||||
UpdatedAt string `json:"updated_at"`
|
||||
}
|
||||
|
||||
type ProductList struct {
|
||||
Products []Product `json:"products"`
|
||||
Total int64 `json:"total"`
|
||||
Limit int `json:"limit"`
|
||||
Offset int `json:"offset"`
|
||||
}
|
||||
@@ -0,0 +1,19 @@
|
||||
package response
|
||||
|
||||
type Studio struct {
|
||||
ID *int64 `json:"id"`
|
||||
BranchId *int64 `json:"branch_id"`
|
||||
Name string `json:"name"`
|
||||
Status string `json:"status"`
|
||||
Price float64 `json:"price"`
|
||||
CreatedAt string `json:"created_at"`
|
||||
Metadata map[string]interface{} `json:"metadata"`
|
||||
UpdatedAt string `json:"updated_at"`
|
||||
}
|
||||
|
||||
type StudioList struct {
|
||||
Studios []Studio `json:"studios"`
|
||||
Total int64 `json:"total"`
|
||||
Limit int `json:"limit"`
|
||||
Offset int `json:"offset"`
|
||||
}
|
||||
@@ -0,0 +1,21 @@
|
||||
package response
|
||||
|
||||
type User struct {
|
||||
ID int64 `json:"id"`
|
||||
Name string `json:"name"`
|
||||
Email string `json:"email"`
|
||||
Status string `json:"status"`
|
||||
RoleID int64 `json:"role_id"`
|
||||
RoleName string `json:"role_name"`
|
||||
PartnerID *int64 `json:"partner_id"`
|
||||
BranchName string `json:"partner_name"`
|
||||
CreatedAt string `json:"created_at,omitempty"`
|
||||
UpdatedAt string `json:"updated_at,omitempty"`
|
||||
}
|
||||
|
||||
type UserList struct {
|
||||
Users []User `json:"users"`
|
||||
Total int64 `json:"total"`
|
||||
Limit int `json:"limit"`
|
||||
Offset int `json:"offset"`
|
||||
}
|
||||
@@ -0,0 +1,63 @@
|
||||
package middlewares
|
||||
|
||||
import (
|
||||
"furtuna-be/internal/common/mycontext"
|
||||
"net/http"
|
||||
"strings"
|
||||
|
||||
"github.com/gin-gonic/gin"
|
||||
|
||||
"furtuna-be/internal/repository"
|
||||
)
|
||||
|
||||
func AuthorizationMiddleware(cryp repository.Crypto) gin.HandlerFunc {
|
||||
return func(c *gin.Context) {
|
||||
// Get the JWT token from the header
|
||||
tokenString := c.GetHeader("Authorization")
|
||||
if tokenString == "" {
|
||||
c.JSON(http.StatusUnauthorized, gin.H{"error": "Authorization header is required"})
|
||||
c.Abort()
|
||||
return
|
||||
}
|
||||
|
||||
tokenString = strings.TrimPrefix(tokenString, "Bearer ")
|
||||
|
||||
claims, err := cryp.ParseAndValidateJWT(tokenString)
|
||||
if err != nil {
|
||||
c.JSON(http.StatusUnauthorized, gin.H{"error": "Invalid JWT token"})
|
||||
c.Abort()
|
||||
return
|
||||
}
|
||||
|
||||
customCtx, err := mycontext.NewMyContext(c.Request.Context(), claims)
|
||||
if err != nil {
|
||||
c.JSON(http.StatusInternalServerError, gin.H{"error": "error initialize context"})
|
||||
c.Abort()
|
||||
return
|
||||
}
|
||||
|
||||
c.Set("myCtx", customCtx)
|
||||
|
||||
c.Next()
|
||||
}
|
||||
}
|
||||
|
||||
func SuperAdminMiddleware() gin.HandlerFunc {
|
||||
return func(c *gin.Context) {
|
||||
ctx, exists := c.Get("myCtx")
|
||||
if !exists {
|
||||
c.JSON(http.StatusUnauthorized, gin.H{"error": "Unauthorized"})
|
||||
c.Abort()
|
||||
return
|
||||
}
|
||||
|
||||
myCtx, ok := ctx.(*mycontext.MyContextImpl)
|
||||
if !ok || !myCtx.IsSuperAdmin() {
|
||||
c.JSON(http.StatusUnauthorized, gin.H{"error": "Unauthorized"})
|
||||
c.Abort()
|
||||
return
|
||||
}
|
||||
|
||||
c.Next()
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,38 @@
|
||||
package middlewares
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"net/http"
|
||||
|
||||
"github.com/gin-gonic/gin"
|
||||
|
||||
"furtuna-be/internal/common/logger"
|
||||
)
|
||||
|
||||
func Cors() gin.HandlerFunc {
|
||||
return func(c *gin.Context) {
|
||||
c.Header("Access-Control-Allow-Origin", "*")
|
||||
c.Header("Access-Control-Allow-Credentials", "true")
|
||||
c.Header("Access-Control-Allow-Headers", "Content-Type, Content-Length, Accept-Encoding, X-CSRF-Token, Authorization, Accept, origin, Referer, Cache-Control, X-Requested-With")
|
||||
c.Header("Access-Control-Allow-Methods", "POST,HEAD,PATCH, OPTIONS, GET, PUT, DELETE")
|
||||
c.Header("Vary", "Origin")
|
||||
|
||||
if c.Request.Method == "OPTIONS" {
|
||||
c.AbortWithStatus(204)
|
||||
return
|
||||
}
|
||||
|
||||
c.Next()
|
||||
}
|
||||
}
|
||||
|
||||
func LogCorsError() gin.HandlerFunc {
|
||||
return func(c *gin.Context) {
|
||||
c.Next()
|
||||
|
||||
// check if the request was blocked due to CORS
|
||||
if c.Writer.Status() == http.StatusForbidden && c.Writer.Header().Get("Access-Control-Allow-Origin") == "" {
|
||||
logger.GetLogger().Error(fmt.Sprintf("CORS error: %s", c.Writer.Header().Get("Access-Control-Allow-Origin")))
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,31 @@
|
||||
package middlewares
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"time"
|
||||
|
||||
"github.com/gin-gonic/gin"
|
||||
|
||||
"furtuna-be/internal/common/request"
|
||||
)
|
||||
|
||||
func Logger() gin.HandlerFunc {
|
||||
return gin.LoggerWithFormatter(func(param gin.LogFormatterParams) string {
|
||||
var parsedReqInfo request.RequestInfo
|
||||
|
||||
reqInfo, exists := param.Keys[request.ReqInfoKey]
|
||||
if exists {
|
||||
parsedReqInfo = reqInfo.(request.RequestInfo)
|
||||
}
|
||||
|
||||
return fmt.Sprintf("%s - [HTTP] TraceId: %s; UserId: %d; Method: %s; Path: %s; Status: %d, Latency: %s;\n\n",
|
||||
param.TimeStamp.Format(time.RFC1123),
|
||||
parsedReqInfo.TraceId,
|
||||
parsedReqInfo.UserId,
|
||||
param.Method,
|
||||
param.Path,
|
||||
param.StatusCode,
|
||||
param.Latency,
|
||||
)
|
||||
})
|
||||
}
|
||||
@@ -0,0 +1,130 @@
|
||||
package middlewares
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"encoding/json"
|
||||
"fmt"
|
||||
"io"
|
||||
"net/http"
|
||||
"strconv"
|
||||
"strings"
|
||||
"time"
|
||||
|
||||
"github.com/gin-gonic/gin"
|
||||
"go.uber.org/zap"
|
||||
|
||||
"furtuna-be/internal/common/logger"
|
||||
)
|
||||
|
||||
func RequestMiddleware() (handler gin.HandlerFunc) {
|
||||
return func(ctx *gin.Context) {
|
||||
start := time.Now()
|
||||
body, _ := readRequestBody(ctx.Request)
|
||||
reqData := getRequestParam(ctx.Request, body)
|
||||
|
||||
// Check if the request contains a file
|
||||
isFileUpload := false
|
||||
contentType := ctx.Request.Header.Get("Content-Type")
|
||||
if strings.HasPrefix(contentType, "multipart/form-data") {
|
||||
isFileUpload = true
|
||||
}
|
||||
|
||||
// Log the request if it's not a file upload
|
||||
if !isFileUpload {
|
||||
logger.ContextLogger(ctx).With(reqData...).Info("Request")
|
||||
}
|
||||
|
||||
rbw := &ResponseBodyWriter{body: bytes.NewBufferString(""), ResponseWriter: ctx.Writer}
|
||||
ctx.Writer = rbw
|
||||
|
||||
stop := time.Now()
|
||||
latency := stop.Sub(start).Milliseconds()
|
||||
|
||||
resData := reqData
|
||||
resData = append(resData, getResponseParam(rbw, latency)...)
|
||||
|
||||
if !isFileUpload {
|
||||
logger.ContextLogger(ctx).With(resData...).Info("Response")
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func readRequestBody(req *http.Request) ([]byte, error) {
|
||||
body, err := io.ReadAll(req.Body)
|
||||
if err != nil {
|
||||
logger.ContextLogger(req.Context()).Error(fmt.Sprintf("Error reading body: %v", err))
|
||||
return nil, err
|
||||
}
|
||||
|
||||
req.Body = io.NopCloser(bytes.NewBuffer(body))
|
||||
|
||||
return body, nil
|
||||
}
|
||||
|
||||
type ResponseBodyWriter struct {
|
||||
gin.ResponseWriter
|
||||
body *bytes.Buffer
|
||||
}
|
||||
|
||||
func excludeSensitiveFields(data []interface{}) []interface{} {
|
||||
var result []interface{}
|
||||
for _, item := range data {
|
||||
if param, ok := item.(gin.Param); ok {
|
||||
// Exclude Authorization and Password fields
|
||||
if param.Key != "Authorization" && param.Key != "Password" {
|
||||
result = append(result, item)
|
||||
}
|
||||
} else {
|
||||
result = append(result, item)
|
||||
}
|
||||
}
|
||||
return result
|
||||
}
|
||||
|
||||
func getRequestParam(req *http.Request, body []byte) []zap.Field {
|
||||
var reqData []zap.Field
|
||||
reqData = append(reqData, zap.Any("host", req.Host),
|
||||
zap.Any("uri", req.RequestURI),
|
||||
zap.Any("method", req.Method),
|
||||
zap.Any("path", func() interface{} {
|
||||
p := req.URL.Path
|
||||
if p == "" {
|
||||
p = "/"
|
||||
}
|
||||
|
||||
return p
|
||||
}()),
|
||||
zap.Any("protocol", req.Proto),
|
||||
zap.Any("referer", req.Referer()),
|
||||
zap.Any("user_agent", req.UserAgent()),
|
||||
zap.Any("headers", req.Header),
|
||||
zap.Any("remote_ip", req.RemoteAddr),
|
||||
zap.Any("body", excludeSensitiveFieldsFromBody(body)),
|
||||
)
|
||||
|
||||
return reqData
|
||||
}
|
||||
|
||||
func getResponseParam(rbw *ResponseBodyWriter, latency int64) []zap.Field {
|
||||
var resData []zap.Field
|
||||
resData = append(resData,
|
||||
zap.Any("httpStatus", rbw.Status()),
|
||||
zap.Any("body", rbw.body.String()),
|
||||
zap.Any("latency_human", strconv.FormatInt(latency, 10)),
|
||||
zap.Any("headers", rbw.Header()),
|
||||
)
|
||||
|
||||
return resData
|
||||
}
|
||||
|
||||
func excludeSensitiveFieldsFromBody(body []byte) string {
|
||||
var data map[string]interface{}
|
||||
if err := json.Unmarshal(body, &data); err != nil {
|
||||
return string(body)
|
||||
}
|
||||
|
||||
delete(data, "password")
|
||||
|
||||
result, _ := json.Marshal(data)
|
||||
return string(result)
|
||||
}
|
||||
@@ -0,0 +1,20 @@
|
||||
package middlewares
|
||||
|
||||
import (
|
||||
"furtuna-be/internal/common/request"
|
||||
"furtuna-be/internal/constants"
|
||||
"furtuna-be/internal/utils/generator"
|
||||
"github.com/gin-gonic/gin"
|
||||
)
|
||||
|
||||
func Trace() gin.HandlerFunc {
|
||||
return func(c *gin.Context) {
|
||||
traceId := c.Request.Header.Get("Trace-Id")
|
||||
if traceId == "" {
|
||||
traceId = generator.GenerateUUID()
|
||||
}
|
||||
|
||||
request.SetTraceId(c, traceId)
|
||||
c.Set(constants.ContextRequestID, traceId)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1 @@
|
||||
package auth
|
||||
@@ -0,0 +1,47 @@
|
||||
package auth
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"fmt"
|
||||
|
||||
"go.uber.org/zap"
|
||||
"gorm.io/gorm"
|
||||
|
||||
"furtuna-be/internal/common/logger"
|
||||
"furtuna-be/internal/entity"
|
||||
)
|
||||
|
||||
type AuthRepository struct {
|
||||
db *gorm.DB
|
||||
}
|
||||
|
||||
func NewAuthRepository(db *gorm.DB) *AuthRepository {
|
||||
return &AuthRepository{
|
||||
db: db,
|
||||
}
|
||||
}
|
||||
|
||||
func (r *AuthRepository) CheckExistsUserAccount(ctx context.Context, email string) (*entity.UserDB, error) {
|
||||
var user entity.UserDB
|
||||
|
||||
err := r.db.
|
||||
Table("users").
|
||||
Select("users.*, user_roles.role_id, user_roles.partner_id, roles.role_name, partners.name as partner_name").
|
||||
Where("users.email = ?", email).
|
||||
Joins("left join user_roles on users.id = user_roles.user_id").
|
||||
Joins("left join roles on user_roles.role_id = roles.role_id").
|
||||
Joins("left join partners on user_roles.partner_id = partners.id").
|
||||
First(&user).Error
|
||||
|
||||
if err != nil {
|
||||
if errors.Is(err, gorm.ErrRecordNotFound) {
|
||||
return nil, fmt.Errorf("user with email %s does not exist", email) // or use a custom error type
|
||||
}
|
||||
|
||||
logger.ContextLogger(ctx).Error(fmt.Sprintf("Failed to get user with email: %s", email), zap.Error(err))
|
||||
return nil, err
|
||||
}
|
||||
|
||||
return &user, nil
|
||||
}
|
||||
@@ -0,0 +1,91 @@
|
||||
package branches
|
||||
|
||||
import (
|
||||
"context"
|
||||
"furtuna-be/internal/common/logger"
|
||||
"furtuna-be/internal/entity"
|
||||
|
||||
"go.uber.org/zap"
|
||||
"gorm.io/gorm"
|
||||
)
|
||||
|
||||
type BranchRepository struct {
|
||||
db *gorm.DB
|
||||
}
|
||||
|
||||
func NewBranchRepository(db *gorm.DB) *BranchRepository {
|
||||
return &BranchRepository{
|
||||
db: db,
|
||||
}
|
||||
}
|
||||
|
||||
func (b *BranchRepository) CreateBranch(ctx context.Context, branch *entity.BranchDB) (*entity.BranchDB, error) {
|
||||
err := b.db.Create(branch).Error
|
||||
if err != nil {
|
||||
logger.ContextLogger(ctx).Error("error when create branch", zap.Error(err))
|
||||
return nil, err
|
||||
}
|
||||
return branch, nil
|
||||
}
|
||||
|
||||
func (b *BranchRepository) UpdateBranch(ctx context.Context, branch *entity.BranchDB) (*entity.BranchDB, error) {
|
||||
if err := b.db.Save(branch).Error; err != nil {
|
||||
logger.ContextLogger(ctx).Error("error when update branch", zap.Error(err))
|
||||
return nil, err
|
||||
}
|
||||
return branch, nil
|
||||
}
|
||||
|
||||
func (b *BranchRepository) GetBranchByID(ctx context.Context, id int64) (*entity.BranchDB, error) {
|
||||
branch := new(entity.BranchDB)
|
||||
if err := b.db.First(branch, id).Error; err != nil {
|
||||
logger.ContextLogger(ctx).Error("error when get by id branch", zap.Error(err))
|
||||
return nil, err
|
||||
}
|
||||
return branch, nil
|
||||
}
|
||||
|
||||
func (b *BranchRepository) GetAllBranches(ctx context.Context, req entity.BranchSearch) (entity.BranchList, int, error) {
|
||||
var branches []*entity.BranchDB
|
||||
var total int64
|
||||
|
||||
query := b.db
|
||||
query = query.Where("deleted_at is null")
|
||||
|
||||
if req.Search != "" {
|
||||
query = query.Where("name ILIKE ?", "%"+req.Search+"%")
|
||||
}
|
||||
|
||||
if req.Name != "" {
|
||||
query = query.Where("name ILIKE ?", "%"+req.Name+"%")
|
||||
}
|
||||
|
||||
if req.Limit > 0 {
|
||||
query = query.Limit(req.Limit)
|
||||
}
|
||||
|
||||
if req.Offset > 0 {
|
||||
query = query.Offset(req.Offset)
|
||||
}
|
||||
|
||||
if err := query.Find(&branches).Error; err != nil {
|
||||
logger.ContextLogger(ctx).Error("error when get all branches", zap.Error(err))
|
||||
return nil, 0, err
|
||||
}
|
||||
|
||||
if err := b.db.Model(&entity.BranchDB{}).Where(query).Count(&total).Error; err != nil {
|
||||
logger.ContextLogger(ctx).Error("error when count branches", zap.Error(err))
|
||||
return nil, 0, err
|
||||
}
|
||||
|
||||
return branches, int(total), nil
|
||||
}
|
||||
|
||||
func (b *BranchRepository) DeleteBranch(ctx context.Context, id int64) error {
|
||||
branch := new(entity.BranchDB)
|
||||
branch.ID = id
|
||||
if err := b.db.Delete(branch).Error; err != nil {
|
||||
return err
|
||||
}
|
||||
return nil
|
||||
}
|
||||
@@ -0,0 +1,4 @@
|
||||
//go:generate mockery --name Crypto --filename crypto.go --output ./mock --with-expecter
|
||||
|
||||
package crypto
|
||||
|
||||
@@ -0,0 +1,90 @@
|
||||
package crypto
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"strconv"
|
||||
"time"
|
||||
|
||||
"github.com/golang-jwt/jwt"
|
||||
"golang.org/x/crypto/bcrypt"
|
||||
|
||||
"furtuna-be/internal/common/errors"
|
||||
"furtuna-be/internal/entity"
|
||||
)
|
||||
|
||||
func NewCrypto(config CryptoConfig) *CryptoImpl {
|
||||
return &CryptoImpl{
|
||||
Config: config,
|
||||
}
|
||||
}
|
||||
|
||||
type CryptoConfig interface {
|
||||
AccessTokenSecret() string
|
||||
AccessTokenExpiresDate() time.Time
|
||||
}
|
||||
|
||||
type CryptoImpl struct {
|
||||
Config CryptoConfig
|
||||
}
|
||||
|
||||
func (c *CryptoImpl) CompareHashAndPassword(hash string, password string) bool {
|
||||
err := bcrypt.CompareHashAndPassword([]byte(hash), []byte(password))
|
||||
return err == nil
|
||||
}
|
||||
|
||||
func (c *CryptoImpl) ValidateWT(tokenString string) (*jwt.Token, error) {
|
||||
token, err := jwt.Parse(tokenString, func(token *jwt.Token) (interface{}, error) {
|
||||
if _, ok := token.Method.(*jwt.SigningMethodHMAC); !ok {
|
||||
return nil, fmt.Errorf("Unexpected signing method: %v", token.Header["alg"])
|
||||
}
|
||||
return []byte(c.Config.AccessTokenSecret()), nil
|
||||
})
|
||||
|
||||
return token, err
|
||||
}
|
||||
|
||||
func (c *CryptoImpl) GenerateJWT(user *entity.User) (string, error) {
|
||||
branchID := int64(0)
|
||||
if user.PartnerID != nil {
|
||||
branchID = *user.PartnerID
|
||||
}
|
||||
|
||||
claims := &entity.JWTAuthClaims{
|
||||
StandardClaims: jwt.StandardClaims{
|
||||
Subject: strconv.FormatInt(user.ID, 10),
|
||||
ExpiresAt: c.Config.AccessTokenExpiresDate().Unix(),
|
||||
IssuedAt: time.Now().Unix(),
|
||||
NotBefore: time.Now().Unix(),
|
||||
},
|
||||
UserID: user.ID,
|
||||
Name: user.Name,
|
||||
Email: user.Email,
|
||||
Role: int(user.RoleID),
|
||||
BranchID: branchID,
|
||||
}
|
||||
|
||||
token, err := jwt.
|
||||
NewWithClaims(jwt.SigningMethodHS256, claims).
|
||||
SignedString([]byte(c.Config.AccessTokenSecret()))
|
||||
|
||||
if err != nil {
|
||||
return "", err
|
||||
}
|
||||
|
||||
return token, nil
|
||||
}
|
||||
|
||||
func (c *CryptoImpl) ParseAndValidateJWT(tokenString string) (*entity.JWTAuthClaims, error) {
|
||||
token, err := jwt.ParseWithClaims(tokenString, &entity.JWTAuthClaims{}, func(token *jwt.Token) (interface{}, error) {
|
||||
return []byte(c.Config.AccessTokenSecret()), nil
|
||||
})
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
if claims, ok := token.Claims.(*entity.JWTAuthClaims); ok && token.Valid {
|
||||
return claims, nil
|
||||
} else {
|
||||
return nil, errors.ErrorUnauthorized
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,86 @@
|
||||
package event
|
||||
|
||||
import (
|
||||
"context"
|
||||
|
||||
"go.uber.org/zap"
|
||||
"gorm.io/gorm"
|
||||
|
||||
"furtuna-be/internal/common/logger"
|
||||
"furtuna-be/internal/entity"
|
||||
)
|
||||
|
||||
type EventRepoImpl struct {
|
||||
DB *gorm.DB
|
||||
}
|
||||
|
||||
func NewEventRepo(db *gorm.DB) *EventRepoImpl {
|
||||
return &EventRepoImpl{DB: db}
|
||||
}
|
||||
|
||||
func (e *EventRepoImpl) CreateEvent(ctx context.Context, event *entity.EventDB) (*entity.EventDB, error) {
|
||||
err := e.DB.Create(event).Error
|
||||
if err != nil {
|
||||
logger.ContextLogger(ctx).Error("error when create event", zap.Error(err))
|
||||
return nil, err
|
||||
}
|
||||
return event, nil
|
||||
}
|
||||
|
||||
func (e *EventRepoImpl) UpdateEvent(ctx context.Context, event *entity.EventDB) (*entity.EventDB, error) {
|
||||
if err := e.DB.Save(event).Error; err != nil {
|
||||
logger.ContextLogger(ctx).Error("error when update event", zap.Error(err))
|
||||
return nil, err
|
||||
}
|
||||
return event, nil
|
||||
}
|
||||
|
||||
func (e *EventRepoImpl) GetEventByID(ctx context.Context, id int64) (*entity.EventDB, error) {
|
||||
event := new(entity.EventDB)
|
||||
if err := e.DB.First(event, id).Error; err != nil {
|
||||
logger.ContextLogger(ctx).Error("error when get event by id", zap.Error(err))
|
||||
return nil, err
|
||||
}
|
||||
return event, nil
|
||||
}
|
||||
|
||||
func (e *EventRepoImpl) GetAllEvents(ctx context.Context, nameFilter string, limit, offset int) (entity.EventList, int, error) {
|
||||
var events []*entity.EventDB
|
||||
var total int64
|
||||
|
||||
query := e.DB
|
||||
query = query.Where("deleted_at is null")
|
||||
|
||||
if nameFilter != "" {
|
||||
query = query.Where("name LIKE ?", "%"+nameFilter+"%")
|
||||
}
|
||||
|
||||
if limit > 0 {
|
||||
query = query.Limit(limit)
|
||||
}
|
||||
if offset > 0 {
|
||||
query = query.Offset(offset)
|
||||
}
|
||||
|
||||
if err := query.Find(&events).Error; err != nil {
|
||||
logger.ContextLogger(ctx).Error("error when get all events", zap.Error(err))
|
||||
return nil, 0, err
|
||||
}
|
||||
|
||||
if err := e.DB.Model(&entity.EventDB{}).Where(query).Count(&total).Error; err != nil {
|
||||
logger.ContextLogger(ctx).Error("error when count event", zap.Error(err))
|
||||
return nil, 0, err
|
||||
}
|
||||
|
||||
return events, int(total), nil
|
||||
}
|
||||
|
||||
func (e *EventRepoImpl) DeleteEvent(ctx context.Context, id int64) error {
|
||||
event := new(entity.EventDB)
|
||||
event.ID = id
|
||||
if err := e.DB.Delete(event).Error; err != nil {
|
||||
logger.ContextLogger(ctx).Error("error when get all events", zap.Error(err))
|
||||
return err
|
||||
}
|
||||
return nil
|
||||
}
|
||||
@@ -0,0 +1,303 @@
|
||||
package orders
|
||||
|
||||
import (
|
||||
"context"
|
||||
"fmt"
|
||||
"furtuna-be/internal/common/logger"
|
||||
"furtuna-be/internal/entity"
|
||||
|
||||
"go.uber.org/zap"
|
||||
"gorm.io/gorm"
|
||||
)
|
||||
|
||||
type OrderRepository struct {
|
||||
db *gorm.DB
|
||||
}
|
||||
|
||||
func NewOrderRepository(db *gorm.DB) *OrderRepository {
|
||||
return &OrderRepository{
|
||||
db: db,
|
||||
}
|
||||
}
|
||||
|
||||
func (o *OrderRepository) CreateOrder(ctx context.Context, order *entity.OrderDB) (*entity.OrderDB, error) {
|
||||
tx := o.db.Begin()
|
||||
|
||||
if err := tx.Select("branch_id", "status", "customer_name", "customer_phone", "pax", "amount", "created_by").Create(order).Error; err != nil {
|
||||
tx.Rollback()
|
||||
logError(ctx, "creating order", err)
|
||||
return nil, err
|
||||
}
|
||||
|
||||
for i, orditem := range order.OrderItem {
|
||||
orderItem := orditem.ToOrderItemDB()
|
||||
orderItem.OrderID = order.ID
|
||||
|
||||
err := tx.Select("order_id", "item_id", "item_type", "price", "qty", "created_by").Create(orderItem).Error
|
||||
if err != nil {
|
||||
logger.ContextLogger(ctx).Error("error when create order item", zap.Error(err))
|
||||
return nil, err
|
||||
}
|
||||
|
||||
order.OrderItem[i] = *orderItem.ToOrderItem()
|
||||
}
|
||||
|
||||
//insert transaction
|
||||
transaction := order.Transaction.ToTransactionDB()
|
||||
transaction.OrderID = order.ID
|
||||
|
||||
if err := tx.Select("branch_id", "status", "amount", "order_id", "payment_method", "customer_name", "customer_phone", "created_by").Create(transaction).Error; err != nil {
|
||||
tx.Rollback()
|
||||
logError(ctx, "creating transaction", err)
|
||||
return nil, err
|
||||
}
|
||||
|
||||
if err := tx.Commit().Error; err != nil {
|
||||
tx.Rollback()
|
||||
logError(ctx, "committing transaction", err)
|
||||
return nil, err
|
||||
}
|
||||
|
||||
return order, nil
|
||||
}
|
||||
|
||||
func (b *OrderRepository) UpdateOrder(ctx context.Context, order *entity.OrderDB) (*entity.OrderDB, error) {
|
||||
|
||||
if err := b.db.Select("status", "updated_at", "updated_by").Save(order).Error; err != nil {
|
||||
logError(ctx, "update order", err)
|
||||
return nil, err
|
||||
}
|
||||
|
||||
return order, nil
|
||||
}
|
||||
|
||||
func (b *OrderRepository) GetAllOrders(ctx context.Context, req entity.OrderSearch) (entity.OrderList, int, error) {
|
||||
var orders []*entity.OrderDB
|
||||
var total int64
|
||||
|
||||
query := b.db.Table("orders").
|
||||
Select("orders.id, orders.branch_id, b.name as branch_name, orders.status, orders.amount, orders.created_at, orders.updated_at, oi.order_item_id, oi.order_id, oi.item_id, oi.item_type, COALESCE(p.name, s.name, '') as item_name, oi.price, oi.qty, oi.created_at, oi.updated_at, COALESCE(t.payment_method, ''), COALESCE(orders.customer_name, ''), COALESCE(orders.customer_phone, ''), COALESCE(orders.pax, 0)").
|
||||
Joins("LEFT JOIN order_items oi ON orders.id = oi.order_id").
|
||||
Joins("LEFT JOIN transactions t ON orders.id = t.order_id").
|
||||
Joins("LEFT JOIN products p ON oi.item_id = p.id AND oi.item_type ='PRODUCT' ").
|
||||
Joins("LEFT JOIN studios s ON oi.item_id = s.id AND oi.item_type ='STUDIO' ").
|
||||
Joins("LEFT JOIN branches b ON orders.branch_id = b.id")
|
||||
|
||||
if req.Search != "" {
|
||||
query = query.Where("b.name ILIKE ? or orders.status ILIKE ? or oi.item_type ILIKE ? or p.name ILIKE ? or orders.customer_name ILIKE ? ", "%"+req.Search+"%", "%"+req.Search+"%", "%"+req.Search+"%", "%"+req.Search+"%", "%"+req.Search+"%")
|
||||
}
|
||||
|
||||
if req.Status != "" {
|
||||
query = query.Where("orders.status = ?", req.Status)
|
||||
}
|
||||
|
||||
if req.BranchID > 0 {
|
||||
query = query.Where("orders.branch_id = ?", req.BranchID)
|
||||
}
|
||||
|
||||
if req.StatusActive.IsActive() {
|
||||
query = query.Joins("INNER JOIN (SELECT o.id, oi.qty, o.created_at FROM orders o INNER JOIN order_items oi ON o.id = oi.order_id AND oi.item_type = 'STUDIO' where o.status != 'CANCEL' and CURRENT_TIMESTAMP > o.created_at AND CURRENT_TIMESTAMP < (o.created_at + (oi.qty || ' hours')::interval)) order_active on order_active.id=orders.id")
|
||||
}
|
||||
|
||||
if req.Limit > 0 {
|
||||
query = query.Limit(req.Limit)
|
||||
}
|
||||
|
||||
if req.Offset > 0 {
|
||||
query = query.Offset(req.Offset)
|
||||
}
|
||||
|
||||
query.Order("orders.created_at DESC")
|
||||
|
||||
rows, err := query.Rows()
|
||||
if err != nil {
|
||||
return nil, 0, err
|
||||
}
|
||||
|
||||
defer rows.Close()
|
||||
|
||||
ordersMap := make(map[int64]*entity.OrderDB) // Map to store orders by ID
|
||||
for rows.Next() {
|
||||
var ordr entity.OrderDB
|
||||
var oi entity.OrderItem
|
||||
|
||||
err := rows.Scan(&ordr.ID, &ordr.BranchID, &ordr.BranchName, &ordr.Status, &ordr.Amount, &ordr.CreatedAt, &ordr.UpdatedAt,
|
||||
&oi.OrderItemID, &oi.OrderID, &oi.ItemID, &oi.ItemType, &oi.ItemName, &oi.Price, &oi.Qty, &oi.CreatedAt, &oi.UpdatedAt,
|
||||
&ordr.Transaction.PaymentMethod, &ordr.CustomerName, &ordr.CustomerPhone, &ordr.Pax)
|
||||
if err != nil {
|
||||
logger.ContextLogger(ctx).Error("error scanning rows", zap.Error(err))
|
||||
return nil, 0, err
|
||||
}
|
||||
|
||||
if order, ok := ordersMap[ordr.ID]; ok {
|
||||
// Order already exists in map, append OrderItem to existing order
|
||||
order.OrderItem = append(order.OrderItem, oi)
|
||||
} else {
|
||||
// Order doesn't exist in map, create a new OrderDB
|
||||
newOrder := ordr
|
||||
newOrder.OrderItem = []entity.OrderItem{oi}
|
||||
ordersMap[ordr.ID] = &newOrder
|
||||
|
||||
orders = append(orders, &ordr)
|
||||
}
|
||||
}
|
||||
|
||||
// assign value order item
|
||||
for _, v := range orders {
|
||||
v.OrderItem = ordersMap[v.ID].OrderItem
|
||||
}
|
||||
|
||||
//reset limit for count total data
|
||||
query = query.Offset(-1).Limit(-1)
|
||||
|
||||
if err := query.Count(&total).Error; err != nil {
|
||||
logger.ContextLogger(ctx).Error("error when count orders", zap.Error(err))
|
||||
return nil, 0, err
|
||||
}
|
||||
|
||||
return orders, int(total), nil
|
||||
}
|
||||
|
||||
func (b *OrderRepository) GetOrderByID(ctx context.Context, id int64) (*entity.OrderDB, error) {
|
||||
var orders *entity.OrderDB
|
||||
|
||||
query := b.db.Table("orders").
|
||||
Select("orders.id, orders.branch_id, b.name as branch_name, orders.status, orders.amount, orders.created_at, orders.updated_at, oi.order_item_id, oi.order_id, oi.item_id, oi.item_type, COALESCE(p.name, s.name, '') as item_name, oi.price, oi.qty, oi.created_at, oi.updated_at, t.payment_method, orders.customer_name, orders.customer_phone, orders.pax").
|
||||
Joins("LEFT JOIN order_items oi ON orders.id = oi.order_id").
|
||||
Joins("LEFT JOIN transactions t ON orders.id = t.order_id").
|
||||
Joins("LEFT JOIN products p ON oi.item_id = p.id AND oi.item_type ='PRODUCT' ").
|
||||
Joins("LEFT JOIN studios s ON oi.item_id = s.id AND oi.item_type ='STUDIO' ").
|
||||
Joins("LEFT JOIN branches b ON orders.branch_id = b.id").
|
||||
Where("orders.id = ?", id)
|
||||
|
||||
rows, err := query.Rows()
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
defer rows.Close()
|
||||
|
||||
var ordr entity.OrderDB // Map to store orders by ID
|
||||
for rows.Next() {
|
||||
var oi entity.OrderItem
|
||||
|
||||
err := rows.Scan(&ordr.ID, &ordr.BranchID, &ordr.BranchName, &ordr.Status, &ordr.Amount, &ordr.CreatedAt, &ordr.UpdatedAt,
|
||||
&oi.OrderItemID, &oi.OrderID, &oi.ItemID, &oi.ItemType, &oi.ItemName, &oi.Price, &oi.Qty, &oi.CreatedAt, &oi.UpdatedAt,
|
||||
&ordr.Transaction.PaymentMethod, &ordr.CustomerName, &ordr.CustomerPhone, &ordr.Pax)
|
||||
if err != nil {
|
||||
logger.ContextLogger(ctx).Error("error scanning rows", zap.Error(err))
|
||||
return nil, err
|
||||
}
|
||||
|
||||
ordr.OrderItem = append(ordr.OrderItem, oi)
|
||||
}
|
||||
|
||||
orders = &ordr
|
||||
|
||||
if orders == nil {
|
||||
return nil, fmt.Errorf("order not found")
|
||||
}
|
||||
|
||||
return orders, nil
|
||||
}
|
||||
|
||||
func (b *OrderRepository) GetTotalRevenue(ctx context.Context, req entity.OrderTotalRevenueSearch) (float64, int64, error) {
|
||||
var (
|
||||
totalmonthlyRevenue float64
|
||||
totalmonthlyTrans int64
|
||||
)
|
||||
|
||||
query := b.db.Table("orders").
|
||||
Select("COALESCE(sum(amount),0) as total_amount, COALESCE(count(id),0) as total_transaction").
|
||||
Where("status in ('NEW','PAID') ")
|
||||
|
||||
if req.BranchID > 0 {
|
||||
query = query.Where("branch_id = ?", req.BranchID)
|
||||
}
|
||||
|
||||
if req.Month > 0 {
|
||||
query = query.Where("EXTRACT(MONTH FROM created_at) = ? ", req.Month)
|
||||
}
|
||||
|
||||
if req.Year > 0 {
|
||||
query = query.Where("EXTRACT(YEAR FROM created_at) = ? ", req.Year)
|
||||
}
|
||||
|
||||
if req.DateStart != nil {
|
||||
query = query.Where("created_at >= ? ", req.DateStart)
|
||||
}
|
||||
|
||||
if req.DateEnd != nil {
|
||||
query = query.Where("created_at <= ? ", req.DateEnd)
|
||||
}
|
||||
|
||||
rows, err := query.Rows()
|
||||
if err != nil {
|
||||
return totalmonthlyRevenue, totalmonthlyTrans, err
|
||||
}
|
||||
defer rows.Close()
|
||||
|
||||
for rows.Next() {
|
||||
err := rows.Scan(&totalmonthlyRevenue, &totalmonthlyTrans)
|
||||
if err != nil {
|
||||
logger.ContextLogger(ctx).Error("error scanning rows", zap.Error(err))
|
||||
return totalmonthlyRevenue, totalmonthlyTrans, err
|
||||
}
|
||||
}
|
||||
|
||||
return totalmonthlyRevenue, totalmonthlyTrans, nil
|
||||
}
|
||||
|
||||
func (b *OrderRepository) GetYearlyRevenue(ctx context.Context, year int) (entity.OrderYearlyRevenueList, error) {
|
||||
var result entity.OrderYearlyRevenueList
|
||||
|
||||
err := b.db.Raw(` SELECT
|
||||
oi.item_type,
|
||||
EXTRACT(MONTH FROM o.created_at) AS month_number,
|
||||
SUM(oi.price ) AS total_amount
|
||||
FROM
|
||||
orders o
|
||||
JOIN
|
||||
order_items oi ON o.id = oi.order_id
|
||||
WHERE
|
||||
EXTRACT(YEAR FROM o.created_at) = ?
|
||||
AND o.status IN ('NEW', 'PAID')
|
||||
GROUP BY
|
||||
EXTRACT(MONTH FROM o.created_at),
|
||||
oi.item_type
|
||||
ORDER BY
|
||||
month_number,
|
||||
oi.item_type`, year).Scan(&result).Error
|
||||
|
||||
return result, err
|
||||
}
|
||||
|
||||
func (b *OrderRepository) GetBranchRevenue(ctx context.Context, req entity.OrderBranchRevenueSearch) (entity.OrderBranchRevenueList, error) {
|
||||
var result entity.OrderBranchRevenueList
|
||||
|
||||
query := b.db.Table("orders o").
|
||||
Joins("JOIN branches ON branches.id = o.branch_id").
|
||||
Select("o.branch_id, branches.name, branches.location, SUM(o.amount) as total_amount, COUNT(o.id) as total_trans").
|
||||
Where("o.status IN ('NEW', 'PAID')").
|
||||
Group("o.branch_id, branches.name, branches.location").
|
||||
Order("total_amount DESC, total_trans DESC")
|
||||
|
||||
if req.DateStart != nil {
|
||||
query = query.Where("o.created_at >= ? ", req.DateStart)
|
||||
}
|
||||
|
||||
if req.DateEnd != nil {
|
||||
query = query.Where("o.created_at <= ? ", req.DateEnd)
|
||||
}
|
||||
|
||||
if err := query.Find(&result).Error; err != nil {
|
||||
logger.ContextLogger(ctx).Error("error when GetBranchRevenue", zap.Error(err))
|
||||
return nil, err
|
||||
}
|
||||
|
||||
return result, nil
|
||||
}
|
||||
|
||||
func logError(ctx context.Context, s string, err error) {
|
||||
panic("unimplemented")
|
||||
}
|
||||
@@ -0,0 +1,67 @@
|
||||
package oss
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"context"
|
||||
"fmt"
|
||||
|
||||
"github.com/aws/aws-sdk-go/aws"
|
||||
"github.com/aws/aws-sdk-go/aws/credentials"
|
||||
"github.com/aws/aws-sdk-go/aws/session"
|
||||
"github.com/aws/aws-sdk-go/service/s3"
|
||||
)
|
||||
|
||||
type OSSConfig interface {
|
||||
GetAccessKeyID() string
|
||||
GetAccessKeySecret() string
|
||||
GetEndpoint() string
|
||||
GetBucketName() string
|
||||
GetHostURL() string
|
||||
}
|
||||
|
||||
const _awsRegion = "us-east-1"
|
||||
const _s3ACL = "public-read"
|
||||
|
||||
type OssRepositoryImpl struct {
|
||||
s3 *s3.S3
|
||||
cfg OSSConfig
|
||||
}
|
||||
|
||||
func NewOssRepositoryImpl(ossCfg OSSConfig) *OssRepositoryImpl {
|
||||
sess, err := session.NewSession(&aws.Config{
|
||||
S3ForcePathStyle: aws.Bool(true),
|
||||
Endpoint: aws.String(ossCfg.GetEndpoint()),
|
||||
Region: aws.String(_awsRegion),
|
||||
Credentials: credentials.NewStaticCredentials(ossCfg.GetAccessKeyID(), ossCfg.GetAccessKeySecret(), ""),
|
||||
})
|
||||
|
||||
if err != nil {
|
||||
fmt.Println("Failed to create AWS session:", err)
|
||||
return nil
|
||||
}
|
||||
|
||||
return &OssRepositoryImpl{
|
||||
s3: s3.New(sess),
|
||||
cfg: ossCfg,
|
||||
}
|
||||
}
|
||||
|
||||
func (r *OssRepositoryImpl) UploadFile(ctx context.Context, fileName string, fileContent []byte) (fileUrl string, err error) {
|
||||
reader := bytes.NewReader(fileContent)
|
||||
|
||||
_, err = r.s3.PutObject(&s3.PutObjectInput{
|
||||
Bucket: aws.String(r.cfg.GetBucketName()),
|
||||
Key: aws.String(fileName),
|
||||
Body: reader,
|
||||
ACL: aws.String(_s3ACL),
|
||||
})
|
||||
|
||||
return r.GetPublicURL(fileName), err
|
||||
}
|
||||
|
||||
func (r *OssRepositoryImpl) GetPublicURL(fileName string) string {
|
||||
if fileName == "" {
|
||||
return ""
|
||||
}
|
||||
return fmt.Sprintf("%s/%s%s", r.cfg.GetHostURL(), r.cfg.GetBucketName(), fileName)
|
||||
}
|
||||
@@ -0,0 +1,91 @@
|
||||
package partners
|
||||
|
||||
import (
|
||||
"context"
|
||||
"furtuna-be/internal/common/logger"
|
||||
"furtuna-be/internal/entity"
|
||||
|
||||
"go.uber.org/zap"
|
||||
"gorm.io/gorm"
|
||||
)
|
||||
|
||||
type PartnerRepository struct {
|
||||
db *gorm.DB
|
||||
}
|
||||
|
||||
func NewPartnerRepository(db *gorm.DB) *PartnerRepository {
|
||||
return &PartnerRepository{
|
||||
db: db,
|
||||
}
|
||||
}
|
||||
|
||||
func (b *PartnerRepository) Create(ctx context.Context, Partner *entity.PartnerDB) (*entity.PartnerDB, error) {
|
||||
err := b.db.Create(Partner).Error
|
||||
if err != nil {
|
||||
logger.ContextLogger(ctx).Error("error when create Partner", zap.Error(err))
|
||||
return nil, err
|
||||
}
|
||||
return Partner, nil
|
||||
}
|
||||
|
||||
func (b *PartnerRepository) Update(ctx context.Context, Partner *entity.PartnerDB) (*entity.PartnerDB, error) {
|
||||
if err := b.db.Save(Partner).Error; err != nil {
|
||||
logger.ContextLogger(ctx).Error("error when update Partner", zap.Error(err))
|
||||
return nil, err
|
||||
}
|
||||
return Partner, nil
|
||||
}
|
||||
|
||||
func (b *PartnerRepository) GetByID(ctx context.Context, id int64) (*entity.PartnerDB, error) {
|
||||
Partner := new(entity.PartnerDB)
|
||||
if err := b.db.First(Partner, id).Error; err != nil {
|
||||
logger.ContextLogger(ctx).Error("error when get by id Partner", zap.Error(err))
|
||||
return nil, err
|
||||
}
|
||||
return Partner, nil
|
||||
}
|
||||
|
||||
func (b *PartnerRepository) GetAll(ctx context.Context, req entity.PartnerSearch) (entity.PartnerList, int, error) {
|
||||
var Partneres []*entity.PartnerDB
|
||||
var total int64
|
||||
|
||||
query := b.db
|
||||
query = query.Where("deleted_at is null")
|
||||
|
||||
if req.Search != "" {
|
||||
query = query.Where("name ILIKE ?", "%"+req.Search+"%")
|
||||
}
|
||||
|
||||
if req.Name != "" {
|
||||
query = query.Where("name ILIKE ?", "%"+req.Name+"%")
|
||||
}
|
||||
|
||||
if req.Limit > 0 {
|
||||
query = query.Limit(req.Limit)
|
||||
}
|
||||
|
||||
if req.Offset > 0 {
|
||||
query = query.Offset(req.Offset)
|
||||
}
|
||||
|
||||
if err := query.Find(&Partneres).Error; err != nil {
|
||||
logger.ContextLogger(ctx).Error("error when get all Partneres", zap.Error(err))
|
||||
return nil, 0, err
|
||||
}
|
||||
|
||||
if err := b.db.Model(&entity.PartnerDB{}).Where(query).Count(&total).Error; err != nil {
|
||||
logger.ContextLogger(ctx).Error("error when count Partneres", zap.Error(err))
|
||||
return nil, 0, err
|
||||
}
|
||||
|
||||
return Partneres, int(total), nil
|
||||
}
|
||||
|
||||
func (b *PartnerRepository) Delete(ctx context.Context, id int64) error {
|
||||
Partner := new(entity.PartnerDB)
|
||||
Partner.ID = id
|
||||
if err := b.db.Delete(Partner).Error; err != nil {
|
||||
return err
|
||||
}
|
||||
return nil
|
||||
}
|
||||
@@ -0,0 +1,107 @@
|
||||
package products
|
||||
|
||||
import (
|
||||
"context"
|
||||
"furtuna-be/internal/common/logger"
|
||||
"furtuna-be/internal/entity"
|
||||
|
||||
"go.uber.org/zap"
|
||||
"gorm.io/gorm"
|
||||
)
|
||||
|
||||
type ProductRepository struct {
|
||||
db *gorm.DB
|
||||
}
|
||||
|
||||
func NewProductRepository(db *gorm.DB) *ProductRepository {
|
||||
return &ProductRepository{
|
||||
db: db,
|
||||
}
|
||||
}
|
||||
|
||||
func (b *ProductRepository) CreateProduct(ctx context.Context, product *entity.ProductDB) (*entity.ProductDB, error) {
|
||||
err := b.db.Create(product).Error
|
||||
if err != nil {
|
||||
logger.ContextLogger(ctx).Error("error when create product", zap.Error(err))
|
||||
return nil, err
|
||||
}
|
||||
return product, nil
|
||||
}
|
||||
|
||||
func (b *ProductRepository) UpdateProduct(ctx context.Context, product *entity.ProductDB) (*entity.ProductDB, error) {
|
||||
if err := b.db.Save(product).Error; err != nil {
|
||||
logger.ContextLogger(ctx).Error("error when update product", zap.Error(err))
|
||||
return nil, err
|
||||
}
|
||||
return product, nil
|
||||
}
|
||||
|
||||
func (b *ProductRepository) GetProductByID(ctx context.Context, id int64) (*entity.ProductDB, error) {
|
||||
product := new(entity.ProductDB)
|
||||
if err := b.db.First(product, id).Error; err != nil {
|
||||
logger.ContextLogger(ctx).Error("error when get by id product", zap.Error(err))
|
||||
return nil, err
|
||||
}
|
||||
return product, nil
|
||||
}
|
||||
|
||||
func (b *ProductRepository) GetAllProducts(ctx context.Context, req entity.ProductSearch) (entity.ProductList, int, error) {
|
||||
var products []*entity.ProductDB
|
||||
var total int64
|
||||
|
||||
query := b.db
|
||||
query = query.Where("deleted_at is null")
|
||||
|
||||
if req.Search != "" {
|
||||
query = query.Where("name ILIKE ?", "%"+req.Search+"%")
|
||||
}
|
||||
|
||||
if req.Name != "" {
|
||||
query = query.Where("name ILIKE ?", "%"+req.Name+"%")
|
||||
}
|
||||
|
||||
if req.Type != "" {
|
||||
query = query.Where("type = ? ", req.Type)
|
||||
}
|
||||
|
||||
if req.BranchID > 0 {
|
||||
query = query.Where("branch_id = ? ", req.BranchID)
|
||||
}
|
||||
|
||||
if req.Available != "" {
|
||||
if req.Available.IsAvailable() {
|
||||
query = query.Where("stock_qty > 0 ")
|
||||
} else if req.Available.IsUnavailable() {
|
||||
query = query.Where("stock_qty < 1 ")
|
||||
}
|
||||
}
|
||||
|
||||
if req.Limit > 0 {
|
||||
query = query.Limit(req.Limit)
|
||||
}
|
||||
|
||||
if req.Offset > 0 {
|
||||
query = query.Offset(req.Offset)
|
||||
}
|
||||
|
||||
if err := query.Find(&products).Error; err != nil {
|
||||
logger.ContextLogger(ctx).Error("error when get all products", zap.Error(err))
|
||||
return nil, 0, err
|
||||
}
|
||||
|
||||
if err := b.db.Model(&entity.ProductDB{}).Where(query).Count(&total).Error; err != nil {
|
||||
logger.ContextLogger(ctx).Error("error when count products", zap.Error(err))
|
||||
return nil, 0, err
|
||||
}
|
||||
|
||||
return products, int(total), nil
|
||||
}
|
||||
|
||||
func (b *ProductRepository) DeleteProduct(ctx context.Context, id int64) error {
|
||||
product := new(entity.ProductDB)
|
||||
product.ID = id
|
||||
if err := b.db.Delete(product).Error; err != nil {
|
||||
return err
|
||||
}
|
||||
return nil
|
||||
}
|
||||
@@ -0,0 +1,122 @@
|
||||
package repository
|
||||
|
||||
import (
|
||||
"context"
|
||||
"furtuna-be/internal/repository/branches"
|
||||
"furtuna-be/internal/repository/orders"
|
||||
"furtuna-be/internal/repository/oss"
|
||||
"furtuna-be/internal/repository/partners"
|
||||
"furtuna-be/internal/repository/products"
|
||||
"furtuna-be/internal/repository/studios"
|
||||
"furtuna-be/internal/repository/users"
|
||||
|
||||
"github.com/golang-jwt/jwt"
|
||||
"gorm.io/gorm"
|
||||
|
||||
"furtuna-be/config"
|
||||
"furtuna-be/internal/entity"
|
||||
"furtuna-be/internal/repository/auth"
|
||||
"furtuna-be/internal/repository/crypto"
|
||||
event "furtuna-be/internal/repository/events"
|
||||
)
|
||||
|
||||
type RepoManagerImpl struct {
|
||||
Crypto Crypto
|
||||
Auth Auth
|
||||
Event Event
|
||||
User User
|
||||
Branch Branch
|
||||
Studio Studio
|
||||
Product Product
|
||||
Order Order
|
||||
OSS OSSRepository
|
||||
Partner PartnerRepository
|
||||
}
|
||||
|
||||
func NewRepoManagerImpl(db *gorm.DB, cfg *config.Config) *RepoManagerImpl {
|
||||
return &RepoManagerImpl{
|
||||
Crypto: crypto.NewCrypto(cfg.Auth()),
|
||||
Auth: auth.NewAuthRepository(db),
|
||||
Event: event.NewEventRepo(db),
|
||||
User: users.NewUserRepository(db),
|
||||
Branch: branches.NewBranchRepository(db),
|
||||
Studio: studios.NewStudioRepository(db),
|
||||
Product: products.NewProductRepository(db),
|
||||
Order: orders.NewOrderRepository(db),
|
||||
OSS: oss.NewOssRepositoryImpl(cfg.OSSConfig),
|
||||
Partner: partners.NewPartnerRepository(db),
|
||||
}
|
||||
}
|
||||
|
||||
type Auth interface {
|
||||
CheckExistsUserAccount(ctx context.Context, email string) (*entity.UserDB, error)
|
||||
}
|
||||
|
||||
type Event interface {
|
||||
CreateEvent(ctx context.Context, event *entity.EventDB) (*entity.EventDB, error)
|
||||
UpdateEvent(ctx context.Context, event *entity.EventDB) (*entity.EventDB, error)
|
||||
GetEventByID(ctx context.Context, id int64) (*entity.EventDB, error)
|
||||
GetAllEvents(ctx context.Context, nameFilter string, limit, offset int) (entity.EventList, int, error)
|
||||
DeleteEvent(ctx context.Context, id int64) error
|
||||
}
|
||||
|
||||
type Crypto interface {
|
||||
CompareHashAndPassword(hash string, password string) bool
|
||||
ValidateWT(tokenString string) (*jwt.Token, error)
|
||||
GenerateJWT(user *entity.User) (string, error)
|
||||
ParseAndValidateJWT(token string) (*entity.JWTAuthClaims, error)
|
||||
}
|
||||
|
||||
type User interface {
|
||||
Create(ctx context.Context, user *entity.UserDB) (*entity.UserDB, error)
|
||||
GetAllUsers(ctx context.Context, req entity.UserSearch) (entity.UserList, int, error)
|
||||
GetUserByID(ctx context.Context, id int64) (*entity.UserDB, error)
|
||||
GetUserByEmail(ctx context.Context, email string) (*entity.UserDB, error)
|
||||
UpdateUser(ctx context.Context, user *entity.UserDB) (*entity.UserDB, error)
|
||||
}
|
||||
|
||||
type Branch interface {
|
||||
CreateBranch(ctx context.Context, branch *entity.BranchDB) (*entity.BranchDB, error)
|
||||
UpdateBranch(ctx context.Context, branch *entity.BranchDB) (*entity.BranchDB, error)
|
||||
GetBranchByID(ctx context.Context, id int64) (*entity.BranchDB, error)
|
||||
GetAllBranches(ctx context.Context, req entity.BranchSearch) (entity.BranchList, int, error)
|
||||
DeleteBranch(ctx context.Context, id int64) error
|
||||
}
|
||||
|
||||
type Studio interface {
|
||||
CreateStudio(ctx context.Context, studio *entity.StudioDB) (*entity.StudioDB, error)
|
||||
UpdateStudio(ctx context.Context, studio *entity.StudioDB) (*entity.StudioDB, error)
|
||||
GetStudioByID(ctx context.Context, id int64) (*entity.StudioDB, error)
|
||||
SearchStudios(ctx context.Context, req entity.StudioSearch) (entity.StudioList, int, error)
|
||||
}
|
||||
|
||||
type Product interface {
|
||||
CreateProduct(ctx context.Context, product *entity.ProductDB) (*entity.ProductDB, error)
|
||||
UpdateProduct(ctx context.Context, product *entity.ProductDB) (*entity.ProductDB, error)
|
||||
GetProductByID(ctx context.Context, id int64) (*entity.ProductDB, error)
|
||||
GetAllProducts(ctx context.Context, req entity.ProductSearch) (entity.ProductList, int, error)
|
||||
DeleteProduct(ctx context.Context, id int64) error
|
||||
}
|
||||
|
||||
type Order interface {
|
||||
CreateOrder(ctx context.Context, order *entity.OrderDB) (*entity.OrderDB, error)
|
||||
UpdateOrder(ctx context.Context, order *entity.OrderDB) (*entity.OrderDB, error)
|
||||
GetOrderByID(ctx context.Context, id int64) (*entity.OrderDB, error)
|
||||
GetAllOrders(ctx context.Context, req entity.OrderSearch) (entity.OrderList, int, error)
|
||||
GetTotalRevenue(ctx context.Context, req entity.OrderTotalRevenueSearch) (float64, int64, error)
|
||||
GetYearlyRevenue(ctx context.Context, year int) (entity.OrderYearlyRevenueList, error)
|
||||
GetBranchRevenue(ctx context.Context, req entity.OrderBranchRevenueSearch) (entity.OrderBranchRevenueList, error)
|
||||
}
|
||||
|
||||
type OSSRepository interface {
|
||||
UploadFile(ctx context.Context, fileName string, fileContent []byte) (fileUrl string, err error)
|
||||
GetPublicURL(fileName string) string
|
||||
}
|
||||
|
||||
type PartnerRepository interface {
|
||||
Create(ctx context.Context, branch *entity.PartnerDB) (*entity.PartnerDB, error)
|
||||
Update(ctx context.Context, branch *entity.PartnerDB) (*entity.PartnerDB, error)
|
||||
GetByID(ctx context.Context, id int64) (*entity.PartnerDB, error)
|
||||
GetAll(ctx context.Context, req entity.PartnerSearch) (entity.PartnerList, int, error)
|
||||
Delete(ctx context.Context, id int64) error
|
||||
}
|
||||
@@ -0,0 +1,89 @@
|
||||
package studios
|
||||
|
||||
import (
|
||||
"context"
|
||||
"furtuna-be/internal/common/logger"
|
||||
"furtuna-be/internal/entity"
|
||||
|
||||
"go.uber.org/zap"
|
||||
"gorm.io/gorm"
|
||||
)
|
||||
|
||||
type StudioRepository struct {
|
||||
db *gorm.DB
|
||||
}
|
||||
|
||||
func NewStudioRepository(db *gorm.DB) *StudioRepository {
|
||||
return &StudioRepository{
|
||||
db: db,
|
||||
}
|
||||
}
|
||||
|
||||
func (s *StudioRepository) CreateStudio(ctx context.Context, studio *entity.StudioDB) (*entity.StudioDB, error) {
|
||||
err := s.db.Omit("ID").Create(studio).Error
|
||||
if err != nil {
|
||||
logger.ContextLogger(ctx).Error("error when creating studio", zap.Error(err))
|
||||
return nil, err
|
||||
}
|
||||
return studio, nil
|
||||
}
|
||||
|
||||
func (s *StudioRepository) UpdateStudio(ctx context.Context, studio *entity.StudioDB) (*entity.StudioDB, error) {
|
||||
if err := s.db.Save(studio).Error; err != nil {
|
||||
logger.ContextLogger(ctx).Error("error when updating studio", zap.Error(err))
|
||||
return nil, err
|
||||
}
|
||||
return studio, nil
|
||||
}
|
||||
|
||||
func (s *StudioRepository) GetStudioByID(ctx context.Context, id int64) (*entity.StudioDB, error) {
|
||||
studio := new(entity.StudioDB)
|
||||
if err := s.db.First(studio, id).Error; err != nil {
|
||||
logger.ContextLogger(ctx).Error("error when getting studio by ID", zap.Error(err))
|
||||
return nil, err
|
||||
}
|
||||
return studio, nil
|
||||
}
|
||||
|
||||
func (s *StudioRepository) SearchStudios(ctx context.Context, req entity.StudioSearch) (entity.StudioList, int, error) {
|
||||
var studios []*entity.StudioDB
|
||||
var total int64
|
||||
|
||||
query := s.db
|
||||
|
||||
if req.Id > 0 {
|
||||
query = query.Where("id = ?", req.Id)
|
||||
}
|
||||
|
||||
if req.Name != "" {
|
||||
query = query.Where("name ILIKE ?", "%"+req.Name+"%")
|
||||
}
|
||||
|
||||
if req.Status != "" {
|
||||
query = query.Where("status = ?", req.Status)
|
||||
}
|
||||
|
||||
if req.BranchId > 0 {
|
||||
query = query.Where("branch_id = ?", req.BranchId)
|
||||
}
|
||||
|
||||
if req.Limit > 0 {
|
||||
query = query.Limit(req.Limit)
|
||||
}
|
||||
|
||||
if req.Offset > 0 {
|
||||
query = query.Offset(req.Offset)
|
||||
}
|
||||
|
||||
if err := query.Find(&studios).Error; err != nil {
|
||||
logger.ContextLogger(ctx).Error("error when getting all studios", zap.Error(err))
|
||||
return nil, 0, err
|
||||
}
|
||||
|
||||
if err := s.db.Model(&entity.StudioDB{}).Where(query).Count(&total).Error; err != nil {
|
||||
logger.ContextLogger(ctx).Error("error when counting studios", zap.Error(err))
|
||||
return nil, 0, err
|
||||
}
|
||||
|
||||
return studios, int(total), nil
|
||||
}
|
||||
@@ -0,0 +1,166 @@
|
||||
package users
|
||||
|
||||
import (
|
||||
"context"
|
||||
"furtuna-be/internal/common/logger"
|
||||
"furtuna-be/internal/entity"
|
||||
|
||||
"go.uber.org/zap"
|
||||
"gorm.io/gorm"
|
||||
)
|
||||
|
||||
type UserRepository struct {
|
||||
db *gorm.DB
|
||||
}
|
||||
|
||||
func NewUserRepository(db *gorm.DB) *UserRepository {
|
||||
return &UserRepository{
|
||||
db: db,
|
||||
}
|
||||
}
|
||||
|
||||
func (r *UserRepository) Create(ctx context.Context, user *entity.UserDB) (*entity.UserDB, error) {
|
||||
tx := r.db.Begin()
|
||||
|
||||
user.ID = 0
|
||||
if err := tx.Select("name", "email", "password", "status", "created_by", "nik", "user_type", "phone_number").Create(user).Error; err != nil {
|
||||
tx.Rollback()
|
||||
logError(ctx, "creating user", err)
|
||||
return nil, err
|
||||
}
|
||||
|
||||
if err := tx.First(user, user.ID).Error; err != nil {
|
||||
tx.Rollback()
|
||||
logError(ctx, "retrieving user", err)
|
||||
return nil, err
|
||||
}
|
||||
|
||||
userRole := user.ToUserRoleDB()
|
||||
if err := tx.Create(userRole).Error; err != nil {
|
||||
tx.Rollback()
|
||||
logError(ctx, "creating user role", err)
|
||||
return nil, err
|
||||
}
|
||||
|
||||
if err := tx.Commit().Error; err != nil {
|
||||
tx.Rollback()
|
||||
logError(ctx, "committing transaction", err)
|
||||
return nil, err
|
||||
}
|
||||
|
||||
return user, nil
|
||||
}
|
||||
|
||||
func (b *UserRepository) GetAllUsers(ctx context.Context, req entity.UserSearch) (entity.UserList, int, error) {
|
||||
var users []*entity.UserDB
|
||||
var total int64
|
||||
|
||||
query := b.db.Table("users").
|
||||
Select("users.id, users.email, users.name, users.status, users.created_at, users.updated_at, ur.role_id, r.role_name, ur.partner_id, b.name as partner_name").
|
||||
Joins("LEFT JOIN user_roles ur ON users.id = ur.user_id").
|
||||
Joins("LEFT JOIN roles r ON ur.role_id = r.role_id").
|
||||
Joins("LEFT JOIN partners b ON ur.partner_id = b.id").
|
||||
Where("users.deleted_at is null")
|
||||
|
||||
if req.Search != "" {
|
||||
query = query.Where("users.name ILIKE ? or users.email ILIKE ? or r.role_name ILIKE ? or b.name ILIKE ? ", "%"+req.Search+"%", "%"+req.Search+"%", "%"+req.Search+"%", "%"+req.Search+"%")
|
||||
}
|
||||
|
||||
if req.Name != "" {
|
||||
query = query.Where("users.name ILIKE ?", "%"+req.Name+"%")
|
||||
}
|
||||
|
||||
if req.RoleID > 0 {
|
||||
query = query.Where("ur.role_id = ? ", req.RoleID)
|
||||
}
|
||||
|
||||
if req.PartnerID > 0 {
|
||||
query = query.Where("ur.partner_id = ? ", req.PartnerID)
|
||||
}
|
||||
|
||||
// Get the total count without applying the limit and offset.
|
||||
if err := query.Model(&entity.UserDB{}).Count(&total).Error; err != nil {
|
||||
logger.ContextLogger(ctx).Error("error when count users", zap.Error(err))
|
||||
return nil, 0, err
|
||||
}
|
||||
|
||||
// Apply pagination.
|
||||
query = query.Offset(req.Offset).Limit(req.Limit)
|
||||
|
||||
if err := query.Scan(&users).Error; err != nil {
|
||||
logger.ContextLogger(ctx).Error("error when get all users", zap.Error(err))
|
||||
return nil, 0, err
|
||||
}
|
||||
|
||||
return users, int(total), nil
|
||||
}
|
||||
|
||||
func (b *UserRepository) GetUserByID(ctx context.Context, id int64) (*entity.UserDB, error) {
|
||||
var user *entity.UserDB
|
||||
|
||||
query := b.db.Table("users").
|
||||
Select("users.id, users.email, users.name, users.status, users.created_at, users.updated_at, ur.role_id, r.role_name, ur.partner_id, b.name as partner_name").
|
||||
Joins("LEFT JOIN user_roles ur ON users.id = ur.user_id").
|
||||
Joins("LEFT JOIN roles r ON ur.role_id = r.role_id").
|
||||
Joins("LEFT JOIN partners b ON ur.partner_id = b.id").
|
||||
Where("users.id = ?", id)
|
||||
|
||||
if err := query.Scan(&user).Error; err != nil {
|
||||
logger.ContextLogger(ctx).Error("error when get user", zap.Error(err))
|
||||
return nil, err
|
||||
}
|
||||
|
||||
return user, nil
|
||||
}
|
||||
|
||||
func (b *UserRepository) GetUserByEmail(ctx context.Context, email string) (*entity.UserDB, error) {
|
||||
var user *entity.UserDB
|
||||
|
||||
query := b.db.Table("users").
|
||||
Select("users.id, users.email, users.name, users.status, users.created_at, users.updated_at, ur.role_id, r.role_name, ur.partner_id, b.name as partner_name").
|
||||
Joins("LEFT JOIN user_roles ur ON users.id = ur.user_id").
|
||||
Joins("LEFT JOIN roles r ON ur.role_id = r.role_id").
|
||||
Joins("LEFT JOIN partners b ON ur.partner_id = b.id").
|
||||
Where("users.email = ?", email)
|
||||
|
||||
if err := query.Scan(&user).Error; err != nil {
|
||||
logger.ContextLogger(ctx).Error("error when get user", zap.Error(err))
|
||||
return nil, err
|
||||
}
|
||||
|
||||
return user, nil
|
||||
}
|
||||
|
||||
func (r *UserRepository) UpdateUser(ctx context.Context, user *entity.UserDB) (*entity.UserDB, error) {
|
||||
tx := r.db.Begin()
|
||||
defer func() {
|
||||
if r := recover(); r != nil {
|
||||
tx.Rollback()
|
||||
}
|
||||
}()
|
||||
|
||||
if err := tx.Select("name", "email", "password", "status", "deleted_at", "updated_by").Save(user).Error; err != nil {
|
||||
tx.Rollback()
|
||||
logError(ctx, "update user", err)
|
||||
return nil, err
|
||||
}
|
||||
|
||||
userRole := user.ToUserRoleDB()
|
||||
if err := tx.Model(userRole).Where("user_id = ?", user.ID).Updates(userRole).Error; err != nil {
|
||||
tx.Rollback()
|
||||
logError(ctx, "update user role", err)
|
||||
return nil, err
|
||||
}
|
||||
|
||||
if err := tx.Commit().Error; err != nil {
|
||||
tx.Rollback()
|
||||
logError(ctx, "committing transaction", err)
|
||||
return nil, err
|
||||
}
|
||||
|
||||
return user, nil
|
||||
}
|
||||
|
||||
func logError(ctx context.Context, action string, err error) {
|
||||
logger.ContextLogger(ctx).Error("error when "+action, zap.Error(err))
|
||||
}
|
||||
@@ -0,0 +1,60 @@
|
||||
package routes
|
||||
|
||||
import (
|
||||
"furtuna-be/internal/handlers/http/branch"
|
||||
"furtuna-be/internal/handlers/http/order"
|
||||
"furtuna-be/internal/handlers/http/oss"
|
||||
"furtuna-be/internal/handlers/http/partner"
|
||||
"furtuna-be/internal/handlers/http/product"
|
||||
"furtuna-be/internal/handlers/http/studio"
|
||||
"furtuna-be/internal/handlers/http/user"
|
||||
swaggerFiles "github.com/swaggo/files"
|
||||
ginSwagger "github.com/swaggo/gin-swagger"
|
||||
"net/http"
|
||||
|
||||
"furtuna-be/internal/handlers/http/event"
|
||||
"furtuna-be/internal/middlewares"
|
||||
|
||||
"github.com/gin-gonic/gin"
|
||||
|
||||
"furtuna-be/internal/app"
|
||||
"furtuna-be/internal/handlers/http/auth"
|
||||
"furtuna-be/internal/repository"
|
||||
"furtuna-be/internal/services"
|
||||
)
|
||||
|
||||
func RegisterPublicRoutes(app *app.Server, serviceManager *services.ServiceManagerImpl,
|
||||
repoManager *repository.RepoManagerImpl) {
|
||||
route := app.Group("/")
|
||||
route.GET("/", func(c *gin.Context) {
|
||||
c.JSON(http.StatusOK, "HEALTHY")
|
||||
})
|
||||
route.GET("/docs/*any", ginSwagger.WrapHandler(swaggerFiles.Handler))
|
||||
}
|
||||
|
||||
type HTTPHandlerRoutes interface {
|
||||
Route(group *gin.RouterGroup, jwt gin.HandlerFunc)
|
||||
}
|
||||
|
||||
func RegisterPrivateRoutes(app *app.Server, serviceManager *services.ServiceManagerImpl,
|
||||
repoManager *repository.RepoManagerImpl) {
|
||||
approute := app.Group("/api/v1")
|
||||
|
||||
authMiddleware := middlewares.AuthorizationMiddleware(repoManager.Crypto)
|
||||
|
||||
serverRoutes := []HTTPHandlerRoutes{
|
||||
auth.NewAuthHandler(serviceManager.AuthSvc),
|
||||
event.NewHandler(serviceManager.EventSvc),
|
||||
user.NewHandler(serviceManager.UserSvc),
|
||||
branch.NewHandler(serviceManager.BranchSvc),
|
||||
studio.NewStudioHandler(serviceManager.StudioSvc),
|
||||
product.NewHandler(serviceManager.ProductSvc),
|
||||
order.NewHandler(serviceManager.OrderSvc),
|
||||
oss.NewOssHandler(serviceManager.OSSSvc),
|
||||
partner.NewHandler(serviceManager.PartnerSvc),
|
||||
}
|
||||
|
||||
for _, handler := range serverRoutes {
|
||||
handler.Route(approute, authMiddleware)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,48 @@
|
||||
package auth
|
||||
|
||||
import (
|
||||
"context"
|
||||
"furtuna-be/internal/entity"
|
||||
|
||||
"go.uber.org/zap"
|
||||
|
||||
"furtuna-be/internal/common/errors"
|
||||
"furtuna-be/internal/common/logger"
|
||||
"furtuna-be/internal/repository"
|
||||
)
|
||||
|
||||
type AuthServiceImpl struct {
|
||||
authRepo repository.Auth
|
||||
crypto repository.Crypto
|
||||
}
|
||||
|
||||
func New(authRepo repository.Auth, crypto repository.Crypto) *AuthServiceImpl {
|
||||
return &AuthServiceImpl{
|
||||
authRepo: authRepo,
|
||||
crypto: crypto,
|
||||
}
|
||||
}
|
||||
|
||||
func (u *AuthServiceImpl) AuthenticateUser(ctx context.Context, email, password string) (*entity.AuthenticateUser, error) {
|
||||
user, err := u.authRepo.CheckExistsUserAccount(ctx, email)
|
||||
if err != nil {
|
||||
logger.ContextLogger(ctx).Error("error when get user", zap.Error(err))
|
||||
return nil, errors.ErrorInternalServer
|
||||
}
|
||||
|
||||
if user == nil {
|
||||
return nil, errors.ErrorUserIsNotFound
|
||||
}
|
||||
|
||||
if ok := u.crypto.CompareHashAndPassword(user.Password, password); !ok {
|
||||
return nil, errors.ErrorUserInvalidLogin
|
||||
}
|
||||
|
||||
signedToken, err := u.crypto.GenerateJWT(user.ToUser())
|
||||
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
return user.ToUserAuthenticate(signedToken), nil
|
||||
}
|
||||
@@ -0,0 +1,89 @@
|
||||
package branch
|
||||
|
||||
import (
|
||||
"context"
|
||||
"furtuna-be/internal/common/logger"
|
||||
"furtuna-be/internal/common/mycontext"
|
||||
"furtuna-be/internal/entity"
|
||||
"furtuna-be/internal/repository"
|
||||
|
||||
"go.uber.org/zap"
|
||||
)
|
||||
|
||||
type BranchService struct {
|
||||
repo repository.Branch
|
||||
}
|
||||
|
||||
func NewBranchService(repo repository.Branch) *BranchService {
|
||||
return &BranchService{
|
||||
repo: repo,
|
||||
}
|
||||
}
|
||||
|
||||
func (s *BranchService) Create(ctx mycontext.Context, branchReq *entity.Branch) (*entity.Branch, error) {
|
||||
branchDB := branchReq.ToBranchDB()
|
||||
branchDB.CreatedBy = ctx.RequestedBy()
|
||||
|
||||
branchDB, err := s.repo.CreateBranch(ctx, branchDB)
|
||||
if err != nil {
|
||||
logger.ContextLogger(ctx).Error("error when create branch", zap.Error(err))
|
||||
return nil, err
|
||||
}
|
||||
|
||||
return branchDB.ToBranch(), nil
|
||||
}
|
||||
|
||||
func (s *BranchService) Update(ctx mycontext.Context, id int64, branchReq *entity.Branch) (*entity.Branch, error) {
|
||||
existingBranch, err := s.repo.GetBranchByID(ctx, id)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
existingBranch.ToUpdatedBranch(ctx.RequestedBy(), *branchReq)
|
||||
|
||||
updatedBranchDB, err := s.repo.UpdateBranch(ctx, existingBranch.ToBranchDB())
|
||||
if err != nil {
|
||||
logger.ContextLogger(ctx).Error("error when update branch", zap.Error(err))
|
||||
return nil, err
|
||||
}
|
||||
|
||||
return updatedBranchDB.ToBranch(), nil
|
||||
}
|
||||
|
||||
func (s *BranchService) GetByID(ctx context.Context, id int64) (*entity.Branch, error) {
|
||||
branchDB, err := s.repo.GetBranchByID(ctx, id)
|
||||
if err != nil {
|
||||
logger.ContextLogger(ctx).Error("error when get branch by id", zap.Error(err))
|
||||
return nil, err
|
||||
}
|
||||
|
||||
return branchDB.ToBranch(), nil
|
||||
}
|
||||
|
||||
func (s *BranchService) GetAll(ctx context.Context, search entity.BranchSearch) ([]*entity.Branch, int, error) {
|
||||
branches, total, err := s.repo.GetAllBranches(ctx, search)
|
||||
if err != nil {
|
||||
logger.ContextLogger(ctx).Error("error when get all branches", zap.Error(err))
|
||||
return nil, 0, err
|
||||
}
|
||||
|
||||
return branches.ToBranchList(), total, nil
|
||||
}
|
||||
|
||||
func (s *BranchService) Delete(ctx mycontext.Context, id int64) error {
|
||||
branchDB, err := s.repo.GetBranchByID(ctx, id)
|
||||
if err != nil {
|
||||
logger.ContextLogger(ctx).Error("error when get branch by id", zap.Error(err))
|
||||
return err
|
||||
}
|
||||
|
||||
branchDB.SetDeleted(ctx.RequestedBy())
|
||||
|
||||
_, err = s.repo.UpdateBranch(ctx, branchDB)
|
||||
if err != nil {
|
||||
logger.ContextLogger(ctx).Error("error when update branch", zap.Error(err))
|
||||
return err
|
||||
}
|
||||
|
||||
return nil
|
||||
}
|
||||
@@ -0,0 +1,88 @@
|
||||
package event
|
||||
|
||||
import (
|
||||
"context"
|
||||
|
||||
"go.uber.org/zap"
|
||||
|
||||
"furtuna-be/internal/common/logger"
|
||||
"furtuna-be/internal/entity"
|
||||
"furtuna-be/internal/repository"
|
||||
)
|
||||
|
||||
type EventService struct {
|
||||
repo repository.Event
|
||||
}
|
||||
|
||||
func NewEventService(repo repository.Event) *EventService {
|
||||
return &EventService{
|
||||
repo: repo,
|
||||
}
|
||||
}
|
||||
|
||||
func (s *EventService) Create(ctx context.Context, eventReq *entity.Event) (*entity.Event, error) {
|
||||
eventDB := eventReq.ToEventDB()
|
||||
|
||||
eventDB, err := s.repo.CreateEvent(ctx, eventDB)
|
||||
if err != nil {
|
||||
logger.ContextLogger(ctx).Error("error when create event", zap.Error(err))
|
||||
return nil, err
|
||||
}
|
||||
|
||||
return eventDB.ToEvent(), nil
|
||||
}
|
||||
|
||||
func (s *EventService) Update(ctx context.Context, id int64, eventReq *entity.Event) (*entity.Event, error) {
|
||||
existingEvent, err := s.repo.GetEventByID(ctx, id)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
existingEvent.ToUpdatedEvent(*eventReq)
|
||||
|
||||
updatedEventDB, err := s.repo.UpdateEvent(ctx, existingEvent.ToEventDB())
|
||||
if err != nil {
|
||||
logger.ContextLogger(ctx).Error("error when update event", zap.Error(err))
|
||||
return nil, err
|
||||
}
|
||||
|
||||
return updatedEventDB.ToEvent(), nil
|
||||
}
|
||||
|
||||
func (s *EventService) GetByID(ctx context.Context, id int64) (*entity.Event, error) {
|
||||
eventDB, err := s.repo.GetEventByID(ctx, id)
|
||||
if err != nil {
|
||||
logger.ContextLogger(ctx).Error("error when get event by id", zap.Error(err))
|
||||
return nil, err
|
||||
}
|
||||
|
||||
return eventDB.ToEvent(), nil
|
||||
}
|
||||
|
||||
func (s *EventService) GetAll(ctx context.Context, search entity.EventSearch) ([]*entity.Event, int, error) {
|
||||
events, total, err := s.repo.GetAllEvents(ctx, search.Name, search.Limit, search.Offset)
|
||||
if err != nil {
|
||||
logger.ContextLogger(ctx).Error("error when get all events", zap.Error(err))
|
||||
return nil, 0, err
|
||||
}
|
||||
|
||||
return events.ToEventList(), total, nil
|
||||
}
|
||||
|
||||
func (s *EventService) Delete(ctx context.Context, id int64) error {
|
||||
eventDB, err := s.repo.GetEventByID(ctx, id)
|
||||
if err != nil {
|
||||
logger.ContextLogger(ctx).Error("error when get event by id", zap.Error(err))
|
||||
return err
|
||||
}
|
||||
|
||||
eventDB.SetDeleted()
|
||||
|
||||
_, err = s.repo.UpdateEvent(ctx, eventDB)
|
||||
if err != nil {
|
||||
logger.ContextLogger(ctx).Error("error when update event", zap.Error(err))
|
||||
return err
|
||||
}
|
||||
|
||||
return nil
|
||||
}
|
||||
@@ -0,0 +1,147 @@
|
||||
package order
|
||||
|
||||
import (
|
||||
"context"
|
||||
"fmt"
|
||||
"furtuna-be/internal/common/logger"
|
||||
"furtuna-be/internal/common/mycontext"
|
||||
"furtuna-be/internal/constants/order"
|
||||
"furtuna-be/internal/constants/transaction"
|
||||
"furtuna-be/internal/entity"
|
||||
"furtuna-be/internal/repository"
|
||||
|
||||
"go.uber.org/zap"
|
||||
)
|
||||
|
||||
type OrderService struct {
|
||||
repo repository.Order
|
||||
prodRepo repository.Product
|
||||
studioRepo repository.Studio
|
||||
}
|
||||
|
||||
func NewOrderService(repo repository.Order, prodRepo repository.Product, studioRepo repository.Studio) *OrderService {
|
||||
return &OrderService{
|
||||
repo: repo,
|
||||
prodRepo: prodRepo,
|
||||
studioRepo: studioRepo,
|
||||
}
|
||||
}
|
||||
|
||||
func (o *OrderService) Create(ctx mycontext.Context, req *entity.Order) error {
|
||||
|
||||
for i, oi := range req.OrderItem {
|
||||
if oi.ItemType.IsProduct() {
|
||||
item, err := o.prodRepo.GetProductByID(ctx, oi.ItemID)
|
||||
if err != nil {
|
||||
logger.ContextLogger(ctx).Error("error when get product item", zap.Error(err))
|
||||
return err
|
||||
}
|
||||
|
||||
req.OrderItem[i].Price = item.Price
|
||||
req.OrderItem[i].CreatedBy = ctx.RequestedBy()
|
||||
} else if oi.ItemType.IsStudio() {
|
||||
//get data studio
|
||||
item, err := o.studioRepo.GetStudioByID(ctx, oi.ItemID)
|
||||
if err != nil {
|
||||
logger.ContextLogger(ctx).Error("error when get studio item", zap.Error(err))
|
||||
return err
|
||||
}
|
||||
|
||||
req.OrderItem[i].Price = item.Price
|
||||
req.OrderItem[i].CreatedBy = ctx.RequestedBy()
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
orderDB := req.ToOrderDB()
|
||||
orderDB.CreatedBy = ctx.RequestedBy()
|
||||
orderDB.Transaction.CreatedBy = ctx.RequestedBy()
|
||||
|
||||
//set status
|
||||
orderDB.Status = order.Paid
|
||||
orderDB.Transaction.Status = transaction.Paid
|
||||
|
||||
orderDB, err := o.repo.CreateOrder(ctx, orderDB)
|
||||
if err != nil {
|
||||
logger.ContextLogger(ctx).Error("error when create order", zap.Error(err))
|
||||
return err
|
||||
}
|
||||
|
||||
return nil
|
||||
}
|
||||
|
||||
func (s *OrderService) GetByID(ctx context.Context, id int64) (*entity.Order, error) {
|
||||
orderDB, err := s.repo.GetOrderByID(ctx, id)
|
||||
if err != nil {
|
||||
logger.ContextLogger(ctx).Error("error when get order by id", zap.Error(err))
|
||||
return nil, err
|
||||
}
|
||||
|
||||
return orderDB.ToOrder(), nil
|
||||
}
|
||||
|
||||
func (s *OrderService) GetAll(ctx context.Context, search entity.OrderSearch) ([]*entity.Order, int, error) {
|
||||
orders, total, err := s.repo.GetAllOrders(ctx, search)
|
||||
if err != nil {
|
||||
logger.ContextLogger(ctx).Error("error when get all orders", zap.Error(err))
|
||||
return nil, 0, err
|
||||
}
|
||||
|
||||
return orders.ToOrderList(), total, nil
|
||||
}
|
||||
|
||||
func (s *OrderService) GetTotalRevenue(ctx context.Context, search entity.OrderTotalRevenueSearch) (float64, int64, error) {
|
||||
rev, trans, err := s.repo.GetTotalRevenue(ctx, search)
|
||||
if err != nil {
|
||||
logger.ContextLogger(ctx).Error("error when get total revenue orders", zap.Error(err))
|
||||
return 0, 0, err
|
||||
}
|
||||
|
||||
return rev, trans, nil
|
||||
}
|
||||
|
||||
func (s *OrderService) GetYearlyRevenue(ctx context.Context, year int) (entity.OrderYearlyRevenueList, error) {
|
||||
result, err := s.repo.GetYearlyRevenue(ctx, year)
|
||||
if err != nil {
|
||||
logger.ContextLogger(ctx).Error("error when get yearly revenue orders", zap.Error(err))
|
||||
return nil, err
|
||||
}
|
||||
|
||||
return result, nil
|
||||
}
|
||||
|
||||
func (s *OrderService) GetBranchRevenue(ctx context.Context, req entity.OrderBranchRevenueSearch) (entity.OrderBranchRevenueList, error) {
|
||||
result, err := s.repo.GetBranchRevenue(ctx, req)
|
||||
if err != nil {
|
||||
logger.ContextLogger(ctx).Error("error when get branch revenue orders", zap.Error(err))
|
||||
return nil, err
|
||||
}
|
||||
|
||||
return result, nil
|
||||
}
|
||||
|
||||
func (s *OrderService) UpdateStatus(ctx mycontext.Context, id int64, orderReq *entity.Order) (*entity.Order, error) {
|
||||
existingOrder, err := s.repo.GetOrderByID(ctx, id)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
//validate state
|
||||
if !existingOrder.Status.IsNew() {
|
||||
return nil, fmt.Errorf("Invalid order status")
|
||||
}
|
||||
|
||||
if existingOrder.Status == orderReq.Status {
|
||||
return nil, fmt.Errorf("Order status already %s", existingOrder.Status)
|
||||
}
|
||||
|
||||
existingOrder.ToUpdatedOrder(ctx.RequestedBy(), *orderReq)
|
||||
|
||||
_, err = s.repo.UpdateOrder(ctx, existingOrder)
|
||||
if err != nil {
|
||||
logger.ContextLogger(ctx).Error("error when update user", zap.Error(err))
|
||||
return nil, err
|
||||
}
|
||||
|
||||
return existingOrder.ToOrder(), nil
|
||||
}
|
||||
@@ -0,0 +1,45 @@
|
||||
package oss
|
||||
|
||||
import (
|
||||
"context"
|
||||
"fmt"
|
||||
"furtuna-be/internal/entity"
|
||||
"furtuna-be/internal/utils/generator"
|
||||
"path"
|
||||
|
||||
"github.com/go-playground/validator/v10"
|
||||
)
|
||||
|
||||
func (s *OssService) UploadFile(ctx context.Context, req *entity.UploadFileRequest) (*entity.UploadFileResponse, error) {
|
||||
file := req.FileHeader
|
||||
req.FileSize = file.Size
|
||||
req.Ext = path.Ext(file.Filename)
|
||||
validate := validator.New()
|
||||
if err := validate.Struct(req); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
// Open the file and read its content
|
||||
srcFile, err := file.Open()
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
defer srcFile.Close()
|
||||
|
||||
fileContent := make([]byte, file.Size)
|
||||
_, err = srcFile.Read(fileContent)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
filePath := fmt.Sprintf("%v/%v%v", req.FolderName, generator.GenerateFileName(), req.Ext)
|
||||
fileUrl, err := s.ossRepo.UploadFile(ctx, filePath, fileContent)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
return &entity.UploadFileResponse{
|
||||
FilePath: filePath,
|
||||
FileUrl: fileUrl,
|
||||
}, nil
|
||||
}
|
||||
@@ -0,0 +1,13 @@
|
||||
package oss
|
||||
|
||||
import "furtuna-be/internal/repository"
|
||||
|
||||
type OssService struct {
|
||||
ossRepo repository.OSSRepository
|
||||
}
|
||||
|
||||
func NewOSSService(ossRepo repository.OSSRepository) *OssService {
|
||||
return &OssService{
|
||||
ossRepo: ossRepo,
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,89 @@
|
||||
package partner
|
||||
|
||||
import (
|
||||
"context"
|
||||
"furtuna-be/internal/common/logger"
|
||||
"furtuna-be/internal/common/mycontext"
|
||||
"furtuna-be/internal/entity"
|
||||
"furtuna-be/internal/repository"
|
||||
|
||||
"go.uber.org/zap"
|
||||
)
|
||||
|
||||
type PartnerService struct {
|
||||
repo repository.PartnerRepository
|
||||
}
|
||||
|
||||
func NewPartnerService(repo repository.PartnerRepository) *PartnerService {
|
||||
return &PartnerService{
|
||||
repo: repo,
|
||||
}
|
||||
}
|
||||
|
||||
func (s *PartnerService) Create(ctx mycontext.Context, PartnerReq *entity.Partner) (*entity.Partner, error) {
|
||||
PartnerDB := PartnerReq.ToPartnerDB()
|
||||
PartnerDB.CreatedBy = ctx.RequestedBy()
|
||||
|
||||
PartnerDB, err := s.repo.Create(ctx, PartnerDB)
|
||||
if err != nil {
|
||||
logger.ContextLogger(ctx).Error("error when create Partner", zap.Error(err))
|
||||
return nil, err
|
||||
}
|
||||
|
||||
return PartnerDB.ToPartner(), nil
|
||||
}
|
||||
|
||||
func (s *PartnerService) Update(ctx mycontext.Context, id int64, PartnerReq *entity.Partner) (*entity.Partner, error) {
|
||||
existingPartner, err := s.repo.GetByID(ctx, id)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
existingPartner.ToUpdatedPartner(ctx.RequestedBy(), *PartnerReq)
|
||||
|
||||
updatedPartnerDB, err := s.repo.Update(ctx, existingPartner.ToPartnerDB())
|
||||
if err != nil {
|
||||
logger.ContextLogger(ctx).Error("error when update Partner", zap.Error(err))
|
||||
return nil, err
|
||||
}
|
||||
|
||||
return updatedPartnerDB.ToPartner(), nil
|
||||
}
|
||||
|
||||
func (s *PartnerService) GetByID(ctx context.Context, id int64) (*entity.Partner, error) {
|
||||
PartnerDB, err := s.repo.GetByID(ctx, id)
|
||||
if err != nil {
|
||||
logger.ContextLogger(ctx).Error("error when get Partner by id", zap.Error(err))
|
||||
return nil, err
|
||||
}
|
||||
|
||||
return PartnerDB.ToPartner(), nil
|
||||
}
|
||||
|
||||
func (s *PartnerService) GetAll(ctx context.Context, search entity.PartnerSearch) ([]*entity.Partner, int, error) {
|
||||
Partneres, total, err := s.repo.GetAll(ctx, search)
|
||||
if err != nil {
|
||||
logger.ContextLogger(ctx).Error("error when get all Partneres", zap.Error(err))
|
||||
return nil, 0, err
|
||||
}
|
||||
|
||||
return Partneres.ToPartnerList(), total, nil
|
||||
}
|
||||
|
||||
func (s *PartnerService) Delete(ctx mycontext.Context, id int64) error {
|
||||
PartnerDB, err := s.repo.GetByID(ctx, id)
|
||||
if err != nil {
|
||||
logger.ContextLogger(ctx).Error("error when get Partner by id", zap.Error(err))
|
||||
return err
|
||||
}
|
||||
|
||||
PartnerDB.SetDeleted(ctx.RequestedBy())
|
||||
|
||||
_, err = s.repo.Update(ctx, PartnerDB)
|
||||
if err != nil {
|
||||
logger.ContextLogger(ctx).Error("error when update Partner", zap.Error(err))
|
||||
return err
|
||||
}
|
||||
|
||||
return nil
|
||||
}
|
||||
@@ -0,0 +1,89 @@
|
||||
package product
|
||||
|
||||
import (
|
||||
"context"
|
||||
"furtuna-be/internal/common/logger"
|
||||
"furtuna-be/internal/common/mycontext"
|
||||
"furtuna-be/internal/entity"
|
||||
"furtuna-be/internal/repository"
|
||||
|
||||
"go.uber.org/zap"
|
||||
)
|
||||
|
||||
type ProductService struct {
|
||||
repo repository.Product
|
||||
}
|
||||
|
||||
func NewProductService(repo repository.Product) *ProductService {
|
||||
return &ProductService{
|
||||
repo: repo,
|
||||
}
|
||||
}
|
||||
|
||||
func (s *ProductService) Create(ctx mycontext.Context, productReq *entity.Product) (*entity.Product, error) {
|
||||
productDB := productReq.ToProductDB()
|
||||
productDB.CreatedBy = ctx.RequestedBy()
|
||||
|
||||
productDB, err := s.repo.CreateProduct(ctx, productDB)
|
||||
if err != nil {
|
||||
logger.ContextLogger(ctx).Error("error when create product", zap.Error(err))
|
||||
return nil, err
|
||||
}
|
||||
|
||||
return productDB.ToProduct(), nil
|
||||
}
|
||||
|
||||
func (s *ProductService) Update(ctx mycontext.Context, id int64, productReq *entity.Product) (*entity.Product, error) {
|
||||
existingProduct, err := s.repo.GetProductByID(ctx, id)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
existingProduct.ToUpdatedProduct(ctx.RequestedBy(), *productReq)
|
||||
|
||||
updatedProductDB, err := s.repo.UpdateProduct(ctx, existingProduct.ToProductDB())
|
||||
if err != nil {
|
||||
logger.ContextLogger(ctx).Error("error when update product", zap.Error(err))
|
||||
return nil, err
|
||||
}
|
||||
|
||||
return updatedProductDB.ToProduct(), nil
|
||||
}
|
||||
|
||||
func (s *ProductService) GetByID(ctx context.Context, id int64) (*entity.Product, error) {
|
||||
productDB, err := s.repo.GetProductByID(ctx, id)
|
||||
if err != nil {
|
||||
logger.ContextLogger(ctx).Error("error when get product by id", zap.Error(err))
|
||||
return nil, err
|
||||
}
|
||||
|
||||
return productDB.ToProduct(), nil
|
||||
}
|
||||
|
||||
func (s *ProductService) GetAll(ctx context.Context, search entity.ProductSearch) ([]*entity.Product, int, error) {
|
||||
products, total, err := s.repo.GetAllProducts(ctx, search)
|
||||
if err != nil {
|
||||
logger.ContextLogger(ctx).Error("error when get all products", zap.Error(err))
|
||||
return nil, 0, err
|
||||
}
|
||||
|
||||
return products.ToProductList(), total, nil
|
||||
}
|
||||
|
||||
func (s *ProductService) Delete(ctx mycontext.Context, id int64) error {
|
||||
productDB, err := s.repo.GetProductByID(ctx, id)
|
||||
if err != nil {
|
||||
logger.ContextLogger(ctx).Error("error when get product by id", zap.Error(err))
|
||||
return err
|
||||
}
|
||||
|
||||
productDB.SetDeleted(ctx.RequestedBy())
|
||||
|
||||
_, err = s.repo.UpdateProduct(ctx, productDB)
|
||||
if err != nil {
|
||||
logger.ContextLogger(ctx).Error("error when update product", zap.Error(err))
|
||||
return err
|
||||
}
|
||||
|
||||
return nil
|
||||
}
|
||||
@@ -0,0 +1,110 @@
|
||||
package services
|
||||
|
||||
import (
|
||||
"context"
|
||||
"furtuna-be/internal/common/mycontext"
|
||||
"furtuna-be/internal/services/branch"
|
||||
"furtuna-be/internal/services/order"
|
||||
"furtuna-be/internal/services/oss"
|
||||
"furtuna-be/internal/services/partner"
|
||||
"furtuna-be/internal/services/product"
|
||||
"furtuna-be/internal/services/studio"
|
||||
"furtuna-be/internal/services/users"
|
||||
|
||||
"furtuna-be/config"
|
||||
"furtuna-be/internal/entity"
|
||||
"furtuna-be/internal/repository"
|
||||
"furtuna-be/internal/services/auth"
|
||||
"furtuna-be/internal/services/event"
|
||||
)
|
||||
|
||||
type ServiceManagerImpl struct {
|
||||
AuthSvc Auth
|
||||
EventSvc Event
|
||||
UserSvc User
|
||||
BranchSvc Branch
|
||||
StudioSvc Studio
|
||||
ProductSvc Product
|
||||
OrderSvc Order
|
||||
OSSSvc OSSService
|
||||
PartnerSvc Partner
|
||||
}
|
||||
|
||||
func NewServiceManagerImpl(cfg *config.Config, repo *repository.RepoManagerImpl) *ServiceManagerImpl {
|
||||
return &ServiceManagerImpl{
|
||||
AuthSvc: auth.New(repo.Auth, repo.Crypto),
|
||||
EventSvc: event.NewEventService(repo.Event),
|
||||
UserSvc: users.NewUserService(repo.User, repo.Branch),
|
||||
BranchSvc: branch.NewBranchService(repo.Branch),
|
||||
StudioSvc: studio.NewStudioService(repo.Studio),
|
||||
ProductSvc: product.NewProductService(repo.Product),
|
||||
OrderSvc: order.NewOrderService(repo.Order, repo.Product, repo.Studio),
|
||||
OSSSvc: oss.NewOSSService(repo.OSS),
|
||||
PartnerSvc: partner.NewPartnerService(repo.Partner),
|
||||
}
|
||||
}
|
||||
|
||||
type Auth interface {
|
||||
AuthenticateUser(ctx context.Context, email, password string) (*entity.AuthenticateUser, error)
|
||||
}
|
||||
|
||||
type Event interface {
|
||||
Create(ctx context.Context, eventReq *entity.Event) (*entity.Event, error)
|
||||
Update(ctx context.Context, id int64, eventReq *entity.Event) (*entity.Event, error)
|
||||
GetByID(ctx context.Context, id int64) (*entity.Event, error)
|
||||
GetAll(ctx context.Context, search entity.EventSearch) ([]*entity.Event, int, error)
|
||||
Delete(ctx context.Context, id int64) error
|
||||
}
|
||||
|
||||
type User interface {
|
||||
Create(ctx mycontext.Context, userReq *entity.User) (*entity.User, error)
|
||||
GetAll(ctx mycontext.Context, search entity.UserSearch) ([]*entity.User, int, error)
|
||||
Update(ctx mycontext.Context, id int64, userReq *entity.User) (*entity.User, error)
|
||||
GetByID(ctx mycontext.Context, id int64) (*entity.User, error)
|
||||
Delete(ctx mycontext.Context, id int64) error
|
||||
}
|
||||
|
||||
type Branch interface {
|
||||
Create(ctx mycontext.Context, branchReq *entity.Branch) (*entity.Branch, error)
|
||||
Update(ctx mycontext.Context, id int64, branchReq *entity.Branch) (*entity.Branch, error)
|
||||
GetByID(ctx context.Context, id int64) (*entity.Branch, error)
|
||||
GetAll(ctx context.Context, search entity.BranchSearch) ([]*entity.Branch, int, error)
|
||||
Delete(ctx mycontext.Context, id int64) error
|
||||
}
|
||||
|
||||
type Studio interface {
|
||||
Create(ctx mycontext.Context, studioReq *entity.Studio) (*entity.Studio, error)
|
||||
Update(ctx mycontext.Context, id int64, studioReq *entity.Studio) (*entity.Studio, error)
|
||||
GetByID(ctx context.Context, id int64) (*entity.Studio, error)
|
||||
Search(ctx context.Context, search entity.StudioSearch) ([]*entity.Studio, int, error)
|
||||
}
|
||||
|
||||
type Product interface {
|
||||
Create(ctx mycontext.Context, productReq *entity.Product) (*entity.Product, error)
|
||||
Update(ctx mycontext.Context, id int64, productReq *entity.Product) (*entity.Product, error)
|
||||
GetByID(ctx context.Context, id int64) (*entity.Product, error)
|
||||
GetAll(ctx context.Context, search entity.ProductSearch) ([]*entity.Product, int, error)
|
||||
Delete(ctx mycontext.Context, id int64) error
|
||||
}
|
||||
|
||||
type Order interface {
|
||||
Create(ctx mycontext.Context, req *entity.Order) error
|
||||
UpdateStatus(ctx mycontext.Context, id int64, orderReq *entity.Order) (*entity.Order, error)
|
||||
GetByID(ctx context.Context, id int64) (*entity.Order, error)
|
||||
GetAll(ctx context.Context, search entity.OrderSearch) ([]*entity.Order, int, error)
|
||||
GetTotalRevenue(ctx context.Context, search entity.OrderTotalRevenueSearch) (float64, int64, error)
|
||||
GetYearlyRevenue(ctx context.Context, year int) (entity.OrderYearlyRevenueList, error)
|
||||
GetBranchRevenue(ctx context.Context, req entity.OrderBranchRevenueSearch) (entity.OrderBranchRevenueList, error)
|
||||
}
|
||||
|
||||
type OSSService interface {
|
||||
UploadFile(ctx context.Context, req *entity.UploadFileRequest) (*entity.UploadFileResponse, error)
|
||||
}
|
||||
|
||||
type Partner interface {
|
||||
Create(ctx mycontext.Context, branchReq *entity.Partner) (*entity.Partner, error)
|
||||
Update(ctx mycontext.Context, id int64, branchReq *entity.Partner) (*entity.Partner, error)
|
||||
GetByID(ctx context.Context, id int64) (*entity.Partner, error)
|
||||
GetAll(ctx context.Context, search entity.PartnerSearch) ([]*entity.Partner, int, error)
|
||||
Delete(ctx mycontext.Context, id int64) error
|
||||
}
|
||||
@@ -0,0 +1,70 @@
|
||||
package studio
|
||||
|
||||
import (
|
||||
"context"
|
||||
"furtuna-be/internal/common/logger"
|
||||
"furtuna-be/internal/common/mycontext"
|
||||
"furtuna-be/internal/entity"
|
||||
"furtuna-be/internal/repository"
|
||||
"go.uber.org/zap"
|
||||
)
|
||||
|
||||
type StudioService struct {
|
||||
repo repository.Studio
|
||||
}
|
||||
|
||||
func NewStudioService(repo repository.Studio) *StudioService {
|
||||
return &StudioService{
|
||||
repo: repo,
|
||||
}
|
||||
}
|
||||
|
||||
func (s *StudioService) Create(ctx mycontext.Context, studioReq *entity.Studio) (*entity.Studio, error) {
|
||||
newStudioDB := studioReq.NewStudiosDB()
|
||||
newStudioDB.CreatedBy = ctx.RequestedBy()
|
||||
|
||||
newStudioDB, err := s.repo.CreateStudio(ctx, newStudioDB)
|
||||
if err != nil {
|
||||
logger.ContextLogger(ctx).Error("error when creating studio", zap.Error(err))
|
||||
return nil, err
|
||||
}
|
||||
|
||||
return newStudioDB.ToStudio(), nil
|
||||
}
|
||||
|
||||
func (s *StudioService) Update(ctx mycontext.Context, id int64, studioReq *entity.Studio) (*entity.Studio, error) {
|
||||
existingStudio, err := s.repo.GetStudioByID(ctx, id)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
existingStudio.ToUpdatedStudio(ctx.RequestedBy(), *studioReq)
|
||||
|
||||
updatedStudioDB, err := s.repo.UpdateStudio(ctx, existingStudio.ToStudioDB())
|
||||
if err != nil {
|
||||
logger.ContextLogger(ctx).Error("error when updating studio", zap.Error(err))
|
||||
return nil, err
|
||||
}
|
||||
|
||||
return updatedStudioDB.ToStudio(), nil
|
||||
}
|
||||
|
||||
func (s *StudioService) GetByID(ctx context.Context, id int64) (*entity.Studio, error) {
|
||||
studioDB, err := s.repo.GetStudioByID(ctx, id)
|
||||
if err != nil {
|
||||
logger.ContextLogger(ctx).Error("error when getting studio by id", zap.Error(err))
|
||||
return nil, err
|
||||
}
|
||||
|
||||
return studioDB.ToStudio(), nil
|
||||
}
|
||||
|
||||
func (s *StudioService) Search(ctx context.Context, search entity.StudioSearch) ([]*entity.Studio, int, error) {
|
||||
studios, total, err := s.repo.SearchStudios(ctx, search)
|
||||
if err != nil {
|
||||
logger.ContextLogger(ctx).Error("error when getting all studios", zap.Error(err))
|
||||
return nil, 0, err
|
||||
}
|
||||
|
||||
return studios.ToStudioList(), total, nil
|
||||
}
|
||||
@@ -0,0 +1,118 @@
|
||||
package users
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"furtuna-be/internal/common/mycontext"
|
||||
|
||||
"go.uber.org/zap"
|
||||
|
||||
"furtuna-be/internal/common/logger"
|
||||
"furtuna-be/internal/entity"
|
||||
"furtuna-be/internal/repository"
|
||||
)
|
||||
|
||||
type UserService struct {
|
||||
repo repository.User
|
||||
branchRepo repository.Branch
|
||||
}
|
||||
|
||||
func NewUserService(repo repository.User, branchRepo repository.Branch) *UserService {
|
||||
return &UserService{
|
||||
repo: repo,
|
||||
branchRepo: branchRepo,
|
||||
}
|
||||
}
|
||||
|
||||
func (s *UserService) Create(ctx mycontext.Context, userReq *entity.User) (*entity.User, error) {
|
||||
//check
|
||||
userExist, err := s.repo.GetUserByEmail(ctx, userReq.Email)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
if userExist != nil {
|
||||
return nil, fmt.Errorf("Email already exist")
|
||||
}
|
||||
|
||||
userDB, err := userReq.ToUserDB(ctx.RequestedBy())
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
userDB, err = s.repo.Create(ctx, userDB)
|
||||
if err != nil {
|
||||
logger.ContextLogger(ctx).Error("error when create user", zap.Error(err))
|
||||
return nil, err
|
||||
}
|
||||
|
||||
return userDB.ToUser(), nil
|
||||
}
|
||||
|
||||
func (s *UserService) GetAll(ctx mycontext.Context, search entity.UserSearch) ([]*entity.User, int, error) {
|
||||
|
||||
users, total, err := s.repo.GetAllUsers(ctx, search)
|
||||
if err != nil {
|
||||
logger.ContextLogger(ctx).Error("error when get all users", zap.Error(err))
|
||||
return nil, 0, err
|
||||
}
|
||||
|
||||
return users.ToUserList(), total, nil
|
||||
}
|
||||
|
||||
func (s *UserService) GetByID(ctx mycontext.Context, id int64) (*entity.User, error) {
|
||||
userDB, err := s.repo.GetUserByID(ctx, id)
|
||||
if err != nil {
|
||||
logger.ContextLogger(ctx).Error("error when get user by id", zap.Error(err))
|
||||
return nil, err
|
||||
}
|
||||
|
||||
return userDB.ToUser(), nil
|
||||
}
|
||||
|
||||
func (s *UserService) Update(ctx mycontext.Context, id int64, userReq *entity.User) (*entity.User, error) {
|
||||
existingUser, err := s.repo.GetUserByID(ctx, id)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
//if changed branch
|
||||
if *userReq.PartnerID > 0 {
|
||||
branch, err := s.branchRepo.GetBranchByID(ctx, *userReq.PartnerID)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
existingUser.BranchName = branch.Name
|
||||
}
|
||||
|
||||
err = existingUser.ToUpdatedUser(*userReq)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
updatedUserDB, err := s.repo.UpdateUser(ctx, existingUser)
|
||||
if err != nil {
|
||||
logger.ContextLogger(ctx).Error("error when update user", zap.Error(err))
|
||||
return nil, err
|
||||
}
|
||||
|
||||
return updatedUserDB.ToUser(), nil
|
||||
}
|
||||
|
||||
func (s *UserService) Delete(ctx mycontext.Context, id int64) error {
|
||||
userDB, err := s.repo.GetUserByID(ctx, id)
|
||||
if err != nil {
|
||||
logger.ContextLogger(ctx).Error("error when get user by id", zap.Error(err))
|
||||
return err
|
||||
}
|
||||
|
||||
userDB.SetDeleted(ctx.RequestedBy())
|
||||
|
||||
_, err = s.repo.UpdateUser(ctx, userDB)
|
||||
if err != nil {
|
||||
logger.ContextLogger(ctx).Error("error when update user", zap.Error(err))
|
||||
return err
|
||||
}
|
||||
|
||||
return nil
|
||||
}
|
||||
@@ -0,0 +1,20 @@
|
||||
package utils
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"strings"
|
||||
)
|
||||
|
||||
func ArrayToString(a []int64, delim string) string {
|
||||
return strings.Trim(strings.Replace(fmt.Sprint(a), " ", delim, -1), "[]")
|
||||
}
|
||||
|
||||
func Contains(slice []string, item string) bool {
|
||||
set := make(map[string]struct{}, len(slice))
|
||||
for _, s := range slice {
|
||||
set[s] = struct{}{}
|
||||
}
|
||||
|
||||
_, ok := set[item]
|
||||
return ok
|
||||
}
|
||||
@@ -0,0 +1,43 @@
|
||||
package utils
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"math/rand"
|
||||
"strconv"
|
||||
"strings"
|
||||
"time"
|
||||
)
|
||||
|
||||
func FormatCurrency(value float64) string {
|
||||
currencyStr := strconv.FormatFloat(value, 'f', 2, 64)
|
||||
split := strings.Split(currencyStr, ".")
|
||||
n := len(split[0])
|
||||
if n <= 3 {
|
||||
return fmt.Sprintf("Rp %s,%s", split[0], split[1])
|
||||
}
|
||||
var result []string
|
||||
for i := 0; i < n; i += 3 {
|
||||
end := n - i
|
||||
start := end - 3
|
||||
if start < 0 {
|
||||
start = 0
|
||||
}
|
||||
result = append([]string{split[0][start:end]}, result...)
|
||||
}
|
||||
currencyStr = strings.Join(result, ".")
|
||||
return fmt.Sprintf("Rp %s,%s", currencyStr, split[1])
|
||||
}
|
||||
|
||||
const charset = "abcdefghijklmnopqrstuvwxyz" +
|
||||
"ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789"
|
||||
|
||||
var seededRand *rand.Rand = rand.New(
|
||||
rand.NewSource(time.Now().UnixNano()))
|
||||
|
||||
func GenerateRandomString(length int) string {
|
||||
b := make([]byte, length)
|
||||
for i := range b {
|
||||
b[i] = charset[seededRand.Intn(len(charset))]
|
||||
}
|
||||
return string(b)
|
||||
}
|
||||
@@ -0,0 +1,36 @@
|
||||
package utils
|
||||
|
||||
import "testing"
|
||||
|
||||
func TestFormatCurrency(t *testing.T) {
|
||||
type args struct {
|
||||
value float64
|
||||
}
|
||||
tests := []struct {
|
||||
name string
|
||||
args args
|
||||
want string
|
||||
}{
|
||||
{
|
||||
name: "hundred",
|
||||
args: args{
|
||||
value: 626000,
|
||||
},
|
||||
want: "Rp 626.000,00",
|
||||
},
|
||||
{
|
||||
name: "million",
|
||||
args: args{
|
||||
value: 62603300,
|
||||
},
|
||||
want: "Rp 62.603.300,00",
|
||||
},
|
||||
}
|
||||
for _, tt := range tests {
|
||||
t.Run(tt.name, func(t *testing.T) {
|
||||
if got := FormatCurrency(tt.args.value); got != tt.want {
|
||||
t.Errorf("FormatCurrency() = %v, want %v", got, tt.want)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,36 @@
|
||||
package generator
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"math/rand"
|
||||
"strconv"
|
||||
"time"
|
||||
|
||||
"github.com/google/uuid"
|
||||
)
|
||||
|
||||
func MedicalRecordNumberRand() string {
|
||||
return RandStringRunes(10)
|
||||
}
|
||||
|
||||
func RandStringRunes(n int) string {
|
||||
rand.Seed(time.Now().UnixNano()) // seed the random number generator
|
||||
|
||||
const letterBytes = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ"
|
||||
b := make([]byte, n)
|
||||
for i := range b {
|
||||
b[i] = letterBytes[rand.Intn(len(letterBytes))]
|
||||
}
|
||||
|
||||
return string(b)
|
||||
}
|
||||
|
||||
// format -> <uuid>-<time unix>
|
||||
func GenerateFileName() string {
|
||||
return fmt.Sprintf("%v-%v", GenerateUUID(), strconv.Itoa(int(time.Now().Unix())))
|
||||
}
|
||||
|
||||
func GenerateUUID() string {
|
||||
id := uuid.New()
|
||||
return id.String()
|
||||
}
|
||||
Reference in New Issue
Block a user