import { ChangeDetectionStrategy, Component } from '@angular/core';
import { UntypedFormControl } from '@angular/forms';
import { configurableDefinitionToInstance, configurableOperationValueIsValid, GlobalFlag, toConfigurableOperationInput, } from '@vendure/admin-ui/core';
import * as i0 from "@angular/core";
import * as i1 from "@vendure/admin-ui/core";
import * as i2 from "@angular/common";
import * as i3 from "@angular/forms";
import * as i4 from "@ngx-translate/core";
export class FulfillOrderDialogComponent {
    constructor(dataService, changeDetector) {
        this.dataService = dataService;
        this.changeDetector = changeDetector;
        this.fulfillmentHandlerControl = new UntypedFormControl();
        this.fulfillmentQuantities = {};
    }
    ngOnInit() {
        this.dataService.settings.getGlobalSettings().single$.subscribe(({ globalSettings }) => {
            this.fulfillmentQuantities = this.order.lines.reduce((result, line) => {
                const fulfillCount = this.getFulfillableCount(line, globalSettings.trackInventory);
                return {
                    ...result,
                    [line.id]: { fulfillCount, max: fulfillCount },
                };
            }, {});
            this.changeDetector.markForCheck();
        });
        this.dataService.shippingMethod
            .getShippingMethodOperations()
            .mapSingle(data => data.fulfillmentHandlers)
            .subscribe(handlers => {
            this.fulfillmentHandlerDef =
                handlers.find(h => h.code === this.order.shippingLines[0]?.shippingMethod?.fulfillmentHandlerCode) || handlers[0];
            this.fulfillmentHandler = configurableDefinitionToInstance(this.fulfillmentHandlerDef);
            this.fulfillmentHandlerControl.patchValue(this.fulfillmentHandler);
            this.changeDetector.markForCheck();
        });
    }
    getFulfillableCount(line, globalTrackInventory) {
        const { trackInventory, stockOnHand } = line.productVariant;
        const effectiveTracInventory = trackInventory === GlobalFlag.INHERIT ? globalTrackInventory : trackInventory === GlobalFlag.TRUE;
        const unfulfilledCount = this.getUnfulfilledCount(line);
        return effectiveTracInventory ? Math.min(unfulfilledCount, stockOnHand) : unfulfilledCount;
    }
    getUnfulfilledCount(line) {
        const fulfilled = this.order.fulfillments
            ?.filter(f => f.state !== 'Cancelled')
            .map(f => f.lines)
            .flat()
            .filter(row => row.orderLineId === line.id)
            .reduce((sum, row) => sum + row.quantity, 0) ?? 0;
        return line.quantity - fulfilled;
    }
    canSubmit() {
        const totalCount = Object.values(this.fulfillmentQuantities).reduce((total, { fulfillCount }) => total + fulfillCount, 0);
        const fulfillmentQuantityIsValid = Object.values(this.fulfillmentQuantities).every(({ fulfillCount, max }) => fulfillCount <= max);
        const formIsValid = configurableOperationValueIsValid(this.fulfillmentHandlerDef, this.fulfillmentHandlerControl.value) && this.fulfillmentHandlerControl.valid;
        return formIsValid && 0 < totalCount && fulfillmentQuantityIsValid;
    }
    select() {
        const lines = Object.entries(this.fulfillmentQuantities).map(([orderLineId, { fulfillCount }]) => ({
            orderLineId,
            quantity: fulfillCount,
        }));
        this.resolveWith({
            lines,
            handler: toConfigurableOperationInput(this.fulfillmentHandler, this.fulfillmentHandlerControl.value),
        });
    }
    cancel() {
        this.resolveWith();
    }
    static { this.ɵfac = i0.ɵɵngDeclareFactory({ minVersion: "12.0.0", version: "16.2.2", ngImport: i0, type: FulfillOrderDialogComponent, deps: [{ token: i1.DataService }, { token: i0.ChangeDetectorRef }], target: i0.ɵɵFactoryTarget.Component }); }
    static { this.ɵcmp = i0.ɵɵngDeclareComponent({ minVersion: "14.0.0", version: "16.2.2", type: FulfillOrderDialogComponent, selector: "vdr-fulfill-order-dialog", ngImport: i0, template: "<ng-template vdrDialogTitle>{{ 'order.fulfill-order' | translate }}</ng-template>\n\n<div class=\"fulfillment-wrapper\">\n    <div class=\"order-table\">\n        <table class=\"table\">\n            <thead>\n                <tr>\n                    <th></th>\n                    <th>{{ 'order.product-name' | translate }}</th>\n                    <th>{{ 'order.product-sku' | translate }}</th>\n                    <th>{{ 'order.unfulfilled' | translate }}</th>\n                    <th>{{ 'catalog.stock-on-hand' | translate }}</th>\n                    <th>{{ 'order.fulfill' | translate }}</th>\n                </tr>\n            </thead>\n            <tr\n                *ngFor=\"let line of order.lines\"\n                class=\"order-line\"\n                [class.ignore]=\"getUnfulfilledCount(line) === 0\"\n            >\n                <td class=\"align-middle thumb\">\n                    <img *ngIf=\"line.featuredAsset\" [src]=\"line.featuredAsset | assetPreview: 'tiny'\" />\n                </td>\n                <td class=\"align-middle name\">{{ line.productVariant.name }}</td>\n                <td class=\"align-middle sku\">{{ line.productVariant.sku }}</td>\n                <td class=\"align-middle quantity\">{{ getUnfulfilledCount(line) }}</td>\n                <td class=\"align-middle quantity\">{{ line.productVariant.stockOnHand }}</td>\n                <td class=\"align-middle fulfil\">\n                    <input\n                        *ngIf=\"fulfillmentQuantities[line.id]\"\n                        [disabled]=\"getUnfulfilledCount(line) === 0\"\n                        [(ngModel)]=\"fulfillmentQuantities[line.id].fulfillCount\"\n                        type=\"number\"\n                        [max]=\"fulfillmentQuantities[line.id].max\"\n                        min=\"0\"\n                    />\n                </td>\n            </tr>\n        </table>\n    </div>\n    <div class=\"shipping-details\">\n        <vdr-formatted-address [address]=\"order.shippingAddress\"></vdr-formatted-address>\n        <h6>{{ 'order.shipping-method' | translate }}</h6>\n        {{ order.shippingLines[0]?.shippingMethod?.name }}\n        <strong>{{ order.shipping | localeCurrency: order.currencyCode }}</strong>\n        <vdr-configurable-input\n            [operationDefinition]=\"fulfillmentHandlerDef\"\n            [operation]=\"fulfillmentHandler\"\n            [formControl]=\"fulfillmentHandlerControl\"\n            [removable]=\"false\"\n        ></vdr-configurable-input>\n    </div>\n</div>\n\n<ng-template vdrDialogButtons>\n    <button type=\"button\" class=\"btn\" (click)=\"cancel()\">{{ 'common.cancel' | translate }}</button>\n    <button type=\"submit\" (click)=\"select()\" [disabled]=\"!canSubmit()\" class=\"btn btn-primary\">\n        {{ 'order.create-fulfillment' | translate }}\n    </button>\n</ng-template>\n", styles: [":host{height:100%;display:flex;min-height:64vh}:host .is-cancelled td{text-decoration:line-through;background-color:var(--color-component-bg-200)}:host .sub-total td{border-top:1px dashed var(--color-component-border-200)}:host .total td{font-weight:700;border-top:1px dashed var(--color-component-border-200)}:host td.custom-fields-row{border-top-style:dashed;border-top-color:var(--color-grey-200)}:host img{border-radius:var(--border-radius-img)}:host .order-line-custom-fields{display:flex;flex-wrap:wrap}:host .order-line-custom-fields .custom-field{text-align:start;max-width:200px;overflow:hidden;text-overflow:ellipsis;margin-bottom:6px;margin-inline-end:18px}:host .draft-qty{max-width:48px}:host .order-line-custom-field{background-color:var(--color-component-bg-100)}:host .order-line-custom-field .custom-field-ellipsis{color:var(--color-text-300)}:host .net-price{font-size:11px;color:var(--color-text-300);line-height:14px}:host .promotions-label{-webkit-text-decoration:underline dotted var(--color-text-200);text-decoration:underline dotted var(--color-text-200);font-size:11px;margin-top:6px;cursor:pointer;text-transform:lowercase}:host .thumb img{width:50px;height:50px}:host .shipping-method-name{font-size:var(--font-size-xs);margin-inline-end:2px}:host .order-placed-quantity{text-decoration:line-through;color:var(--color-text-300);margin-inline-end:2px}.fulfillment-wrapper{flex:1}@media screen and (min-width: 768px){.fulfillment-wrapper{display:flex;flex-direction:row}}.fulfillment-wrapper .shipping-details{margin-top:24px}@media screen and (min-width: 768px){.fulfillment-wrapper .shipping-details{margin-top:0;margin-inline-start:24px;width:250px}}.fulfillment-wrapper .shipping-details clr-input-container{margin-top:24px}.fulfillment-wrapper .order-table{flex:1;overflow-y:auto}.fulfillment-wrapper .order-table table{margin-top:0}.fulfillment-wrapper tr.ignore{color:var(--color-grey-300)}\n"], dependencies: [{ kind: "directive", type: i2.NgForOf, selector: "[ngFor][ngForOf]", inputs: ["ngForOf", "ngForTrackBy", "ngForTemplate"] }, { kind: "directive", type: i2.NgIf, selector: "[ngIf]", inputs: ["ngIf", "ngIfThen", "ngIfElse"] }, { kind: "directive", type: i3.DefaultValueAccessor, selector: "input:not([type=checkbox])[formControlName],textarea[formControlName],input:not([type=checkbox])[formControl],textarea[formControl],input:not([type=checkbox])[ngModel],textarea[ngModel],[ngDefaultControl]" }, { kind: "directive", type: i3.NumberValueAccessor, selector: "input[type=number][formControlName],input[type=number][formControl],input[type=number][ngModel]" }, { kind: "directive", type: i3.NgControlStatus, selector: "[formControlName],[ngModel],[formControl]" }, { kind: "directive", type: i3.MinValidator, selector: "input[type=number][min][formControlName],input[type=number][min][formControl],input[type=number][min][ngModel]", inputs: ["min"] }, { kind: "directive", type: i3.MaxValidator, selector: "input[type=number][max][formControlName],input[type=number][max][formControl],input[type=number][max][ngModel]", inputs: ["max"] }, { kind: "directive", type: i3.NgModel, selector: "[ngModel]:not([formControlName]):not([formControl])", inputs: ["name", "disabled", "ngModel", "ngModelOptions"], outputs: ["ngModelChange"], exportAs: ["ngModel"] }, { kind: "directive", type: i3.FormControlDirective, selector: "[formControl]", inputs: ["formControl", "disabled", "ngModel"], outputs: ["ngModelChange"], exportAs: ["ngForm"] }, { kind: "component", type: i1.ConfigurableInputComponent, selector: "vdr-configurable-input", inputs: ["operation", "operationDefinition", "readonly", "removable", "position"], outputs: ["remove"] }, { kind: "directive", type: i1.FormFieldControlDirective, selector: "input, textarea, select" }, { kind: "directive", type: i1.DialogButtonsDirective, selector: "[vdrDialogButtons]" }, { kind: "directive", type: i1.DialogTitleDirective, selector: "[vdrDialogTitle]" }, { kind: "component", type: i1.FormattedAddressComponent, selector: "vdr-formatted-address", inputs: ["address"] }, { kind: "pipe", type: i4.TranslatePipe, name: "translate" }, { kind: "pipe", type: i1.AssetPreviewPipe, name: "assetPreview" }, { kind: "pipe", type: i1.LocaleCurrencyPipe, name: "localeCurrency" }], changeDetection: i0.ChangeDetectionStrategy.OnPush }); }
}
i0.ɵɵngDeclareClassMetadata({ minVersion: "12.0.0", version: "16.2.2", ngImport: i0, type: FulfillOrderDialogComponent, decorators: [{
            type: Component,
            args: [{ selector: 'vdr-fulfill-order-dialog', changeDetection: ChangeDetectionStrategy.OnPush, template: "<ng-template vdrDialogTitle>{{ 'order.fulfill-order' | translate }}</ng-template>\n\n<div class=\"fulfillment-wrapper\">\n    <div class=\"order-table\">\n        <table class=\"table\">\n            <thead>\n                <tr>\n                    <th></th>\n                    <th>{{ 'order.product-name' | translate }}</th>\n                    <th>{{ 'order.product-sku' | translate }}</th>\n                    <th>{{ 'order.unfulfilled' | translate }}</th>\n                    <th>{{ 'catalog.stock-on-hand' | translate }}</th>\n                    <th>{{ 'order.fulfill' | translate }}</th>\n                </tr>\n            </thead>\n            <tr\n                *ngFor=\"let line of order.lines\"\n                class=\"order-line\"\n                [class.ignore]=\"getUnfulfilledCount(line) === 0\"\n            >\n                <td class=\"align-middle thumb\">\n                    <img *ngIf=\"line.featuredAsset\" [src]=\"line.featuredAsset | assetPreview: 'tiny'\" />\n                </td>\n                <td class=\"align-middle name\">{{ line.productVariant.name }}</td>\n                <td class=\"align-middle sku\">{{ line.productVariant.sku }}</td>\n                <td class=\"align-middle quantity\">{{ getUnfulfilledCount(line) }}</td>\n                <td class=\"align-middle quantity\">{{ line.productVariant.stockOnHand }}</td>\n                <td class=\"align-middle fulfil\">\n                    <input\n                        *ngIf=\"fulfillmentQuantities[line.id]\"\n                        [disabled]=\"getUnfulfilledCount(line) === 0\"\n                        [(ngModel)]=\"fulfillmentQuantities[line.id].fulfillCount\"\n                        type=\"number\"\n                        [max]=\"fulfillmentQuantities[line.id].max\"\n                        min=\"0\"\n                    />\n                </td>\n            </tr>\n        </table>\n    </div>\n    <div class=\"shipping-details\">\n        <vdr-formatted-address [address]=\"order.shippingAddress\"></vdr-formatted-address>\n        <h6>{{ 'order.shipping-method' | translate }}</h6>\n        {{ order.shippingLines[0]?.shippingMethod?.name }}\n        <strong>{{ order.shipping | localeCurrency: order.currencyCode }}</strong>\n        <vdr-configurable-input\n            [operationDefinition]=\"fulfillmentHandlerDef\"\n            [operation]=\"fulfillmentHandler\"\n            [formControl]=\"fulfillmentHandlerControl\"\n            [removable]=\"false\"\n        ></vdr-configurable-input>\n    </div>\n</div>\n\n<ng-template vdrDialogButtons>\n    <button type=\"button\" class=\"btn\" (click)=\"cancel()\">{{ 'common.cancel' | translate }}</button>\n    <button type=\"submit\" (click)=\"select()\" [disabled]=\"!canSubmit()\" class=\"btn btn-primary\">\n        {{ 'order.create-fulfillment' | translate }}\n    </button>\n</ng-template>\n", styles: [":host{height:100%;display:flex;min-height:64vh}:host .is-cancelled td{text-decoration:line-through;background-color:var(--color-component-bg-200)}:host .sub-total td{border-top:1px dashed var(--color-component-border-200)}:host .total td{font-weight:700;border-top:1px dashed var(--color-component-border-200)}:host td.custom-fields-row{border-top-style:dashed;border-top-color:var(--color-grey-200)}:host img{border-radius:var(--border-radius-img)}:host .order-line-custom-fields{display:flex;flex-wrap:wrap}:host .order-line-custom-fields .custom-field{text-align:start;max-width:200px;overflow:hidden;text-overflow:ellipsis;margin-bottom:6px;margin-inline-end:18px}:host .draft-qty{max-width:48px}:host .order-line-custom-field{background-color:var(--color-component-bg-100)}:host .order-line-custom-field .custom-field-ellipsis{color:var(--color-text-300)}:host .net-price{font-size:11px;color:var(--color-text-300);line-height:14px}:host .promotions-label{-webkit-text-decoration:underline dotted var(--color-text-200);text-decoration:underline dotted var(--color-text-200);font-size:11px;margin-top:6px;cursor:pointer;text-transform:lowercase}:host .thumb img{width:50px;height:50px}:host .shipping-method-name{font-size:var(--font-size-xs);margin-inline-end:2px}:host .order-placed-quantity{text-decoration:line-through;color:var(--color-text-300);margin-inline-end:2px}.fulfillment-wrapper{flex:1}@media screen and (min-width: 768px){.fulfillment-wrapper{display:flex;flex-direction:row}}.fulfillment-wrapper .shipping-details{margin-top:24px}@media screen and (min-width: 768px){.fulfillment-wrapper .shipping-details{margin-top:0;margin-inline-start:24px;width:250px}}.fulfillment-wrapper .shipping-details clr-input-container{margin-top:24px}.fulfillment-wrapper .order-table{flex:1;overflow-y:auto}.fulfillment-wrapper .order-table table{margin-top:0}.fulfillment-wrapper tr.ignore{color:var(--color-grey-300)}\n"] }]
        }], ctorParameters: function () { return [{ type: i1.DataService }, { type: i0.ChangeDetectorRef }]; } });
//# sourceMappingURL=data:application/json;base64, 