89 lines
1.9 KiB
Go
89 lines
1.9 KiB
Go
package db
|
|
|
|
import (
|
|
"context"
|
|
"database/sql"
|
|
"fmt"
|
|
|
|
"github.com/google/uuid"
|
|
)
|
|
|
|
type Store struct {
|
|
*Queries
|
|
db *sql.DB
|
|
}
|
|
|
|
func NewStore(db *sql.DB) *Store {
|
|
return &Store{
|
|
db: db,
|
|
Queries: New(db),
|
|
}
|
|
}
|
|
|
|
func (store *Store) execTx(ctx context.Context, fn func(*Queries) error) error {
|
|
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()
|
|
|
|
}
|
|
|
|
type PurchaseOrderProduct struct {
|
|
ProductID uuid.UUID `json:"product_id"`
|
|
Quantity float64 `json:"quantity"`
|
|
Sub_total float64 `json:"sub_total"`
|
|
Price float64 `json:"price"`
|
|
}
|
|
|
|
type PurchasoOrderTxParams struct {
|
|
MerchantID uuid.UUID `json:"merchant_id"`
|
|
SupplierID uuid.UUID `json:"supplier_id"`
|
|
Code sql.NullString `json:"code"`
|
|
IsPaid bool `json:"is_paid"`
|
|
Total float64 `json:"total"`
|
|
PaidNominal float64 `json:"paid_nominal"`
|
|
Note sql.NullString `json:"note"`
|
|
Products []PurchaseOrderProduct `json:"products"`
|
|
}
|
|
|
|
type PurchaseOrderTxResult struct {
|
|
PurchaseOrder PurchaseOrder `json:"purchase_order"`
|
|
// PurchaseOrderDetail []PurchaseOrderDetail `json:"detail"`
|
|
}
|
|
|
|
func (store *Store) PurchaseOrderTx(ctx context.Context, arg PurchasoOrderTxParams) (PurchaseOrderTxResult, error) {
|
|
var result PurchaseOrderTxResult
|
|
|
|
err := store.execTx(ctx, func(q *Queries) error {
|
|
var err error
|
|
result.PurchaseOrder, err = q.CreatePurchaseOrder(ctx, CreatePurchaseOrderParams{
|
|
MerchantID: arg.MerchantID,
|
|
SupplierID: arg.SupplierID,
|
|
Code: arg.Code,
|
|
IsPaid: arg.IsPaid,
|
|
Total: arg.Total,
|
|
PaidNominal: arg.PaidNominal,
|
|
Note: arg.Note,
|
|
})
|
|
|
|
if err != nil {
|
|
return err
|
|
}
|
|
|
|
return nil
|
|
})
|
|
|
|
return result, err
|
|
}
|