# req-030 Schist must implement the procedure described below as `calculate_bucket_balance`. Source: req-029 Satisfied by: - task-001 (desktop interface for inserting transactions) - task-006 (SMS interface for inserting transactions) - task-054 (Web interface for inserting transactions) - req-109 (transactions have a `timestamp`) - req-107 (transactions have a `bucket_id`) - req-108 (transactions have an `amount`) - req-027 (buckets have a `balance`) - req-110 (buckets have a `balance_cache_key`) - req-111 (buckets have an `id`) - req-098 (buckets have a `name`) - req-035 (implement `is_bucket_balance_up_to_date`) - req-037 (implement `update_bucket_drips`) - dml-drip (drips have a `bucket_id` and `amount`) ## calculate_bucket_balance Inputs: - A bucket name, `name` 1. If no bucket exists with the name, `name`, then return empty. 2. If more than one bucket exists with the name, `name`, then panic. 3. Let `bucket` be the bucket with the given name. 4. Let `cache_key = bucket.balance_cache_key`. 5. Let `is_up_to_date` be the result of the procedure, `is_bucket_balance_up_to_date(bucket)`, as described in req-035. 6. If `is_up_to_date = TRUE`, then return `bucket.balance`. 7. Carry out the procedure, `update_bucket_drips(bucket)`, as described in req-037. 8. Let `latest_transaction` be the transaction `t` with the most recent `t.timestamp` such that `t.bucket_id = bucket.id`. 9. Let `transaction_sum` be the sum over the property, `amount`, of all transactions `t` such that `t.bucket_id = bucket.id`. 10. Let `latest_drip` be the drip `d` with the most recent `d.timestamp` such that `d.bucket_id = bucket.id`. 11. Let `drip_sum` be the sum over the property, `amount`, of all drips `d` such that `d.bucket_id = bucket.id`. 12. Let `balance` be `drip_sum - transaction_sum`. 13. Set `bucket.balance` to `balance`. 14. Set `bucket.balance_cache_key` to `{latest_drip.id}:{latest_transaction.id}`.