Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Feature/balance activation #20

Merged
merged 15 commits into from
Jul 17, 2024
Merged
Show file tree
Hide file tree
Changes from 5 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
allOf:
- $ref: '#/components/schemas/CreateBalanceKey'
- $ref: '#/components/schemas/ActivateBalanceKey'
- type: object
x-go-is-request: true
required:
Expand All @@ -14,4 +14,3 @@ allOf:
type: string
description: referrer code from the link
example: "rCx18MZ4"

Original file line number Diff line number Diff line change
Expand Up @@ -10,4 +10,4 @@ properties:
pattern: '^0x[0-9a-fA-F]{64}$'
type:
type: string
enum: [ create_balance ]
enum: [ activate_balance, create_balance ]
27 changes: 7 additions & 20 deletions docs/spec/paths/integrations@geo-points-svc@v1@[email protected]
Original file line number Diff line number Diff line change
Expand Up @@ -3,14 +3,10 @@ post:
- Points balance
summary: Create points balance
description: |
Create an empty balance for authorized user who makes the request. Rank is included
in response.

This operation might be time-consuming, because `open` events should be added for
the new account synchronously (to display them right after the request).

Create an empty balance inactive for authorized user who makes the request.
violog marked this conversation as resolved.
Show resolved Hide resolved

If balance already exists, but it is disabled (it was not referred by another user,
but has fulfilled some event), you should use PATCH balances/{nullifier} endpoint as well.
but has fulfilled some event), you should use PATCH balances/ endpoint as well.
violog marked this conversation as resolved.
Show resolved Hide resolved
operationId: createPointsBalance
requestBody:
content:
Expand All @@ -21,23 +17,14 @@ post:
- data
properties:
data:
$ref: '#/components/schemas/CreateBalance'
$ref: '#/components/schemas/ActivateBalance'
Zaptoss marked this conversation as resolved.
Show resolved Hide resolved
responses:
201:
204:
description: Created
content:
application/vnd.api+json:
schema:
type: object
required:
- data
properties:
data:
$ref: '#/components/schemas/Balance'
400:
$ref: '#/components/responses/invalidParameter'
401:
$ref: '#/components/responses/invalidAuth'
404:
$ref: '#/components/responses/notFound'
409:
description: Balance already exists for provided nullifier
content:
Expand Down
35 changes: 35 additions & 0 deletions docs/spec/paths/integrations@geo-points-svc@v2@[email protected]
Original file line number Diff line number Diff line change
@@ -0,0 +1,35 @@
post:
tags:
- Points balance
summary: Create points balance V2
description: |
Create an empty balance inactive for authorized user who makes the request.
violog marked this conversation as resolved.
Show resolved Hide resolved

If balance already exists, but it is disabled (it was not referred by another user,
but has fulfilled some event), you should use PATCH balances/ endpoint as well.
violog marked this conversation as resolved.
Show resolved Hide resolved
operationId: createPointsBalance
requestBody:
content:
application/vnd.api+json:
schema:
type: object
required:
- data
properties:
data:
$ref: '#/components/schemas/ActivateBalanceKey'
responses:
204:
description: Created
400:
$ref: '#/components/responses/invalidParameter'
401:
$ref: '#/components/responses/invalidAuth'
409:
description: Balance already exists for provided nullifier
content:
application/vnd.api+json:
schema:
$ref: '#/components/schemas/Errors'
500:
$ref: '#/components/responses/internalError'
Original file line number Diff line number Diff line change
@@ -0,0 +1,47 @@
patch:
tags:
- Points balance
summary: Activate points balance
description: |
Activate points balance for authorized user who makes the request. Rank is included
in response.

