Skip to content

Commit

Permalink
Monthly close (#35)
Browse files Browse the repository at this point in the history
* update schema

* close

* add code rule

* refactor

* refactor

* refactor
  • Loading branch information
katayama8000 authored Jun 13, 2024
1 parent 99e8dc3 commit 5182ad9
Show file tree
Hide file tree
Showing 8 changed files with 148 additions and 45 deletions.
11 changes: 11 additions & 0 deletions CoadingRule.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,11 @@
## 命名
- テーブル名は複数形
- 関数名は動詞+名詞(テーブル名)+その他の情報
- DBから値を取得する関数名は`fetch`をつける
- 例: `fetchUser`
- テーブルのデータをすべて取得する場合
- テーブル名は複数形
- テーブル名の後ろに`All`をつける
- 例: `fetchUsersAll`
- キーを使って取得する場合は`By`をつける
- 例: `fetchUserById`
4 changes: 2 additions & 2 deletions app/(auth)/sign-in.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -30,9 +30,9 @@ const SignInScreen = () => {
});

if (error) {
Alert.alert(error.message);
alert(error.message);
} else {
Alert.alert("サインインしました");
alert("サインインしました");
}
setLoading(false);
};
Expand Down
11 changes: 6 additions & 5 deletions app/(modal)/payment-modal.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,7 @@ import { Colors } from "@/constants/Colors";
import { defaultFontSize } from "@/style/defaultStyle";

export default function PaymentModalScreen() {
const { payments, addPayment, updatePayment, setName, setAmount, name, amount } = usePayment();
const { payments, addPayment, updatePayment, setName, setAmount, name, amount, fetchPaymentsAll } = usePayment();
const { kind, id } = useLocalSearchParams();
const { setOptions } = useNavigation();

Expand All @@ -26,16 +26,17 @@ export default function PaymentModalScreen() {
}
}, [kind, id, setName, setAmount, payments, setOptions]);

