File size: 4,072 Bytes
1a81036
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
import mongoose from 'mongoose';
import { v4 as uuidv4 } from 'uuid';

const orderItemSchema = new mongoose.Schema({
  product: { type: mongoose.Schema.Types.ObjectId, ref: 'Product', required: true },
  name: { type: String, required: true }, // Snapshot
  price: { type: Number, required: true }, // Snapshot
  quantity: { type: Number, required: true, min: 1 },
  unit: { type: String },
  imageUrl: { type: String },
  isPreorder: { type: Boolean, default: false },
  expectedRestockDate: { type: Date },
}, { _id: false });

const orderSchema = new mongoose.Schema({
  orderNumber: { 
    type: String, 
    unique: true,
    default: () => `WL-${Date.now().toString(36).toUpperCase()}-${uuidv4().slice(0,4).toUpperCase()}`,
  },
  
  // Customer info
  customer: { type: mongoose.Schema.Types.ObjectId, ref: 'User' },
  guestName: { type: String },
  guestEmail: { type: String },
  guestPhone: { type: String },
  
  // Items
  items: [orderItemSchema],
  
  // Pricing
  subtotal: { type: Number, required: true },
  discount: { type: Number, default: 0 },
  total: { type: Number, required: true },
  currency: { type: String, default: 'TZS' },
  
  // Pickup info
  pickupTime: { type: Date },
  pickupNote: { type: String },
  pickupCode: { type: String }, // 6-digit code for pickup verification
  
  // Status workflow: pending → confirmed → ready → completed | cancelled
  status: { 
    type: String, 
    enum: ['pending', 'confirmed', 'preparing', 'ready', 'completed', 'cancelled'],
    default: 'pending',
  },
  
  statusHistory: [{
    status: { type: String },
    note: { type: String },
    updatedBy: { type: mongoose.Schema.Types.ObjectId, ref: 'User' },
    timestamp: { type: Date, default: Date.now },
  }],
  
  // Flags
  hasPreorderItems: { type: Boolean, default: false },
  isFullyPreorder: { type: Boolean, default: false },
  
  // Payment
  payment: {
    method: { type: String, enum: ['mpesa', 'card', 'cash', 'tigopesa', 'airtel_money'], default: 'cash' },
    status: { type: String, enum: ['pending', 'processing', 'paid', 'failed', 'refunded'], default: 'pending' },
    transactionId: { type: String },
    paidAt: { type: Date },
    amount: { type: Number },
    // M-Pesa / mobile money specifics
    phoneNumber: { type: String },
    reference: { type: String },
    // Card specifics
    last4: { type: String },
    cardBrand: { type: String },
    // Simulation flag
    isSimulated: { type: Boolean, default: false },
  },
  
  // Staff processing
  assignedTo: { type: mongoose.Schema.Types.ObjectId, ref: 'User' },
  staffNotes: { type: String },
  
  // Loyalty
  loyaltyPointsEarned: { type: Number, default: 0 },
  loyaltyPointsUsed: { type: Number, default: 0 },
  
}, { timestamps: true });

// Generate pickup code
orderSchema.pre('save', function (next) {
  if (!this.pickupCode) {
    this.pickupCode = Math.floor(100000 + Math.random() * 900000).toString();
  }
  next();
});

// Calculate loyalty points (1 point per 1000 TZS)
orderSchema.pre('save', function (next) {
  this.loyaltyPointsEarned = Math.floor(this.total / 1000);
  next();
});

// Normalize field names for frontend compatibility
orderSchema.set('toJSON', {
  virtuals: true,
  transform(doc, ret) {
    // Alias total → totalAmount
    ret.totalAmount   = ret.total;
    // Alias guest fields → customer fields (for consistent frontend)
    ret.customerName  = ret.customer?.name  || ret.guestName  || '';
    ret.customerPhone = ret.customer?.phone || ret.guestPhone || '';
    ret.customerEmail = ret.customer?.email || ret.guestEmail || '';
    // Normalize items
    if (Array.isArray(ret.items)) {
      ret.items = ret.items.map(item => ({
        ...item,
        qty:   item.quantity,
        image: item.imageUrl,
      }));
    }
    return ret;
  },
});

// unique:true on schema field already creates index for orderNumber
orderSchema.index({ customer: 1, status: 1 });
orderSchema.index({ status: 1, createdAt: -1 });
orderSchema.index({ 'payment.status': 1 });

export default mongoose.model('Order', orderSchema);