Day 9 完了

実装内容:
1. backend/apps/fields/views.py - FieldViewSetをModelViewSetに変更(書き込み可能)
2. frontend/src/components/Navbar.tsx - 圃場管理リンク追加
3. frontend/src/app/fields/page.tsx - 圃場一覧画面
4. frontend/src/app/fields/new/page.tsx - 新規作成画面
5. frontend/src/app/fields/[id]/page.tsx - 編集画面
API CRUDテスト結果:
- POST /api/fields/ → 201 Created
- GET /api/fields/ → 200 OK
- PATCH /api/fields/{id}/ → 200 OK
- DELETE /api/fields/{id}/ → 204 No Content
ブラウザで http://localhost:3000/fields から圃場のCRUD操作が可能です。
次の工程に移りますか?
This commit is contained in:
Akira
2026-02-15 13:34:32 +09:00
parent afd434cd4c
commit 923dd5dece
5 changed files with 605 additions and 5 deletions

View File

@@ -8,7 +8,7 @@ from .models import OfficialKyosaiField, OfficialChusankanField, Field
from .serializers import FieldSerializer from .serializers import FieldSerializer
class FieldViewSet(viewsets.ReadOnlyModelViewSet): class FieldViewSet(viewsets.ModelViewSet):
queryset = Field.objects.all() queryset = Field.objects.all()
serializer_class = FieldSerializer serializer_class = FieldSerializer
permission_classes = [permissions.AllowAny] permission_classes = [permissions.AllowAny]

View File

@@ -0,0 +1,240 @@
'use client';
import { useState, useEffect } from 'react';
import { useRouter, useParams } from 'next/navigation';
import { api } from '@/lib/api';
import { Field } from '@/types';
import Navbar from '@/components/Navbar';
import { ArrowLeft, Save } from 'lucide-react';
export default function EditFieldPage() {
const router = useRouter();
const params = useParams();
const fieldId = parseInt(params.id as string);
const [loading, setLoading] = useState(true);
const [saving, setSaving] = useState(false);
const [error, setError] = useState('');
const [notFound, setNotFound] = useState(false);
const [formData, setFormData] = useState({
name: '',
address: '',
area_tan: '',
area_m2: '',
owner_name: '',
});
useEffect(() => {
fetchField();
}, [fieldId]);
const fetchField = async () => {
try {
const response = await api.get(`/fields/${fieldId}/`);
const field: Field = response.data;
setFormData({
name: field.name || '',
address: field.address || '',
area_tan: field.area_tan?.toString() || '',
area_m2: field.area_m2?.toString() || '',
owner_name: field.owner_name || '',
});
} catch (err: unknown) {
console.error('Failed to fetch field:', err);
const axiosError = err as { response?: { status?: number } };
if (axiosError.response?.status === 404) {
setNotFound(true);
}
} finally {
setLoading(false);
}
};
const handleChange = (e: React.ChangeEvent<HTMLInputElement>) => {
const { name, value } = e.target;
setFormData((prev) => ({ ...prev, [name]: value }));
};
const handleSubmit = async (e: React.FormEvent) => {
e.preventDefault();
setError('');
setSaving(true);
try {
const data = {
name: formData.name,
address: formData.address || null,
area_tan: formData.area_tan ? parseFloat(formData.area_tan) : null,
area_m2: formData.area_m2 ? parseInt(formData.area_m2) : null,
owner_name: formData.owner_name || null,
};
await api.patch(`/fields/${fieldId}/`, data);
router.push('/fields');
} catch (err: unknown) {
console.error('Failed to update field:', err);
setError('保存に失敗しました');
} finally {
setSaving(false);
}
};
if (loading) {
return (
<div className="min-h-screen bg-gray-50">
<Navbar />
<div className="flex items-center justify-center h-64">
<div className="text-gray-500">...</div>
</div>
</div>
);
}
if (notFound) {
return (
<div className="min-h-screen bg-gray-50">
<Navbar />
<div className="max-w-2xl mx-auto px-4 sm:px-6 lg:px-8 py-8">
<div className="bg-white rounded-lg shadow p-8 text-center">
<p className="text-gray-500"></p>
<button
onClick={() => router.push('/fields')}
className="mt-4 text-green-600 hover:text-green-700"
>
</button>
</div>
</div>
</div>
);
}
return (
<div className="min-h-screen bg-gray-50">
<Navbar />
<div className="max-w-2xl mx-auto px-4 sm:px-6 lg:px-8 py-8">
<div className="mb-6">
<button
onClick={() => router.push('/fields')}
className="flex items-center text-gray-600 hover:text-gray-900"
>
<ArrowLeft className="h-4 w-4 mr-2" />
</button>
</div>
<div className="bg-white rounded-lg shadow p-6">
<h1 className="text-2xl font-bold text-gray-900 mb-6"></h1>
{error && (
<div className="mb-4 p-3 text-sm text-red-600 bg-red-50 rounded-md">
{error}
</div>
)}
<form onSubmit={handleSubmit} className="space-y-4">
<div>
<label htmlFor="name" className="block text-sm font-medium text-gray-700 mb-1">
<span className="text-red-500">*</span>
</label>
<input
type="text"
id="name"
name="name"
value={formData.name}
onChange={handleChange}
required
className="w-full px-3 py-2 border border-gray-300 rounded-md focus:outline-none focus:ring-2 focus:ring-green-500"
placeholder="例A-1圃場"
/>
</div>
<div>
<label htmlFor="address" className="block text-sm font-medium text-gray-700 mb-1">
</label>
<input
type="text"
id="address"
name="address"
value={formData.address}
onChange={handleChange}
className="w-full px-3 py-2 border border-gray-300 rounded-md focus:outline-none focus:ring-2 focus:ring-green-500"
placeholder="例:山形県鶴岡市..."
/>
</div>
<div className="grid grid-cols-2 gap-4">
<div>
<label htmlFor="area_tan" className="block text-sm font-medium text-gray-700 mb-1">
()
</label>
<input
type="number"
step="0.0001"
id="area_tan"
name="area_tan"
value={formData.area_tan}
onChange={handleChange}
className="w-full px-3 py-2 border border-gray-300 rounded-md focus:outline-none focus:ring-2 focus:ring-green-500"
placeholder="例1.5"
/>
</div>
<div>
<label htmlFor="area_m2" className="block text-sm font-medium text-gray-700 mb-1">
(m2)
</label>
<input
type="number"
id="area_m2"
name="area_m2"
value={formData.area_m2}
onChange={handleChange}
className="w-full px-3 py-2 border border-gray-300 rounded-md focus:outline-none focus:ring-2 focus:ring-green-500"
placeholder="例1500"
/>
</div>
</div>
<div>
<label htmlFor="owner_name" className="block text-sm font-medium text-gray-700 mb-1">
</label>
<input
type="text"
id="owner_name"
name="owner_name"
value={formData.owner_name}
onChange={handleChange}
className="w-full px-3 py-2 border border-gray-300 rounded-md focus:outline-none focus:ring-2 focus:ring-green-500"
placeholder="例:山田太郎"
/>
</div>
<div className="pt-4">
<button
type="submit"
disabled={saving}
className="w-full flex items-center justify-center px-4 py-2 bg-green-600 text-white rounded-md hover:bg-green-700 disabled:opacity-50 disabled:cursor-not-allowed transition-colors"
>
{saving ? (
<>
<div className="animate-spin h-4 w-4 border-2 border-white border-t-transparent rounded-full mr-2" />
...
</>
) : (
<>
<Save className="h-4 w-4 mr-2" />
</>
)}
</button>
</div>
</form>
</div>
</div>
</div>
);
}

