7 Commits

13 changed files with 546 additions and 70 deletions

79
Asset/css/finance.css Normal file
View File

@@ -0,0 +1,79 @@
/*
* FinanceBuddy styles.
*/
/* Per-column net total in the column header (its own line, subtle pill). */
.fb-column-total {
display: inline-block;
margin-top: 3px;
padding: 0 5px;
font-weight: bold;
font-size: 0.95em;
background: rgba(0, 0, 0, 0.05);
border-radius: 3px;
}
.fb-total-debit {
color: #b94a48;
}
.fb-total-credit {
color: #468847;
}
.fb-total-zero {
color: #777;
}
/* Line-3 money badge on board cards. Its own background guarantees contrast on any card color. */
.fb-line {
margin: 2px 0 4px;
line-height: 1.4;
}
.fb-badge {
display: inline-block;
padding: 1px 6px;
border-radius: 3px;
color: #fff;
font-weight: bold;
font-size: 1.1em;
}
.fb-badge-debit {
background: #b94a48;
}
.fb-badge-credit {
background: #468847;
}
.fb-installments {
margin-left: 6px;
color: #000;
font-size: 1.05em;
}
/* Task-form finance fieldset (middle column). */
.fb-form-directions {
margin-bottom: 8px;
}
.fb-form-inline {
display: inline-block;
margin-right: 14px;
cursor: pointer;
}
.fb-form-installments {
display: flex;
align-items: center;
}
.fb-form-installments .fb-form-num {
width: 5em;
}
.fb-form-installments span {
margin: 0 8px;
}

View File

@@ -1 +0,0 @@
/* Skeleton plugin styles -- add CSS here. Loaded via template:layout:css. */

View File

@@ -1 +0,0 @@
// Skeleton plugin script -- add JS here. Loaded via template:layout:js.

170
Helper/FinanceHelper.php Normal file
View File

