mirror of
https://github.com/grassrootseconomics/farmstar-survey-backend.git
synced 2024-12-21 23:17:33 +01:00
80 lines
1.8 KiB
Go
80 lines
1.8 KiB
Go
|
package worker
|
||
|
|
||
|
import (
|
||
|
"context"
|
||
|
"errors"
|
||
|
|
||
|
"github.com/grassrootseconomics/farmstar-survey-backend/pkg/custodial"
|
||
|
"github.com/grassrootseconomics/farmstar-survey-backend/pkg/ussd"
|
||
|
"github.com/pocketbase/pocketbase"
|
||
|
"github.com/pocketbase/pocketbase/forms"
|
||
|
"github.com/pocketbase/pocketbase/models"
|
||
|
"github.com/riverqueue/river"
|
||
|
)
|
||
|
|
||
|
type (
|
||
|
RewardsArgs struct {
|
||
|
Phone string `json:"phone"`
|
||
|
Amount uint `json:"amount"`
|
||
|
}
|
||
|
|
||
|
RewardsWorker struct {
|
||
|
river.WorkerDefaults[RewardsArgs]
|
||
|
|
||
|
Pocketbase *pocketbase.PocketBase
|
||
|
USSDClient *ussd.USSDClient
|
||
|
CustodialClient *custodial.CustodialClient
|
||
|
VaultAddress string
|
||
|
VoucherAddress string
|
||
|
}
|
||
|
)
|
||
|
|
||
|
func (RewardsArgs) Kind() string {
|
||
|
return "rewards"
|
||
|
}
|
||
|
|
||
|
func (w *RewardsWorker) Work(ctx context.Context, job *river.Job[RewardsArgs]) error {
|
||
|
userRecord, err := w.Pocketbase.Dao().FindFirstRecordByData("users", "phone", job.Args.Phone)
|
||
|
if err != nil {
|
||
|
return err
|
||
|
}
|
||
|
|
||
|
rewardsCollection, err := w.Pocketbase.Dao().FindCollectionByNameOrId("rewards")
|
||
|
if err != nil {
|
||
|
return err
|
||
|
}
|
||
|
rewardsRecord := models.NewRecord(rewardsCollection)
|
||
|
rewardsForm := forms.NewRecordUpsert(w.Pocketbase, rewardsRecord)
|
||
|
|
||
|
address, err := w.USSDClient.GetAddress(ctx, job.Args.Phone)
|
||
|
if err != nil {
|
||
|
return err
|
||
|
}
|
||
|
|
||
|
if address == "" {
|
||
|
return errors.New("ussd account not found")
|
||
|
}
|
||
|
|
||
|
trackingId, err := w.CustodialClient.SignTransfer(ctx, custodial.SignTransferPayload{
|
||
|
Amount: job.Args.Amount,
|
||
|
To: address,
|
||
|
From: w.VaultAddress,
|
||
|
VoucherAddress: w.VoucherAddress,
|
||
|
})
|
||
|
if err != nil {
|
||
|
return err
|
||
|
}
|
||
|
|
||
|
rewardsForm.LoadData(map[string]any{
|
||
|
"receiver": userRecord.Id,
|
||
|
"ge_tracking_id": trackingId,
|
||
|
"value": job.Args.Amount / 1_000_000,
|
||
|
})
|
||
|
|
||
|
if err := rewardsForm.Submit(); err != nil {
|
||
|
return err
|
||
|
}
|
||
|
|
||
|
return nil
|
||
|
}
|