Skip to content

Commit

Permalink
Improves naming differentiating subscriptions and plans
Browse files Browse the repository at this point in the history
  • Loading branch information
emmdim committed Nov 7, 2024
1 parent 94df5d6 commit 22cf35e
Show file tree
Hide file tree
Showing 13 changed files with 154 additions and 154 deletions.
12 changes: 6 additions & 6 deletions api/organizations.go
Original file line number Diff line number Diff line change
Expand Up @@ -69,16 +69,16 @@ func (a *API) createOrganizationHandler(w http.ResponseWriter, r *http.Request)
parentOrg = orgInfo.Parent.Address
}
// find default plan
defaultPlan, err := a.db.DefaultSubscription()
defaultPlan, err := a.db.DefaultPlan()
if err != nil || defaultPlan == nil {
ErrNoDefaultPLan.WithErr((err)).Write(w)
return
}
subscription := &db.OrganizationSubscription{
SubscriptionID: defaultPlan.ID,
StartDate: time.Now(),
Active: true,
MaxCensusSize: defaultPlan.Organization.CensusSize,
PlanID: defaultPlan.ID,
StartDate: time.Now(),
Active: true,
MaxCensusSize: defaultPlan.Organization.CensusSize,
}
// create the organization
if err := a.db.SetOrganization(&db.Organization{
Expand Down Expand Up @@ -485,7 +485,7 @@ func (a *API) getOrganizationSubscriptionHandler(w http.ResponseWriter, r *http.
return
}
// get the subscription from the database
plan, err := a.db.Subscription(org.Subscription.SubscriptionID)
plan, err := a.db.Plan(org.Subscription.PlanID)
if err != nil {
ErrGenericInternalServerError.Withf("could not get subscription: %v", err).Write(w)
return
Expand Down
14 changes: 7 additions & 7 deletions api/stripe.go
Original file line number Diff line number Diff line change
Expand Up @@ -49,7 +49,7 @@ func (a *API) handleWebhook(w http.ResponseWriter, r *http.Request) {
w.WriteHeader(http.StatusBadRequest)
return
}
dbSubscription, err := a.db.SubscriptionByStripeId(subscription.Items.Data[0].Plan.Product.ID)
dbSubscription, err := a.db.PlanByStripeId(subscription.Items.Data[0].Plan.Product.ID)
if err != nil || dbSubscription == nil {
log.Warnf("Could not update subscription %s, a corresponding subscription was not found.",
subscription.ID)
Expand All @@ -62,12 +62,12 @@ func (a *API) handleWebhook(w http.ResponseWriter, r *http.Request) {
renewalDate := time.Unix(subscription.BillingCycleAnchor, 0)

organizationSubscription := &db.OrganizationSubscription{
SubscriptionID: dbSubscription.ID,
StartDate: startDate,
EndDate: endDate,
RenewalDate: renewalDate,
Active: subscription.Status == "active",
MaxCensusSize: int(subscription.Items.Data[0].Quantity),
PlanID: dbSubscription.ID,
StartDate: startDate,
EndDate: endDate,
RenewalDate: renewalDate,
Active: subscription.Status == "active",
MaxCensusSize: int(subscription.Items.Data[0].Quantity),
}

// TODO will only worked for new subscriptions
Expand Down
2 changes: 1 addition & 1 deletion api/subscriptions.go
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,7 @@ import (
// It returns the list of subscriptions with their information.
func (a *API) getSubscriptionsHandler(w http.ResponseWriter, r *http.Request) {
// get the subscritions from the database
subscriptions, err := a.db.Subscriptions()
subscriptions, err := a.db.Plans()
if err != nil {
ErrGenericInternalServerError.Withf("could not get subscriptions: %v", err).Write(w)
return
Expand Down
2 changes: 1 addition & 1 deletion api/types.go
Original file line number Diff line number Diff line change
Expand Up @@ -180,5 +180,5 @@ func organizationFromDB(dbOrg, parent *db.Organization) *OrganizationInfo {
type OrganizationSubscriptionInfo struct {
SubcriptionDetails *db.OrganizationSubscription `json:"subscriptionDetails"`
Usage *db.OrganizationCounters `json:"usage"`
Plan *db.Subscription `json:"plan"`
Plan *db.Plan `json:"plan"`
}
6 changes: 3 additions & 3 deletions cmd/service/main.go
Original file line number Diff line number Diff line change
Expand Up @@ -28,7 +28,7 @@ func main() {
flag.StringP("vocdoniApi", "v", "https://api-dev.vocdoni.net/v2", "vocdoni node remote API URL")
flag.StringP("privateKey", "k", "", "private key for the Vocdoni account")
flag.BoolP("fullTransparentMode", "a", false, "allow all transactions and do not modify any of them")
flag.String("subscriptionsFile", "subscriptions.json", "JSON file that contains the subscriptions info")
flag.String("plansFile", "subscriptions.json", "JSON file that contains the subscriptions info")
flag.String("smtpServer", "", "SMTP server")
flag.Int("smtpPort", 587, "SMTP port")
flag.String("smtpUsername", "", "SMTP username")
Expand All @@ -55,7 +55,7 @@ func main() {
}
mongoURL := viper.GetString("mongoURL")
mongoDB := viper.GetString("mongoDB")
subscriptionsFile := viper.GetString("subscriptionsFile")
plansFile := viper.GetString("plansFile")
// email vars
smtpServer := viper.GetString("smtpServer")
smtpPort := viper.GetInt("smtpPort")
Expand All @@ -69,7 +69,7 @@ func main() {

log.Init("debug", "stdout", os.Stderr)
// initialize the MongoDB database
database, err := db.New(mongoURL, mongoDB, subscriptionsFile)
database, err := db.New(mongoURL, mongoDB, plansFile)
if err != nil {
log.Fatalf("could not create the MongoDB database: %v", err)
}
Expand Down
44 changes: 22 additions & 22 deletions db/helpers.go
Original file line number Diff line number Diff line change
Expand Up @@ -26,8 +26,8 @@ func (ms *MongoStorage) initCollections(database string) error {
return err
}
log.Infow("current collections", "collections", currentCollections)
log.Infow("reading subscriptions from file %s", ms.subscriptionsFile)
loadedSubscriptions, err := readSubscriptionJSON(ms.subscriptionsFile)
log.Infow("reading plans from file %s", ms.plansFile)
loadedPlans, err := readPlanJSON(ms.plansFile)
if err != nil {
return err
}
Expand All @@ -51,7 +51,7 @@ func (ms *MongoStorage) initCollections(database string) error {
return nil, fmt.Errorf("failed to update collection validator: %w", err)
}
}
if name == "subscriptions" {
if name == "plans" {
// clear subscriptions collection and update the DB with the new ones
if _, err := ms.client.Database(database).Collection(name).DeleteMany(ctx, bson.D{}); err != nil {
return nil, err
Expand All @@ -68,14 +68,14 @@ func (ms *MongoStorage) initCollections(database string) error {
return nil, err
}
}
if name == "subscriptions" {
var subscriptions []interface{}
for _, sub := range loadedSubscriptions {
subscriptions = append(subscriptions, sub)
if name == "plans" {
var plans []interface{}
for _, plan := range loadedPlans {
plans = append(plans, plan)
}
count, err := ms.client.Database(database).Collection(name).InsertMany(ctx, subscriptions)
if err != nil || len(count.InsertedIDs) != len(loadedSubscriptions) {
return nil, fmt.Errorf("failed to insert subscriptions: %w", err)
count, err := ms.client.Database(database).Collection(name).InsertMany(ctx, plans)
if err != nil || len(count.InsertedIDs) != len(loadedPlans) {
return nil, fmt.Errorf("failed to insert plans: %w", err)
}
}
// return the collection
Expand All @@ -98,7 +98,7 @@ func (ms *MongoStorage) initCollections(database string) error {
return err
}
// subscriptions collection
if ms.subscriptions, err = getCollection("subscriptions"); err != nil {
if ms.plans, err = getCollection("plans"); err != nil {
return err
}
return nil
Expand Down Expand Up @@ -222,15 +222,15 @@ func dynamicUpdateDocument(item interface{}, alwaysUpdateTags []string) (bson.M,
return bson.M{"$set": update}, nil
}

// readSubscriptionJSON reads a JSON file with an array of subscritpions
// and return it as a Subscription array
func readSubscriptionJSON(subscriptionsFile string) ([]*Subscription, error) {
log.Warnf("Reading subscriptions from %s", subscriptionsFile)
file, err := root.Assets.Open(fmt.Sprintf("assets/%s", subscriptionsFile))
// readPlanJSON reads a JSON file with an array of subscritpions
// and return it as a Plan array
func readPlanJSON(plansFile string) ([]*Plan, error) {
log.Warnf("Reading subscriptions from %s", plansFile)
file, err := root.Assets.Open(fmt.Sprintf("assets/%s", plansFile))
if err != nil {
return nil, err
}
// file, err := os.Open(subscriptionsFile)
// file, err := os.Open(plansFile)
// if err != nil {
// return nil, err
// }
Expand All @@ -243,14 +243,14 @@ func readSubscriptionJSON(subscriptionsFile string) ([]*Subscription, error) {
// Create a JSON decoder
decoder := json.NewDecoder(file)

var subscriptions []*Subscription
err = decoder.Decode(&subscriptions)
var plans []*Plan
err = decoder.Decode(&plans)
if err != nil {
return nil, err
}
// print subscriptions
for _, sub := range subscriptions {
// print plans
for _, sub := range plans {
fmt.Println(sub)
}
return subscriptions, nil
return plans, nil
}
16 changes: 8 additions & 8 deletions db/mongo.go
Original file line number Diff line number Diff line change
Expand Up @@ -17,24 +17,24 @@ import (

// MongoStorage uses an external MongoDB service for stoting the user data and election details.
type MongoStorage struct {
database string
client *mongo.Client
keysLock sync.RWMutex
subscriptionsFile string
database string
client *mongo.Client
keysLock sync.RWMutex
plansFile string

users *mongo.Collection
verifications *mongo.Collection
organizations *mongo.Collection
organizationInvites *mongo.Collection
subscriptions *mongo.Collection
plans *mongo.Collection
}

type Options struct {
MongoURL string
Database string
}

func New(url, database, subscriptionsFile string) (*MongoStorage, error) {
func New(url, database, plansFile string) (*MongoStorage, error) {
var err error
ms := &MongoStorage{}
if url == "" {
Expand Down Expand Up @@ -67,7 +67,7 @@ func New(url, database, subscriptionsFile string) (*MongoStorage, error) {
// init the database client
ms.client = client
ms.database = database
ms.subscriptionsFile = subscriptionsFile
ms.plansFile = plansFile
// init the collections
if err := ms.initCollections(ms.database); err != nil {
return nil, err
Expand Down Expand Up @@ -116,7 +116,7 @@ func (ms *MongoStorage) Reset() error {
return err
}
// drop subscriptions collection
if err := ms.subscriptions.Drop(ctx); err != nil {
if err := ms.plans.Drop(ctx); err != nil {
return err
}
// init the collections
Expand Down
4 changes: 2 additions & 2 deletions db/mongo_types.go
Original file line number Diff line number Diff line change
Expand Up @@ -12,8 +12,8 @@ type OrganizationCollection struct {
Organizations []Organization `json:"organizations" bson:"organizations"`
}

type SubscriptionCollection struct {
Subscriptions []Subscription `json:"subscriptions" bson:"subscriptions"`
type PlanCollection struct {
Plans []Plan `json:"plans" bson:"plans"`
}

type OrganizationInvitesCollection struct {
Expand Down
2 changes: 1 addition & 1 deletion db/organizations.go
Original file line number Diff line number Diff line change
Expand Up @@ -191,7 +191,7 @@ func (ms *MongoStorage) OrganizationsMembers(address string) ([]User, error) {
// the given address. If an error occurs, it returns the error. This method must
// be called with the keysLock held.
func (ms *MongoStorage) AddSubscriptionToOrganization(address string, orgSubscription *OrganizationSubscription) error {
if _, err := ms.Subscription(orgSubscription.SubscriptionID); err != nil {
if _, err := ms.Plan(orgSubscription.PlanID); err != nil {
return ErrInvalidData
}
ms.keysLock.Lock()
Expand Down
10 changes: 5 additions & 5 deletions db/organizations_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -181,20 +181,20 @@ func TestOrganizationsMembers(t *testing.T) {
c.Assert(singleMember.Email, qt.Equals, testUserEmail)
}

func TestAddOrganizationSubscription(t *testing.T) {
func TestAddOrganizationPlan(t *testing.T) {
defer func() {
if err := db.Reset(); err != nil {
t.Error(err)
}
}()
c := qt.New(t)
// create a new organization
address := "orgToAddSubscription"
address := "orgToAddPlan"
c.Assert(db.SetOrganization(&Organization{
Address: address,
}), qt.IsNil)
// add a subscription to the organization
subscriptionName := "testSubscription"
subscriptionName := "testPlan"
startDate := time.Now()
endDate := startDate.AddDate(1, 0, 0)
active := true
Expand All @@ -206,14 +206,14 @@ func TestAddOrganizationSubscription(t *testing.T) {
}
// using a non existing subscription should fail
c.Assert(db.AddSubscriptionToOrganization(address, orgSubscription), qt.IsNotNil)
subscriptionID, err := db.SetSubscription(&Subscription{
subscriptionID, err := db.SetPlan(&Plan{
Name: subscriptionName,
StripeID: stripeID,
})
if err != nil {
t.Error(err)
}
orgSubscription.SubscriptionID = subscriptionID
orgSubscription.PlanID = subscriptionID
c.Assert(db.AddSubscriptionToOrganization(address, orgSubscription), qt.IsNil)
// retrieve the organization and check the subscription details
org, _, err := db.Organization(address, false)
Expand Down
Loading

0 comments on commit 22cf35e

Please sign in to comment.