OrderRequest.kt

/*
 * This file is part of GNU Taler
 * (C) 2026 Taler Systems S.A.
 *
 * GNU Taler is free software; you can redistribute it and/or modify it under the
 * terms of the GNU General Public License as published by the Free Software
 * Foundation; either version 3, or (at your option) any later version.
 *
 * GNU Taler is distributed in the hope that it will be useful, but WITHOUT ANY
 * WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR
 * A PARTICULAR PURPOSE.  See the GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License along with
 * GNU Taler; see the file COPYING.  If not, see <http://www.gnu.org/licenses/>
 */

package net.taler.merchantpos.payment

import net.taler.common.RelativeTime
import net.taler.merchantlib.MinimalInventoryProduct
import net.taler.merchantpos.order.Order

import java.util.concurrent.TimeUnit.HOURS

/** Refund window for orders created at the till. */
internal val POS_REFUND_DELAY: RelativeTime = RelativeTime.fromMillis(HOURS.toMillis(1))

internal data class OrderParts(
    val contractTerms: net.taler.common.Order,
    val inventoryProducts: List<MinimalInventoryProduct>?,
)

/**
 * The backend expands inventory lines and merges them with explicit custom lines.
 */
internal fun Order.toOrderParts(includeProducts: Boolean): OrderParts
{
    val inventoryProducts =
        if (includeProducts)
        {
            products.mapNotNull { product ->
                val productId = product.productId ?: return@mapNotNull null
                MinimalInventoryProduct(productId = productId, quantity = product.quantity)
            }
        }
        else
        {
            emptyList()
        }
    val useInventoryProducts = includeProducts && inventoryProducts.isNotEmpty()
    return OrderParts(
        contractTerms =
            toContractTerms(includeProducts = includeProducts).let { terms ->
                if (useInventoryProducts)
                {
                    terms.copy(
                        products =
                            products
                                .filter { it.productId == null }
                                .map { it.toContractProduct() }
                                .ifEmpty { null },
                    )
                }
                else
                {
                    terms
                }
            },
        inventoryProducts = inventoryProducts.takeIf { useInventoryProducts },
    )
}