summaryrefslogtreecommitdiff
path: root/src/pages/api/shop/finish-checkout.js
blob: 9eaa36db8ab305290c74dc4736cbfd9ae84800b8 (plain)
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
import odooApi from '@/core/api/odooApi'
import mailer from '@/core/utils/mailer'
import FinishCheckoutEmail from '@/lib/checkout/email/FinishCheckoutEmail'
import { render } from '@react-email/render'
import axios from 'axios'
import camelcaseObjectDeep from 'camelcase-object-deep'

export default async function handler(req, res) {
  const { orderName = null } = req.query

  if (!orderName) {
    return res.status(422).json({ error: 'parameter missing' })
  }

  let { auth } = req.cookies

  if (!auth) {
    return res.status(401).json({ error: 'Unauthorized' })
  }
  auth = JSON.parse(auth)

  const midtransAuthKey = btoa(process.env.MIDTRANS_SERVER_KEY + ':')
  const midtransHeaders = {
    Accept: 'application/json',
    'Content-Type': 'application/json',
    Authorization: `Basic ${midtransAuthKey}`
  }
  let midtransStatus = {}
  try {
    midtransStatus = await axios.get(`${process.env.MIDTRANS_HOST}/v2/${orderName}/status`, {
      headers: midtransHeaders
    })
    midtransStatus = camelcaseObjectDeep(midtransStatus.data)
  } catch (error) {
    console.log(error)
  }

  let statusPayment = 'manual'
  if (midtransStatus?.orderId) {
    const transactionStatus = midtransStatus.transactionStatus
    statusPayment = 'failed'
    if (['capture', 'settlement'].includes(transactionStatus)) {
      statusPayment = 'success'
    } else if (transactionStatus == 'pending') {
      statusPayment = 'pending'
    }
  }

  const query = `name=${orderName.replaceAll('-', '/')}&limit=1&context=quotation`
  const searchTransaction = await odooApi(
    'GET',
    `/api/v1/partner/${auth.partnerId}/sale_order?${query}`,
    {},
    { Token: auth.token }
  )
  if (searchTransaction.saleOrderTotal == 0) {
    return res.status(400).json({ error: 'Transaction Not Found' })
  }

  let transaction = await odooApi(
    'GET',
    `/api/v1/partner/${auth.partnerId}/sale_order/${searchTransaction.saleOrders[0].id}`,
    {},
    { Token: auth.token }
  )
  if (!transaction?.id) {
    return res.status(400).json({ error: 'Transaction Detail Not Found' })
  }

  transaction.subtotal = 0
  transaction.discountTotal = 0
  for (const product of transaction.products) {
    transaction.subtotal += product.price.price * product.quantity
    transaction.discountTotal -=
      (product.price.price - product.price.priceDiscount) * product.quantity
  }

  const emailMessage = render(
    <FinishCheckoutEmail
      transaction={transaction}
      payment={midtransStatus}
      statusPayment={statusPayment}
    />
  )

  mailer.sendMail({
    from: 'sales@indoteknik.com',
    to: transaction.address.customer.email,
    subject: 'Pembelian di Indoteknik.com',
    html: emailMessage
  })

  return res.status(200).json({ description: 'success' })
}