View File

@@ -0,0 +1,178 @@
'use client';
import { useState } from 'react';
import { useRouter } from 'next/navigation';
import { api } from '@/lib/api';
import Navbar from '@/components/Navbar';
import { ArrowLeft, Save } from 'lucide-react';
export default function NewFieldPage() {
const router = useRouter();
const [loading, setLoading] = useState(false);
const [error, setError] = useState('');
const [formData, setFormData] = useState({
name: '',
address: '',
area_tan: '',
area_m2: '',
owner_name: '',
});
const handleChange = (e: React.ChangeEvent<HTMLInputElement>) => {
const { name, value } = e.target;
setFormData((prev) => ({ ...prev, [name]: value }));
};
const handleSubmit = async (e: React.FormEvent) => {
e.preventDefault();
setError('');
setLoading(true);
try {
const data = {
name: formData.name,
address: formData.address || null,
area_tan: formData.area_tan ? parseFloat(formData.area_tan) : null,
area_m2: formData.area_m2 ? parseInt(formData.area_m2) : null,
owner_name: formData.owner_name || null,
};
await api.post('/fields/', data);
router.push('/fields');
} catch (err: unknown) {
console.error('Failed to create field:', err);
setError('保存に失敗しました');
} finally {
setLoading(false);
}
};
return (
<div className="min-h-screen bg-gray-50">
<Navbar />
<div className="max-w-2xl mx-auto px-4 sm:px-6 lg:px-8 py-8">
<div className="mb-6">
<button
onClick={() => router.push('/fields')}
className="flex items-center text-gray-600 hover:text-gray-900"
>
<ArrowLeft className="h-4 w-4 mr-2" />
</button>
</div>
<div className="bg-white rounded-lg shadow p-6">
<h1 className="text-2xl font-bold text-gray-900 mb-6"></h1>
{error && (
<div className="mb-4 p-3 text-sm text-red-600 bg-red-50 rounded-md">
{error}
</div>
)}
<form onSubmit={handleSubmit} className="space-y-4">
<div>
<label htmlFor="name" className="block text-sm font-medium text-gray-700 mb-1">
<span className="text-red-500">*</span>
</label>
<input
type="text"
id="name"
name="name"
value={formData.name}
onChange={handleChange}
required
className="w-full px-3 py-2 border border-gray-300 rounded-md focus:outline-none focus:ring-2 focus:ring-green-500"
placeholder="例A-1圃場"
/>
</div>
<div>
<label htmlFor="address" className="block text-sm font-medium text-gray-700 mb-1">
</label>
<input
type="text"
id="address"
name="address"
value={formData.address}
onChange={handleChange}
className="w-full px-3 py-2 border border-gray-300 rounded-md focus:outline-none focus:ring-2 focus:ring-green-500"
placeholder="例:山形県鶴岡市..."
/>
</div>
<div className="grid grid-cols-2 gap-4">
<div>
<label htmlFor="area_tan" className="block text-sm font-medium text-gray-700 mb-1">
()
</label>
<input
type="number"
step="0.0001"
id="area_tan"
name="area_tan"
value={formData.area_tan}
onChange={handleChange}
className="w-full px-3 py-2 border border-gray-300 rounded-md focus:outline-none focus:ring-2 focus:ring-green-500"
placeholder="例1.5"
/>
</div>
<div>
<label htmlFor="area_m2" className="block text-sm font-medium text-gray-700 mb-1">
(m2)
</label>
<input
type="number"
id="area_m2"
name="area_m2"
value={formData.area_m2}
onChange={handleChange}
className="w-full px-3 py-2 border border-gray-300 rounded-md focus:outline-none focus:ring-2 focus:ring-green-500"
placeholder="例1500"
/>
</div>
</div>
<div>
<label htmlFor="owner_name" className="block text-sm font-medium text-gray-700 mb-1">
</label>
<input
type="text"
id="owner_name"
name="owner_name"
value={formData.owner_name}
onChange={handleChange}
className="w-full px-3 py-2 border border-gray-300 rounded-md focus:outline-none focus:ring-2 focus:ring-green-500"
placeholder="例:山田太郎"
/>
</div>
<div className="pt-4">
<button
type="submit"
disabled={loading}
className="w-full flex items-center justify-center px-4 py-2 bg-green-600 text-white rounded-md hover:bg-green-700 disabled:opacity-50 disabled:cursor-not-allowed transition-colors"
>
{loading ? (
<>
<div className="animate-spin h-4 w-4 border-2 border-white border-t-transparent rounded-full mr-2" />
...
</>
) : (
<>
<Save className="h-4 w-4 mr-2" />
</>
)}
</button>
</div>
</form>
</div>
</div>
</div>
);
}

