diff --git a/docs/guides/product-feed.md b/docs/guides/product-feed.md new file mode 100644 index 000000000..e4fefa285 --- /dev/null +++ b/docs/guides/product-feed.md @@ -0,0 +1,52 @@ +# Product Feed + +The **Product Feed** addon publishes your store catalogue as JSON, so your website can show the same prices, +options and addons the order form charges, without copying them by hand. + +## Turn it on + +1. Go to **Extensions → Manage extensions**, find **Product Feed** and activate it. +2. Open it. The page shows the feed address and the address of each published group. + +The feed is at `https:///feed/products.json`. It needs no login: it shows only what anyone can already +see in the store. + +## What it contains + +- the groups you publish, each with its name, slug, headline and tagline; +- their products that are neither hidden nor retired: name, slug, description (as written and as HTML), whether tax + applies, the order link, and the price and setup fee of each billing cycle the product is sold on; +- the product's configurable options and their values that are not hidden, priced on the product's cycles (a value + not sold on a cycle has no price for it); +- the product addons offered with it, priced the same way. + +Prices are in the default currency, the one the store sells in, as you entered them (before tax). + +## Parameters + +| Parameter | Example | Effect | +| --- | --- | --- | +| `group` | `?group=backup` | only that group | +| `product` | `?product=backup-500` | only that product | +| `lang` | `?lang=it` | descriptions in that language, order links that open the store in it | + +## Settings + +- **Groups to publish**: group slugs, separated by commas. Empty publishes every group the store lists. A hidden + group can be published by naming it here, for a landing page that is not in the store menu. +- **Websites allowed to read it from the browser**: one address per line (`https://www.example.com`), or `*`. + Needed only when JavaScript on another domain reads the feed. A site that reads it on its server, or when its + pages are built, needs nothing here. +- **Cache (minutes)**: how long an answer is kept, 10 by default. A price change shows in the feed after this time. + `0` turns the cache off. + +The feed answers at most 60 requests a minute from the same address. + +## Using it on a website + +The simplest and most robust way is to read the feed when the site is built, and write the prices into the pages: +the site stays fast and keeps working if PNLCS is unreachable. Build again after a price change, or every night. + +```sh +curl -s 'https://billing.example.com/feed/products.json?group=backup&lang=en' -o products.json +``` diff --git a/mkdocs.yml b/mkdocs.yml index ec2daa369..1459bdc47 100644 --- a/mkdocs.yml +++ b/mkdocs.yml @@ -85,6 +85,7 @@ nav: - Guides: - Configure Email: guides/configure-email.md - Payment Gateways: guides/payment-gateways.md + - Product Feed: guides/product-feed.md - Connect a Server: guides/connect-a-server.md - "Plesk: Existing Accounts & Resellers": guides/plesk-existing-accounts.md - Live Servers: guides/live-servers.md diff --git a/modules/Addons/ProductFeed/Http/Controllers/ProductFeedController.php b/modules/Addons/ProductFeed/Http/Controllers/ProductFeedController.php new file mode 100644 index 000000000..545003004 --- /dev/null +++ b/modules/Addons/ProductFeed/Http/Controllers/ProductFeedController.php @@ -0,0 +1,75 @@ +validate([ + 'group' => ['nullable', 'string', 'max:255'], + 'product' => ['nullable', 'string', 'max:255'], + 'lang' => ['nullable', 'string', 'max:10', 'regex:/^[a-z]{2}(-[a-z]{2})?$/'], + ]); + + $language = isset($validated['lang']) && File::isDirectory(lang_path($validated['lang'])) ? $validated['lang'] : null; + $minutes = max(0, (int) AddonSetting::getSetting(ProductFeed::ADDON, 'cache_minutes', 10)); + $key = 'productfeed:'.sha1(json_encode([$validated['group'] ?? null, $validated['product'] ?? null, $language])); + + $build = function () use ($feed, $validated, $language): array { + $previous = app()->getLocale(); + if ($language !== null) { + app()->setLocale($language); + } + + try { + return ['generated_at' => now()->toIso8601String()] + + $feed->build($validated['group'] ?? null, $validated['product'] ?? null, $language); + } finally { + app()->setLocale($previous); + } + }; + + $data = $minutes > 0 ? Cache::remember($key, now()->addMinutes($minutes), $build) : $build(); + + return response()->json($data, 200, $this->corsHeaders($request) + [ + 'Cache-Control' => 'public, max-age='.($minutes * 60), + ], JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES); + } + + /** + * The origins allowed to read the feed from a browser. A site that builds + * its pages on the server needs none of this; JavaScript on another domain + * does. + * + * @return array + */ + private function corsHeaders(Request $request): array + { + $allowed = ProductFeed::listSetting('allowed_origins'); + $origin = (string) $request->headers->get('Origin', ''); + + if (in_array('*', $allowed, true)) { + return ['Access-Control-Allow-Origin' => '*']; + } + + if ($origin !== '' && in_array(rtrim($origin, '/'), array_map(fn (string $value) => rtrim($value, '/'), $allowed), true)) { + return ['Access-Control-Allow-Origin' => $origin, 'Vary' => 'Origin']; + } + + return []; + } +} diff --git a/modules/Addons/ProductFeed/ProductFeedModule.php b/modules/Addons/ProductFeed/ProductFeedModule.php new file mode 100644 index 000000000..8377d80d2 --- /dev/null +++ b/modules/Addons/ProductFeed/ProductFeedModule.php @@ -0,0 +1,100 @@ + true, 'message' => 'Product Feed activated']; + } + + /** @return array{success: bool, message: string} */ + public function deactivate(): array + { + return ['success' => true, 'message' => 'Product Feed deactivated']; + } + + /** @return list */ + public function config(): array + { + return [ + ['name' => 'groups', 'label' => __('product-feed::addon.groups'), 'type' => 'text', 'default' => '', + 'hint' => __('product-feed::addon.groups_hint')], + ['name' => 'allowed_origins', 'label' => __('product-feed::addon.allowed_origins'), 'type' => 'textarea', 'default' => '', + 'hint' => __('product-feed::addon.allowed_origins_hint')], + ['name' => 'cache_minutes', 'label' => __('product-feed::addon.cache_minutes'), 'type' => 'text', 'default' => '10', + 'hint' => __('product-feed::addon.cache_minutes_hint')], + ]; + } + + /** @return list */ + public function sidebar(): array + { + return []; + } + + /** @return array{success: bool, message: string} */ + public function upgrade(string $fromVersion): array + { + return ['success' => true, 'message' => 'Upgraded from '.e($fromVersion)]; + } + + public function output(Request $request): string + { + $url = url('feed/products.json'); + $groups = app(ProductFeed::class)->publishedGroups(); + + $html = '

