import { ChangeDetectionStrategy, Component } from '@angular/core';
import { marker as _ } from '@biesbjerg/ngx-translate-extract-marker';
import { I18nService, } from '@ishop/admin-ui/core';
import { summate } from '@ishop/common/lib/shared-utils';
export class RefundOrderDialogComponent {
    constructor(i18nService) {
        this.i18nService = i18nService;
        this.lineQuantities = {};
        this.refundShipping = false;
        this.adjustment = 0;
        this.reasons = [_('order.refund-reason-customer-request'), _('order.refund-reason-not-available')];
        this.reasons = this.reasons.map(r => this.i18nService.translate(r));
    }
    get refundTotal() {
        const itemTotal = this.order.lines.reduce((total, line) => {
            const lineRef = this.lineQuantities[line.id];
            const refundCount = (lineRef.refund && lineRef.quantity) || 0;
            return total + line.proratedUnitPriceWithTax * refundCount;
        }, 0);
        return itemTotal + (this.refundShipping ? this.order.shippingWithTax : 0) + this.adjustment;
    }
    get settledPaymentsTotal() {
        return this.settledPayments
            .map(payment => {
            const paymentTotal = payment.amount;
            const alreadyRefundedTotal = summate(payment.refunds.filter(r => r.state !== 'Failed'), 'total');
            return paymentTotal - alreadyRefundedTotal;
        })
            .reduce((sum, amount) => sum + amount, 0);
    }
    lineCanBeRefundedOrCancelled(line) {
        var _a, _b;
        const refunds = (_b = (_a = this.order.payments) === null || _a === void 0 ? void 0 : _a.reduce((all, payment) => [...all, ...payment.refunds], [])) !== null && _b !== void 0 ? _b : [];
        const refundable = line.items.filter(i => {
            if (i.cancelled) {
                return false;
            }
            if (i.refundId == null) {
                return true;
            }
            const refund = refunds.find(r => r.id === i.refundId);
            return (refund === null || refund === void 0 ? void 0 : refund.state) === 'Failed';
        });
        return 0 < refundable.length;
    }
    ngOnInit() {
        this.lineQuantities = this.order.lines.reduce((result, line) => {
            return Object.assign(Object.assign({}, result), { [line.id]: {
                    quantity: 0,
                    refund: false,
                    cancel: false,
                } });
        }, {});
        this.settledPayments = (this.order.payments || []).filter(p => p.state === 'Settled');
        if (this.settledPayments.length) {
            this.selectedPayment = this.settledPayments[0];
        }
    }
    handleZeroQuantity(line) {
        if ((line === null || line === void 0 ? void 0 : line.quantity) === 0) {
            line.cancel = false;
            line.refund = false;
        }
    }
    isRefunding() {
        const result = Object.values(this.lineQuantities).reduce((isRefunding, line) => {
            return isRefunding || (0 < line.quantity && line.refund);
        }, false);
        return result;
    }
    isCancelling() {
        const result = Object.values(this.lineQuantities).reduce((isCancelling, line) => {
            return isCancelling || (0 < line.quantity && line.cancel);
        }, false);
        return result;
    }
    canSubmit() {
        if (this.isRefunding()) {
            return !!(this.selectedPayment &&
                this.reason &&
                0 < this.refundTotal &&
                this.refundTotal <= this.settledPaymentsTotal);
        }
        else if (this.isCancelling()) {
            return !!this.reason;
        }
        return false;
    }
    select() {
        const payment = this.selectedPayment;
        if (payment) {
            const refundLines = this.getOrderLineInput(line => line.refund);
            const cancelLines = this.getOrderLineInput(line => line.cancel);
            this.resolveWith({
                refund: {
                    lines: refundLines,
                    reason: this.reason,
                    shipping: this.refundShipping ? this.order.shipping : 0,
                    adjustment: this.adjustment,
                    paymentId: payment.id,
                },
                cancel: {
                    lines: cancelLines,
                    orderId: this.order.id,
                    reason: this.reason,
                },
            });
        }
    }
    cancel() {
        this.resolveWith();
    }
    getOrderLineInput(filterFn) {
        return Object.entries(this.lineQuantities)
            .filter(([orderLineId, line]) => 0 < line.quantity && filterFn(line))
            .map(([orderLineId, line]) => ({
            orderLineId,
            quantity: line.quantity,
        }));
    }
}
RefundOrderDialogComponent.decorators = [
    { type: Component, args: [{
                selector: 'vdr-refund-order-dialog',
                template: "<ng-template vdrDialogTitle>{{ 'order.refund-and-cancel-order' | translate }}</ng-template>\r\n\r\n<div class=\"refund-wrapper\">\r\n    <div class=\"order-table\">\r\n        <table class=\"table\">\r\n            <thead>\r\n                <tr>\r\n                    <th></th>\r\n                    <th>{{ 'order.product-name' | translate }}</th>\r\n                    <th>{{ 'order.product-sku' | translate }}</th>\r\n                    <th>{{ 'order.quantity' | translate }}</th>\r\n                    <th>{{ 'order.unit-price' | translate }}</th>\r\n                    <th>{{ 'order.prorated-unit-price' | translate }}</th>\r\n                    <th>{{ 'order.quantity' | translate }}</th>\r\n                    <th>{{ 'order.refund' | translate }}</th>\r\n                    <th>{{ 'order.cancel' | translate }}</th>\r\n                </tr>\r\n            </thead>\r\n            <tr *ngFor=\"let line of order.lines\" class=\"order-line\">\r\n                <td class=\"align-middle thumb\">\r\n                    <img [src]=\"line.featuredAsset | assetPreview: 'tiny'\" />\r\n                </td>\r\n                <td class=\"align-middle name\">{{ line.productVariant.name }}</td>\r\n                <td class=\"align-middle sku\">{{ line.productVariant.sku }}</td>\r\n                <td class=\"align-middle quantity\">\r\n                    {{ line.quantity }}\r\n                    <vdr-line-refunds [line]=\"line\" [payments]=\"order.payments\"></vdr-line-refunds>\r\n                </td>\r\n                <td class=\"align-middle quantity\">\r\n                    {{ line.unitPriceWithTax | localeCurrency: order.currencyCode }}\r\n                </td>\r\n                <td class=\"align-middle quantity\">\r\n                    <div class=\"prorated-wrapper\">\r\n                        {{ line.proratedUnitPriceWithTax | localeCurrency: order.currencyCode }}\r\n                        <ng-container *ngIf=\"line.discounts as discounts\">\r\n                            <vdr-dropdown *ngIf=\"discounts.length\">\r\n                                <div class=\"promotions-label\" vdrDropdownTrigger>\r\n                                    <button class=\"icon-button\"><clr-icon shape=\"info\"></clr-icon></button>\r\n                                </div>\r\n                                <vdr-dropdown-menu>\r\n                                    <div class=\"line-promotion\" *ngFor=\"let discount of discounts\">\r\n                                        {{ discount.description }}\r\n                                        <div class=\"promotion-amount\">\r\n                                            {{\r\n                                                discount.amount / 100 / line.quantity\r\n                                                    | number: '1.0-2'\r\n                                                    | currency: order.currencyCode\r\n                                            }}\r\n                                        </div>\r\n                                    </div>\r\n                                </vdr-dropdown-menu>\r\n                            </vdr-dropdown>\r\n                        </ng-container>\r\n                    </div>\r\n                </td>\r\n                <td class=\"align-middle fulfil\">\r\n                    <input\r\n                        *ngIf=\"lineCanBeRefundedOrCancelled(line)\"\r\n                        [(ngModel)]=\"lineQuantities[line.id].quantity\"\r\n                        type=\"number\"\r\n                        [max]=\"line.quantity\"\r\n                        min=\"0\"\r\n                        (input)=\"handleZeroQuantity(lineQuantities[line.id])\"\r\n                    />\r\n                </td>\r\n                <td class=\"align-middle\">\r\n                    <div class=\"cancel-checkbox-wrapper\">\r\n                        <input\r\n                            type=\"checkbox\"\r\n                            *ngIf=\"lineCanBeRefundedOrCancelled(line)\"\r\n                            clrCheckbox\r\n                            [disabled]=\"0 === lineQuantities[line.id].quantity\"\r\n                            [(ngModel)]=\"lineQuantities[line.id].refund\"\r\n                        />\r\n                    </div>\r\n                </td>\r\n                <td class=\"align-middle\">\r\n                    <div class=\"cancel-checkbox-wrapper\">\r\n                        <input\r\n                            type=\"checkbox\"\r\n                            *ngIf=\"lineCanBeRefundedOrCancelled(line)\"\r\n                            clrCheckbox\r\n                            [disabled]=\"0 === lineQuantities[line.id].quantity\"\r\n                            [(ngModel)]=\"lineQuantities[line.id].cancel\"\r\n                        />\r\n                    </div>\r\n                </td>\r\n            </tr>\r\n        </table>\r\n    </div>\r\n    <div class=\"refund-details mt4\">\r\n        <div>\r\n            <label class=\"clr-control-label\">{{ 'order.refund-cancellation-reason' | translate }}</label>\r\n            <ng-select\r\n                [disabled]=\"!isRefunding() && !isCancelling()\"\r\n                [items]=\"reasons\"\r\n                bindLabel=\"name\"\r\n                autofocus\r\n                [placeholder]=\"'order.refund-cancellation-reason-required' | translate\"\r\n                bindValue=\"id\"\r\n                [addTag]=\"true\"\r\n                [(ngModel)]=\"reason\"\r\n            ></ng-select>\r\n        </div>\r\n\r\n        <div>\r\n            <clr-select-container>\r\n                <label>{{ 'order.payment-to-refund' | translate }}</label>\r\n                <select clrSelect name=\"options\" [(ngModel)]=\"selectedPayment\" [disabled]=\"!isRefunding()\">\r\n                    <option\r\n                        *ngFor=\"let payment of settledPayments\"\r\n                        [ngValue]=\"payment\"\r\n                        [disabled]=\"payment.state !== 'Settled'\"\r\n                    >\r\n                        #{{ payment.id }} {{ payment.method }}:\r\n                        {{ payment.amount | localeCurrency: order.currencyCode }}\r\n                    </option>\r\n                </select>\r\n            </clr-select-container>\r\n\r\n            <clr-checkbox-wrapper>\r\n                <input type=\"checkbox\" clrCheckbox [(ngModel)]=\"refundShipping\" [disabled]=\"!isRefunding()\" />\r\n                <label>\r\n                    {{ 'order.refund-shipping' | translate }} ({{\r\n                        order.shipping | localeCurrency: order.currencyCode\r\n                    }})\r\n                </label>\r\n            </clr-checkbox-wrapper>\r\n            <clr-input-container>\r\n                <label>{{ 'order.refund-adjustment' | translate }}</label>\r\n                <vdr-currency-input\r\n                    clrInput\r\n                    [disabled]=\"!isRefunding()\"\r\n                    [currencyCode]=\"order.currencyCode\"\r\n                    [(ngModel)]=\"adjustment\"\r\n                ></vdr-currency-input>\r\n            </clr-input-container>\r\n            <div class=\"totals\" [class.disabled]=\"!isRefunding()\">\r\n                <div class=\"order-total\">\r\n                    {{ 'order.payment-amount' | translate }}:\r\n                    {{ selectedPayment.amount | localeCurrency: order.currencyCode }}\r\n                </div>\r\n                <div class=\"refund-total\">\r\n                    {{ 'order.refund-total' | translate }}:\r\n                    {{ refundTotal | localeCurrency: order.currencyCode }}\r\n                </div>\r\n                <div class=\"refund-total-error\" *ngIf=\"refundTotal < 0 || settledPaymentsTotal < refundTotal\">\r\n                    {{\r\n                        'order.refund-total-error'\r\n                            | translate\r\n                                : {\r\n                                      min: 0 | currency: order.currencyCode,\r\n                                      max: settledPaymentsTotal | localeCurrency: order.currencyCode\r\n                                  }\r\n                    }}\r\n                </div>\r\n                <div class=\"refund-total-warning\" *ngIf=\"selectedPayment.amount < refundTotal\">\r\n                    {{ 'order.refund-total-warning' | translate }}\r\n                </div>\r\n            </div>\r\n        </div>\r\n    </div>\r\n</div>\r\n\r\n<ng-template vdrDialogButtons>\r\n    <button type=\"button\" class=\"btn\" (click)=\"cancel()\">{{ 'common.cancel' | translate }}</button>\r\n    <button type=\"submit\" (click)=\"select()\" [disabled]=\"!canSubmit()\" class=\"btn btn-primary\">\r\n        <ng-container *ngIf=\"isRefunding(); else cancelling\">\r\n            {{\r\n                'order.refund-with-amount'\r\n                    | translate: { amount: refundTotal | localeCurrency: order.currencyCode }\r\n            }}\r\n        </ng-container>\r\n        <ng-template #cancelling>\r\n            {{ 'order.cancel-selected-items' | translate }}\r\n        </ng-template>\r\n    </button>\r\n</ng-template>\r\n",
                changeDetection: ChangeDetectionStrategy.OnPush,
                styles: [":host{height:100%;display:flex;min-height:64vh}.refund-wrapper{flex:1;flex-direction:column}.refund-wrapper .order-table{flex:1;overflow-y:auto}.refund-wrapper .order-table table{margin-top:0}.refund-wrapper tr.ignore{color:var(--color-grey-300)}.cancel-checkbox-wrapper{display:flex;align-items:center;justify-content:center}clr-checkbox-wrapper{margin-top:12px;margin-bottom:12px;display:block}.refund-details{display:flex;justify-content:space-between}.totals{margin-top:48px}.totals .refund-total{font-size:18px}.totals .refund-total-error{color:var(--color-error-500)}.totals .refund-total-warning{color:var(--color-warning-600);max-width:250px}.totals.disabled{color:var(--color-grey-300)}.prorated-wrapper{display:flex;justify-content:center}.line-promotion{display:flex;justify-content:space-between;font-size:12px;padding:3px 6px}.line-promotion .promotion-amount{margin-left:12px}"]
            },] }
];
RefundOrderDialogComponent.ctorParameters = () => [
    { type: I18nService }
];
//# sourceMappingURL=data:application/json;base64, 