payredu

[WIP] Cross-platform ledger GUI written in c99

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 
#include <stdio.h>
#include <stddef.h>
#include <stdlib.h>
#include <inttypes.h>
#include <ctype.h>
#include <limits.h>
#include <errno.h>

#include "common.h"
#include "strn.h"

#ifndef _WIN32
#include <unistd.h>
#endif

#define _XOPEN_SOURCE
#include <time.h>

#include "vstr.h"
#include <account.h>
#include <book.h>

#define BUFFER_SIZE 256

#define warning(STR) \
	fprintf(stdout, "\033[31m"STR"\033[0m");

#define warningf(STR,...) \
	fprintf(stdout, "\033[31m"STR"\033[0m", __VA_ARGS__);

vstr_t tags[100] = { 0 };

size_t tags_size = 0;

/*
 * char* tags = { "Expenses:Auto:Gas", "Liabilities:MasterCard",
 * "Assets:Credit" };
 */

/**
 *
 read the file | parse for newlines
 2023/10/24 - 5, fptr + 0, fptr + 6, fptr + 9
 Entry* entry = get_entry("2023/10/24");

 skip \n
 read until date, and read until from

 **/

// commodity max size 256
// commodity name max size 4
char commodity_list[256][8];

map_tree_t *rootp = NULL;


// store numbers in the least denom
// 1.50$ == 150
// 2$ == 200
// 2.23$ == 200

typedef struct {
	vstr_t *denom;
	size_t quantity;
	int8_t decimal;
} LedgerValue;

typedef struct {
	vstr_t *reg;
	LedgerValue val;
} LedgerRecord;

typedef struct {
	time_t date;		// the date associated with the entry
	vstr_t comment;		// comment associated with the entry
	LedgerRecord **records;
} LedgerEntry;

time_t
ledger_timestamp_from_ledger_date(char *date_str)
{
	// converts string 'YYYY-MM-DD' to unix timestamp
	// date_str should be exactly 10 characters
	// printf("%.*s\n", 4, date_str);
	struct tm tm = { 0 };
	tm.tm_year = natoi(date_str, 4) - 1900;
	tm.tm_mon = natoi(date_str + 5, 2) - 1;
	tm.tm_mday = natoi(date_str + 8, 2);
	// warning("tm_year %d, tm_mon: %d, tm_mday: %d", natoi(date_str, 4),
	// tm.tm_mon, tm.tm_mday);
	return mktime(&tm);
}

const char *states_str[] = {
	"DATE",
	"COMMENT",
	"ENTRY START",
	"ENTRY SPACE",
	"ENTRY WHO",
	"ENTRY AMOUNT",
	"ENTRY DENOM",
	"ENTRY END",
};

typedef enum {
	DATE,
	COMMENT,
	ENTRY_START, // entry starts after a comment
	ENTRY_SPACE,
	ENTRY_WHO,
	ENTRY_AMOUNT,
	ENTRY_DENOM ,
	ENTRY_END, // finish up entry if encountering any \n\n or \n text_len == i or text_len == i, otherwise set state to ENTRY_SPACE
	POSTING_END,
} LedgerParseStates;


