File size: 2,760 Bytes
50ca514
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
import mongoose from 'mongoose';

const portfolioSchema = new mongoose.Schema({
    userId: {
        type: mongoose.Schema.Types.ObjectId,
        ref: 'Users', // Updated to match your existing User model name
        required: true
    },
    balance: {
        type: Number,
        default: 10000,
        min: 0
    },
    stocks: [{
        code: {
            type: String,
            required: true,
            uppercase: true // Automatically convert stock codes to uppercase
        },
        quantity: {
            type: Number,
            required: true,
            min: 0
        },
        avgPrice: {
            type: Number,
            required: true,
            min: 0
        }
    }],
    transactions: [{
        type: {
            type: String,
            enum: ['BUY', 'SELL'],
            required: true
        },
        code: {
            type: String,
            required: true,
            uppercase: true
        },
        quantity: {
            type: Number,
            required: true,
            min: 1
        },
        price: {
            type: Number,
            required: true,
            min: 0
        },
        timestamp: {
            type: Date,
            default: Date.now
        }
    }],
    createdAt: {
        type: Date,
        default: Date.now
    },
    lastUpdated: {
        type: Date,
        default: Date.now
    }
});

// Pre-save middleware to update lastUpdated timestamp
portfolioSchema.pre('save', function(next) {
    this.lastUpdated = new Date();
    next();
});

// Add methods to calculate portfolio value, returns, etc.
portfolioSchema.methods.calculatePortfolioValue = async function(currentPrices) {
    const stocksValue = this.stocks.reduce((total, stock) => {
        const currentPrice = currentPrices[stock.code] || stock.avgPrice;
        return total + (stock.quantity * currentPrice);
    }, 0);
    return stocksValue + this.balance;
};

portfolioSchema.methods.calculateReturns = async function(currentPrices) {
    const currentValue = await this.calculatePortfolioValue(currentPrices);
    const investedValue = this.stocks.reduce((total, stock) => {
        return total + (stock.quantity * stock.avgPrice);
    }, 0);
    return {
        absoluteReturn: currentValue - investedValue,
        percentageReturn: ((currentValue - investedValue) / investedValue) * 100
    };
};

// Static method to find user's portfolio with validation
portfolioSchema.statics.findUserPortfolio = async function(userId) {
    const portfolio = await this.findOne({ userId });
    if (!portfolio) {
        throw new Error('Portfolio not found');
    }
    return portfolio;
};

const Portfolio = mongoose.model('Portfolio', portfolioSchema);

export default Portfolio;