@@ -171,10 +171,57 @@ export async function createPrice(
171171 unit_amount : amountCents ,
172172 currency : "cad" ,
173173 } ) ;
174- await stripe . products . update ( productId , { default_price : price . id } ) ;
174+
175175 return { priceId : price . id } ;
176176}
177177
178+ export async function replaceProductPrice (
179+ productId : string ,
180+ amountCents : number ,
181+ ) : Promise < { priceId : string } > {
182+ // get the current default price for the product
183+ const product = await stripe . products . retrieve ( productId , {
184+ expand : [ "default_price" ] ,
185+ } ) ;
186+
187+ const currentDefaultPrice =
188+ typeof product . default_price === "string"
189+ ? product . default_price
190+ : product . default_price ?. id ;
191+
192+ // create the new price FIRST (rlly important)
193+ const newPrice = await stripe . prices . create ( {
194+ product : productId ,
195+ unit_amount : amountCents ,
196+ currency : "cad" ,
197+ } ) ;
198+
199+ // set the new price as the product default
200+ await stripe . products . update ( productId , {
201+ default_price : newPrice . id ,
202+ } ) ;
203+
204+ // archive old active prices but NEVER archive the new default price
205+ const prices = await stripe . prices . list ( {
206+ product : productId ,
207+ active : true ,
208+ limit : 100 ,
209+ } ) ;
210+
211+ for ( const p of prices . data ) {
212+ if ( p . id !== newPrice . id && p . id !== currentDefaultPrice ) {
213+ await stripe . prices . update ( p . id , { active : false } ) ;
214+ }
215+ }
216+
217+ // archive the old default price after default_price has been swapped
218+ if ( currentDefaultPrice && currentDefaultPrice !== newPrice . id ) {
219+ await stripe . prices . update ( currentDefaultPrice , { active : false } ) ;
220+ }
221+
222+ return { priceId : newPrice . id } ;
223+ }
224+
178225export async function deactivateActivePricesForProduct (
179226 productId : string ,
180227) : Promise < void > {
0 commit comments