feat(purchase): add checkout expiration settings and reservation status to purchase items

- Introduced a new configuration file for purchase settings, including checkout and payment expiration times.
- Added a migration to include a `reservation_status` column in the `compra_items` table, defaulting to 'active' and updating existing records based on purchase status.
- Created a migration to add an `expires_at` timestamp to the `compras` table, updating it for existing records based on their status.
- Scoped unique indexes in the `carritos` table to only active carts, adding virtual columns for active user and guest tokens.
- Implemented a console command to expire overdue purchases and release stock reservations, scheduled to run every minute.
- Added tests for Google token exchange and login functionality, ensuring proper cart handling and user authentication.
- Updated purchase-related tests to reflect changes in item handling and customer data validation.
This commit is contained in:
2026-07-27 12:49:27 -03:00
parent c37b8894e4
commit 8b26a2b63e
30 changed files with 1738 additions and 396 deletions

View File

@@ -3,77 +3,54 @@
namespace App\Domains\Purchase\Services;
use App\Domains\Attachable\Models\Attachment;
use App\Domains\Attachable\Services\AttachmentService;
use App\Domains\Cart\Models\Cart;
use App\Domains\Cart\Models\CartItem;
use App\Domains\Catalog\Models\CatalogItem;
use App\Domains\Catalog\Models\Inventory;
use App\Domains\Catalog\Models\Variant;
use App\Domains\Catalog\Services\CatalogInventoryService;
use App\Domains\Purchase\Models\Purchase;
use App\Domains\Purchase\Models\PurchaseItem;
use App\Domains\Tenant\Models\Tenant;
use Illuminate\Support\Collection;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Storage;
use Illuminate\Validation\ValidationException;
use Symfony\Component\HttpKernel\Exception\NotFoundHttpException;
use Throwable;
class CheckoutService
{
public function __construct(
private readonly AttachmentService $attachmentService,
private readonly CatalogInventoryService $catalogInventoryService,
) {}
public function startCheckout(Tenant $tenant, int $userId, array $purchaseData): Purchase
{
$cartId = (int) $purchaseData['cart_id'];
unset($purchaseData['cart_id']);
return DB::transaction(function () use ($tenant, $userId, $purchaseData): Purchase {
$directItem = $purchaseData['direct_item'] ?? null;
$cartId = isset($purchaseData['cart_id']) ? (int) $purchaseData['cart_id'] : null;
unset($purchaseData['direct_item'], $purchaseData['cart_id']);
return DB::transaction(function () use ($tenant, $userId, $purchaseData, $cartId): Purchase {
$cart = $this->resolveCheckoutCart($tenant, $userId, $cartId);
$cartItems = $cart->items()->lockForUpdate()->get();
if (is_array($directItem)) {
return $this->startDirectCheckout(
$tenant,
$userId,
$purchaseData,
$directItem,
);
}
if ($cartItems->isEmpty()) {
if ($cartId === null) {
throw ValidationException::withMessages([
'cart_id' => 'The selected cart does not contain items.',
'cart_id' => 'A cart or direct item is required.',
]);
}
$this->loadCartItems($cartItems);
$cart->setRelation('items', $cartItems);
$totalAmount = $cart->getTotalAmount();
/** @var Purchase|null $purchase */
$purchase = Purchase::query()
->where('cart_id', $cart->getKey())
->where('tenant_codigo', $tenant->codigo)
->where('user_id', $userId)
->whereIn('status', [Purchase::STATUS_CREATED, Purchase::STATUS_PENDING_PAYMENT])
->latest('id')
->first();
if ($purchase === null) {
/** @var Purchase $purchase */
$purchase = Purchase::query()->create([
...$purchaseData,
'cart_id' => $cart->getKey(),
'tenant_codigo' => $tenant->codigo,
'user_id' => $userId,
'status' => Purchase::STATUS_CREATED,
'payment_method' => null,
'total' => $totalAmount,
]);
} else {
$purchase->fill([
...$purchaseData,
'status' => Purchase::STATUS_CREATED,
'payment_method' => null,
'total' => $totalAmount,
]);
$purchase->save();
}
return $this->loadPurchase($purchase);
return $this->startCartCheckout(
$tenant,
$userId,
$purchaseData,
$cartId,
);
});
}
@@ -91,7 +68,12 @@ class CheckoutService
]);
}
if (in_array($purchase->status, [Purchase::STATUS_PAID, Purchase::STATUS_CANCELLED, Purchase::STATUS_REJECTED], true)) {
if (in_array($purchase->status, [
Purchase::STATUS_PAID,
Purchase::STATUS_CANCELLED,
Purchase::STATUS_REJECTED,
Purchase::STATUS_EXPIRED,
], true)) {
return $this->loadPurchase($purchase);
}
@@ -104,59 +86,515 @@ class CheckoutService
});
}
public function confirmPurchase(Purchase $purchase): void
/**
* @param array<string, string> $customerData
*/
public function updateCustomerData(Purchase $purchase, array $customerData): Purchase
{
$snapshotPaths = [];
return DB::transaction(function () use ($purchase, $customerData): Purchase {
/** @var Purchase $purchase */
$purchase = Purchase::query()
->lockForUpdate()
->findOrFail($purchase->getKey());
try {
DB::transaction(function () use ($purchase, &$snapshotPaths): void {
/** @var Purchase $purchase */
$purchase = Purchase::query()
->lockForUpdate()
->findOrFail($purchase->getKey());
if ($purchase->items()->exists()) {
return;
}
/** @var Cart|null $cart */
$cart = $purchase->cart()->lockForUpdate()->first();
if ($cart === null) {
throw ValidationException::withMessages([
'cart_id' => 'The purchase cart is no longer available.',
]);
}
$cartItems = $cart->items()->lockForUpdate()->get();
if ($cartItems->isEmpty()) {
throw ValidationException::withMessages([
'cart_id' => 'The purchase cart does not contain items.',
]);
}
$this->loadCartItems($cartItems);
$this->verifyTenantItems($purchase->tenant, $cartItems);
$purchaseItemsPayload = $this->buildPurchaseItemsPayload($purchase, $cartItems, $snapshotPaths);
$purchase->items()->createMany($purchaseItemsPayload);
$this->completeCartConversion($cart, $cartItems);
});
} catch (Throwable $throwable) {
foreach ($snapshotPaths as $snapshotPath) {
Storage::disk('s3')->delete($snapshotPath);
if (
$purchase->status !== Purchase::STATUS_CREATED
|| ($purchase->expires_at !== null && $purchase->expires_at->isPast())
) {
throw ValidationException::withMessages([
'purchase' => 'The purchase is no longer editable.',
]);
}
throw $throwable;
$purchase->update($customerData);
return $this->loadPurchase($purchase);
});
}
public function updateItemQuantity(
Purchase $purchase,
PurchaseItem $purchaseItem,
int $quantity,
): Purchase {
return DB::transaction(function () use ($purchase, $purchaseItem, $quantity): Purchase {
/** @var Purchase $purchase */
$purchase = Purchase::query()
->lockForUpdate()
->findOrFail($purchase->getKey());
if (
$purchase->status !== Purchase::STATUS_CREATED
|| ($purchase->expires_at !== null && $purchase->expires_at->isPast())
) {
throw ValidationException::withMessages([
'purchase' => 'The purchase is no longer editable.',
]);
}
/** @var PurchaseItem|null $purchaseItem */
$purchaseItem = $purchase->items()
->whereKey($purchaseItem->getKey())
->lockForUpdate()
->first();
if ($purchaseItem === null) {
throw new NotFoundHttpException('Purchase item not found.');
}
if ($purchaseItem->reservation_status !== PurchaseItem::RESERVATION_ACTIVE) {
throw ValidationException::withMessages([
'item' => 'The purchase item is no longer editable.',
]);
}
$currentQuantity = (int) $purchaseItem->cantidad;
$difference = $quantity - $currentQuantity;
if ($difference !== 0) {
$selection = $this->resolvePurchaseItemSelection($purchase->tenant, $purchaseItem);
try {
if ($difference > 0) {
$this->catalogInventoryService->reserve($selection, $difference);
} else {
$this->catalogInventoryService->release($selection, abs($difference));
}
} catch (\InvalidArgumentException $exception) {
throw ValidationException::withMessages([
'quantity' => 'No hay suficiente stock disponible.',
]);
}
$purchaseItem->update([
'cantidad' => $quantity,
'total' => (float) $purchaseItem->precio_unitario * $quantity,
]);
$this->syncSourceCartItemQuantity($purchase, $purchaseItem, $quantity);
}
$purchase->update([
'total' => $purchase->calculateCurrentTotalAmount(),
]);
return $this->loadPurchase($purchase);
});
}
public function prepareItemEditing(Purchase $purchase): Purchase
{
return DB::transaction(function () use ($purchase): Purchase {
/** @var Purchase $purchase */
$purchase = Purchase::query()
->lockForUpdate()
->findOrFail($purchase->getKey());
if (
! in_array($purchase->status, [
Purchase::STATUS_CREATED,
Purchase::STATUS_PENDING_PAYMENT,
], true)
|| ($purchase->expires_at !== null && $purchase->expires_at->isPast())
) {
throw ValidationException::withMessages([
'purchase' => 'The purchase is no longer editable.',
]);
}
$purchase->telepagosQr()->delete();
$purchase->update([
'status' => Purchase::STATUS_CREATED,
'payment_method' => null,
'transfer_payer_dni' => null,
'expires_at' => now()->addMinutes(
max(1, (int) config('purchase.checkout_expiration_minutes', 30)),
),
]);
return $this->loadPurchase($purchase);
});
}
public function confirmPurchase(Purchase $purchase): void
{
DB::transaction(function () use ($purchase): void {
/** @var Purchase $purchase */
$purchase = Purchase::query()
->lockForUpdate()
->findOrFail($purchase->getKey());
if ($purchase->status === Purchase::STATUS_PAID) {
return;
}
if (in_array($purchase->status, [
Purchase::STATUS_CANCELLED,
Purchase::STATUS_REJECTED,
Purchase::STATUS_EXPIRED,
], true)) {
throw ValidationException::withMessages([
'purchase' => 'A cancelled, rejected or expired purchase cannot be confirmed.',
]);
}
$items = $purchase->items()
->where('reservation_status', PurchaseItem::RESERVATION_ACTIVE)
->lockForUpdate()
->get();
foreach ($items as $item) {
$selection = $this->resolvePurchaseItemSelection($purchase->tenant, $item);
try {
$this->catalogInventoryService->commit($selection, (int) $item->cantidad);
} catch (\InvalidArgumentException $exception) {
throw ValidationException::withMessages([
'items' => 'The purchase has an inconsistent stock reservation.',
]);
}
$item->update([
'reservation_status' => PurchaseItem::RESERVATION_COMMITTED,
]);
}
$this->finalizeSourceCart($purchase);
});
}
public function cancelPurchase(Purchase $purchase): Purchase
{
return $this->releasePurchase($purchase, Purchase::STATUS_CANCELLED);
}
public function expirePurchase(Purchase $purchase): Purchase
{
return $this->releasePurchase($purchase, Purchase::STATUS_EXPIRED);
}
public function expireOverduePurchases(): int
{
$expiredCount = 0;
Purchase::query()
->whereIn('status', [Purchase::STATUS_CREATED, Purchase::STATUS_PENDING_PAYMENT])
->whereNotNull('expires_at')
->where('expires_at', '<=', now())
->orderBy('id')
->eachById(function (Purchase $purchase) use (&$expiredCount): void {
$purchase = $this->expirePurchase($purchase);
if ($purchase->status === Purchase::STATUS_EXPIRED) {
$expiredCount++;
}
});
return $expiredCount;
}
private function releasePurchase(Purchase $purchase, string $targetStatus): Purchase
{
return DB::transaction(function () use ($purchase, $targetStatus): Purchase {
/** @var Purchase $purchase */
$purchase = Purchase::query()
->lockForUpdate()
->findOrFail($purchase->getKey());
if ($purchase->status === Purchase::STATUS_PAID) {
if ($targetStatus === Purchase::STATUS_EXPIRED) {
return $this->loadPurchase($purchase);
}
throw ValidationException::withMessages([
'purchase' => 'A paid purchase cannot be cancelled.',
]);
}
if (in_array($purchase->status, [
Purchase::STATUS_CANCELLED,
Purchase::STATUS_REJECTED,
Purchase::STATUS_EXPIRED,
], true)) {
return $this->loadPurchase($purchase);
}
if (
$targetStatus === Purchase::STATUS_EXPIRED
&& ($purchase->expires_at === null || $purchase->expires_at->isFuture())
) {
return $this->loadPurchase($purchase);
}
$items = $purchase->items()
->where('reservation_status', PurchaseItem::RESERVATION_ACTIVE)
->lockForUpdate()
->get();
$reservationReturnedToCart = $this->restoreSourceCart($purchase);
foreach ($items as $item) {
if (! $reservationReturnedToCart) {
$selection = $this->resolvePurchaseItemSelection($purchase->tenant, $item);
try {
$this->catalogInventoryService->release($selection, (int) $item->cantidad);
} catch (\InvalidArgumentException $exception) {
throw ValidationException::withMessages([
'items' => 'The purchase has an inconsistent stock reservation.',
]);
}
}
$item->update([
'reservation_status' => PurchaseItem::RESERVATION_RELEASED,
]);
}
$purchase->update([
'status' => $targetStatus,
]);
return $this->loadPurchase($purchase);
});
}
/**
* @param array<string, mixed> $purchaseData
* @param array<string, mixed> $directItem
*/
private function startDirectCheckout(
Tenant $tenant,
int $userId,
array $purchaseData,
array $directItem,
): Purchase {
$catalogItemId = (int) $directItem['catalog_item_id'];
$variantId = isset($directItem['variant_id']) ? (int) $directItem['variant_id'] : null;
$quantity = (int) $directItem['cantidad'];
$selection = $this->resolveSelection($tenant, $catalogItemId, $variantId);
$availableQuantity = $this->catalogInventoryService->availableQuantity($selection);
if ($availableQuantity !== null && $availableQuantity < $quantity) {
throw ValidationException::withMessages([
'direct_item.cantidad' => "Stock insuficiente. Maximo disponible: {$availableQuantity}.",
]);
}
try {
$this->catalogInventoryService->reserve($selection, $quantity);
} catch (\InvalidArgumentException $exception) {
throw ValidationException::withMessages([
'direct_item.cantidad' => 'No hay suficiente stock disponible.',
]);
}
$purchase = $this->createPurchase(
$tenant,
$userId,
$purchaseData,
$selection->getPrice() * $quantity,
null,
);
$cartItem = $this->makeDirectCartItem($selection, $catalogItemId, $variantId, $quantity);
$purchase->items()->createMany(
$this->buildPurchaseItemsPayload(collect([$cartItem])),
);
return $this->loadPurchase($purchase);
}
/**
* @param array<string, mixed> $purchaseData
*/
private function startCartCheckout(
Tenant $tenant,
int $userId,
array $purchaseData,
int $cartId,
): Purchase {
$cart = $this->resolveCheckoutCart($tenant, $userId, $cartId);
$cartItems = $cart->items()->lockForUpdate()->get();
if ($cartItems->isEmpty()) {
throw ValidationException::withMessages([
'cart_id' => 'The selected cart does not contain items.',
]);
}
$this->loadCartItems($cartItems);
$this->verifyTenantItems($tenant, $cartItems);
$cart->setRelation('items', $cartItems);
$purchase = $this->createPurchase(
$tenant,
$userId,
$purchaseData,
$cart->getTotalAmount(),
$cart->getKey(),
);
$purchase->items()->createMany(
$this->buildPurchaseItemsPayload($cartItems),
);
// PurchaseItem owns the reservation during checkout. The source cart is
// kept with its owner so it can be restored if the purchase is cancelled
// or expires. Only active carts participate in the identity constraint.
$cart->update([
'status' => 'checkout',
'guest_token' => null,
]);
return $this->loadPurchase($purchase);
}
private function restoreSourceCart(Purchase $purchase): bool
{
if ($purchase->cart_id === null) {
return false;
}
/** @var Cart|null $sourceCart */
$sourceCart = Cart::withTrashed()
->whereKey($purchase->cart_id)
->lockForUpdate()
->first();
if ($sourceCart === null) {
return false;
}
/** @var Cart|null $activeCart */
$activeCart = Cart::query()
->where('tenant_codigo', $purchase->tenant_codigo)
->where('user_id', $purchase->user_id)
->where('status', 'active')
->where('id', '!=', $sourceCart->getKey())
->lockForUpdate()
->first();
if ($activeCart !== null) {
$sourceItems = $sourceCart->items()->lockForUpdate()->get();
foreach ($sourceItems as $sourceItem) {
/** @var CartItem|null $activeItem */
$activeItem = $activeCart->items()
->where('catalog_item_id', $sourceItem->catalog_item_id)
->where('variant_id', $sourceItem->variant_id)
->lockForUpdate()
->first();
if ($activeItem === null) {
$activeCart->items()->create([
'catalog_item_id' => $sourceItem->catalog_item_id,
'variant_id' => $sourceItem->variant_id,
'cantidad' => $sourceItem->cantidad,
]);
} else {
$activeItem->increment('cantidad', (int) $sourceItem->cantidad);
}
}
$sourceCart->update([
'status' => 'converted',
'guest_token' => null,
]);
if (! $sourceCart->trashed()) {
$sourceCart->delete();
}
return true;
}
if ($sourceCart->trashed()) {
$sourceCart->restore();
}
$sourceCart->update([
'status' => 'active',
'user_id' => $purchase->user_id,
'guest_token' => null,
]);
return true;
}
private function syncSourceCartItemQuantity(
Purchase $purchase,
PurchaseItem $purchaseItem,
int $quantity,
): void {
if ($purchase->cart_id === null) {
return;
}
$sourceCart = Cart::withTrashed()
->whereKey($purchase->cart_id)
->lockForUpdate()
->first();
if ($sourceCart === null) {
return;
}
$sourceCart->items()
->where('catalog_item_id', $purchaseItem->source_catalog_item_id)
->where('variant_id', $purchaseItem->source_variant_id)
->update([
'cantidad' => $quantity,
]);
}
private function finalizeSourceCart(Purchase $purchase): void
{
if ($purchase->cart_id === null) {
return;
}
/** @var Cart|null $sourceCart */
$sourceCart = Cart::withTrashed()
->whereKey($purchase->cart_id)
->lockForUpdate()
->first();
if ($sourceCart === null || $sourceCart->trashed()) {
return;
}
$sourceCart->update([
'status' => 'converted',
'guest_token' => null,
]);
$sourceCart->delete();
}
/**
* @param array<string, mixed> $purchaseData
*/
private function createPurchase(
Tenant $tenant,
int $userId,
array $purchaseData,
float $total,
?int $cartId,
): Purchase {
return Purchase::query()->create([
...$purchaseData,
'cart_id' => $cartId,
'tenant_codigo' => $tenant->codigo,
'user_id' => $userId,
'status' => Purchase::STATUS_CREATED,
'payment_method' => null,
'expires_at' => now()->addMinutes(
max(1, (int) config('purchase.checkout_expiration_minutes', 30)),
),
'total' => $total,
]);
}
protected function verifyTenantItems(Tenant $tenant, Collection $cartItems): void
{
foreach ($cartItems as $item) {
$selectedItem = $item->selectedItem();
if ($selectedItem === null) {
if ($item->selectedItem() === null) {
throw ValidationException::withMessages([
'cart_id' => 'One or more catalog items could not be loaded.',
]);
@@ -170,10 +608,6 @@ class CheckoutService
}
}
/**
* @param Collection<int, CartItem> $cartItems
* @return Collection<int, CartItem>
*/
protected function resolveCheckoutCart(Tenant $tenant, int $userId, int $cartId): Cart
{
/** @var Cart|null $cart */
@@ -198,21 +632,14 @@ class CheckoutService
* @param Collection<int, CartItem> $cartItems
* @return array<int, array<string, mixed>>
*/
protected function buildPurchaseItemsPayload(
Purchase $purchase,
Collection $cartItems,
array &$snapshotPaths = [],
): array {
protected function buildPurchaseItemsPayload(Collection $cartItems): array
{
return $cartItems
->map(function (CartItem $item) use ($purchase, &$snapshotPaths): array {
->map(function (CartItem $item): array {
$selectedItem = $item->selectedItem();
$quantity = (int) $item['cantidad'];
$quantity = (int) $item->cantidad;
$unitPrice = $selectedItem?->getPrice() ?? 0;
$imageAttachment = $this->snapshotFirstImage($purchase, $item);
if ($imageAttachment !== null) {
$snapshotPaths[] = $imageAttachment->path;
}
$imageAttachment = $this->firstImageAttachment($item);
return [
'source_catalog_item_id' => $item->catalog_item_id,
@@ -230,37 +657,117 @@ class CheckoutService
'discount_total' => null,
'tax_total' => null,
'total' => $unitPrice * $quantity,
'reservation_status' => PurchaseItem::RESERVATION_ACTIVE,
];
})
->all();
}
/**
* @param Collection<int, CartItem> $cartItems
*/
protected function completeCartConversion(Cart $cart, Collection $cartItems): void
{
foreach ($cartItems as $item) {
$selectedItem = $item->selectedItem();
$quantity = (int) $item->cantidad;
private function resolveSelection(
Tenant $tenant,
int $catalogItemId,
?int $variantId,
): CatalogItem|Variant {
/** @var CatalogItem|null $catalogItem */
$catalogItem = CatalogItem::query()
->whereKey($catalogItemId)
->where('tenant_code', $tenant->codigo)
->lockForUpdate()
->first();
try {
$this->catalogInventoryService->commit(
$selectedItem,
$quantity,
);
} catch (\InvalidArgumentException $exception) {
throw ValidationException::withMessages([
'cart_id' => 'The selected cart has inconsistent stock state.',
]);
}
if ($catalogItem === null) {
throw new NotFoundHttpException('Catalog item not found for tenant.');
}
$cart->status = 'converted';
$cart->user_id = null;
$cart->guest_token = null;
$cart->save();
$cart->delete();
if ($catalogItem->isBundle()) {
if ($variantId !== null) {
throw ValidationException::withMessages([
'direct_item.variant_id' => 'Un bundle no admite una variante.',
]);
}
if (! $catalogItem->bundleComponents()->exists()) {
throw ValidationException::withMessages([
'direct_item.catalog_item_id' => 'El bundle no tiene componentes.',
]);
}
return $catalogItem;
}
if ($variantId === null) {
if ($catalogItem->inventory_id === null) {
throw ValidationException::withMessages([
'direct_item.variant_id' => 'Debe seleccionar una variante para este item.',
]);
}
$catalogItem->setRelation(
'inventory',
Inventory::query()->whereKey($catalogItem->inventory_id)->lockForUpdate()->firstOrFail(),
);
return $catalogItem;
}
/** @var Variant|null $variant */
$variant = Variant::query()
->whereKey($variantId)
->where('catalog_item_id', $catalogItem->id)
->lockForUpdate()
->first();
if ($variant === null) {
throw new NotFoundHttpException('Variant not found for catalog item.');
}
$variant->setRelation('catalogItem', $catalogItem);
$variant->setRelation(
'inventory',
Inventory::query()->whereKey($variant->inventory_id)->lockForUpdate()->firstOrFail(),
);
return $variant;
}
private function resolvePurchaseItemSelection(Tenant $tenant, PurchaseItem $item): CatalogItem|Variant
{
return $this->resolveSelection(
$tenant,
(int) $item->source_catalog_item_id,
$item->source_variant_id === null ? null : (int) $item->source_variant_id,
);
}
private function makeDirectCartItem(
CatalogItem|Variant $selection,
int $catalogItemId,
?int $variantId,
int $quantity,
): CartItem {
$catalogItem = $selection instanceof Variant
? $selection->catalogItem
: $selection;
$catalogItem->loadMissing(['inventory', 'attachments']);
if ($selection instanceof Variant) {
$selection->loadMissing([
'inventory',
'attachments',
'catalogItem',
'definitions.itemAttribute.attribute',
]);
}
$item = new CartItem([
'catalog_item_id' => $catalogItemId,
'variant_id' => $variantId,
'cantidad' => $quantity,
]);
$item->setRelation('catalogItem', $catalogItem);
$item->setRelation('variant', $selection instanceof Variant ? $selection : null);
return $item;
}
/** @param Collection<int, CartItem> $cartItems */
@@ -283,19 +790,10 @@ class CheckoutService
]);
}
private function snapshotFirstImage(Purchase $purchase, CartItem $item): ?Attachment
private function firstImageAttachment(CartItem $item): ?Attachment
{
$source = $item->variant?->attachments->first()
return $item->variant?->attachments->first()
?? $item->catalogItem?->attachments->first();
if ($source === null) {
return null;
}
return $this->attachmentService->copy(
$source,
"purchase/{$purchase->id}",
);
}
/** @return array<int, array{name: string, value: mixed}> */