diff --git a/.gitignore b/.gitignore new file mode 100644 index 0000000..5c10450 --- /dev/null +++ b/.gitignore @@ -0,0 +1,35 @@ +# ---------- ความลับ / ไฟล์ส่วนตัว (ห้ามขึ้น remote) ---------- +# ข้อความเรียกค่าไถ่ (ransomware note) — ไม่ใช่ไฟล์โปรเจกต์ +_readme.txt +# สัญญาจ้าง / เอกสารการเงินส่วนตัว +สัญญาจ้างทำของ.docx +สัญญาจ้างทำของ.pdf +การบริหารรายได้.docx +บัญชีกิจการ farm-planning/ +หลักฐานการโอนเงิน/ +หลักฐานสมัคร Affiliate/ +# compose ทดลองที่มีรหัสผ่าน plaintext +PWA-fam-plans/v.3.8.yaml +# ค่าตั้งที่มีรหัสฐานข้อมูล +service/.env +*.env +!*.env.example + +# ---------- ขยะ Windows / ไฟล์ชั่วคราว ---------- +desktop.ini +Thumbs.db +*.tmp +~WRL*.tmp +*~ +*.url +*.zip + +# ---------- สำเนาเทมเพลต / หน้าระบบอื่นที่เซฟไว้ (~48 MB) ---------- +แรงบันดาลใจ/ +start Bootstrap/ +startbootstrap-freelancer-gh-pages.zip +---/ + +# ---------- ระหว่างพัฒนา ---------- +*.log +.DS_Store diff --git a/AGENTS.md b/AGENTS.md index 8c778a3..4e2c3c1 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -28,6 +28,25 @@ node --test tests/*.test.mjs python -m http.server 8090 # แล้วเปิด http://localhost:8090 ตรวจด้วยตา 1 รอบ ``` +## บริการ API (Julia + PostgreSQL) + +```bash +# ติดตั้ง dependency ครั้งแรก +julia --project=service -e 'using Pkg; Pkg.add(["HTTP","JSON3","LibPQ"])' + +# รัน API (ค่า env อยู่ใน service/.env — คัดลอกจาก .env.example แล้วใส่รหัสเอง) +julia --project=service service/src/server.jl # http://127.0.0.1:8000 + +# ทดสอบสูตรทั้งสองฝั่ง (ต้องได้เลขตรงกันตาม golden vectors) +julia --project=service service/test/runtests.jl +node --test tests/*.test.mjs +``` + +- สูตรอยู่ที่ `service/src/formulas.jl` (แหล่งความจริง) — `core/*.js` เป็นตัวสำรองตอนออฟไลน์ +- แก้สูตร = แก้ 3 ที่พร้อมกัน: `core/*.js`, `service/src/formulas.jl`, `tests/golden/vectors.json` +- สคีมา DB: `service/db/001_init.sql` · สัญญา API: `service/openapi.yaml` +- ห้าม commit `service/.env` (มีรหัส DB) + ## อัปเดตเวอร์ชัน — ห้ามแก้มือทีละไฟล์ ```bash diff --git a/service/.env.example b/service/.env.example new file mode 100644 index 0000000..5322e32 --- /dev/null +++ b/service/.env.example @@ -0,0 +1,19 @@ +# .env.example — คัดลอกเป็น service/.env แล้วใส่ค่าจริงเอง (ห้าม commit .env) +# ห้ามส่งรหัสผ่านผ่านแชท/แชทบอท — ใส่ในไฟล์นี้ในเครื่องคุณเท่านั้น + +# ---- PostgreSQL ---- +FARM_DB_HOST=localhost +FARM_DB_PORT=5432 +FARM_DB_NAME=farm_planning +FARM_DB_USER=postgres +FARM_DB_PASSWORD= + +# ---- API ---- +FARM_API_HOST=127.0.0.1 +FARM_API_PORT=8000 + +# เปิด CORS ให้เว็บ static ที่รันคนละพอร์ต (ตอนพัฒนา) +FARM_CORS_ORIGIN=http://localhost:8090 + +# ปิดการเขียน DB ชั่วคราวได้ (เช่น ตอน demo ออฟไลน์) +FARM_PERSIST_RUNS=true diff --git a/service/Manifest.toml b/service/Manifest.toml new file mode 100644 index 0000000..49e7607 --- /dev/null +++ b/service/Manifest.toml @@ -0,0 +1,484 @@ +# This file is machine-generated - editing it directly is not advised + +julia_version = "1.13.4" +manifest_format = "2.1" +project_hash = "b119028bf67d4cbacd5ab03b83bae663cb1bb894" + +[[deps.ArgTools]] +uuid = "0dad84c5-d112-42e6-8d28-ef12dabb789f" +version = "1.1.2" + +[[deps.ArrowTypes]] +deps = ["Sockets", "UUIDs"] +git-tree-sha1 = "404265cd8128a2515a81d5eae16de90fdef05101" +registries = "General" +uuid = "31f734f8-188a-4ce0-8406-c8a06bd891cd" +version = "2.3.0" + +[[deps.Artifacts]] +uuid = "56f22d72-fd6d-98f1-02f0-08ddc0907c33" +version = "1.11.0" + +[[deps.Base64]] +uuid = "2a0f44e3-6c83-55bd-87e4-b1978d98bd5f" +version = "1.11.0" + +[[deps.CEnum]] +git-tree-sha1 = "389ad5c84de1ae7cf0e28e381131c98ea87d54fc" +registries = "General" +uuid = "fa961155-64e5-5f13-b03f-caf6b980ea82" +version = "0.5.0" + +[[deps.CodecZlib]] +deps = ["TranscodingStreams", "Zlib_jll"] +git-tree-sha1 = "970758a3d591a2a5c2a907c53f2e2f8c1b1d3537" +registries = "General" +uuid = "944b1d66-785c-5afd-91f1-9de20f533193" +version = "0.7.9" + +[[deps.Compat]] +deps = ["TOML", "UUIDs"] +git-tree-sha1 = "9d8a54ce4b17aa5bdce0ea5c34bc5e7c340d16ad" +registries = "General" +uuid = "34da2185-b29b-5c13-b0c7-acf172513d20" +version = "4.18.1" + + [deps.Compat.extensions] + CompatLinearAlgebraExt = "LinearAlgebra" + + [deps.Compat.weakdeps] + Dates = "ade2ca70-3891-5945-98fb-dc099432e06a" + LinearAlgebra = "37e2e46d-f89d-539d-b4ee-838fcccc9c8e" + +[[deps.CompilerSupportLibraries_jll]] +deps = ["Artifacts", "Libdl"] +uuid = "e66e0078-7015-5450-92f7-15fbd957f2ae" +version = "1.5.5+2" + +[[deps.DBInterface]] +git-tree-sha1 = "3b22439978973353092e8782275c59e62f611e3b" +registries = "General" +uuid = "a10d1c49-ce27-4219-8d33-6db1a4562965" +version = "2.8.0" + +[[deps.DataAPI]] +git-tree-sha1 = "abe83f3a2f1b857aac70ef8b269080af17764bbe" +registries = "General" +uuid = "9a962f9c-6df0-11e9-0e5d-c546b8b5ee8a" +version = "1.16.0" + +[[deps.DataValueInterfaces]] +git-tree-sha1 = "bfc1187b79289637fa0ef6d4436ebdfe6905cbd6" +registries = "General" +uuid = "e2d170a0-9d28-54be-80f0-106bbe20a464" +version = "1.0.0" + +[[deps.Dates]] +deps = ["Printf"] +uuid = "ade2ca70-3891-5945-98fb-dc099432e06a" +version = "1.11.0" + +[[deps.Decimals]] +git-tree-sha1 = "e98abef36d02a0ec385d68cd7dadbce9b28cbd88" +registries = "General" +uuid = "abce61dc-4473-55a0-ba07-351d65e31d42" +version = "0.4.1" + +[[deps.Distributed]] +deps = ["Random", "Serialization", "Sockets"] +uuid = "8ba89e20-285c-5b6f-9357-94700520ee1b" +version = "1.11.0" + +[[deps.DocStringExtensions]] +git-tree-sha1 = "7442a5dfe1ebb773c29cc2962a8980f47221d76c" +registries = "General" +uuid = "ffbed154-4ef7-542d-bbb7-c09d3a79fcae" +version = "0.9.5" + +[[deps.Downloads]] +deps = ["ArgTools", "FileWatching", "LibCURL", "NetworkOptions"] +uuid = "f43a241f-c20a-4ad4-852c-f6b1247861c6" +version = "1.7.0" + +[[deps.EnumX]] +git-tree-sha1 = "c49898e8438c828577f04b92fc9368c388ac783c" +registries = "General" +uuid = "4e289a0a-7415-4d19-859d-a7e5c4648b56" +version = "1.0.7" + +[[deps.ExprTools]] +git-tree-sha1 = "d2e49e7efd29719d6f28b891b0e0e159daa9d2b4" +registries = "General" +uuid = "e2ba6199-217a-4e67-a87a-7c52f15ade04" +version = "0.1.11" + +[[deps.FileWatching]] +uuid = "7b1f6079-737a-58dc-b8bc-7a2ca5c1b5ee" +version = "1.11.0" + +[[deps.HTTP]] +deps = ["Base64", "CodecZlib", "Dates", "EnumX", "Logging", "PrecompileTools", "Random", "Reseau", "SHA", "TranscodingStreams", "URIs", "UUIDs", "Zlib_jll"] +git-tree-sha1 = "48d59dc5887b523cc3c6d388f3ce79e51b67cc48" +registries = "General" +uuid = "cd3eb016-35fb-5094-929b-558a96fad6f3" +version = "2.16.0" + +[[deps.ICU_jll]] +deps = ["Artifacts", "JLLWrappers", "Libdl"] +git-tree-sha1 = "b3d8be712fbf9237935bde0ce9b5a736ae38fc34" +registries = "General" +uuid = "a51ab1cf-af8e-5615-a023-bc2c838bba6b" +version = "76.2.0+0" + +[[deps.Infinity]] +deps = ["Dates", "Random", "Requires"] +git-tree-sha1 = "cf8234411cbeb98676c173f930951ea29dca3b23" +registries = "General" +uuid = "a303e19e-6eb4-11e9-3b09-cd9505f79100" +version = "0.2.4" + +[[deps.InlineStrings]] +git-tree-sha1 = "6e0a59a838f58259f49474e913e39c23e8ca1366" +registries = "General" +uuid = "842dd82b-1e85-43dc-bf29-5d0ee9dffc48" +version = "2.0.1" +weakdeps = ["ArrowTypes", "Parsers", "Serialization"] + + [deps.InlineStrings.extensions] + ArrowTypesExt = "ArrowTypes" + ParsersExt = "Parsers" + SerializationExt = "Serialization" + +[[deps.InteractiveUtils]] +deps = ["Markdown"] +uuid = "b77e0a4c-d291-57a0-90e8-8db25a27a240" +version = "1.11.0" + +[[deps.Intervals]] +deps = ["ArrowTypes", "Dates", "Printf", "RecipesBase", "Serialization", "TimeZones"] +git-tree-sha1 = "d6fe00b123e32ddd17231b35d69a6394e696fd5a" +registries = "General" +uuid = "d8418881-c3e1-53bb-8760-2df7ec849ed5" +version = "1.11.0" + +[[deps.IterTools]] +git-tree-sha1 = "123311cf9834c6ee6a8347bba9af68f255615391" +registries = "General" +uuid = "c8e1da08-722c-5040-9ed9-7db0dc04731e" +version = "1.11.0" + +[[deps.IteratorInterfaceExtensions]] +git-tree-sha1 = "a3f24677c21f5bbe9d2a714f95dcd58337fb2856" +registries = "General" +uuid = "82899510-4779-5014-852e-03e436cf321d" +version = "1.0.0" + +[[deps.JLLWrappers]] +deps = ["Artifacts", "Preferences"] +git-tree-sha1 = "7204148362dafe5fe6a273f855b8ccbe4df8173e" +registries = "General" +uuid = "692b3bcd-3c85-4b1f-b108-f13ce0eb3210" +version = "1.8.0" + +[[deps.JSON3]] +deps = ["Dates", "Mmap", "Parsers", "PrecompileTools", "StructTypes", "UUIDs"] +git-tree-sha1 = "34a52631602d7233eb1dca1a358ae82b656f9f2a" +registries = "General" +uuid = "0f8b85d8-7281-11e9-16c2-39a750bddbf1" +version = "1.14.4" +weakdeps = ["ArrowTypes"] + + [deps.JSON3.extensions] + JSON3ArrowExt = ["ArrowTypes"] + +[[deps.JuliaSyntaxHighlighting]] +deps = ["StyledStrings"] +uuid = "ac6e5ff7-fb65-4e79-a425-ec3bc9c03011" +version = "1.12.0" + +[[deps.Kerberos_krb5_jll]] +deps = ["Artifacts", "JLLWrappers", "Libdl"] +git-tree-sha1 = "0f2899fdadaab4b8f57db558ba21bdb4fb52f1f0" +registries = "General" +uuid = "b39eb1a6-c29a-53d7-8c32-632cd16f18da" +version = "1.21.3+0" + +[[deps.LayerDicts]] +git-tree-sha1 = "6087ad3521d6278ebe5c27ae55e7bbb15ca312cb" +registries = "General" +uuid = "6f188dcb-512c-564b-bc01-e0f76e72f166" +version = "1.0.0" + +[[deps.LibCURL]] +deps = ["LibCURL_jll", "MozillaCACerts_jll"] +uuid = "b27032c2-a3e7-50c8-80cd-2d36dbcbfd21" +version = "1.0.0" + +[[deps.LibCURL_jll]] +deps = ["Artifacts", "CompilerSupportLibraries_jll", "LibSSH2_jll", "Libdl", "OpenSSL_jll", "Zlib_jll", "Zstd_jll", "nghttp2_jll"] +uuid = "deac9b47-8bc7-5906-a0fe-35ac56dc84c0" +version = "8.22.0+0" + +[[deps.LibPQ]] +deps = ["CEnum", "DBInterface", "Dates", "Decimals", "DocStringExtensions", "FileWatching", "Infinity", "Intervals", "IterTools", "LayerDicts", "LibPQ_jll", "Libdl", "Memento", "OffsetArrays", "SQLStrings", "Tables", "TimeZones", "UTCDateTimes"] +git-tree-sha1 = "3d227cd13cbf1e9a54d7748dab33e078da6f9168" +registries = "General" +uuid = "194296ae-ab2e-5f79-8cd4-7183a0a5a0d1" +version = "1.18.0" + +[[deps.LibPQ_jll]] +deps = ["Artifacts", "ICU_jll", "JLLWrappers", "Kerberos_krb5_jll", "Libdl", "OpenSSL_jll", "Zstd_jll"] +git-tree-sha1 = "c692057e05ba6da348bc45d5dab8c7a2c88da518" +registries = "General" +uuid = "08be9ffa-1c94-5ee5-a977-46a84ec9b350" +version = "16.14.0+0" + +[[deps.LibSSH2_jll]] +deps = ["Artifacts", "CompilerSupportLibraries_jll", "Libdl", "OpenSSL_jll", "Zlib_jll"] +uuid = "29816b5a-b9ab-546f-933c-edad1886dfa8" +version = "1.11.104+0" + +[[deps.Libdl]] +uuid = "8f399da3-3557-5675-b5ff-fb832c97cbdb" +version = "1.11.0" + +[[deps.Logging]] +uuid = "56ddb016-857b-54e1-b83d-db4d58db5568" +version = "1.11.0" + +[[deps.Markdown]] +deps = ["Base64", "JuliaSyntaxHighlighting", "StyledStrings"] +uuid = "d6f4376e-aef5-505a-96c1-9c027394607a" +version = "1.11.0" + +[[deps.Memento]] +deps = ["Dates", "Distributed", "Requires", "Serialization", "Sockets", "Test", "UUIDs"] +git-tree-sha1 = "e03a25cb3b6569623f8246d3d8b3faa7ce86f4ad" +registries = "General" +uuid = "f28f55f0-a522-5efc-85c2-fe41dfb9b2d9" +version = "1.5.0" + +[[deps.Mmap]] +uuid = "a63ad114-7e13-5084-954f-fe012c677804" +version = "1.11.0" + +[[deps.Mocking]] +deps = ["Compat", "ExprTools"] +git-tree-sha1 = "2c140d60d7cb82badf06d8783800d0bcd1a7daa2" +registries = "General" +uuid = "78c3b35d-d492-501b-9361-3d52fe80e533" +version = "0.8.1" + +[[deps.MozillaCACerts_jll]] +uuid = "14a3606d-f60d-562e-9121-12d972cd8159" +version = "2026.11.5" + +[[deps.NetworkOptions]] +uuid = "ca575930-c2e3-43a9-ace4-1e988b2c1908" +version = "1.3.0" + +[[deps.OffsetArrays]] +git-tree-sha1 = "750d0f2b5aac238d50dfee5f7a44fae3175a3305" +registries = "General" +uuid = "6fe1bfb0-de20-5000-8ca7-80f57d26f881" +version = "1.18.0" + + [deps.OffsetArrays.extensions] + OffsetArraysAdaptExt = "Adapt" + + [deps.OffsetArrays.weakdeps] + Adapt = "79e6a3ab-5dfb-504d-930d-738a2a938a0e" + +[[deps.OpenSSL_jll]] +deps = ["Artifacts", "Libdl"] +uuid = "458c3c95-2e84-50aa-8efc-19380b2a3a95" +version = "3.5.8+0" + +[[deps.OrderedCollections]] +git-tree-sha1 = "b079a6affebde167dad8ffe0d670b53917fbcb68" +registries = "General" +uuid = "bac558e1-5e72-5ebc-8fee-abe8a469f55d" +version = "2.0.3" + +[[deps.Parsers]] +deps = ["Dates", "PrecompileTools", "UUIDs"] +git-tree-sha1 = "2facd7b5863092567d54590997caf8f6db8e0b1e" +registries = "General" +uuid = "69de0a69-1ddd-5017-9359-2bf0b02dc9f0" +version = "2.8.11" + +[[deps.PrecompileTools]] +deps = ["Preferences"] +git-tree-sha1 = "1e697ad6f68af89cd3651bbe9b4a7b5d800adf5a" +registries = "General" +uuid = "aea7be01-6a6a-4083-8856-8a6e6704d82a" +version = "1.4.0" + +[[deps.Preferences]] +deps = ["TOML"] +git-tree-sha1 = "aef1987d90dcc2e2cbd919ad10b2d25bcce4f418" +registries = "General" +uuid = "21216c6a-2e73-6563-6e65-726566657250" +version = "1.6.1" + +[[deps.Printf]] +deps = ["Unicode"] +uuid = "de0858da-6303-5e67-8744-51eddeeeb8d7" +version = "1.11.0" + +[[deps.Random]] +deps = ["SHA"] +uuid = "9a3f8284-a2c9-5f02-9a11-845980a1fd5c" +version = "1.11.0" + +[[deps.RecipesBase]] +deps = ["PrecompileTools"] +git-tree-sha1 = "0c0dcffc464cda2ff33fc8ffc1dd1bdd53cd98be" +registries = "General" +uuid = "3cdcf5f2-1ef4-517c-9805-6587b60abb01" +version = "1.4.0" + +[[deps.Requires]] +deps = ["UUIDs"] +git-tree-sha1 = "62389eeff14780bfe55195b7204c0d8738436d64" +registries = "General" +uuid = "ae029012-a4dd-5104-9daa-d747884805df" +version = "1.3.1" + +[[deps.Reseau]] +deps = ["NetworkOptions", "OpenSSL_jll", "PrecompileTools", "Random", "SHA"] +git-tree-sha1 = "1c73ca688c4bae68dac5cfc13427c70e285f0a79" +registries = "General" +uuid = "802f3686-a58f-41ce-bb0c-3c43c75bba36" +version = "1.7.0" + +[[deps.SHA]] +uuid = "ea8e919c-243c-51af-8825-aaa63cd721ce" +version = "1.0.0" + +[[deps.SQLStrings]] +git-tree-sha1 = "55de0530689832b1d3d43491ee6b67bd54d3323c" +registries = "General" +uuid = "af517c2e-c243-48fa-aab8-efac3db270f5" +version = "0.1.0" + +[[deps.Scratch]] +deps = ["Dates"] +git-tree-sha1 = "9b81b8393e50b7d4e6d0a9f14e192294d3b7c109" +registries = "General" +uuid = "6c6a2e73-6563-6170-7368-637461726353" +version = "1.3.0" + +[[deps.Serialization]] +uuid = "9e88b42a-f829-5b0c-bbe9-9e923198166b" +version = "1.11.0" + +[[deps.Sockets]] +uuid = "6462fe0b-24de-5631-8697-dd941f90decc" +version = "1.11.0" + +[[deps.StructTypes]] +deps = ["Dates", "UUIDs"] +git-tree-sha1 = "fd6a55e88450cb4256e49103a5a243f065c7b781" +registries = "General" +uuid = "856f2bd8-1eba-4b0a-8007-ebc267875bd4" +version = "1.11.1" + +[[deps.StyledStrings]] +uuid = "f489334b-da3d-4c2e-b8f0-e476e12c162b" +version = "1.11.0" + +[[deps.TOML]] +deps = ["Dates"] +uuid = "fa267f1f-6049-4f14-aa54-33bafae1ed76" +version = "1.0.3" + +[[deps.TZJData]] +deps = ["Artifacts"] +git-tree-sha1 = "17e108908f841e0f1f607d8d9b7af9b7037879b1" +registries = "General" +uuid = "dc5dba14-91b3-4cab-a142-028a31da12f7" +version = "1.12.0+2026f" + +[[deps.TableTraits]] +deps = ["IteratorInterfaceExtensions"] +git-tree-sha1 = "c06b2f539df1c6efa794486abfb6ed2022561a39" +registries = "General" +uuid = "3783bdb8-4a98-5b6b-af9a-565f29a5fe9c" +version = "1.0.1" + +[[deps.Tables]] +deps = ["DataAPI", "DataValueInterfaces", "IteratorInterfaceExtensions", "OrderedCollections", "TableTraits"] +git-tree-sha1 = "a94d9bdda1b7bed0046cea645639ab3f62196fac" +registries = "General" +uuid = "bd369af6-aec1-5ad0-b16a-f7cc5008161c" +version = "1.14.0" + +[[deps.Test]] +deps = ["InteractiveUtils", "Logging", "Random", "Serialization"] +uuid = "8dfed614-e22c-5e08-85e1-65c5234f0b40" +version = "1.11.0" + +[[deps.TimeZones]] +deps = ["Artifacts", "Dates", "Downloads", "InlineStrings", "Mocking", "Printf", "Scratch", "TZJData", "Unicode", "p7zip_jll"] +git-tree-sha1 = "0306ccbb2891bad73bd38bd28c2d0987aa532a5e" +registries = "General" +uuid = "f269a46b-ccf7-5d73-abea-4c690281aa53" +version = "1.22.4" +weakdeps = ["RecipesBase"] + + [deps.TimeZones.extensions] + TimeZonesRecipesBaseExt = "RecipesBase" + +[[deps.TranscodingStreams]] +git-tree-sha1 = "0c45878dcfdcfa8480052b6ab162cdd138781742" +registries = "General" +uuid = "3bb67fe8-82b1-5028-8e26-92a6c54297fa" +version = "0.11.3" + +[[deps.URIs]] +deps = ["Serialization"] +git-tree-sha1 = "eb3b85ca904a1d1647b15acc091b113b8874b648" +registries = "General" +uuid = "5c2747f8-b7ea-4ff2-ba2e-563bfd36b1d4" +version = "1.7.3" + +[[deps.UTCDateTimes]] +deps = ["Dates", "TimeZones"] +git-tree-sha1 = "4af3552bf0cf4a071bf3d14bd20023ea70f31b62" +registries = "General" +uuid = "0f7cfa37-7abf-4834-b969-a8aa512401c2" +version = "1.6.1" + +[[deps.UUIDs]] +deps = ["Random", "SHA"] +uuid = "cf7118a7-6976-5b1a-9a39-7adc72f591a4" +version = "1.11.0" + +[[deps.Unicode]] +uuid = "4ec0a83e-493e-50e2-b9ac-8f72acf5a8f5" +version = "1.11.0" + +[[deps.Zlib_jll]] +deps = ["Libdl"] +uuid = "83775a58-1f1d-513f-b197-d71354ab007a" +version = "1.3.2+0" + +[[deps.Zstd_jll]] +deps = ["CompilerSupportLibraries_jll", "Libdl"] +uuid = "3161d3a3-bdf6-5164-811a-617609db77b4" +version = "1.5.7+1" + +[[deps.nghttp2_jll]] +deps = ["Artifacts", "CompilerSupportLibraries_jll", "Libdl"] +uuid = "8e850ede-7688-5339-a07c-302acd2aaf8d" +version = "1.70.0+0" + +[[deps.p7zip_jll]] +deps = ["Artifacts", "CompilerSupportLibraries_jll", "Libdl"] +uuid = "3f19e933-33d8-53b3-aaab-bd5110c3b7a0" +version = "17.8.5+0" + +[registries.General] +url = "https://github.com/JuliaRegistries/General.git" +uuid = "23338594-aafe-5451-b93e-139f81909106" diff --git a/service/Project.toml b/service/Project.toml new file mode 100644 index 0000000..78dd37e --- /dev/null +++ b/service/Project.toml @@ -0,0 +1,4 @@ +[deps] +HTTP = "cd3eb016-35fb-5094-929b-558a96fad6f3" +JSON3 = "0f8b85d8-7281-11e9-16c2-39a750bddbf1" +LibPQ = "194296ae-ab2e-5f79-8cd4-7183a0a5a0d1" diff --git a/service/README.md b/service/README.md new file mode 100644 index 0000000..f4a3c69 --- /dev/null +++ b/service/README.md @@ -0,0 +1,78 @@ +# service — farm-planning API (Julia + PostgreSQL) + +คำนวณสูตรทั้งหมดด้วย Julia แล้วคุยกับเว็บผ่าน HTTP/JSON · สูตรชุดเดียวกับ `core/*.js` +โดยมี **golden vectors** (`tests/golden/vectors.json`) บังคับให้สองฝั่งได้เลขตรงกัน + +## ต้องมีอะไรก่อน + +| ของ | เวอร์ชัน | หมายเหตุ | +|---|---|---| +| Julia | 1.10+ | `winget install --id Julialang.Julia -e` | +| PostgreSQL | 14+ | เครื่องนี้มี 17 อยู่แล้ว (พอร์ต 5432) | + +## 1) เตรียมฐานข้อมูล + +```bash +# สร้างฐาน (ใช้ psql ของ PostgreSQL 17) +"/c/Program Files/PostgreSQL/17/bin/createdb.exe" -U postgres farm_planning +"/c/Program Files/PostgreSQL/17/bin/psql.exe" -U postgres -d farm_planning -f service/db/001_init.sql +``` + +## 2) ตั้งค่า + +```bash +cp service/.env.example service/.env +# แล้วแก้ FARM_DB_PASSWORD ใน service/.env เอง (ห้าม commit ไฟล์นี้) +``` + +ถ้าไม่ตั้งรหัส → service ยังรันได้ แต่ **ไม่บันทึกผลลง DB** และ `/api/v1/health` จะบอกว่าฐานข้อมูลไม่ได้เชื่อม + +## 3) ติดตั้ง dependency ของ Julia (ครั้งแรกครั้งเดียว) + +```bash +julia --project=service -e 'using Pkg; Pkg.add(["HTTP","JSON3","LibPQ"])' +``` + +## 4) รัน + +```bash +julia --project=service service/src/server.jl +# ฟังที่ http://127.0.0.1:8000 +``` + +ตรวจว่าใช้งานได้: + +```bash +curl -s http://127.0.0.1:8000/api/v1/health +curl -s -X POST http://127.0.0.1:8000/api/v1/waters/calculate/plant \ + -H 'Content-Type: application/json' \ + -d '{"eto_mm_per_day":3.71,"crop_coefficient":1.0,"area_rai":10,"irrigation_efficiency_percent":75}' +# → value 79.15 (ตรงกับ core/crop_water.js) +``` + +## 5) ทดสอบสูตร (ต้องผ่านทั้งสองฝั่ง) + +```bash +julia --project=service service/test/runtests.jl # ฝั่ง Julia +node --test tests/*.test.mjs # ฝั่ง JS (รวม golden vectors) +``` + +## ไฟล์ + +``` +service/ +├── src/formulas.jl สูตร pure function (ไม่มี DB/HTTP) — แหล่งความจริง +├── src/db.jl LibPQ + บันทึก calculation_runs +├── src/server.jl HTTP.jl router + CORS + JSON +├── db/001_init.sql สคีมา (calculation_runs, provinces, eto_monthly, view) +├── test/runtests.jl ทดสอบด้วย golden vectors ชุดเดียวกับ JS +├── openapi.yaml สัญญา API +└── .env.example ค่าที่ต้องตั้ง (คัดลอกเป็น .env เอง) +``` + +## กติกา + +- **ห้ามเขียนสูตรซ้ำใน `server.jl`** — เรียก `Formulas` เท่านั้น +- แก้สูตร → แก้ `core/*.js` + `service/src/formulas.jl` + `tests/golden/vectors.json` พร้อมกัน แล้วรัน test ทั้งสองฝั่ง +- เพิ่ม field ในผลลัพธ์ = เพิ่มใน `openapi.yaml` ด้วย +- ค่าที่ผิด (<= 0, เกิน 100%) ต้องตอบ 400 พร้อมข้อความภาษาไทย ไม่ใช่ 500 diff --git a/service/db/001_init.sql b/service/db/001_init.sql new file mode 100644 index 0000000..7d251f2 --- /dev/null +++ b/service/db/001_init.sql @@ -0,0 +1,59 @@ +-- 001_init.sql — สคีมาเริ่มต้นของ farm-planning API (PostgreSQL 17) +-- ใช้: psql -U -d farm_planning -f service/db/001_init.sql +-- หลักการ: เก็บ "ทุกครั้งที่คำนวณ" แบบ append-only (input + result เป็น jsonb) +-- ห้ามแก้ผลเก่า — ถ้าสูตรเปลี่ยนให้เพิ่ม formula_version ในแถวใหม่ + +BEGIN; + +CREATE EXTENSION IF NOT EXISTS pgcrypto; -- gen_random_uuid() + +-- --------------------------------------------------------------- +-- 1) ผลการคำนวณทุกครั้ง (audit trail + ใช้ทำ golden test ได้) +-- --------------------------------------------------------------- +CREATE TABLE IF NOT EXISTS calculation_runs ( + run_id uuid PRIMARY KEY DEFAULT gen_random_uuid(), + calculation_kind text NOT NULL, -- 'crop_water' | 'reservoir' + input_payload jsonb NOT NULL, + result_payload jsonb NOT NULL, + formula_version text NOT NULL DEFAULT '1.0', + engine text NOT NULL DEFAULT 'julia', -- julia | js-offline + client_version text, -- build ของเว็บที่เรียก + created_at timestamptz NOT NULL DEFAULT now(), + CONSTRAINT calculation_kind_known + CHECK (calculation_kind IN ('crop_water', 'reservoir')) +); + +CREATE INDEX IF NOT EXISTS calculation_runs_kind_created_idx + ON calculation_runs (calculation_kind, created_at DESC); + +-- --------------------------------------------------------------- +-- 2) ข้อมูลอ้างอิง: ETo รายจังหวัด (โหลดจาก data/climate/eto_by_region.json) +-- --------------------------------------------------------------- +CREATE TABLE IF NOT EXISTS provinces ( + province_id serial PRIMARY KEY, + region_id text NOT NULL, + region_name_th text NOT NULL, + province_name_th text NOT NULL, + UNIQUE (region_id, province_name_th) +); + +CREATE TABLE IF NOT EXISTS eto_monthly ( + province_id int NOT NULL REFERENCES provinces (province_id) ON DELETE CASCADE, + month_number smallint NOT NULL CHECK (month_number BETWEEN 1 AND 12), + eto_mm_per_day numeric(6, 3) NOT NULL CHECK (eto_mm_per_day > 0), + source_reference text, + PRIMARY KEY (province_id, month_number) +); + +-- --------------------------------------------------------------- +-- 3) มุมมองสรุปการใช้งาน (ไม่บังคับ ใช้ตอนตรวจ) +-- --------------------------------------------------------------- +CREATE OR REPLACE VIEW calculation_runs_daily AS +SELECT calculation_kind, + date_trunc('day', created_at) AS run_date, + count(*) AS runs +FROM calculation_runs +GROUP BY 1, 2 +ORDER BY 2 DESC; + +COMMIT; diff --git a/service/openapi.yaml b/service/openapi.yaml new file mode 100644 index 0000000..aa2fcfa --- /dev/null +++ b/service/openapi.yaml @@ -0,0 +1,127 @@ +openapi: 3.1.0 +info: + title: farm-planning API + version: 1.0.0 + description: > + คำนวณความต้องการน้ำของพืชและปริมาตรสระน้ำ (Julia + PostgreSQL) + ผลลัพธ์มีโครงเดียวกับ core/*.js เพื่อให้หน้าเว็บใช้แทนกันได้ + ทุกครั้งที่คำนวณสำเร็จจะบันทึกใน calculation_runs (ถ้าเปิดการบันทึก) +servers: + - url: http://127.0.0.1:8000 + description: local development + +paths: + /api/v1/health: + get: + summary: สถานะบริการ + การเชื่อมต่อฐานข้อมูล + responses: + "200": + description: OK + content: + application/json: + schema: + type: object + properties: + status: { type: string, example: ok } + api_version: { type: string, example: 1.0.0 } + formula_version: { type: string, example: "1.0" } + persist_runs: { type: boolean } + database: + type: object + properties: + connected: { type: boolean } + database: { type: string } + calculation_runs: { type: integer } + detail: { type: string } + + /api/v1/meta: + get: + summary: รายการ endpoint และชื่อเดือนที่รองรับ + responses: + "200": + description: OK + + /api/v1/waters/calculate/plant: + post: + summary: น้ำที่พืชต้องการ (ETc = Kc × ETo) + requestBody: + required: true + content: + application/json: + schema: + type: object + required: [eto_mm_per_day, crop_coefficient, area_rai, irrigation_efficiency_percent] + properties: + eto_mm_per_day: { type: number, minimum: 0.01, example: 3.71 } + crop_coefficient: { type: number, minimum: 0.01, example: 1.0 } + area_rai: { type: number, minimum: 0.01, example: 10 } + irrigation_efficiency_percent: { type: number, minimum: 1, maximum: 100, example: 75 } + client_version: { type: string, example: 2026.11.16.7 } + responses: + "200": + description: ผลลัพธ์ (โครงเดียวกับ core/crop_water.js) + content: + application/json: + schema: + type: object + properties: + value: { type: number, example: 79.15 } + unit: { type: string, example: cubic_metre_per_day } + steps: + type: array + items: + type: object + properties: + label: { type: string } + value: { type: number } + unit: { type: string } + warnings: + type: array + items: { type: string } + details: + type: object + properties: + eto_mm_per_day: { type: number } + etc_mm_per_day: { type: number } + net_m3_per_day: { type: number } + gross_m3_per_day: { type: number } + gross_m3_per_week: { type: number } + gross_m3_per_month: { type: number } + run_id: + type: [string, "null"] + description: uuid ของแถวใน calculation_runs (null ถ้าไม่ได้เปิดการบันทึก) + engine: { type: string, example: julia } + formula_version: { type: string, example: "1.0" } + "400": + description: ค่าที่ส่งมาไม่ถูกต้อง (ข้อความเป็นภาษาไทย) + + /api/v1/capacities/reservoir: + post: + summary: ปริมาตรสระน้ำ (เรขาคณิต + น้ำฝนลงสระ) + requestBody: + required: true + content: + application/json: + schema: + type: object + required: [top_length_m, top_width_m, depth_m, usable_depth_percent] + properties: + shape: { type: string, enum: [box, trapezoid], default: trapezoid } + top_length_m: { type: number, example: 40 } + top_width_m: { type: number, example: 30 } + depth_m: { type: number, example: 4 } + side_slope_horizontal_per_vertical: { type: number, default: 1.5 } + usable_depth_percent: { type: number, maximum: 100, example: 80 } + catchment_rai: { type: number, default: 0 } + rainfall_mm: { type: number, default: 0 } + runoff_coefficient: { type: number, default: 0.8 } + responses: + "200": + description: ผลลัพธ์ (โครงเดียวกับ core/pond.js) + +components: + schemas: + Error: + type: object + properties: + error: { type: string } diff --git a/service/src/db.jl b/service/src/db.jl new file mode 100644 index 0000000..19355c7 --- /dev/null +++ b/service/src/db.jl @@ -0,0 +1,108 @@ +""" + db.jl — การเชื่อม PostgreSQL ผ่าน LibPQ + การบันทึกผลคำนวณ + +หลักการ: ถ้าไม่มีค่า env ครบ → service ยังรันได้ แต่ "ไม่บันทึก" (persist = false) +และ /api/v1/health จะรายงานว่าฐานข้อมูลไม่ได้เชื่อม เพื่อไม่ให้เข้าใจผิดว่าบันทึกแล้ว +""" + +module Db + +using LibPQ +using JSON3 +using Dates + +export DbConfig, load_config, connect, persist_run, health + +Base.@kwdef struct DbConfig + host::String = "localhost" + port::Int = 5432 + dbname::String = "farm_planning" + user::String = "postgres" + password::String = "" + enabled::Bool = false +end + +function load_config() + password = get(ENV, "FARM_DB_PASSWORD", "") + enabled = get(ENV, "FARM_PERSIST_RUNS", "true") == "true" && !isempty(password) + return DbConfig( + host = get(ENV, "FARM_DB_HOST", "localhost"), + port = parse(Int, get(ENV, "FARM_DB_PORT", "5432")), + dbname = get(ENV, "FARM_DB_NAME", "farm_planning"), + user = get(ENV, "FARM_DB_USER", "postgres"), + password = password, + enabled = enabled, + ) +end + +const STATE = Ref{Any}(nothing) # LibPQ.Connection หรือ nothing +const LAST_ERROR = Ref{String}("") + +function connect(config::DbConfig) + if !config.enabled + LAST_ERROR[] = "ยังไม่ได้ตั้ง FARM_DB_PASSWORD (หรือ FARM_PERSIST_RUNS=false)" + return nothing + end + try + conn = LibPQ.Connection( + "host=$(config.host) port=$(config.port) dbname=$(config.dbname) " * + "user=$(config.user) password=$(config.password) connect_timeout=5") + STATE[] = conn + LAST_ERROR[] = "" + return conn + catch error + LAST_ERROR[] = sprint(showerror, error) + STATE[] = nothing + return nothing + end +end + +"""บันทึกหนึ่งครั้งของการคำนวณ — คืนค่า run_id หรือ nothing ถ้ายังไม่มี DB""" +function persist_run(; kind::String, input::Dict, result::Dict, + formula_version::String = "1.0", + engine::String = "julia", + client_version::Union{Nothing,String} = nothing) + conn = STATE[] + conn === nothing && return nothing + try + statement = """ + INSERT INTO calculation_runs + (calculation_kind, input_payload, result_payload, formula_version, engine, client_version) + VALUES (\$1, \$2, \$3, \$4, \$5, \$6) + RETURNING run_id::text + """ + rows = LibPQ.execute(conn, statement, [ + kind, + JSON3.write(input), + JSON3.write(result), + formula_version, + engine, + client_version, + ]) + data = LibPQ.columntable(rows) + return isempty(data.run_id) ? nothing : data.run_id[1] + catch error + LAST_ERROR[] = sprint(showerror, error) + return nothing + end +end + +function health() + conn = STATE[] + if conn === nothing + return Dict("connected" => false, "detail" => LAST_ERROR[]) + end + try + rows = LibPQ.execute(conn, "SELECT current_database() AS db, count(*)::int AS runs FROM calculation_runs") + data = LibPQ.columntable(rows) + return Dict( + "connected" => true, + "database" => data.db[1], + "calculation_runs" => data.runs[1], + ) + catch error + return Dict("connected" => false, "detail" => sprint(showerror, error)) + end +end + +end # module diff --git a/service/src/formulas.jl b/service/src/formulas.jl new file mode 100644 index 0000000..5f76eda --- /dev/null +++ b/service/src/formulas.jl @@ -0,0 +1,168 @@ +""" + formulas.jl — สูตรคำนวณ (pure functions, ไม่แตะ DB และไม่แตะ HTTP) + +ต้องให้ผลตรงกับ core/*.js ทุกหลัก — มี golden vector ร่วมที่ tests/golden/vectors.json +(ถ้าแก้สูตรที่นี่ ต้องแก้ JS และอัปเดต vectors พร้อมกัน) +""" + +module Formulas + +export calculate_crop_water_demand, calculate_pond_volume + +const RAI_IN_SQUARE_METRE = 1600.0 +const CUBIC_METRE_PER_MM_PER_RAI = RAI_IN_SQUARE_METRE / 1000.0 # 1.6 + +const MONTH_NAMES = (:january, :february, :march, :april, :may, :june, + :july, :august, :september, :october, :november, :december) + +round2(x) = round(x, digits = 2) + +function require_positive(value, label) + number = Float64(value) + (isfinite(number) && number > 0) || + throw(ArgumentError("$label ต้องเป็นตัวเลขมากกว่า 0")) + return number +end + +function require_percent(value, label) + number = Float64(value) + (isfinite(number) && number > 0 && number <= 100) || + throw(ArgumentError("$label ต้องอยู่ระหว่าง 0–100")) + return number +end + +frustum_volume(bottom_area, top_area, height) = + (height / 3.0) * (bottom_area + top_area + sqrt(bottom_area * top_area)) + +""" + calculate_crop_water_demand(; eto_mm_per_day, crop_coefficient, area_rai, + irrigation_efficiency_percent) + +ETc = Kc × ETo · ปริมาณน้ำที่พืชใช้ = ETc × 1.6 × ไร่ · +ปริมาณที่ต้องให้ = หารด้วยประสิทธิภาพการให้น้ำ +""" +function calculate_crop_water_demand(; eto_mm_per_day, crop_coefficient, + area_rai, irrigation_efficiency_percent) + eto = require_positive(eto_mm_per_day, "ETo") + kc = require_positive(crop_coefficient, "Kc") + area = require_positive(area_rai, "พื้นที่ปลูก") + efficiency = require_percent(irrigation_efficiency_percent, "ประสิทธิภาพการให้น้ำ") + + etc = eto * kc + net = etc * CUBIC_METRE_PER_MM_PER_RAI * area + gross_mm = etc / (efficiency / 100.0) + gross = gross_mm * CUBIC_METRE_PER_MM_PER_RAI * area + + warnings = String[] + if kc < 0.2 || kc > 1.3 + push!(warnings, "Kc = $kc อยู่นอกช่วง 0.2–1.3 ที่พบทั่วไป — ตรวจค่ากับตาราง Kc ของพืชก่อนใช้") + end + if efficiency < 40 + push!(warnings, "ประสิทธิภาพการให้น้ำต่ำกว่า 40% — น้ำที่ต้องสูบจะมากกว่าที่พืชใช้หลายเท่า") + end + + steps = [ + Dict("label" => "ETo ของพื้นที่/เดือนที่เลือก", "value" => round2(eto), "unit" => "มม./วัน"), + Dict("label" => "ETc = Kc × ETo = $kc × $eto", "value" => round2(etc), "unit" => "มม./วัน"), + Dict("label" => "1 มม. บน 1 ไร่", "value" => CUBIC_METRE_PER_MM_PER_RAI, "unit" => "ลบ.ม."), + Dict("label" => "ปริมาณน้ำที่พืชใช้ = ETc × 1.6 × $area", "value" => round2(net), "unit" => "ลบ.ม./วัน"), + Dict("label" => "ปริมาณน้ำที่ต้องให้ = ÷ ประสิทธิภาพ $efficiency%", "value" => round2(gross), "unit" => "ลบ.ม./วัน"), + ] + + return Dict( + "value" => round2(gross), + "unit" => "cubic_metre_per_day", + "steps" => steps, + "warnings" => warnings, + "details" => Dict( + "eto_mm_per_day" => round2(eto), + "etc_mm_per_day" => round2(etc), + "net_m3_per_day" => round2(net), + "gross_m3_per_day" => round2(gross), + "gross_m3_per_week" => round2(gross * 7), + "gross_m3_per_month" => round2(gross * 30), + ), + ) +end + +""" + calculate_pond_volume(; shape, top_length_m, top_width_m, depth_m, + side_slope_horizontal_per_vertical, usable_depth_percent, + catchment_rai, rainfall_mm, runoff_coefficient) + +ปริมาตรบ่อ = frustum (หรือกล่อง) + น้ำใช้การ + น้ำฝนที่ไหลลงสระ +""" +function calculate_pond_volume(; shape = "trapezoid", top_length_m, top_width_m, depth_m, + side_slope_horizontal_per_vertical = 1.5, + usable_depth_percent, catchment_rai = 0.0, + rainfall_mm = 0.0, runoff_coefficient = 0.8) + kind = shape == "box" ? "box" : "trapezoid" + top_length = require_positive(top_length_m, "ความยาวปากบ่อ") + top_width = require_positive(top_width_m, "ความกว้างปากบ่อ") + depth = require_positive(depth_m, "ความลึกบ่อ") + slope = kind == "box" ? 0.0 : max(0.0, Float64(side_slope_horizontal_per_vertical)) + usable_percent = require_percent(usable_depth_percent, "ระดับน้ำใช้การ") + + catchment = max(0.0, Float64(catchment_rai)) + rainfall = max(0.0, Float64(rainfall_mm)) + runoff = clamp(Float64(runoff_coefficient), 0.0, 1.0) + + bottom_length = top_length - 2 * slope * depth + bottom_width = top_width - 2 * slope * depth + + (bottom_length > 0 && bottom_width > 0) || throw(ArgumentError( + "ผนังลาดชันเกินขนาดปากบ่อ: ด้านล่างเหลือ $(round2(bottom_length)) × $(round2(bottom_width)) ม. " * + "— เพิ่มขนาดปากบ่อ ลดความลึก หรือลดความชันผนัง")) + + top_area = top_length * top_width + bottom_area = bottom_length * bottom_width + excavated = kind == "box" ? top_area * depth : frustum_volume(bottom_area, top_area, depth) + + usable_depth = depth * usable_percent / 100.0 + level_length = bottom_length + 2 * slope * usable_depth + level_width = bottom_width + 2 * slope * usable_depth + level_area = level_length * level_width + usable = kind == "box" ? bottom_area * usable_depth : frustum_volume(bottom_area, level_area, usable_depth) + + rain_harvest = catchment * RAI_IN_SQUARE_METRE * (rainfall / 1000.0) * runoff + total = usable + rain_harvest + + warnings = String[] + if usable_percent < 50 + push!(warnings, "ระดับน้ำใช้การเหลือ $usable_percent% — น้ำส่วนล่างจะระเหย/รั่วซึมง่าย") + end + if kind == "box" && depth > 4 + push!(warnings, "ผนังตั้งฉากลึกเกิน 4 ม. เสี่ยงดินถล่ม — ควรลาดผนัง (trapezoid)") + end + if rainfall > 0 && catchment == 0 + push!(warnings, "ใส่พื้นที่รับน้ำฝนเป็น 0 — น้ำฝนที่คำนวณได้จึงเป็น 0") + end + + steps = [ + Dict("label" => "พื้นที่ปากบ่อ", "value" => round2(top_area), "unit" => "ตร.ม."), + Dict("label" => "พื้นที่ก้นบ่อ", "value" => round2(bottom_area), "unit" => "ตร.ม."), + Dict("label" => "ปริมาตรขุดทั้งหมด", "value" => round2(excavated), "unit" => "ลบ.ม."), + Dict("label" => "ระดับน้ำใช้การ $usable_percent% = $(round2(usable_depth)) ม.", + "value" => round2(usable), "unit" => "ลบ.ม."), + Dict("label" => "น้ำฝนลงสระ = $catchment ไร่ × $rainfall มม. × $runoff", + "value" => round2(rain_harvest), "unit" => "ลบ.ม."), + ] + + return Dict( + "value" => round2(total), + "unit" => "cubic_metre", + "steps" => steps, + "warnings" => warnings, + "details" => Dict( + "excavated_volume_m3" => round2(excavated), + "usable_volume_m3" => round2(usable), + "rain_harvest_m3" => round2(rain_harvest), + "total_available_m3" => round2(total), + "bottom_length_m" => round2(bottom_length), + "bottom_width_m" => round2(bottom_width), + "usable_depth_m" => round2(usable_depth), + ), + ) +end + +end # module diff --git a/service/src/server.jl b/service/src/server.jl new file mode 100644 index 0000000..c34164f --- /dev/null +++ b/service/src/server.jl @@ -0,0 +1,181 @@ +""" + server.jl — HTTP API (HTTP.jl + JSON3) ของ farm-planning + +รัน: + julia --project=service service/src/server.jl + +จุดออกแบบ: + · สูตรทั้งหมดเรียกจาก Formulas (ไม่เขียนสูตรซ้ำในชั้น HTTP) + · ทุก POST ที่คำนวณสำเร็จจะพยายามบันทึก DB ผ่าน Db.persist_run (ถ้าไม่มี DB ก็ยังตอบผลได้) + · ตอบ JSON รูปเดียวกับ core/*.js เพื่อให้เว็บใช้ผลจาก API แทนได้ทันที +""" + +include("formulas.jl") +include("db.jl") + +using HTTP +using JSON3 +using Dates + +const API_VERSION = "1.0.0" +const FORMULA_VERSION = "1.0" + +"อ่าน service/.env แบบง่าย (KEY=VALUE) — ไม่เพิ่ม dependency" +function load_dotenv(path) + isfile(path) || return nothing + for line in eachline(path) + stripped = strip(line) + (isempty(stripped) || startswith(stripped, "#")) && continue + occursin('=', stripped) || continue + key, value = split(stripped, '='; limit = 2) + key = strip(key) + value = strip(replace(value, "\"" => "")) + haskey(ENV, key) || (ENV[key] = value) + end + return nothing +end + +load_dotenv(joinpath(@__DIR__, "..", ".env")) + +const DB_CONFIG = Db.load_config() +const CORS_ORIGIN = get(ENV, "FARM_CORS_ORIGIN", "*") + +function cors_headers() + return [ + "Access-Control-Allow-Origin" => CORS_ORIGIN, + "Access-Control-Allow-Methods" => "GET, POST, OPTIONS", + "Access-Control-Allow-Headers" => "Content-Type", + "Cache-Control" => "no-store", + ] +end + +json_response(status::Int, payload) = + HTTP.Response(status, cors_headers(), JSON3.write(payload)) + +function error_response(status::Int, message::String) + return json_response(status, Dict("error" => message)) +end + +body_json(request) = JSON3.read(String(request.body)) + +function number_field(payload, key, label) + haskey(payload, Symbol(key)) || throw(ArgumentError("ต้องส่งฟิลด์ $key ($label)")) + return payload[Symbol(key)] +end + +function handle_plant(payload, client_version) + input = Dict( + "eto_mm_per_day" => payload[:eto_mm_per_day], + "crop_coefficient" => payload[:crop_coefficient], + "area_rai" => payload[:area_rai], + "irrigation_efficiency_percent" => payload[:irrigation_efficiency_percent], + ) + result = Formulas.calculate_crop_water_demand( + eto_mm_per_day = number_field(payload, "eto_mm_per_day", "ETo"), + crop_coefficient = number_field(payload, "crop_coefficient", "Kc"), + area_rai = number_field(payload, "area_rai", "พื้นที่ปลูก (ไร่)"), + irrigation_efficiency_percent = number_field(payload, "irrigation_efficiency_percent", "ประสิทธิภาพ (%)"), + ) + run_id = Db.persist_run(kind = "crop_water", input = input, result = result, + formula_version = FORMULA_VERSION, client_version = client_version) + result["run_id"] = run_id + result["engine"] = "julia" + result["formula_version"] = FORMULA_VERSION + return result +end + +function handle_reservoir(payload, client_version) + get(payload, :shape, "trapezoid") in ("box", "trapezoid") || + throw(ArgumentError("shape ต้องเป็น box หรือ trapezoid")) + input = Dict( + "shape" => get(payload, :shape, "trapezoid"), + "top_length_m" => payload[:top_length_m], + "top_width_m" => payload[:top_width_m], + "depth_m" => payload[:depth_m], + "side_slope_horizontal_per_vertical" => get(payload, :side_slope_horizontal_per_vertical, 1.5), + "usable_depth_percent" => payload[:usable_depth_percent], + "catchment_rai" => get(payload, :catchment_rai, 0.0), + "rainfall_mm" => get(payload, :rainfall_mm, 0.0), + "runoff_coefficient" => get(payload, :runoff_coefficient, 0.8), + ) + result = Formulas.calculate_pond_volume( + shape = input["shape"], + top_length_m = number_field(payload, "top_length_m", "ความยาวปากบ่อ"), + top_width_m = number_field(payload, "top_width_m", "ความกว้างปากบ่อ"), + depth_m = number_field(payload, "depth_m", "ความลึก"), + side_slope_horizontal_per_vertical = input["side_slope_horizontal_per_vertical"], + usable_depth_percent = number_field(payload, "usable_depth_percent", "ระดับน้ำใช้การ (%)"), + catchment_rai = input["catchment_rai"], + rainfall_mm = input["rainfall_mm"], + runoff_coefficient = input["runoff_coefficient"], + ) + run_id = Db.persist_run(kind = "reservoir", input = input, result = result, + formula_version = FORMULA_VERSION, client_version = client_version) + result["run_id"] = run_id + result["engine"] = "julia" + result["formula_version"] = FORMULA_VERSION + return result +end + +function router(request::HTTP.Request) + path = request.target + method = request.method + + if method == "OPTIONS" + return HTTP.Response(204, cors_headers()) + end + + try + if path == "/api/v1/health" && method == "GET" + return json_response(200, Dict( + "status" => "ok", + "api_version" => API_VERSION, + "formula_version" => FORMULA_VERSION, + "persist_runs" => DB_CONFIG.enabled, + "database" => Db.health(), + "server_time" => string(now(UTC)), + )) + elseif path == "/api/v1/meta" && method == "GET" + return json_response(200, Dict( + "api_version" => API_VERSION, + "formula_version" => FORMULA_VERSION, + "months" => String.(Formulas.MONTH_NAMES), + "endpoints" => [ + "GET /api/v1/health", + "GET /api/v1/meta", + "POST /api/v1/waters/calculate/plant", + "POST /api/v1/capacities/reservoir", + ], + )) + elseif path == "/api/v1/waters/calculate/plant" && method == "POST" + payload = body_json(request) + client_version = get(payload, :client_version, nothing) + return json_response(200, handle_plant(payload, client_version)) + elseif path == "/api/v1/capacities/reservoir" && method == "POST" + payload = body_json(request) + client_version = get(payload, :client_version, nothing) + return json_response(200, handle_reservoir(payload, client_version)) + else + return error_response(404, "ไม่พบ endpoint: $method $path") + end + catch error + if error isa ArgumentError || error isa RangeError + return error_response(400, sprint(showerror, error)) + end + return error_response(500, "เกิดข้อผิดพลาดภายใน: " * sprint(showerror, error)) + end +end + +function main() + Db.connect(DB_CONFIG) + host = get(ENV, "FARM_API_HOST", "127.0.0.1") + port = parse(Int, get(ENV, "FARM_API_PORT", "8000")) + println("farm-planning API $(API_VERSION) · สูตร $(FORMULA_VERSION)") + println(" ฟังที่ http://$(host):$(port)") + println(" บันทึก DB: $(DB_CONFIG.enabled ? "เปิด" : "ปิด")") + HTTP.serve(router, host, port) +end + +if abspath(PROGRAM_FILE) == @__FILE__ + main() +end diff --git a/service/test/runtests.jl b/service/test/runtests.jl new file mode 100644 index 0000000..84b2312 --- /dev/null +++ b/service/test/runtests.jl @@ -0,0 +1,55 @@ +# runtests.jl — ทดสอบสูตรฝั่ง Julia ด้วยชุดทดสอบร่วมเดียวกับ JS +# julia --project=service service/test/runtests.jl +# (ไม่ใช้ Test.jl แบบ suite เพื่อให้รันได้แม้ยังไม่ลง package เพิ่ม) + +include(joinpath(@__DIR__, "..", "src", "formulas.jl")) +using JSON3 + +const VECTORS = JSON3.read(read(joinpath(@__DIR__, "..", "..", "tests", "golden", "vectors.json"), String)) +const TOLERANCE = haskey(VECTORS, :tolerance) ? VECTORS[:tolerance] : 0.01 + +function run_case(test_case) + input = test_case[:input] + if test_case[:kind] == "crop_water" + return Formulas.calculate_crop_water_demand( + eto_mm_per_day = input[:eto_mm_per_day], + crop_coefficient = input[:crop_coefficient], + area_rai = input[:area_rai], + irrigation_efficiency_percent = input[:irrigation_efficiency_percent], + ) + elseif test_case[:kind] == "reservoir" + return Formulas.calculate_pond_volume( + shape = get(input, :shape, "trapezoid"), + top_length_m = input[:top_length_m], + top_width_m = input[:top_width_m], + depth_m = input[:depth_m], + side_slope_horizontal_per_vertical = get(input, :side_slope_horizontal_per_vertical, 1.5), + usable_depth_percent = input[:usable_depth_percent], + catchment_rai = get(input, :catchment_rai, 0.0), + rainfall_mm = get(input, :rainfall_mm, 0.0), + runoff_coefficient = get(input, :runoff_coefficient, 0.8), + ) + end + error("kind ไม่รู้จัก: $(test_case[:kind])") +end + +failures = 0 +for test_case in VECTORS[:cases] + result = run_case(test_case) + for (key, expected) in test_case[:expected] + actual = key == :value ? result["value"] : result["details"][String(key)] + ok = abs(Float64(actual) - Float64(expected)) <= TOLERANCE + if ok + println("ok $(test_case[:id]).$key = $actual") + else + global failures += 1 + println("FAIL $(test_case[:id]).$key: ได้ $actual แต่ vectors กำหนด $expected") + end + end +end + +if failures > 0 + println("\nล้มเหลว $failures จุด") + exit(1) +end +println("\nผ่านทั้งหมด — Julia ตรงกับ core/*.js ตาม golden vectors") diff --git a/tests/golden.test.mjs b/tests/golden.test.mjs new file mode 100644 index 0000000..d5c8a6f --- /dev/null +++ b/tests/golden.test.mjs @@ -0,0 +1,52 @@ +/* tests/golden.test.mjs — เทียบ core/*.js กับชุดทดสอบร่วม tests/golden/vectors.json + ชุดเดียวกับที่ service/test/runtests.jl ใช้ → ถ้าสองฝั่งเพี้ยนจากกัน test จะ fail + รัน: node --test tests/* +*/ +import test from "node:test"; +import assert from "node:assert/strict"; +import { readFileSync } from "node:fs"; + +import { calculateCropWaterDemand } from "../core/crop_water.js"; +import { calculatePondVolume } from "../core/pond.js"; + +const document = JSON.parse(readFileSync(new URL("./golden/vectors.json", import.meta.url), "utf8")); +const TOLERANCE = document.tolerance ?? 0.01; + +function runCase(testCase) { + const input = testCase.input; + if (testCase.kind === "crop_water") { + return calculateCropWaterDemand({ + eto_mm_per_day: input.eto_mm_per_day, + crop_coefficient: input.crop_coefficient, + area_rai: input.area_rai, + irrigation_efficiency_percent: input.irrigation_efficiency_percent + }); + } + if (testCase.kind === "reservoir") { + return calculatePondVolume({ + shape: input.shape, + top_length_m: input.top_length_m, + top_width_m: input.top_width_m, + depth_m: input.depth_m, + side_slope_horizontal_per_vertical: input.side_slope_horizontal_per_vertical, + usable_depth_percent: input.usable_depth_percent, + catchment_rai: input.catchment_rai, + rainfall_mm: input.rainfall_mm, + runoff_coefficient: input.runoff_coefficient + }); + } + throw new Error("kind ไม่รู้จัก: " + testCase.kind); +} + +for (const testCase of document.cases) { + test(`golden: ${testCase.id}`, () => { + const result = runCase(testCase); + for (const [key, expected] of Object.entries(testCase.expected)) { + const actual = key === "value" ? result.value : result.details[key]; + assert.ok( + Math.abs(actual - expected) <= TOLERANCE, + `${testCase.id}.${key}: ได้ ${actual} แต่ vectors กำหนด ${expected} (±${TOLERANCE})` + ); + } + }); +} diff --git a/tests/golden/vectors.json b/tests/golden/vectors.json new file mode 100644 index 0000000..529cae2 --- /dev/null +++ b/tests/golden/vectors.json @@ -0,0 +1,78 @@ +{ + "schema_version": "1.0", + "description_th": "ชุดทดสอบร่วม (golden vectors) — ผลลัพธ์ต้องตรงกันทั้ง core/*.js และ service/src/formulas.jl", + "tolerance": 0.01, + "cases": [ + { + "id": "crop_water_reference_crop", + "kind": "crop_water", + "input": { + "eto_mm_per_day": 3.71, + "crop_coefficient": 1.0, + "area_rai": 10, + "irrigation_efficiency_percent": 75 + }, + "expected": { + "value": 79.15, + "etc_mm_per_day": 3.71, + "net_m3_per_day": 59.36, + "gross_m3_per_week": 554.03 + } + }, + { + "id": "crop_water_drip_efficiency", + "kind": "crop_water", + "input": { + "eto_mm_per_day": 5.22, + "crop_coefficient": 0.85, + "area_rai": 25, + "irrigation_efficiency_percent": 60 + }, + "expected": { + "value": 295.8, + "etc_mm_per_day": 4.44, + "net_m3_per_day": 177.48, + "gross_m3_per_month": 8874.0 + } + }, + { + "id": "pond_box_with_rain", + "kind": "reservoir", + "input": { + "shape": "box", + "top_length_m": 40, + "top_width_m": 30, + "depth_m": 4, + "usable_depth_percent": 80, + "catchment_rai": 10, + "rainfall_mm": 60, + "runoff_coefficient": 0.8 + }, + "expected": { + "value": 4608.0, + "excavated_volume_m3": 4800.0, + "usable_volume_m3": 3840.0, + "rain_harvest_m3": 768.0 + } + }, + { + "id": "pond_trapezoid_slope", + "kind": "reservoir", + "input": { + "shape": "trapezoid", + "top_length_m": 40, + "top_width_m": 30, + "depth_m": 4, + "side_slope_horizontal_per_vertical": 1.5, + "usable_depth_percent": 80 + }, + "expected": { + "value": 2415.97, + "excavated_volume_m3": 3308.92, + "usable_volume_m3": 2415.97, + "bottom_length_m": 28.0, + "bottom_width_m": 18.0 + } + } + ] +}