View File

@@ -0,0 +1,156 @@
'use client';
import { useState, useEffect } from 'react';
import { useRouter } from 'next/navigation';
import { api } from '@/lib/api';
import { Field } from '@/types';
import Navbar from '@/components/Navbar';
import { Plus, Pencil, Trash2 } from 'lucide-react';
export default function FieldsPage() {
const router = useRouter();
const [fields, setFields] = useState<Field[]>([]);
const [loading, setLoading] = useState(true);
const [deleting, setDeleting] = useState<number | null>(null);
useEffect(() => {
fetchFields();
}, []);
const fetchFields = async () => {
setLoading(true);
try {
const response = await api.get('/fields/');
setFields(response.data);
} catch (error) {
console.error('Failed to fetch fields:', error);
} finally {
setLoading(false);
}
};
const handleDelete = async (id: number) => {
if (!confirm('この圃場を削除してもよろしいですか?')) {
return;
}
setDeleting(id);
try {
await api.delete(`/fields/${id}/`);
await fetchFields();
} catch (error) {
console.error('Failed to delete field:', error);
alert('削除に失敗しました');
} finally {
setDeleting(null);
}
};
if (loading) {
return (
<div className="min-h-screen bg-gray-50">
<Navbar />
<div className="flex items-center justify-center h-64">
<div className="text-gray-500">...</div>
</div>
</div>
);
}
return (
<div className="min-h-screen bg-gray-50">
<Navbar />
<div className="max-w-7xl mx-auto px-4 sm:px-6 lg:px-8 py-8">
<div className="mb-6 flex items-center justify-between">
<h1 className="text-2xl font-bold text-gray-900"></h1>
<button
onClick={() => router.push('/fields/new')}
className="flex items-center px-4 py-2 bg-green-600 text-white rounded-md hover:bg-green-700 transition-colors"
>
<Plus className="h-4 w-4 mr-2" />
</button>
</div>
{fields.length === 0 ? (
<div className="bg-white rounded-lg shadow p-8 text-center">
<p className="text-gray-500"></p>
</div>
) : (
<div className="bg-white rounded-lg shadow overflow-hidden">
<div className="overflow-x-auto">
<table className="min-w-full divide-y divide-gray-200">
<thead className="bg-gray-50">
<tr>
<th className="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">
</th>
<th className="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">
</th>
<th className="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">
()
</th>
<th className="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">
(m2)
</th>
<th className="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">
</th>
<th className="px-6 py-3 text-right text-xs font-medium text-gray-500 uppercase tracking-wider">
</th>
</tr>
</thead>
<tbody className="bg-white divide-y divide-gray-200">
{fields.map((field) => (
<tr key={field.id} className="hover:bg-gray-50">
<td className="px-6 py-4 whitespace-nowrap">
<div className="text-sm font-medium text-gray-900">
{field.name}
</div>
</td>
<td className="px-6 py-4">
<div className="text-sm text-gray-500">
{field.address || '-'}
</div>
</td>
<td className="px-6 py-4 whitespace-nowrap text-sm text-gray-500">
{field.area_tan || '-'}
</td>
<td className="px-6 py-4 whitespace-nowrap text-sm text-gray-500">
{field.area_m2 || '-'}
</td>
<td className="px-6 py-4 whitespace-nowrap text-sm text-gray-500">
{field.owner_name || '-'}
</td>
<td className="px-6 py-4 whitespace-nowrap text-right text-sm font-medium">
<div className="flex justify-end space-x-2">
<button
onClick={() => router.push(`/fields/${field.id}`)}
className="text-blue-600 hover:text-blue-900 p-1"
title="編集"
>
<Pencil className="h-4 w-4" />
</button>
<button
onClick={() => handleDelete(field.id)}
disabled={deleting === field.id}
className="text-red-600 hover:text-red-900 p-1 disabled:opacity-50"
title="削除"
>
<Trash2 className="h-4 w-4" />
</button>
</div>
</td>
</tr>
))}
</tbody>
</table>
</div>
</div>
)}
</div>
</div>
);
}

