diff --git a/frontend/src/app/fertilizer/_components/FertilizerEditPage.tsx b/frontend/src/app/fertilizer/_components/FertilizerEditPage.tsx index 0b25f0a..e19a2f6 100644 --- a/frontend/src/app/fertilizer/_components/FertilizerEditPage.tsx +++ b/frontend/src/app/fertilizer/_components/FertilizerEditPage.tsx @@ -103,13 +103,41 @@ export default function FertilizerEditPage({ planId }: { planId?: number }) { const fields = fieldsRes.data.filter((f: Field) => fieldIds.includes(f.id)); setSelectedFields(fields); - // 保存済みの値は adjusted に復元(calc値はなし) + // 保存済みの値は adjusted に復元 const newAdjusted: Matrix = {}; plan.entries.forEach((e) => { if (!newAdjusted[e.field]) newAdjusted[e.field] = {}; newAdjusted[e.field][e.fertilizer] = String(e.bags); }); setAdjusted(newAdjusted); + + // 保存済み calc_settings でページ開時に自動計算してラベル用 calcMatrix を生成 + const validSettings = plan.calc_settings?.filter((s) => s.param) ?? []; + if (validSettings.length > 0 && fieldIds.length > 0) { + try { + const calcResults = await Promise.all( + validSettings.map((s) => + api.post('/fertilizer/calculate/', { + method: s.method, + param: parseFloat(s.param), + fertilizer_id: s.fertilizer_id, + field_ids: fieldIds, + }) + ) + ); + const newCalcMatrix: Matrix = {}; + validSettings.forEach((s, i) => { + const results: { field_id: number; bags: number }[] = calcResults[i].data; + results.forEach(({ field_id, bags }) => { + if (!newCalcMatrix[field_id]) newCalcMatrix[field_id] = {}; + newCalcMatrix[field_id][s.fertilizer_id] = String(bags); + }); + }); + setCalcMatrix(newCalcMatrix); + } catch { + // 自動計算失敗はサイレントに無視(ラベルなしで表示継続) + } + } } } catch (e: unknown) { const err = e as { response?: { status?: number; data?: unknown } }; @@ -255,13 +283,13 @@ export default function FertilizerEditPage({ planId }: { planId?: number }) { }); setRoundedColumns((prev) => { const next = new Set(prev); next.delete(fertId); return next; }); } else { - // 四捨五入: calc値を整数に丸めて adjusted に書き込む + // 四捨五入: calc値(なければ現在の入力値)を整数に丸めて adjusted に書き込む setAdjusted((prev) => { const next = { ...prev }; selectedFields.forEach((field) => { - const calc = calcMatrix[field.id]?.[fertId]; - if (calc !== undefined && calc !== '') { - const v = parseFloat(calc); + const raw = calcMatrix[field.id]?.[fertId] ?? prev[field.id]?.[fertId]; + if (raw !== undefined && raw !== '') { + const v = parseFloat(raw); if (!isNaN(v)) { if (!next[field.id]) next[field.id] = {}; next[field.id][fertId] = String(Math.round(v)); @@ -596,8 +624,8 @@ export default function FertilizerEditPage({ planId }: { planId?: number }) { {planFertilizers.map((fert) => { const calcVal = calcMatrix[field.id]?.[fert.id]; const adjVal = adjusted[field.id]?.[fert.id]; - // adjusted が設定されているときだけ灰色参照を表示(丸め後) - const showRef = adjVal !== undefined && calcVal !== undefined; + // 計算結果があればラベルを表示(adjusted が上書きされた場合は参照値として) + const showRef = calcVal !== undefined; // 入力欄: adjusted → calc値 → 空 const inputValue = adjVal !== undefined ? adjVal : (calcVal ?? ''); return (