@@ -0,0 +1,170 @@
<?php
namespace Kanboard\Plugin\FinanceBuddy\Helper;
use Kanboard\Core\Base;
/**
* Template/controller helper for FinanceBuddy.
*
* FinanceBuddy is opt-in per board: every render and save point is gated on isEnabled(), so an
* un-enabled board is untouched. The enable flag lives in project metadata (financebuddy_enabled);
* the per-task money lives in task metadata under the keys below.
*/
class FinanceHelper extends Base
{
const ENABLED_KEY = 'financebuddy_enabled';
const AMOUNT_KEY = 'financebuddy_amount';
const DIRECTION_KEY = 'financebuddy_direction';
const INSTALLMENT_CURRENT_KEY = 'financebuddy_installment_current';
const INSTALLMENT_TOTAL_KEY = 'financebuddy_installment_total';
// Hidden marker present only when the task form was submitted with the finance fieldset, so
// non-finance task updates (moves, API calls) are ignored by the persistence hooks.
const FORM_MARKER = 'financebuddy_form';
// Memoized per project_id: the board hooks below call isEnabled() once per card.
private static $enabledCache = array();
/**
* Is FinanceBuddy enabled for this board?
*
* @param integer $project_id
* @return bool
*/
public function isEnabled($project_id)
{
$project_id = (int) $project_id;
if (! isset(self::$enabledCache[$project_id])) {
self::$enabledCache[$project_id] = (int) $this->projectMetadataModel->get($project_id, self::ENABLED_KEY, 0) === 1;
}
return self::$enabledCache[$project_id];
}
/**
* Stored finance values for a task, with defaults. One query (getAll) since the board renders
* this per card.
*
* @param integer $task_id
* @return array
*/
public function get($task_id)
{
$all = $this->taskMetadataModel->getAll($task_id);
return array(
'amount' => isset($all[self::AMOUNT_KEY]) ? $all[self::AMOUNT_KEY] : '',
'direction' => (isset($all[self::DIRECTION_KEY]) && $all[self::DIRECTION_KEY] === 'credit') ? 'credit' : 'debit',
'installment_current' => isset($all[self::INSTALLMENT_CURRENT_KEY]) ? $all[self::INSTALLMENT_CURRENT_KEY] : '',
'installment_total' => isset($all[self::INSTALLMENT_TOTAL_KEY]) ? $all[self::INSTALLMENT_TOTAL_KEY] : '',
);
}
/**
* Net money for a board column: credits positive, debits negative, summed over the cards in
* the column. One grouped query over the column's task ids (the task rows carry no metadata).
*
* @param array $column A board column as passed to template:board:column:header ('tasks').
* @return float
*/
public function columnNet(array $column)
{
if (empty($column['tasks'])) {
return 0.0;
}
$task_ids = array();
foreach ($column['tasks'] as $task) {
$task_ids[] = (int) $task['id'];
}
$rows = $this->db->table('task_has_metadata')
->columns('task_id', 'name', 'value')
->in('task_id', $task_ids)
->in('name', array(self::AMOUNT_KEY, self::DIRECTION_KEY))
->findAll();
$amounts = array();
$directions = array();
foreach ($rows as $row) {
if ($row['name'] === self::AMOUNT_KEY) {
$amounts[$row['task_id']] = (float) $row['value'];
} else {
$directions[$row['task_id']] = $row['value'];
}
}
$net = 0.0;
foreach ($amounts as $task_id => $amount) {
if ($amount <= 0) {
continue;
}
$is_credit = isset($directions[$task_id]) && $directions[$task_id] === 'credit';
$net += $is_credit ? $amount : -$amount;
}
return $net;
}
/**
* Values to prefill the task-form fields: a re-post (after a validation error) wins, then the
* stored metadata for an existing task, otherwise blanks for a new task.
*
* @param array $values
* @return array
*/
public function formValues(array $values)
{
if (isset($values[self::FORM_MARKER])) {
return array(
'amount' => isset($values[self::AMOUNT_KEY]) ? $values[self::AMOUNT_KEY] : '',
'direction' => (isset($values[self::DIRECTION_KEY]) && $values[self::DIRECTION_KEY] === 'credit') ? 'credit' : 'debit',
'installment_current' => isset($values[self::INSTALLMENT_CURRENT_KEY]) ? $values[self::INSTALLMENT_CURRENT_KEY] : '',
'installment_total' => isset($values[self::INSTALLMENT_TOTAL_KEY]) ? $values[self::INSTALLMENT_TOTAL_KEY] : '',
);
}
if (! empty($values['id'])) {
return $this->get($values['id']);
}
return array('amount' => '', 'direction' => 'debit', 'installment_current' => '', 'installment_total' => '');
}
/**
* Parse a user-typed amount. Accepts a dot or a comma as the decimal separator and an optional
* "R$"; there is no thousand separator. Returns a non-negative float (0.0 when unparseable).
*
* @param string $raw
* @return float
*/
public static function parseAmount($raw)
{
$raw = str_replace(array('R$', ' '), '', trim((string) $raw));
$raw = str_replace(',', '.', $raw);
if ($raw === '' || ! is_numeric($raw)) {
return 0.0;
}
$value = round((float) $raw, 2);
return $value > 0 ? $value : 0.0;
}
/**
* Format a money value for display: two decimals, comma decimal separator, no thousand
* separator (e.g. 20.9 -> "20,90"). Accepts a float or a canonical dot-string.
*
* @param float|string $amount
* @return string
*/
public static function money($amount)
{
return number_format((float) $amount, 2, ',', '');
}
}

View File