This operation might be time-consuming, because `open` events should be added for
violog marked this conversation as resolved.
Show resolved Hide resolved
the new account synchronously (to display them right after the request).
operationId: activatePointsBalance
requestBody:
content:
application/vnd.api+json:
schema:
type: object
required:
- data
properties:
data:
$ref: '#/components/schemas/ActivateBalance'
responses:
200:
description: Created
content:
application/vnd.api+json:
schema:
type: object
required:
- data
properties:
data:
$ref: '#/components/schemas/Balance'
400:
$ref: '#/components/responses/invalidParameter'
401:
$ref: '#/components/responses/invalidAuth'
404:
$ref: '#/components/responses/notFound'
409:
description: Balance already activated
content:
application/vnd.api+json:
schema:
$ref: '#/components/schemas/Errors'
500:
$ref: '#/components/responses/internalError'
1 change: 1 addition & 0 deletions internal/data/balances.go
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,7 @@ import (

const (
ColAmount = "amount"
ColReferredBy = "referred_by"
ColLevel = "level"
ColAnonymousID = "anonymous_id"
ColSharedHash = "shared_hash"
Expand Down
147 changes: 147 additions & 0 deletions internal/service/handlers/activate_balance.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,147 @@
package handlers

import (
"fmt"
"net/http"

"github.com/rarimo/geo-auth-svc/pkg/auth"
"github.com/rarimo/geo-points-svc/internal/data"
"github.com/rarimo/geo-points-svc/internal/data/evtypes"
"github.com/rarimo/geo-points-svc/internal/data/evtypes/models"
"github.com/rarimo/geo-points-svc/internal/service/requests"
"gitlab.com/distributed_lab/ape"
"gitlab.com/distributed_lab/ape/problems"
)

func ActivateBalance(w http.ResponseWriter, r *http.Request) {
req, err := requests.NewActivateBalance(r)
if err != nil {
ape.RenderErr(w, problems.BadRequest(err)...)
return
}

nullifier := req.Data.ID
referralCode := req.Data.Attributes.ReferredBy

if !auth.Authenticates(UserClaims(r), auth.UserGrant(nullifier)) {
ape.RenderErr(w, problems.Unauthorized())
return
}

balance, err := BalancesQ(r).FilterByNullifier(nullifier).Get()
if err != nil {
Log(r).WithError(err).Error("Failed to get balance by nullifier")
ape.RenderErr(w, problems.InternalError())
return
}

if balance == nil {
Log(r).Debugf("Balance %s not exist", nullifier)
ape.RenderErr(w, problems.NotFound())
return
}

if balance.ReferredBy != nil {
Log(r).Infof("Balance already activated with code '%s'", *balance.ReferredBy)
ape.RenderErr(w, problems.Conflict())
return
}

referral, err := ReferralsQ(r).FilterInactive().Get(req.Data.Attributes.ReferredBy)
if err != nil {
Log(r).WithError(err).Error("Failed to get referral by ID")
ape.RenderErr(w, problems.InternalError())
return
}
if referral == nil {
Log(r).Debugf("Referral code '%s' not found", referralCode)
ape.RenderErr(w, problems.NotFound())
return
}

refBalance, err := BalancesQ(r).FilterByNullifier(referral.Nullifier).Get()
if err != nil || refBalance == nil { // must exist due to FK constraint
Log(r).WithError(err).Error("Failed to get referrer balance by nullifier")
ape.RenderErr(w, problems.InternalError())
return
}

err = EventsQ(r).Transaction(func() error {
level, err := doLvlUpAndReferralsUpdate(Levels(r), ReferralsQ(r), *balance, 0)
if err != nil {
return fmt.Errorf("failed to do lvlup and referrals update: %w", err)
}

err = BalancesQ(r).FilterByNullifier(balance.Nullifier).Update(map[string]any{
data.ColReferredBy: referralCode,
data.ColLevel: level,
})
if err != nil {
return fmt.Errorf("update balance amount and level: %w", err)
}

if refBalance.ReferredBy != nil {
violog marked this conversation as resolved.
Show resolved Hide resolved
err = EventsQ(r).Insert(data.Event{
Nullifier: nullifier,
Type: models.TypeBeReferred,
Status: data.EventFulfilled,
})
if err != nil {
return fmt.Errorf("failed to insert `be_referred` event: %w", err)
}
}

if err = ReferralsQ(r).Consume(referralCode); err != nil {
return fmt.Errorf("failed to consume referral: %w", err)
}

evTypeRef := EventTypes(r).Get(models.TypeReferralSpecific, evtypes.FilterInactive)
if evTypeRef == nil {
Log(r).Debug("Referral specific event type is inactive")
return nil
}

if balance.IsVerified {
// Be referred event is a welcome bonus when you created balance with non-genesis referral code
if err = claimBeReferredEvent(r, *balance); err != nil {
return fmt.Errorf("failed to claim be referred event: %w", err)
}
}

// Adds a friend event for the referrer. If the event
// is inactive, then nothing happens. If active, the
// fulfilled event is added and, if possible, the event claimed
if err = addEventForReferrer(r, evTypeRef, *balance); err != nil {
return fmt.Errorf("add event for referrer: %w", err)
}

return nil
})
if err != nil {
Log(r).WithError(err).Error("failed to insert events and consume referral for balance")
violog marked this conversation as resolved.
Show resolved Hide resolved
ape.RenderErr(w, problems.InternalError())
return
}

// We can't return inserted balance in a single query, because we can't calculate
// rank in transaction: RANK() is a window function allowed on a set of rows,
// while with RETURNING we operate a single one.
// Balance will exist cause of previous logic.
if balance, err = BalancesQ(r).GetWithRank(nullifier); err != nil {
Log(r).WithError(err).Error("Failed to get created balance by nullifier")
ape.RenderErr(w, problems.InternalError())
return
}

referrals, err := ReferralsQ(r).
FilterByNullifier(nullifier).
WithStatus().
Select()
if err != nil {
Log(r).WithError(err).Error("Failed to get referrals by nullifier with rewarding field")
ape.RenderErr(w, problems.InternalError())
return
}

ape.Render(w, newBalanceResponse(*balance, referrals, 0, 0))
}
58 changes: 58 additions & 0 deletions internal/service/handlers/create_balance_v2.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,58 @@
package handlers

import (
"fmt"
"net/http"

"github.com/rarimo/geo-auth-svc/pkg/auth"
"github.com/rarimo/geo-points-svc/internal/data"
"github.com/rarimo/geo-points-svc/internal/service/requests"
"gitlab.com/distributed_lab/ape"
"gitlab.com/distributed_lab/ape/problems"
)

func CreateBalanceV2(w http.ResponseWriter, r *http.Request) {
req, err := requests.NewCreateBalanceV2(r)
if err != nil {
ape.RenderErr(w, problems.BadRequest(err)...)
return
}

nullifier := req.Data.ID
if !auth.Authenticates(UserClaims(r), auth.UserGrant(nullifier)) {
ape.RenderErr(w, problems.Unauthorized())
return
}

balance, err := BalancesQ(r).FilterByNullifier(nullifier).Get()
if err != nil {
Log(r).WithError(err).Error("Failed to get balance by nullifier")
ape.RenderErr(w, problems.InternalError())
return
}

if balance != nil {
ape.RenderErr(w, problems.Conflict())
return
}

err = EventsQ(r).Transaction(func() error {
events := prepareEventsWithRef(nullifier, "", false, r)
violog marked this conversation as resolved.
Show resolved Hide resolved
Log(r).Debugf("%d events will be added for nullifier=%s", len(events), nullifier)
if err = EventsQ(r).Insert(events...); err != nil {
return fmt.Errorf("add open events: %w", err)
}

if err = BalancesQ(r).Insert(data.Balance{Nullifier: nullifier}); err != nil {
return fmt.Errorf("failed to insert balance: %w", err)
}
return nil
})
if err != nil {
Log(r).WithError(err).Error("Failed to create balance")
ape.RenderErr(w, problems.InternalError())
return
}

w.WriteHeader(http.StatusNoContent)
}
12 changes: 12 additions & 0 deletions internal/service/handlers/get_event.go
Original file line number Diff line number Diff line change
Expand Up @@ -42,5 +42,17 @@ func GetEvent(w http.ResponseWriter, r *http.Request) {
return
}

bal, err := BalancesQ(r).FilterByNullifier(event.Nullifier).FilterDisabled().Get()
if err != nil {
Log(r).WithError(err).Error("Failed to get event by ID")
ape.RenderErr(w, problems.InternalError())
return
}
if bal == nil {
Log(r).Debugf("Balance disabled or absent: %s", event.Nullifier)
ape.RenderErr(w, problems.NotFound())
return
}

ape.Render(w, resources.EventResponse{Data: newEventModel(*event, evType.Resource(r.Header.Get(langHeader)))})
}
Loading
Loading