2023-03-05 23:35:41 +07:00
|
|
|
package db
|
|
|
|
|
|
|
|
import (
|
|
|
|
"context"
|
|
|
|
"database/sql"
|
|
|
|
"fmt"
|
|
|
|
)
|
|
|
|
|
2023-03-12 11:01:43 +07:00
|
|
|
type Store interface {
|
|
|
|
Querier
|
|
|
|
PurchaseOrderTx(ctx context.Context, arg PurchasoOrderTxParams) (PurchaseOrderTxResult, error)
|
2023-03-13 09:24:59 +07:00
|
|
|
CreateUserMerchantTx(ctx context.Context, arg UserMerchantTxParams) (UserMerchantTxResult, error)
|
2023-03-22 12:06:09 +07:00
|
|
|
SaleOrderTx(ctx context.Context, arg SaleOrderTxParams) (SaleOrderTxResult, error)
|
2023-03-12 11:01:43 +07:00
|
|
|
}
|
|
|
|
|
|
|
|
type SQLStore struct {
|
2023-03-05 23:35:41 +07:00
|
|
|
*Queries
|
|
|
|
db *sql.DB
|
|
|
|
}
|
|
|
|
|
2023-03-12 11:01:43 +07:00
|
|
|
func NewStore(db *sql.DB) Store {
|
|
|
|
return &SQLStore{
|
2023-03-05 23:35:41 +07:00
|
|
|
db: db,
|
|
|
|
Queries: New(db),
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2023-03-12 11:01:43 +07:00
|
|
|
func (store *SQLStore) execTx(ctx context.Context, fn func(*Queries) error) error {
|
2023-03-05 23:35:41 +07:00
|
|
|
tx, err := store.db.BeginTx(ctx, nil)
|
|
|
|
if err != nil {
|
|
|
|
return err
|
|
|
|
}
|
|
|
|
|
|
|
|
q := New(tx)
|
|
|
|
err = fn(q)
|
|
|
|
if err != nil {
|
|
|
|
if rbErr := tx.Rollback(); rbErr != nil {
|
|
|
|
return fmt.Errorf("tx err: %v, rb err : %v", err, rbErr)
|
|
|
|
}
|
|
|
|
return err
|
|
|
|
}
|
|
|
|
|
|
|
|
return tx.Commit()
|
|
|
|
|
|
|
|
}
|
|
|
|
|
2023-03-13 09:24:59 +07:00
|
|
|
type UserMerchantTxParams struct {
|
|
|
|
Email string `json:"email"`
|
|
|
|
Fullname string `json:"fullname"`
|
|
|
|
Password string `json:"password"`
|
|
|
|
OutletName string `json:"outlet_name"`
|
|
|
|
}
|
|
|
|
|
|
|
|
type UserMerchantTxResult struct {
|
|
|
|
OwnerProfile User `json:"owner_profile"`
|
|
|
|
OutletProfile Merchant `json:"outlet_profile"`
|
|
|
|
}
|
|
|
|
|
|
|
|
func (store *SQLStore) CreateUserMerchantTx(ctx context.Context, arg UserMerchantTxParams) (UserMerchantTxResult, error) {
|
|
|
|
var result UserMerchantTxResult
|
|
|
|
err := store.execTx(ctx, func(q *Queries) error {
|
|
|
|
var err error
|
|
|
|
|
|
|
|
result.OwnerProfile, err = q.CreateUser(ctx, CreateUserParams{
|
|
|
|
Email: arg.Email,
|
|
|
|
Password: arg.Password,
|
|
|
|
Fullname: arg.Fullname,
|
|
|
|
})
|
|
|
|
|
|
|
|
if err != nil {
|
|
|
|
return err
|
|
|
|
}
|
|
|
|
|
|
|
|
result.OutletProfile, err = q.CreateMerchant(ctx, CreateMerchantParams{
|
|
|
|
Name: arg.OutletName,
|
|
|
|
OwnerID: result.OwnerProfile.ID,
|
|
|
|
})
|
|
|
|
|
|
|
|
if err != nil {
|
|
|
|
return err
|
|
|
|
}
|
|
|
|
|
|
|
|
return nil
|
|
|
|
})
|
|
|
|
|
|
|
|
return result, err
|
|
|
|
|
|
|
|
}
|