summaryrefslogtreecommitdiff
path: root/src/tax_table.h
blob: 31683ac4ef6208901f7d6d8e55f8ec21475d0a68 (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
#ifndef BOKF_TAX_TABLE_H
#define BOKF_TAX_TABLE_H

#include <sqlite3.h>
#include <stddef.h>
#include <stdint.h>

#include "util.h"

/* One record from Skatteverket's fixed-width allmanna-tabeller-manad.txt.
   Income and tax are öre; % records carry percent x100 in pct with
   tax_ore 0, B records carry the whole-krona tax x100 in tax_ore. */
struct tax_row {
    int table_no;
    int column_no;
    int64_t income_from_ore;
    int64_t income_to_ore; /* < 0 = open-ended top range */
    int64_t tax_ore;
    int64_t pct;
    int is_pct;
};

/* Parses the fixed-width file (UTF-8 BOM tolerated); skips blank lines.
   Returns 0 with a malloc'd rows array, -1 with a message otherwise. */
int tax_table_parse(const unsigned char *data, size_t len,
                    struct tax_row **out, size_t *out_n, char **err);

/* Replaces year's rows and meta. The caller owns the transaction: on failure
   the caller rolls the whole thing back. */
int tax_table_store(sqlite3 *db, int year, const struct tax_row *rows,
                    size_t n, const char *source_url,
                    const unsigned char sha256[32], const char *fetched_at,
                    char **err);

/* Looks up the B range containing gross_ore. 0 = found; 1 = gross is above
   the tabulated B range; 2 = no B range contains it (or none stored);
   -1 = database error. % rows exist in the table but wave 1 refuses to
   guess how Skatteverket applies them. */
int tax_table_lookup(sqlite3 *db, int year, int table_no, int column_no,
                     int64_t gross_ore, int64_t *tax_ore);

/* HTTPS GET with the system trust store, following up to five redirects.
   Returns 0 and the body, -1 with a message. */
int tax_table_https_get(const char *url, struct buf *out, char **err);

/* Downloads the official monthly table for year: finds the year's link on
   Skatteverket's page in document order (current year first), downloads it
   and returns the bytes and the absolute source URL. */
int tax_table_fetch_year(int year, unsigned char **data, size_t *len,
                         char **source_url, char **err);

#endif