@@ -96,6 +96,9 @@ const Member = ghostBookshelf.Model.extend({
9696 } , {
9797 key : 'offer_redemptions' ,
9898 replacement : 'offer_redemptions.offer_id'
99+ } , {
100+ key : 'count.active_stripe_customers' ,
101+ replacement : 'active_stripe_customers_count'
99102 } ] ;
100103 } ,
101104
@@ -169,6 +172,21 @@ const Member = ghostBookshelf.Model.extend({
169172 tableName : 'offer_redemptions' ,
170173 type : 'oneToOne' ,
171174 joinFrom : 'member_id'
175+ } ,
176+ active_stripe_customers_count : {
177+ type : 'aggregate' ,
178+ aggregate : { fn : 'countDistinct' , column : 'members_stripe_customers_subscriptions.customer_id' } ,
179+ tableName : 'members_stripe_customers' ,
180+ joinFrom : 'member_id' ,
181+ joins : [ {
182+ tableName : 'members_stripe_customers_subscriptions' ,
183+ from : 'customer_id' ,
184+ to : 'customer_id'
185+ } ] ,
186+ wheres : {
187+ 'members_stripe_customers_subscriptions.status' : 'active' ,
188+ 'members_stripe_customers_subscriptions.cancel_at_period_end' : false
189+ }
172190 }
173191 } ;
174192 } ,
@@ -198,26 +216,6 @@ const Member = ghostBookshelf.Model.extend({
198216 offers : 'offers'
199217 } ,
200218
201- applyCustomQuery ( options ) {
202- if ( ! options . activeStripeCustomersCount ) {
203- return ;
204- }
205-
206- this . query ( ( qb ) => {
207- qb . innerJoin ( function ( ) {
208- this
209- . select ( 'members_stripe_customers.member_id' )
210- . from ( 'members_stripe_customers' )
211- . innerJoin ( 'members_stripe_customers_subscriptions' , 'members_stripe_customers_subscriptions.customer_id' , 'members_stripe_customers.customer_id' )
212- . where ( 'members_stripe_customers_subscriptions.status' , 'active' )
213- . where ( 'members_stripe_customers_subscriptions.cancel_at_period_end' , false )
214- . groupBy ( 'members_stripe_customers.member_id' )
215- . havingRaw ( 'COUNT(DISTINCT members_stripe_customers_subscriptions.customer_id) > 1' )
216- . as ( 'multiple_active_stripe_customers' ) ;
217- } , 'multiple_active_stripe_customers.member_id' , 'members.id' ) ;
218- } ) ;
219- } ,
220-
221219 productEvents ( ) {
222220 return this . hasMany ( 'MemberProductEvent' , 'member_id' , 'id' )
223221 . query ( 'orderBy' , 'created_at' , 'DESC' ) ;
@@ -516,7 +514,7 @@ const Member = ghostBookshelf.Model.extend({
516514 let options = ghostBookshelf . Model . permittedOptions . call ( this , methodName ) ;
517515
518516 if ( [ 'findPage' , 'findAll' ] . includes ( methodName ) ) {
519- options = options . concat ( [ 'search' , 'activeStripeCustomersCount' ] ) ;
517+ options = options . concat ( [ 'search' ] ) ;
520518 }
521519
522520 return options ;
0 commit comments