void
ledger_parse_data(char *text, size_t text_len)
{
	char *denom_list[256];
	memset(denom_list, 0, 256);
	char* denomptr = NULL;
	setvbuf(stdout, NULL, _IONBF, 0);

	LedgerParseStates state = DATE;
	size_t line_no = 1;
	size_t current_column = 1;
	time_t t = time(NULL);
	size_t i = 0;
	// TODO it may be possible to push these to the tree itself, explore the possibility
	// these act as temporary register until we push back the entry to a tree
	time_t hold_date;
	vstr_t hold_comment = { 0 };
	vstr_t hold_register = { 0 };
	long hold_amount = LONG_MAX;
	char hold_sign = 0;
	size_t hold_denom_id = { 0 };
	short n_count = 0;
	char hold_fquantity = 0;

	hold_amount = LONG_MAX;

	setvbuf(stdout, NULL, _IONBF, 0);
	// TODO it may be possible to push these to the tree itself, explore the possibility
	// these act as temporary register until we push back the entry to a tree

	while (i < text_len) {
		char c = text[i];
		/* \n identifies an entry done in ledger */
		switch (c) {
			case '\n':
			case '\r':
				line_no++;
				n_count++;
				switch (state) {
					// after parsing the amount seq, we set the state to ENTRY_WHO
					case ENTRY_WHO:
					case ENTRY_END:
						hold_sign = 0;
						hold_amount = LONG_MAX;
						hold_denom_id = 0;
						// if entry_count <= 1 throw error
						if (text[i - 1] == '\n') {
							state = DATE;
							// TODO push the entries to stack or somethin
							warning("\n==\n");
							// state = POSTING_END;
							break;
						}
						state = ENTRY_WHO;
						warning(",");
						break;
					case COMMENT:
						state = ENTRY_START;
						break;
					case ENTRY_DENOM:
						//warningf("%s", "denom not found, setting state WHO");
						state = ENTRY_WHO;
						break;
					case ENTRY_AMOUNT:
						goto ledger_parse_error_handle;
						break;
				}
				i++;
				continue;
			case ' ':
			case '\t':
				n_count = 0;
				i++;
				continue;
				break;
		}
		n_count = 0;
		// next state
		switch (state) {
			case DATE:
				if (isdigit(c)) {
					// try to parse a date
					time_t tn = ledger_timestamp_from_ledger_date(text + i);
					warningf("%.*s: %ld	", 10, text + i, (long)tn);
					// date is expected to have the form DD/MM/YYYY (10)
					i += 10;
					if (tn == (time_t) - 1) goto ledger_parse_error_handle;
					state = COMMENT;
				}
				break;
			case COMMENT:
				if (isalnum(c)) {
					// we hit alphanumerical after whitespace
					vstr_t comment = {
						.str = text + i,
						.len = 0
					};
					while (i < text_len && *(text + i) != '\n') {
						i++;
						comment.len++;
					}
					warningf("Comment: %.*s", comment.len,
							comment.str);
					state = ENTRY_START;
				}
				break;
			case ENTRY_START:
			case ENTRY_WHO:
				{
					// add this to register
					size_t who_len = i;
					vstr_t who = {
						.str = text + i,
						.len = 0
					};
					while (i < text_len) {
						switch (text[i]) {
							case '\n':
							case '\r':
								goto ledger_who_parsed;
								break;
							case '\t':
							case ' ':
								goto ledger_who_parsed;
								break;
							default:
								i++;
								break;
						}
					}
ledger_who_parsed:
					who_len = i - who_len;
					account_add(&rootp, who.str, who_len);
					warningf("\n@%d Who=%.*s", i, who_len, who);
					state = ENTRY_DENOM;
					/* TODO add to tags here */
				}
				break;
			case ENTRY_DENOM: {
				char _c;
				if (hold_denom_id) {
					warning("Denom already parsed\n");
					goto ledger_parse_error_handle;
				}
				char *denom = text + i;
				size_t denom_len = 0;

				if (*denom == '-') {
					if (hold_sign) goto ledger_parse_error_handle;
					hold_sign = 1;
					i++;
					state = ENTRY_DENOM;
					break;
				}

				warningf(" @%d D", i + 1);

				while (i < text_len &&
						( isalpha(*(text + i))
				/* TODO Search denomlist instead of just checking '$' */
						 || *(text + i) == '$')) i++;
				denom_len = (text + i) - denom;
				/* FIXME Use proper id */
				hold_denom_id = *denom;//get_denom_id(denom, denom_len);
				// hold_denom_len = denom_len;
				state = hold_amount == LONG_MAX? ENTRY_AMOUNT : ENTRY_END;
				warningf("#%d(%.*s)", denom_len, denom_len, denom);
				break;
			}
			case ENTRY_AMOUNT: {
				char _c;
				if (hold_amount != LONG_MAX) {
					warning("Amount already parsed\n");
					goto ledger_parse_error_handle;
				}

				char *amount = text + i;
				size_t amount_len = 0;

				char *eptr = NULL;
				char *efptr = NULL;

				if (*amount == '-') {
					if (hold_sign) goto ledger_parse_error_handle;
					hold_sign = 1;
					i++;
					state = ENTRY_AMOUNT;
					break;
				}

				warningf(" @%d A", i + 1);

				hold_amount = strtol(amount, &eptr, 10);

				if (errno == ERANGE) {
					perror("FATAL: Big ints are not supported at the moment");
					exit(-1);
				}
				if (errno) {
					perror("Some unknown error occured while parsing quantity");
					exit(-1);
				}

				amount_len = eptr - amount;

				if (*eptr == ',') *eptr = '.';
				if (amount_len && *eptr == '.') {
					float temp = strtof(eptr, &efptr);
					if (efptr == eptr) {
						/*
						TODO Check if '.' should end a transaction
						TODO Handle @
						*/
						printf("Searching for decimal value got '%c'\n", *efptr);
						exit(-1);
					}

					if (efptr - eptr > 3) {
						warning("FATAL: Only 2 decimal places are supported at the moment\n");
						exit(-1);
					}
					hold_fquantity = (char) (temp * 100);
					eptr = efptr;
				}

				amount_len = eptr - amount;
				i += amount_len;

				/* number parse failed */
				if (eptr == amount) {
					if (hold_denom_id) goto ledger_parse_error_handle;
					state = ENTRY_DENOM;
					break;
				}

				state = hold_denom_id ? ENTRY_END : ENTRY_DENOM;
				warningf("#%d(%.*s)", amount_len, amount_len, amount);
				}
				break;
			default:
				goto ledger_parse_error_handle;
		}
	}
	warning("read complete\n");
	return;
ledger_parse_error_handle:
	warningf("\nParse failed @%d line:%ld, Expected %s, got '%c'\n",
			i, line_no, states_str[state], text[i]);
}

Entry**
ledger_read_file(const char* filename, time_t date_start, time_t date_end) {
	Entity me = {"Account:Income"};
	// list population, read from
	FILE* file = fopen(filename, "r");
	if (file == NULL) {
		printf("Failed to open file %s\n", filename);
	}
	Entry** new_list = (Entry**)malloc(sizeof(Entry*) * 12);
	for(int i = 0; i < 12; i++) {
		Entry* entry = (Entry*)malloc(sizeof(Entry));
		new_list[i] = entry;
		entry->from = &me;
		entry->to = (Entity*)malloc(sizeof(Entity));
		entry->to->name = (char*)malloc(sizeof(char*) * 20);
		strncpy(entry->to->name, "Man", 3);
	}
	return new_list;
}

void
*module_main(char *data, size_t data_len)
{
	// printf("%s\n", data);
	warning("\n=======| Startality |=======\n");
	ledger_parse_data(data, data_len);
	warning("\n========| Fatality |========\n");
	return NULL;
}