Add support for colours

This commit is contained in:
Sebastiaan de Schaetzen 2025-05-25 13:42:41 +02:00
parent a006fce336
commit 3152287d9f
3 changed files with 61 additions and 18 deletions

30
backend/colour.go Normal file
View File

@ -0,0 +1,30 @@
package main
import (
"errors"
"fmt"
)
func ConvertStringToColour(colourStr string) (int, error) {
if len(colourStr) == 0 {
return 0xFF0000, nil // Default colour if no string is provided
}
if colourStr[0] == '#' {
colourStr = colourStr[1:]
}
if len(colourStr) != 6 && len(colourStr) != 3 {
return 0, errors.New("colour must be a valid hex string")
}
var colour int
_, err := fmt.Sscanf(colourStr, "%x", &colour)
if err != nil {
return 0, fmt.Errorf("invalid colour format: %v", err)
}
if len(colourStr) == 3 {
r := (colour & 0xF00) >> 8
g := (colour & 0x0F0) >> 4
b := (colour & 0x00F) >> 0
colour = (r << 16 << 4) | (g << 8 << 4) | (b << 0 << 4)
}
return colour, nil
}

30
backend/colour_test.go Normal file
View File

@ -0,0 +1,30 @@
package main
import (
"github.com/stretchr/testify/require"
"testing"
)
func TestConvertStringToColourWithSign(t *testing.T) {
colour, err := ConvertStringToColour("#123456")
require.NoError(t, err)
require.Equal(t, 0x123456, colour)
}
func TestConvertStringToColourWithoutSign(t *testing.T) {
colour, err := ConvertStringToColour("123456")
require.NoError(t, err)
require.Equal(t, 0x123456, colour)
}
func TestConvertStringToColourWithSignThreeDigits(t *testing.T) {
colour, err := ConvertStringToColour("#ABC")
require.NoError(t, err)
require.Equal(t, 0xA0B0C0, colour)
}
func TestConvertStringToColourWithoutSignThreeDigits(t *testing.T) {
colour, err := ConvertStringToColour("ABC")
require.NoError(t, err)
require.Equal(t, 0xA0B0C0, colour)
}

View File

@ -127,23 +127,6 @@ func (db *Db) GetUserAllowanceById(userId int, allowanceId int) (*Allowance, err
return allowance, nil
}
func ConvertStringToColour(colourStr string) (int, error) {
if len(colourStr) == 0 {
return 0xFF0000, nil // Default colour if no string is provided
}
if colourStr[0] == '#' {
colourStr = colourStr[1:]
}
if len(colourStr) != 6 && len(colourStr) != 3 {
return 0, errors.New("colour must be a valid hex string")
}
colour, err := fmt.Sscanf(colourStr, "%x", &colourStr)
if err != nil {
return 0, fmt.Errorf("invalid colour format: %v", err)
}
return colour, nil
}
func (db *Db) CreateAllowance(userId int, allowance *CreateAllowanceRequest) (int, error) {
// Check if user exists before attempting to create an allowance
exists, err := db.UserExists(userId)
@ -287,7 +270,7 @@ func (db *Db) UpdateAllowance(userId int, allowanceId int, allowance *UpdateAllo
target := int(math.Round(allowance.Target * 100.0))
err = tx.Query("update allowances set name=?, target=?, weight=?, colour=? where id = ? and user_id = ?").
Bind(allowance.Name, target, allowance.Weight, allowanceId, userId, colour).
Bind(allowance.Name, target, allowance.Weight, colour, allowanceId, userId).
Exec()
if err != nil {
return err