Skip to content

Commit

Permalink
PR fixes
Browse files Browse the repository at this point in the history
  • Loading branch information
emmdim committed Nov 8, 2024
1 parent c39e526 commit 9e05cd3
Show file tree
Hide file tree
Showing 8 changed files with 30 additions and 51 deletions.
16 changes: 8 additions & 8 deletions api/docs.md
Original file line number Diff line number Diff line change
Expand Up @@ -29,12 +29,12 @@
- [🧑‍💼 Invite organization member](#-invite-organization-member)
- [⏳ List pending invitations](#-list-pending-invitations)
- [🤝 Accept organization invitation](#-accept-organization-invitation)
- [👥 Organization Subscription Info](#-organization_subscription-info)
- [💸 Organization Subscription Info](#-organization-subscription-info)
- [🤠 Available organization members roles](#-available-organization-members-roles)
- [🏛️ Available organization types](#-available-organization-types)
- [💳 Plans](#-plans)
- [Get Available Plans](#-get-plans)
- [Get Plan Info](#-get-plan-info)
- [🏦 Plans](#-plans)
- [🛒 Get Available Plans](#-get-plans)
- [🛍️ Get Plan Info](#-get-plan-info)

</details>

Expand Down Expand Up @@ -674,7 +674,7 @@ Only the following parameters can be changed. Every parameter is optional.
| `409` | `40901` | `duplicate conflict` |
| `500` | `50002` | `internal server error` |

### 👥 Organization subscription info
### 💸 Organization subscription info

* **Path** `/organizations/{address}/subscription`
* **Method** `GET`
Expand Down Expand Up @@ -822,9 +822,9 @@ This request can be made only by organization admins.
}
```

## 💳 Plans
## 🏦 Plans

### Get Plans
### 🛒 Get Plans

* **Path** `/plans`
* **Method** `GET`
Expand Down Expand Up @@ -862,7 +862,7 @@ This request can be made only by organization admins.
|:---:|:---:|:---|
| `500` | `50002` | `internal server error` |

### Get Plan info
### 🛍️ Get Plan info

* **Path** `/plans/{planID}`
* **Method** `GET`
Expand Down
18 changes: 9 additions & 9 deletions api/stripe.go
Original file line number Diff line number Diff line change
Expand Up @@ -20,15 +20,15 @@ func (a *API) handleWebhook(w http.ResponseWriter, r *http.Request) {
payload, err := io.ReadAll(r.Body)
if err != nil {

log.Warnw("Stripe Webhook: Error reading request body: %v\n", err)
log.Warnw("stripe webhook: Error reading request body: %v\n", err)
w.WriteHeader(http.StatusServiceUnavailable)
return
}

signatureHeader := r.Header.Get("Stripe-Signature")
event, err := a.stripe.DecodeEvent(payload, signatureHeader)
if err != nil {
log.Warnw("Stripe Webhook: Error decoding event: %v\n", err)
log.Warnw("stripe Webhook: error decoding event: %v\n", err)
w.WriteHeader(http.StatusBadRequest)
return
}
Expand All @@ -37,23 +37,23 @@ func (a *API) handleWebhook(w http.ResponseWriter, r *http.Request) {
case "customer.subscription.created":
customer, subscription, err := a.stripe.GetInfoFromEvent(*event)
if err != nil {
log.Warnw("Stripe Webhook: Error getting info from event: %v\n", err)
log.Warnw("stripe webhook: error getting info from event: %v\n", err)
w.WriteHeader(http.StatusBadRequest)
return
}
org, _, err := a.db.OrganizationByCreatorEmail(customer.Email, false)
if err != nil || org == nil {
log.Warnf("Could not update subscription %s, a corresponding organization was not found.", subscription.ID)
log.Warnf("could not update subscription %s, a corresponding organization was not found.", subscription.ID)

log.Warnf("Please do manually for creator %s \n Error: %s", customer.Email, err.Error())
log.Warnf("please do manually for creator %s \n Error: %s", customer.Email, err.Error())
w.WriteHeader(http.StatusBadRequest)
return
}
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.",
log.Warnf("could not update subscription %s, a corresponding subscription was not found.",
subscription.ID)
log.Warnf("Please do manually: %s", err.Error())
log.Warnf("please do manually: %s", err.Error())
w.WriteHeader(http.StatusBadRequest)
return
}
Expand All @@ -71,8 +71,8 @@ func (a *API) handleWebhook(w http.ResponseWriter, r *http.Request) {
}

// TODO will only worked for new subscriptions
if err := a.db.AddSubscriptionToOrganization(org.Address, organizationSubscription); err != nil {
log.Warnf("Could not update subscription %s for organization %s: %s", subscription.ID, org.Address, err.Error())
if err := a.db.SetOrganizationSubscription(org.Address, organizationSubscription); err != nil {
log.Warnf("could not update subscription %s for organization %s: %s", subscription.ID, org.Address, err.Error())
w.WriteHeader(http.StatusBadRequest)
return
}
Expand Down
7 changes: 2 additions & 5 deletions api/types.go
Original file line number Diff line number Diff line change
Expand Up @@ -149,11 +149,6 @@ type MessageSignature struct {
Signature types.HexBytes `json:"signature,omitempty"`
}

type StripeConfig struct {
ApiKey string
WebhookKey string
}

// organizationFromDB converts a db.Organization to an OrganizationInfo, if the parent
// organization is provided it will be included in the response.
func organizationFromDB(dbOrg, parent *db.Organization) *OrganizationInfo {
Expand Down Expand Up @@ -181,6 +176,8 @@ func organizationFromDB(dbOrg, parent *db.Organization) *OrganizationInfo {
}
}

// OrganizationSubscriptionInfo is the struct used to provide detailed information
// regaridng the subscription of an organization.
type OrganizationSubscriptionInfo struct {
SubcriptionDetails *db.OrganizationSubscription `json:"subscriptionDetails"`
Usage *db.OrganizationCounters `json:"usage"`
Expand Down
25 changes: 3 additions & 22 deletions db/organizations.go
Original file line number Diff line number Diff line change
Expand Up @@ -187,10 +187,9 @@ func (ms *MongoStorage) OrganizationsMembers(address string) ([]User, error) {
return users, nil
}

// addSubscriptionToOrganization internal method adds the subscription to the organiation with
// 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 {
// SetOrganizationSubscription method adds the provided subscription to
// the organization with the given address
func (ms *MongoStorage) SetOrganizationSubscription(address string, orgSubscription *OrganizationSubscription) error {
if _, err := ms.Plan(orgSubscription.PlanID); err != nil {
return ErrInvalidData
}
Expand All @@ -208,21 +207,3 @@ func (ms *MongoStorage) AddSubscriptionToOrganization(address string, orgSubscri
}
return nil
}

// Implement update subscription method and ensuere that only members
// with adequate role can update the subscription
func (ms *MongoStorage) UpdateOrganizationSubscritpion(address string, orgSubscription *OrganizationSubscription) error {
ms.keysLock.Lock()
defer ms.keysLock.Unlock()
// create a context with a timeout
ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second)
defer cancel()
// prepare the document to be updated in the database
filter := bson.M{"_id": address}
updateDoc := bson.M{"$set": bson.M{"subscription": orgSubscription}}
// update the organization in the database
if _, err := ms.organizations.UpdateOne(ctx, filter, updateDoc); err != nil {
return err
}
return nil
}
4 changes: 2 additions & 2 deletions db/organizations_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -205,7 +205,7 @@ func TestAddOrganizationPlan(t *testing.T) {
Active: true,
}
// using a non existing subscription should fail
c.Assert(db.AddSubscriptionToOrganization(address, orgSubscription), qt.IsNotNil)
c.Assert(db.SetOrganizationSubscription(address, orgSubscription), qt.IsNotNil)
subscriptionID, err := db.SetPlan(&Plan{
Name: subscriptionName,
StripeID: stripeID,
Expand All @@ -214,7 +214,7 @@ func TestAddOrganizationPlan(t *testing.T) {
t.Error(err)
}
orgSubscription.PlanID = subscriptionID
c.Assert(db.AddSubscriptionToOrganization(address, orgSubscription), qt.IsNil)
c.Assert(db.SetOrganizationSubscription(address, orgSubscription), qt.IsNil)
// retrieve the organization and check the subscription details
org, _, err := db.Organization(address, false)
c.Assert(err, qt.IsNil)
Expand Down
1 change: 1 addition & 0 deletions db/types.go
Original file line number Diff line number Diff line change
Expand Up @@ -60,6 +60,7 @@ type Organization struct {
Subscription OrganizationSubscription `json:"subscription" bson:"subscription"`
Counters OrganizationCounters `json:"counters" bson:"counters"`
}

type PlanLimits struct {
Memberships int `json:"memberships" bson:"memberships"`
SubOrgs int `json:"subOrgs" bson:"subOrgs"`
Expand Down
2 changes: 1 addition & 1 deletion db/validations.go
Original file line number Diff line number Diff line change
Expand Up @@ -24,7 +24,7 @@ var usersCollectionValidator = bson.M{
"email": bson.M{
"bsonType": "string",
"description": "must be an email and is required",
"pattern": `^[\w.\+\.\-]+@([\w\-]+\.)+[\w]{2,}$`,
"pattern": internal.EmailRegexTemplate,
},
"password": bson.M{
"bsonType": "string",
Expand Down
8 changes: 4 additions & 4 deletions stripe/stripe.go
Original file line number Diff line number Diff line change
Expand Up @@ -29,13 +29,13 @@ func (s *StripeClient) DecodeEvent(payload []byte, signatureHeader string) (*str
event := stripe.Event{}

if err := json.Unmarshal(payload, &event); err != nil {
log.Warnw("Stripe Webhook: error while parsing basic request. %s\n", err.Error())
log.Warnw("stripe webhook: error while parsing basic request. %s\n", err.Error())
return nil, err
}

event, err := webhook.ConstructEvent(payload, signatureHeader, s.webhookSecret)
if err != nil {
log.Warnw("Stripe Webhook: Webhook signature verification failed. %s\n", err.Error())
log.Warnw("stripe webhook: webhook signature verification failed. %s\n", err.Error())
return nil, err
}
return &event, nil
Expand All @@ -46,15 +46,15 @@ func (s *StripeClient) GetInfoFromEvent(event stripe.Event) (*stripe.Customer, *
var subscription stripe.Subscription
err := json.Unmarshal(event.Data.Raw, &subscription)
if err != nil {
log.Warnf("Error parsing webhook JSON: %s\n", err.Error())
log.Warnf("error parsing webhook JSON: %s\n", err.Error())
return nil, nil, err
}

log.Debugf("Subscription created for %s and plan %s", subscription.ID, subscription.Customer.ID)
params := &stripe.CustomerParams{}
customer, err := customer.Get(subscription.Customer.ID, params)
if err != nil || customer == nil {
log.Warnf("Could not update subscription %s, stripe internal error getting customer", subscription.ID)
log.Warnf("could not update subscription %s, stripe internal error getting customer", subscription.ID)
return nil, nil, err
}
return customer, &subscription, nil
Expand Down

0 comments on commit 9e05cd3

Please sign in to comment.