"use strict";
var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
    if (k2 === undefined) k2 = k;
    Object.defineProperty(o, k2, { enumerable: true, get: function() { return m[k]; } });
}) : (function(o, m, k, k2) {
    if (k2 === undefined) k2 = k;
    o[k2] = m[k];
}));
var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
    Object.defineProperty(o, "default", { enumerable: true, value: v });
}) : function(o, v) {
    o["default"] = v;
});
var __importStar = (this && this.__importStar) || function (mod) {
    if (mod && mod.__esModule) return mod;
    var result = {};
    if (mod != null) for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k);
    __setModuleDefault(result, mod);
    return result;
};
var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
    function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
    return new (P || (P = Promise))(function (resolve, reject) {
        function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
        function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
        function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
        step((generator = generator.apply(thisArg, _arguments || [])).next());
    });
};
var __importDefault = (this && this.__importDefault) || function (mod) {
    return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
const bignumber_js_1 = __importDefault(require("bignumber.js"));
const sinon_1 = __importDefault(require("sinon"));
const configureDividendDistribution_1 = require("../configureDividendDistribution");
const mocks_1 = require("../../../testUtils/mocks");
const types_1 = require("../../../types");
const utils_1 = require("../../../types/utils");
const utilsConversionModule = __importStar(require("../../../utils/conversion"));
const utilsInternalModule = __importStar(require("../../../utils/internal"));
jest.mock('~/api/entities/DefaultPortfolio', require("../../../testUtils/mocks/entities").mockDefaultPortfolioModule('~/api/entities/DefaultPortfolio'));
jest.mock('~/api/entities/NumberedPortfolio', require("../../../testUtils/mocks/entities").mockNumberedPortfolioModule('~/api/entities/NumberedPortfolio'));
jest.mock('~/api/entities/DividendDistribution', require("../../../testUtils/mocks/entities").mockDividendDistributionModule('~/api/entities/DividendDistribution'));
jest.mock('~/api/entities/Identity', require("../../../testUtils/mocks/entities").mockIdentityModule('~/api/entities/Identity'));
jest.mock('~/api/entities/Asset', require("../../../testUtils/mocks/entities").mockAssetModule('~/api/entities/Asset'));
describe('configureDividendDistribution procedure', () => {
    let ticker;
    let declarationDate;
    let checkpoint;
    let description;
    let targets;
    let defaultTaxWithholding;
    let taxWithholdings;
    let originPortfolio;
    let currency;
    let perShare;
    let maxAmount;
    let paymentDate;
    let expiryDate;
    let rawPortfolioNumber;
    let rawCurrency;
    let rawPerShare;
    let rawAmount;
    let rawPaymentAt;
    let rawExpiresAt;
    let rawCaId;
    let distribution;
    let mockContext;
    let addTransactionStub;
    let distributeTransaction;
    let stringToTickerStub;
    let bigNumberToU64Stub;
    let dateToMomentStub;
    let bigNumberToBalanceStub;
    beforeAll(() => {
        mocks_1.entityMockUtils.initMocks();
        mocks_1.dsMockUtils.initMocks();
        mocks_1.procedureMockUtils.initMocks();
        ticker = 'SOME_TICKER';
        declarationDate = new Date('10/14/1987');
        checkpoint = new Date(new Date().getTime() + 60 * 60 * 1000);
        description = 'someDescription';
        targets = {
            identities: ['someDid'],
            treatment: types_1.TargetTreatment.Exclude,
        };
        defaultTaxWithholding = new bignumber_js_1.default(10);
        taxWithholdings = [{ identity: 'someDid', percentage: new bignumber_js_1.default(30) }];
        originPortfolio = mocks_1.entityMockUtils.getNumberedPortfolioInstance({
            id: new bignumber_js_1.default(2),
            getAssetBalances: [
                {
                    asset: mocks_1.entityMockUtils.getAssetInstance({ ticker: currency }),
                    total: new bignumber_js_1.default(1000001),
                    locked: new bignumber_js_1.default(0),
                    free: new bignumber_js_1.default(1000001),
                },
            ],
        });
        currency = 'USD';
        perShare = new bignumber_js_1.default(100);
        maxAmount = new bignumber_js_1.default(1000000);
        paymentDate = new Date(checkpoint.getTime() + 60 * 60 * 1000);
        expiryDate = new Date(paymentDate.getTime() + 60 * 60 * 1000 * 24 * 365);
        rawPortfolioNumber = mocks_1.dsMockUtils.createMockU64(originPortfolio.id);
        rawCurrency = mocks_1.dsMockUtils.createMockTicker(currency);
        rawPerShare = mocks_1.dsMockUtils.createMockBalance(perShare);
        rawAmount = mocks_1.dsMockUtils.createMockBalance(maxAmount);
        rawPaymentAt = mocks_1.dsMockUtils.createMockMoment(new bignumber_js_1.default(paymentDate.getTime()));
        rawExpiresAt = mocks_1.dsMockUtils.createMockMoment(new bignumber_js_1.default(expiryDate.getTime()));
        rawCaId = 'caId';
        distribution = 'distribution';
        stringToTickerStub = sinon_1.default.stub(utilsConversionModule, 'stringToTicker');
        bigNumberToU64Stub = sinon_1.default.stub(utilsConversionModule, 'bigNumberToU64');
        dateToMomentStub = sinon_1.default.stub(utilsConversionModule, 'dateToMoment');
        bigNumberToBalanceStub = sinon_1.default.stub(utilsConversionModule, 'bigNumberToBalance');
    });
    beforeEach(() => {
        mocks_1.procedureMockUtils.getAddProcedureStub().returns(rawCaId);
        addTransactionStub = mocks_1.procedureMockUtils.getAddTransactionStub().returns([distribution]);
        distributeTransaction = mocks_1.dsMockUtils.createTxStub('capitalDistribution', 'distribute');
        mockContext = mocks_1.dsMockUtils.getContextInstance();
        stringToTickerStub.withArgs(currency, mockContext).returns(rawCurrency);
        bigNumberToU64Stub.withArgs(originPortfolio.id, mockContext).returns(rawPortfolioNumber);
        dateToMomentStub.withArgs(paymentDate, mockContext).returns(rawPaymentAt);
        dateToMomentStub.withArgs(expiryDate, mockContext).returns(rawExpiresAt);
        bigNumberToBalanceStub.withArgs(perShare, mockContext).returns(rawPerShare);
        bigNumberToBalanceStub.withArgs(maxAmount, mockContext).returns(rawAmount);
    });
    afterEach(() => {
        mocks_1.entityMockUtils.reset();
        mocks_1.procedureMockUtils.reset();
        mocks_1.dsMockUtils.reset();
    });
    afterAll(() => {
        mocks_1.procedureMockUtils.cleanup();
        mocks_1.dsMockUtils.cleanup();
    });
    test('should throw an error if the Asset is being used as the distribution currency', () => __awaiter(void 0, void 0, void 0, function* () {
        const proc = mocks_1.procedureMockUtils.getInstance(mockContext, { portfolio: originPortfolio });
        let err;
        try {
            yield configureDividendDistribution_1.prepareConfigureDividendDistribution.call(proc, {
                ticker,
                declarationDate,
                checkpoint,
                description,
                targets,
                defaultTaxWithholding,
                taxWithholdings,
                originPortfolio,
                currency: ticker,
                perShare,
                maxAmount,
                paymentDate,
                expiryDate,
            });
        }
        catch (error) {
            err = error;
        }
        expect(err.message).toBe('Cannot distribute Dividends using the Asset as currency');
    }));
    test('should throw an error if the payment date is in the past', () => __awaiter(void 0, void 0, void 0, function* () {
        const proc = mocks_1.procedureMockUtils.getInstance(mockContext, { portfolio: originPortfolio });
        let err;
        try {
            yield configureDividendDistribution_1.prepareConfigureDividendDistribution.call(proc, {
                ticker,
                declarationDate,
                checkpoint,
                description,
                targets,
                defaultTaxWithholding,
                taxWithholdings,
                originPortfolio,
                currency,
                perShare,
                maxAmount,
                paymentDate: new Date('10/14/1987'),
                expiryDate,
            });
        }
        catch (error) {
            err = error;
        }
        expect(err.message).toBe('Payment date must be in the future');
    }));
    test('should throw an error if the payment date is earlier than the Checkpoint date', () => __awaiter(void 0, void 0, void 0, function* () {
        const proc = mocks_1.procedureMockUtils.getInstance(mockContext, { portfolio: originPortfolio });
        let err;
        try {
            yield configureDividendDistribution_1.prepareConfigureDividendDistribution.call(proc, {
                ticker,
                declarationDate,
                checkpoint,
                description,
                targets,
                defaultTaxWithholding,
                taxWithholdings,
                originPortfolio,
                currency,
                perShare,
                maxAmount,
                paymentDate: new Date(new Date().getTime() + 1000 * 60 * 20),
                expiryDate,
            });
        }
        catch (error) {
            err = error;
        }
        expect(err.message).toBe('Payment date must be after the Checkpoint date');
        try {
            yield configureDividendDistribution_1.prepareConfigureDividendDistribution.call(proc, {
                ticker,
                declarationDate,
                checkpoint: mocks_1.entityMockUtils.getCheckpointScheduleInstance({
                    details: {
                        nextCheckpointDate: new Date(new Date(new Date().getTime() + 1000 * 60 * 30)),
                    },
                }),
                description,
                targets,
                defaultTaxWithholding,
                taxWithholdings,
                originPortfolio,
                currency,
                perShare,
                maxAmount,
                paymentDate: new Date(new Date().getTime() + 1000 * 60 * 20),
                expiryDate,
            });
        }
        catch (error) {
            err = error;
        }
        expect(err.message).toBe('Payment date must be after the Checkpoint date');
    }));
    test('should throw an error if the payment date is after the expiry date', () => __awaiter(void 0, void 0, void 0, function* () {
        const proc = mocks_1.procedureMockUtils.getInstance(mockContext, { portfolio: originPortfolio });
        let err;
        try {
            yield configureDividendDistribution_1.prepareConfigureDividendDistribution.call(proc, {
                ticker,
                declarationDate,
                checkpoint,
                description,
                targets,
                defaultTaxWithholding,
                taxWithholdings,
                currency,
                perShare,
                maxAmount,
                paymentDate,
                expiryDate: new Date(paymentDate.getTime() - 1000),
            });
        }
        catch (error) {
            err = error;
        }
        expect(err.message).toBe('Expiry date must be after payment date');
    }));
    test('should throw an error if the origin Portfolio does not have enough balance', () => __awaiter(void 0, void 0, void 0, function* () {
        const proc = mocks_1.procedureMockUtils.getInstance(mockContext, {
            portfolio: mocks_1.entityMockUtils.getNumberedPortfolioInstance({
                getAssetBalances: [
                    {
                        asset: mocks_1.entityMockUtils.getAssetInstance({ ticker: currency }),
                        total: new bignumber_js_1.default(1),
                        locked: new bignumber_js_1.default(0),
                        free: new bignumber_js_1.default(1),
                    },
                ],
            }),
        });
        let err;
        try {
            yield configureDividendDistribution_1.prepareConfigureDividendDistribution.call(proc, {
                ticker,
                declarationDate,
                checkpoint: mocks_1.entityMockUtils.getCheckpointInstance(),
                description,
                targets,
                defaultTaxWithholding,
                taxWithholdings,
                originPortfolio,
                currency,
                perShare,
                maxAmount,
                paymentDate,
                expiryDate,
            });
        }
        catch (error) {
            err = error;
        }
        expect(err.message).toBe("The origin Portfolio's free balance is not enough to cover the Distribution amount");
        expect(err.data).toEqual({
            free: new bignumber_js_1.default(1),
        });
    }));
    test('should throw an error if the origin Portfolio does not exist', () => __awaiter(void 0, void 0, void 0, function* () {
        const proc = mocks_1.procedureMockUtils.getInstance(mockContext, {
            portfolio: mocks_1.entityMockUtils.getNumberedPortfolioInstance({
                exists: false,
            }),
        });
        let err;
        try {
            yield configureDividendDistribution_1.prepareConfigureDividendDistribution.call(proc, {
                ticker,
                declarationDate,
                checkpoint: mocks_1.entityMockUtils.getCheckpointInstance(),
                description,
                targets,
                defaultTaxWithholding,
                taxWithholdings,
                originPortfolio,
                currency,
                perShare,
                maxAmount,
                paymentDate,
                expiryDate,
            });
        }
        catch (error) {
            err = error;
        }
        expect(err.message).toBe("The origin Portfolio doesn't exist");
    }));
    test('should add a distribute transaction to the queue', () => __awaiter(void 0, void 0, void 0, function* () {
        let proc = mocks_1.procedureMockUtils.getInstance(mockContext, {
            portfolio: originPortfolio,
        });
        const result = yield configureDividendDistribution_1.prepareConfigureDividendDistribution.call(proc, {
            ticker,
            declarationDate,
            checkpoint,
            description,
            targets,
            defaultTaxWithholding,
            taxWithholdings,
            originPortfolio,
            currency,
            perShare,
            maxAmount,
            paymentDate,
            expiryDate,
        });
        sinon_1.default.assert.calledWith(addTransactionStub, sinon_1.default.match({
            transaction: distributeTransaction,
            resolvers: sinon_1.default.match.array,
            args: [
                rawCaId,
                rawPortfolioNumber,
                rawCurrency,
                rawPerShare,
                rawAmount,
                rawPaymentAt,
                rawExpiresAt,
            ],
        }));
        expect(result).toEqual(distribution);
        yield configureDividendDistribution_1.prepareConfigureDividendDistribution.call(proc, {
            ticker,
            declarationDate,
            checkpoint,
            description,
            targets,
            defaultTaxWithholding,
            taxWithholdings,
            originPortfolio: originPortfolio.id,
            currency,
            perShare,
            maxAmount,
            paymentDate,
            expiryDate,
        });
        sinon_1.default.assert.calledWith(addTransactionStub, sinon_1.default.match({
            transaction: distributeTransaction,
            resolvers: sinon_1.default.match.array,
            args: [
                rawCaId,
                rawPortfolioNumber,
                rawCurrency,
                rawPerShare,
                rawAmount,
                rawPaymentAt,
                rawExpiresAt,
            ],
        }));
        proc = mocks_1.procedureMockUtils.getInstance(mockContext, {
            portfolio: mocks_1.entityMockUtils.getDefaultPortfolioInstance({
                did: 'someDid',
                getAssetBalances: [
                    {
                        asset: mocks_1.entityMockUtils.getAssetInstance({ ticker: currency }),
                        total: new bignumber_js_1.default(1000001),
                        locked: new bignumber_js_1.default(0),
                        free: new bignumber_js_1.default(1000001),
                    },
                ],
            }),
        });
        yield configureDividendDistribution_1.prepareConfigureDividendDistribution.call(proc, {
            ticker,
            declarationDate,
            checkpoint,
            description,
            targets,
            defaultTaxWithholding,
            taxWithholdings,
            currency,
            perShare,
            maxAmount,
            paymentDate,
        });
        sinon_1.default.assert.calledWith(addTransactionStub, sinon_1.default.match({
            transaction: distributeTransaction,
            resolvers: sinon_1.default.match.array,
            args: [rawCaId, null, rawCurrency, rawPerShare, rawAmount, rawPaymentAt, null],
        }));
    }));
    describe('dividendDistributionResolver', () => {
        const filterEventRecordsStub = sinon_1.default.stub(utilsInternalModule, 'filterEventRecords');
        const id = new bignumber_js_1.default(1);
        const portfolioNumber = new bignumber_js_1.default(3);
        const did = 'someDid';
        let rawCorporateAction;
        let rawDistribution;
        beforeAll(() => {
            mocks_1.entityMockUtils.initMocks();
            /* eslint-disable @typescript-eslint/naming-convention */
            rawCorporateAction = mocks_1.dsMockUtils.createMockCorporateAction({
                kind: 'UnpredictableBenefit',
                decl_date: new bignumber_js_1.default(declarationDate.getTime()),
                record_date: mocks_1.dsMockUtils.createMockRecordDate({
                    date: new bignumber_js_1.default(new Date('10/14/2021').getTime()),
                    checkpoint: {
                        Scheduled: [
                            mocks_1.dsMockUtils.createMockU64(new bignumber_js_1.default(1)),
                            mocks_1.dsMockUtils.createMockU64(new bignumber_js_1.default(2)),
                        ],
                    },
                }),
                targets,
                default_withholding_tax: defaultTaxWithholding.shiftedBy(4),
                withholding_tax: taxWithholdings.map(({ identity, percentage }) => utils_1.tuple(identity, percentage.shiftedBy(4))),
            });
            rawDistribution = mocks_1.dsMockUtils.createMockDistribution({
                from: { did, kind: { User: mocks_1.dsMockUtils.createMockU64(portfolioNumber) } },
                currency,
                per_share: perShare.shiftedBy(6),
                amount: maxAmount.shiftedBy(6),
                remaining: new bignumber_js_1.default(10000),
                reclaimed: false,
                payment_at: new bignumber_js_1.default(paymentDate.getTime()),
                expires_at: mocks_1.dsMockUtils.createMockOption(mocks_1.dsMockUtils.createMockMoment(new bignumber_js_1.default(expiryDate === null || expiryDate === void 0 ? void 0 : expiryDate.getTime()))),
            });
            /* eslint-enable @typescript-eslint/naming-convention */
            mocks_1.dsMockUtils.createQueryStub('corporateAction', 'corporateActions', {
                returnValue: mocks_1.dsMockUtils.createMockOption(rawCorporateAction),
            });
            mocks_1.dsMockUtils.createQueryStub('corporateAction', 'details', {
                returnValue: mocks_1.dsMockUtils.createMockText(description),
            });
        });
        beforeEach(() => {
            /* eslint-disable @typescript-eslint/naming-convention */
            filterEventRecordsStub.returns([
                mocks_1.dsMockUtils.createMockIEvent([
                    'data',
                    mocks_1.dsMockUtils.createMockCAId({
                        ticker,
                        local_id: id,
                    }),
                    rawDistribution,
                ]),
            ]);
            /* eslint-enable @typescript-eslint/naming-convention */
        });
        afterEach(() => {
            filterEventRecordsStub.reset();
        });
        test('should return the new DividendDistribution', () => __awaiter(void 0, void 0, void 0, function* () {
            const result = yield configureDividendDistribution_1.createDividendDistributionResolver(mockContext)({});
            expect(result.asset.ticker).toBe(ticker);
            expect(result.id).toEqual(id);
            expect(result.declarationDate).toEqual(declarationDate);
            expect(result.description).toEqual(description);
            expect(result.targets).toEqual({
                identities: targets.identities.map(targetDid => expect.objectContaining({ did: targetDid })),
                treatment: targets.treatment,
            });
            expect(result.defaultTaxWithholding).toEqual(defaultTaxWithholding);
            expect(result.taxWithholdings).toEqual([
                {
                    identity: expect.objectContaining({ did: taxWithholdings[0].identity }),
                    percentage: taxWithholdings[0].percentage,
                },
            ]);
            expect(result.origin).toEqual(expect.objectContaining({
                owner: expect.objectContaining({ did }),
                id: new bignumber_js_1.default(portfolioNumber),
            }));
            expect(result.currency).toEqual(currency);
            expect(result.maxAmount).toEqual(maxAmount);
            expect(result.expiryDate).toEqual(expiryDate);
            expect(result.paymentDate).toEqual(paymentDate);
        }));
    });
    describe('getAuthorization', () => {
        test('should return the appropriate roles and permissions', () => {
            const proc = mocks_1.procedureMockUtils.getInstance(mockContext, { portfolio: originPortfolio });
            const boundFunc = configureDividendDistribution_1.getAuthorization.bind(proc);
            const args = {
                ticker,
            };
            expect(boundFunc(args)).toEqual({
                roles: [
                    {
                        type: types_1.RoleType.PortfolioCustodian,
                        portfolioId: { did: originPortfolio.owner.did, number: originPortfolio.id },
                    },
                ],
                permissions: {
                    transactions: [types_1.TxTags.capitalDistribution.Distribute],
                    assets: [expect.objectContaining({ ticker })],
                    portfolios: [originPortfolio],
                },
            });
        });
    });
    describe('prepareStorage', () => {
        test('should return the origin Portfolio', () => __awaiter(void 0, void 0, void 0, function* () {
            const did = 'someDid';
            mocks_1.dsMockUtils.configureMocks({
                contextOptions: {
                    did,
                },
            });
            const proc = mocks_1.procedureMockUtils.getInstance(mockContext);
            const boundFunc = configureDividendDistribution_1.prepareStorage.bind(proc);
            let result = yield boundFunc({ originPortfolio });
            expect(result).toEqual({
                portfolio: originPortfolio,
            });
            const portfolioId = new bignumber_js_1.default(1);
            result = yield boundFunc({ originPortfolio: portfolioId });
            expect(result).toEqual({
                portfolio: expect.objectContaining({
                    owner: expect.objectContaining({ did }),
                    id: portfolioId,
                }),
            });
            result = yield boundFunc({});
            expect(result).toEqual({
                portfolio: expect.objectContaining({ owner: expect.objectContaining({ did }) }),
            });
        }));
    });
});
//# sourceMappingURL=configureDividendDistribution.js.map