code refactor

This commit is contained in:
MaysWind
2025-06-08 02:10:11 +08:00
parent 8c71f03f6f
commit ce4bca8272
14 changed files with 364 additions and 467 deletions

View File

@@ -1,37 +1,21 @@
/** import { type JestConfigWithTsJest, createDefaultEsmPreset } from 'ts-jest';
* For a detailed explanation regarding each configuration property, visit:
* https://jestjs.io/docs/configuration
*/
import type { Config } from 'jest'; const presetConfig = createDefaultEsmPreset({
tsconfig: '<rootDir>/tsconfig.jest.json'
const config: Config = { });
// Automatically clear mock calls, instances, contexts and results before every test
clearMocks: true,
// Indicates whether the coverage information should be collected while executing the test
collectCoverage: false,
// A map from regular expressions to module names or to arrays of module names that allow to stub out resources with a single module
moduleNameMapper: {
"^@/(.*)$": "<rootDir>/src/$1"
},
// The test environment that will be used for testing
testEnvironment: "node",
// The glob patterns Jest uses to detect test files
testMatch: [
"**/__tests__/**/*.[jt]s?(x)",
"!**/__tests__/*_gen.[jt]s?(x)"
],
// A map from regular expressions to paths to transformers
transform: {
'^.+\\.m?tsx?$': ['ts-jest', { useESM: true, isolatedModules: true }],
},
const config: JestConfigWithTsJest = {
...presetConfig,
clearMocks: true,
collectCoverage: false,
moduleNameMapper: {
"^@/(.*)$": "<rootDir>/src/$1"
},
testEnvironment: "node",
testMatch: [
"**/__tests__/**/*.[jt]s?(x)",
"!**/__tests__/*_gen.[jt]s?(x)"
]
}; };
module.exports = config; export default config;

View File

