aboutsummaryrefslogtreecommitdiffstats
path: root/routes/invoices.ts
blob: 0cb7368734d8a92ad50fe7a64b7614ce3d5707ca (plain) (blame)
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
import config from "$config";
import { db, g, gf, s } from "$lib/db";
import { generate } from "$lib/invoices";
import { err } from "$lib/logging";
import { bail, fail, fields, getInvoice, getUser } from "$lib/utils";
import rpc from "@coinos/rpc";

export default {
  async get(req, res) {
    try {
      const {
        params: { id },
      } = req;
      if (id === "undefined") fail("invalid id");
      const invoice = await getInvoice(id);

      if (invoice) {
        invoice.secret = undefined;
        invoice.user = await getUser(invoice.uid, fields);

        invoice.items ||= [];
      }
      if (invoice) res.send(invoice);
      else fail("invoice not found");
    } catch (e) {
      bail(res, e.message);
    }
  },

  async create(req, res) {
    let { body, user } = req;
    const { invoice } = body;

    if (body.user) user = body.user;
    if (req.user.username === user.username) invoice.own = true;
    else invoice.own = false;

    try {
      const result = await generate({ invoice, user });
      res.send(result);
    } catch (e) {
      bail(res, e.message);
    }
  },

  async update(req, res) {
    try {
      const { id } = req.params;
      const { body } = req;
      const { tip, webhook, secret } = body.invoice;

      if (tip < 0) fail("Invalid tip");

      let invoice = await gf(`invoice:${id}`);
      const user = await g(`user:${invoice.uid}`);

      if (typeof tip !== "undefined") invoice.tip = tip;

      if (webhook && secret) {
        if (invoice.uid !== req.user?.id) fail("Unauthorized");
        invoice.webhook = webhook;
        invoice.secret = secret;
      }

      invoice = await generate({ invoice, user });
      await s(`invoice:${id}`, invoice);

      res.send(invoice);
    } catch (e) {
      bail(res, e.message);
    }
  },

  async list(req, res) {
    const { id } = req.user;
    let invoices = await db.lRange(`${id}:invoices`, 0, -1);
    invoices = (await Promise.all(invoices.map((i) => getInvoice(i)))).filter(
      Boolean,
    );
    res.send(invoices);
  },

  async sign(req, res) {
    try {
      const { address, message, type = "bitcoin" } = req.body;
      const node = rpc(config[type]);

      if (config[type].walletpass)
        await node.walletPassphrase(config[type].walletpass, 300);

      const signature = await node.signMessage({ address, message });
      res.send({ signature });
    } catch (e) {
      bail(res, e.message);
    }
  },
};