75 lines
2.6 KiB
TypeScript
75 lines
2.6 KiB
TypeScript
import { marbasAxiosInstance, MarbasObject } from "@/marbas";
|
|
import { AxiosResponse } from "axios";
|
|
import log from "loglevel";
|
|
import { defineStore } from "pinia";
|
|
import { computed, ref } from "vue";
|
|
|
|
export type AcquiredTypeSource = 'bo' | 'so' | 'prod' | 'misc';
|
|
|
|
export type MarbasAcquiredType = MarbasObject & {
|
|
type: number;
|
|
quantity: number;
|
|
remaining: number;
|
|
price: number;
|
|
date: Date;
|
|
source: AcquiredTypeSource;
|
|
}
|
|
|
|
type RawMarbasAcquiredType = Omit<MarbasAcquiredType, 'date'> & {
|
|
date: string;
|
|
}
|
|
|
|
type InsertableRawMarbasAcquiredType = Omit<MarbasAcquiredType, 'id' | 'date'>;
|
|
|
|
const mapRawMarbasAcquiredType = (raw: RawMarbasAcquiredType): MarbasAcquiredType => ({
|
|
...raw,
|
|
date: raw.date ? new Date(raw.date) : new Date()
|
|
});
|
|
|
|
const endpoint = '/api/acquisitions/';
|
|
|
|
export const useAcquiredTypesStore = defineStore('market-acquisition', () => {
|
|
const acquiredTypes = ref<MarbasAcquiredType[]>([]);
|
|
|
|
const types = computed(() => acquiredTypes.value.filter(item => item.remaining > 0));
|
|
const addAcquiredType = async (type: number, quantity: number, price: number, source?: AcquiredTypeSource) => {
|
|
const newItem = mapRawMarbasAcquiredType((await marbasAxiosInstance.post<RawMarbasAcquiredType, AxiosResponse<RawMarbasAcquiredType>, InsertableRawMarbasAcquiredType>(endpoint, {
|
|
type: type,
|
|
quantity: quantity,
|
|
remaining: quantity,
|
|
price: price,
|
|
source: source ?? 'misc',
|
|
})).data);
|
|
|
|
acquiredTypes.value = [...acquiredTypes.value, newItem];
|
|
log.info(`Acquired type ${newItem.id} with quantity ${newItem.quantity} and price ${newItem.price}`, newItem);
|
|
};
|
|
const removeAcquiredType = async (id: number, quantity: number) => {
|
|
const found = acquiredTypes.value.find(t => t.id === id);
|
|
|
|
if (!found) {
|
|
return 0;
|
|
}
|
|
|
|
const item = {
|
|
...found,
|
|
remaining: Math.max(0, found.remaining - quantity)
|
|
};
|
|
|
|
acquiredTypes.value = acquiredTypes.value.map(i => {
|
|
if (i.id === item.id) {
|
|
return item;
|
|
} else {
|
|
return i;
|
|
}
|
|
});
|
|
await marbasAxiosInstance.put(`${endpoint}${item.id}/`, item);
|
|
log.info(`Acquired type ${item.id} remaining: ${item.remaining}`, item);
|
|
};
|
|
|
|
const refresh = () => marbasAxiosInstance.get<RawMarbasAcquiredType[]>(endpoint).then(res => acquiredTypes.value = res.data.map(mapRawMarbasAcquiredType));
|
|
|
|
refresh();
|
|
|
|
return { acquiredTypes: types, addAcquiredType, removeAcquiredType, refresh };
|
|
}); |