const handlePayment = () => {
const handlePayment = async () => {
if (kind === "edit" && id) {
if (!name || !amount) {
alert("入力してください");
alert("Please enter both name and amount.");
return;
}
updatePayment(Number(id), { name, amount });
await updatePayment(Number(id), { name, amount });
} else {
addPayment();
await addPayment();
}
await fetchPaymentsAll();
};

return (
Expand Down
66 changes: 62 additions & 4 deletions app/(tabs)/index.tsx
Original file line number Diff line number Diff line change
@@ -1,24 +1,65 @@
import { View, Text, FlatList, TouchableOpacity, Alert, StyleSheet } from "react-native";
import { AntDesign } from "@expo/vector-icons";
import type { FC } from "react";
import type { Payment as PaymentRow } from "@/types/Row";
import type { Couple, Payment as PaymentRow } from "@/types/Row";
import { usePayment } from "../hooks/usePayment";
import { Colors } from "@/constants/Colors";
import { useRouter } from "expo-router";
import type { ExpoRouter } from "expo-router/types/expo-router";
import { defaultFontSize, defaultShadowColor } from "@/style/defaultStyle";
import dayjs from "dayjs";
import { useInvoice } from "../hooks/useInvoice";
import { supabase } from "@/lib/supabase";
import { useCouple } from "../hooks/useCouple";

const HomeScreen: FC = () => {
const { payments, isRefreshing, fetchAllPayments, deletePayment } = usePayment();
const { payments, isRefreshing, fetchPaymentsAll, deletePayment } = usePayment();
const { addInvoice, unActiveInvoicesAll, turnInvoicePaid } = useInvoice();
const { fetchCoupleIdByUserId } = useCouple();
const router = useRouter();
const showCloseMonthButton = true;
// dayjs().date() >= 25 || dayjs().date() <= 5;

const handleCloseMonth = async (coupleId: Couple["id"]) => {
Alert.alert("今月の精算を完了します", "よろしいですか?", [
{ text: "いいえ", style: "cancel" },
{
text: "はい",
onPress: () => {
unActiveInvoicesAll(coupleId);
turnInvoicePaid(coupleId);
addInvoice(coupleId);
},
},
]);
};

return (
<View style={styles.container}>
<AddPaymentButton onPress={() => router.push({ pathname: "/payment-modal", params: { kind: "add" } })} />
<View style={styles.buttonWrapper}>
<AddPaymentButton onPress={() => router.push({ pathname: "/payment-modal", params: { kind: "add" } })} />
{showCloseMonthButton && (
<CloseMonthButton
onPress={async () => {
const userId = (await supabase.auth.getUser()).data.user?.id;
if (!userId) {
alert("userId is not found");
return;
}
const coupleId = await fetchCoupleIdByUserId(userId);
if (!coupleId) {
alert("coupleId is not found");
return;
}
handleCloseMonth(coupleId);
}}
/>
)}
</View>
<PaymentList
payments={payments}
isRefreshing={isRefreshing}
fetchAllPayments={fetchAllPayments}
fetchAllPayments={fetchPaymentsAll}
deletePayment={deletePayment}
routerPush={router.push}
/>
Expand All @@ -37,6 +78,19 @@ const AddPaymentButton: FC<AddPaymentButtonProps> = ({ onPress }) => (
</TouchableOpacity>
);

type CloseMonthButtonProps = {
onPress: () => void;
};

const CloseMonthButton: FC<CloseMonthButtonProps> = ({ onPress }) => {
return (
<TouchableOpacity style={styles.addButton} onPress={onPress}>
<AntDesign name="checkcircleo" size={24} color="white" />
<Text style={styles.addButtonText}>締める</Text>
</TouchableOpacity>
);
};

type PaymentListProps = {
payments: PaymentRow[];
isRefreshing: boolean;
Expand Down Expand Up @@ -94,6 +148,10 @@ const styles = StyleSheet.create({
flex: 1,
padding: 16,
},
buttonWrapper: {
flexDirection: "row",
justifyContent: "space-between",
},
addButton: {
borderRadius: 50,
marginBottom: 16,
Expand Down
6 changes: 3 additions & 3 deletions app/hooks/useCouple.ts
Original file line number Diff line number Diff line change
Expand Up @@ -7,9 +7,9 @@ export const useCouple = () => {
const user1 = await supabase.from(dev_couples).select("id").eq("user1_id", user_id).single();
const user2 = await supabase.from(dev_couples).select("id").eq("user2_id", user_id).single();

console.log("user1", user1);
console.log("user2", user2);

if (user1.error || user2.error) {
throw new Error("Failed to fetch couple id");
}
return user1.data?.id || user2.data?.id;
};

Expand Down
69 changes: 50 additions & 19 deletions app/hooks/useInvoice.ts
Original file line number Diff line number Diff line change
Expand Up @@ -17,26 +17,32 @@ export const useInvoice = () => {
);
}, []);

const fetchInvoiceByCoupleId = useCallback(
async (coupleId: Invoice["couple_id"]) => {
try {
const { data: invoices, error } = await supabase
.from(dev_monthly_invoices)
.select("*")
.eq("couple_id", coupleId);
const getActiveInvoice = async () => {
const { data, error } = await supabase.from(dev_monthly_invoices).select("*").eq("active", true);

if (error) throw error;
if (error) throw error;

return getCurrentMonthInvoice(invoices);
} catch (error) {
console.error(error);
return undefined;
}
},
[getCurrentMonthInvoice],
);
return data[0];
};

const fetchInvoiceByCoupleId = useCallback(async (coupleId: Invoice["couple_id"]) => {
try {
const { data, error } = await supabase
.from(dev_monthly_invoices)
.select("*")
.eq("couple_id", coupleId)
.eq("active", true);

if (error) throw error;

const fetchAllInvoices = useCallback(async () => {
return data[0];
} catch (error) {
console.error(error);
return undefined;
}
}, []);

const fetchInvoicesAll = useCallback(async () => {
setIsRefreshing(true);
try {
const { data: invoices, error } = await supabase.from(dev_monthly_invoices).select("*");
Expand All @@ -59,16 +65,41 @@ export const useInvoice = () => {
{
couple_id,
is_paid: false,
active: true,
},
]);
if (error) throw error;
} catch (error) {
console.error(error);
}
};

const unActiveInvoicesAll = async (couple_id: Invoice["couple_id"]) => {
try {
const { error } = await supabase.from(dev_monthly_invoices).update({ active: false }).eq("couple_id", couple_id);
if (error) throw error;
} catch (error) {
console.error(error);
}
};

await fetchAllInvoices();
const turnInvoicePaid = async (invoice_id: Invoice["id"]) => {
try {
const { error } = await supabase.from(dev_monthly_invoices).update({ is_paid: true }).eq("id", invoice_id);
if (error) throw error;
} catch (error) {
console.error(error);
}
};

return { invoices, isRefreshing, fetchAllInvoices, fetchInvoiceByCoupleId, addInvoice };
return {
invoices,
isRefreshing,
fetchInvoicesAll,
fetchInvoiceByCoupleId,
addInvoice,
getActiveInvoice,
unActiveInvoicesAll,
turnInvoicePaid,
};
};
23 changes: 11 additions & 12 deletions app/hooks/usePayment.ts
Original file line number Diff line number Diff line change
Expand Up @@ -19,7 +19,7 @@ export const usePayment = () => {
const router = useRouter();

useEffect(() => {
fetchAllPayments();
fetchPaymentsAll();
}, []);

const resetForm = () => {
Expand Down Expand Up @@ -69,15 +69,14 @@ export const usePayment = () => {

alert("Success");
resetForm();
fetchAllPayments();
router.back();
} catch (error) {
console.error(error);
alert("An error occurred. Please try again.");
}
}, [name, amount, router, resetForm, fetchInvoiceByCoupleId, fetchCoupleIdByUserId]);

const fetchAllPayments = useCallback(async (): Promise<void> => {
const fetchPaymentsAll = useCallback(async (): Promise<void> => {
setIsRefreshing(true);
try {
const { data, error } = await supabase.from(dev_payments).select("*");
Expand Down Expand Up @@ -120,14 +119,14 @@ export const usePayment = () => {
alert("An error occurred. Please try again.");
return;
}
fetchAllPayments();
fetchPaymentsAll();
router.back();
} catch (error) {
console.error(error);
alert("An error occurred. Please try again.");
}
},
[fetchAllPayments, router],
[fetchPaymentsAll, router],
);

const deletePayment = useCallback(
Expand All @@ -139,16 +138,16 @@ export const usePayment = () => {
alert("An error occurred. Please try again.");
return;
}
fetchAllPayments();
fetchPaymentsAll();
} catch (error) {
console.error(error);
alert("An error occurred. Please try again.");
}
},
[fetchAllPayments],
[fetchPaymentsAll],
);

const getTotalPayment = async (monthly_invoice_id: Payment["monthly_invoice_id"]) => {
const fetchPaymentToal = async (monthly_invoice_id: Payment["monthly_invoice_id"]) => {
const { data, error } = await supabase
.from(dev_payments)
.select("amount")
Expand All @@ -160,7 +159,7 @@ export const usePayment = () => {
return data.reduce((acc, cur) => acc + cur.amount, 0);
};

const getPaymentsByMonthlyInvoiceId = async (id: Invoice["id"]) => {
const fetchPaymentsByMonthlyInvoiceId = async (id: Invoice["id"]) => {
const { data, error } = await supabase.from(dev_payments).select("*").eq("monthly_invoice_id", id);
if (error) {
console.error(error);
Expand All @@ -177,11 +176,11 @@ export const usePayment = () => {
setName,
setAmount,
addPayment,
fetchAllPayments,
fetchPaymentsAll,
fetchPaymentById,
updatePayment,
deletePayment,
getTotalPayment,
getPaymentsByMonthlyInvoiceId,
fetchPaymentToal,
fetchPaymentsByMonthlyInvoiceId,
};
};
3 changes: 3 additions & 0 deletions types/supabase.ts
Original file line number Diff line number Diff line change
Expand Up @@ -26,20 +26,23 @@ export type Database = {
};
dev_monthly_invoices: {
Row: {
active: boolean;
couple_id: number;
created_at: string;
id: number;
is_paid: boolean;
updated_at: string;
};
Insert: {
active?: boolean;
couple_id: number;
created_at?: string;
id?: number;
is_paid: boolean;
updated_at?: string;
};
Update: {
active?: boolean;
couple_id?: number;
created_at?: string;
id?: number;
Expand Down

0 comments on commit 5182ad9

Please sign in to comment.