@smbcloud / smbcloud-ascapi Mirror · read-only / commits / 679016e
Fork 0

Read-only mirror of github.com/smbcloudXYZ/smbcloud-ascapi.

Mirrored from https://github.com/smbcloudXYZ/smbcloud-ascapi.git

Synced Nov 25, 09:15 UTC

Add asc play products to create one-time products

Play only lets an app sell a product that exists, and asc play had no way to make one. products list and get read the app's one-time products. products create converts one price to every region (pricing:convertRegionPrices), creates the product with onetimeproducts.patch and allowMissing, activates its purchase option and reads it back. It refuses an id that already exists, so a rerun cannot overwrite a price, and --dry-run converts prices and sends nothing. onetimeproducts.patch has an all-lowercase path while get, list and the state change use oneTimeProducts. A wrong case is a 404 page from the front end, so the patch path has its own function and a test. Tried against a real app: an app with no products answers list with an empty body, which now reads as an empty list, and onde.unlock was created with 174 regional prices and an ACTIVE purchase option. Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>

Seto Elkahfi committed Nov 8, 2026 at 13:30 UTC 679016ed94ea18d17247452c394c355884fb6033
7 files changed +544 -3
.agents/AGENTS.md
+9 -1
@@ -314,6 +314,9 @@ asc play images list <PACKAGE> --locale en-US --type phone-screenshots
314 asc play images replace <PACKAGE> --locale en-US --type phone-screenshots --file a.png --file b.png
315 asc play tracks get <PACKAGE> --track internal
316 asc play tracks set-notes <PACKAGE> --track internal --version-code 120 --locale en-US --notes-file n.txt
317 +asc play products list <PACKAGE>
318 +asc play products create <PACKAGE> --id app.unlock --title "Unlock" --description "..." \
319 + --price 4.99 --language en-GB # --dry-run prints the body and sends nothing
320 ```
321
322 Limits linted before sending: title 30, short description 80, full description
@@ -322,7 +325,12 @@ Limits linted before sending: title 30, short description 80, full description
325 `images replace` deletes the bucket and uploads the files in one edit, so a
326 failed upload keeps the old set. MCP exposes only the reads
327 (`play_listing_list`, `play_images_list`, `play_track_get`); every write stays
325 -CLI-only, like review submission. The operations live in
328 +CLI-only, like review submission. One-time products are not inside an edit:
329 +`products create` converts one price to every region
330 +(`pricing:convertRegionPrices`), creates the product with `onetimeproducts.patch`
331 +(`allowMissing`), activates its purchase option and reads it back; it refuses an
332 +id that exists. Note the patch path is lowercase `onetimeproducts` while get,
333 +list and the state change use `oneTimeProducts`. The operations live in
334 `crates/frontend/src/play.rs`.
335
336 ## Microsoft Store (CLI)
crates/cli/src/main.rs
+81 -1
@@ -40,7 +40,10 @@ use smbcloud_ascapi_iap::in_app_purchase::{
40 use smbcloud_ascapi_iap::localization::LocalizationUpdate;
41 use smbcloud_ascapi_iap::prelude::*;
42 use smbcloud_ascapi_msstore::ListingFields as MsStoreListingFields;
43 -use smbcloud_ascapi_play::{ImageType as PlayImageType, ListingFields as PlayListingFields};
43 +use smbcloud_ascapi_play::{
44 + ImageType as PlayImageType, ListingFields as PlayListingFields, Money as PlayMoney,
45 + NewProduct as PlayNewProduct,
46 +};
47 use smbcloud_ascapi_pricing::app_price::PriceKind;
48 use smbcloud_ascapi_pricing::prelude::*;
49 use smbcloud_ascapi_reports::prelude::*;
@@ -110,6 +113,11 @@ enum PlayCommand {
113 #[command(subcommand)]
114 command: PlayTracksCommand,
115 },
116 + /// One-time products (in-app products): list, read, create.
117 + Products {
118 + #[command(subcommand)]
119 + command: PlayProductsCommand,
120 + },
121 }
122
123 // The update commands carry many flags; boxing a clap subcommand field is not
@@ -624,6 +632,38 @@ enum PlayTracksCommand {
632 MaxVersionCode { package: String },
633 }
634
635 +#[derive(Subcommand)]
636 +enum PlayProductsCommand {
637 + /// Every one-time product of the app.
638 + List { package: String },
639 + /// One one-time product by id.
640 + Get { package: String, product_id: String },
641 + /// Create a one-time product, price it in every region from one price,
642 + /// and activate it. Refuses an id that exists. With `--dry-run` it prints
643 + /// the product body and sends nothing.
644 + Create {
645 + package: String,
646 + #[arg(long)]
647 + id: String,
648 + #[arg(long)]
649 + title: String,
650 + #[arg(long)]
651 + description: String,
652 + /// Price in `--currency`, for example 4.99. Play converts it to every
653 + /// other region, as Play Console does.
654 + #[arg(long)]
655 + price: String,
656 + #[arg(long, default_value = "USD")]
657 + currency: String,
658 + /// Language of the title and description; the app's default language.
659 + #[arg(long)]
660 + language: String,
661 + /// Purchase option id.
662 + #[arg(long, default_value = "buy")]
663 + option_id: String,
664 + },
665 +}
666 +
667 #[derive(Subcommand)]
668 #[allow(clippy::large_enum_variant)]
669 enum MsStoreCommand {
@@ -1386,6 +1426,46 @@ async fn run_play(
1426 Ok(())
1427 }
1428 },
1429 + PlayCommand::Products { command } => match command {
1430 + PlayProductsCommand::List { package } => {
1431 + print_json(&play::read_products(&client, &package).await.map_err(fail)?)
1432 + }
1433 + PlayProductsCommand::Get {
1434 + package,
1435 + product_id,
1436 + } => print_json(
1437 + &play::read_product(&client, &package, &product_id)
1438 + .await
1439 + .map_err(fail)?,
1440 + ),
1441 + PlayProductsCommand::Create {
1442 + package,
1443 + id,
1444 + title,
1445 + description,
1446 + price,
1447 + currency,
1448 + language,
1449 + option_id,
1450 + } => {
1451 + let price = PlayMoney::parse(&currency, &price).map_err(|e| fail(e.to_string()))?;
1452 + let product = PlayNewProduct {
1453 + package,
1454 + product_id: id,
1455 + language,
1456 + title,
1457 + description,
1458 + purchase_option_id: option_id,
1459 + };
1460 + let result = play::create_product(&client, &product, &price, dry_run)
1461 + .await
1462 + .map_err(fail)?;
1463 + if result.dry_run {
1464 + println!("# dry run: nothing was created; body that would be sent:");
1465 + }
1466 + print_json(&result)
1467 + }
1468 + },
1469 }
1470 }
1471
crates/frontend/src/play.rs
+92 -1
@@ -10,7 +10,9 @@ use std::path::{Path, PathBuf};
10 use serde::Serialize;
11 use sha2::{Digest, Sha256};
12 use smbcloud_ascapi_play::{
13 - png_dimensions, Image, ImageType, Listing, ListingFields, PlayClient, RolloutAction,
13 + png_dimensions,
14 + product::{product_body, regions_version},
15 + Image, ImageType, Listing, ListingFields, Money, NewProduct, PlayClient, RolloutAction,
16 ServiceAccount, Track,
17 };
18
@@ -563,6 +565,95 @@ pub async fn max_version_code(client: &PlayClient, package: &str) -> Result<u64,
565 .ok_or_else(|| format!("no track of {package} carries a version code"))
566 }
567
568 +/// All one-time products of the app.
569 +pub async fn read_products(
570 + client: &PlayClient,
571 + package: &str,
572 +) -> Result<Vec<serde_json::Value>, String> {
573 + client.list_products(package).await.map_err(err)
574 +}
575 +
576 +/// One one-time product by id.
577 +pub async fn read_product(
578 + client: &PlayClient,
579 + package: &str,
580 + product_id: &str,
581 +) -> Result<serde_json::Value, String> {
582 + client.get_product(package, product_id).await.map_err(err)
583 +}
584 +
585 +/// The result of creating a one-time product.
586 +#[derive(Debug, Serialize)]
587 +#[serde(rename_all = "camelCase")]
588 +pub struct ProductCreated {
589 + pub dry_run: bool,
590 + /// The product body that is sent (dry run) or was sent.
591 + pub sent: serde_json::Value,
592 + /// The product as Play stores it, read back after activation. `None` on a
593 + /// dry run.
594 + pub stored: Option<serde_json::Value>,
595 +}
596 +
597 +/// Create a one-time product priced in one currency and converted to every
598 +/// region, then activate its purchase option. Refuses a product id that
599 +/// already exists, so a rerun never overwrites a price. A dry run converts
600 +/// prices (a read) and sends nothing.
601 +pub async fn create_product(
602 + client: &PlayClient,
603 + product: &NewProduct,
604 + price: &Money,
605 + dry_run: bool,
606 +) -> Result<ProductCreated, String> {
607 + product.check().map_err(err)?;
608 + let package = product.package.as_str();
609 + let id = product.product_id.as_str();
610 + match client.get_product(package, id).await {
611 + Ok(_) => {
612 + return Err(format!(
613 + "{id} already exists in {package}; it was left alone"
614 + ))
615 + }
616 + Err(smbcloud_ascapi_play::Error::Api { status: 404, .. }) => {}
617 + Err(e) => return Err(err(e)),
618 + }
619 + let converted = client
620 + .convert_region_prices(package, price)
621 + .await
622 + .map_err(err)?;
623 + let body = product_body(product, &converted).map_err(err)?;
624 + if dry_run {
625 + return Ok(ProductCreated {
626 + dry_run,
627 + sent: body,
628 + stored: None,
629 + });
630 + }
631 + let version = regions_version(&converted).map_err(err)?;
632 + client
633 + .upsert_product(package, id, &body, &version)
634 + .await
635 + .map_err(err)?;
636 + client
637 + .activate_purchase_option(package, id, &product.purchase_option_id)
638 + .await
639 + .map_err(err)?;
640 + let stored = client.get_product(package, id).await.map_err(err)?;
641 + let state = stored
642 + .pointer("/purchaseOptions/0/state")
643 + .and_then(|v| v.as_str());
644 + if state != Some("ACTIVE") {
645 + return Err(format!(
646 + "created {id}, but its purchase option is {} and not ACTIVE",
647 + state.unwrap_or("missing")
648 + ));
649 + }
650 + Ok(ProductCreated {
651 + dry_run,
652 + sent: body,
653 + stored: Some(stored),
654 + })
655 +}
656 +
657 #[cfg(test)]
658 mod tests {
659 use super::*;
crates/play/src/client.rs
+116
@@ -24,6 +24,19 @@ pub(crate) fn edits_path(package: &str, suffix: &str) -> String {
24 format!("/androidpublisher/v3/applications/{package}/edits{suffix}")
25 }
26
27 +/// Build `/androidpublisher/v3/applications/{package}/oneTimeProducts…`.
28 +pub(crate) fn products_path(package: &str, suffix: &str) -> String {
29 + format!("/androidpublisher/v3/applications/{package}/oneTimeProducts{suffix}")
30 +}
31 +
32 +/// `onetimeproducts.patch` is the one call in this resource whose path is
33 +/// all lowercase (`onetimeproducts`); get, list and the state changes use
34 +/// `oneTimeProducts`. Google's discovery document says so, and a wrong case is
35 +/// a 404 page from the front end.
36 +pub(crate) fn product_patch_path(package: &str, product_id: &str) -> String {
37 + format!("/androidpublisher/v3/applications/{package}/onetimeproducts/{product_id}")
38 +}
39 +
40 pub(crate) fn upload_path(package: &str, edit_id: &str, locale: &str, image: ImageType) -> String {
41 format!(
42 "/upload/androidpublisher/v3/applications/{package}/edits/{edit_id}/listings/{locale}/{}?uploadType=media",
@@ -257,6 +270,93 @@ impl PlayClient {
270 Ok(deleted.deleted.len())
271 }
272
273 + /// All one-time products of the app, as Play returns them.
274 + pub async fn list_products(&self, package: &str) -> Result<Vec<serde_json::Value>> {
275 + // An app with no products can answer with an empty body, not `{}`.
276 + let text = self
277 + .send(Method::GET, &products_path(package, ""), None)
278 + .await?
279 + .text()
280 + .await?;
281 + if text.trim().is_empty() {
282 + return Ok(Vec::new());
283 + }
284 + let page: serde_json::Value = serde_json::from_str(&text)?;
285 + Ok(page
286 + .get("oneTimeProducts")
287 + .and_then(|v| v.as_array())
288 + .cloned()
289 + .unwrap_or_default())
290 + }
291 +
292 + pub async fn get_product(&self, package: &str, product_id: &str) -> Result<serde_json::Value> {
293 + self.json(
294 + Method::GET,
295 + &products_path(package, &format!("/{product_id}")),
296 + None::<&()>,
297 + )
298 + .await
299 + }
300 +
301 + /// `pricing:convertRegionPrices`: one price in, a price for every region out.
302 + pub async fn convert_region_prices(
303 + &self,
304 + package: &str,
305 + price: &crate::product::Money,
306 + ) -> Result<serde_json::Value> {
307 + let path =
308 + format!("/androidpublisher/v3/applications/{package}/pricing:convertRegionPrices");
309 + self.json(
310 + Method::POST,
311 + &path,
312 + Some(&serde_json::json!({ "price": price.to_json() })),
313 + )
314 + .await
315 + }
316 +
317 + /// `onetimeproducts.patch` with `allowMissing`, so it creates the product
318 + /// when it does not exist. `regions_version` is the one the prices were
319 + /// converted against.
320 + pub async fn upsert_product(
321 + &self,
322 + package: &str,
323 + product_id: &str,
324 + body: &serde_json::Value,
325 + regions_version: &str,
326 + ) -> Result<serde_json::Value> {
327 + let path = format!(
328 + "{}?allowMissing=true&updateMask=listings,purchaseOptions&regionsVersion.version={}",
329 + product_patch_path(package, product_id),
330 + regions_version.replace('/', "%2F"),
331 + );
332 + self.json(Method::PATCH, &path, Some(body)).await
333 + }
334 +
335 + /// Activate one purchase option, which is what makes the product buyable.
336 + pub async fn activate_purchase_option(
337 + &self,
338 + package: &str,
339 + product_id: &str,
340 + purchase_option_id: &str,
341 + ) -> Result<serde_json::Value> {
342 + let path = format!(
343 + "{}:batchUpdateStates",
344 + products_path(package, &format!("/{product_id}/purchaseOptions"))
345 + );
346 + self.json(
347 + Method::POST,
348 + &path,
349 + Some(&serde_json::json!({ "requests": [{
350 + "activatePurchaseOptionRequest": {
351 + "packageName": package,
352 + "productId": product_id,
353 + "purchaseOptionId": purchase_option_id,
354 + }
355 + }]})),
356 + )
357 + .await
358 + }
359 +
360 pub async fn get_track(&self, package: &str, edit_id: &str, track: &str) -> Result<Track> {
361 self.json(
362 Method::GET,
@@ -313,6 +413,22 @@ mod tests {
413 );
414 }
415
416 + #[test]
417 + fn product_urls_use_the_one_time_products_resource() {
418 + assert_eq!(
419 + products_path("p", "/app.unlock"),
420 + "/androidpublisher/v3/applications/p/oneTimeProducts/app.unlock"
421 + );
422 + }
423 +
424 + #[test]
425 + fn the_product_patch_path_is_lowercase() {
426 + assert_eq!(
427 + product_patch_path("p", "app.unlock"),
428 + "/androidpublisher/v3/applications/p/onetimeproducts/app.unlock"
429 + );
430 + }
431 +
432 #[test]
433 fn uploads_use_the_upload_host_path_with_media_type() {
434 assert_eq!(
crates/play/src/error.rs
+4
@@ -28,6 +28,10 @@ pub enum Error {
28
29 #[error("Google Play API returned {status}: {detail}")]
30 Api { status: u16, detail: String },
31 +
32 + /// Input refused before anything was sent.
33 + #[error("{0}")]
34 + Invalid(String),
35 }
36
37 pub type Result<T> = std::result::Result<T, Error>;
crates/play/src/lib.rs
+2
@@ -12,6 +12,7 @@ pub mod client;
12 pub mod error;
13 pub mod image;
14 pub mod listing;
15 +pub mod product;
16 pub mod track;
17
18 pub use auth::ServiceAccount;
@@ -22,4 +23,5 @@ pub use listing::{
23 Listing, ListingFields, FULL_DESCRIPTION_MAX_LEN, RELEASE_NOTES_MAX_LEN,
24 SHORT_DESCRIPTION_MAX_LEN, TITLE_MAX_LEN,
25 };
26 +pub use product::{Money, NewProduct};
27 pub use track::{LocalizedText, PromotePlan, RolloutAction, RolloutPlan, Track, TrackRelease};
crates/play/src/product.rs new
+240
@@ -0,0 +1,240 @@
1 +//! One-time products ("in-app products") through the Play monetization API.
2 +//!
3 +//! These calls are not inside an edit: a product is changed directly and takes
4 +//! effect when its purchase option is activated. Prices are set per region, so
5 +//! a price in one currency is converted to every region first
6 +//! (`pricing:convertRegionPrices`), the way Play Console does it.
7 +
8 +use serde_json::{json, Value};
9 +
10 +use crate::error::{Error, Result};
11 +
12 +/// A price split the way the Play API wants it: whole units as a string, and
13 +/// nanos (billionths) as an integer.
14 +#[derive(Debug, Clone, PartialEq, Eq)]
15 +pub struct Money {
16 + pub currency: String,
17 + pub units: String,
18 + pub nanos: i32,
19 +}
20 +
21 +impl Money {
22 + /// Parse `4.99` (up to 9 decimals) in `currency`, for example `USD`.
23 + pub fn parse(currency: &str, amount: &str) -> Result<Self> {
24 + let invalid = || Error::Invalid(format!("not a price: {amount:?} (expected e.g. 4.99)"));
25 + let currency = currency.trim().to_ascii_uppercase();
26 + if currency.len() != 3 || !currency.chars().all(|c| c.is_ascii_alphabetic()) {
27 + return Err(Error::Invalid(format!(
28 + "not a currency code: {currency:?} (expected e.g. USD)"
29 + )));
30 + }
31 + let (whole, frac) = amount.trim().split_once('.').unwrap_or((amount.trim(), ""));
32 + if whole.is_empty()
33 + || !whole.chars().all(|c| c.is_ascii_digit())
34 + || frac.len() > 9
35 + || !frac.chars().all(|c| c.is_ascii_digit())
36 + {
37 + return Err(invalid());
38 + }
39 + let nanos: i32 = format!("{frac:0<9}").parse().map_err(|_| invalid())?;
40 + let units = whole.trim_start_matches('0');
41 + let units = if units.is_empty() { "0" } else { units };
42 + if units == "0" && nanos == 0 {
43 + return Err(Error::Invalid("the price must be above zero".to_string()));
44 + }
45 + Ok(Self {
46 + currency,
47 + units: units.to_string(),
48 + nanos,
49 + })
50 + }
51 +
52 + pub fn to_json(&self) -> Value {
53 + json!({ "currencyCode": self.currency, "units": self.units, "nanos": self.nanos })
54 + }
55 +}
56 +
57 +/// What a new one-time product says about itself.
58 +#[derive(Debug, Clone)]
59 +pub struct NewProduct {
60 + pub package: String,
61 + pub product_id: String,
62 + pub language: String,
63 + pub title: String,
64 + pub description: String,
65 + pub purchase_option_id: String,
66 +}
67 +
68 +pub const TITLE_MAX_LEN: usize = 55;
69 +pub const DESCRIPTION_MAX_LEN: usize = 200;
70 +
71 +impl NewProduct {
72 + pub fn check(&self) -> Result<()> {
73 + let id = &self.product_id;
74 + let id_ok = !id.is_empty()
75 + && id.len() <= 100
76 + && id
77 + .chars()
78 + .next()
79 + .is_some_and(|c| c.is_ascii_lowercase() || c.is_ascii_digit())
80 + && id.chars().all(|c| {
81 + c.is_ascii_lowercase() || c.is_ascii_digit() || matches!(c, '_' | '.' | '-')
82 + });
83 + if !id_ok {
84 + return Err(Error::Invalid(format!(
85 + "product id {id:?}: use lowercase letters, digits, _ . - (starting with a letter or digit)"
86 + )));
87 + }
88 + for (name, value, max) in [
89 + ("title", &self.title, TITLE_MAX_LEN),
90 + ("description", &self.description, DESCRIPTION_MAX_LEN),
91 + ] {
92 + let len = value.chars().count();
93 + if len == 0 || len > max {
94 + return Err(Error::Invalid(format!(
95 + "{name} must be 1 to {max} characters (got {len})"
96 + )));
97 + }
98 + }
99 + Ok(())
100 + }
101 +}
102 +
103 +/// The `OneTimeProduct` body: one listing and one purchase option, priced in
104 +/// every region from a `pricing:convertRegionPrices` answer.
105 +pub fn product_body(product: &NewProduct, converted: &Value) -> Result<Value> {
106 + let regions = converted
107 + .get("convertedRegionPrices")
108 + .and_then(Value::as_object)
109 + .filter(|m| !m.is_empty())
110 + .ok_or_else(|| Error::Invalid("Play returned no regional prices".to_string()))?;
111 + let mut configs: Vec<Value> = regions
112 + .iter()
113 + .filter_map(|(code, entry)| {
114 + let price = entry.get("price")?;
115 + Some(json!({ "regionCode": code, "price": price, "availability": "AVAILABLE" }))
116 + })
117 + .collect();
118 + configs.sort_by(|a, b| a["regionCode"].as_str().cmp(&b["regionCode"].as_str()));
119 +
120 + let mut option = json!({
121 + "purchaseOptionId": product.purchase_option_id,
122 + "buyOption": { "legacyCompatible": true, "multiQuantityEnabled": false },
123 + "regionalPricingAndAvailabilityConfigs": configs,
124 + });
125 + if let Some(other) = converted.get("convertedOtherRegionsPrice") {
126 + option["newRegionsConfig"] = json!({
127 + "usdPrice": other.get("usdPrice").cloned().unwrap_or(Value::Null),
128 + "eurPrice": other.get("eurPrice").cloned().unwrap_or(Value::Null),
129 + "availability": "AVAILABLE",
130 + });
131 + }
132 + Ok(json!({
133 + "packageName": product.package,
134 + "productId": product.product_id,
135 + "listings": [{
136 + "languageCode": product.language,
137 + "title": product.title,
138 + "description": product.description,
139 + }],
140 + "purchaseOptions": [option],
141 + }))
142 +}
143 +
144 +/// The regions version Play priced the conversion against, which the product
145 +/// write must quote back.
146 +pub fn regions_version(converted: &Value) -> Result<String> {
147 + converted
148 + .pointer("/regionVersion/version")
149 + .and_then(Value::as_str)
150 + .map(str::to_string)
151 + .ok_or_else(|| Error::Invalid("Play returned no regions version".to_string()))
152 +}
153 +
154 +#[cfg(test)]
155 +mod tests {
156 + use super::*;
157 +
158 + fn product() -> NewProduct {
159 + NewProduct {
160 + package: "com.example.app".into(),
161 + product_id: "app.unlock".into(),
162 + language: "en-GB".into(),
163 + title: "Unlock".into(),
164 + description: "Removes the limit.".into(),
165 + purchase_option_id: "buy".into(),
166 + }
167 + }
168 +
169 + #[test]
170 + fn prices_split_into_units_and_nanos() {
171 + let m = Money::parse("usd", "4.99").unwrap();
172 + assert_eq!(
173 + (m.currency.as_str(), m.units.as_str(), m.nanos),
174 + ("USD", "4", 990_000_000)
175 + );
176 + let m = Money::parse("USD", "5").unwrap();
177 + assert_eq!((m.units.as_str(), m.nanos), ("5", 0));
178 + let m = Money::parse("USD", "0.5").unwrap();
179 + assert_eq!((m.units.as_str(), m.nanos), ("0", 500_000_000));
180 + }
181 +
182 + #[test]
183 + fn bad_prices_are_refused() {
184 + for bad in ["", "abc", "-1", "4.9.9", "0", "0.0", "1.1234567891", ".5"] {
185 + assert!(Money::parse("USD", bad).is_err(), "{bad:?}");
186 + }
187 + assert!(Money::parse("US", "1").is_err());
188 + assert!(Money::parse("U5D", "1").is_err());
189 + }
190 +
191 + #[test]
192 + fn product_ids_and_text_are_checked() {
193 + assert!(product().check().is_ok());
194 + let mut p = product();
195 + p.product_id = "Bad Id".into();
196 + assert!(p.check().is_err());
197 + let mut p = product();
198 + p.title = "x".repeat(56);
199 + assert!(p.check().is_err());
200 + let mut p = product();
201 + p.description = String::new();
202 + assert!(p.check().is_err());
203 + }
204 +
205 + #[test]
206 + fn the_body_prices_every_region_and_keeps_new_regions_in() {
207 + let converted = json!({
208 + "regionVersion": { "version": "2022/02" },
209 + "convertedRegionPrices": {
210 + "US": { "price": { "currencyCode": "USD", "units": "4", "nanos": 990000000 } },
211 + "GB": { "price": { "currencyCode": "GBP", "units": "3", "nanos": 990000000 } }
212 + },
213 + "convertedOtherRegionsPrice": {
214 + "usdPrice": { "currencyCode": "USD", "units": "4", "nanos": 990000000 },
215 + "eurPrice": { "currencyCode": "EUR", "units": "4", "nanos": 990000000 }
216 + }
217 + });
218 + let body = product_body(&product(), &converted).unwrap();
219 + assert_eq!(body["productId"], "app.unlock");
220 + let option = &body["purchaseOptions"][0];
221 + assert_eq!(option["buyOption"]["legacyCompatible"], true);
222 + let regions = option["regionalPricingAndAvailabilityConfigs"]
223 + .as_array()
224 + .unwrap();
225 + assert_eq!(regions.len(), 2);
226 + assert_eq!(regions[0]["regionCode"], "GB");
227 + assert_eq!(regions[0]["availability"], "AVAILABLE");
228 + assert_eq!(
229 + option["newRegionsConfig"]["eurPrice"]["currencyCode"],
230 + "EUR"
231 + );
232 + assert_eq!(regions_version(&converted).unwrap(), "2022/02");
233 + }
234 +
235 + #[test]
236 + fn an_empty_conversion_is_an_error() {
237 + assert!(product_body(&product(), &json!({ "convertedRegionPrices": {} })).is_err());
238 + assert!(regions_version(&json!({})).is_err());
239 + }
240 +}