aboutsummaryrefslogtreecommitdiff
path: root/abrechenbarkeit.lua
blob: e6075412cbe75fc91d099c6e71401ae9e46c8fa8 (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
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
#!/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 function load_config()
    local log = io.open("config", "r")
    if log == nil then return {} end
    local config = {}
    for l in log:lines("l") do
        if l ~= "" and l[0] ~= "#" then
            local key, value = string.match(l, "^([^=]+)=([^=]*)")
            if key ~= nil and value ~= nil then
                config[key] = value
            end
        end
    end
    return config
end

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

local stylesheet = io.open("style.css"):read("a")
local script = io.open("script.js"):read("a")

local function get_user_theme(username)
    local c = ""
    local js = ""
    if username == "_jeb" then
        c = "html { animation: 2s jeb infinite; }"
        c = c .. "@keyframes jeb {\n"
        for i = 0, 100 do
            c = c .. string.format("%.02f%% { --hue: %.02f; } \n", i, i / 100 * 360)
        end
        c = c .. "\n}"
    elseif username == "Dinnerbone" then
        c = "html { transform: scale(-1); } "
    end
    return c, js
end

local function respond(status, title, body)
    local themecss, themejs = get_user_theme(path and path:sub(2))

    print(string.format("Status: %d", status))
    print("Content-Type: text/html")
    print("")
    print(string.format([[
        <!DOCTYPE html>
        <html><head>
            <title>%s</title>
            <meta charset="utf-8" />
            <style>%s</style>
            <style>%s</style>
            <script>%s</script>
            %s
        </head>
        <body>
            <nav>
                <a class="logo" href="/">
					<svg xmlns="http://www.w3.org/2000/svg" width="16" height="16" fill="currentColor" class="bi bi-receipt-cutoff" viewBox="0 0 16 16">
					  <path d="M3 4.5a.5.5 0 0 1 .5-.5h6a.5.5 0 1 1 0 1h-6a.5.5 0 0 1-.5-.5m0 2a.5.5 0 0 1 .5-.5h6a.5.5 0 1 1 0 1h-6a.5.5 0 0 1-.5-.5m0 2a.5.5 0 0 1 .5-.5h6a.5.5 0 1 1 0 1h-6a.5.5 0 0 1-.5-.5m0 2a.5.5 0 0 1 .5-.5h6a.5.5 0 0 1 0 1h-6a.5.5 0 0 1-.5-.5m0 2a.5.5 0 0 1 .5-.5h6a.5.5 0 0 1 0 1h-6a.5.5 0 0 1-.5-.5M11.5 4a.5.5 0 0 0 0 1h1a.5.5 0 0 0 0-1zm0 2a.5.5 0 0 0 0 1h1a.5.5 0 0 0 0-1zm0 2a.5.5 0 0 0 0 1h1a.5.5 0 0 0 0-1zm0 2a.5.5 0 0 0 0 1h1a.5.5 0 0 0 0-1zm0 2a.5.5 0 0 0 0 1h1a.5.5 0 0 0 0-1z"/>
					  <path d="M2.354.646a.5.5 0 0 0-.801.13l-.5 1A.5.5 0 0 0 1 2v13H.5a.5.5 0 0 0 0 1h15a.5.5 0 0 0 0-1H15V2a.5.5 0 0 0-.053-.224l-.5-1a.5.5 0 0 0-.8-.13L13 1.293l-.646-.647a.5.5 0 0 0-.708 0L11 1.293l-.646-.647a.5.5 0 0 0-.708 0L9 1.293 8.354.646a.5.5 0 0 0-.708 0L7 1.293 6.354.646a.5.5 0 0 0-.708 0L5 1.293 4.354.646a.5.5 0 0 0-.708 0L3 1.293zm-.217 1.198.51.51a.5.5 0 0 0 .707 0L4 1.707l.646.647a.5.5 0 0 0 .708 0L6 1.707l.646.647a.5.5 0 0 0 .708 0L8 1.707l.646.647a.5.5 0 0 0 .708 0L10 1.707l.646.647a.5.5 0 0 0 .708 0L12 1.707l.646.647a.5.5 0 0 0 .708 0l.509-.51.137.274V15H2V2.118z"/>
					</svg>
                    Abrechenbarkeit</a>
                <a href="/?log">Log</a>
                <a href="/?products">Products</a>
                <a href="https://codeberg.org/metamuffin/strichliste">Source</a>
            </nav>
    ]],
        escape(title),
        stylesheet, -- style.css
        themecss,   -- theme for user
        script,     -- script.js
        config.head_extra or ""
    ))
    body()
    print(string.format(
        "<script>%s</script></body></html>",
        themejs
    ))
end

local function error_box(message)
    return string.format([[<div class="notif error"><p>Error: %s</p></div>]], message)
end

local function respond_error(message)
    respond(400, "Error", function()
        print(error_box(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 format_duration(t)
    if t > 86400 then return string.format("%d day%s", t / 86400, math.floor(t / 86400) ~= 1 and "s" or "") end
    if t > 3600 then return string.format("%d hour%s", t / 3600, math.floor(t / 3600) ~= 1 and "s" or "") end
    if t > 60 then return string.format("%d minute%s", t / 60, math.floor(t / 60) ~= 1 and "s" or "") end
    return string.format("%d seconds", t)
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, pcode, pcount, comment = string.match(l,
            "(%d+),([%w_ -]+),(-?%d+),([%w_-]*),(-?%d*),([%w_ -]*)")
        return tonumber(time), username, tonumber(amount), pcode, tonumber(pcount), 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, price, name, owner = string.match(l, "([%w_-]+),(-?%d+),([%w_ -]*),([%w_ -]*)")
        return barcode, tonumber(price), name, owner
    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 product_balances()
    local products = {}
    for _, _, _, pcode, pcount, _ in read_log() do
        if pcode ~= nil and pcount ~= nil then
            products[pcode] = (products[pcode] or 0) + pcount
        end
    end
    return products
end

local function last_txns()
    local users = {}
    for time, username, _, _, _, _ in read_log() do
        users[username] = time
    end
    return users
end

local function get_active_users()
    local user_balances = {}
    for time, username, amount, _, _, _ in read_log() do
        user_balances[username] = {
            time = time,
            username = username,
            balance = (user_balances[username] or { balance = 0 }).balance + amount
        }
    end

    local users = {}
    for _, user in pairs(user_balances) do
        table.insert(users, user)
    end

    table.sort(users, function(a, b) return a.time > b.time end)
    return users
end

local function r_user_post(username)
    local data = form_data()
    local amount = tonumber(data.amount)
    local comment = data.comment
    local pcode = nil
    local pcount = nil
    local powner = nil
    local powner_comment = nil
    if data.pcode then
        for p_barcode, p_amount, p_name, p_owner in read_products() do
            if p_barcode == data.pcode then
                powner = p_owner
                pcount = (tonumber(data.pcount) or 1) * (data.negate_pcount ~= nil and -1 or 1)
                pcode = p_barcode
                if amount == nil then amount = pcount * p_amount end
                if comment == nil then
                    comment = string.format("%s %d %s", pcount < 0 and "Buy" or "Restock",
                        math.abs(pcount), p_name)

                    powner_comment = string.format("%s %d %s %s %s",
                        pcount < 0 and "Sell" or "Restock",
                        math.abs(pcount), p_name,
                        pcount < 0 and "to" or "by",
                        username)
                end
            end
        end
        if amount == nil then
            return error_box("unknown product")
        end
    end
    if amount == nil then
        return error_box("amount invalid")
    end
    if comment == nil or comment:match("^[%w_ -]*$") == nil then
        return error_box("comment invalid")
    end
    local log = io.open("log", "a+")
    if log == nil then
        return error_box("failed to open log")
    end
    local time = os.time()
    -- subtract from buyer
    log:write(string.format("%d,%s,%d,%s,%s,%s\n", time, username, amount, pcode or "", pcount or "", comment))
    -- add to owner
    if powner then
        -- count is always zero as doesn't affect stock
        log:write(string.format("%d,%s,%d,%s,%s,%s\n", time, powner, -amount, pcode or "", "", powner_comment))
    end
    log:flush()
    log:close()
    return string.format([[
        <div class="notif"><p>Transaction successful: <strong class="amount-%s">%.02f</strong> (%s)</p></div>
        <audio src="%s" autoplay></audio>
    ]],
        amount >= 0 and "pos" or "neg", amount / 100,
        escape(comment),
        config.transaction_sound or ""
    )
end

local function r_user(username)
    local notif = nil
    if method == "POST" then
        notif = r_user_post(username)
    end
    return respond(200, string.format("Abrechenbarheit: %s", username), function()
        print(string.format("<h1>%s</h1>", username))
        local balance = balances()[username]
        local last_txn = last_txns()[username]
        local new_user = balance == nil
        balance = balance or 0
        if notif then print(notif) end
        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>
            ]])
        else
            print([[<div class="backgroundbox userinfo">]])
            print(string.format([[
                Current balance:<br><span class="amount-%s balance-value">%.02f</span><br>
            ]], balance >= 0 and "pos" or "neg", balance / 100))
            print(string.format([[
                Last transaction added %s ago. <a href="/%s?log">View user log</a>
            ]], format_duration(os.time() - last_txn), username))
            print([[</div>]])
        end
        print([[<div class="transactions container firstchildlarge">]])
        print([[<div class="amount-presets backgroundbox">]])
        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 button" />
                    </form>
                    ]], amount * type, ({ [-1] = "-", [1] = "+" })[type], amount / 100,
                    ({ [-1] = "neg", [1] = "pos" })[type]))
            end
        end
        print("</div>")
        print([[
            <form class="transaction box backgroundbox" action="" method="POST">
                <h3>Create Transaction</h3>
                <label for="amount">Amount (ct): </label>
                <input type="number" name="amount" id="amount" />
                <label for="comment">Comment: </label>
                <input type="text" name="comment" id="comment" />
                <input type="submit" value="Update" class="amount-ntr button" />
            </form>
            <form class="transaction box backgroundbox" action="" method="POST" id="buy_product">
                <h3>Buy Product</h3>
                <input type="text" name="negate_pcount" value="1" hidden />
                <label for="pcount">Count: </label>
                <input type="number" name="pcount" id="pcount" value="1" />
                <label for="pcode">Product Barcode: </label>
                <input type="text" name="pcode" id="pcode" />
                <input class="amount-neg button" type="submit" value="Buy" />
            </form>
            <form class="transaction box backgroundbox" action="" method="POST" id="buy_product">
                <h3>Restock Product</h3>
                <label for="pcount">Count: </label>
                <input type="number" name="pcount" id="pcount" value="1" />
                <label for="amount">Upstream price: </label>
                <input type="number" name="amount" id="amount" />
                <label for="pcode">Product Barcode: </label>
                <input type="text" name="pcode" id="pcode" />
                <input type="submit" value="Restock" class="button amount-pos" />
            </form>
        ]])
        print("</div>")
    end)