'.e(__('product-feed::addon.intro')).'

'; + $html .= '

'.e($url).'

'; + $html .= '

'.e(__('product-feed::addon.parameters')).'

'; + $html .= '
'.e(__('product-feed::addon.published_groups')).'
'; + + if ($groups->isEmpty()) { + return $html.'

'.e(__('product-feed::addon.no_groups')).'

'; + } + + $html .= '
    '; + foreach ($groups as $group) { + $groupUrl = $url.'?group='.rawurlencode((string) $group->slug); + $html .= '
  • '.e((string) $group->name).' — '.e($groupUrl).'
  • '; + } + + return $html.'
'; + } +} diff --git a/modules/Addons/ProductFeed/ProductFeedServiceProvider.php b/modules/Addons/ProductFeed/ProductFeedServiceProvider.php new file mode 100644 index 000000000..ce08e0f22 --- /dev/null +++ b/modules/Addons/ProductFeed/ProductFeedServiceProvider.php @@ -0,0 +1,14 @@ +loadRoutesFrom(__DIR__.'/routes.php'); + $this->loadTranslationsFrom(__DIR__.'/lang', 'product-feed'); + } +} diff --git a/modules/Addons/ProductFeed/Services/ProductFeed.php b/modules/Addons/ProductFeed/Services/ProductFeed.php new file mode 100644 index 000000000..7c487fc1a --- /dev/null +++ b/modules/Addons/ProductFeed/Services/ProductFeed.php @@ -0,0 +1,189 @@ +>} + */ + public function build(?string $groupSlug = null, ?string $productSlug = null, ?string $language = null): array + { + $currency = Currency::getDefault(); + + $groups = $this->publishedGroups() + ->when($groupSlug !== null, fn (Collection $groups) => $groups->where('slug', $groupSlug)) + ->map(fn (ProductGroup $group) => $this->group($group, $productSlug, $language)) + ->filter(fn (array $group) => $group['products'] !== []) + ->values() + ->all(); + + return [ + 'currency' => $currency ? ['code' => (string) $currency->code, 'prefix' => (string) $currency->prefix, 'suffix' => (string) $currency->suffix] : null, + 'groups' => $groups, + ]; + } + + /** + * The groups the operator publishes: those named in the settings, or every + * group the store lists when none is named. + * + * @return Collection + */ + public function publishedGroups(): Collection + { + $named = self::listSetting('groups'); + $query = ProductGroup::query()->orderBy('sort_order')->orderBy('id'); + + return $named === [] + ? $query->where('hidden', false)->get() + : $query->whereIn('slug', $named)->get(); + } + + /** + * A comma or newline separated setting, as a list of trimmed values. + * + * @return list + */ + public static function listSetting(string $key): array + { + $raw = (string) AddonSetting::getSetting(self::ADDON, $key, ''); + + return array_values(array_filter(array_map('trim', preg_split('/[\s,]+/', $raw) ?: []), fn (string $value) => $value !== '')); + } + + /** + * @return array + */ + private function group(ProductGroup $group, ?string $productSlug, ?string $language): array + { + $products = Product::query() + ->with(['pricing', 'terms', 'translations']) + ->active() + ->where('group_id', $group->id) + ->when($productSlug !== null, fn ($query) => $query->where('slug', $productSlug)) + ->orderBy('sort_order') + ->orderBy('id') + ->get(); + + return [ + 'name' => (string) $group->name, + 'slug' => (string) $group->slug, + 'headline' => (string) $group->headline, + 'tagline' => (string) $group->tagline, + 'products' => $products->map(fn (Product $product) => $this->product($product, $language))->values()->all(), + ]; + } + + /** + * @return array + */ + private function product(Product $product, ?string $language): array + { + $prices = []; + foreach ($product->pricedCycles() as $cycle => $price) { + $prices[$cycle] = ['price' => $price, 'setup_fee' => $product->setupFeeFor($cycle)]; + } + $cycles = array_keys($prices); + + return [ + 'name' => (string) $product->name, + 'slug' => (string) $product->slug, + 'pay_type' => (string) $product->pay_type, + 'description' => $product->localizedDescription(), + 'description_html' => $product->descriptionHtml(), + 'taxed' => (bool) $product->tax, + 'order_url' => route('client.store.configure', array_filter(['product' => $product->slug, 'lang' => $language])), + 'prices' => $prices, + 'options' => $this->configOptions->groupsFor($product) + ->flatMap(fn ($group) => $group->options) + ->map(fn (ConfigOption $option) => $this->option($option, $cycles)) + ->values() + ->all(), + 'addons' => $this->addons->availableFor($product) + ->map(fn (ProductAddon $addon) => $this->addon($addon, $cycles)) + ->filter(fn (array $addon) => $addon['prices'] !== []) + ->values() + ->all(), + ]; + } + + /** + * @param list $cycles + * @return array + */ + private function option(ConfigOption $option, array $cycles): array + { + return [ + 'name' => $option->displayName(), + 'type' => (string) $option->option_type, + 'choices' => $option->subs + ->map(fn (ConfigOptionSub $sub) => [ + 'name' => $sub->displayName(), + 'prices' => $this->pricesOf($cycles, fn (string $cycle) => $sub->offeredOn($cycle) ? $sub->priceFor($cycle) : null), + ]) + ->values() + ->all(), + ]; + } + + /** + * @param list $cycles + * @return array + */ + private function addon(ProductAddon $addon, array $cycles): array + { + return [ + 'name' => (string) $addon->name, + 'description' => (string) $addon->description, + 'prices' => $this->pricesOf($cycles, fn (string $cycle) => $addon->offeredOn($cycle) ? $addon->priceFor($cycle) : null), + ]; + } + + /** + * The price on each of the product's cycles, leaving out the cycles where + * the item is not sold. + * + * @param list $cycles + * @param callable(string): ?float $priceOn + * @return array + */ + private function pricesOf(array $cycles, callable $priceOn): array + { + $prices = []; + foreach ($cycles as $cycle) { + $price = $priceOn($cycle); + if ($price !== null) { + $prices[$cycle] = $price; + } + } + + return $prices; + } +} diff --git a/modules/Addons/ProductFeed/lang/de/addon.php b/modules/Addons/ProductFeed/lang/de/addon.php new file mode 100644 index 000000000..e011ab6b4 --- /dev/null +++ b/modules/Addons/ProductFeed/lang/de/addon.php @@ -0,0 +1,14 @@ + 'Der Shop-Katalog als JSON für Ihre Website: Produkte, die weder ausgeblendet noch eingestellt sind, ihre Preise in der Standardwährung, Optionen und Add-ons. Jeder kann ihn lesen, so wie jeder den Shop sehen kann.', + 'parameters' => 'Parameter: group=, product=, lang= (Beschreibungen und Bestelllinks in dieser Sprache).', + 'published_groups' => 'Veröffentlichte Gruppen', + 'no_groups' => 'Keine Gruppe veröffentlicht.', + 'groups' => 'Zu veröffentlichende Gruppen', + 'groups_hint' => 'Gruppen-Slugs, durch Kommas getrennt. Leer: alle Gruppen, die der Shop anzeigt.', + 'allowed_origins' => 'Websites, die ihn im Browser lesen dürfen', + 'allowed_origins_hint' => 'Eine Adresse pro Zeile, zum Beispiel https://www.example.com, oder * für alle. Nicht nötig, wenn Ihre Website den Feed auf dem Server oder beim Erstellen liest.', + 'cache_minutes' => 'Cache (Minuten)', + 'cache_minutes_hint' => 'Wie lange eine Antwort behalten wird, bevor sie neu erstellt wird. Preisänderungen erscheinen nach dieser Zeit. 0 schaltet den Cache aus.', +]; diff --git a/modules/Addons/ProductFeed/lang/en/addon.php b/modules/Addons/ProductFeed/lang/en/addon.php new file mode 100644 index 000000000..dc9e573eb --- /dev/null +++ b/modules/Addons/ProductFeed/lang/en/addon.php @@ -0,0 +1,14 @@ + 'The store catalogue as JSON, for your website: products that are not hidden or retired, their prices in the default currency, options and addons. Anyone can read it, as anyone can read the store.', + 'parameters' => 'Parameters: group=, product=, lang= (descriptions and order links in that language).', + 'published_groups' => 'Published groups', + 'no_groups' => 'No group is published.', + 'groups' => 'Groups to publish', + 'groups_hint' => 'Group slugs, separated by commas. Empty: every group the store lists.', + 'allowed_origins' => 'Websites allowed to read it from the browser', + 'allowed_origins_hint' => 'One address per line, for example https://www.example.com, or * for any. Not needed when your site reads the feed on the server or at build time.', + 'cache_minutes' => 'Cache (minutes)', + 'cache_minutes_hint' => 'How long an answer is kept before it is built again. Price changes show after this time. 0 turns the cache off.', +]; diff --git a/modules/Addons/ProductFeed/lang/it/addon.php b/modules/Addons/ProductFeed/lang/it/addon.php new file mode 100644 index 000000000..d4bba6ffd --- /dev/null +++ b/modules/Addons/ProductFeed/lang/it/addon.php @@ -0,0 +1,14 @@ + 'Il catalogo del negozio in JSON, per il tuo sito: i prodotti non nascosti né ritirati, i prezzi nella valuta predefinita, le opzioni e gli addon. Chiunque può leggerlo, come chiunque può vedere il negozio.', + 'parameters' => 'Parametri: group=, product=, lang= (descrizioni e link d\'ordine in quella lingua).', + 'published_groups' => 'Gruppi pubblicati', + 'no_groups' => 'Nessun gruppo pubblicato.', + 'groups' => 'Gruppi da pubblicare', + 'groups_hint' => 'Slug dei gruppi, separati da virgole. Vuoto: tutti i gruppi elencati nel negozio.', + 'allowed_origins' => 'Siti che possono leggerlo dal browser', + 'allowed_origins_hint' => 'Un indirizzo per riga, per esempio https://www.example.com, oppure * per tutti. Non serve se il tuo sito legge il feed dal server o quando viene generato.', + 'cache_minutes' => 'Cache (minuti)', + 'cache_minutes_hint' => 'Per quanto tempo una risposta viene tenuta prima di essere ricostruita. Le modifiche ai prezzi si vedono dopo questo tempo. 0 disattiva la cache.', +]; diff --git a/modules/Addons/ProductFeed/lang/pl/addon.php b/modules/Addons/ProductFeed/lang/pl/addon.php new file mode 100644 index 000000000..88851435e --- /dev/null +++ b/modules/Addons/ProductFeed/lang/pl/addon.php @@ -0,0 +1,14 @@ + 'Katalog sklepu w formacie JSON dla Twojej strony: produkty, które nie są ukryte ani wycofane, ich ceny w walucie domyślnej, opcje i dodatki. Każdy może go odczytać, tak jak każdy może zobaczyć sklep.', + 'parameters' => 'Parametry: group=, product=, lang= (opisy i linki do zamówienia w tym języku).', + 'published_groups' => 'Opublikowane grupy', + 'no_groups' => 'Żadna grupa nie jest opublikowana.', + 'groups' => 'Grupy do opublikowania', + 'groups_hint' => 'Slugi grup oddzielone przecinkami. Puste: wszystkie grupy widoczne w sklepie.', + 'allowed_origins' => 'Strony, które mogą go odczytać z przeglądarki', + 'allowed_origins_hint' => 'Jeden adres w wierszu, na przykład https://www.example.com, lub * dla wszystkich. Niepotrzebne, gdy strona odczytuje feed na serwerze lub podczas budowania.', + 'cache_minutes' => 'Pamięć podręczna (minuty)', + 'cache_minutes_hint' => 'Jak długo odpowiedź jest przechowywana, zanim zostanie zbudowana ponownie. Zmiany cen pojawiają się po tym czasie. 0 wyłącza pamięć podręczną.', +]; diff --git a/modules/Addons/ProductFeed/lang/tr/addon.php b/modules/Addons/ProductFeed/lang/tr/addon.php new file mode 100644 index 000000000..2b1c9b086 --- /dev/null +++ b/modules/Addons/ProductFeed/lang/tr/addon.php @@ -0,0 +1,14 @@ + 'Web siteniz için mağaza kataloğu JSON olarak: gizli veya kullanımdan kaldırılmış olmayan ürünler, varsayılan para birimindeki fiyatları, seçenekleri ve eklentileri. Mağaza gibi herkes okuyabilir.', + 'parameters' => 'Parametreler: group=, product=<ürün kısa adı>, lang= (açıklamalar ve sipariş bağlantıları o dilde).', + 'published_groups' => 'Yayınlanan gruplar', + 'no_groups' => 'Yayınlanan grup yok.', + 'groups' => 'Yayınlanacak gruplar', + 'groups_hint' => 'Grup kısa adları, virgülle ayrılmış. Boş: mağazanın listelediği tüm gruplar.', + 'allowed_origins' => 'Tarayıcıdan okuyabilecek web siteleri', + 'allowed_origins_hint' => 'Her satıra bir adres, örneğin https://www.example.com, ya da herkes için *. Siteniz akışı sunucuda veya derleme sırasında okuyorsa gerekmez.', + 'cache_minutes' => 'Önbellek (dakika)', + 'cache_minutes_hint' => 'Bir yanıtın yeniden oluşturulmadan önce ne kadar tutulacağı. Fiyat değişiklikleri bu süreden sonra görünür. 0 önbelleği kapatır.', +]; diff --git a/modules/Addons/ProductFeed/lang/zh/addon.php b/modules/Addons/ProductFeed/lang/zh/addon.php new file mode 100644 index 000000000..0d95b4292 --- /dev/null +++ b/modules/Addons/ProductFeed/lang/zh/addon.php @@ -0,0 +1,14 @@ + '以 JSON 格式提供的商店目录,供您的网站使用:未隐藏且未停售的产品、默认货币的价格、选项和附加组件。与商店一样,任何人都可以读取。', + 'parameters' => '参数:group=<分组别名>,product=<产品别名>,lang=<语言代码>(该语言的描述和订购链接)。', + 'published_groups' => '已发布的分组', + 'no_groups' => '没有已发布的分组。', + 'groups' => '要发布的分组', + 'groups_hint' => '分组别名,用逗号分隔。留空:商店中列出的所有分组。', + 'allowed_origins' => '允许从浏览器读取的网站', + 'allowed_origins_hint' => '每行一个地址,例如 https://www.example.com,或用 * 表示全部。如果您的网站在服务器上或构建时读取该源,则无需设置。', + 'cache_minutes' => '缓存(分钟)', + 'cache_minutes_hint' => '响应在重新生成前保留的时间。价格变更会在此时间后显示。0 表示关闭缓存。', +]; diff --git a/modules/Addons/ProductFeed/routes.php b/modules/Addons/ProductFeed/routes.php new file mode 100644 index 000000000..aa06de873 --- /dev/null +++ b/modules/Addons/ProductFeed/routes.php @@ -0,0 +1,8 @@ +get('feed/products.json', [ProductFeedController::class, 'products']) + ->name('productfeed.products'); diff --git a/tests/Feature/ProductFeedTest.php b/tests/Feature/ProductFeedTest.php new file mode 100644 index 000000000..b5b6fe2bc --- /dev/null +++ b/tests/Feature/ProductFeedTest.php @@ -0,0 +1,189 @@ +forgetInstance(AddonManager::class); + (new AddonServiceProvider(app()))->boot(); + app('router')->getRoutes()->refreshNameLookups(); +} + +/** @param array $prices */ +function feedPrice(string $type, int $relId, array $prices): void +{ + $cycles = ['monthly', 'quarterly', 'semiannually', 'annually', 'biennially', 'triennially']; + Pricing::create($prices + ['type' => $type, 'rel_id' => $relId, 'currency_id' => Currency::getDefault()->id] + + array_fill_keys($cycles, -1) + array_fill_keys(array_map(fn ($c) => $c.'_setup', $cycles), 0)); +} + +/** A group "Backup" with a plan sold monthly and yearly, one option and one addon. */ +function feedCatalogue(): array +{ + Currency::query()->update(['is_default' => false]); + Currency::factory()->default()->create(['code' => 'EUR', 'prefix' => '€', 'suffix' => '']); + + $group = ProductGroup::factory()->create(['name' => 'Backup', 'slug' => 'feed-backup', 'hidden' => false, 'headline' => 'Off-site copies']); + $plan = Product::factory()->create(['group_id' => $group->id, 'name' => 'Backup 500', 'slug' => 'feed-backup-500', 'description' => 'Plain **500 GB**.', 'tax' => true]); + feedPrice('product', $plan->id, ['monthly' => 24, 'annually' => 240, 'annually_setup' => 10]); + + $options = ConfigOptionGroup::create(['name' => 'Backup 500 extras']); + ConfigOptionLink::create(['group_id' => $options->id, 'product_id' => $plan->id]); + $space = ConfigOption::create(['group_id' => $options->id, 'option_name' => 'addon|Extra space', 'option_type' => 'dropdown', 'sort_order' => 1]); + $none = ConfigOptionSub::create(['config_id' => $space->id, 'option_name' => 'none|None', 'sort_order' => 0]); + $hundred = ConfigOptionSub::create(['config_id' => $space->id, 'option_name' => 'Space +100 GB|+100 GB', 'sort_order' => 1]); + $yearOnly = ConfigOptionSub::create(['config_id' => $space->id, 'option_name' => 'Space +300 GB|+300 GB', 'sort_order' => 2]); + ConfigOptionSub::create(['config_id' => $space->id, 'option_name' => 'Secret|Not for sale', 'sort_order' => 3, 'hidden' => true]); + feedPrice(ConfigOptionSub::PRICING_TYPE, $none->id, ['monthly' => 0, 'annually' => 0]); + feedPrice(ConfigOptionSub::PRICING_TYPE, $hundred->id, ['monthly' => 3, 'annually' => 30]); + feedPrice(ConfigOptionSub::PRICING_TYPE, $yearOnly->id, ['annually' => 60]); + + $addon = ProductAddon::create(['name' => 'Priority support', 'description' => 'Answer within 4 hours.', 'packages' => (string) $plan->id, 'hidden' => false, 'retired' => false, 'sort_order' => 1]); + feedPrice('addon', $addon->id, ['annually' => 50]); + + return compact('group', 'plan'); +} + +it('is not served while the addon is inactive', function () { + $this->getJson('/feed/products.json')->assertNotFound(); +}); + +it('shows the admin the feed address of every published group', function () { + feedCatalogue(); + bootProductFeedAddon(); + + $this->actingAs(Admin::factory()->create(), 'admin') + ->get(route('admin.config.addons.modules.show', 'productfeed')) + ->assertOk() + ->assertSee(url('feed/products.json').'?group=feed-backup') + ->assertSee('Groups to publish'); +}); + +it('publishes the visible products with their prices, options and addons', function () { + ['group' => $group] = feedCatalogue(); + Product::factory()->create(['group_id' => $group->id, 'slug' => 'feed-hidden', 'hidden' => true]); + Product::factory()->create(['group_id' => $group->id, 'slug' => 'feed-retired', 'retired' => true]); + $hiddenGroup = ProductGroup::factory()->create(['slug' => 'feed-internal', 'hidden' => true]); + Product::factory()->create(['group_id' => $hiddenGroup->id, 'slug' => 'feed-internal-plan']); + bootProductFeedAddon(); + + $response = $this->getJson('/feed/products.json?group=feed-backup')->assertOk(); + + expect($response->json('currency'))->toBe(['code' => 'EUR', 'prefix' => '€', 'suffix' => '']) + ->and($response->json('groups'))->toHaveCount(1) + ->and($response->json('groups.0.headline'))->toBe('Off-site copies') + ->and(array_column($response->json('groups.0.products'), 'slug'))->toBe(['feed-backup-500']); + + $plan = $response->json('groups.0.products.0'); + expect($plan['prices'])->toEqual(['monthly' => ['price' => 24, 'setup_fee' => 0], 'annually' => ['price' => 240, 'setup_fee' => 10]]) + ->and($plan['taxed'])->toBeTrue() + ->and($plan['description_html'])->toContain('500 GB') + ->and($plan['order_url'])->toBe(route('client.store.configure', ['product' => 'feed-backup-500'])) + ->and($plan['options'][0]['name'])->toBe('Extra space') + ->and($plan['options'][0]['choices'])->toEqual([ + ['name' => 'None', 'prices' => ['monthly' => 0, 'annually' => 0]], + ['name' => '+100 GB', 'prices' => ['monthly' => 3, 'annually' => 30]], + ['name' => '+300 GB', 'prices' => ['annually' => 60]], + ]) + ->and($plan['addons'])->toEqual([['name' => 'Priority support', 'description' => 'Answer within 4 hours.', 'prices' => ['annually' => 50]]]); + + expect($this->getJson('/feed/products.json?group=feed-internal')->json('groups'))->toBe([]); +}); + +it('publishes only the groups named in the settings, hidden ones included', function () { + feedCatalogue(); + $landing = ProductGroup::factory()->create(['slug' => 'feed-landing', 'hidden' => true]); + $product = Product::factory()->create(['group_id' => $landing->id, 'slug' => 'feed-landing-plan']); + feedPrice('product', $product->id, ['annually' => 99]); + AddonSetting::setSetting('productfeed', 'groups', 'feed-landing'); + bootProductFeedAddon(); + + $groups = $this->getJson('/feed/products.json')->assertOk()->json('groups'); + + expect(array_column($groups, 'slug'))->toBe(['feed-landing']); +}); + +it('narrows the feed to one product', function () { + ['group' => $group] = feedCatalogue(); + Product::factory()->create(['group_id' => $group->id, 'slug' => 'feed-backup-1t']); + bootProductFeedAddon(); + + $products = $this->getJson('/feed/products.json?product=feed-backup-500')->json('groups.0.products'); + + expect(array_column($products, 'slug'))->toBe(['feed-backup-500']); +}); + +it('gives the description and the order link in the language asked for', function () { + ['plan' => $plan] = feedCatalogue(); + ProductTranslation::create(['product_id' => $plan->id, 'language' => 'it', 'description' => 'Semplice, 500 GB.']); + bootProductFeedAddon(); + + $product = $this->getJson('/feed/products.json?group=feed-backup&lang=it')->json('groups.0.products.0'); + + expect($product['description'])->toBe('Semplice, 500 GB.') + ->and($product['order_url'])->toBe(route('client.store.configure', ['product' => 'feed-backup-500', 'lang' => 'it'])) + ->and(app()->getLocale())->not->toBe('it'); +}); + +it('ignores a language the panel does not have', function () { + feedCatalogue(); + bootProductFeedAddon(); + + $product = $this->getJson('/feed/products.json?group=feed-backup&lang=xx')->assertOk()->json('groups.0.products.0'); + + expect($product['description'])->toBe('Plain **500 GB**.') + ->and($product['order_url'])->toBe(route('client.store.configure', ['product' => 'feed-backup-500'])); +}); + +it('refuses a malformed language code', function () { + bootProductFeedAddon(); + + $this->getJson('/feed/products.json?lang=../../etc')->assertUnprocessable()->assertJsonValidationErrors('lang'); +}); + +it('lets only the configured websites read it from a browser', function () { + feedCatalogue(); + AddonSetting::setSetting('productfeed', 'allowed_origins', "https://www.example.com\nhttps://shop.example.org"); + bootProductFeedAddon(); + + $this->getJson('/feed/products.json', ['Origin' => 'https://www.example.com']) + ->assertHeader('Access-Control-Allow-Origin', 'https://www.example.com'); + $this->getJson('/feed/products.json', ['Origin' => 'https://evil.example.net']) + ->assertHeaderMissing('Access-Control-Allow-Origin'); +}); + +it('keeps an answer for the cache minutes, so a price change shows afterwards', function () { + ['plan' => $plan] = feedCatalogue(); + Cache::flush(); + AddonSetting::setSetting('productfeed', 'cache_minutes', '5'); + bootProductFeedAddon(); + + $this->getJson('/feed/products.json?group=feed-backup')->assertHeader('Cache-Control', 'max-age=300, public'); + Pricing::where('type', 'product')->where('rel_id', $plan->id)->update(['annually' => 260]); + + expect($this->getJson('/feed/products.json?group=feed-backup')->json('groups.0.products.0.prices.annually.price'))->toEqual(240); + + $this->travel(6)->minutes(); + expect($this->getJson('/feed/products.json?group=feed-backup')->json('groups.0.products.0.prices.annually.price'))->toEqual(260); +});