@@ -0,0 +1,123 @@
<?php
namespace Kanboard\Plugin\FinanceBuddy\Model;
use Kanboard\Core\Base;
use Kanboard\Plugin\FinanceBuddy\Helper\FinanceHelper;
/**
* Persists the FinanceBuddy fields that live in the core task form.
*
* PicoDb's insert()/update() build SQL straight from the value keys, so any non-column field left
* in $values would break task saving (this is why core unset()s "tags"). We therefore:
* (a) strip every financebuddy_* key from $values in the create/modify "prepare" hooks, and
* (b) write the values to task metadata separately.
*
* Everything here runs synchronously inside the model call during the HTTP request (the "prepare"
* and "aftersave" reference hooks), so it does NOT depend on the optionally-async event queue. The
* finance values are read straight from $values (getValues() cannot be reused: the controller
* already consumed the CSRF token). The task id comes from the aftersave hook (create) or the
* route parameter (modify).
*/
class FinancePersistence extends Base
{
private $pending = null;
/**
* model:task:creation:prepare -- fires before INSERT, $values by reference, no task id yet.
*/
public function onCreationPrepare(array &$values)
{
$this->pending = null;
if (isset($values[FinanceHelper::FORM_MARKER])) {
$this->pending = array(
'project_id' => isset($values['project_id']) ? (int) $values['project_id'] : 0,
'fields' => $this->extract($values),
);
}
$this->strip($values);
}
/**
* model:task:creation:aftersave -- fires after INSERT, hands over the new task id by reference.
*/
public function onCreationAfterSave(&$task_id)
{
if ($this->pending !== null) {
$this->persist((int) $task_id, $this->pending['project_id'], $this->pending['fields']);
$this->pending = null;
}
}
/**
* model:task:modification:prepare -- fires before UPDATE, $values by reference. The task id is
* removed from $values by core, but it is the route parameter of the modification request.
*/
public function onModificationPrepare(array &$values)
{
if (isset($values[FinanceHelper::FORM_MARKER])) {
$task_id = $this->request->getIntegerParam('task_id');
$project_id = isset($values['project_id']) ? (int) $values['project_id'] : 0;
if ($task_id > 0) {
$this->persist($task_id, $project_id, $this->extract($values));
}
}
$this->strip($values);
}
private function extract(array $values)
{
return array(
'amount' => isset($values[FinanceHelper::AMOUNT_KEY]) ? $values[FinanceHelper::AMOUNT_KEY] : '',
'direction' => (isset($values[FinanceHelper::DIRECTION_KEY]) && $values[FinanceHelper::DIRECTION_KEY] === 'credit') ? 'credit' : 'debit',
'installment_current' => isset($values[FinanceHelper::INSTALLMENT_CURRENT_KEY]) ? $values[FinanceHelper::INSTALLMENT_CURRENT_KEY] : '',
'installment_total' => isset($values[FinanceHelper::INSTALLMENT_TOTAL_KEY]) ? $values[FinanceHelper::INSTALLMENT_TOTAL_KEY] : '',
);
}
private function strip(array &$values)
{
foreach (array_keys($values) as $key) {
if (strpos($key, 'financebuddy_') === 0) {
unset($values[$key]);
}
}
}
private function persist($task_id, $project_id, array $fields)
{
// Only touch metadata on boards where a manager opted in.
if ((int) $this->projectMetadataModel->get($project_id, FinanceHelper::ENABLED_KEY, 0) !== 1) {
return;
}
$amount = FinanceHelper::parseAmount($fields['amount']);
// No (or cleared) amount: drop any finance metadata so the card goes back to plain.
if ($amount <= 0) {
foreach (array(FinanceHelper::AMOUNT_KEY, FinanceHelper::DIRECTION_KEY, FinanceHelper::INSTALLMENT_CURRENT_KEY, FinanceHelper::INSTALLMENT_TOTAL_KEY) as $key) {
$this->taskMetadataModel->remove($task_id, $key);
}
return;
}
$this->taskMetadataModel->save($task_id, array(
FinanceHelper::AMOUNT_KEY => number_format($amount, 2, '.', ''),
FinanceHelper::DIRECTION_KEY => $fields['direction'] === 'credit' ? 'credit' : 'debit',
FinanceHelper::INSTALLMENT_CURRENT_KEY => $this->intOrBlank($fields['installment_current']),
FinanceHelper::INSTALLMENT_TOTAL_KEY => $this->intOrBlank($fields['installment_total']),
));
}
private function intOrBlank($raw)
{
$raw = trim((string) $raw);
return ($raw !== '' && ctype_digit($raw) && (int) $raw > 0) ? (string) (int) $raw : '';
}
}

View File

