Category calculations

The fifth and final section contains functions to calculate totals by category, which we'll utilize in the pie charts, as follows:

void upsertCategoryNode(int categoryId, float transactionRaw,
float transactionCooked) {
struct Node *foundNode = findNodeById(categoryId, categoriesHead);
if (foundNode != NULL) {
foundNode->rawAmount += transactionRaw;
foundNode->cookedAmount += transactionCooked;
} else {
appendNode(&categoriesHead, categoryId, categoryId, transactionRaw,
transactionCooked);
}
}

void buildValuesByCategoryList() {
struct Node *node = transactionsHead;
while (node != NULL) {
upsertCategoryNode(node->categoryId, node->rawAmount,
node->cookedAmount);
node = node->next;
}
}

void recalculateForCategories() {
categoriesHead = NULL;
buildValuesByCategoryList();
}

float getCategoryTotal(AmountType type, int categoryId) {
// Ensure the category totals have been calculated:
if (categoriesHead == NULL) buildValuesByCategoryList();

struct Node *categoryNode = findNodeById(categoryId, categoriesHead);
if (categoryNode == NULL) return 0;

if (type == RAW) return categoryNode->rawAmount;
if (type == COOKED) return categoryNode->cookedAmount;
return 0;
}

The buildValuesByCategoryList() function is called whenever the recalculateForCategories() or getCategoryTotal() functions are called. The function loops through all of the transactions in the transactions linked list and creates a node in a separate linked list for each corresponding category with the aggregated raw and total amounts. The upsertCategoryNode() function looks for a node that corresponds to the categoryId in the categories linked list. If it finds it, the raw and cooked transaction amounts are added to the existing amounts on that node, otherwise a new node is created for said category. The recalculateForCategories() function is called to ensure the category totals are up to date with any transactions changes.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset