proxy-platform 0.3.0__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.

Potentially problematic release.


This version of proxy-platform might be problematic. Click here for more details.

@@ -0,0 +1,509 @@
1
+ """Order and payment management commands."""
2
+
3
+ import typer
4
+ from rich.console import Console
5
+ from rich.prompt import Prompt
6
+ from rich.table import Table
7
+
8
+ from ..client import APIClient
9
+ from ..config import get_current_environment, get_default_api_type
10
+
11
+ app = typer.Typer()
12
+ console = Console()
13
+
14
+
15
+ @app.command(name="list")
16
+ def list_orders(
17
+ limit: int = typer.Option(10, "--limit", "-l", help="Number of orders to fetch"),
18
+ api: str | None = typer.Option(None, "--api", "-a", help="API type (admin or user)"),
19
+ ) -> None:
20
+ """List user orders."""
21
+ if api is None:
22
+ api = get_default_api_type()
23
+
24
+ try:
25
+ client = APIClient(api_type=api)
26
+ response = client.get(f"/api/v1/users/orders?limit={limit}")
27
+
28
+ if response.status_code == 200:
29
+ data = response.json()
30
+ # API returns {"orders": [...]} not {"items": [...]}
31
+ orders = data.get("orders", data.get("items", []))
32
+
33
+ if not orders:
34
+ console.print("[yellow]No orders found[/yellow]")
35
+ return
36
+
37
+ total = data.get("total_count", data.get("total", len(orders)))
38
+ table = Table(title=f"Orders ({len(orders)} of {total})")
39
+ table.add_column("ID", style="cyan", no_wrap=True)
40
+ table.add_column("Description", style="white")
41
+ table.add_column("Amount", style="green")
42
+ table.add_column("Status", style="yellow")
43
+ table.add_column("Date", style="blue")
44
+
45
+ for order in orders:
46
+ # Handle amount which might be a string
47
+ amount = order.get("amount", order.get("total_amount", 0))
48
+ try:
49
+ amount_float = float(amount) if amount else 0
50
+ except (ValueError, TypeError):
51
+ amount_float = 0
52
+
53
+ table.add_row(
54
+ str(order.get("id", "N/A"))[:8] + "...",
55
+ order.get("description", "N/A"),
56
+ f"{order.get('currency', 'EUR')} {amount_float:.2f}",
57
+ order.get("status", "N/A"),
58
+ order.get("created_at", "N/A")[:10] if order.get("created_at") else "N/A",
59
+ )
60
+
61
+ console.print()
62
+ console.print(table)
63
+ console.print()
64
+ else:
65
+ console.print(f"[red]Error: {response.status_code}[/red]")
66
+ console.print(response.json().get("detail", "Unknown error"))
67
+ raise typer.Exit(1)
68
+
69
+ except Exception as e:
70
+ console.print(f"[red]Error: {str(e)}[/red]")
71
+ raise typer.Exit(1) from None
72
+
73
+
74
+ @app.command(name="get")
75
+ def get_order(
76
+ order_id: str = typer.Argument(..., help="Order ID"),
77
+ api: str | None = typer.Option(None, "--api", "-a", help="API type (admin or user)"),
78
+ ) -> None:
79
+ """Get details about a specific order."""
80
+ if api is None:
81
+ api = get_default_api_type()
82
+
83
+ try:
84
+ client = APIClient(api_type=api)
85
+
86
+ # Try to get from orders list first
87
+ response = client.get("/api/v1/users/orders?limit=100")
88
+
89
+ if response.status_code == 200:
90
+ data = response.json()
91
+ # API returns {"orders": [...]} not {"items": [...]}
92
+ orders = data.get("orders", data.get("items", []))
93
+ order = next(
94
+ (o for o in orders if str(o.get("id")) == order_id or str(o.get("id")).startswith(order_id)), None
95
+ )
96
+
97
+ if order:
98
+ # Handle amount which might be a string
99
+ amount = order.get("amount", order.get("total_amount", 0))
100
+ try:
101
+ amount_float = float(amount) if amount else 0
102
+ except (ValueError, TypeError):
103
+ amount_float = 0
104
+
105
+ console.print()
106
+ console.print("[bold]Order Details[/bold]")
107
+ console.print("─" * 70)
108
+ console.print(f"ID: [cyan]{order.get('id')}[/cyan]")
109
+ console.print(f"Description: {order.get('description', 'N/A')}")
110
+ console.print(f"Amount: [green]{order.get('currency', 'EUR')} {amount_float:.2f}[/green]")
111
+ console.print(f"Status: [yellow]{order.get('status')}[/yellow]")
112
+
113
+ if order.get("created_at"):
114
+ console.print(f"Created: {order.get('created_at')}")
115
+
116
+ if order.get("paid_at"):
117
+ console.print(f"Paid: {order.get('paid_at')}")
118
+
119
+ if order.get("product_id"):
120
+ console.print(f"Product ID: {order.get('product_id')}")
121
+
122
+ console.print()
123
+ else:
124
+ console.print(f"[red]Order not found: {order_id}[/red]")
125
+ raise typer.Exit(1)
126
+ else:
127
+ console.print(f"[red]Error: {response.status_code}[/red]")
128
+ console.print(response.json().get("detail", "Unknown error"))
129
+ raise typer.Exit(1)
130
+
131
+ except Exception as e:
132
+ console.print(f"[red]Error: {str(e)}[/red]")
133
+ raise typer.Exit(1) from None
134
+
135
+
136
+ @app.command(name="create")
137
+ def create_order(
138
+ product_id: str | None = typer.Option(None, "--product", "-p", help="Product ID (skip product selection)"),
139
+ tier: str | None = typer.Option(None, "--tier", "-t", help="Pricing tier name or ID (skip tier selection)"),
140
+ provider: str | None = typer.Option(
141
+ None, "--provider", help="Cloud provider, e.g. hetzner (skip provider selection)"
142
+ ),
143
+ region: str | None = typer.Option(None, "--region", "-r", help="Region code, e.g. nbg1 (skip region selection)"),
144
+ firewall_id: str | None = typer.Option(
145
+ None, "--firewall", "-f", help="Firewall ID to attach (skip firewall selection)"
146
+ ),
147
+ no_firewall: bool = typer.Option(False, "--no-firewall", help="Deploy without firewall"),
148
+ auto_pay: bool = typer.Option(True, "--auto-pay", help="Automatically simulate payment in dev mode"),
149
+ yes: bool = typer.Option(False, "--yes", "-y", help="Accept terms without prompting"),
150
+ api: str | None = typer.Option(None, "--api", "-a", help="API type (admin or user)"),
151
+ ) -> None:
152
+ """Create an order with full deployment configuration.
153
+
154
+ Runs interactively when no flags are given. Supply flags to skip individual steps:
155
+
156
+ Example:
157
+ pbd orders create
158
+ pbd orders create --product f25bea71 --tier starter --provider hetzner --region nbg1 --no-firewall --yes
159
+ """
160
+ try:
161
+ if api is None:
162
+ api = get_default_api_type()
163
+
164
+ client = APIClient(api_type=api)
165
+
166
+ # Step 1: Product Selection
167
+ if not product_id:
168
+ products_response = client.get("/api/v1/products?limit=100")
169
+ if products_response.status_code != 200:
170
+ console.print("[red]Failed to fetch products[/red]")
171
+ raise typer.Exit(1)
172
+
173
+ products = products_response.json()
174
+ if not products:
175
+ console.print("[yellow]No products available[/yellow]")
176
+ raise typer.Exit(1)
177
+
178
+ if len(products) == 1:
179
+ selected_product = products[0]
180
+ product_id = selected_product.get("id")
181
+ else:
182
+ console.print("\n[bold cyan]Step 1: Select a Product[/bold cyan]")
183
+ console.print()
184
+
185
+ table = Table(title="Available Products")
186
+ table.add_column("#", style="cyan", no_wrap=True)
187
+ table.add_column("Name", style="green")
188
+ table.add_column("Type", style="blue")
189
+ table.add_column("Description")
190
+
191
+ for idx, product in enumerate(products, 1):
192
+ table.add_row(
193
+ str(idx),
194
+ product.get("name", "N/A"),
195
+ product.get("product_type", "N/A"),
196
+ (product.get("description", "")[:50] + "...")
197
+ if len(product.get("description", "")) > 50
198
+ else product.get("description", "N/A"),
199
+ )
200
+
201
+ console.print(table)
202
+ console.print()
203
+
204
+ choice = Prompt.ask("Select product number", default="1")
205
+ try:
206
+ selected_product = products[int(choice) - 1]
207
+ product_id = selected_product.get("id")
208
+ except (ValueError, IndexError):
209
+ console.print("[red]Invalid selection[/red]")
210
+ raise typer.Exit(1) from None
211
+ else:
212
+ # Fetch specific product
213
+ if len(product_id) < 36:
214
+ # Resolve partial ID
215
+ products_response = client.get("/api/v1/products?limit=100")
216
+ products = products_response.json()
217
+ matching = [p for p in products if str(p.get("id", "")).startswith(product_id)]
218
+ if len(matching) == 1:
219
+ product_id = matching[0].get("id")
220
+ selected_product = matching[0]
221
+ else:
222
+ console.print("[red]Could not resolve product ID[/red]")
223
+ raise typer.Exit(1)
224
+ else:
225
+ product_response = client.get(f"/api/v1/products/{product_id}")
226
+ if product_response.status_code != 200:
227
+ console.print(f"[red]Product not found: {product_id}[/red]")
228
+ raise typer.Exit(1)
229
+ selected_product = product_response.json()
230
+
231
+ console.print(f"\n[green]✓[/green] Selected: [bold]{selected_product.get('name')}[/bold]")
232
+
233
+ # Step 2: Pricing Tier Selection
234
+ pricing_tiers = selected_product.get("pricing_tiers", [])
235
+ if not pricing_tiers:
236
+ console.print("[red]No pricing tiers available for this product[/red]")
237
+ raise typer.Exit(1)
238
+
239
+ selected_tier = None
240
+ if tier:
241
+ # Match by name (case-insensitive) or ID
242
+ for t in pricing_tiers:
243
+ if t.get("name", "").lower() == tier.lower() or str(t.get("id", "")).startswith(tier):
244
+ selected_tier = t
245
+ break
246
+ if not selected_tier:
247
+ console.print(f"[red]Tier not found: {tier}[/red]")
248
+ console.print(f"Available: {', '.join(t.get('name') for t in pricing_tiers)}")
249
+ raise typer.Exit(1)
250
+ else:
251
+ console.print("\n[bold cyan]Step 2: Select Pricing Tier[/bold cyan]")
252
+ console.print()
253
+
254
+ table = Table(title="Available Pricing Tiers")
255
+ table.add_column("#", style="cyan", no_wrap=True)
256
+ table.add_column("Name", style="green")
257
+ table.add_column("Price", style="yellow")
258
+ table.add_column("Billing", style="blue")
259
+ table.add_column("Specs")
260
+
261
+ for idx, t in enumerate(pricing_tiers, 1):
262
+ specs = t.get("specs", {})
263
+ specs_str = f"CPU: {specs.get('cpu_cores', 'N/A')}, RAM: {specs.get('memory_gb', 'N/A')}GB, Nodes: {specs.get('nodes', 'N/A')}"
264
+ table.add_row(
265
+ str(idx),
266
+ t.get("name", "N/A"),
267
+ f"€{t.get('price', 0):.2f}",
268
+ t.get("billing_interval", "N/A"),
269
+ specs_str,
270
+ )
271
+
272
+ console.print(table)
273
+ console.print()
274
+
275
+ tier_choice = Prompt.ask("Select pricing tier number", default="1")
276
+ try:
277
+ selected_tier = pricing_tiers[int(tier_choice) - 1]
278
+ except (ValueError, IndexError):
279
+ console.print("[red]Invalid selection[/red]")
280
+ raise typer.Exit(1) from None
281
+
282
+ console.print(
283
+ f"[green]✓[/green] Selected: [bold]{selected_tier.get('name')}[/bold] - €{selected_tier.get('price', 0):.2f}/{selected_tier.get('billing_interval', 'month')}"
284
+ )
285
+
286
+ # Step 3: Provider Selection
287
+ available_providers = [
288
+ {"name": "Hetzner", "value": "hetzner", "description": "German cloud provider, cost-effective"},
289
+ {"name": "AWS", "value": "aws", "description": "Amazon Web Services (not yet implemented)"},
290
+ {"name": "GCP", "value": "gcp", "description": "Google Cloud Platform (not yet implemented)"},
291
+ ]
292
+
293
+ if provider:
294
+ selected_provider = provider.lower()
295
+ if selected_provider != "hetzner":
296
+ console.print(f"[yellow]Note: {selected_provider} is not yet implemented. Using Hetzner.[/yellow]")
297
+ selected_provider = "hetzner"
298
+ else:
299
+ console.print("\n[bold cyan]Step 3: Select Cloud Provider[/bold cyan]")
300
+ console.print()
301
+ for idx, p in enumerate(available_providers, 1):
302
+ status = "" if p["value"] == "hetzner" else " [dim](coming soon)[/dim]"
303
+ console.print(f" {idx}. [bold]{p['name']}[/bold]{status} - {p['description']}")
304
+ console.print()
305
+ provider_choice = Prompt.ask("Select provider number", default="1")
306
+ selected_provider = available_providers[int(provider_choice) - 1]["value"]
307
+ if selected_provider != "hetzner":
308
+ console.print("[yellow]Note: Not yet implemented. Using Hetzner.[/yellow]")
309
+ selected_provider = "hetzner"
310
+
311
+ console.print(f"[green]✓[/green] Selected: [bold]{selected_provider}[/bold]")
312
+
313
+ # Step 4: Region Selection
314
+ available_regions = [
315
+ {"name": "Nuremberg, Germany", "value": "nbg1", "location": "🇩🇪"},
316
+ {"name": "Falkenstein, Germany", "value": "fsn1", "location": "🇩🇪"},
317
+ {"name": "Helsinki, Finland", "value": "hel1", "location": "🇫🇮"},
318
+ {"name": "Ashburn, USA", "value": "ash", "location": "🇺🇸"},
319
+ ]
320
+
321
+ if region:
322
+ selected_region = region.lower()
323
+ region_label = next(
324
+ (r["name"] for r in available_regions if r["value"] == selected_region), selected_region
325
+ )
326
+ else:
327
+ console.print("\n[bold cyan]Step 4: Select Region[/bold cyan]")
328
+ console.print()
329
+ for idx, r in enumerate(available_regions, 1):
330
+ console.print(f" {idx}. {r['location']} [bold]{r['name']}[/bold] ({r['value']})")
331
+ console.print()
332
+ region_choice = Prompt.ask("Select region number", default="1")
333
+ selected_region = available_regions[int(region_choice) - 1]["value"]
334
+ region_label = available_regions[int(region_choice) - 1]["name"]
335
+
336
+ console.print(f"[green]✓[/green] Selected: [bold]{region_label}[/bold]")
337
+
338
+ # Step 5: Firewall Configuration
339
+ selected_firewall_id: str | None = None
340
+ fw_response = client.get("/api/v1/firewalls")
341
+ firewalls = fw_response.json() if fw_response.status_code == 200 else []
342
+ if isinstance(firewalls, dict):
343
+ firewalls = firewalls.get("items", firewalls.get("data", []))
344
+
345
+ if no_firewall:
346
+ console.print("[green]✓[/green] Firewall: [bold]None[/bold]")
347
+ elif firewall_id:
348
+ # Match by ID or name
349
+ matched = next(
350
+ (
351
+ fw
352
+ for fw in firewalls
353
+ if str(fw.get("id", "")).startswith(firewall_id)
354
+ or fw.get("name", "").lower() == firewall_id.lower()
355
+ ),
356
+ None,
357
+ )
358
+ if matched:
359
+ selected_firewall_id = matched.get("id")
360
+ console.print(f"[green]✓[/green] Firewall: [bold]{matched.get('name')}[/bold]")
361
+ else:
362
+ console.print(f"[red]Firewall not found: {firewall_id}[/red]")
363
+ raise typer.Exit(1)
364
+ elif firewalls:
365
+ console.print("\n[bold cyan]Step 5: Firewall Configuration[/bold cyan]")
366
+ console.print()
367
+ fw_table = Table()
368
+ fw_table.add_column("#", style="cyan", width=4)
369
+ fw_table.add_column("Name", style="green")
370
+ fw_table.add_column("Description", style="dim")
371
+ for i, fw in enumerate(firewalls, 1):
372
+ fw_table.add_row(str(i), fw.get("name", "N/A"), fw.get("description") or "")
373
+ console.print(fw_table)
374
+ console.print()
375
+
376
+ fw_options = [str(i) for i in range(1, len(firewalls) + 1)]
377
+ fw_choice = Prompt.ask(f"Select firewall [{'/ '.join(fw_options)}/none]", default="1")
378
+ if fw_choice.lower() != "none" and fw_choice in fw_options:
379
+ selected_fw = firewalls[int(fw_choice) - 1]
380
+ selected_firewall_id = selected_fw.get("id")
381
+ console.print(f"[green]✓[/green] Firewall: [bold]{selected_fw.get('name')}[/bold]")
382
+ else:
383
+ console.print("[green]✓[/green] Firewall: [bold]None[/bold]")
384
+ else:
385
+ console.print("[dim]No firewalls available — deploying without firewall.[/dim]")
386
+ console.print("[green]✓[/green] Firewall: [bold]None[/bold]")
387
+
388
+ # Step 6: Accept terms
389
+ if not yes:
390
+ console.print("\n[bold cyan]Step 6: Terms & Conditions[/bold cyan]")
391
+ console.print()
392
+ console.print("By placing this order you accept the platform terms of service,")
393
+ console.print("privacy policy, and provider-specific agreements.")
394
+ console.print()
395
+ if not typer.confirm("I accept the terms and conditions"):
396
+ console.print("[yellow]Order cancelled.[/yellow]")
397
+ raise typer.Exit(0)
398
+
399
+ # Step 7: Create Order
400
+ console.print("\n[bold cyan]Step 7: Creating Order[/bold cyan]")
401
+ console.print()
402
+
403
+ # Prepare order data
404
+ order_data: dict[str, object] = {
405
+ "amount": float(selected_tier.get("price", 0)),
406
+ "currency": selected_tier.get("currency", "EUR"),
407
+ "description": f"{selected_product.get('name')} - {selected_tier.get('name')}",
408
+ "redirect_url": "http://localhost:3000/payment/success",
409
+ "product_id": product_id,
410
+ "pricing_tier_id": selected_tier.get("id"),
411
+ "accepted_documents": True,
412
+ }
413
+ if selected_firewall_id:
414
+ order_data["firewall_id"] = selected_firewall_id
415
+
416
+ is_dev = get_current_environment() == "development"
417
+ console.print(f"[yellow]Creating order for {order_data['currency']} {order_data['amount']:.2f}...[/yellow]")
418
+
419
+ response = client.post("/api/v1/payments/create", data=order_data)
420
+
421
+ if response.status_code not in [200, 201]:
422
+ console.print(f"[red]Error: {response.status_code}[/red]")
423
+ console.print(f"[red]{response.json().get('detail', 'Unknown error')}[/red]")
424
+ raise typer.Exit(1)
425
+
426
+ result = response.json()
427
+ order_id = result.get("order_id")
428
+
429
+ console.print()
430
+ console.print("[green]✓ Order created successfully![/green]")
431
+ console.print()
432
+ console.print("[bold]Order Summary[/bold]")
433
+ console.print("─" * 70)
434
+ console.print(f"Order ID: [cyan]{order_id}[/cyan]")
435
+ console.print(f"Product: [green]{selected_product.get('name')}[/green]")
436
+ console.print(f"Tier: [green]{selected_tier.get('name')}[/green]")
437
+ console.print(f"Amount: [yellow]{order_data['currency']} {order_data['amount']:.2f}[/yellow]")
438
+ console.print(f"Provider: [blue]{selected_provider}[/blue]")
439
+ console.print(f"Region: [blue]{selected_region}[/blue]")
440
+ fw_label = (
441
+ next((fw.get("name") for fw in firewalls if fw.get("id") == selected_firewall_id), "None")
442
+ if selected_firewall_id
443
+ else "None"
444
+ )
445
+ console.print(f"Firewall: [blue]{fw_label}[/blue]")
446
+ console.print(f"Status: [yellow]{result.get('status', 'pending')}[/yellow]")
447
+ if result.get("payment_url") and not is_dev:
448
+ console.print(f"Payment URL: [blue]{result.get('payment_url')}[/blue]")
449
+ console.print()
450
+
451
+ # Step 8: Auto-simulate payment in dev mode only
452
+ if auto_pay and is_dev:
453
+ console.print("[bold cyan]Step 8: Simulating Payment (Dev Mode)[/bold cyan]")
454
+ console.print()
455
+
456
+ admin_client = APIClient(api_type="admin")
457
+
458
+ # Simulate payment
459
+ pay_response = admin_client.post(
460
+ "/api/v1/dev/simulate-payment",
461
+ data={
462
+ "order_id": order_id,
463
+ "payment_status": "paid",
464
+ },
465
+ )
466
+
467
+ if pay_response.status_code in [200, 201]:
468
+ pay_result = pay_response.json()
469
+ console.print("[green]✓ Payment simulated successfully![/green]")
470
+ console.print()
471
+
472
+ # Check if deployment was triggered
473
+ if pay_result.get("deployment_triggered"):
474
+ deployment_result = pay_result.get("deployment_result", {})
475
+ deployment_id = deployment_result.get("deployment_id") or deployment_result.get("cluster_id")
476
+
477
+ if deployment_id:
478
+ console.print("[green]✓ Deployment triggered automatically![/green]")
479
+ console.print()
480
+ console.print(f"Deployment ID: [cyan]{deployment_id}[/cyan]")
481
+ console.print(f"Status: [yellow]{deployment_result.get('status', 'pending')}[/yellow]")
482
+ console.print()
483
+ console.print(f"[cyan]Check status: pbd clusters get {deployment_id}[/cyan]")
484
+ console.print("[cyan]List clusters: pbd clusters list[/cyan]")
485
+ else:
486
+ console.print("[yellow]Payment succeeded but deployment not triggered automatically[/yellow]")
487
+ console.print(f"[cyan]Trigger manually: pbd dev trigger-deployment {order_id}[/cyan]")
488
+ else:
489
+ console.print(f"[red]Payment simulation failed: {pay_response.status_code}[/red]")
490
+ console.print(f"[cyan]Try manually: pbd dev simulate-payment {order_id}[/cyan]")
491
+ else:
492
+ payment_url = result.get("payment_url")
493
+ if payment_url:
494
+ console.print("[bold cyan]Step 8: Complete Payment[/bold cyan]")
495
+ console.print()
496
+ console.print("[green]Open the link below to complete your payment:[/green]")
497
+ console.print(f"[bold blue]{payment_url}[/bold blue]")
498
+ console.print()
499
+ console.print("[dim]Your cluster will be deployed automatically after payment.[/dim]")
500
+ elif is_dev:
501
+ console.print(f"[cyan]To simulate payment: pbd dev simulate-payment {order_id}[/cyan]")
502
+
503
+ console.print()
504
+
505
+ except typer.Exit:
506
+ raise
507
+ except Exception as e:
508
+ console.print(f"[red]Error: {str(e)}[/red]")
509
+ raise typer.Exit(1) from None
@@ -0,0 +1,143 @@
1
+ """Product catalog commands."""
2
+
3
+ import typer
4
+ from rich.console import Console
5
+ from rich.table import Table
6
+
7
+ from ..client import APIClient
8
+ from ..config import get_default_api_type
9
+
10
+ app = typer.Typer()
11
+ console = Console()
12
+
13
+
14
+ @app.command(name="list")
15
+ def list_products(
16
+ limit: int = typer.Option(50, "--limit", "-l", help="Number of products to fetch"),
17
+ api: str | None = typer.Option(None, "--api", "-a", help="API type (admin or user)"),
18
+ ) -> None:
19
+ """List available products.
20
+
21
+ Shows all products available for purchase.
22
+ """
23
+ if api is None:
24
+ api = get_default_api_type()
25
+
26
+ try:
27
+ client = APIClient(api_type=api)
28
+ response = client.get(f"/api/v1/products?limit={limit}")
29
+
30
+ if response.status_code == 200:
31
+ data = response.json()
32
+
33
+ # Handle both list and dict responses
34
+ if isinstance(data, list):
35
+ products = data
36
+ else:
37
+ products = data.get("items", [])
38
+
39
+ if not products:
40
+ console.print("[yellow]No products found[/yellow]")
41
+ return
42
+
43
+ table = Table(title=f"Available Products ({len(products)})")
44
+ table.add_column("ID", style="cyan", no_wrap=True, overflow="fold")
45
+ table.add_column("Name", style="green")
46
+ table.add_column("Category", style="yellow")
47
+ table.add_column("Price", style="magenta")
48
+ table.add_column("Provider", style="blue")
49
+
50
+ for product in products:
51
+ provider = product.get("provider", {})
52
+ product_id = str(product.get("id", "N/A"))
53
+ # Truncate long UUIDs for display
54
+ display_id = product_id[:8] + "..." if len(product_id) > 8 else product_id
55
+
56
+ table.add_row(
57
+ display_id,
58
+ product.get("name", "N/A"),
59
+ product.get("category", "N/A"),
60
+ f"€{product.get('price', 0):.2f}",
61
+ provider.get("name", "N/A") if provider else "N/A",
62
+ )
63
+
64
+ console.print()
65
+ console.print(table)
66
+ console.print()
67
+ console.print("[cyan]💡 To see full product ID for ordering, use: pbd products get <partial-id>[/cyan]")
68
+ console.print()
69
+ else:
70
+ console.print(f"[red]Error: {response.status_code}[/red]")
71
+ console.print(response.json().get("detail", "Unknown error"))
72
+ raise typer.Exit(1)
73
+
74
+ except Exception as e:
75
+ console.print(f"[red]Error: {str(e)}[/red]")
76
+ raise typer.Exit(1) from None
77
+
78
+
79
+ @app.command(name="get")
80
+ def get_product(
81
+ product_id: str = typer.Argument(..., help="Product ID (or partial ID)"),
82
+ api: str | None = typer.Option(None, "--api", "-a", help="API type (admin or user)"),
83
+ ) -> None:
84
+ """Get details about a specific product."""
85
+ if api is None:
86
+ api = get_default_api_type()
87
+
88
+ try:
89
+ client = APIClient(api_type=api)
90
+
91
+ # Try direct get first
92
+ response = client.get(f"/api/v1/products/{product_id}")
93
+
94
+ if response.status_code == 200:
95
+ product = response.json()
96
+ else:
97
+ # If not found, try to find by partial ID
98
+ list_response = client.get("/api/v1/products?limit=100")
99
+ if list_response.status_code == 200:
100
+ list_data = list_response.json()
101
+ products = list_data if isinstance(list_data, list) else list_data.get("items", [])
102
+ matching = [p for p in products if str(p.get("id", "")).startswith(product_id)]
103
+
104
+ if len(matching) == 1:
105
+ product = matching[0]
106
+ elif len(matching) > 1:
107
+ console.print(f"[yellow]Multiple products match '{product_id}':[/yellow]")
108
+ for p in matching:
109
+ console.print(f" - {p.get('id')} ({p.get('name')})")
110
+ console.print("\n[cyan]Please provide a more specific ID[/cyan]")
111
+ raise typer.Exit(1)
112
+ else:
113
+ console.print(f"[red]Product not found: {product_id}[/red]")
114
+ raise typer.Exit(1)
115
+ else:
116
+ console.print(f"[red]Error: {response.status_code}[/red]")
117
+ raise typer.Exit(1)
118
+
119
+ # Display product details
120
+ console.print()
121
+ console.print(f"[bold]Product Details: {product.get('name')}[/bold]")
122
+ console.print("─" * 70)
123
+ console.print(f"ID: [cyan]{product.get('id')}[/cyan]")
124
+ console.print(f"Name: [green]{product.get('name')}[/green]")
125
+ console.print(f"Category: [yellow]{product.get('category', 'N/A')}[/yellow]")
126
+ console.print(f"Price: [magenta]€{product.get('price', 0):.2f}[/magenta]")
127
+
128
+ provider = product.get("provider", {})
129
+ if provider:
130
+ console.print(f"Provider: [blue]{provider.get('name', 'N/A')}[/blue]")
131
+
132
+ if product.get("description"):
133
+ console.print(f"Description: {product.get('description')}")
134
+
135
+ console.print()
136
+ console.print(
137
+ f"[cyan]💡 To order: pbd orders create {product.get('price', 0):.2f} --product {product.get('id')}[/cyan]"
138
+ )
139
+ console.print()
140
+
141
+ except Exception as e:
142
+ console.print(f"[red]Error: {str(e)}[/red]")
143
+ raise typer.Exit(1) from None