end

local function r_log(filter)
    return respond(200, "Abrechnungen", function()
        print([[<table class="log"]])
        print([[<thead><tr>
            <th>Time</th>
            <th>Username</th>
            <th>Amount</th>
            <th>P.-Barcode</th>
            <th>P.-Count</th>
            <th>Comment</th>
            <th>Actions</th>
        </tr></thead>]])
        print("<tbody>")
        for time, username, amount, pcode, pcount, comment in read_log() do
            if filter == nil or filter == username then
                print(string.format([[
                    <tr>
                        <td>%s (%s ago)</td>
                        <td>%s</td>
                        <td class="amount-%s">%.02f</td>
                        <td>%s</td>
                        <td>%s %s</td>
                        <td>%s</td>
                        <td>
                            <form action="/%s" method="POST">
                                <input type="number" name="amount" id="amount" value="%d" hidden />
                                <input type="text" name="comment" id="comment" value="Revert %s" hidden />
                                <input type="submit" class="amount-ntr button" value="Revert" />
                            </form>
                        </td>
                    </tr>
                ]],
                    os.date("!%Y-%m-%dT%H:%M:%SZ", time), format_duration(os.time() - time),
                    escape(username),
                    amount >= 0 and "pos" or "neg", amount / 100,
                    escape(pcode) or "",
                    pcount and (pcount < 0 and "buy" or "stock") or "", pcount and tostring(math.abs(pcount)) or "",
                    escape(comment),
                    escape(username),
                    -amount,
                    escape(comment)
                ))
            end
        end
        print("</tbody>")
        print("</table>")
    end)
