Skip to content

Commit

Permalink
added transactions for functions
Browse files Browse the repository at this point in the history
  • Loading branch information
elraphty committed Jun 10, 2024
1 parent 3616fc1 commit e6ab5cb
Show file tree
Hide file tree
Showing 6 changed files with 166 additions and 26 deletions.
22 changes: 20 additions & 2 deletions db/db.go
Original file line number Diff line number Diff line change
Expand Up @@ -1724,9 +1724,18 @@ func (db database) AddUserInvoiceData(userData UserInvoiceData) UserInvoiceData

func (db database) ProcessAddInvoice(invoice NewInvoiceList, userData UserInvoiceData) error {
tx := db.db.Begin()

var err error

defer func() {
if r := recover(); r != nil {
tx.Rollback()
}
}()

if err = tx.Error; err != nil {
return err
}

if err = tx.Create(&invoice).Error; err != nil {
tx.Rollback()
}
Expand All @@ -1740,9 +1749,18 @@ func (db database) ProcessAddInvoice(invoice NewInvoiceList, userData UserInvoic

func (db database) ProcessBudgetInvoice(paymentHistory NewPaymentHistory, newInvoice NewInvoiceList) error {
tx := db.db.Begin()

var err error

defer func() {
if r := recover(); r != nil {
tx.Rollback()
}
}()

if err = tx.Error; err != nil {
return err
}

if err = tx.Create(&paymentHistory).Error; err != nil {
tx.Rollback()
}
Expand Down
1 change: 1 addition & 0 deletions db/interface.go
Original file line number Diff line number Diff line change
Expand Up @@ -109,6 +109,7 @@ type Database interface {
AddAndUpdateBudget(invoice NewInvoiceList) NewPaymentHistory
WithdrawBudget(sender_pubkey string, workspace_uuid string, amount uint)
AddPaymentHistory(payment NewPaymentHistory) NewPaymentHistory
ProcessBountyPayment(payment NewPaymentHistory, bounty NewBounty) error
GetPaymentHistory(workspace_uuid string, r *http.Request) []NewPaymentHistory
GetInvoice(payment_request string) NewInvoiceList
GetWorkspaceInvoices(workspace_uuid string) []NewInvoiceList
Expand Down
76 changes: 74 additions & 2 deletions db/workspaces.go
Original file line number Diff line number Diff line change
Expand Up @@ -255,11 +255,21 @@ func (db database) ProcessUpdateBudget(invoice NewInvoiceList) error {
// Start db transaction
tx := db.db.Begin()

var err error

defer func() {
if r := recover(); r != nil {
tx.Rollback()
}
}()

if err = tx.Error; err != nil {
return err
}

created := invoice.Created
workspace_uuid := invoice.WorkspaceUuid

var err error

// Get payment history and update budget
paymentHistory := db.GetPaymentHistoryByCreated(created, workspace_uuid)
if paymentHistory.WorkspaceUuid != "" && paymentHistory.Amount != 0 {
Expand Down Expand Up @@ -341,6 +351,16 @@ func (db database) WithdrawBudget(sender_pubkey string, workspace_uuid string, a
tx := db.db.Begin()
var err error

defer func() {
if r := recover(); r != nil {
tx.Rollback()
}
}()

if err = tx.Error; err != nil {
return
}

// get Workspace budget and add payment to total budget
WorkspaceBudget := db.GetWorkspaceBudget(workspace_uuid)
totalBudget := WorkspaceBudget.TotalBudget
Expand Down Expand Up @@ -389,6 +409,48 @@ func (db database) AddPaymentHistory(payment NewPaymentHistory) NewPaymentHistor
return payment
}

func (db database) ProcessBountyPayment(payment NewPaymentHistory, bounty NewBounty) error {
tx := db.db.Begin()
var err error

defer func() {
if r := recover(); r != nil {
tx.Rollback()
}
}()

if err = tx.Error; err != nil {
return err
}

// add to payment history
if err = tx.Create(&payment).Error; err != nil {
tx.Rollback()
return err
}

// get Workspace budget and subtract payment from total budget
WorkspaceBudget := db.GetWorkspaceBudget(payment.WorkspaceUuid)
totalBudget := WorkspaceBudget.TotalBudget

// update budget
WorkspaceBudget.TotalBudget = totalBudget - payment.Amount
if err = tx.Model(&NewBountyBudget{}).Where("workspace_uuid = ?", payment.WorkspaceUuid).Updates(map[string]interface{}{
"total_budget": WorkspaceBudget.TotalBudget,
}).Error; err != nil {
tx.Rollback()
return err
}

// updatge bounty status
if err = tx.Where("created", bounty.Created).Updates(&bounty).Error; err != nil {
tx.Rollback()
return err
}

return tx.Commit().Error
}

func (db database) GetPaymentHistory(workspace_uuid string, r *http.Request) []NewPaymentHistory {
payment := []NewPaymentHistory{}

Expand Down Expand Up @@ -445,6 +507,16 @@ func (db database) ProcessDeleteWorkspace(workspace_uuid string) error {
tx := db.db.Begin()
var err error

defer func() {
if r := recover(); r != nil {
tx.Rollback()
}
}()

if err = tx.Error; err != nil {
return err
}

updates := map[string]interface{}{
"website": "",
"github": "",
Expand Down
25 changes: 23 additions & 2 deletions handlers/bounty.go
Original file line number Diff line number Diff line change
Expand Up @@ -527,6 +527,12 @@ func (h *bountyHandler) MakeBountyPayment(w http.ResponseWriter, r *http.Request
request := db.BountyPayRequest{}
body, err := io.ReadAll(r.Body)
r.Body.Close()
if err != nil {
fmt.Println("[read body]", err)
w.WriteHeader(http.StatusNotAcceptable)
h.m.Unlock()
return
}

err = json.Unmarshal(body, &request)
if err != nil {
Expand Down Expand Up @@ -557,6 +563,13 @@ func (h *bountyHandler) MakeBountyPayment(w http.ResponseWriter, r *http.Request

defer res.Body.Close()
body, err = io.ReadAll(res.Body)
if err != nil {
fmt.Println("[read body]", err)
w.WriteHeader(http.StatusNotAcceptable)
h.m.Unlock()
return
}

msg := make(map[string]interface{})

// payment is successful add to payment history
Expand All @@ -566,7 +579,15 @@ func (h *bountyHandler) MakeBountyPayment(w http.ResponseWriter, r *http.Request
keysendRes := db.KeysendSuccess{}
err = json.Unmarshal(body, &keysendRes)

if err != nil {
fmt.Println("[Unmarshal]", err)
w.WriteHeader(http.StatusNotAcceptable)
h.m.Unlock()
return
}

now := time.Now()

paymentHistory := db.NewPaymentHistory{
Amount: amount,
SenderPubKey: pubKeyFromAuth,
Expand All @@ -578,13 +599,13 @@ func (h *bountyHandler) MakeBountyPayment(w http.ResponseWriter, r *http.Request
Status: true,
PaymentType: "payment",
}
h.db.AddPaymentHistory(paymentHistory)

bounty.Paid = true
bounty.PaidDate = &now
bounty.Completed = true
bounty.CompletionDate = &now
h.db.UpdateBounty(bounty)

h.db.ProcessBountyPayment(paymentHistory, bounty)

msg["msg"] = "keysend_success"
msg["invoice"] = ""
Expand Down
21 changes: 1 addition & 20 deletions handlers/bounty_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -106,7 +106,6 @@ func TestCreateOrEditBounty(t *testing.T) {
rr := httptest.NewRecorder()
handler := http.HandlerFunc(bHandler.CreateOrEditBounty)


existingBounty := db.NewBounty{
ID: 1,
Type: "coding",
Expand Down Expand Up @@ -1325,28 +1324,10 @@ func TestMakeBountyPayment(t *testing.T) {
bHandler.getSocketConnections = mockGetSocketConnections
bHandler.userHasAccess = mockUserHasAccessTrue

now := time.Now()
expectedBounty := db.NewBounty{
ID: bountyID,
OrgUuid: "org-1",
WorkspaceUuid: "work-1",
Assignee: "assignee-1",
Price: uint(1000),
Paid: true,
PaidDate: &now,
CompletionDate: &now,
}

mockDb.On("GetBounty", bountyID).Return(bounty, nil)
mockDb.On("GetWorkspaceBudget", bounty.WorkspaceUuid).Return(db.NewBountyBudget{TotalBudget: 2000}, nil)
mockDb.On("GetPersonByPubkey", bounty.Assignee).Return(db.Person{OwnerPubKey: "assignee-1", OwnerRouteHint: "OwnerRouteHint"}, nil)
mockDb.On("AddPaymentHistory", mock.AnythingOfType("db.NewPaymentHistory")).Return(db.NewPaymentHistory{ID: 1})
mockDb.On("UpdateBounty", mock.AnythingOfType("db.NewBounty")).Run(func(args mock.Arguments) {
updatedBounty := args.Get(0).(db.NewBounty)
assert.True(t, updatedBounty.Paid)
assert.NotNil(t, updatedBounty.PaidDate)
assert.NotNil(t, updatedBounty.CompletionDate)
}).Return(expectedBounty, nil).Once()
mockDb.On("ProcessBountyPayment", mock.AnythingOfType("db.NewPaymentHistory"), mock.AnythingOfType("db.NewBounty")).Return(nil)

expectedUrl := fmt.Sprintf("%s/payment", config.RelayUrl)
expectedBody := `{"amount": 1000, "destination_key": "assignee-1", "route_hint": "OwnerRouteHint", "text": "memotext added for notification"}`
Expand Down
47 changes: 47 additions & 0 deletions mocks/Database.go

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

0 comments on commit e6ab5cb

Please sign in to comment.