farmstar-survey-backend/internal/hooks/transaction.go

94 lines
2.8 KiB
Go
Raw Normal View History

2024-02-05 14:05:28 +01:00
package hooks
import (
"database/sql"
"fmt"
"github.com/grassrootseconomics/farmstar-survey-backend/internal/worker"
"github.com/pocketbase/dbx"
"github.com/pocketbase/pocketbase/core"
)
func (r *HooksContainer) bootstrapTransactionHook() {
r.pb.OnModelAfterCreate("transactions").Add(func(e *core.ModelEvent) error {
transactionRecord, err := r.pb.Dao().FindRecordById("transactions", e.Model.GetId())
if err != nil {
return err
}
quantity := uint(transactionRecord.GetInt("evergrow_quantity"))
initiatorRecord, err := r.pb.Dao().FindRecordById("users", transactionRecord.GetString("initiator"))
if err != nil {
return err
}
counterpartyRecord, err := r.pb.Dao().FindRecordById("users", transactionRecord.GetString("counterparty"))
if err != nil {
return err
}
inverseTransactionRecord, err := r.pb.Dao().FindFirstRecordByFilter(
"transactions",
"completed = {:completed} && evergrow_quantity = {:quantity} && initiator = {:initiator} && counterparty = {:counterparty} && tx_date = {:tx_date}",
2024-02-05 14:05:28 +01:00
dbx.Params{
"completed": false,
"quantity": transactionRecord.GetInt("evergrow_quantity"),
"initiator": counterpartyRecord.GetId(),
"counterparty": initiatorRecord.GetId(),
"tx_date": transactionRecord.GetDateTime("tx_date"),
2024-02-05 14:05:28 +01:00
},
)
if err != nil && err != sql.ErrNoRows {
return err
}
if inverseTransactionRecord != nil {
if isFarmer(initiatorRecord.GetString("participant_type")) {
if err := r.worker.QueueRewardsTask(initiatorRecord.GetString("phone"), 65_000_000*quantity); err != nil {
return err
}
}
if isFarmer(counterpartyRecord.GetString("participant_type")) {
if err := r.worker.QueueRewardsTask(counterpartyRecord.GetString("phone"), 65_000_000*quantity); err != nil {
return err
}
}
transactionRecord.Set("completed", true)
if err := r.pb.Dao().SaveRecord(transactionRecord); err != nil {
return err
}
inverseTransactionRecord.Set("completed", true)
if err := r.pb.Dao().SaveRecord(inverseTransactionRecord); err != nil {
return err
}
}
if err := r.worker.QueueSMSTask(initiatorRecord.GetString("phone"), worker.PurchaseComplete, ""); err != nil {
return err
}
msg := fmt.Sprintf(
"New purchase survey completed:\n\ninitiator: %s\ncounterparty: %s\nquantity: %d\ndate: %s\nfeedback: %s",
2024-02-05 14:05:28 +01:00
fmt.Sprintf("%s (%s)", initiatorRecord.GetString("name"), initiatorRecord.GetString("participant_type")),
fmt.Sprintf("%s (%s)", counterpartyRecord.GetString("name"), counterpartyRecord.GetString("participant_type")),
transactionRecord.GetInt("evergrow_quantity"),
transactionRecord.GetDateTime("tx_date").String(),
2024-02-05 14:05:28 +01:00
transactionRecord.GetString("feedback"),
)
if err := r.worker.QueueTgTask(msg); err != nil {
return err
}
return nil
})
}
func isFarmer(value string) bool {
return value == "farmer"
}