end

local function r_index()
    return respond(200, "Abrechenbarkeit", function()
        print([[
            <form action="/" method="GET" id="user_creation">
                <h3>User Creation</h3>
                <label for="username">Username: </label>
                <input type="text" name="create_user" id="username" />
                <input type="submit" value="Continue" class="button amount-ntr" />
            </form>
        ]])
        print([[<div class="userlist"></div>]]) -- for printing
        print([[<ul class="userlist">]])
        for _, user in ipairs(get_active_users()) do
            print(string.format([[
                <li><a href="/%s"><span class="name">%s</span> <span class="amount amount-%s">%.02f</span></a></li>
            ]],
                urlencode(user.username),
                escape(user.username),
                user.balance >= 0 and "pos" or "neg", user.balance / 100
            ))
        end
        print("</ul>")
    end)
end

local function validate_username(username)
    -- disallow leading or traling whitespace
    return username ~= nil
        and username:match("^([%w_ -]+)$") ~= nil
        and username:match("^%s") == nil
        and username:match("%s$") == nil
end

local function r_create_user()
    local username = query.create_user
    if not validate_username(username) then
        return respond_error("invalid username " .. username)
    end
    return redirect(string.format("/%s", urlencode(username)))
end

local function r_products_post()
    local data = form_data()
    local barcode = data.barcode
    if barcode == nil then
        return error_box("barcode unset")
    end
    if barcode:match("^[%w_-]*$") == nil then
        return error_box("barcode invalid")
    end
    if data.delete then
        local new_products = io.open("products.new", "w+")
        if new_products == nil then
            return error_box("failed to open new products")
        end
        for a_barcode, price, name, owner in read_products() do
            if barcode ~= a_barcode then
                new_products:write(string.format("%s,%d,%s,%s\n", a_barcode, price, name, owner))
            end
        end
        new_products:flush()
        new_products:close()
        os.rename("products.new", "products")
    else
        local price = tonumber(data.price)
        local name = data.name
        if price == nil then
            return error_box("price invalid")
        end
        if name:match("^[%w_ -]*$") == nil then
            return error_box("name invalid")
        end
        local products = io.open("products", "a+")
        if products == nil then
            return error_box("failed to open products")
        end
        local owner = data.owner or ""
        if name:match("^[%w_ -]*$") == nil then
            return error_box("owner invalid")
        end
        products:write(string.format("%s,%d,%s,%s\n", barcode, price, name, owner))
        products:flush()
        products:close()
    end
