File size: 2,174 Bytes
498f280
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
63383e6
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
498f280
 
63383e6
 
 
498f280
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
'use strict';

const marketplaceService = require('../services/marketplace.service');

const asyncHandler = (fn) => (req, res, next) => {
  Promise.resolve(fn(req, res, next)).catch(next);
};

const checkout = asyncHandler(async (req, res) => {
  const userId = req.user.id || req.user.sub;
  const { productId, quantity, shippingAddress } = req.body;

  if (!productId || !quantity || !shippingAddress) {
    return res.status(400).json({ error: { message: 'Missing required order fields' } });
  }

  try {
    const order = await marketplaceService.placeOrder(userId, productId, quantity, shippingAddress);
    res.status(201).json({ data: order });
  } catch (err) {
    res.status(400).json({ error: { message: err.message } });
  }
});

const getHistory = asyncHandler(async (req, res) => {
  const userId = req.user.id || req.user.sub;
  const orders = await marketplaceService.listUserOrders(userId);
  res.json({ data: orders });
});

const getProviderOrders = asyncHandler(async (req, res) => {
  const userId = req.user.id || req.user.sub;
  
  // Get provider profile first
  const pool = require('../db').getPool();
  const profileRes = await pool.query('SELECT id FROM provider_profiles WHERE user_id = $1', [userId]);
  
  if (profileRes.rows.length === 0) {
    return res.status(404).json({ error: { message: 'Provider profile not found' } });
  }

  const orders = await marketplaceService.listProviderOrders(profileRes.rows[0].id);
  res.json({ data: orders });
});

const updateStatus = asyncHandler(async (req, res) => {
  const userId = req.user.id || req.user.sub;
  const { status } = req.body;
  const { id } = req.params;

  // Get provider profile first
  const pool = require('../db').getPool();
  const profileRes = await pool.query('SELECT id FROM provider_profiles WHERE user_id = $1', [userId]);
  
  if (profileRes.rows.length === 0) {
    return res.status(404).json({ error: { message: 'Provider profile not found' } });
  }

  const order = await marketplaceService.updateOrderStatus(id, status, profileRes.rows[0].id);
  res.json({ data: order });
});

module.exports = {
  checkout,
  getHistory,
  getProviderOrders,
  updateStatus
};