@@ -16,7 +16,7 @@
"build": "cross-env NODE_ENV=production vite build", "build": "cross-env NODE_ENV=production vite build",
"serve:dist": "vite preview", "serve:dist": "vite preview",
"lint": "tsc --noEmit && eslint . --fix", "lint": "tsc --noEmit && eslint . --fix",
"test": "jest" "test": "cross-env TS_NODE_PROJECT=\"./tsconfig.jest.json\" jest"
}, },
"dependencies": { "dependencies": {
"@mdi/js": "^7.4.47", "@mdi/js": "^7.4.47",

View File

@@ -17,11 +17,25 @@ const (
FISCAL_YEAR_START_INVALID FiscalYearStart = 0xFFFF // Invalid FISCAL_YEAR_START_INVALID FiscalYearStart = 0xFFFF // Invalid
) )
var MONTH_MAX_DAYS = []uint8{
uint8(31), // January
uint8(28), // February (Disallow fiscal year start on leap day)
uint8(31), // March
uint8(30), // April
uint8(31), // May
uint8(30), // June
uint8(31), // July
uint8(31), // August
uint8(30), // September
uint8(31), // October
uint8(30), // November
uint8(31), // December
}
// NewFiscalYearStart creates a new FiscalYearStart from month and day values // NewFiscalYearStart creates a new FiscalYearStart from month and day values
func NewFiscalYearStart(month uint8, day uint8) (FiscalYearStart, error) { func NewFiscalYearStart(month uint8, day uint8) (FiscalYearStart, error) {
month, day, err := validateMonthDay(month, day) if !isValidMonthDay(month, day) {
if err != nil { return 0, errs.ErrFormatInvalid
return 0, err
} }
return FiscalYearStart(uint16(month)<<8 | uint16(day)), nil return FiscalYearStart(uint16(month)<<8 | uint16(day)), nil
@@ -37,39 +51,27 @@ func (f FiscalYearStart) GetMonthDay() (uint8, uint8, error) {
month := uint8(f >> 8) month := uint8(f >> 8)
day := uint8(f & 0xFF) day := uint8(f & 0xFF)
return validateMonthDay(month, day) if !isValidMonthDay(month, day) {
return 0, 0, errs.ErrFormatInvalid
}
return month, day, nil
} }
// String returns a string representation of FiscalYearStart in MM/DD format // String returns a string representation of FiscalYearStart in MM/DD format
func (f FiscalYearStart) String() string { func (f FiscalYearStart) String() string {
month, day, err := f.GetMonthDay() month, day, err := f.GetMonthDay()
if err != nil { if err != nil {
return "Invalid" return "Invalid"
} }
return fmt.Sprintf("%02d-%02d", month, day) return fmt.Sprintf("%02d-%02d", month, day)
} }
// validateMonthDay validates a month and day and returns them if valid // isValidMonthDay returns whether the specified month and day is valid
func validateMonthDay(month uint8, day uint8) (uint8, uint8, error) { func isValidMonthDay(month uint8, day uint8) bool {
if month < 1 || month > 12 || day < 1 { return uint8(1) <= month && month <= uint8(12) && uint8(1) <= day && day <= MONTH_MAX_DAYS[int(month)-1]
return 0, 0, errs.ErrFormatInvalid
}
maxDays := uint8(31)
switch month {
case 1, 3, 5, 7, 8, 10, 12: // January, March, May, July, August, October, December
maxDays = 31
case 4, 6, 9, 11: // April, June, September, November
maxDays = 30
case 2: // February
maxDays = 28 // Disallow fiscal year start on leap day
}
if day > maxDays {
return 0, 0, errs.ErrFormatInvalid
}
return month, day, nil
} }
// FiscalYearFormat represents the fiscal year format as a uint8 // FiscalYearFormat represents the fiscal year format as a uint8

View File

@@ -3,8 +3,9 @@ package core
import ( import (
"testing" "testing"
"github.com/mayswind/ezbookkeeping/pkg/errs"
"github.com/stretchr/testify/assert" "github.com/stretchr/testify/assert"
"github.com/mayswind/ezbookkeeping/pkg/errs"
) )
func TestNewFiscalYearStart_ValidMonthDay(t *testing.T) { func TestNewFiscalYearStart_ValidMonthDay(t *testing.T) {

View File

@@ -1,88 +1,95 @@
import { computed } from 'vue'; import { ref, computed } from 'vue';
import { FiscalYearStart } from '@/core/fiscalyear.ts'; import { FiscalYearStart } from '@/core/fiscalyear.ts';
import { arrangeArrayWithNewStartIndex } from '@/lib/common.ts';
import { useUserStore } from '@/stores/user.ts';
import { useI18n } from '@/locales/helpers.ts'; import { useI18n } from '@/locales/helpers.ts';
import { arrangeArrayWithNewStartIndex } from '@/lib/common'; import { useUserStore } from '@/stores/user.ts';
export interface FiscalYearStartSelectionBaseProps { export interface CommonFiscalYearStartSelectionProps {
modelValue?: number; modelValue?: number;
disabled?: boolean;
readonly?: boolean;
label?: string;
} }
export interface FiscalYearStartSelectionBaseEmits { export interface CommonFiscalYearStartSelectionEmits {
(e: 'update:modelValue', value: number): void; (e: 'update:modelValue', value: number): void;
} }
export function useFiscalYearStartSelectionBase(props: FiscalYearStartSelectionBaseProps, emit: FiscalYearStartSelectionBaseEmits) { function getFiscalYearStartFromProps(props: CommonFiscalYearStartSelectionProps): number {
const { getAllMinWeekdayNames, formatMonthDayToLongDay, getCurrentFiscalYearStartFormatted } = useI18n(); if (!props.modelValue) {
return FiscalYearStart.Default.value;
}
const dayNames = computed<string[]>(() => arrangeArrayWithNewStartIndex(getAllMinWeekdayNames(), firstDayOfWeek.value)); const fiscalYearStart = FiscalYearStart.valueOf(props.modelValue);
const displayName = computed<string>(() => { if (!fiscalYearStart) {
const fy = FiscalYearStart.fromNumber(selectedFiscalYearStart.value); return FiscalYearStart.Default.value;
}
if ( fy ) { return fiscalYearStart.value;
return formatMonthDayToLongDay(fy.toMonthDashDayString()) }
}
return formatMonthDayToLongDay(FiscalYearStart.strictFromNumber(userStore.currentUserFiscalYearStart).toMonthDashDayString()); export function useFiscalYearStartSelectionBase(props: CommonFiscalYearStartSelectionProps) {
const {
}); getAllMinWeekdayNames,
formatMonthDayToLongDay
const disabledDates = (date: Date) => { } = useI18n();
// Disable February 29 (leap day)
return date.getMonth() === 1 && date.getDate() === 29;
};
const firstDayOfWeek = computed<number>(() => userStore.currentUserFirstDayOfWeek);
const selectedFiscalYearStart = computed<number>(() => {
return props.modelValue !== undefined ? props.modelValue : userStore.currentUserFiscalYearStart;
});
const userStore = useUserStore(); const userStore = useUserStore();
function selectedDisplayName(dateString: string): string { const disabledDates = (date: Date) => {
const fy = FiscalYearStart.fromMonthDashDayString(dateString); // Disable February 29 (leap day)
if ( fy ) { return date.getMonth() === 1 && date.getDate() === 29;
return formatMonthDayToLongDay(fy.toMonthDashDayString()); };
const selectedFiscalYearStart = ref<number>(getFiscalYearStartFromProps(props));
const selectedFiscalYearStartValue = computed<string>({
get: () => {
const fiscalYearStart = FiscalYearStart.valueOf(selectedFiscalYearStart.value);
if (fiscalYearStart) {
return fiscalYearStart.toMonthDashDayString();
} else {
return FiscalYearStart.Default.toMonthDashDayString();
}
},
set: (value: string) => {
const fiscalYearStart = FiscalYearStart.parse(value);
if (fiscalYearStart) {
selectedFiscalYearStart.value = fiscalYearStart.value;
} else {
selectedFiscalYearStart.value = FiscalYearStart.Default.value;
}
} }
return displayName.value; });
}
function getModelValueToDateString(): string { const displayFiscalYearStartDate = computed<string>(() => {
const input = selectedFiscalYearStart.value; let fiscalYearStart = FiscalYearStart.valueOf(selectedFiscalYearStart.value);
const fy = FiscalYearStart.fromNumber(input);
if ( fy ) { if (!fiscalYearStart) {
return fy.toMonthDashDayString(); fiscalYearStart = FiscalYearStart.Default;
} }
return getCurrentFiscalYearStartFormatted(); return formatMonthDayToLongDay(fiscalYearStart.toMonthDashDayString());
} });
const firstDayOfWeek = computed<number>(() => userStore.currentUserFirstDayOfWeek);
const dayNames = computed<string[]>(() => arrangeArrayWithNewStartIndex(getAllMinWeekdayNames(), firstDayOfWeek.value));
function getDateStringToModelValue(input: string): number {
const fyString = FiscalYearStart.fromMonthDashDayString(input);
if (fyString) {
return fyString.value;
}
return userStore.currentUserFiscalYearStart;
}
return { return {
// functions // constants
getDateStringToModelValue,
getModelValueToDateString,
selectedDisplayName,
// computed states
dayNames,
displayName,
disabledDates, disabledDates,
firstDayOfWeek, // states,
selectedFiscalYearStart, selectedFiscalYearStart,
} // computed states
selectedFiscalYearStartValue,
displayFiscalYearStartDate,
firstDayOfWeek,
dayNames
};
} }

View File

@@ -3,18 +3,16 @@
persistent-placeholder persistent-placeholder
:readonly="readonly" :readonly="readonly"
:disabled="disabled" :disabled="disabled"
:clearable="modelValue ? clearable : false"
:label="label" :label="label"
:menu-props="{ contentClass: 'fiscal-year-start-select-menu' }" :menu-props="{ contentClass: 'fiscal-year-start-select-menu' }"
v-model="selectedDate" v-model="selectedFiscalYearStartValue"
> >
<template #selection> <template #selection>
<span class="text-truncate cursor-pointer">{{ displayName }}</span> <span class="text-truncate cursor-pointer">{{ displayFiscalYearStartDate }}</span>
</template> </template>
<template #no-data> <template #no-data>
<vue-date-picker inline vertical auto-apply hide-offset-dates disable-year-select <vue-date-picker inline auto-apply hide-offset-dates disable-year-select
ref="datepicker"
month-name-format="long" month-name-format="long"
model-type="MM-dd" model-type="MM-dd"
:clearable="false" :clearable="false"
@@ -23,8 +21,7 @@
:week-start="firstDayOfWeek" :week-start="firstDayOfWeek"
:day-names="dayNames" :day-names="dayNames"
:disabled-dates="disabledDates" :disabled-dates="disabledDates"
:start-date="selectedDate" v-model="selectedFiscalYearStartValue"
v-model="selectedDate"
> >
<template #month="{ text }"> <template #month="{ text }">
{{ getMonthShortName(text) }} {{ getMonthShortName(text) }}
@@ -38,51 +35,46 @@
</template> </template>
<script setup lang="ts"> <script setup lang="ts">
import { computed } from 'vue'; import { computed, watch } from 'vue';
import { useTheme } from 'vuetify'; import { useTheme } from 'vuetify';
import { useUserStore } from '@/stores/user.ts';
import { ThemeType } from '@/core/theme.ts';
import { arrangeArrayWithNewStartIndex } from '@/lib/common.ts';
import {
type FiscalYearStartSelectionBaseProps,
type FiscalYearStartSelectionBaseEmits,
useFiscalYearStartSelectionBase
} from '@/components/base/FiscalYearStartSelectionBase.ts';
import { useI18n } from '@/locales/helpers.ts'; import { useI18n } from '@/locales/helpers.ts';
interface FiscalYearStartSelectProps extends FiscalYearStartSelectionBaseProps { import {
disabled?: boolean; type CommonFiscalYearStartSelectionProps,
readonly?: boolean; type CommonFiscalYearStartSelectionEmits,
clearable?: boolean; useFiscalYearStartSelectionBase
label?: string; } from '@/components/base/FiscalYearStartSelectionBase.ts';
}
const props = defineProps<FiscalYearStartSelectProps>(); import { ThemeType } from '@/core/theme.ts';
const emit = defineEmits<FiscalYearStartSelectionBaseEmits>();
const props = defineProps<CommonFiscalYearStartSelectionProps>();
const emit = defineEmits<CommonFiscalYearStartSelectionEmits>();
const { getMonthShortName } = useI18n(); const { getMonthShortName } = useI18n();
const theme = useTheme(); const theme = useTheme();
const isDarkMode = computed<boolean>(() => theme.global.name.value === ThemeType.Dark); const isDarkMode = computed<boolean>(() => theme.global.name.value === ThemeType.Dark);
// Get all base functionality
const { const {
dayNames,
displayName,
disabledDates, disabledDates,
selectedFiscalYearStart,
selectedFiscalYearStartValue,
displayFiscalYearStartDate,
firstDayOfWeek, firstDayOfWeek,
getModelValueToDateString, dayNames
getDateStringToModelValue, } = useFiscalYearStartSelectionBase(props);
} = useFiscalYearStartSelectionBase(props, emit);
const selectedDate = computed<string>({ watch(() => props.modelValue, (newValue) => {
get: () => { if (newValue) {
return getModelValueToDateString(); selectedFiscalYearStart.value = newValue;
},
set: (value: string) => {
emit('update:modelValue', getDateStringToModelValue(value));
} }
}); });
watch(selectedFiscalYearStart, (newValue) => {
emit('update:modelValue', newValue);
});
</script> </script>
<style> <style>

View File

@@ -4,7 +4,7 @@
<f7-toolbar> <f7-toolbar>
<div class="swipe-handler"></div> <div class="swipe-handler"></div>
<div class="left"> <div class="left">
<f7-link :text="tt('Clear')" @click="clear"></f7-link> <f7-link :text="tt('Reset')" @click="reset"></f7-link>
</div> </div>
<div class="right"> <div class="right">
<f7-link :text="tt('Done')" @click="confirm"></f7-link> <f7-link :text="tt('Done')" @click="confirm"></f7-link>
@@ -17,14 +17,13 @@
model-type="MM-dd" model-type="MM-dd"
six-weeks="center" six-weeks="center"
class="justify-content-center" class="justify-content-center"
:clearable="false"
:enable-time-picker="false" :enable-time-picker="false"
:clearable="true"
:dark="isDarkMode" :dark="isDarkMode"
:week-start="firstDayOfWeek" :week-start="firstDayOfWeek"
:day-names="dayNames" :day-names="dayNames"
:disabled-dates="disabledDates" :disabled-dates="disabledDates"
:start-date="selectedDate" v-model="selectedFiscalYearStartValue">
v-model="selectedDate">
<template #month="{ text }"> <template #month="{ text }">
{{ getMonthShortName(text) }} {{ getMonthShortName(text) }}
</template> </template>
@@ -38,71 +37,71 @@
</template> </template>
<script setup lang="ts"> <script setup lang="ts">
import { computed, ref } from 'vue'; import { computed } from 'vue';
import { useI18n } from '@/locales/helpers.ts'; import { useI18n } from '@/locales/helpers.ts';
import { useEnvironmentsStore } from '@/stores/environment.ts'; import { useEnvironmentsStore } from '@/stores/environment.ts';
import { useUserStore } from '@/stores/user.ts';
import { import {
type FiscalYearStartSelectionBaseProps, type CommonFiscalYearStartSelectionProps,
type FiscalYearStartSelectionBaseEmits, type CommonFiscalYearStartSelectionEmits,
useFiscalYearStartSelectionBase useFiscalYearStartSelectionBase
} from '@/components/base/FiscalYearStartSelectionBase.ts'; } from '@/components/base/FiscalYearStartSelectionBase.ts';
interface FiscalYearStartSelectionSheetProps extends FiscalYearStartSelectionBaseProps { import { FiscalYearStart } from '@/core/fiscalyear.ts';
interface MobileFiscalYearStartSelectionSheetProps extends CommonFiscalYearStartSelectionProps {
clearable?: boolean; clearable?: boolean;
disabled?: boolean;
label?: string;
readonly?: boolean;
show: boolean; show: boolean;
title?: string; title?: string;
} }
const props = defineProps<FiscalYearStartSelectionSheetProps>(); interface MobileFiscalYearStartSelectionSheetEmits extends CommonFiscalYearStartSelectionEmits {
interface FiscalYearStartSelectionSheetEmits extends FiscalYearStartSelectionBaseEmits {
(e: 'update:show', value: boolean): void; (e: 'update:show', value: boolean): void;
(e: 'update:title', value: string): void;
} }
const emit = defineEmits<FiscalYearStartSelectionSheetEmits>(); const props = defineProps<MobileFiscalYearStartSelectionSheetProps>();
const emit = defineEmits<MobileFiscalYearStartSelectionSheetEmits>();
const { tt, getMonthShortName, getCurrentFiscalYearStartFormatted } = useI18n(); const { tt, getMonthShortName } = useI18n();
const environmentsStore = useEnvironmentsStore(); const environmentsStore = useEnvironmentsStore();
const userStore = useUserStore();
const { const {
dayNames,
disabledDates, disabledDates,
selectedFiscalYearStart,
selectedFiscalYearStartValue,
firstDayOfWeek, firstDayOfWeek,
getDateStringToModelValue, dayNames
getModelValueToDateString, } = useFiscalYearStartSelectionBase(props);
selectedDisplayName,
} = useFiscalYearStartSelectionBase(props, emit);
const isDarkMode = computed<boolean>(() => environmentsStore.framework7DarkMode || false); const isDarkMode = computed<boolean>(() => environmentsStore.framework7DarkMode || false);
const selectedDate = ref<string>(getModelValueToDateString()); function confirm(): void {
emit('update:modelValue', selectedFiscalYearStart.value);
emit('update:show', false);
}
function reset(): void {
selectedFiscalYearStart.value = userStore.currentUserFiscalYearStart;
}
function onSheetOpen(): void { function onSheetOpen(): void {
selectedDate.value = getModelValueToDateString(); if (props.modelValue) {
const fiscalYearStart = FiscalYearStart.valueOf(props.modelValue);
if (fiscalYearStart) {
selectedFiscalYearStart.value = fiscalYearStart.value;
}
}
} }
function onSheetClosed(): void { function onSheetClosed(): void {
emit('update:show', false); emit('update:show', false);
} }
function clear(): void {
selectedDate.value = getCurrentFiscalYearStartFormatted();
}
function confirm(): void {
emit('update:modelValue', getDateStringToModelValue(selectedDate.value));
emit('update:show', false);
emit('update:title', selectedDisplayName(selectedDate.value));
}
</script> </script>
<style> <style>

View File

@@ -1,197 +1,87 @@
import type { TypeAndDisplayName } from '@/core/base.ts'; import type { UnixTimeRange } from './datetime.ts';
import type { UnixTimeRange } from './datetime';
export class FiscalYearStart { export class FiscalYearStart {
public static readonly Default = new FiscalYearStart(1, 1); public static readonly JanuaryFirstDay = new FiscalYearStart(1, 1);
public static readonly Default = FiscalYearStart.JanuaryFirstDay;
private static readonly MONTH_MAX_DAYS: number[] = [
31, // January
28, // February (Disallow fiscal year start on leap day)
31, // March
30, // April
31, // May
30, // June
31, // July
31, // August
30, // September
31, // October
30, // November
31 // December
];
public readonly day: number;
public readonly month: number; public readonly month: number;
public readonly day: number;
public readonly value: number; public readonly value: number;
private constructor(month: number, day: number) { private constructor(month: number, day: number) {
const [validMonth, validDay] = validateMonthDay(month, day); this.month = month;
this.day = validDay; this.day = day;
this.month = validMonth; this.value = (month << 8) | day;
this.value = (validMonth << 8) | validDay;
} }
public static of(month: number, day: number): FiscalYearStart { public static of(month: number, day: number): FiscalYearStart | undefined {
if (!FiscalYearStart.isValidMonthDay(month, day)) {
return undefined;
}
return new FiscalYearStart(month, day); return new FiscalYearStart(month, day);
} }
public static valueOf(value: number): FiscalYearStart {
return FiscalYearStart.strictFromNumber(value);
}
public static valuesFromNumber(value: number): number[] {
return FiscalYearStart.strictFromNumber(value).values();
}
public values(): number[] {
return [
this.month,
this.day
];
}
public static parse(valueString: string): FiscalYearStart | undefined {
return FiscalYearStart.strictFromMonthDashDayString(valueString);
}
public static isValidType(value: number): boolean {
if (value < 0x0101 || value > 0x0C1F) {
return false;
}
const month = (value >> 8) & 0xFF;
const day = value & 0xFF;
try {
validateMonthDay(month, day);
return true;
} catch (error) {
return false;
}
}
public isValid(): boolean {
try {
FiscalYearStart.validateMonthDay(this.month, this.day);
return true;
} catch (error) {
return false;
}
}
public isDefault(): boolean {
return this.month === 1 && this.day === 1;
}
public static validateMonthDay(month: number, day: number): [number, number] {
return validateMonthDay(month, day);
}
public static strictFromMonthDayValues(month: number, day: number): FiscalYearStart {
return FiscalYearStart.of(month, day);
}
/** /**
* Create a FiscalYearStart from a uint16 value (two bytes - month high, day low) * Create a FiscalYearStart from a uint16 value (two bytes - month high, day low)
* @param value uint16 value (month in high byte, day in low byte) * @param value uint16 value (month in high byte, day in low byte)
* @returns FiscalYearStart instance * @returns FiscalYearStart instance or undefined if the value is out of range
*/ */
public static strictFromNumber(value: number): FiscalYearStart { public static valueOf(value: number): FiscalYearStart | undefined {
if (value < 0 || value > 0xFFFF) { if (value < 0x0101 || value > 0x0C1F) {
throw new Error('Invalid uint16 value'); return undefined;
} }
const month = (value >> 8) & 0xFF; // high byte const month = (value >> 8) & 0xFF; // high byte
const day = value & 0xFF; // low byte const day = value & 0xFF; // low byte
try { return FiscalYearStart.of(month, day);
const [validMonth, validDay] = validateMonthDay(month, day);
return FiscalYearStart.of(validMonth, validDay);
} catch (error) {
throw new Error('Invalid uint16 value');
}
} }
/** /**
* Create a FiscalYearStart from a month/day string * Create a FiscalYearStart from a month/day string
* @param input MM-dd string (e.g. "04-01" = 1 April) * @param monthDay MM-dd string (e.g. "04-01" = 1 April)
* @returns FiscalYearStart instance * @returns FiscalYearStart instance or undefined if the monthDay is invalid
*/ */
public static strictFromMonthDashDayString(input: string): FiscalYearStart { public static parse(monthDay: string): FiscalYearStart | undefined {
if (!input || !input.includes('-')) { if (!monthDay || !monthDay.includes('-')) {
throw new Error('Invalid input string'); return undefined;
} }
const parts = input.split('-'); const parts = monthDay.split('-');
if (parts.length !== 2) { if (parts.length !== 2) {
throw new Error('Invalid input string'); return undefined;
} }
const month = parseInt(parts[0], 10); const month = parseInt(parts[0], 10);
const day = parseInt(parts[1], 10); const day = parseInt(parts[1], 10);
if (isNaN(month) || isNaN(day)) { return FiscalYearStart.of(month, day);
throw new Error('Invalid input string');
}
try {
const [validMonth, validDay] = validateMonthDay(month, day);
return FiscalYearStart.of(validMonth, validDay);
} catch (error) {
throw new Error('Invalid input string');
}
}
public static fromMonthDashDayString(input: string): FiscalYearStart | null {
try {
return FiscalYearStart.strictFromMonthDashDayString(input);
} catch (error) {
return null;
}
}
public static fromNumber(value: number): FiscalYearStart | null {
try {
return FiscalYearStart.strictFromNumber(value);
} catch (error) {
return null;
}
}
public static fromMonthDayValues(month: number, day: number): FiscalYearStart | null {
try {
return FiscalYearStart.strictFromMonthDayValues(month, day);
} catch (error) {
return null;
}
} }
public toMonthDashDayString(): string { public toMonthDashDayString(): string {
return `${this.month.toString().padStart(2, '0')}-${this.day.toString().padStart(2, '0')}`; return `${this.month.toString().padStart(2, '0')}-${this.day.toString().padStart(2, '0')}`;
} }
public toMonthDayValues(): [string, string] { private static isValidMonthDay(month: number, day: number): boolean {
return [ return 1 <= month && month <= 12 && 1 <= day && day <= FiscalYearStart.MONTH_MAX_DAYS[month - 1];
`${this.month.toString().padStart(2, '0')}`,
`${this.day.toString().padStart(2, '0')}`
]
} }
public toString(): string {
return this.toMonthDashDayString();
}
}
function validateMonthDay(month: number, day: number): [number, number] {
if (month < 1 || month > 12 || day < 1) {
throw new Error('Invalid month or day');
}
let maxDays = 31;
switch (month) {
// January, March, May, July, August, October, December
case 1: case 3: case 5: case 7: case 8: case 10: case 12:
maxDays = 31;
break;
// April, June, September, November
case 4: case 6: case 9: case 11:
maxDays = 30;
break;
// February
case 2:
maxDays = 28; // Disallow fiscal year start on leap day
break;
}
if (day > maxDays) {
throw new Error('Invalid day for given month');
}
return [month, day];
} }
export class FiscalYearUnixTime implements UnixTimeRange { export class FiscalYearUnixTime implements UnixTimeRange {
@@ -212,7 +102,7 @@ export class FiscalYearUnixTime implements UnixTimeRange {
export const LANGUAGE_DEFAULT_FISCAL_YEAR_FORMAT_VALUE: number = 0; export const LANGUAGE_DEFAULT_FISCAL_YEAR_FORMAT_VALUE: number = 0;
export class FiscalYearFormat implements TypeAndDisplayName { export class FiscalYearFormat {
private static readonly allInstances: FiscalYearFormat[] = []; private static readonly allInstances: FiscalYearFormat[] = [];
private static readonly allInstancesByType: Record<number, FiscalYearFormat> = {}; private static readonly allInstancesByType: Record<number, FiscalYearFormat> = {};
private static readonly allInstancesByTypeName: Record<string, FiscalYearFormat> = {}; private static readonly allInstancesByTypeName: Record<string, FiscalYearFormat> = {};
@@ -226,19 +116,15 @@ export class FiscalYearFormat implements TypeAndDisplayName {
public static readonly Default = FiscalYearFormat.EndYYYY; public static readonly Default = FiscalYearFormat.EndYYYY;
public readonly type: number; public readonly type: number;
public readonly displayName: string; public readonly typeName: string;
private constructor(type: number, displayName: string) { private constructor(type: number, typeName: string) {
this.type = type; this.type = type;
this.displayName = displayName; this.typeName = typeName;
FiscalYearFormat.allInstances.push(this); FiscalYearFormat.allInstances.push(this);
FiscalYearFormat.allInstancesByType[type] = this; FiscalYearFormat.allInstancesByType[type] = this;
FiscalYearFormat.allInstancesByTypeName[displayName] = this; FiscalYearFormat.allInstancesByTypeName[typeName] = this;
}
public static all(): Record<string, FiscalYearFormat> {
return FiscalYearFormat.allInstancesByTypeName;
} }
public static values(): FiscalYearFormat[] { public static values(): FiscalYearFormat[] {
@@ -249,7 +135,7 @@ export class FiscalYearFormat implements TypeAndDisplayName {
return FiscalYearFormat.allInstancesByType[type]; return FiscalYearFormat.allInstancesByType[type];
} }
public static parse(displayName: string): FiscalYearFormat | undefined { public static parse(typeName: string): FiscalYearFormat | undefined {
return FiscalYearFormat.allInstancesByTypeName[displayName]; return FiscalYearFormat.allInstancesByTypeName[typeName];
} }
} }

View File

@@ -1,30 +1,29 @@
// Unit tests for fiscal year functions // Unit tests for fiscal year functions
import moment from 'moment-timezone';
import { describe, expect, test, beforeAll } from '@jest/globals';
import fs from 'fs'; import fs from 'fs';
import path from 'path'; import path from 'path';
import { describe, expect, test, beforeAll } from '@jest/globals';
import moment from 'moment-timezone';
// Import all the fiscal year functions from the lib // Import all the fiscal year functions from the lib
import { FiscalYearStart, FiscalYearUnixTime } from '@/core/fiscalyear.ts';
import { import {
getFiscalYearFromUnixTime, getFiscalYearFromUnixTime,
getFiscalYearStartUnixTime, getFiscalYearStartUnixTime,
getFiscalYearEndUnixTime, getFiscalYearEndUnixTime,
getFiscalYearTimeRangeFromUnixTime, getFiscalYearTimeRangeFromUnixTime,
getAllFiscalYearsStartAndEndUnixTimes, getAllFiscalYearsStartAndEndUnixTimes,
getFiscalYearTimeRangeFromYear getFiscalYearTimeRangeFromYear,
formatUnixTime
} from '@/lib/datetime.ts'; } from '@/lib/datetime.ts';
import { formatUnixTime } from '@/lib/datetime.ts';
import { FiscalYearStart, FiscalYearUnixTime } from '@/core/fiscalyear.ts';
// Set test environment timezone to UTC, since the test data constants are in UTC // Set test environment timezone to UTC, since the test data constants are in UTC
beforeAll(() => { beforeAll(() => {
moment.tz.setDefault('UTC'); moment.tz.setDefault('UTC');
}); });
// UTILITIES // UTILITIES
function importTestData(datasetName: string): unknown[] {
function importTestData(datasetName: string): any[] {
const data = JSON.parse( const data = JSON.parse(
fs.readFileSync(path.join(__dirname, 'fiscal_year.data.json'), 'utf8') fs.readFileSync(path.join(__dirname, 'fiscal_year.data.json'), 'utf8')
); );
@@ -74,13 +73,13 @@ const TEST_FISCAL_YEAR_START_PRESETS: Record<string, FiscalYearStartConfig> = {
// VALIDATE FISCAL YEAR START PRESETS // VALIDATE FISCAL YEAR START PRESETS
describe('validateFiscalYearStart', () => { describe('validateFiscalYearStart', () => {
Object.values(TEST_FISCAL_YEAR_START_PRESETS).forEach((testFiscalYearStart) => { Object.values(TEST_FISCAL_YEAR_START_PRESETS).forEach((testFiscalYearStart) => {
test(`should return true if fiscal year start value (uint16) is valid: id: ${testFiscalYearStart.id}; value: 0x${testFiscalYearStart.value.toString(16)}`, () => { test(`should return fiscal year start object if fiscal year start value (uint16) is valid: id: ${testFiscalYearStart.id}; value: 0x${testFiscalYearStart.value.toString(16)}`, () => {
expect(FiscalYearStart.isValidType(testFiscalYearStart.value)).toBe(true); expect(FiscalYearStart.valueOf(testFiscalYearStart.value)).toBeDefined();
}); });
test(`returns same month-date string for valid fiscal year start value: id: ${testFiscalYearStart.id}; value: 0x${testFiscalYearStart.value.toString(16)}`, () => { test(`returns same month-date string for valid fiscal year start value: id: ${testFiscalYearStart.id}; value: 0x${testFiscalYearStart.value.toString(16)}`, () => {
const fiscalYearStart = FiscalYearStart.strictFromNumber(testFiscalYearStart.value); const fiscalYearStart = FiscalYearStart.valueOf(testFiscalYearStart.value);
expect(fiscalYearStart.toString()).toStrictEqual(testFiscalYearStart.monthDateString); expect(fiscalYearStart?.toMonthDashDayString()).toStrictEqual(testFiscalYearStart.monthDateString);
}); });
}); });
}); });
@@ -103,24 +102,20 @@ const TestCase_invalidFiscalYearValues = [
describe('validateFiscalYearStartInvalidValues', () => { describe('validateFiscalYearStartInvalidValues', () => {
TestCase_invalidFiscalYearValues.forEach((testCase) => { TestCase_invalidFiscalYearValues.forEach((testCase) => {
test(`should return false if fiscal year start value (uint16) is invalid: value: 0x${testCase.toString(16)}`, () => { test(`should return undefined if fiscal year start value (uint16) is invalid: value: 0x${testCase.toString(16)}`, () => {
expect(FiscalYearStart.isValidType(testCase)).toBe(false); expect(FiscalYearStart.valueOf(testCase)).not.toBeDefined();
}); });
}); });
}); });
// VALIDATE LEAP DAY FEBRUARY 29 IS NOT VALID // VALIDATE LEAP DAY FEBRUARY 29 IS NOT VALID
describe('validateFiscalYearStartLeapDay', () => { describe('validateFiscalYearStartLeapDay', () => {
test(`should return false if fiscal year start value (uint16) for February 29 is invalid: value: 0x0229}`, () => { test(`should return undefined if fiscal year start value (uint16) for February 29 is invalid: value: 0x0229}`, () => {
expect(FiscalYearStart.isValidType(0x0229)).toBe(false); expect(FiscalYearStart.valueOf(0x021D)).not.toBeDefined();
}); });
test(`should return error if fiscal year month-day string "02-29" is used to create fiscal year start object`, () => { test(`should return undefined if fiscal year month-day string "02-29" is used to create fiscal year start object`, () => {
expect(() => FiscalYearStart.strictFromMonthDashDayString('02-29')).toThrow(); expect(FiscalYearStart.parse('02-29')).not.toBeDefined();
});
test(`should return error if integers "02" and "29" are used to create fiscal year start object`, () => {
expect(() => FiscalYearStart.validateMonthDay(2, 29)).toThrow();
}); });
}); });
@@ -133,8 +128,8 @@ type TestCase_getFiscalYearFromUnixTime = {
}; };
}; };
let TEST_CASES_GET_FISCAL_YEAR_FROM_UNIX_TIME: TestCase_getFiscalYearFromUnixTime[]; const TEST_CASES_GET_FISCAL_YEAR_FROM_UNIX_TIME: TestCase_getFiscalYearFromUnixTime[] =
TEST_CASES_GET_FISCAL_YEAR_FROM_UNIX_TIME = importTestData('test_cases_getFiscalYearFromUnixTime') as TestCase_getFiscalYearFromUnixTime[]; importTestData('test_cases_getFiscalYearFromUnixTime') as TestCase_getFiscalYearFromUnixTime[];
describe('getFiscalYearFromUnixTime', () => { describe('getFiscalYearFromUnixTime', () => {
Object.values(TEST_FISCAL_YEAR_START_PRESETS).forEach((testFiscalYearStart) => { Object.values(TEST_FISCAL_YEAR_START_PRESETS).forEach((testFiscalYearStart) => {
@@ -161,8 +156,8 @@ type TestCase_getFiscalYearStartUnixTime = {
}; };
} }
let TEST_CASES_GET_FISCAL_YEAR_START_UNIX_TIME: TestCase_getFiscalYearStartUnixTime[]; const TEST_CASES_GET_FISCAL_YEAR_START_UNIX_TIME: TestCase_getFiscalYearStartUnixTime[] =
TEST_CASES_GET_FISCAL_YEAR_START_UNIX_TIME = importTestData('test_cases_getFiscalYearStartUnixTime') as TestCase_getFiscalYearStartUnixTime[]; importTestData('test_cases_getFiscalYearStartUnixTime') as TestCase_getFiscalYearStartUnixTime[];
describe('getFiscalYearStartUnixTime', () => { describe('getFiscalYearStartUnixTime', () => {
Object.values(TEST_FISCAL_YEAR_START_PRESETS).forEach((testFiscalYearStart) => { Object.values(TEST_FISCAL_YEAR_START_PRESETS).forEach((testFiscalYearStart) => {
@@ -172,7 +167,7 @@ describe('getFiscalYearStartUnixTime', () => {
const startUnixTime = getFiscalYearStartUnixTime(testCaseUnixTime, testFiscalYearStart.value); const startUnixTime = getFiscalYearStartUnixTime(testCaseUnixTime, testFiscalYearStart.value);
const expected = testCase.expected[testFiscalYearStart.id]; const expected = testCase.expected[testFiscalYearStart.id];
const unixTimeISO = formatUnixTimeISO(startUnixTime); const unixTimeISO = formatUnixTimeISO(startUnixTime);
expect({ unixTime: startUnixTime, ISO: unixTimeISO }).toStrictEqual({ unixTime: expected.unixTime, ISO: expected.unixTimeISO }); expect({ unixTime: startUnixTime, ISO: unixTimeISO }).toStrictEqual({ unixTime: expected.unixTime, ISO: expected.unixTimeISO });
}); });
}); });
@@ -191,8 +186,8 @@ type TestCase_getFiscalYearEndUnixTime = {
}; };
} }
let TEST_CASES_GET_FISCAL_YEAR_END_UNIX_TIME: TestCase_getFiscalYearEndUnixTime[]; const TEST_CASES_GET_FISCAL_YEAR_END_UNIX_TIME: TestCase_getFiscalYearEndUnixTime[] =
TEST_CASES_GET_FISCAL_YEAR_END_UNIX_TIME = importTestData('test_cases_getFiscalYearEndUnixTime') as TestCase_getFiscalYearEndUnixTime[]; importTestData('test_cases_getFiscalYearEndUnixTime') as TestCase_getFiscalYearEndUnixTime[];
describe('getFiscalYearEndUnixTime', () => { describe('getFiscalYearEndUnixTime', () => {
Object.values(TEST_FISCAL_YEAR_START_PRESETS).forEach((testFiscalYearStart) => { Object.values(TEST_FISCAL_YEAR_START_PRESETS).forEach((testFiscalYearStart) => {
@@ -202,9 +197,9 @@ describe('getFiscalYearEndUnixTime', () => {
const endUnixTime = getFiscalYearEndUnixTime(testCaseUnixTime, testFiscalYearStart.value); const endUnixTime = getFiscalYearEndUnixTime(testCaseUnixTime, testFiscalYearStart.value);
const expected = testCase.expected[testFiscalYearStart.id]; const expected = testCase.expected[testFiscalYearStart.id];
const unixTimeISO = formatUnixTimeISO(endUnixTime); const unixTimeISO = formatUnixTimeISO(endUnixTime);
expect({ unixTime: endUnixTime, ISO: unixTimeISO }).toStrictEqual({ unixTime: expected.unixTime, ISO: expected.unixTimeISO }); expect({ unixTime: endUnixTime, ISO: unixTimeISO }).toStrictEqual({ unixTime: expected.unixTime, ISO: expected.unixTimeISO });
}); });
}); });
}); });
@@ -218,8 +213,8 @@ type TestCase_getFiscalYearTimeRangeFromUnixTime = {
} }
} }
let TEST_CASES_GET_FISCAL_YEAR_UNIX_TIME_RANGE: TestCase_getFiscalYearTimeRangeFromUnixTime[]; const TEST_CASES_GET_FISCAL_YEAR_UNIX_TIME_RANGE: TestCase_getFiscalYearTimeRangeFromUnixTime[] =
TEST_CASES_GET_FISCAL_YEAR_UNIX_TIME_RANGE = importTestData('test_cases_getFiscalYearTimeRangeFromUnixTime') as TestCase_getFiscalYearTimeRangeFromUnixTime[]; importTestData('test_cases_getFiscalYearTimeRangeFromUnixTime') as TestCase_getFiscalYearTimeRangeFromUnixTime[];
describe('getFiscalYearTimeRangeFromUnixTime', () => { describe('getFiscalYearTimeRangeFromUnixTime', () => {
Object.values(TEST_FISCAL_YEAR_START_PRESETS).forEach((testFiscalYearStart) => { Object.values(TEST_FISCAL_YEAR_START_PRESETS).forEach((testFiscalYearStart) => {
@@ -242,29 +237,31 @@ type TestCase_getAllFiscalYearsStartAndEndUnixTimes = {
expected: FiscalYearUnixTime[] expected: FiscalYearUnixTime[]
} }
let TEST_CASES_GET_ALL_FISCAL_YEARS_START_AND_END_UNIX_TIMES: TestCase_getAllFiscalYearsStartAndEndUnixTimes[]; const TEST_CASES_GET_ALL_FISCAL_YEARS_START_AND_END_UNIX_TIMES: TestCase_getAllFiscalYearsStartAndEndUnixTimes[] =
TEST_CASES_GET_ALL_FISCAL_YEARS_START_AND_END_UNIX_TIMES = importTestData('test_cases_getAllFiscalYearsStartAndEndUnixTimes') as TestCase_getAllFiscalYearsStartAndEndUnixTimes[]; importTestData('test_cases_getAllFiscalYearsStartAndEndUnixTimes') as TestCase_getAllFiscalYearsStartAndEndUnixTimes[];
describe('getAllFiscalYearsStartAndEndUnixTimes', () => { describe('getAllFiscalYearsStartAndEndUnixTimes', () => {
TEST_CASES_GET_ALL_FISCAL_YEARS_START_AND_END_UNIX_TIMES.forEach((testCase) => { TEST_CASES_GET_ALL_FISCAL_YEARS_START_AND_END_UNIX_TIMES.forEach((testCase) => {
const fiscalYearStart = FiscalYearStart.strictFromMonthDashDayString(testCase.fiscalYearStart); const fiscalYearStart = FiscalYearStart.parse(testCase.fiscalYearStart);
test(`returns correct fiscal year start and end unix times for ${getTestTitleFormatString(testCase.fiscalYearStartId, `${testCase.startYearMonth} to ${testCase.endYearMonth}`)}`, () => { test(`returns correct fiscal year start and end unix times for ${getTestTitleFormatString(testCase.fiscalYearStartId, `${testCase.startYearMonth} to ${testCase.endYearMonth}`)}`, () => {
const fiscalYearStartAndEndUnixTimes = getAllFiscalYearsStartAndEndUnixTimes(testCase.startYearMonth, testCase.endYearMonth, fiscalYearStart.value); expect(fiscalYearStart).toBeDefined();
const fiscalYearStartAndEndUnixTimes = getAllFiscalYearsStartAndEndUnixTimes(testCase.startYearMonth, testCase.endYearMonth, fiscalYearStart?.value || 0);
// Convert results to include ISO strings for better test output // Convert results to include ISO strings for better test output
const resultWithISO = fiscalYearStartAndEndUnixTimes.map(data => ({ const resultWithISO = fiscalYearStartAndEndUnixTimes.map(data => ({
...data, ...data,
minUnixTimeISO: formatUnixTimeISO(data.minUnixTime), minUnixTimeISO: formatUnixTimeISO(data.minUnixTime),
maxUnixTimeISO: formatUnixTimeISO(data.maxUnixTime) maxUnixTimeISO: formatUnixTimeISO(data.maxUnixTime)
})); }));
// Convert expected to include ISO strings // Convert expected to include ISO strings
const expectedWithISO = testCase.expected.map(data => ({ const expectedWithISO = testCase.expected.map(data => ({
...data, ...data,
minUnixTimeISO: formatUnixTimeISO(data.minUnixTime), minUnixTimeISO: formatUnixTimeISO(data.minUnixTime),
maxUnixTimeISO: formatUnixTimeISO(data.maxUnixTime) maxUnixTimeISO: formatUnixTimeISO(data.maxUnixTime)
})); }));
expect(resultWithISO).toStrictEqual(expectedWithISO); expect(resultWithISO).toStrictEqual(expectedWithISO);
}); });
}); });
@@ -277,15 +274,16 @@ type TestCase_getFiscalYearTimeRangeFromYear = {
expected: FiscalYearUnixTime; expected: FiscalYearUnixTime;
} }
let TEST_CASES_GET_FISCAL_YEAR_RANGE_FROM_YEAR: TestCase_getFiscalYearTimeRangeFromYear[]; const TEST_CASES_GET_FISCAL_YEAR_RANGE_FROM_YEAR: TestCase_getFiscalYearTimeRangeFromYear[] =
TEST_CASES_GET_FISCAL_YEAR_RANGE_FROM_YEAR = importTestData('test_cases_getFiscalYearTimeRangeFromYear') as TestCase_getFiscalYearTimeRangeFromYear[]; importTestData('test_cases_getFiscalYearTimeRangeFromYear') as TestCase_getFiscalYearTimeRangeFromYear[];
describe('getFiscalYearTimeRangeFromYear', () => { describe('getFiscalYearTimeRangeFromYear', () => {
TEST_CASES_GET_FISCAL_YEAR_RANGE_FROM_YEAR.forEach((testCase) => { TEST_CASES_GET_FISCAL_YEAR_RANGE_FROM_YEAR.forEach((testCase) => {
const fiscalYearStart = FiscalYearStart.strictFromMonthDashDayString(testCase.fiscalYearStart); const fiscalYearStart = FiscalYearStart.parse(testCase.fiscalYearStart);
test(`returns correct fiscal year unix time range for input year integer ${testCase.year} and FY_START: ${testCase.fiscalYearStart}`, () => { test(`returns correct fiscal year unix time range for input year integer ${testCase.year} and FY_START: ${testCase.fiscalYearStart}`, () => {
const fiscalYearRange = getFiscalYearTimeRangeFromYear(testCase.year, fiscalYearStart.value); expect(fiscalYearStart).toBeDefined();
const fiscalYearRange = getFiscalYearTimeRangeFromYear(testCase.year, fiscalYearStart?.value || 0);
expect(fiscalYearRange).toStrictEqual(testCase.expected); expect(fiscalYearRange).toStrictEqual(testCase.expected);
}); });
}); });
}); });

View File

@@ -442,7 +442,7 @@ export function getAllYearsStartAndEndUnixTimes(startYearMonth: YearMonth | stri
return allYearTimes; return allYearTimes;
} }
export function getAllFiscalYearsStartAndEndUnixTimes(startYearMonth: YearMonth | string, endYearMonth: YearMonth | string, fiscalYearStart: number): FiscalYearUnixTime[] { export function getAllFiscalYearsStartAndEndUnixTimes(startYearMonth: YearMonth | string, endYearMonth: YearMonth | string, fiscalYearStartValue: number): FiscalYearUnixTime[] {
// user selects date range: start=2024-01 and end=2026-12 // user selects date range: start=2024-01 and end=2026-12
// result should be 4x FiscalYearUnixTime made up of: // result should be 4x FiscalYearUnixTime made up of:
// - 2024-01->2024-06 (FY 24) - input start year-month->end of fiscal year in which the input start year-month falls // - 2024-01->2024-06 (FY 24) - input start year-month->end of fiscal year in which the input start year-month falls
@@ -459,39 +459,45 @@ export function getAllFiscalYearsStartAndEndUnixTimes(startYearMonth: YearMonth
const inputStartUnixTime = getYearMonthFirstUnixTime(range.startYearMonth); const inputStartUnixTime = getYearMonthFirstUnixTime(range.startYearMonth);
const inputEndUnixTime = getYearMonthLastUnixTime(range.endYearMonth); const inputEndUnixTime = getYearMonthLastUnixTime(range.endYearMonth);
const fiscalYearStartMonth = FiscalYearStart.strictFromNumber(fiscalYearStart).month; let fiscalYearStart = FiscalYearStart.valueOf(fiscalYearStartValue);
if (!fiscalYearStart) {
fiscalYearStart = FiscalYearStart.Default;
}
const fiscalYearStartMonth = fiscalYearStart.month;
// Loop over 1 year before and 1 year after the input date range // Loop over 1 year before and 1 year after the input date range
// to include fiscal years that start in the previous calendar year. // to include fiscal years that start in the previous calendar year.
for (let year = range.startYearMonth.year - 1; year <= range.endYearMonth.year + 1; year++) { for (let year = range.startYearMonth.year - 1; year <= range.endYearMonth.year + 1; year++) {
const thisYearMonthUnixTime = getYearMonthFirstUnixTime({ year: year, month: fiscalYearStartMonth }); const thisYearMonthUnixTime = getYearMonthFirstUnixTime({ year: year, month: fiscalYearStartMonth });
const fiscalStartTime = getFiscalYearStartUnixTime(thisYearMonthUnixTime, fiscalYearStart); const fiscalStartTime = getFiscalYearStartUnixTime(thisYearMonthUnixTime, fiscalYearStart.value);
const fiscalEndTime = getFiscalYearEndUnixTime(thisYearMonthUnixTime, fiscalYearStart); const fiscalEndTime = getFiscalYearEndUnixTime(thisYearMonthUnixTime, fiscalYearStart.value);
const fiscalYear = getFiscalYearFromUnixTime(fiscalStartTime, fiscalYearStart); const fiscalYear = getFiscalYearFromUnixTime(fiscalStartTime, fiscalYearStart.value);
if (fiscalStartTime <= inputEndUnixTime && fiscalEndTime >= inputStartUnixTime) { if (fiscalStartTime <= inputEndUnixTime && fiscalEndTime >= inputStartUnixTime) {
let minUnixTime = fiscalStartTime; let minUnixTime = fiscalStartTime;
let maxUnixTime = fiscalEndTime; let maxUnixTime = fiscalEndTime;
// Cap the min and max unix times to the input date range // Cap the min and max unix times to the input date range
if (minUnixTime < inputStartUnixTime) { if (minUnixTime < inputStartUnixTime) {
minUnixTime = inputStartUnixTime; minUnixTime = inputStartUnixTime;
} }
if (maxUnixTime > inputEndUnixTime) { if (maxUnixTime > inputEndUnixTime) {
maxUnixTime = inputEndUnixTime; maxUnixTime = inputEndUnixTime;
} }
const fiscalYearTime: FiscalYearUnixTime = { const fiscalYearTime: FiscalYearUnixTime = {
year: fiscalYear, year: fiscalYear,
minUnixTime: minUnixTime, minUnixTime: minUnixTime,
maxUnixTime: maxUnixTime, maxUnixTime: maxUnixTime,
}; };
allFiscalYearTimes.push(fiscalYearTime); allFiscalYearTimes.push(fiscalYearTime);
} }
if (fiscalStartTime > inputEndUnixTime) { if (fiscalStartTime > inputEndUnixTime) {
break; break;
} }
@@ -1010,25 +1016,29 @@ export function isDateRangeMatchOneMonth(minTime: number, maxTime: number): bool
return isDateRangeMatchFullMonths(minTime, maxTime); return isDateRangeMatchFullMonths(minTime, maxTime);
} }
export function getFiscalYearFromUnixTime(unixTime: number, fiscalYearStart: number): number { export function getFiscalYearFromUnixTime(unixTime: number, fiscalYearStartValue: number): number {
const date = moment.unix(unixTime); const date = moment.unix(unixTime);
// For January 1 fiscal year start, fiscal year matches calendar year // For January 1 fiscal year start, fiscal year matches calendar year
if (fiscalYearStart === 0x0101) { if (fiscalYearStartValue === FiscalYearStart.JanuaryFirstDay.value) {
return date.year(); return date.year();
} }
// Get date components // Get date components
const month = date.month() + 1; // 1-index const month = date.month() + 1; // 1-index
const day = date.date(); const day = date.date();
const year = date.year(); const year = date.year();
const [fiscalYearStartMonth, fiscalYearStartDay] = FiscalYearStart.strictFromNumber(fiscalYearStart).values(); let fiscalYearStart = FiscalYearStart.valueOf(fiscalYearStartValue);
if (!fiscalYearStart) {
fiscalYearStart = FiscalYearStart.Default;
}
// For other fiscal year starts: // For other fiscal year starts:
// If input time comes before the fiscal year start day in the calendar year, // If input time comes before the fiscal year start day in the calendar year,
// it belongs to the fiscal year that ends in the current calendar year // it belongs to the fiscal year that ends in the current calendar year
if (month < fiscalYearStartMonth || (month === fiscalYearStartMonth && day < fiscalYearStartDay)) { if (month < fiscalYearStart.month || (month === fiscalYearStart.month && day < fiscalYearStart.day)) {
return year; return year;
} }
@@ -1037,33 +1047,38 @@ export function getFiscalYearFromUnixTime(unixTime: number, fiscalYearStart: num
return year + 1; return year + 1;
} }
export function getFiscalYearStartUnixTime(unixTime: number, fiscalYearStart: number): number { export function getFiscalYearStartUnixTime(unixTime: number, fiscalYearStartValue: number): number {
const date = moment.unix(unixTime); const date = moment.unix(unixTime);
// For January 1 fiscal year start, fiscal year start time is always January 1 in the input calendar year // For January 1 fiscal year start, fiscal year start time is always January 1 in the input calendar year
if (fiscalYearStart === 0x0101) { if (fiscalYearStartValue === FiscalYearStart.JanuaryFirstDay.value) {
return moment().year(date.year()).month(0).date(1).hour(0).minute(0).second(0).millisecond(0).unix(); return moment().year(date.year()).month(0).date(1).hour(0).minute(0).second(0).millisecond(0).unix();
} }
const [fiscalYearStartMonth, fiscalYearStartDay] = FiscalYearStart.strictFromNumber(fiscalYearStart).values(); let fiscalYearStart = FiscalYearStart.valueOf(fiscalYearStartValue);
if (!fiscalYearStart) {
fiscalYearStart = FiscalYearStart.Default;
}
const month = date.month() + 1; // 1-index const month = date.month() + 1; // 1-index
const day = date.date(); const day = date.date();
const year = date.year(); const year = date.year();
// For other fiscal year starts: // For other fiscal year starts:
// If input time comes before the fiscal year start day in the calendar year, // If input time comes before the fiscal year start day in the calendar year,
// the relevant fiscal year has a start date in Calendar Year = Input Year, and end date in Calendar Year = Input Year + 1. // the relevant fiscal year has a start date in Calendar Year = Input Year, and end date in Calendar Year = Input Year + 1.
// If input time comes on or after the fiscal year start day in the calendar year, // If input time comes on or after the fiscal year start day in the calendar year,
// the relevant fiscal year has a start date in Calendar Year = Input Year - 1, and end date in Calendar Year = Input Year. // the relevant fiscal year has a start date in Calendar Year = Input Year - 1, and end date in Calendar Year = Input Year.
let startYear = year - 1; let startYear = year - 1;
if (month > fiscalYearStartMonth || (month === fiscalYearStartMonth && day >= fiscalYearStartDay)) { if (month > fiscalYearStart.month || (month === fiscalYearStart.month && day >= fiscalYearStart.day)) {
startYear = year; startYear = year;
} }
return moment().set({ return moment().set({
year: startYear, year: startYear,
month: fiscalYearStartMonth - 1, // 0-index month: fiscalYearStart.month - 1, // 0-index
date: fiscalYearStartDay, date: fiscalYearStart.day,
hour: 0, hour: 0,
minute: 0, minute: 0,
second: 0, second: 0,
@@ -1073,7 +1088,7 @@ export function getFiscalYearStartUnixTime(unixTime: number, fiscalYearStart: nu
export function getFiscalYearEndUnixTime(unixTime: number, fiscalYearStart: number): number { export function getFiscalYearEndUnixTime(unixTime: number, fiscalYearStart: number): number {
const fiscalYearStartTime = moment.unix(getFiscalYearStartUnixTime(unixTime, fiscalYearStart)); const fiscalYearStartTime = moment.unix(getFiscalYearStartUnixTime(unixTime, fiscalYearStart));
return fiscalYearStartTime.add(1, 'year').subtract(1, 'second').unix(); return fiscalYearStartTime.add(1, 'years').subtract(1, 'seconds').unix();
} }
export function getCurrentFiscalYear(fiscalYearStart: number): number { export function getCurrentFiscalYear(fiscalYearStart: number): number {
@@ -1091,33 +1106,35 @@ export function getFiscalYearTimeRangeFromUnixTime(unixTime: number, fiscalYearS
}; };
} }
export function getFiscalYearTimeRangeFromYear(year: number, fiscalYearStart: number): FiscalYearUnixTime { export function getFiscalYearTimeRangeFromYear(year: number, fiscalYearStartValue: number): FiscalYearUnixTime {
const fiscalYear = year; const fiscalYear = year;
const fiscalYearStartObj = FiscalYearStart.strictFromNumber(fiscalYearStart); let fiscalYearStart = FiscalYearStart.valueOf(fiscalYearStartValue);
if (!fiscalYearStart) {
fiscalYearStart = FiscalYearStart.Default;
}
// For a specified fiscal year (e.g., 2023), the start date is in the previous calendar year // For a specified fiscal year (e.g., 2023), the start date is in the previous calendar year
// unless fiscal year starts on January 1 // unless fiscal year starts on January 1
const calendarStartYear = fiscalYearStart === 0x0101 ? fiscalYear : fiscalYear - 1; const calendarStartYear = fiscalYearStartValue === FiscalYearStart.JanuaryFirstDay.value ? fiscalYear : fiscalYear - 1;
// Create the timestamp for the start of the fiscal year // Create the timestamp for the start of the fiscal year
const fiscalYearStartUnixTime = moment().set({ const fiscalYearStartUnixTime = moment().set({
year: calendarStartYear, year: calendarStartYear,
month: fiscalYearStartObj.month - 1, // 0-index month: fiscalYearStart.month - 1, // 0-index
date: fiscalYearStartObj.day, date: fiscalYearStart.day,
hour: 0, hour: 0,
minute: 0, minute: 0,
second: 0, second: 0,
millisecond: 0, millisecond: 0,
}).unix(); }).unix();
// Fiscal year end is one year after start minus 1 second // Fiscal year end is one year after start minus 1 second
const fiscalYearEndUnixTime = moment.unix(fiscalYearStartUnixTime).add(1, 'year').subtract(1, 'second').unix(); const fiscalYearEndUnixTime = moment.unix(fiscalYearStartUnixTime).add(1, 'years').subtract(1, 'seconds').unix();
return { return {
year: fiscalYear, year: fiscalYear,
minUnixTime: fiscalYearStartUnixTime, minUnixTime: fiscalYearStartUnixTime,
maxUnixTime: fiscalYearEndUnixTime, maxUnixTime: fiscalYearEndUnixTime,
}; };
} }

View File

@@ -935,31 +935,36 @@ export function useI18n() {
]; ];
} }
function getAllFiscalYearFormats(): FiscalYearFormat[] { function getAllFiscalYearFormats(): TypeAndDisplayName[] {
const now = getCurrentUnixTime(); const now = getCurrentUnixTime();
let fiscalYearStart = userStore.currentUserFiscalYearStart; let fiscalYearStart = userStore.currentUserFiscalYearStart;
if (!fiscalYearStart) { if (!fiscalYearStart) {
fiscalYearStart = FiscalYearStart.Default.value; fiscalYearStart = FiscalYearStart.Default.value;
} }
const nowFiscalYearRange = getFiscalYearTimeRangeFromUnixTime(now, userStore.currentUserFiscalYearStart);
const ret: FiscalYearFormat[] = []; const currentFiscalYearRange = getFiscalYearTimeRangeFromUnixTime(now, fiscalYearStart);
const ret: TypeAndDisplayName[] = [];
let defaultFiscalYearFormatType = FiscalYearFormat.parse(t('default.fiscalYearFormat')); let fiscalYearFormat = FiscalYearFormat.parse(getDefaultFiscalYearFormat());
if (!defaultFiscalYearFormatType) {
defaultFiscalYearFormatType = FiscalYearFormat.Default; if (!fiscalYearFormat) {
fiscalYearFormat = FiscalYearFormat.Default;
} }
ret.push({ ret.push({
type: LANGUAGE_DEFAULT_FISCAL_YEAR_FORMAT_VALUE, type: LANGUAGE_DEFAULT_FISCAL_YEAR_FORMAT_VALUE,
displayName: `${t('Language Default')} (${formatTimeRangeToFiscalYearFormat(defaultFiscalYearFormatType, nowFiscalYearRange)})` displayName: `${t('Language Default')} (${formatTimeRangeToFiscalYearFormat(fiscalYearFormat, currentFiscalYearRange)})`
}); });
const allFiscalYearFormats = FiscalYearFormat.values(); const allFiscalYearFormats = FiscalYearFormat.values();
for (let i = 0; i < allFiscalYearFormats.length; i++) { for (let i = 0; i < allFiscalYearFormats.length; i++) {
const type = allFiscalYearFormats[i]; const format = allFiscalYearFormats[i];
ret.push({ ret.push({
type: type.type, type: format.type,
displayName: formatTimeRangeToFiscalYearFormat(type, nowFiscalYearRange), displayName: formatTimeRangeToFiscalYearFormat(format, currentFiscalYearRange),
}); });
} }
@@ -1366,7 +1371,7 @@ export function useI18n() {
let fiscalYearFormat = FiscalYearFormat.valueOf(userStore.currentUserFiscalYearFormat); let fiscalYearFormat = FiscalYearFormat.valueOf(userStore.currentUserFiscalYearFormat);
if (!fiscalYearFormat) { if (!fiscalYearFormat) {
const defaultFiscalYearFormatTypeName = t('default.fiscalYearFormat'); const defaultFiscalYearFormatTypeName = getDefaultFiscalYearFormat();
fiscalYearFormat = FiscalYearFormat.parse(defaultFiscalYearFormatTypeName); fiscalYearFormat = FiscalYearFormat.parse(defaultFiscalYearFormatTypeName);
if (!fiscalYearFormat) { if (!fiscalYearFormat) {
@@ -1477,7 +1482,7 @@ export function useI18n() {
format = FiscalYearFormat.Default; format = FiscalYearFormat.Default;
} }
return t('format.fiscalYear.' + format.displayName, { return t('format.fiscalYear.' + format.typeName, {
StartYYYY: formatUnixTime(timeRange.minUnixTime, 'YYYY'), StartYYYY: formatUnixTime(timeRange.minUnixTime, 'YYYY'),
StartYY: formatUnixTime(timeRange.minUnixTime, 'YY'), StartYY: formatUnixTime(timeRange.minUnixTime, 'YY'),
EndYYYY: formatUnixTime(timeRange.maxUnixTime, 'YYYY'), EndYYYY: formatUnixTime(timeRange.maxUnixTime, 'YYYY'),
@@ -1493,7 +1498,6 @@ export function useI18n() {
} }
const timeRange = getFiscalYearTimeRangeFromUnixTime(unixTime, userStore.currentUserFiscalYearStart); const timeRange = getFiscalYearTimeRangeFromUnixTime(unixTime, userStore.currentUserFiscalYearStart);
return formatTimeRangeToFiscalYearFormat(fiscalYearFormat, timeRange); return formatTimeRangeToFiscalYearFormat(fiscalYearFormat, timeRange);
} }
@@ -1505,18 +1509,17 @@ export function useI18n() {
} }
const timeRange = getFiscalYearTimeRangeFromYear(year, userStore.currentUserFiscalYearStart); const timeRange = getFiscalYearTimeRangeFromYear(year, userStore.currentUserFiscalYearStart);
return formatTimeRangeToFiscalYearFormat(fiscalYearFormat, timeRange); return formatTimeRangeToFiscalYearFormat(fiscalYearFormat, timeRange);
} }
function formatFiscalYearStart(fiscalYearStart: number) { function formatFiscalYearStartToLongDay(fiscalYearStartValue: number) {
let fy = FiscalYearStart.fromNumber(fiscalYearStart); let fiscalYearStart = FiscalYearStart.valueOf(fiscalYearStartValue);
if ( !fy ) { if (!fiscalYearStart) {
fy = FiscalYearStart.Default; fiscalYearStart = FiscalYearStart.Default;
} }
return formatMonthDayToLongDay(fy.toMonthDashDayString()); return formatMonthDayToLongDay(fiscalYearStart.toMonthDashDayString());
} }
function getTimezoneDifferenceDisplayText(utcOffset: number): string { function getTimezoneDifferenceDisplayText(utcOffset: number): string {
@@ -1865,7 +1868,6 @@ export function useI18n() {
getWeekdayLongName, getWeekdayLongName,
getMultiMonthdayShortNames, getMultiMonthdayShortNames,
getMultiWeekdayLongNames, getMultiWeekdayLongNames,
getCurrentFiscalYearStartFormatted: () => formatMonthDayToLongDay(FiscalYearStart.strictFromNumber(userStore.currentUserFiscalYearStart).toMonthDashDayString()),
getCurrentFiscalYearFormatType, getCurrentFiscalYearFormatType,
getCurrentDecimalSeparator, getCurrentDecimalSeparator,
getCurrentDigitGroupingSymbol, getCurrentDigitGroupingSymbol,
@@ -1896,7 +1898,7 @@ export function useI18n() {
formatMonthDayToLongDay, formatMonthDayToLongDay,
formatYearQuarter, formatYearQuarter,
formatDateRange, formatDateRange,
formatFiscalYearStart, formatFiscalYearStartToLongDay,
formatTimeRangeToFiscalYearFormat, formatTimeRangeToFiscalYearFormat,
formatUnixTimeToFiscalYear, formatUnixTimeToFiscalYear,
formatYearToFiscalYear, formatYearToFiscalYear,

View File

@@ -25,6 +25,7 @@
<f7-list-item class="list-item-with-header-and-title list-item-no-item-after" header="Default Language" title="Language" link="#"></f7-list-item> <f7-list-item class="list-item-with-header-and-title list-item-no-item-after" header="Default Language" title="Language" link="#"></f7-list-item>
<f7-list-item class="list-item-with-header-and-title list-item-no-item-after" header="Default Currency" title="Currency" link="#"></f7-list-item> <f7-list-item class="list-item-with-header-and-title list-item-no-item-after" header="Default Currency" title="Currency" link="#"></f7-list-item>
<f7-list-item class="list-item-with-header-and-title list-item-no-item-after" header="First Day of Week" title="Week Day" link="#"></f7-list-item> <f7-list-item class="list-item-with-header-and-title list-item-no-item-after" header="First Day of Week" title="Week Day" link="#"></f7-list-item>
<f7-list-item class="list-item-with-header-and-title list-item-no-item-after" header="Fiscal Year Start Date" title="January 1" link="#"></f7-list-item>
</f7-list> </f7-list>
<f7-list strong inset dividers class="margin-vertical skeleton-text" v-if="loading"> <f7-list strong inset dividers class="margin-vertical skeleton-text" v-if="loading">
@@ -32,6 +33,7 @@
<f7-list-item class="list-item-with-header-and-title list-item-no-item-after" header="Short Date Format" title="YYYY-MM-DD" link="#"></f7-list-item> <f7-list-item class="list-item-with-header-and-title list-item-no-item-after" header="Short Date Format" title="YYYY-MM-DD" link="#"></f7-list-item>
<f7-list-item class="list-item-with-header-and-title list-item-no-item-after" header="Long Time Format" title="HH:mm:ss" link="#"></f7-list-item> <f7-list-item class="list-item-with-header-and-title list-item-no-item-after" header="Long Time Format" title="HH:mm:ss" link="#"></f7-list-item>
<f7-list-item class="list-item-with-header-and-title list-item-no-item-after" header="Short Time Format" title="HH:mm" link="#"></f7-list-item> <f7-list-item class="list-item-with-header-and-title list-item-no-item-after" header="Short Time Format" title="HH:mm" link="#"></f7-list-item>
<f7-list-item class="list-item-with-header-and-title list-item-no-item-after" header="Fiscal Year Format" title="FY YYYY" link="#"></f7-list-item>
</f7-list> </f7-list>
<f7-list strong inset dividers class="margin-vertical skeleton-text" v-if="loading"> <f7-list strong inset dividers class="margin-vertical skeleton-text" v-if="loading">
@@ -207,7 +209,7 @@
link="#" link="#"
class="list-item-with-header-and-title list-item-no-item-after" class="list-item-with-header-and-title list-item-no-item-after"
:header="tt('Fiscal Year Start Date')" :header="tt('Fiscal Year Start Date')"
:title="currentFiscalYearStartDate" :title="formatFiscalYearStartToLongDay(newProfile.fiscalYearStart)"
@click="showFiscalYearStartSheet = true" @click="showFiscalYearStartSheet = true"
> >
<fiscal-year-start-selection-sheet <fiscal-year-start-selection-sheet
@@ -516,7 +518,7 @@ const props = defineProps<{
f7router: Router.Router; f7router: Router.Router;
}>(); }>();
const { tt, getAllLanguageOptions, getAllCurrencies, getCurrencyName, formatFiscalYearStart } = useI18n(); const { tt, getAllLanguageOptions, getAllCurrencies, getCurrencyName, formatFiscalYearStartToLongDay } = useI18n();
const { showAlert, showToast, routeBackOnError } = useI18nUIComponents(); const { showAlert, showToast, routeBackOnError } = useI18nUIComponents();
const { const {
@@ -597,7 +599,6 @@ const currentLanguageName = computed<string>(() => {
}); });
const currentDayOfWeekName = computed<string | null>(() => findDisplayNameByType(allWeekDays.value, newProfile.value.firstDayOfWeek)); const currentDayOfWeekName = computed<string | null>(() => findDisplayNameByType(allWeekDays.value, newProfile.value.firstDayOfWeek));
const currentFiscalYearStartDate = computed<string | null>( () => formatFiscalYearStart(newProfile.value.fiscalYearStart) );
function init(): void { function init(): void {
loading.value = true; loading.value = true;

7
tsconfig.jest.json Normal file
View File

@@ -0,0 +1,7 @@
{
"extends": "./tsconfig.json",
"compilerOptions": {
"isolatedModules": true,
"verbatimModuleSyntax": false
}
}

View File

@@ -16,6 +16,7 @@
}, },
"include": [ "include": [
"src/**/*", "src/**/*",
"vite.config.ts" "vite.config.ts",
"jest.config.ts"
] ]
} }