File size: 1,687 Bytes
ff4d747
 
 
 
 
 
 
 
 
 
 
 
 
9b8d6f0
 
 
ff4d747
 
 
 
 
 
 
9b8d6f0
 
 
 
ff4d747
 
 
 
9b8d6f0
 
ff4d747
9b8d6f0
ff4d747
 
 
 
 
 
9b8d6f0
 
ff4d747
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
const { generateCode } = require('./generateCode');

async function createAccessTokenForPayment({
  connection,
  paymentId,
  clientId,
  deviceId,
  planId,
  durationSeconds,
  downLimit,
  downUnit,
  upLimit,
  upUnit,
  code: preferredCode = null,
  omadaVoucherId = null,
  omadaVoucherGroupId = null,
}) {
  if (!connection) {
    throw new Error('Database connection is required');
  }

  let lastError = null;

  const attempts = preferredCode ? 1 : 5;

  for (let attempt = 0; attempt < attempts; attempt += 1) {
    const code = String(preferredCode || generateCode()).toUpperCase();

    try {
      const [insertResult] = await connection.execute(
        `INSERT INTO access_tokens
           (client_id, device_id, plan_id, payment_id, code,
            omada_voucher_id, omada_voucher_group_id, duration_seconds,
            down_limit, down_unit, up_limit, up_unit, status)
         VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, 'unused')`,
        [
          clientId,
          deviceId,
          planId,
          paymentId,
          code,
          omadaVoucherId,
          omadaVoucherGroupId,
          durationSeconds,
          downLimit,
          downUnit,
          upLimit,
          upUnit,
        ]
      );

      await connection.execute(
        `UPDATE payments SET access_token_code = ? WHERE id = ?`,
        [code, paymentId]
      );

      return {
        tokenId: insertResult.insertId,
        code,
      };
    } catch (err) {
      lastError = err;
      if (err.code !== 'ER_DUP_ENTRY') throw err;
    }
  }

  throw lastError || new Error('Failed to generate a unique token code');
}

module.exports = { createAccessTokenForPayment };