end

local function r_products()
    local notif = nil
    if method == "POST" then
        notif = r_products_post()
    end
    respond(200, "Abrechenbare Product List", function()
        print("<h1>Product List</h1>")
        if notif then print(notif) end
        print([[
        	<div class="container">
            <form action="/?products" method="POST" class="box backgroundbox">
                <h3>Add Product</h3>
                <label for="name">Name: </label>
                <input type="text" name="name" id="name" />
                <label for="price">Price (ct): </label>
                <input type="number" name="price" id="price" />
                <label for="owner">Owner: </label>
                <input type="text" name="owner" id="owner" />
                <label for="barcode">Barcode: </label>
                <input type="text" name="barcode" id="barcode" />
                <input type="submit" value="Add" class="amount-ntr button" />
            </form>
            <form action="/?products" method="POST" class="box backgroundbox">
                <h3>Remove Product</h3>
                <input type="text" name="delete" value="1" hidden />
                <label for="barcode">Barcode: </label>
                <input type="text" name="barcode" id="barcode" />
                <input type="submit" value="Remove"class="amount-ntr button" />
            </form>
            </div>
        ]])
        print([[<table class="productlist"><tr>
            <th>Name</th>
            <th>Price</th>
            <th>Barcode</th>
            <th>Count</th>
            <th>Owner</th>
        </tr>]])
        local pbals = product_balances()
        for barcode, price, name, owner in read_products() do
            print(string.format([[
                <tr><td>%s</td><td class="amount-%s">%.02f</td><td>%s</td><td>%s</td><td>%s</td></tr>
            ]],
                name,
                -price >= 0 and "pos" or "neg", -price / 100,
                barcode,
                pbals[barcode] or "0",
                owner
            ))
        end
        print("</table>")
    end)
end

local function extract_username()
    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 nil
    end
    return username
end

if path == "/" then
    if query.products then
        return r_products()
    elseif query.log then
        return r_log()
    elseif query.create_user then
        return r_create_user()
    else
        return r_index()
    end
else
    local username = extract_username()
    if username == nil or not validate_username(username) then
        return respond_error("username invalid")
    elseif query.log then
        return r_log(username)
    else
        return r_user(username)
    end
end