View File

@@ -1,23 +1,49 @@
'use client'; 'use client';
import { useRouter } from 'next/navigation'; import { useRouter, usePathname } from 'next/navigation';
import { LogOut } from 'lucide-react'; import { LogOut, Wheat, MapPin } from 'lucide-react';
import { logout } from '@/lib/api'; import { logout } from '@/lib/api';
export default function Navbar() { export default function Navbar() {
const router = useRouter(); const router = useRouter();
const pathname = usePathname();
const handleLogout = () => { const handleLogout = () => {
logout(); logout();
}; };
const isActive = (path: string) => pathname === path;
return ( return (
<nav className="bg-white shadow-sm border-b border-gray-200"> <nav className="bg-white shadow-sm border-b border-gray-200">
<div className="max-w-7xl mx-auto px-4 sm:px-6 lg:px-8"> <div className="max-w-7xl mx-auto px-4 sm:px-6 lg:px-8">
<div className="flex justify-between h-16"> <div className="flex justify-between h-16">
<div className="flex items-center"> <div className="flex items-center space-x-8">
<h1 className="text-xl font-bold text-green-700">KeinaSystem</h1> <h1 className="text-xl font-bold text-green-700">KeinaSystem</h1>
<span className="ml-2 text-sm text-gray-500"></span> <div className="flex items-center space-x-4">
<button
onClick={() => router.push('/allocation')}
className={`flex items-center px-3 py-2 text-sm rounded-md transition-colors ${
isActive('/allocation')
? 'text-green-700 bg-green-50'
: 'text-gray-700 hover:text-gray-900 hover:bg-gray-100'
}`}
>
<Wheat className="h-4 w-4 mr-2" />
</button>
<button
onClick={() => router.push('/fields')}
className={`flex items-center px-3 py-2 text-sm rounded-md transition-colors ${
isActive('/fields') || pathname?.startsWith('/fields/')
? 'text-green-700 bg-green-50'
: 'text-gray-700 hover:text-gray-900 hover:bg-gray-100'
}`}
>
<MapPin className="h-4 w-4 mr-2" />
</button>
</div>
</div> </div>
<div className="flex items-center"> <div className="flex items-center">
<button <button