aboutsummaryrefslogtreecommitdiff
path: root/strichliste.lua
blob: 927a08a8e2130b039e45b5e3b74db491f2556f85 (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
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
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
#!/usr/bin/env luajit

local function escape(s)
    return s:gsub("<", "&lt;"):gsub("<", "&lt;")
end
local function urldecode(s)
    if s == nil then return nil end
    return s:gsub("+", " "):gsub("%%20", " ")
end
local function urlencode(s)
    if s == nil then return nil end
    return s:gsub(" ", "%%20")
end

local function parse_query(q)
    if q == nil then return {} end
    local data = {}
    for pair in string.gmatch(q, "([^&]+)") do
        local flag = string.match(pair, "^([^=]+)$")
        if flag ~= nil then
            data[flag] = "1"
        else
            local key, value = string.match(pair, "^([^=]+)=([^=]*)$")
            if key ~= nil and value ~= nil then
                data[key] = urldecode(value)
            end
        end
    end
    return data
end

local path = os.getenv("PATH_INFO")
local method = os.getenv("REQUEST_METHOD")
local query = parse_query(os.getenv("QUERY_STRING"))

local stylesheet = [[
    /* body { background-color: #161616; }
    h1, h2, h3, h4, h5, h6, p, label, a { color: #e2e2e2; } */
    .amount-presets form { display: inline-block; width: 60px }
    .amount-pos { color: green; }
    .amount-neg { color: red; }
    nav h2 { display: inline-block }
    .notif { padding: 0.5em; margin: 0.5em; background-color: #ddd; }
    .notif p { margin: 5px; }
    form.box { border: 2px solid grey; padding: 0.5em; margin: 0.5em; display: inline-block; }
    form h3 { margin: 5px; }
]]

local script = [[

]]

local function respond(status, title, body)
    print(string.format("Status: %d", status))
    print("Content-Type: text/html")
    print("")
    print(string.format([[
        <html><head>
            <title>%s</title>
            <meta charset="utf-8" />
            <style>%s</style>
            <script>%s</script>
        </head>
        <body>
            <nav>
                <h2><a href="/">Strichliste v2</a></h2>
                <span><a href="/?log">View Log</a></span>
                <span><a href="https://codeberg.org/metamuffin/strichliste">Source</a></span>
            </nav>
    ]], escape(title), stylesheet, script))
    body()
    print("</body></html>")
end

local function respond_error(message)
    respond(400, "Error", function()
        print(string.format("<p>Error: %s</p>", escape(message)))
    end)
end

local function redirect(path)
    print("Status: 307")
    print(string.format("Location: %s", path))
    print()
end

local function form_data()
    return parse_query(io.read())
end

local function read_log()
    local log = io.open("log", "r")
    if log == nil then
        return function() return nil end
    end
    local lines = log:lines("l")
    return function()
        local l = lines()
        if l == "" or l == nil then
            return nil
        end
        local time, username, amount, comment = string.match(l, "(%d+),([%w_ -]+),(-?%d+),([%w_ -]*)")
        return tonumber(time), username, tonumber(amount), comment
    end
end
local function read_products()
    local log = io.open("products", "r")
    if log == nil then
        return function() return nil end
    end
    local lines = log:lines("l")
    return function()
        local l = lines()
        if l == "" or l == nil then
            return nil
        end
        local barcode, amount, name = string.match(l, "([%w_-]+),(-?%d+),([%w_ -]*)")
        return barcode, tonumber(amount), name
    end
end

local function balances()
    local users = {}
    for _, username, amount, _ in read_log() do
        users[username] = (users[username] or 0) + amount
    end
    return users
end

local function r_user()
    if path == nil then
        return respond_error("no path")
    end
    local username = urldecode(path:sub(2))
    if username == nil or username:match("^([%w_ -]+)$") == nil then
        return respond_error("username invalid")
    end
    local notif = nil
    if method == "POST" then
        local data = form_data()
        local amount = nil
        local comment = ""
        if data.barcode then
            for p_barcode, p_amount, p_name in read_products() do
                if p_barcode == data.barcode then
                    amount = p_amount
                    comment = p_name
                end
            end
        else
            amount = tonumber(data.amount)
            comment = data.comment or ""
        end
        if amount == nil then
            return respond_error("amount invalid")
        end
        if comment:match("^[%w_ -]*$") == nil then
            return respond_error("comment invalid")
        end
        local log = io.open("log", "a+")
        if log == nil then
            return respond_error("failed to open log")
        end
        local time = os.time()
        log:write(string.format("%d,%s,%d,%s\n", time, username, amount, comment))
        log:flush()
        log:close()
        notif = string.format(
            "<div class=\"notif\"><p>Transaction successful: <strong class=\"amount-%s\">%.02f€</strong> (%s)</p></div>",
            amount >= 0 and "pos" or "neg", amount / 100, escape(comment)
        )
    end

    return respond(200, username, function()
        print(string.format("<h1>%s</h1>", username))
        local balance = balances()[username]
        local new_user = balance == nil
        balance = balance or 0
        if new_user then
            print([[
                <div class="notif"><p><i>This user account does not exist yet. It will only be created after the first transaction.</i></p></div>
            ]])
        end
        if notif then
            print(notif)
        end
        print(string.format("<p>Current balance: <span class=\"amount-%s\">%.02f€</p>", balance >= 0 and "pos" or "neg",
            balance / 100))
        print([[
            <form class="transaction box" action="" method="POST">
                <h3>Create Transaction</h3>
                <label for="amount">Amount: </label>
                <input type="number" name="amount" id="amount" /><br/>
                <label for="comment">Comment: </label>
                <input type="text" name="comment" id="comment" /><br/>
                <input type="submit" value="Update" />
            </form>
        ]])
        print("<div class=\"amount-presets\">")
        for _, type in ipairs({ 1, -1 }) do
            for _, amount in ipairs({ 50, 100, 150, 200, 500, 1000 }) do
                print(string.format([[
                    <form action="" method="POST">
                        <input type="number" name="amount" id="amount" value="%d" hidden />
                        <input type="text" name="comment" id="comment" value="" hidden />
                        <input type="submit" value="%s%.02f€" class="amount-%s" />
                    </form>
                    ]], amount * type, ({ [-1] = "-", [1] = "+" })[type], amount / 100,
                    ({ [-1] = "neg", [1] = "pos" })[type]))
            end
            print("<br/>")
        end
        print("</div>")
    end)
end

local function r_log()
    return respond(200, "Log", function()
        print("<table>")
        print("<tr><th>Time</th><th>Username</th><th>Amount</th><th>Comment</th></tr>")
        for time, username, amount, comment in read_log() do
            print(string.format("<tr><td>%d</td><td>%s</td><td class=\"amount-%s\">%.02f€</td><td>%s</td></tr>", time,
                escape(username),
                amount >= 0 and "pos" or "neg", amount / 100, escape(comment)))
        end
        print("</table>")
    end)
end

local function r_index()
    return respond(200, "Users", function()
        print([[
            <form action="/" method="GET" class="box">
                <h3>User Creation</h3>
                <label for="username">Username: </label>
                <input type="text" name="create_user" id="username" /><br/>
                <input type="submit" value="Continue" />
            </form>
        ]])
        print("<ul>")
        for username, balance in pairs(balances()) do
            print(string.format("<li><a href=\"/%s\">%s</a>: %.02f€</li>", escape(username), escape(username),
                balance / 100))
        end
        print("</ul>")
    end)
end

local function r_create_user()
    local username = query.create_user
    if username:match("^([%w_ -]+)$") == nil then
        return respond_error("invalid username " .. username)
    end
    return redirect(string.format("/%s", urlencode(username)))
end

if path == "/" then
    if query.log then
        return r_log()
    elseif query.create_user then
        return r_create_user()
    else
        return r_index()
    end
else
    return r_user()
end