72 lines
2.4 KiB
TypeScript
72 lines
2.4 KiB
TypeScript
import { Injectable } from '@nestjs/common';
|
|
import { PrismaService } from '../prisma/prisma.service';
|
|
import { getTempUserId } from '../common/user.util';
|
|
|
|
@Injectable()
|
|
export class WalletsService {
|
|
constructor(private prisma: PrismaService) {}
|
|
|
|
private userId() {
|
|
return getTempUserId();
|
|
}
|
|
|
|
list() {
|
|
return this.prisma.wallet.findMany({
|
|
where: { userId: this.userId(), deletedAt: null },
|
|
orderBy: { createdAt: 'asc' },
|
|
});
|
|
}
|
|
|
|
create(input: { name: string; currency?: string; kind?: 'money' | 'asset'; unit?: string; initialAmount?: number; pricePerUnit?: number }) {
|
|
const kind = input.kind ?? 'money';
|
|
return this.prisma.wallet.create({
|
|
data: {
|
|
userId: this.userId(),
|
|
name: input.name,
|
|
kind,
|
|
currency: kind === 'money' ? (input.currency ?? 'IDR') : null,
|
|
unit: kind === 'asset' ? (input.unit ?? null) : null,
|
|
initialAmount: input.initialAmount || null,
|
|
pricePerUnit: kind === 'asset' ? (input.pricePerUnit || null) : null,
|
|
},
|
|
});
|
|
}
|
|
|
|
update(id: string, input: { name?: string; currency?: string; kind?: 'money' | 'asset'; unit?: string; initialAmount?: number; pricePerUnit?: number }) {
|
|
const updateData: any = {};
|
|
|
|
if (input.name !== undefined) updateData.name = input.name;
|
|
if (input.kind !== undefined) {
|
|
updateData.kind = input.kind;
|
|
// Reset currency/unit based on kind
|
|
if (input.kind === 'money') {
|
|
updateData.currency = input.currency ?? 'IDR';
|
|
updateData.unit = null;
|
|
} else {
|
|
updateData.unit = input.unit ?? null;
|
|
updateData.currency = null;
|
|
}
|
|
} else {
|
|
// If kind is not changing, update currency/unit as provided
|
|
if (input.currency !== undefined) updateData.currency = input.currency;
|
|
if (input.unit !== undefined) updateData.unit = input.unit;
|
|
}
|
|
|
|
// Handle initialAmount and pricePerUnit
|
|
if (input.initialAmount !== undefined) updateData.initialAmount = input.initialAmount || null;
|
|
if (input.pricePerUnit !== undefined) updateData.pricePerUnit = input.pricePerUnit || null;
|
|
|
|
return this.prisma.wallet.update({
|
|
where: { id, userId: this.userId() },
|
|
data: updateData,
|
|
});
|
|
}
|
|
|
|
delete(id: string) {
|
|
// Soft delete by setting deletedAt
|
|
return this.prisma.wallet.update({
|
|
where: { id, userId: this.userId() },
|
|
data: { deletedAt: new Date() },
|
|
});
|
|
}
|
|
} |