@@ -1,6 +1,6 @@
<?php <?php
namespace Kanboard\Plugin\Skeleton; namespace Kanboard\Plugin\FinanceBuddy;
use Kanboard\Core\Plugin\Base; use Kanboard\Core\Plugin\Base;
@@ -8,28 +8,51 @@ class Plugin extends Base
{ {
public function initialize() public function initialize()
{ {
// 1. Render a visible word at the top of every page (the demo output). // Plugin stylesheet. Empty for now; the money badge and per-column total styling
$this->template->hook->attach('template:layout:top', 'skeleton:layout/header'); // are added as those features land in later versions.
// 2. Load the plugin stylesheet (currently empty -- proves the CSS hook fires).
$this->hook->on('template:layout:css', array( $this->hook->on('template:layout:css', array(
'template' => 'plugins/Skeleton/Asset/css/skeleton.css', 'template' => 'plugins/FinanceBuddy/Asset/css/finance.css',
)); ));
// 3. Load the plugin script (currently empty -- proves the JS hook fires). // Per-board opt-in: a checkbox on the project's Settings -> Integrations page. Nothing
$this->hook->on('template:layout:js', array( // else in the plugin renders or saves until a project manager enables it for that board.
'template' => 'plugins/Skeleton/Asset/js/skeleton.js', $this->template->hook->attach('template:project:integrations', 'financeBuddy:project/integration');
));
// Finance fields in the task create/edit form (middle column). The template gates itself
// on the board being enabled. These are not task columns, so core cannot persist them:
// FinancePersistence strips them from the task write and stores them in task metadata,
// all synchronously via the model hooks below.
$this->template->hook->attach('template:task:form:second-column', 'financeBuddy:task/form_fields');
$persistence = new \Kanboard\Plugin\FinanceBuddy\Model\FinancePersistence($this->container);
$this->hook->on('model:task:creation:prepare', array($persistence, 'onCreationPrepare'));
$this->hook->on('model:task:creation:aftersave', array($persistence, 'onCreationAfterSave'));
$this->hook->on('model:task:modification:prepare', array($persistence, 'onModificationPrepare'));
// The line-3 money badge on each board card, rendered directly under the title. Two hooks:
// "private" is the normal board, "public" is the read-only board shared by token.
$this->template->hook->attach('template:board:private:task:after-title', 'financeBuddy:board/task_money');
$this->template->hook->attach('template:board:public:task:after-title', 'financeBuddy:board/task_money');
// Per-column net total (credits - debits) in the column header.
$this->template->hook->attach('template:board:column:header', 'financeBuddy:board/column_total');
}
public function getHelpers()
{
return array(
'Plugin\FinanceBuddy\Helper' => array('FinanceHelper'),
);
} }
public function getPluginName() public function getPluginName()
{ {
return 'Skeleton'; return 'FinanceBuddy';
} }
public function getPluginDescription() public function getPluginDescription()
{ {
return t('Reusable skeleton/template for building Kanboard plugins.'); return t('Attach a money value (debit/credit and installments) to board cards, shown on the card and totalled per column. Opt-in per board.');
} }
public function getPluginAuthor() public function getPluginAuthor()
@@ -39,12 +62,12 @@ class Plugin extends Base
public function getPluginVersion() public function getPluginVersion()
{ {
return '0.1.0'; return '0.4.0';
} }
public function getPluginHomepage() public function getPluginHomepage()
{ {
return 'https://code.beco.cc/beco/kanboard-plugin-skeleton'; return 'https://code.beco.cc/beco/FinanceBuddy';
} }
public function getCompatibleVersion() public function getCompatibleVersion()

View File

@@ -1,19 +1,39 @@
# Skeleton -- a Kanboard plugin template # FinanceBuddy -- money on your Kanboard cards
A minimal, working Kanboard plugin that you copy and rename as the starting point for a Attach a money value to a board card, see it on the card, and total it per column -- so a
real plugin. By itself it does only one trivial thing: it renders the word "Skeleton" at Kanboard project can double as a simple, visual finance board (bills, installments, income
the top of every page. It changes no data and runs no database migration. vs expenses).
## What it demonstrates FinanceBuddy is **opt-in per board**: installing it changes nothing until a project manager
enables it for a specific board under Settings -> Integrations. Boards that are not enabled
look exactly as before.
- A complete `Plugin.php` registration class with all the metadata Kanboard shows in ## The idea: a bill-lifecycle board
Settings -> Plugins (name, description, author, version, homepage, compatible version).
- A template hook (`template:layout:top`) that injects a template into the page. Kanboard imposes no structure, so FinanceBuddy is built to fit one rather than dictate it. The
- Asset hooks (`template:layout:css` and `template:layout:js`) that load a stylesheet and suggested organization:
a script. They are empty for now but prove the injection path works -- handy when a real
plugin needs custom CSS or JS. - **Columns = a bill's status:** `Templates -> Due this month -> Paid`. Cards flow left to
- The standard plugin directory layout, with stub folders (`Controller/`, `Model/`, right as they are paid.
`Schema/`, `Locale/`, `Test/`) ready to grow into. - **Tags = category:** housing, utilities, comms, food...
- **Due date = the bill's due date;** color/priority = urgency.
- Each card carries a **money value** (debit or credit) and, optionally, an **installment**
count (`p2/10` = 2nd of 10 payments; leave the total blank for an open-ended recurring bill).
Recurring monthly bills can live as template cards spawned each month by the companion RecoReco
plugin; FinanceBuddy only owns the money.
## Money format
Amounts are shown in R$ with a comma decimal and no thousand separator (for example
`R$1234,56`). Input accepts either a dot or a comma as the decimal separator, so `1234.56` and
`1234,56` are the same value.
## Status
Early development. This version registers the plugin and loads its stylesheet; the per-board
toggle, the in-form editing, the card badge, and the per-column totals arrive in the following
versions.
## Requirements ## Requirements
@@ -21,45 +41,9 @@ the top of every page. It changes no data and runs no database migration.
## Installation ## Installation
No build step and no dependencies. Copy this folder into your Kanboard installation as `plugins/FinanceBuddy/`. The directory name
must be exactly `FinanceBuddy` (Kanboard derives the plugin namespace from the folder name). No
1. Copy this folder into your Kanboard installation as `plugins/Skeleton/`. build step and no database migration.
2. Reload any page. The word "Skeleton" appears at the top.
3. Confirm it under Settings -> Plugins.
To uninstall, delete `plugins/Skeleton/`. Nothing else is left behind.
## Directory layout
```
Skeleton/
Plugin.php Registration and hook wiring (the only required file).
README.md
LICENSE AGPL-3.0.
Template/
layout/header.php The visible "Skeleton" word.
Asset/
css/skeleton.css Loaded via template:layout:css.
js/skeleton.js Loaded via template:layout:js.
Controller/ Stub for future request handlers.
Model/ Stub for future business logic / DB access.
Schema/ Stub for future database migrations.
Locale/ Stub for future translations (e.g. pt_BR/, fr_FR/).
Test/ Stub for future unit tests.
```
## How to fork this into a new plugin
1. Copy the folder and rename it, e.g. `plugins/MyPlugin/`. The folder name must match the
namespace and start with a capital letter.
2. In `Plugin.php`, change the namespace from `Kanboard\Plugin\Skeleton` to
`Kanboard\Plugin\MyPlugin`.
3. Update the metadata methods (`getPluginName`, `getPluginDescription`, `getPluginAuthor`,
`getPluginVersion`, `getPluginHomepage`, `getCompatibleVersion`).
4. Update the hook target paths: the lowercase prefix in `'skeleton:layout/header'` and the
`plugins/Skeleton/Asset/...` asset paths must match the new plugin name.
5. Replace `Template/layout/header.php` with your real template, or attach to a different
hook. See the Kanboard plugin hooks documentation for the full list of hook points.
## License ## License

View File

@@ -0,0 +1,24 @@
<?php
// Per-column net total in the column header (credits - debits). Shown in every column of an
// enabled board, including "total R$0,00" -- never hidden on zero. Server-side, re-renders on
// every board refresh.
if (empty($column['project_id']) || ! $this->FinanceHelper->isEnabled($column['project_id'])) {
return;
}
$net = $this->FinanceHelper->columnNet($column);
if ($net > 0) {
$class = 'fb-column-total fb-total-credit';
$sign = '+';
} elseif ($net < 0) {
$class = 'fb-column-total fb-total-debit';
$sign = '-';
} else {
$class = 'fb-column-total fb-total-zero';
$sign = '';
}
?>
<div class="<?= $class ?>">
<?= t('total') ?> <?= $sign ?>R$<?= \Kanboard\Plugin\FinanceBuddy\Helper\FinanceHelper::money(abs($net)) ?>
</div>

View File

@@ -0,0 +1,27 @@
<?php
// Line-3 money badge, rendered under the card title via the after-title hooks. Server-side, so
// it re-renders correctly on every board refresh. Nothing shows unless the board is enabled and
// the card has a positive amount.
if (empty($task['project_id']) || ! $this->FinanceHelper->isEnabled($task['project_id'])) {
return;
}
$fb = $this->FinanceHelper->get($task['id']);
if ($fb['amount'] === '' || (float) $fb['amount'] <= 0) {
return;
}
$credit = $fb['direction'] === 'credit';
$sign = $credit ? '+' : '-';
$total = $fb['installment_total'];
$current = $fb['installment_current'] !== '' ? $fb['installment_current'] : '1';
?>
<div class="fb-line">
<span class="fb-badge <?= $credit ? 'fb-badge-credit' : 'fb-badge-debit' ?>">
<?= $sign ?>R$<?= \Kanboard\Plugin\FinanceBuddy\Helper\FinanceHelper::money($fb['amount']) ?>
</span>
<?php if ($total !== ''): ?>
<span class="fb-installments">p<?= $this->text->e($current) ?>/<?= $this->text->e($total) ?></span>
<?php endif ?>
</div>

View File

@@ -1 +0,0 @@
<div class="skeleton-plugin-marker">Skeleton</div>

View File

@@ -0,0 +1,20 @@
<h3><i class="fa fa-money fa-fw" aria-hidden="true"></i> <?= t('FinanceBuddy') ?></h3>
<div class="listing">
<?php /* Hidden 0 before the checkbox so unchecking posts a value (a bare unchecked box posts
nothing, which would leave a stale 1). The checkbox's 1 wins when checked. The shared
Integrations form saves this straight into project metadata. */ ?>
<input type="hidden" name="<?= \Kanboard\Plugin\FinanceBuddy\Helper\FinanceHelper::ENABLED_KEY ?>" value="0">
<?= $this->form->checkbox(
\Kanboard\Plugin\FinanceBuddy\Helper\FinanceHelper::ENABLED_KEY,
t('Enable FinanceBuddy on this board'),
1,
isset($values['financebuddy_enabled']) && $values['financebuddy_enabled'] == 1
) ?>
<p class="form-help">
<?= t('When enabled, cards on this board can carry a money value (debit or credit, with optional installments), shown on the card and totalled per column. Boards left disabled are unaffected.') ?>
</p>
</div>
<div class="form-actions">
<button type="submit" class="btn btn-blue"><?= t('Save') ?></button>
</div>

View File

@@ -0,0 +1,29 @@
<?php if (empty($values['project_id']) || ! $this->FinanceHelper->isEnabled($values['project_id'])): ?>
<?php else: ?>
<?php $fb = $this->FinanceHelper->formValues($values) ?>
<div class="fb-form">
<input type="hidden" name="<?= \Kanboard\Plugin\FinanceBuddy\Helper\FinanceHelper::FORM_MARKER ?>" value="1">
<label for="financebuddy_amount"><?= t('Amount (R$)') ?></label>
<input type="text" id="financebuddy_amount" name="financebuddy_amount" value="<?= $this->text->e($fb['amount']) ?>" placeholder="0,00" autocomplete="off">
<label><?= t('Type') ?></label>
<div class="fb-form-directions">
<label class="fb-form-inline">
<input type="radio" name="financebuddy_direction" value="debit" <?= $fb['direction'] !== 'credit' ? 'checked="checked"' : '' ?>> <?= t('Debit') ?>
</label>
<label class="fb-form-inline">
<input type="radio" name="financebuddy_direction" value="credit" <?= $fb['direction'] === 'credit' ? 'checked="checked"' : '' ?>> <?= t('Credit') ?>
</label>
</div>
<label for="financebuddy_installment_current"><?= t('Installment') ?></label>
<div class="fb-form-installments">
<input type="number" min="1" id="financebuddy_installment_current" name="financebuddy_installment_current" value="<?= $this->text->e($fb['installment_current']) ?>" class="fb-form-num">
<span><?= t('of') ?></span>
<input type="number" min="1" name="financebuddy_installment_total" value="<?= $this->text->e($fb['installment_total']) ?>" class="fb-form-num">
</div>
<p class="form-help"><?= t('Leave the total blank for an open-ended recurring bill.') ?></p>
</div>
<?php endif ?>

View File

@@ -1 +1 @@
FinanceBuddy v0.1 FinanceBuddy v0.4