Compare commits

...

2 Commits

Author SHA1 Message Date
c26de5aefc update netListTable, CreateOrUpdateHaulModal 2025-11-10 16:11:02 +07:00
Tran Anh Tuan
f3b0e7b7eb cập nhật api thêm/sửa mẻ 2025-11-10 10:45:31 +07:00
6 changed files with 246 additions and 112 deletions

View File

@@ -18,11 +18,11 @@ export default function TabLayout() {
// TODO: xử lý khi chuyển tab ở đây // TODO: xử lý khi chuyển tab ở đây
if (prev.current === "(tabs)" && currentSegment !== "(tabs)") { if (prev.current === "(tabs)" && currentSegment !== "(tabs)") {
stopEvents(); stopEvents();
// console.log("Stop events"); console.log("Stop events");
} else if (prev.current !== "(tabs)" && currentSegment === "(tabs)") { } else if (prev.current !== "(tabs)" && currentSegment === "(tabs)") {
// we came back into the tabs group — restart polling // we came back into the tabs group — restart polling
startEvents(); startEvents();
// console.log("start events"); console.log("start events");
} }
prev.current = currentSegment; prev.current = currentSegment;
} }

View File

@@ -145,7 +145,7 @@ export default function HomeScreen() {
} }
for (const zone of zones) { for (const zone of zones) {
console.log("Zone Data: ", zone); // console.log("Zone Data: ", zone);
const geom = banzoneData.find((b) => b.id === zone.zone_id); const geom = banzoneData.find((b) => b.id === zone.zone_id);
if (!geom) { if (!geom) {
continue; continue;

View File

@@ -96,7 +96,12 @@ const NetListTable: React.FC = () => {
{/* Cột Trạng thái */} {/* Cột Trạng thái */}
<View style={[styles.cell, styles.statusContainer]}> <View style={[styles.cell, styles.statusContainer]}>
<View style={styles.statusDot} /> <View
style={[
styles.statusDot,
{ backgroundColor: item.status ? "#2ecc71" : "#FFD600" },
]}
/>
<TouchableOpacity <TouchableOpacity
onPress={() => handleStatusPress(item.fishing_log_id)} onPress={() => handleStatusPress(item.fishing_log_id)}
> >
@@ -125,7 +130,12 @@ const NetListTable: React.FC = () => {
{/* Cột Trạng thái */} {/* Cột Trạng thái */}
<View style={[styles.cell, styles.statusContainer]}> <View style={[styles.cell, styles.statusContainer]}>
<View style={styles.statusDot} /> <View
style={[
styles.statusDot,
{ backgroundColor: item.status ? "#2ecc71" : "#FFD600" },
]}
/>
<TouchableOpacity <TouchableOpacity
onPress={() => handleStatusPress(item.fishing_log_id)} onPress={() => handleStatusPress(item.fishing_log_id)}
> >

View File

@@ -1,6 +1,10 @@
import Select from "@/components/Select"; import Select from "@/components/Select";
import { IconSymbol } from "@/components/ui/icon-symbol"; import { IconSymbol } from "@/components/ui/icon-symbol";
import { queryGpsData } from "@/controller/DeviceController";
import { queryUpdateFishingLogs } from "@/controller/TripController";
import { showErrorToast, showSuccessToast } from "@/services/toast_service";
import { useFishes } from "@/state/use-fish"; import { useFishes } from "@/state/use-fish";
import { useTrip } from "@/state/use-trip";
import { zodResolver } from "@hookform/resolvers/zod"; import { zodResolver } from "@hookform/resolvers/zod";
import React from "react"; import React from "react";
import { Controller, useFieldArray, useForm } from "react-hook-form"; import { Controller, useFieldArray, useForm } from "react-hook-form";
@@ -24,7 +28,6 @@ interface CreateOrUpdateHaulModalProps {
fishingLog?: Model.FishingLog | null; fishingLog?: Model.FishingLog | null;
fishingLogIndex?: number; fishingLogIndex?: number;
} }
const UNITS = ["con", "kg", "tấn"] as const; const UNITS = ["con", "kg", "tấn"] as const;
type Unit = (typeof UNITS)[number]; type Unit = (typeof UNITS)[number];
@@ -33,6 +36,14 @@ const UNITS_OPTIONS = UNITS.map((unit) => ({
value: unit.toString(), value: unit.toString(),
})); }));
const SIZE_UNITS = ["cm", "m"] as const;
type SizeUnit = (typeof SIZE_UNITS)[number];
const SIZE_UNITS_OPTIONS = SIZE_UNITS.map((unit) => ({
label: unit,
value: unit,
}));
// Zod schema cho 1 dòng cá // Zod schema cho 1 dòng cá
const fishItemSchema = z.object({ const fishItemSchema = z.object({
id: z.number().min(1, "Chọn loài cá"), id: z.number().min(1, "Chọn loài cá"),
@@ -44,6 +55,7 @@ const fishItemSchema = z.object({
.number({ invalid_type_error: "Kích thước phải là số" }) .number({ invalid_type_error: "Kích thước phải là số" })
.positive("Kích thước > 0") .positive("Kích thước > 0")
.optional(), .optional(),
sizeUnit: z.enum(SIZE_UNITS),
}); });
// Schema tổng: mảng các item // Schema tổng: mảng các item
@@ -57,6 +69,7 @@ const defaultItem = (): FormValues["fish"][number] => ({
quantity: 1, quantity: 1,
unit: "con", unit: "con",
size: undefined, size: undefined,
sizeUnit: "cm",
}); });
const CreateOrUpdateHaulModal: React.FC<CreateOrUpdateHaulModalProps> = ({ const CreateOrUpdateHaulModal: React.FC<CreateOrUpdateHaulModalProps> = ({
@@ -70,6 +83,7 @@ const CreateOrUpdateHaulModal: React.FC<CreateOrUpdateHaulModalProps> = ({
const [expandedFishIndices, setExpandedFishIndices] = React.useState< const [expandedFishIndices, setExpandedFishIndices] = React.useState<
number[] number[]
>([]); >([]);
const { trip, getTrip } = useTrip();
const { control, handleSubmit, formState, watch, reset } = const { control, handleSubmit, formState, watch, reset } =
useForm<FormValues>({ useForm<FormValues>({
resolver: zodResolver(formSchema), resolver: zodResolver(formSchema),
@@ -95,26 +109,90 @@ const CreateOrUpdateHaulModal: React.FC<CreateOrUpdateHaulModalProps> = ({
); );
}; };
const onSubmit = (values: FormValues) => { const onSubmit = async (values: FormValues) => {
// Map form values to the FishingLogInfo-like shape the user requested // Ensure species list is available so we can populate name/rarity
const mapped = values.fish.map((f) => { if (!fishSpecies || fishSpecies.length === 0) {
const meta = fishSpecies!.find((x) => x.id === f.id); showErrorToast("Danh sách loài cá chưa sẵn sàng");
return { return;
fish_species_id: f.id, }
fish_name: meta?.name, // Helper to map form rows -> API info entries (single place)
catch_number: f.quantity, const buildInfo = (rows: FormValues["fish"]) =>
catch_unit: f.unit, rows.map((item) => {
fish_size: f.size, const meta = fishSpecies.find((f) => f.id === item.id);
fish_rarity: meta?.rarity_level, return {
fish_condition: "", fish_species_id: item.id,
gear_usage: "", fish_name: meta?.name ?? "",
} as unknown; // inferred shape — keep as unknown to avoid relying on global types here catch_number: item.quantity,
}); catch_unit: item.unit,
fish_size: item.size,
fish_rarity: meta?.rarity_level ?? null,
fish_condition: "",
gear_usage: "",
} as unknown;
});
console.log("SUBMIT (FishingLogInfo[]): ", JSON.stringify(mapped, null, 2)); try {
const gpsResp = await queryGpsData();
if (!gpsResp.data) {
showErrorToast("Không thể lấy dữ liệu GPS hiện tại");
return;
}
const gpsData = gpsResp.data;
// close modal after submit (you can change this to pass the payload to a parent via prop) const info = buildInfo(values.fish) as any;
onClose();
// Base payload fields shared between create and update
const base: Partial<Model.FishingLog> = {
fishing_log_id: fishingLog?.fishing_log_id || "",
trip_id: trip?.id || "",
start_at: fishingLog?.start_at!,
start_lat: fishingLog?.start_lat!,
start_lon: fishingLog?.start_lon!,
weather_description:
fishingLog?.weather_description || "Nắng đẹp, Trời nhiều mây",
info,
sync: true,
};
// Build final payload depending on create vs update
const body: Model.FishingLog =
fishingLog?.status == 0
? ({
...base,
haul_lat: gpsData.lat,
haul_lon: gpsData.lon,
end_at: new Date(),
status: 1,
} as Model.FishingLog)
: ({
...base,
haul_lat: fishingLog?.haul_lat,
haul_lon: fishingLog?.haul_lon,
end_at: fishingLog?.end_at,
status: fishingLog?.status,
} as Model.FishingLog);
// console.log("Body: ", body);
const resp = await queryUpdateFishingLogs(body);
if (resp?.status === 200) {
showSuccessToast(
fishingLog?.fishing_log_id == null
? "Thêm mẻ cá thành công"
: "Cập nhật mẻ cá thành công"
);
getTrip();
onClose();
} else {
showErrorToast(
fishingLog?.fishing_log_id == null
? "Thêm mẻ cá thất bại"
: "Cập nhật mẻ cá thất bại"
);
}
} catch (err) {
console.error("onSubmit error:", err);
showErrorToast("Có lỗi xảy ra khi lưu mẻ cá");
}
}; };
// Initialize / reset form when modal visibility or haulData changes // Initialize / reset form when modal visibility or haulData changes
@@ -142,6 +220,7 @@ const CreateOrUpdateHaulModal: React.FC<CreateOrUpdateHaulModalProps> = ({
quantity: (h.catch_number as number) ?? 1, quantity: (h.catch_number as number) ?? 1,
unit: (h.catch_unit as Unit) ?? (defaultItem().unit as Unit), unit: (h.catch_unit as Unit) ?? (defaultItem().unit as Unit),
size: (h.fish_size as number) ?? undefined, size: (h.fish_size as number) ?? undefined,
sizeUnit: "cm" as SizeUnit,
})); }));
reset({ fish: mapped as any }); reset({ fish: mapped as any });
setIsCreateMode(false); setIsCreateMode(false);
@@ -157,9 +236,11 @@ const CreateOrUpdateHaulModal: React.FC<CreateOrUpdateHaulModalProps> = ({
}, [isVisible, fishingLog?.info, reset]); }, [isVisible, fishingLog?.info, reset]);
const renderRow = (item: any, index: number) => { const renderRow = (item: any, index: number) => {
const isExpanded = expandedFishIndices.includes(index); const isExpanded = expandedFishIndices.includes(index);
// Give expanded card highest zIndex, others get decreasing zIndex based on position
const cardZIndex = isExpanded ? 1000 : 100 - index;
return ( return (
<View key={item._id} style={styles.fishCard}> <View key={item._id} style={[styles.fishCard, { zIndex: cardZIndex }]}>
{/* Delete + Chevron buttons - top right corner */} {/* Delete + Chevron buttons - top right corner */}
<View <View
style={{ style={{
@@ -247,13 +328,13 @@ const CreateOrUpdateHaulModal: React.FC<CreateOrUpdateHaulModalProps> = ({
{/* Form - visible when expanded */} {/* Form - visible when expanded */}
{isExpanded && ( {isExpanded && (
<View style={{ paddingRight: 100 }}> <View style={{ paddingRight: 10 }}>
{/* Species dropdown */} {/* Species dropdown */}
<Controller <Controller
control={control} control={control}
name={`fish.${index}.id`} name={`fish.${index}.id`}
render={({ field: { value, onChange } }) => ( render={({ field: { value, onChange } }) => (
<View style={styles.fieldGroup}> <View style={[styles.fieldGroup, { marginTop: 20 }]}>
<Text style={styles.label}>Tên </Text> <Text style={styles.label}>Tên </Text>
<Select <Select
options={fishSpecies!.map((fish) => ({ options={fishSpecies!.map((fish) => ({
@@ -274,84 +355,117 @@ const CreateOrUpdateHaulModal: React.FC<CreateOrUpdateHaulModalProps> = ({
)} )}
/> />
{/* Quantity */} {/* Số lượng & Đơn vị cùng hàng */}
<Controller <View style={{ flexDirection: "row", gap: 12 }}>
control={control} <View style={{ flex: 1 }}>
name={`fish.${index}.quantity`} <Controller
render={({ field: { value, onChange, onBlur } }) => ( control={control}
<View style={styles.fieldGroup}> name={`fish.${index}.quantity`}
<Text style={styles.label}>Số lượng</Text> render={({ field: { value, onChange, onBlur } }) => (
<TextInput <View style={styles.fieldGroup}>
keyboardType="numeric" <Text style={styles.label}>Số lượng</Text>
value={String(value ?? "")} <TextInput
onBlur={onBlur} keyboardType="numeric"
onChangeText={(t) => value={String(value ?? "")}
onChange(Number(t.replace(/,/g, ".")) || 0) onBlur={onBlur}
} onChangeText={(t) =>
style={[styles.input, !isEditing && styles.inputDisabled]} onChange(Number(t.replace(/,/g, ".")) || 0)
editable={isEditing} }
/> style={[
{errors.fish?.[index]?.quantity && ( styles.input,
<Text style={styles.errorText}> !isEditing && styles.inputDisabled,
{errors.fish[index]?.quantity?.message as string} ]}
</Text> editable={isEditing}
/>
{errors.fish?.[index]?.quantity && (
<Text style={styles.errorText}>
{errors.fish[index]?.quantity?.message as string}
</Text>
)}
</View>
)} )}
</View> />
)} </View>
/> <View style={{ flex: 1 }}>
<Controller
control={control}
name={`fish.${index}.unit`}
render={({ field: { value, onChange } }) => (
<View style={styles.fieldGroup}>
<Text style={styles.label}>Đơn vị</Text>
<Select
options={UNITS_OPTIONS.map((unit) => ({
label: unit.label,
value: unit.value,
}))}
value={value}
onChange={onChange}
placeholder="Chọn đơn vị"
disabled={!isEditing}
listStyle={{ maxHeight: 100 }}
/>
{errors.fish?.[index]?.unit && (
<Text style={styles.errorText}>
{errors.fish[index]?.unit?.message as string}
</Text>
)}
</View>
)}
/>
</View>
</View>
{/* Unit dropdown */} {/* Size (optional) + Unit dropdown */}
<Controller <View style={{ flexDirection: "row", gap: 12 }}>
control={control} <View style={{ flex: 1 }}>
name={`fish.${index}.unit`} <Controller
render={({ field: { value, onChange } }) => ( control={control}
<View style={styles.fieldGroup}> name={`fish.${index}.size`}
<Text style={styles.label}>Đơn vị</Text> render={({ field: { value, onChange, onBlur } }) => (
<Select <View style={styles.fieldGroup}>
options={UNITS_OPTIONS.map((unit) => ({ <Text style={styles.label}>Kích thước</Text>
label: unit.label, <TextInput
value: unit.value, keyboardType="numeric"
}))} value={value ? String(value) : ""}
value={value} onBlur={onBlur}
onChange={onChange} onChangeText={(t) =>
placeholder="Chọn đơn vị" onChange(t ? Number(t.replace(/,/g, ".")) : undefined)
disabled={!isEditing} }
listStyle={{ maxHeight: 100 }} style={[
/> styles.input,
{errors.fish?.[index]?.unit && ( !isEditing && styles.inputDisabled,
<Text style={styles.errorText}> ]}
{errors.fish[index]?.unit?.message as string} editable={isEditing}
</Text> />
{errors.fish?.[index]?.size && (
<Text style={styles.errorText}>
{errors.fish[index]?.size?.message as string}
</Text>
)}
</View>
)} )}
</View> />
)} </View>
/> <View style={{ flex: 1 }}>
<Controller
{/* Size (optional) */} control={control}
<Controller name={`fish.${index}.sizeUnit`}
control={control} render={({ field: { value, onChange } }) => (
name={`fish.${index}.size`} <View style={styles.fieldGroup}>
render={({ field: { value, onChange, onBlur } }) => ( <Text style={styles.label}>Đơn vị</Text>
<View style={styles.fieldGroup}> <Select
<Text style={styles.label}>Kích thước (cm) tùy chọn</Text> options={SIZE_UNITS_OPTIONS}
<TextInput value={value}
keyboardType="numeric" onChange={onChange}
value={value ? String(value) : ""} placeholder="Chọn đơn vị"
onBlur={onBlur} disabled={!isEditing}
onChangeText={(t) => listStyle={{ maxHeight: 80 }}
onChange(t ? Number(t.replace(/,/g, ".")) : undefined) />
} </View>
style={[styles.input, !isEditing && styles.inputDisabled]}
editable={isEditing}
/>
{errors.fish?.[index]?.size && (
<Text style={styles.errorText}>
{errors.fish[index]?.size?.message as string}
</Text>
)} )}
</View> />
)} </View>
/> </View>
</View> </View>
)} )}
</View> </View>
@@ -379,15 +493,20 @@ const CreateOrUpdateHaulModal: React.FC<CreateOrUpdateHaulModalProps> = ({
<View style={styles.headerButtons}> <View style={styles.headerButtons}>
{isEditing ? ( {isEditing ? (
<> <>
<TouchableOpacity {!isCreateMode && (
onPress={() => { <TouchableOpacity
setIsEditing(false); onPress={() => {
reset(); // reset to previous values setIsEditing(false);
}} reset(); // reset to previous values
style={[styles.saveButton, { backgroundColor: "#6c757d" }]} }}
> style={[
<Text style={styles.saveButtonText}>Hủy</Text> styles.saveButton,
</TouchableOpacity> { backgroundColor: "#6c757d" },
]}
>
<Text style={styles.saveButtonText}>Hủy</Text>
</TouchableOpacity>
)}
<TouchableOpacity <TouchableOpacity
onPress={handleSubmit(onSubmit)} onPress={handleSubmit(onSubmit)}
style={styles.saveButton} style={styles.saveButton}

View File

@@ -2,6 +2,7 @@ import { api } from "@/config";
import { import {
API_GET_TRIP, API_GET_TRIP,
API_HAUL_HANDLE, API_HAUL_HANDLE,
API_UPDATE_FISHING_LOGS,
API_UPDATE_TRIP_STATUS, API_UPDATE_TRIP_STATUS,
} from "@/constants"; } from "@/constants";
@@ -16,3 +17,7 @@ export async function queryUpdateTripState(body: Model.TripUpdateStateRequest) {
export async function queryStartNewHaul(body: Model.NewFishingLogRequest) { export async function queryStartNewHaul(body: Model.NewFishingLogRequest) {
return api.put(API_HAUL_HANDLE, body); return api.put(API_HAUL_HANDLE, body);
} }
export async function queryUpdateFishingLogs(body: Model.FishingLog) {
return api.put(API_UPDATE_FISHING_LOGS, body);
}

View File

@@ -152,8 +152,8 @@ declare namespace Model {
interface FishingLog { interface FishingLog {
fishing_log_id: string; fishing_log_id: string;
trip_id: string; trip_id: string;
start_at: string; // ISO datetime start_at: Date; // ISO datetime
end_at: string; // ISO datetime end_at: Date; // ISO datetime
start_lat: number; start_lat: number;
start_lon: number; start_lon: number;
haul_lat: number; haul_lat: number;