const vnReport = require('../../../core/mixins/vn-report.js');

module.exports = {
    name: 'supplier-campaign-metrics',
    mixins: [vnReport],
    async serverPrefetch() {
        this.supplier = await this.findOneFromDef('supplier', [this.id]);
        this.checkMainEntity(this.supplier);
        let entries = await this.rawSqlFromDef('entries', [this.id, this.from, this.to]);
        this.total = {quantity: 0, price: 0};
        const entriesId = [];

        for (let entry of entries)
            entriesId.push(entry.id);

        const buys = await this.rawSqlFromDef('buys', [entriesId]);

        const entriesMap = new Map();
        for (let entry of entries)
            entriesMap.set(entry.id, entry);

        for (let buy of buys) {
            const entry = entriesMap.get(buy.entryFk);
            if (entry) {
                if (!entry.buys) entry.buys = [];
                this.total.quantity = this.total.quantity + buy.quantity;
                this.total.price = this.total.price + (buy.price * buy.quantity);
                entry.buys.push(buy);
            }
        }

        this.entries = entries;
    },
    props: {
        id: {
            type: Number,
            required: true,
            description: 'The supplier id'
        },
        from: {
            required: true
        },
        to: {
            required: true
        }
    }
};