Compare commits
627 Commits
| Author | SHA1 | Date | |
|---|---|---|---|
| e9f57b6ff6 | |||
| 262ae7fdf8 | |||
| 083eebfd95 | |||
| 0f4608cb43 | |||
| 8e5a682f0d | |||
| b0e816cbdc | |||
| c39139a605 | |||
| 91fd454b2c | |||
| 78d2e665ee | |||
| 4af44f2f7a | |||
| 60d5ca417d | |||
| 2465874198 | |||
| f982a5fa9c | |||
| aa701ed611 | |||
| 8bcf9b4b20 | |||
| dd648d4752 | |||
| 37df7be461 | |||
| 6e69abcfa3 | |||
| 0e6bb53c9c | |||
| 117f40c96f | |||
| ec0eb0a295 | |||
| 7f94e5efe7 | |||
| 3045bc6f99 | |||
| 1678f00c1b | |||
| 7a7e19636f | |||
| 34b8e2fb6b | |||
| 7c53b16566 | |||
| 8043110197 | |||
| 9f57f5d15e | |||
| 4cd349c3a1 | |||
| 5e9c1dac88 | |||
| 282ee559e0 | |||
| 1096fd68ab | |||
| 8bd62fbf6d | |||
| 9229d269c9 | |||
| 4286c45531 | |||
| f87641233b | |||
| 6822329ff2 | |||
| 36834c65b2 | |||
| 359ff29e95 | |||
| 548a163fc4 | |||
| 8636498bc9 | |||
| 9d2e9f6e1b | |||
| 8e1fa556ed | |||
| a65f53ccca | |||
| 547d594659 | |||
| e385b38885 | |||
| ab6c243ab7 | |||
| fc95c8bd25 | |||
| 828ba0938a | |||
| ecc76ae4d8 | |||
| 3b44cf2985 | |||
| f5ddfd366b | |||
| 21659bca35 | |||
| be4c663f70 | |||
| 6ec5485e70 | |||
| 9c94f70e54 | |||
| 7e0f7f7642 | |||
| 3d28d59e4d | |||
| eb208c0c52 | |||
| 1babc39b64 | |||
| 387341b1d8 | |||
| 3476146102 | |||
| de619eaf9f | |||
| de294a53a4 | |||
| 02f83947de | |||
| 2224eb6c22 | |||
| d9db230fe4 | |||
| ece5b06f7a | |||
| fd37e367a1 | |||
| 97b9729671 | |||
| db32d03e07 | |||
| cf0e3f2139 | |||
| e77f3d6a82 | |||
| e6ebf2188b | |||
| 43771edd77 | |||
| 42fdf98560 | |||
| c325d91bab | |||
| 74782da88c | |||
| e3b7e55695 | |||
| f3cb198681 | |||
| 44779c3979 | |||
| 162f9f28d5 | |||
| 99069619d6 | |||
| cff560ad71 | |||
| b637fdeeeb | |||
| 8449b02320 | |||
| 17b119d8c3 | |||
| b7e05f58aa | |||
| 50f25a7ec7 | |||
| 54e4e08802 | |||
| d27257f15b | |||
| 212a3dd6b0 | |||
| 01208ea4d4 | |||
| 49b3b6a0dc | |||
| 4477a68819 | |||
| 5126943a78 | |||
| 97d002a06c | |||
| 4171d61db1 | |||
| 677bf8f1d1 | |||
| 15dcabc538 | |||
| 25c885d5dd | |||
| 61f5b3c320 | |||
| 5d55081464 | |||
| f54f19fa45 | |||
| 876d9758bd | |||
| 0ba6192e95 | |||
| dd5010019d | |||
| 57745e114e | |||
| 307a0c31b1 | |||
| cfb6878bea | |||
| b0f559907f | |||
| b6c8173899 | |||
| d0e3e3622b | |||
| 6055d50dbe | |||
| 321041b65a | |||
| faed6581fd | |||
| 6b04b7ab6e | |||
| a85d562fa7 | |||
| 889522d935 | |||
| 5e5586a25c | |||
| 5cf1a33e98 | |||
| f4b80e8abc | |||
| 7e86e9c91b | |||
| 4ecde312f9 | |||
| 0c17b02468 | |||
| 97f4a904cd | |||
| f7a3afcebf | |||
| b3001c3051 | |||
| 443fa56671 | |||
| 884e654bea | |||
| ff3b36bf77 | |||
| 48cd7f0878 | |||
| 456dfe376f | |||
| 64e19e8c3e | |||
| 6543ce3f0f | |||
| 3a43f699f5 | |||
| c13f529721 | |||
| f904d5935c | |||
| 945b81ab4a | |||
| c85ba4acc3 | |||
| fa50a85730 | |||
| 12c733bafc | |||
| 72352a2ed9 | |||
| 38afbca839 | |||
| ede1f8e5e1 | |||
| 45f92f60ca | |||
| 4ec9f2944a | |||
| 439ecb035c | |||
| 5a660e73dd | |||
| 007a16eb9c | |||
| c9b4fa36fe | |||
| 2a3272e514 | |||
| e420b7f1af | |||
| 7914fc6056 | |||
| 667bdd813c | |||
| 66b5155b9b | |||
| 883fcd24f6 | |||
| fbed3ef159 | |||
| 2b3b36d646 | |||
| d9dd03ecc8 | |||
| d48a942932 | |||
| 3d2e20427c | |||
| d007122782 | |||
| f4d7e9588f | |||
| 7275f12a74 | |||
| 9c166be404 | |||
| 77355b10e4 | |||
| 6c87a736a6 | |||
| 3a0ec6e840 | |||
| 18d2835304 | |||
| fba27772a4 | |||
| c9e5a78115 | |||
| 2bbc2320dc | |||
| 07861dfe8c | |||
| 5d30433019 | |||
| 8c805fdd9c | |||
| e197d3deb3 | |||
| 4b2defac3a | |||
| 197c3c13a3 | |||
| 6f58beb2c5 | |||
| d20ce1efac | |||
| f0391e88fa | |||
| a12a862c47 | |||
| 6191118ac7 | |||
| 36d000eb17 | |||
| 6a1c9f4434 | |||
| 77cf46c859 | |||
| a6f505bebf | |||
| 09f6a2ee6f | |||
| 2cba5596a9 | |||
| de5a8a3d0a | |||
| 906633a884 | |||
| 96f54db0b1 | |||
| 3d14ff4a85 | |||
| 7731e4e8de | |||
| 248782fffb | |||
| c590e0fabe | |||
| bed658576d | |||
| 6fffa88f68 | |||
| 7e459c1926 | |||
| 904cf10e5c | |||
| 1926128fb0 | |||
| cfb11955d4 | |||
| 2f31604c4e | |||
| e63734c984 | |||
| 9883971beb | |||
| da42675a15 | |||
| cebe5719a5 | |||
| b80887ba1b | |||
| 808361b62c | |||
| 88c0c961cc | |||
| b8564e8f3e | |||
| 317cfd2fdd | |||
| ec8b9787e6 | |||
| 443dfc5a8a | |||
| 161dc87c6a | |||
| 4baf098491 | |||
| 08d0b2c013 | |||
| ac9159bdbd | |||
| e3a8649b41 | |||
| 5ef9a55d91 | |||
| e3e3b42c28 | |||
| d7db21a36b | |||
| aea3b5e83a | |||
| 6fe6ca92d4 | |||
| 7fc17b9032 | |||
| 985dbee74e | |||
| af71d4513a | |||
| f0cead5f06 | |||
| f341de7c2b | |||
| 750dc96712 | |||
| 8652064415 | |||
| 48c0c96f1f | |||
| cc68d5be67 | |||
| 16515e9095 | |||
| 2c4f42d383 | |||
| 6d1e4f32a4 | |||
| a396b94a9f | |||
| cba4b3b441 | |||
| 0f4f8cabf0 | |||
| 981ad386bf | |||
| 866dc14f08 | |||
| 34dca7cb76 | |||
| c655eb100d | |||
| f79b970056 | |||
| bc5023c708 | |||
| 48cae3b163 | |||
| d666d28c7c | |||
| d29c26a017 | |||
| 6feacf7582 | |||
| 232695c004 | |||
| 18b3ae007d | |||
| a281bebedf | |||
| 73c896a987 | |||
| bca1082c26 | |||
| cad347a936 | |||
| da5f4d3d65 | |||
| 2f05a73509 | |||
| c82f712f0b | |||
| 3e56f1223a | |||
| bd1cc61434 | |||
| e7d737f853 | |||
| ef6313ec9f | |||
| f1384d3a9a | |||
| 1efc59ffcf | |||
| ee752e66c0 | |||
| 5135e68569 | |||
| d895c35d6a | |||
| 52ca60df9a | |||
| ee96c924fc | |||
| b23774420b | |||
| 1df0c2bbd6 | |||
| a11aaab9be | |||
| 650df5b058 | |||
| d6ea464733 | |||
| bff71eeeba | |||
| 897d19ca1c | |||
| 8c1cc3e7bb | |||
| 962fed151a | |||
| c710e184e7 | |||
| 50d66c00a6 | |||
| 6249ced4fa | |||
| 7f4fb93996 | |||
| f2d4275b7f | |||
| 11ab405783 | |||
| 3aaa1d9daa | |||
| 91de84bec9 | |||
| 28e6cdd78a | |||
| 39d730faa0 | |||
| c3d3b5e8f3 | |||
| 137f6e4d98 | |||
| a29854b2cb | |||
| cc3e702204 | |||
| d4e4bc5dbf | |||
| 52e21a3a68 | |||
| 971666532e | |||
| 9cc508dc50 | |||
| 2a2c436013 | |||
| f486e6f263 | |||
| 90af8a8486 | |||
| 2237e2e799 | |||
| 96438d5078 | |||
| 038007c34e | |||
| 08fe894d1b | |||
| b95d3909a4 | |||
| cb69b086d7 | |||
| 86720d073e | |||
| 7540bc5610 | |||
| 96d33c668b | |||
| c1b3d7af59 | |||
| e64612a8d9 | |||
| 62c345bbb5 | |||
| ee728ed006 | |||
| 619f95b7f4 | |||
| fa7c55dee5 | |||
| 215b937f1e | |||
| f1e8dd5bf5 | |||
| fde37515c8 | |||
| f3b33d4084 | |||
| 86ea9a11d4 | |||
| b5bdf99069 | |||
| a475f0b2f6 | |||
| dcc6cd27b6 | |||
| 12f1d455b9 | |||
| 9429485236 | |||
| 451b37955e | |||
| 2ed275cd80 | |||
| 5d7862515f | |||
| 6121a27454 | |||
| 4c17158753 | |||
| 586a14f7f9 | |||
| 65a1fd1991 | |||
| e722d8ba1b | |||
| 6f3bffd840 | |||
| 80b7becd45 | |||
| 8051e7f207 | |||
| 7933f163b4 | |||
| 0836d6a926 | |||
| 36b1f49340 | |||
| b2710a0831 | |||
| 8bbb1f9ab2 | |||
| 8a597007cb | |||
| dc54553d2f | |||
| 527ec83b30 | |||
| abf03f0a80 | |||
| b397bdf83b | |||
| 32457e4ce8 | |||
| 94fac65238 | |||
| 1cabad8e3b | |||
| e753e55aa1 | |||
| 31db917eb8 | |||
| 59dd7e2ef9 | |||
| 30b0366818 | |||
| d6b15a6aec | |||
| ed7b2ef3ca | |||
| 70743394d8 | |||
| c7cc94a09c | |||
| edd5a97a9b | |||
| 5a4ceead3e | |||
| fa6bb33f11 | |||
| 5eaeee2f57 | |||
| 2e428aa07f | |||
| 4eda10df00 | |||
| 42d2671f80 | |||
| 66a99e2733 | |||
| 3ead7aa9f6 | |||
| e7b1e17579 | |||
| cd33c67df9 | |||
| 0bb23c32de | |||
| f0aae513af | |||
| 8ad8242c41 | |||
| 32877b1ce8 | |||
| 1550b5bb51 | |||
| 35c05e1b81 | |||
| 8b5498bc19 | |||
| bdd03a9ea4 | |||
| 0396cd6639 | |||
| f1f0db1bbe | |||
| 3061d44236 | |||
| 5e70ec1819 | |||
| e5d6a1188c | |||
| c23d1e3ce5 | |||
| bab495d9f2 | |||
| bbe27eac8b | |||
| 53896f0425 | |||
| db73faf270 | |||
| e3bc9d518d | |||
| 15a5eddf20 | |||
| e9fb1c3407 | |||
| 240d61c903 | |||
| e645f4beef | |||
| 4466601c58 | |||
| c3cab212b6 | |||
| b61c0897cc | |||
| 5c05f471b3 | |||
| 4e159e94e7 | |||
| db05538664 | |||
| ea7817752d | |||
| 67001f0a6e | |||
| c30ef72c6e | |||
| 581e0cf325 | |||
| e6b2812624 | |||
| 30fd2c5470 | |||
| 2df86983da | |||
| 90332bcb59 | |||
| 1c42ed5dd3 | |||
| 779cc79a87 | |||
| 1ba494dab8 | |||
| ef38140673 | |||
| 099271fdb2 | |||
| e6d38f342f | |||
| f8245b4499 | |||
| 9a8aea6435 | |||
| eab6b836d2 | |||
| deb5bfb9a1 | |||
| 4d3b747ab7 | |||
| 5471cbc32b | |||
| 4c94bf1293 | |||
| f36f7d3ad4 | |||
| 5bd0a5c406 | |||
| c317d7bb5d | |||
| 941b35a7a6 | |||
| ecc6405299 | |||
| 028831694a | |||
| 542e7fb7d1 | |||
| ac0f48bfce | |||
| 68bf43ea2f | |||
| cf7c44ce49 | |||
| db3b7d500d | |||
| d5fd617425 | |||
| bed3d4fc89 | |||
| 822c955bb6 | |||
| 20a79f5719 | |||
| b4edc16785 | |||
| 66db501170 | |||
| ac01a33c47 | |||
| 513aece27e | |||
| 1d3573a44a | |||
| 410d4fe05c | |||
| c15a746ae4 | |||
| da46abd678 | |||
| d38d00b4d2 | |||
| 8201fde606 | |||
| 70bf263a80 | |||
| 5a2c6ba2ad | |||
| 6ebf705e27 | |||
| 22490664d6 | |||
| 0c6dacb824 | |||
| 6345b69816 | |||
| 3882836fd5 | |||
| 59add598fa | |||
| ca2821464f | |||
| 24950c94ce | |||
| 454b3cc700 | |||
| dd1bc310dc | |||
| 53bead6691 | |||
| 36283ae265 | |||
| 89d204b2fe | |||
| 724b590868 | |||
| e130bbe577 | |||
| bc62e53270 | |||
| 6fd01314d5 | |||
| 1bdcd59287 | |||
| b7c0f28ad2 | |||
| 4320766abd | |||
| e934dd6abf | |||
| 18ac8f0761 | |||
| b5be26089d | |||
| 3a9a94f97b | |||
| c69bc0e9f3 | |||
| 833dbb5fdf | |||
| 2aa6b6efae | |||
| 1759e00213 | |||
| fa6e7066ae | |||
| 7cdca852bd | |||
| ee09e8bfd1 | |||
| ae6b6ec603 | |||
| 89ad338024 | |||
| c07a3466a0 | |||
| 5d054e59b6 | |||
| 061f18d081 | |||
| ee9c04147a | |||
| 6a1c437635 | |||
| 8045d06362 | |||
| 85e91ca882 | |||
| 11e9803965 | |||
| 90fb06c48c | |||
| ac3b90f2be | |||
| a664c4a9fc | |||
| 64aabdfbda | |||
| 98fda9923e | |||
| 53c7c85caf | |||
| c380b5e411 | |||
| 84113d1fd7 | |||
| 4715de9b5b | |||
| d7d4f61bfb | |||
| 69e594ac54 | |||
| f69219919d | |||
| 972c94d86c | |||
| f4606bddc6 | |||
| 06af036f86 | |||
| 8f46d6c13a | |||
| 701f43a1f8 | |||
| 9eea1a073a | |||
| 5278d568de | |||
| 21fc78adb9 | |||
| 4bdab1de3d | |||
| f90884e028 | |||
| 6959941128 | |||
| 18dd9531ad | |||
| 28d56fc3c5 | |||
| b8d944b3ef | |||
| a0722f26ca | |||
| 261267a523 | |||
| da27c9990a | |||
| 50153139fc | |||
| c4fb7761ad | |||
| fb7b25ba2c | |||
| e9be17faab | |||
| 133df472d1 | |||
| 569b33ece4 | |||
| 452e8a9093 | |||
| 1cfcec2bef | |||
| 2d638804d1 | |||
| b6dc82c0b3 | |||
| 2a01d97dd0 | |||
| fc3a2d0b9b | |||
| c766af691a | |||
| b7c24c07e7 | |||
| fbb6c648a5 | |||
| 8b664fc216 | |||
| 5f10f9ce45 | |||
| 46dc038e26 | |||
| c0b742af8a | |||
| 80c9904771 | |||
| 8885bbce6b | |||
| e9618d93d6 | |||
| cbf59d9bf0 | |||
| c9d5e6e017 | |||
| 15e84ba5bc | |||
| 3045944200 | |||
| e1f50e0ca5 | |||
| 9528f735b8 | |||
| 7417e661e0 | |||
| 38d0a87d6b | |||
| cd3577b299 | |||
| 9194487217 | |||
| e958743e65 | |||
| 85cf0a28b1 | |||
| 39dcda66b4 | |||
| f09b8fa2f9 | |||
| df36a5a917 | |||
| d18e801e08 | |||
| b576dd1a38 | |||
| bd0c47e6fc | |||
| 75c0370e54 | |||
| a2a39671b9 | |||
| 2a1a3e7bd9 | |||
| 5bf8c9c160 | |||
| 86622cc4dd | |||
| ed7da57066 | |||
| e2fc14a584 | |||
| d89875db7e | |||
| 321bf11f65 | |||
| 3e4c6dfad3 | |||
| d3c1ca12e9 | |||
| 090e508bf3 | |||
| 193da56edf | |||
| cd0a509215 | |||
| 7647e4b20f | |||
| 2c8542339d | |||
| b32f2ac3a3 | |||
| e726f986db | |||
| 36a6866b96 | |||
| db39d3b383 | |||
| dc2008c5b3 | |||
| 494d84f7c2 | |||
| 44f6ca4ef7 | |||
| 7f9c7a24d3 | |||
| 22af196d56 | |||
| 20232baf06 | |||
| 035cb83d6f | |||
| 114af59b26 | |||
| 6a38fdb06a | |||
| d387048ebf | |||
| 71516713c5 | |||
| d21670f6af | |||
| 2434bce35e | |||
| f02742497a | |||
| 968892d811 | |||
| a3a9444c3b | |||
| e1006c63de | |||
| 21981eb946 | |||
| ac4f2653af | |||
| 51727e419a | |||
| b791f7be68 | |||
| 334b83c973 | |||
| 6ea4a2e0f9 | |||
| ec5d7e2efe | |||
| 737191c170 | |||
| f199eda322 | |||
| 9161e0901f | |||
| 5460c7f676 | |||
| 2a9f6f5628 | |||
| 58dbb7ef3e | |||
| 75b82024de | |||
| 4af1ad8848 | |||
| 164153dc9c | |||
| ac0672bc11 | |||
| 24dd3acd09 | |||
| 4efe7cef58 | |||
| 2dab20f718 | |||
| be298777af | |||
| 45a671940b | |||
| 601971d43d | |||
| c9bce7c976 | |||
| 614747ffca | |||
| 931cc0d1d9 | |||
| b6b4f8c360 | |||
| ff81d80cf9 | |||
| 01000757f3 | |||
| d75dec2a50 | |||
| a45f78217c | |||
| d3761183c3 | |||
| 5d07770ce2 | |||
| 91bdc12e78 |
+45
-3
@@ -26,10 +26,13 @@ CUSTOMER_ORDER_LIST_URL=/orderlist/
|
|||||||
# DB/역할/스키마/센터 seed 생성: scripts/sql/cupang_db_init.sql 참고.
|
# DB/역할/스키마/센터 seed 생성: scripts/sql/cupang_db_init.sql 참고.
|
||||||
# CUPANG_DB_URL=postgresql://cupang_app:replace-me@postgres-db:5432/cupang_db
|
# CUPANG_DB_URL=postgresql://cupang_app:replace-me@postgres-db:5432/cupang_db
|
||||||
|
|
||||||
# 쿠팡 밀크런 출고리스트를 기록할 Google 스프레드시트 (분배 확정 시 출고일 시트 생성)
|
# 쿠팡 밀크런 출고리스트 문서 (분배 확정·출고리스트 작성 팝업이 출고일 시트에 기록)
|
||||||
# - 대상 문서는 반드시 "Google 스프레드시트" 형식(업로드한 .xlsx 는 파일>Google 스프레드시트로 저장)
|
# - 구글 드라이브에 올린 .xlsx 파일 id(기본값 = 아래 id). 구글 스프레드시트 문서 id 여도 된다(형식 자동 판별)
|
||||||
# - 서비스 계정 이메일(client_email)에 해당 문서를 편집자로 공유해야 한다
|
# - .xlsx 는 Drive 권한이 필요하다: 서비스 계정(GOOGLE_SHEETS_CREDENTIALS) 또는 GOOGLE_SLIDES_OAUTH_REFRESH_TOKEN
|
||||||
|
# - 서비스 계정이면 이메일(client_email)에 해당 파일을 편집자로 공유해야 한다
|
||||||
# CUPANG_SHEET_ID=1J74op7lBZOgE27p4R28I3RWsv0EtXdii
|
# CUPANG_SHEET_ID=1J74op7lBZOgE27p4R28I3RWsv0EtXdii
|
||||||
|
# "밀크런 출고리스트 작성" 팝업 전용 — 드라이브 .xlsx 파일 id(기본값 = 아래 id, 엑셀만·구글 시트로 대신 쓰지 않음)
|
||||||
|
# CUPANG_OUTBOUND_XLSX_ID=1J74op7lBZOgE27p4R28I3RWsv0EtXdii
|
||||||
#
|
#
|
||||||
# [방식 A] 사용자 OAuth 리프레시 토큰 — 조직 정책으로 서비스 계정 키를 못 만들 때
|
# [방식 A] 사용자 OAuth 리프레시 토큰 — 조직 정책으로 서비스 계정 키를 못 만들 때
|
||||||
# 토큰 발급: python scripts/google_sheets_authorize.py --client-id .. --client-secret ..
|
# 토큰 발급: python scripts/google_sheets_authorize.py --client-id .. --client-secret ..
|
||||||
@@ -43,6 +46,16 @@ CUSTOMER_ORDER_LIST_URL=/orderlist/
|
|||||||
# GOOGLE_SHEETS_CREDENTIALS=/opt/www/main/secrets/google-sheets-sa.json
|
# GOOGLE_SHEETS_CREDENTIALS=/opt/www/main/secrets/google-sheets-sa.json
|
||||||
# 또는 파일 대신 JSON 본문을 통째로 (한 줄):
|
# 또는 파일 대신 JSON 본문을 통째로 (한 줄):
|
||||||
# GOOGLE_SHEETS_CREDENTIALS_JSON={"type":"service_account", ...}
|
# GOOGLE_SHEETS_CREDENTIALS_JSON={"type":"service_account", ...}
|
||||||
|
#
|
||||||
|
# 주간 회의록 "회의록 보드"(주차마다 빈 Google 슬라이드) — 위 Google 인증을 같이 쓴다.
|
||||||
|
# OAuth 토큰은 Drive·Slides 권한까지 필요: scripts/google_sheets_authorize.py 로 다시 발급(시트 권한도 함께 들어감)
|
||||||
|
# Cloud Console 에서 Google Drive API·Google Slides API 사용 설정. 서비스 계정이면 공유 드라이브 콘텐츠 관리자로 추가.
|
||||||
|
# GOOGLE_SLIDES_OAUTH_REFRESH_TOKEN=replace-me # 비우면 GOOGLE_SHEETS_OAUTH_REFRESH_TOKEN 사용
|
||||||
|
# MEETING_BOARD_FOLDER_ID=0AGF3CIEboPQiUk9PVA # 보드를 만들 공유 드라이브(폴더) ID — 비우면 이 기본값
|
||||||
|
#
|
||||||
|
# Project 업무 파일 → 구글 드라이브(설명란·보드 카드·세부 업무에 파일 끌어 놓기) — 위 Google 인증(Drive 권한)을 같이 쓴다.
|
||||||
|
# 그 아래 프로젝트/섹션/업무/세부 업무 폴더를 자동으로 만든다. 서비스 계정이면 공유 드라이브 폴더여야 올라간다.
|
||||||
|
# PROJECT_DRIVE_FOLDER_ID=1Zdak2FtACRJ6peOnA9zD22hsbbsTixJG # 업무 파일 최상위 폴더 ID — 비우면 이 기본값
|
||||||
|
|
||||||
# ─── 휴가 관리 모듈 (vacation_db) ───
|
# ─── 휴가 관리 모듈 (vacation_db) ───
|
||||||
# 설정해야 모듈이 동작한다(미설정 시 "설정 필요" 안내, JSON 폴백 없음).
|
# 설정해야 모듈이 동작한다(미설정 시 "설정 필요" 안내, JSON 폴백 없음).
|
||||||
@@ -113,6 +126,11 @@ CUSTOMER_ORDER_LIST_URL=/orderlist/
|
|||||||
# 미설정 시 카페24 기본 도메인(https://<mall_id>.cafe24.com)으로 대체된다.
|
# 미설정 시 카페24 기본 도메인(https://<mall_id>.cafe24.com)으로 대체된다.
|
||||||
# CAFE24_SHOP_URL=https://www.miras.co.kr
|
# CAFE24_SHOP_URL=https://www.miras.co.kr
|
||||||
#
|
#
|
||||||
|
# 멀티쇼핑몰 번호(쉼표). 옵션/품목 팝업에서 바꾼 품목 진열·판매를 이 쇼핑몰 모두에 같은 값으로
|
||||||
|
# 보낸다(추가금액·자체코드는 기본몰 1 만). 번호는 카페24 관리자 → 멀티쇼핑몰 관리에서 확인.
|
||||||
|
# 미설정 시 1(기본몰)만.
|
||||||
|
# CAFE24_SHOP_NOS=1,2,3
|
||||||
|
#
|
||||||
# 카페24 읽기 지연 유예시간(분). 카페24 관리자 API 는 PUT 뒤 한동안 GET 에서 예전
|
# 카페24 읽기 지연 유예시간(분). 카페24 관리자 API 는 PUT 뒤 한동안 GET 에서 예전
|
||||||
# 값을 돌려준다. 이 시간 안에 우리가 쓴 값이 있으면, GET 이 그 이전 값을 돌려줘도
|
# 값을 돌려준다. 이 시간 안에 우리가 쓴 값이 있으면, GET 이 그 이전 값을 돌려줘도
|
||||||
# 마지막 쓰기(revision·스냅샷)를 화면·적용 기준으로 삼는다. 지나면 카페24 값을 믿는다.
|
# 마지막 쓰기(revision·스냅샷)를 화면·적용 기준으로 삼는다. 지나면 카페24 값을 믿는다.
|
||||||
@@ -138,6 +156,21 @@ CUSTOMER_ORDER_LIST_URL=/orderlist/
|
|||||||
# CAFE24_MOBILE_DETAIL_FTP_PATH=/sde_design/mobile11/product/detail.html
|
# CAFE24_MOBILE_DETAIL_FTP_PATH=/sde_design/mobile11/product/detail.html
|
||||||
# CAFE24_PC_DETAIL_FTP_PATH=/sde_design/skin11/product/detail.html
|
# CAFE24_PC_DETAIL_FTP_PATH=/sde_design/skin11/product/detail.html
|
||||||
|
|
||||||
|
# ─── 입출고 관리 모듈 (inout_db) — app/modules/inout ───
|
||||||
|
# 본사 → 공장 발주, 물류 입고, 미입고 관리. 미설정 시 "설정 필요" 안내만.
|
||||||
|
# 초기화: scripts/sql/inout_db_init.sql (docs/INOUT_MODULE.md). 제품(단품)은 아래 ITEMCODE_DB_URL 재사용.
|
||||||
|
# INOUT_DB_URL=postgresql://inout_app:replace-me@postgres-db:5432/inout_db
|
||||||
|
|
||||||
|
# ─── 안내문 발송 모듈 (outreach_db) — app/modules/outreach ───
|
||||||
|
# 리스트(이메일·인스타 주소 + 이름)에 안내문 메일 일괄 발송(보내는 사람 본인 Gmail — 입출고 Gmail 연결 재사용)·인스타 DM 반자동.
|
||||||
|
# 초기화: scripts/sql/outreach_db_init.sql (docs/DEPLOYMENT.md "안내문 발송 DB 생성"). 미설정 시 "설정 필요" 안내만.
|
||||||
|
# OUTREACH_DB_URL=postgresql://outreach_app:replace-me@postgres-db:5432/outreach_db
|
||||||
|
|
||||||
|
# ─── 라이브 커머스 모듈 (live_db) — app/modules/live ───
|
||||||
|
# 말레이시아 라이브 방송의 호스트 정보·방송 스케줄·판매금액·결과 이미지.
|
||||||
|
# 초기화: scripts/sql/live_db_init.sql (docs/DEPLOYMENT.md "라이브 커머스 DB 생성"). 미설정 시 "설정 필요" 안내만.
|
||||||
|
# LIVE_DB_URL=postgresql://live_app:replace-me@postgres-db:5432/live_db
|
||||||
|
|
||||||
# ─── 상품 검색 (itemcode_db 읽기 전용) ───
|
# ─── 상품 검색 (itemcode_db 읽기 전용) ───
|
||||||
# cupang 설정 화면에서 제품명을 itemcode_db 에서 검색해 등록한다(읽기만).
|
# cupang 설정 화면에서 제품명을 itemcode_db 에서 검색해 등록한다(읽기만).
|
||||||
# 미설정 시 검색 비활성 → 수동 등록만 가능.
|
# 미설정 시 검색 비활성 → 수동 등록만 가능.
|
||||||
@@ -163,3 +196,12 @@ CUSTOMER_ORDER_LIST_URL=/orderlist/
|
|||||||
# APP_ENCRYPTION_KEY_V1=
|
# APP_ENCRYPTION_KEY_V1=
|
||||||
# [매출 업데이트] 가 가져오는 기간(오늘 포함 최근 N일, 기본 7, 최대 90)
|
# [매출 업데이트] 가 가져오는 기간(오늘 포함 최근 N일, 기본 7, 최대 90)
|
||||||
# PERFORMANCE_SYNC_DAYS=7
|
# PERFORMANCE_SYNC_DAYS=7
|
||||||
|
# 매출·광고비 자동 업데이트(웹 프로세스 안 스레드) — 기본 켜짐, 오늘 포함 최근 10일.
|
||||||
|
# 일정(간격·요일·시작/끝)은 실적 설정 "자동 업데이트" 카드에서 매출·광고비 따로 정한다(performance_db 011). 저장 전 기본 = 매일 9~19시 30분마다.
|
||||||
|
# PERFORMANCE_AUTO_SYNC=false # 끄기(설정 화면 일정과 상관없이)
|
||||||
|
# PERFORMANCE_AUTO_SYNC_DAYS=10 # 가져올 기간(1~90일)
|
||||||
|
# PERFORMANCE_AUTO_SYNC_HOURS=9-19 # 일정 저장 전 기본 시간대(시작시-마지막시, 마지막 시는 정각 회차까지)
|
||||||
|
|
||||||
|
# 자산관리 — 별도 asset_db. 사용자가 서버에서 asset_db_init.sql로 직접 초기화.
|
||||||
|
# 미설정 시 등록/배정은 비활성, HWiNFO XML 분석 미리보기는 사용 가능.
|
||||||
|
# ASSET_DB_URL=postgresql://asset_app:replace-me@postgres-db:5432/asset_db
|
||||||
|
|||||||
@@ -16,3 +16,6 @@ PUBLIC_BASE_URL=http://localhost:8080
|
|||||||
|
|
||||||
CS_ORDER_URL=https://cs.example.com
|
CS_ORDER_URL=https://cs.example.com
|
||||||
CUSTOMER_ORDER_LIST_URL=https://orders.example.com
|
CUSTOMER_ORDER_LIST_URL=https://orders.example.com
|
||||||
|
|
||||||
|
# 자산관리 개발용 DB (사용자가 직접 생성). 운영 DB 접속정보를 사용하지 마세요.
|
||||||
|
# ASSET_DB_URL=postgresql://asset_app:replace-me@host.docker.internal:5432/asset_db
|
||||||
|
|||||||
+11
@@ -24,3 +24,14 @@ __pycache__/
|
|||||||
# dispatch 라벨 PDF 샘플(실제 고객 PII — 커밋 금지)
|
# dispatch 라벨 PDF 샘플(실제 고객 PII — 커밋 금지)
|
||||||
docs/samples/
|
docs/samples/
|
||||||
tests/js/.out/
|
tests/js/.out/
|
||||||
|
|
||||||
|
# HWiNFO 실물 보고서: 시리얼/MAC/사용자 정보가 포함되어 소스에 보관하지 않음
|
||||||
|
KING-DESKTOP.XML
|
||||||
|
|
||||||
|
# Excel 가 파일을 열 때 만드는 잠금 파일
|
||||||
|
~$*
|
||||||
|
|
||||||
|
# 테스트 도구(docs/TESTING.md)
|
||||||
|
.pytest_cache/
|
||||||
|
tests/js/node_modules/
|
||||||
|
tests/js/package-lock.json
|
||||||
|
|||||||
@@ -36,10 +36,15 @@ Codex는 이 저장소에서 작업을 시작하기 전에 **반드시 아래
|
|||||||
- 말레이시아 창고 재고관리 (`app/modules/malaysia/`, `malaysia_stock_db`) — 낱개(MT/MX/MZ) 입출고·조정, 세트(MY) BOM, 일일 재고조사(세트→낱개 자동 분해), 현재고 현황. 뚜껑(MD-)은 재고 집계 제외 — 단, 창고 랙에는 위치 확인용으로 배치 가능(`store.LID_ITEMS`). 상품은 `itemcode_db` 읽기 전용. 권한키 `malaysia`
|
- 말레이시아 창고 재고관리 (`app/modules/malaysia/`, `malaysia_stock_db`) — 낱개(MT/MX/MZ) 입출고·조정, 세트(MY) BOM, 일일 재고조사(세트→낱개 자동 분해), 현재고 현황. 뚜껑(MD-)은 재고 집계 제외 — 단, 창고 랙에는 위치 확인용으로 배치 가능(`store.LID_ITEMS`). 상품은 `itemcode_db` 읽기 전용. 권한키 `malaysia`
|
||||||
- 말레이시아 배송 (`app/modules/dispatch/`, `dispatch_db`) — TikTok·Shopee 출고관리. 플랫폼별 데이터 엑셀 업로드(TikTok=03_TikTok_Order_Export.xlsx, Shopee=Packing List.Doorstep Delivery.xlsx) → 1박스=1카드 출고 작업 리스트·SKU 피킹 요약·Kagayaku 전달표 자동 생성. 1박스 묶음 기준 Package ID > Tracking ID > Order ID, 같은 박스 같은 SKU 합산. 작업 상태 토글(`dispatch_logs` 기록). 받는 사람 이름/전화/주소는 박스 단위로 저장(작업 카드 표시 + 출고 엑셀 생성용 — 개인정보). 배치 다운로드 zip 에 업로드 원본 + 취합 출고 엑셀(`YYYY.MM.DD(Ddd)_tictoc|shopee.xlsx`) 포함. 엑셀은 openpyxl 파싱/생성. 권한키 `dispatch`. 상세는 `docs/DISPATCH_MODULE.md`
|
- 말레이시아 배송 (`app/modules/dispatch/`, `dispatch_db`) — TikTok·Shopee 출고관리. 플랫폼별 데이터 엑셀 업로드(TikTok=03_TikTok_Order_Export.xlsx, Shopee=Packing List.Doorstep Delivery.xlsx) → 1박스=1카드 출고 작업 리스트·SKU 피킹 요약·Kagayaku 전달표 자동 생성. 1박스 묶음 기준 Package ID > Tracking ID > Order ID, 같은 박스 같은 SKU 합산. 작업 상태 토글(`dispatch_logs` 기록). 받는 사람 이름/전화/주소는 박스 단위로 저장(작업 카드 표시 + 출고 엑셀 생성용 — 개인정보). 배치 다운로드 zip 에 업로드 원본 + 취합 출고 엑셀(`YYYY.MM.DD(Ddd)_tictoc|shopee.xlsx`) 포함. 엑셀은 openpyxl 파싱/생성. 권한키 `dispatch`. 상세는 `docs/DISPATCH_MODULE.md`
|
||||||
- 카페24 상품관리 (`app/modules/cafe24/`, `cafe24_db`) — 카페24 관리자에 들어가지 않고 상품 상세페이지(description HTML) 조회·편집·즉시적용·예약적용·자동복원·버전 롤백·일괄수정. 카페24 OAuth/API 클라이언트는 향후 주문관리와 공유하기 위해 **공통 계층 `app/integrations/cafe24/`** 에 둔다 — 라우터에서 `httpx`/`requests` 직접 호출 금지. 토큰은 Fernet 암호화 저장(`CAFE24_TOKEN_SECRET`), 로그/화면에 토큰·시크릿 절대 미출력. 쓰기 직전 항상 카페24 현재 HTML 을 다시 읽어 `BACKUP` revision 생성(로컬 값을 현재값으로 가정 금지). 예약은 DB 저장 + 별도 worker(`app/modules/cafe24/worker.py`, compose 서비스 `dbx-cafe24-worker`)가 처리 — 웹 프로세스에서 대기하지 않는다. 권한키 `cafe24`(연결/해제는 admin 전용). 상세는 `docs/CAFE24_MODULE.md`
|
- 카페24 상품관리 (`app/modules/cafe24/`, `cafe24_db`) — 카페24 관리자에 들어가지 않고 상품 상세페이지(description HTML) 조회·편집·즉시적용·예약적용·자동복원·버전 롤백·일괄수정. 카페24 OAuth/API 클라이언트는 향후 주문관리와 공유하기 위해 **공통 계층 `app/integrations/cafe24/`** 에 둔다 — 라우터에서 `httpx`/`requests` 직접 호출 금지. 토큰은 Fernet 암호화 저장(`CAFE24_TOKEN_SECRET`), 로그/화면에 토큰·시크릿 절대 미출력. 쓰기 직전 항상 카페24 현재 HTML 을 다시 읽어 `BACKUP` revision 생성(로컬 값을 현재값으로 가정 금지). 예약은 DB 저장 + 별도 worker(`app/modules/cafe24/worker.py`, compose 서비스 `dbx-cafe24-worker`)가 처리 — 웹 프로세스에서 대기하지 않는다. 권한키 `cafe24`(연결/해제는 admin 전용). 상세는 `docs/CAFE24_MODULE.md`
|
||||||
- 프로젝트 관리 (`app/modules/project/`, `project_db`) — 아사나식. 프로젝트/서브프로젝트(self-FK `parent_id`, CASCADE)·업무(`tasks`: 담당자·우선순위·시작/마감)·진행단계(`project_stages` 칸반, 생성시 기본 4단계 seed)·멤버 배정(`project_members`)·활동이력(`project_activity`). 메인 뷰 달력(FullCalendar)/타임라인(vis-timeline) 버튼 토글 + 보드(드래그로 단계 이동)/리스트. 진입 권한키 `project`(관리자 페이지 토글로 직원별 부여, admin 자동). 프로젝트 생성/삭제·사용자 배정은 `is_admin` 만, 배정 멤버(또는 owner)는 서브프로젝트/업무/단계 CRUD. 멤버 배정 후보는 `project` 권한 보유 등록 사용자에서 자동 목록(`GET /project/api/assignable-users`). 업무 배정·완료 시 관리자에게 메일(`app/mail.py` stdlib smtplib, `SMTP_*`+`PROJECT_NOTIFY_EMAIL` env, 미설정 시 조용히 skip, `BackgroundTasks` 비동기). 상세는 `docs/PROJECT_MODULE.md`
|
- 프로젝트 관리 (`app/modules/project/`, `project_db`) — 아사나식. 프로젝트/서브프로젝트(self-FK `parent_id`, CASCADE)·업무(`tasks`: 담당자·우선순위·시작/마감)·진행단계(`project_stages` 칸반, 새 프로젝트는 섹션 없이 시작)·멤버 배정(`project_members`)·활동이력(`project_activity`). 메인 뷰 달력(FullCalendar)/타임라인(vis-timeline) 버튼 토글 + 보드(드래그로 단계 이동)/리스트. 진입 권한키 `project`(관리자 페이지 토글로 직원별 부여, admin 자동). 권한은 등급(수퍼관리자 > Admin > Pro user > User, 2026-10-12)과 멤버십 기준 — 표는 `docs/PROJECT_MODULE.md` 6-14, 공통 판단 `access.py`(관리자도 멤버가 아니면 프로젝트가 안 보임, 예외는 수퍼관리자). 멤버 배정 후보는 `project` 권한 보유 등록 사용자에서 자동 목록(`GET /project/api/assignable-users`). 업무 배정·완료 시 관리자에게 메일(`app/mail.py` stdlib smtplib, `SMTP_*`+`PROJECT_NOTIFY_EMAIL` env, 미설정 시 조용히 skip, `BackgroundTasks` 비동기). 상세는 `docs/PROJECT_MODULE.md`
|
||||||
|
|
||||||
상세는 `docs/PROJECT_OVERVIEW.md`.
|
상세는 `docs/PROJECT_OVERVIEW.md`.
|
||||||
|
|
||||||
|
- 자산관리 (`app/modules/asset/`, `asset_db`) — 사무집기·전산장비 등록/배정/반납/상태·구매/보증·이력.
|
||||||
|
HWiNFO XML 분석·사양 조회·이전 보고서와 원본 보존. 권한키 `asset`, 환경변수 `ASSET_DB_URL`.
|
||||||
|
사진 등록/갤러리·모니터 자산 조회/등록/연결·수퍼 관리자 삭제(이력/원본 보존). 기존 설치는 마이그레이션 `asset_db_002_photos_monitors.sql` 필요.
|
||||||
|
DB 미설정 시 저장 비활성, XML 분석 미리보기 가능. DB 생성은 사용자가 서버 명령으로 직접 진행. 상세 `docs/ASSET_MODULE.md`.
|
||||||
|
|
||||||
---
|
---
|
||||||
|
|
||||||
## 개발 원칙
|
## 개발 원칙
|
||||||
@@ -47,7 +52,7 @@ Codex는 이 저장소에서 작업을 시작하기 전에 **반드시 아래
|
|||||||
- 기존 코드를 수정하기 전 관련 파일을 먼저 읽고 구조를 파악한다.
|
- 기존 코드를 수정하기 전 관련 파일을 먼저 읽고 구조를 파악한다.
|
||||||
- 위험 명령은 **반드시 사용자 확인 후** 실행한다 (아래 "위험 명령" 절 참고).
|
- 위험 명령은 **반드시 사용자 확인 후** 실행한다 (아래 "위험 명령" 절 참고).
|
||||||
- `.env`, API 키, DB 비밀번호, OAuth Secret, 토큰은 절대 Git에 올리지 않는다.
|
- `.env`, API 키, DB 비밀번호, OAuth Secret, 토큰은 절대 Git에 올리지 않는다.
|
||||||
- 신규 DB가 필요하면 **승인 요청 후** 생성하며, DB명은 반드시 `_db`로 끝낸다 (예: `inventory_db`).
|
- 신규 DB가 필요하면 **서버에서 실행할 명령을 제공하고 생성은 사용자가 직접 진행한다** (사용자 지시: 2026-10-06). DB명은 반드시 `_db`로 끝낸다 (예: `inventory_db`). 대상 서버·현재 DB·백업 상태와 생성 후 스키마·앱 계정 권한·연결 확인 명령을 함께 제공한다. 기존 DB 삭제·덮어쓰기 등 위험 명령은 아래의 별도 승인 원칙을 그대로 따른다.
|
||||||
- 예전 문서/코드의 `orderlist_app`은 현재 기준 `orderlist_db`이다. 발견 시 수정 대상.
|
- 예전 문서/코드의 `orderlist_app`은 현재 기준 `orderlist_db`이다. 발견 시 수정 대상.
|
||||||
|
|
||||||
---
|
---
|
||||||
|
|||||||
@@ -1,56 +1,90 @@
|
|||||||
# main-app ERP 프로젝트 작업 기준
|
# main-app ERP 프로젝트 작업 기준
|
||||||
|
|
||||||
> 이 문서는 Claude Code가 이 저장소에서 작업할 때 가장 먼저 확인하는 기준 문서입니다.
|
> 이 문서는 Claude Code가 이 저장소에서 작업할 때 **매 대화 자동으로 읽는** 기준 문서다.
|
||||||
> 작업 시작 전, 아래 "반드시 먼저 읽을 문서"를 모두 확인한 뒤 작업을 시작합니다.
|
> 토큰 절약을 위해 짧게 유지한다. 모듈별 상세 규칙은 각 모듈 폴더의 `CLAUDE.md` 와 `docs/*_MODULE.md` 에 둔다.
|
||||||
|
> **이 파일에 모듈 상세 설명을 다시 쌓지 말 것** — 새 기능 설명은 그 모듈의 `CLAUDE.md`(요약)·`docs/*_MODULE.md`(상세)에 쓴다.
|
||||||
|
|
||||||
---
|
---
|
||||||
|
|
||||||
## 반드시 먼저 읽을 문서
|
## 작업 시작 규칙 — 필요한 것만 읽는다
|
||||||
|
|
||||||
Claude Code는 이 저장소에서 작업을 시작하기 전에 **반드시 아래 문서를 순서대로 읽고 맥락을 확보**한 뒤 작업한다.
|
사용자는 요청 앞에 **`[모듈명]`** 을 붙인다(예: `[휴가] 반차 버튼 색 변경`).
|
||||||
|
|
||||||
1. `docs/PROJECT_OVERVIEW.md` — 프로젝트 정의, 기능 범위, 연동 대상
|
1. `[모듈명]` 으로 아래 표에서 모듈을 찾는다.
|
||||||
2. `docs/SERVER_ARCHITECTURE.md` — 서버 구성도와 네트워크 흐름
|
2. 그 모듈의 `app/modules/<폴더>/CLAUDE.md` 를 먼저 읽는다(요약·핵심 규칙).
|
||||||
3. `docs/DATABASES.md` — PostgreSQL DB 구성과 명명 규칙
|
3. 코드는 그 모듈 폴더 + 표의 정적 파일만 본다. 다른 모듈 폴더는 **연결이 확인될 때만** 연다.
|
||||||
4. `docs/DEPLOYMENT.md` — 배포 경로, 서비스 실행 방식, 복구 절차
|
4. 상세 문서(`docs/*_MODULE.md`)는 요약으로 부족할 때만 — 큰 문서는 `grep -n '^#' <문서>` 로 목차를 보고 **필요한 절만** offset/limit 으로 읽는다.
|
||||||
|
5. 큰 코드 파일도 통째로 읽지 말고 Grep 으로 위치를 찾은 뒤 그 부분만 읽는다.
|
||||||
|
6. `[모듈명]` 이 없거나 표에 없으면 어느 모듈인지 짧게 묻는다(뻔하면 추정하고 진행).
|
||||||
|
|
||||||
문서 간 내용이 충돌하면 위의 우선순위(1 → 4)를 따른다.
|
공통 문서는 **작업 종류에 해당할 때만** 읽는다(예전 "4개 필독" 규칙 폐지):
|
||||||
|
|
||||||
|
| 작업 종류 | 추가로 읽을 문서 |
|
||||||
|
| --- | --- |
|
||||||
|
| DB 테이블·마이그레이션·새 DB | `docs/DATABASES.md` (해당 DB 절만) |
|
||||||
|
| 배포·서버·Docker·복구 | `docs/DEPLOYMENT.md`, `docs/SERVER_ARCHITECTURE.md` |
|
||||||
|
| 여러 모듈에 걸친 작업·새 모듈 추가·전체 구조 질문 | `docs/PROJECT_OVERVIEW.md` |
|
||||||
|
| 화면 디자인 공통(ERP 셸·공용 CSS) | `docs/DESIGN.md` |
|
||||||
|
| 테스트 방법 | `docs/TESTING.md` |
|
||||||
|
|
||||||
|
문서끼리 충돌하면 PROJECT_OVERVIEW → SERVER_ARCHITECTURE → DATABASES → DEPLOYMENT 순으로 우선한다.
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## 모듈 표
|
||||||
|
|
||||||
|
| `[모듈명]` | 폴더 (`app/modules/`) | DB | 권한키 | 상세 문서 | 정적 파일 (`app/static/`) |
|
||||||
|
| --- | --- | --- | --- | --- | --- |
|
||||||
|
| `[프로젝트]` `[Project]` | `project/` | `project_db` | `project` | `docs/PROJECT_MODULE.md` (178KB, 절만) | `project*.js/css`, `erp-overdue.*` |
|
||||||
|
| `[실적]` | `performance/` | `performance_db` | `performance` | `docs/PERFORMANCE_MODULE.md` (절만) | `performance.*` |
|
||||||
|
| `[카페24]` | `cafe24/` | `cafe24_db` | `cafe24` | `docs/CAFE24_MODULE.md` (절만) | `cafe24.css`, `cafe24-options.js` |
|
||||||
|
| `[쿠팡]` | `cupang/` | `cupang_db` | `cupang` | (모듈 CLAUDE.md 가 기준) | `cupang.*` |
|
||||||
|
| `[입출고]` | `inout/` | `inout_db` | `inout` | `docs/INOUT_MODULE.md` | `inout.*` |
|
||||||
|
| `[배송]` `[말레이시아배송]` | `dispatch/` | `dispatch_db` | `dispatch` | `docs/DISPATCH_MODULE.md` | `dispatch/` |
|
||||||
|
| `[말레이시아재고]` `[말레이시아]` | `malaysia/` | `malaysia_stock_db` | `malaysia` | `app/modules/malaysia/README.md` | `malaysia*.js` |
|
||||||
|
| `[휴가]` | `vacation/` | `vacation_db` | `vacation`, `vacation_approver` | (모듈 CLAUDE.md) | `vacation.*` |
|
||||||
|
| `[경비]` `[개인경비]` | `expense/` | `expense_db` | `expense` | (모듈 CLAUDE.md) | — |
|
||||||
|
| `[공지]` `[긴급공지]` | `notice/` | `project_db`(024) | 수퍼관리자 | `docs/NOTICE_MODULE.md` | `erp-notice*` |
|
||||||
|
| `[자산]` | `asset/` | `asset_db` | `asset` | `docs/ASSET_MODULE.md` | `asset.*` |
|
||||||
|
| `[안내문 발송]` | `outreach/` | `outreach_db` | `outreach` | (모듈 CLAUDE.md) | `outreach.*` |
|
||||||
|
| `[라이브커머스]` `[라이브]` | `live/` | `live_db` | `live`, `live_host` | (모듈 CLAUDE.md) | `live.*` |
|
||||||
|
| `[공통]` `[ERP]` | `app/main.py`, `app/templates/`(셸·로그인·관리자), 인증·권한 | — | — | `docs/PROJECT_OVERVIEW.md`, `docs/DESIGN.md` | `erp*.js/css`, `styles.css` |
|
||||||
|
| `[배포]` `[서버]` | `docker-compose*.yml`, `Dockerfile`, `scripts/` | — | — | `docs/DEPLOYMENT.md` | — |
|
||||||
|
| `[DB]` | `scripts/sql/` | — | — | `docs/DATABASES.md` | — |
|
||||||
|
|
||||||
|
외부 쇼핑몰 연동(사방넷·네이버 등)·주문관리·상품코드 매칭·재고·CS·반품은 허브 담당 영역 — `docs/PROJECT_OVERVIEW.md` 참고.
|
||||||
|
|
||||||
|
### 모듈 사이 연결 (이것을 바꾸면 상대 모듈도 확인)
|
||||||
|
|
||||||
|
- `itemcode_db` 읽기 전용 상품: 쿠팡·말레이시아재고·입출고 (`itemcode_ro` 권한).
|
||||||
|
- `app/integrations/cafe24/` 토큰: 카페24 + 실적(카페24 어댑터).
|
||||||
|
- `performance_store` 매출: 실적 → 프로젝트 주간 회의록 머리 카드(읽기 전용).
|
||||||
|
- `ProjectStore.pool`(`project_db`): 프로젝트 + 긴급 공지.
|
||||||
|
- `APP_ENCRYPTION_KEY`: 실적(쇼핑몰·광고 인증) + 입출고(Gmail 토큰).
|
||||||
|
- 입출고 Gmail 연결(`inout_gmail_tokens`·`/inout/gmail/callback`, `_GMAIL_ORIGINS`): 입출고 발주 메일 + 휴가 메일(`vacation/notify.py`) + 안내문 발송(`outreach/send.py`) — 모두 보내는 사람 본인 Gmail.
|
||||||
|
- `app/integrations/google_sheets.py`(쿠팡) · `google_slides.py`(프로젝트 회의록 보드).
|
||||||
|
- `asset/media.py prepare_photo`(이미지 확인·메타데이터 제거): 자산 + 라이브 커머스.
|
||||||
|
- `app/mail.py`: 프로젝트 알림 메일.
|
||||||
|
- ERP 모든 화면 스크립트: `erp-notice.js`(공지) · `erp-overdue.js`(프로젝트 마감 알림).
|
||||||
|
- 아사나식 날짜 팝업: 프로젝트(`project.js` 안) + 공용 복사본 `erp-datepop.js/css`(휴가 신청·입출고 날짜 칸·라이브 오른쪽 달력) — 바꾸면 둘 다.
|
||||||
|
- 국경일·대체공휴일 표 `project/store.py KR_HOLIDAYS`: 프로젝트 캘린더·날짜 팝업 + 휴가(달력·일수 계산 `vacation/db.holiday_map`) + 입출고(오른쪽 달력·날짜 칸).
|
||||||
|
|
||||||
---
|
---
|
||||||
|
|
||||||
## 프로젝트 한 줄 정의
|
## 프로젝트 한 줄 정의
|
||||||
|
|
||||||
`main-app`은 DBX ERP 시스템의 **메인 프로젝트(허브)** 이다.
|
`main-app`은 DBX ERP 시스템의 **메인 프로젝트(허브)** 이다. 상세는 `docs/PROJECT_OVERVIEW.md`.
|
||||||
|
|
||||||
담당 영역:
|
|
||||||
|
|
||||||
- 주문관리
|
|
||||||
- 상품코드 매칭
|
|
||||||
- 재고관리
|
|
||||||
- CS관리
|
|
||||||
- 반품관리
|
|
||||||
- 외부 쇼핑몰 API 연동 (카페24, 네이버 스마트스토어, 사방넷 등)
|
|
||||||
- 개인경비 (`app/modules/expense/`, `expense_db`)
|
|
||||||
- 쿠팡 밀크런 (`app/modules/cupang/`, `cupang_db`) — 출고 달력/상자 계산, 상품은 `itemcode_db` 읽기 전용. 출고 묶음은 **상자 계산 화면의 [분배 확정] 으로만** 만든다(신규 등록 폼 없음, `/cupang/new` 는 상자 계산으로 리다이렉트). 확정 조건: 미배분 상자 0 + 담긴 센터마다 출고방식(택배/파렛트) 선택. 확정 시 센터마다 출고 묶음 1건(`status=출고준비`, 센터입고일=출고일+1일, 상자 구성은 `cupang_shipments.box_plan` JSONB 에 스냅샷 — 혼합 상자 내용물·상자 종류 표시용) + 출고리스트 엑셀 자동 다운로드(`GET /cupang/export.xlsx?date=`, 시트명 YYYYMMDD). 양식 생성은 `app/modules/cupang/export.py` 한 곳에서 만들어 xlsx·구글시트가 공유. `CUPANG_SHEET_ID` + 인증(사용자 OAuth `GOOGLE_SHEETS_OAUTH_REFRESH_TOKEN` 또는 서비스 계정 `GOOGLE_SHEETS_CREDENTIALS[_JSON]`) 설정 시 확정과 동시에 Google 스프레드시트에 출고일 시트를 생성/덮어쓰기(`app/integrations/google_sheets.py`, 미설정이면 조용히 skip). 출고 삭제(건별/날짜 전체) 시에도 같은 날짜 시트를 동기화 — 남은 출고가 있으면 다시 쓰고, 없으면 시트 삭제(문서에 시트가 하나뿐이면 내용만 비움). 작업 중 상태는 `cupang_box_calc_drafts` 에 이름 붙여 임시 저장/불러오기. 쿠팡 로켓 매출(`/cupang/sales`, `cupang_sales`·`cupang_sales_weekly`) — 발주 라인별 공급가·원가·물류비·마진 표. 기간/센터/유형/검색 조회, 행 CRUD, 구글 시트 양식 xlsx·csv 업로드(같은 발주번호+SKU+출고일+센터+수량은 덮어씀), 엑셀 다운로드. 광고비·할인 프로모션·장려금은 주차 단위(`cupang_sales_weekly`)로 보관하고 순마진은 화면에서 계산. 초기 데이터는 `scripts/sql/cupang_sales_seed.sql`. 쿠팡 발주 엑셀(xlsx) 다중 업로드 지원(`POST /cupang/api/box-calc/upload`, openpyxl) — F13 입고예정일의 하루 전 = 출고일, 22행부터 B=쿠팡상품코드·F=센터명·G=수량을 읽어 `cupang_products.coupang_item_code` 로 제품 매칭 후 센터별 합산 → 센터 단위로 상자 계산·자동 배분
|
|
||||||
- 휴가 관리 (`app/modules/vacation/`, `vacation_db`) — 월간 달력(구글식 bar)/연차·반차 신청/승인 워크플로/공휴일·연차 설정. 권한키 `vacation`·`vacation_approver`
|
|
||||||
- 말레이시아 창고 재고관리 (`app/modules/malaysia/`, `malaysia_stock_db`) — 낱개(MT/MX/MZ) 입출고·조정, 세트(MY) BOM, 일일 재고조사(세트→낱개 자동 분해), 현재고 현황. 뚜껑(MD-)은 재고 집계 제외 — 단, 창고 랙에는 위치 확인용으로 배치 가능(`store.LID_ITEMS`). 상품은 `itemcode_db` 읽기 전용. 권한키 `malaysia`
|
|
||||||
- 말레이시아 배송 (`app/modules/dispatch/`, `dispatch_db`) — TikTok·Shopee 출고관리. 플랫폼별 데이터 엑셀 업로드(TikTok=03_TikTok_Order_Export.xlsx, Shopee=Packing List.Doorstep Delivery.xlsx) → 1상자=1카드 출고 작업 리스트·SKU 피킹 요약·Kagayaku 전달표 자동 생성. 1상자 묶음 기준 Package ID > Tracking ID > Order ID, 같은 상자 같은 SKU 합산. 작업 상태 토글(`dispatch_logs` 기록). 받는 사람 이름/전화/주소는 상자 단위로 저장(작업 카드 표시 + 출고 엑셀 생성용 — 개인정보). 배치 다운로드 zip 에 업로드 원본 + 취합 출고 엑셀(`YYYY.MM.DD(Ddd)_tictoc|shopee.xlsx`) 포함. 엑셀은 openpyxl 파싱/생성. 권한키 `dispatch`. 상세는 `docs/DISPATCH_MODULE.md`
|
|
||||||
- 카페24 상품관리 (`app/modules/cafe24/`, `cafe24_db`) — 카페24 관리자에 들어가지 않고 상품 상세페이지(description HTML) 조회·편집·즉시적용·예약적용·버전 이력. 3분할 화면(목록 | HTML 편집기 | 상품 정보 패널). 정보 패널(`routes_product_info.py`, `_side.html`)에서 상품명·판매가·공급가·소비자가, 대표이미지(`POST /admin/products/{no}/images` 에 base64 data URI + `image_upload_type=A` — NNEditor 업로드 경로를 PUT `detail_image` 에 넣는 방식은 적용 안 됨), 옵션(생성/이름·썸네일·표시방식 수정/삭제)·품목(자체코드·추가금액·진열·판매)을 수정. 카페24 OAuth/API 클라이언트는 향후 주문관리와 공유하기 위해 **공통 계층 `app/integrations/cafe24/`** 에 둔다 — 라우터에서 `httpx`/`requests` 직접 호출 금지. 토큰은 Fernet 암호화 저장(`CAFE24_TOKEN_SECRET`), 로그/화면에 토큰·시크릿 절대 미출력. 쓰기 직전 항상 카페24 현재 HTML 을 다시 읽어 `BACKUP` revision 생성(로컬 값을 현재값으로 가정 금지). **카페24 관리자 API 는 PUT 뒤 한동안 GET 에서 예전 값을 돌려준다(읽기 지연)** — 우리 캐시 문제가 아니다. 그래서 "마지막 쓰기가 권위": 상세설명은 카페24 값이 최근 revision 중 하나와 같으면 지연으로 보고 마지막 MANUAL/SCHEDULED 를 표시·지문 기준으로 쓰고(`store.resolve_description`), 스칼라(상품명·가격·이미지·진열/판매)는 PUT 응답 스냅샷(`cafe24_products.last_write_snapshot`, 마이그레이션 004)과 GET 의 `updated_date` 를 비교해 덮어씌운다(`store.overlay_recent_write`). 유예시간 `CAFE24_READ_LAG_GRACE_MIN`(기본 360분). 쓰기 후 화면은 PUT 응답으로 그리고 다시 GET 하지 않는다. 예약은 DB 저장 + 별도 worker(`app/modules/cafe24/worker.py`, compose 서비스 `dbx-cafe24-worker`)가 처리 — 웹 프로세스에서 대기하지 않는다. 권한키 `cafe24`(연결/해제는 admin 전용). 상세는 `docs/CAFE24_MODULE.md`
|
|
||||||
- 프로젝트 관리 (`app/modules/project/`, `project_db`) — 아사나식. 프로젝트/서브프로젝트(self-FK `parent_id`, CASCADE)·프로젝트 색상(32색 — 아사나 16색 + 진한 16색)·아이콘(`projects.icon`, Material Symbols 42종, 마이그레이션 011)·작업(`tasks`: 담당자·우선순위·시작/마감)·진행단계(`project_stages` 칸반, 생성시 기본 4단계 seed, 섹션 기본 담당자 `default_assignee_email` — 담당자 빈 작업을 그 섹션에 만들거나 옮기면 자동 배정, 마이그레이션 009)·멤버 배정(`project_members`)·활동이력(`project_activity`). 첫 화면(`/project/`)은 **내 작업 목록**(프로젝트 홈 카드 화면은 폐지). 프로젝트 화면은 캘린더(FullCalendar)/타임라인(vis-timeline)/보드/목록/대시보드 뷰 토글. 좌측 사이드바는 수신함·내 작업·휴지통·프로젝트 화면 공용(`templates/project/_side.html` + 프로젝트 목록 동작 `initSideTree`, 새 프로젝트/수정 모달 `_side_modals.html`) — 프로젝트 목록(순서 변경·✎·×)은 어느 화면에서나 같다. 보드는 아사나처럼 섹션이 가로로 계속 늘어나고(넘치면 가로 스크롤) 카드의 담당자·마감일을 클릭해 그 자리에서 바꾼다. 좌측 사이드바에 수신함·내 작업(접이식) 메뉴. 설명란은 주소 붙여넣기 시 자동 링크, 설명란·댓글에서 @로 멤버를 태그하면 (`task_mentions`, 마이그레이션 006) 수신함에 그 작업이 쌓인다. 진입 권한키 `project`(관리자 페이지 토글로 직원별 부여, admin 자동). 프로젝트 생성은 `project` 권한자 누구나(만든 사람이 owner), 삭제는 만든 사람만(슈퍼관리자 예외), 사용자 배정은 `is_admin` 만. 배정 멤버(또는 owner/admin)만 그 프로젝트를 조회(화면·API 모두, 비멤버 403)하고 서브프로젝트/작업/단계 CRUD — URL 의 섹션·부모 작업이 그 프로젝트 것인지 서버가 검증. 실시간 반영은 `project_live_version` 카운터(마이그레이션 007, 미적용 시 MAX 폴백). 사이드바 전체 검색(`/api/search`, 제목·설명·댓글, pg_trgm) + 프로젝트/내 작업 필터 바(찾기·상태·담당자·마감·우선순위·정렬, 클라이언트 필터). 협업자(`task_followers`, 자동 팔로우: 만든 사람·담당자·댓글·@태그) — 완료·댓글 알림은 담당자+협업자에게만. 작업 삭제는 휴지통(`project_trash`, 마이그레이션 010) — 삭제 직전 스냅샷 3개월 보관, 관리자만 보기·복구(`/project/trash`). 권한은 **지금 기준 공통 모듈 `access.py`**(목록·배지·알림·멘션·메일 수신자·삭제·댓글 수정까지 — 멤버에서 빠지면 기록이 있어도 안 보이고 알림도 없음), 소유자 변경은 관리자만, 연결(멀티호밍)된 작업은 연결된 프로젝트 멤버에게 읽기 전용(docs/PROJECT_MODULE.md 6-10). 연간 목표(마이그레이션 013, `goal_*` 테이블) — 사이드바 "목표" → 연도 펼침 → `/project/goals/{연도}` 에 매출(목표·실적·달성)·로아스 월별 숫자 + 업무 영역(상품·마케팅·컨텐츠·유통 등)별 연간·월별 글, 조회는 전원·입력은 `is_admin` 만. 마감 알림(`reminders.py` 데몬 스레드, 영업일 09시, D-1/당일/지연, `task_reminders` 로 중복 방지, `PROJECT_REMINDER_*` env) — 마이그레이션 008. 라우터 핸들러는 동기 DB 라 `def` 로 둔다(`async def` 금지). 말풍선은 전부 아사나식 공용 말풍선(`.pj-hovertip`) — 새 기능도 `title=`/`data-tip=` 만 달고 별도 툴팁 구현 금지. 멤버 배정 후보는 `project` 권한 보유 등록 사용자에서 자동 목록(`GET /project/api/assignable-users`). 작업 배정·완료 시 관리자에게 메일(`app/mail.py` stdlib smtplib, `SMTP_*`+`PROJECT_NOTIFY_EMAIL` env, 미설정 시 조용히 skip, `BackgroundTasks` 비동기). 작업 창은 **저장 버튼 없이 실시간 저장**(칸별 PUT, `saveField`/`saveChain`, 새 작업은 제목이 생기는 순간 생성). 댓글 답글·이모티콘 반응(마이그레이션 012 `task_comments.parent_id`·`task_comment_reactions`, 미적용 시 버튼 숨김·API 503), 완료 이력 줄은 `project_activity` completed 를 댓글 사이에 표시(댓글 수 제외), 댓글 `@아이디` 는 아이콘+이름 칩. 수신함 "확인"은 페이지 이동 없이 오른쪽 iframe 패널(`/project/p/{pid}?task=&embed=1`, `html.pj-embed`). 상단 바 화면 배율 토글(`html.pj-ui-scale` → `.erp-app` zoom .75, 2880×1620·200%용) — **팝업은 반드시 `document.body` 에 붙인다**(배율 안의 fixed 좌표는 어긋남). 상세는 `docs/PROJECT_MODULE.md`
|
|
||||||
|
|
||||||
- 실적 (`app/modules/performance/`, `performance_db`) — 쇼핑몰 통합 매출. 네 영역 분리: ① 수집 `adapters/`(쇼핑몰 하나 = 어댑터 파일 하나 + `registry.py` 한 줄 + SQL seed 한 줄) + `sync.py`(공통 동기화, 같은 쇼핑몰 동시 실행 차단, 쇼핑몰별 실패 격리) ② 보안 `security/`(AES-256-GCM, 키 버전, 비밀값 가리기) + `credentials.py` ③ 계산 `calc.py`(주=월~일, 수수료 반올림은 `commission()` 한 곳, 요율 이력) + `db.py` ④ 화면 `dashboard.py`/`router.py`/템플릿. 쇼핑몰 API 인증정보는 `.env` 가 아니라 **설정 화면에서 입력 → 마스터 키 `APP_ENCRYPTION_KEY` 로 암호화해 DB 저장**, secret 원문은 화면으로 다시 보내지 않는다. 쇼핑몰 API 는 백엔드에서만 호출, 오류·로그·raw 는 `redact` 후 저장. 매출 기준일: 결제=결제일, 취소·반품=발생일(`sync.sales_date_for`). 금액은 원 단위 정수. 권한키 `performance`, 설정 화면·API 는 `is_admin`. 카페24 어댑터는 기존 `app/integrations/cafe24` 토큰 재사용. 1단계는 모의 데이터(`is_sample`)·구조까지, 실제 수집은 쇼핑몰별로 공식 문서 확인 후 순차 구현. 상세는 `docs/PERFORMANCE_MODULE.md`
|
|
||||||
|
|
||||||
상세는 `docs/PROJECT_OVERVIEW.md`.
|
|
||||||
|
|
||||||
---
|
---
|
||||||
|
|
||||||
## 개발 원칙
|
## 개발 원칙
|
||||||
|
|
||||||
- 기존 코드를 수정하기 전 관련 파일을 먼저 읽고 구조를 파악한다.
|
- 기존 코드를 수정하기 전 관련 파일을 먼저 읽고 구조를 파악한다(범위는 위 "작업 시작 규칙").
|
||||||
- 위험 명령은 **반드시 사용자 확인 후** 실행한다 (아래 "위험 명령" 절 참고).
|
- 위험 명령은 **반드시 사용자 확인 후** 실행한다 (아래 "위험 명령" 절 참고).
|
||||||
- `.env`, API 키, DB 비밀번호, OAuth Secret, 토큰은 절대 Git에 올리지 않는다.
|
- `.env`, API 키, DB 비밀번호, OAuth Secret, 토큰은 절대 Git에 올리지 않는다.
|
||||||
- 신규 DB가 필요하면 **승인 요청 후** 생성하며, DB명은 반드시 `_db`로 끝낸다 (예: `inventory_db`).
|
- 신규 DB가 필요하면 **승인 요청 후** 생성하며, DB명은 반드시 `_db`로 끝낸다 (예: `inventory_db`).
|
||||||
- 예전 문서/코드의 `orderlist_app`은 현재 기준 `orderlist_db`이다. 발견 시 수정 대상.
|
- 예전 문서/코드의 `orderlist_app`은 현재 기준 `orderlist_db`이다. 발견 시 수정 대상.
|
||||||
|
- 새 모듈을 만들면: `app/modules/<폴더>/CLAUDE.md`(요약) + 필요 시 `docs/<이름>_MODULE.md` + 위 모듈 표에 한 줄.
|
||||||
|
|
||||||
---
|
---
|
||||||
|
|
||||||
@@ -92,7 +126,7 @@ Claude Code는 이 저장소에서 작업을 시작하기 전에 **반드시 아
|
|||||||
- `.env`, `.env.local`, `.env.production` 은 **Git에 절대 커밋하지 않는다**.
|
- `.env`, `.env.local`, `.env.production` 은 **Git에 절대 커밋하지 않는다**.
|
||||||
- 예시 파일(`*.example`)만 커밋한다.
|
- 예시 파일(`*.example`)만 커밋한다.
|
||||||
- 비밀값 유출이 의심되면 즉시 회전(rotate)을 권고한다.
|
- 비밀값 유출이 의심되면 즉시 회전(rotate)을 권고한다.
|
||||||
- 신규 환경변수 추가 시 `*.example` 파일과 본 문서(또는 `docs/DEPLOYMENT.md`)에 변수 설명을 함께 갱신한다.
|
- 신규 환경변수 추가 시 `*.example` 파일과 `docs/DEPLOYMENT.md`(또는 그 모듈 CLAUDE.md)에 변수 설명을 함께 갱신한다.
|
||||||
|
|
||||||
---
|
---
|
||||||
|
|
||||||
@@ -101,8 +135,13 @@ Claude Code는 이 저장소에서 작업을 시작하기 전에 **반드시 아
|
|||||||
```
|
```
|
||||||
Main-app/
|
Main-app/
|
||||||
├─ app/ FastAPI 앱 소스
|
├─ app/ FastAPI 앱 소스
|
||||||
├─ docs/ 운영/설계 문서 (작업 전 필독)
|
│ ├─ modules/<모듈>/ 모듈별 코드 + templates/ + CLAUDE.md(모듈 요약)
|
||||||
├─ scripts/ 배포·유지보수 스크립트
|
│ ├─ integrations/ 외부 API 공통 계층(cafe24, google_sheets, google_slides)
|
||||||
|
│ ├─ static/ 정적 파일(모듈별 js/css)
|
||||||
|
│ └─ templates/ ERP 공통 셸·로그인·관리자
|
||||||
|
├─ desktop/notifier/ PC 알림 트레이 프로그램(C#, Windows exe)
|
||||||
|
├─ docs/ 운영/설계 문서 (필요한 것만 읽기)
|
||||||
|
├─ scripts/ 배포·유지보수 스크립트, sql/ 마이그레이션
|
||||||
├─ skills/ Claude Code 규칙/스킬
|
├─ skills/ Claude Code 규칙/스킬
|
||||||
├─ docker-compose.yml 운영 컴포즈
|
├─ docker-compose.yml 운영 컴포즈
|
||||||
├─ docker-compose.local.yml 로컬 컴포즈
|
├─ docker-compose.local.yml 로컬 컴포즈
|
||||||
|
|||||||
@@ -3,6 +3,11 @@ FROM python:3.12-slim
|
|||||||
# 작업 디렉토리
|
# 작업 디렉토리
|
||||||
WORKDIR /app
|
WORKDIR /app
|
||||||
|
|
||||||
|
# 글자 인식(라이브 커머스 결과 이미지 → 매출, app/modules/live/ocr.py) — 영어 데이터만
|
||||||
|
RUN apt-get update \
|
||||||
|
&& apt-get install -y --no-install-recommends tesseract-ocr tesseract-ocr-eng \
|
||||||
|
&& rm -rf /var/lib/apt/lists/*
|
||||||
|
|
||||||
# 의존성 먼저 설치 (캐시 활용)
|
# 의존성 먼저 설치 (캐시 활용)
|
||||||
COPY requirements.txt .
|
COPY requirements.txt .
|
||||||
RUN pip install --no-cache-dir -r requirements.txt
|
RUN pip install --no-cache-dir -r requirements.txt
|
||||||
|
|||||||
@@ -45,6 +45,7 @@ from .errors import (
|
|||||||
Cafe24AuthError,
|
Cafe24AuthError,
|
||||||
Cafe24ConfigError,
|
Cafe24ConfigError,
|
||||||
Cafe24Error,
|
Cafe24Error,
|
||||||
|
Cafe24FtpConflict,
|
||||||
Cafe24FtpError,
|
Cafe24FtpError,
|
||||||
Cafe24RateLimitError,
|
Cafe24RateLimitError,
|
||||||
)
|
)
|
||||||
@@ -80,6 +81,7 @@ __all__ = [
|
|||||||
"Cafe24RateLimitError",
|
"Cafe24RateLimitError",
|
||||||
"Cafe24ApiError",
|
"Cafe24ApiError",
|
||||||
"Cafe24FtpError",
|
"Cafe24FtpError",
|
||||||
|
"Cafe24FtpConflict",
|
||||||
]
|
]
|
||||||
|
|
||||||
|
|
||||||
|
|||||||
@@ -164,6 +164,10 @@ class Cafe24Client:
|
|||||||
method = method.upper()
|
method = method.upper()
|
||||||
forced_refresh = False
|
forced_refresh = False
|
||||||
last_error: Exception | None = None
|
last_error: Exception | None = None
|
||||||
|
# 쓰기 요청이 카페24에 도달했을 수도 있는 시도가 있었나(5xx 응답·응답 전 끊김).
|
||||||
|
# 최종 오류에 실어 호출부가 "반영 여부 모름"을 구분하게 한다(errors.Cafe24ApiError).
|
||||||
|
writes = method in ("PUT", "POST", "DELETE", "PATCH")
|
||||||
|
maybe_applied = False
|
||||||
|
|
||||||
for attempt in range(self._max_retries + 1):
|
for attempt in range(self._max_retries + 1):
|
||||||
self._pace()
|
self._pace()
|
||||||
@@ -224,7 +228,9 @@ class Cafe24Client:
|
|||||||
time.sleep(wait)
|
time.sleep(wait)
|
||||||
continue
|
continue
|
||||||
|
|
||||||
error = Cafe24ApiError(message, status=status, endpoint=endpoint)
|
if writes and status >= 500:
|
||||||
|
maybe_applied = True
|
||||||
|
error = Cafe24ApiError(message, status=status, endpoint=endpoint, maybe_applied=maybe_applied)
|
||||||
if error.retryable and attempt < self._max_retries:
|
if error.retryable and attempt < self._max_retries:
|
||||||
last_error = error
|
last_error = error
|
||||||
time.sleep(min(8.0, 0.5 * (2**attempt)))
|
time.sleep(min(8.0, 0.5 * (2**attempt)))
|
||||||
@@ -241,7 +247,11 @@ class Cafe24Client:
|
|||||||
http_status=status, result="ERROR", error_message=message,
|
http_status=status, result="ERROR", error_message=message,
|
||||||
duration_ms=elapsed,
|
duration_ms=elapsed,
|
||||||
)
|
)
|
||||||
last_error = Cafe24ApiError(message, status=0, endpoint=endpoint)
|
# 연결조차 안 된 경우만 "도달하지 않음"이 확실하다. 그 밖(읽기 타임아웃,
|
||||||
|
# 응답 도중 끊김)은 카페24가 요청을 처리했을 수 있다.
|
||||||
|
if writes and not isinstance(exc, (httpx.ConnectError, httpx.ConnectTimeout)):
|
||||||
|
maybe_applied = True
|
||||||
|
last_error = Cafe24ApiError(message, status=0, endpoint=endpoint, maybe_applied=maybe_applied)
|
||||||
if attempt < self._max_retries:
|
if attempt < self._max_retries:
|
||||||
time.sleep(min(8.0, 0.5 * (2**attempt)))
|
time.sleep(min(8.0, 0.5 * (2**attempt)))
|
||||||
continue
|
continue
|
||||||
|
|||||||
@@ -7,15 +7,28 @@ Admin API(OAuth)로는 스킨 파일을 다루지 못한다(`config.py` 상단
|
|||||||
|
|
||||||
실물 확인(스크린샷): 호스트 `{mall_id}.ftp.cafe24.com`, 포트 21, SSL/TLS 미사용
|
실물 확인(스크린샷): 호스트 `{mall_id}.ftp.cafe24.com`, 포트 21, SSL/TLS 미사용
|
||||||
(평문 FTP). 파일은 텍스트(UTF-8)로 다룬다.
|
(평문 FTP). 파일은 텍스트(UTF-8)로 다룬다.
|
||||||
|
|
||||||
|
쓰기는 원본에 직접 STOR 하지 않는다 (write_text_file)
|
||||||
|
직접 STOR 는 전송 도중 끊기면 원본이 **앞부분만 남은 채** 잘린다(스킨 템플릿이면
|
||||||
|
모든 상품 페이지가 깨진다). 그래서
|
||||||
|
1) 같은 폴더의 임시 파일에 올리고 (원본은 아직 그대로)
|
||||||
|
2) 다시 받아 바이트 단위로 검증하고
|
||||||
|
3) 교체 직전 원본을 다시 읽어 편집 시작 값과 같은지 확인하고(충돌 방지)
|
||||||
|
4) RNFR/RNTO 로 이름을 바꿔 교체한다
|
||||||
|
서버가 "이미 있는 이름으로 바꾸기"를 거부하면 원본을 옆 이름으로 비킨 뒤 교체하고,
|
||||||
|
실패하면 원본을 제자리로 되돌린다. 이름 바꾸기 자체를 지원하지 않으면 **중단**한다
|
||||||
|
(직접 STOR 로 물러서지 않는다).
|
||||||
"""
|
"""
|
||||||
|
|
||||||
from __future__ import annotations
|
from __future__ import annotations
|
||||||
|
|
||||||
import ftplib
|
import ftplib
|
||||||
import io
|
import io
|
||||||
|
import posixpath
|
||||||
|
import uuid
|
||||||
|
|
||||||
from .config import Cafe24FtpConfig
|
from .config import Cafe24FtpConfig
|
||||||
from .errors import Cafe24FtpError
|
from .errors import Cafe24FtpConflict, Cafe24FtpError
|
||||||
|
|
||||||
# 응답이 없을 때 무한 대기하지 않도록 — 관리 화면 요청 안에서 동기 호출되므로
|
# 응답이 없을 때 무한 대기하지 않도록 — 관리 화면 요청 안에서 동기 호출되므로
|
||||||
# 너무 길면 안 되지만, 파일 하나(수십 KB) 전송에는 충분히 넉넉해야 한다.
|
# 너무 길면 안 되지만, 파일 하나(수십 KB) 전송에는 충분히 넉넉해야 한다.
|
||||||
@@ -35,37 +48,142 @@ def _connect(config: Cafe24FtpConfig) -> ftplib.FTP:
|
|||||||
raise Cafe24FtpError(f"FTP 연결/로그인에 실패했습니다: {exc}") from exc
|
raise Cafe24FtpError(f"FTP 연결/로그인에 실패했습니다: {exc}") from exc
|
||||||
|
|
||||||
|
|
||||||
|
def _close(ftp: ftplib.FTP) -> None:
|
||||||
|
try:
|
||||||
|
ftp.quit()
|
||||||
|
except Exception: # noqa: BLE001 — 정리 실패는 무시
|
||||||
|
ftp.close()
|
||||||
|
|
||||||
|
|
||||||
|
def _retr(ftp: ftplib.FTP, path: str) -> bytes:
|
||||||
|
buf = io.BytesIO()
|
||||||
|
ftp.retrbinary(f"RETR {path}", buf.write)
|
||||||
|
return buf.getvalue()
|
||||||
|
|
||||||
|
|
||||||
|
def _delete_quiet(ftp: ftplib.FTP, path: str) -> None:
|
||||||
|
try:
|
||||||
|
ftp.delete(path)
|
||||||
|
except ftplib.all_errors:
|
||||||
|
pass # 임시 파일 정리 실패는 무시(이름에 cf24tmp 가 붙어 있어 구분된다)
|
||||||
|
|
||||||
|
|
||||||
def read_text_file(config: Cafe24FtpConfig, path: str) -> str:
|
def read_text_file(config: Cafe24FtpConfig, path: str) -> str:
|
||||||
"""디자인 보관함의 파일 1개를 읽어 텍스트로 돌려준다."""
|
"""디자인 보관함의 파일 1개를 읽어 텍스트로 돌려준다."""
|
||||||
ftp = _connect(config)
|
ftp = _connect(config)
|
||||||
try:
|
try:
|
||||||
buf = io.BytesIO()
|
|
||||||
try:
|
try:
|
||||||
ftp.retrbinary(f"RETR {path}", buf.write)
|
raw = _retr(ftp, path)
|
||||||
except ftplib.all_errors as exc:
|
except ftplib.all_errors as exc:
|
||||||
raise Cafe24FtpError(f"파일을 읽지 못했습니다({path}): {exc}") from exc
|
raise Cafe24FtpError(f"파일을 읽지 못했습니다({path}): {exc}") from exc
|
||||||
try:
|
try:
|
||||||
return buf.getvalue().decode("utf-8")
|
return raw.decode("utf-8")
|
||||||
except UnicodeDecodeError as exc:
|
except UnicodeDecodeError as exc:
|
||||||
raise Cafe24FtpError(f"파일 인코딩을 UTF-8로 해석하지 못했습니다({path}): {exc}") from exc
|
raise Cafe24FtpError(f"파일 인코딩을 UTF-8로 해석하지 못했습니다({path}): {exc}") from exc
|
||||||
finally:
|
finally:
|
||||||
try:
|
_close(ftp)
|
||||||
ftp.quit()
|
|
||||||
except Exception: # noqa: BLE001 — 정리 실패는 무시
|
|
||||||
ftp.close()
|
|
||||||
|
|
||||||
|
|
||||||
def write_text_file(config: Cafe24FtpConfig, path: str, content: str) -> None:
|
def temp_names(path: str, tag: str) -> tuple[str, str]:
|
||||||
"""디자인 보관함의 파일 1개를 통째로 덮어쓴다."""
|
"""(임시 업로드 이름, 원본을 잠시 비킬 이름) — 같은 폴더, 원본 이름 + 표식.
|
||||||
|
|
||||||
|
⚠️ 원래 확장자를 **맨 끝에 그대로** 둔다. 카페24 디자인 FTP 는 허용된 확장자(.js·
|
||||||
|
.html·.css 등)만 받는다 — 예전 이름 `product-swiper.js.cf24tmp-…` 는 확장자가 바뀌어
|
||||||
|
STOR 가 `550 Operation not permitted` 로 거부됐다(실물). 그래서
|
||||||
|
`product-swiper_cf24tmp_<tag>.js` 모양으로 만든다(점·하이픈 대신 밑줄).
|
||||||
|
"""
|
||||||
|
folder, name = posixpath.split(path)
|
||||||
|
stem, ext = posixpath.splitext(name)
|
||||||
|
return (posixpath.join(folder, f"{stem}_cf24tmp_{tag}{ext}"),
|
||||||
|
posixpath.join(folder, f"{stem}_cf24old_{tag}{ext}"))
|
||||||
|
|
||||||
|
|
||||||
|
def write_text_file(
|
||||||
|
config: Cafe24FtpConfig, path: str, content: str, *, expected_current: str | None = None
|
||||||
|
) -> None:
|
||||||
|
"""디자인 보관함의 파일 1개를 안전하게 교체한다(모듈 설명 참고).
|
||||||
|
|
||||||
|
expected_current: 편집 시작(또는 백업) 때 읽은 원본. 주면 교체 직전 원본을 다시
|
||||||
|
읽어 다르면 Cafe24FtpConflict 로 멈춘다(원본 그대로).
|
||||||
|
실패 시 Cafe24FtpError — maybe_applied=True 면 원본이 이미 바뀌었을 수 있다.
|
||||||
|
"""
|
||||||
|
data = content.encode("utf-8")
|
||||||
|
tmp, aside = temp_names(path, uuid.uuid4().hex[:10])
|
||||||
ftp = _connect(config)
|
ftp = _connect(config)
|
||||||
try:
|
try:
|
||||||
buf = io.BytesIO(content.encode("utf-8"))
|
# 1) 임시 파일에 올린다 — 원본은 아직 그대로다.
|
||||||
try:
|
try:
|
||||||
ftp.storbinary(f"STOR {path}", buf)
|
ftp.storbinary(f"STOR {tmp}", io.BytesIO(data))
|
||||||
except ftplib.all_errors as exc:
|
except ftplib.all_errors as exc:
|
||||||
raise Cafe24FtpError(f"파일을 쓰지 못했습니다({path}): {exc}") from exc
|
_delete_quiet(ftp, tmp)
|
||||||
finally:
|
raise Cafe24FtpError(f"임시 파일을 올리지 못했습니다 — 원본은 그대로입니다({path}): {exc}") from exc
|
||||||
|
|
||||||
|
# 2) 검증 — 다시 받아 바이트 단위로 비교한다(전송이 잘렸으면 여기서 잡힌다).
|
||||||
try:
|
try:
|
||||||
ftp.quit()
|
uploaded = _retr(ftp, tmp)
|
||||||
except Exception: # noqa: BLE001 — 정리 실패는 무시
|
except ftplib.all_errors as exc:
|
||||||
ftp.close()
|
_delete_quiet(ftp, tmp)
|
||||||
|
raise Cafe24FtpError(f"올린 임시 파일을 확인하지 못했습니다 — 원본은 그대로입니다: {exc}") from exc
|
||||||
|
if uploaded != data:
|
||||||
|
_delete_quiet(ftp, tmp)
|
||||||
|
raise Cafe24FtpError(
|
||||||
|
f"올린 임시 파일이 보낸 내용과 다릅니다({len(uploaded)}/{len(data)}바이트) — 원본은 그대로입니다."
|
||||||
|
)
|
||||||
|
|
||||||
|
# 3) 충돌 확인 — 교체 직전의 원본이 편집 시작 값 그대로인가.
|
||||||
|
if expected_current is not None:
|
||||||
|
try:
|
||||||
|
now = _retr(ftp, path)
|
||||||
|
except ftplib.all_errors as exc:
|
||||||
|
_delete_quiet(ftp, tmp)
|
||||||
|
raise Cafe24FtpError(f"교체 직전 원본을 다시 읽지 못했습니다 — 원본은 그대로입니다: {exc}") from exc
|
||||||
|
if now != expected_current.encode("utf-8"):
|
||||||
|
_delete_quiet(ftp, tmp)
|
||||||
|
raise Cafe24FtpConflict(
|
||||||
|
"적용하는 사이 FTP 파일이 바뀌었습니다 — 원본은 그대로입니다. 새로고침해 확인한 뒤 다시 적용하세요."
|
||||||
|
)
|
||||||
|
|
||||||
|
# 4) 교체 — 이름 바꾸기. 덮어쓰기를 거부하는 서버면 원본을 비킨 뒤 교체한다.
|
||||||
|
moved_aside = False
|
||||||
|
try:
|
||||||
|
ftp.rename(tmp, path)
|
||||||
|
except ftplib.all_errors as first:
|
||||||
|
try:
|
||||||
|
ftp.rename(path, aside)
|
||||||
|
except ftplib.all_errors as exc:
|
||||||
|
_delete_quiet(ftp, tmp)
|
||||||
|
raise Cafe24FtpError(
|
||||||
|
"이 FTP 서버가 파일 이름 바꾸기(rename)를 지원하지 않아 중단했습니다 — 원본은 그대로입니다. "
|
||||||
|
f"({first} / {exc})"
|
||||||
|
) from exc
|
||||||
|
try:
|
||||||
|
ftp.rename(tmp, path)
|
||||||
|
except ftplib.all_errors as exc:
|
||||||
|
try:
|
||||||
|
ftp.rename(aside, path)
|
||||||
|
except ftplib.all_errors as exc2:
|
||||||
|
raise Cafe24FtpError(
|
||||||
|
f"교체에 실패했고 원본 되돌리기도 실패했습니다. FTP 에서 {aside} 를 {path} 로 "
|
||||||
|
f"직접 되돌리세요: {exc} / {exc2}",
|
||||||
|
maybe_applied=True,
|
||||||
|
) from exc2
|
||||||
|
_delete_quiet(ftp, tmp)
|
||||||
|
raise Cafe24FtpError(f"교체에 실패해 원본을 되돌렸습니다: {exc}") from exc
|
||||||
|
moved_aside = True
|
||||||
|
|
||||||
|
# 5) 확인 — 교체 뒤 원본 경로가 새 내용인가.
|
||||||
|
try:
|
||||||
|
final = _retr(ftp, path)
|
||||||
|
except ftplib.all_errors as exc:
|
||||||
|
raise Cafe24FtpError(
|
||||||
|
f"교체 뒤 확인 조회에 실패했습니다 — 적용됐을 수 있으니 파일을 다시 열어 확인하세요: {exc}",
|
||||||
|
maybe_applied=True,
|
||||||
|
) from exc
|
||||||
|
if final != data:
|
||||||
|
raise Cafe24FtpError(
|
||||||
|
"교체 뒤 파일 내용이 보낸 것과 다릅니다 — 파일을 다시 열어 확인하세요.", maybe_applied=True
|
||||||
|
)
|
||||||
|
if moved_aside:
|
||||||
|
_delete_quiet(ftp, aside)
|
||||||
|
finally:
|
||||||
|
_close(ftp)
|
||||||
|
|||||||
@@ -32,16 +32,35 @@ class Cafe24RateLimitError(Cafe24Error):
|
|||||||
|
|
||||||
|
|
||||||
class Cafe24FtpError(Cafe24Error):
|
class Cafe24FtpError(Cafe24Error):
|
||||||
"""디자인 보관함 FTP 연결/전송 실패 (product-swiper.js 편집 등)."""
|
"""디자인 보관함 FTP 연결/전송 실패 (product-swiper.js 편집 등).
|
||||||
|
|
||||||
|
maybe_applied: 원본 경로가 이미 새 내용으로 바뀌었을 수 있다(교체 뒤 확인 단계 실패).
|
||||||
|
False 면 원본은 그대로다(임시 파일 단계에서 멈춤).
|
||||||
|
"""
|
||||||
|
|
||||||
|
def __init__(self, message: str, *, maybe_applied: bool = False):
|
||||||
|
super().__init__(message)
|
||||||
|
self.maybe_applied = maybe_applied
|
||||||
|
|
||||||
|
|
||||||
|
class Cafe24FtpConflict(Cafe24FtpError):
|
||||||
|
"""교체 직전 다시 읽은 원본이 편집 시작 때와 다르다 — 남의 수정을 덮지 않고 멈춘다."""
|
||||||
|
|
||||||
|
|
||||||
class Cafe24ApiError(Cafe24Error):
|
class Cafe24ApiError(Cafe24Error):
|
||||||
"""그 외 API 오류(4xx/5xx). status 로 재시도 가능 여부를 판단한다."""
|
"""그 외 API 오류(4xx/5xx). status 로 재시도 가능 여부를 판단한다.
|
||||||
|
|
||||||
def __init__(self, message: str, *, status: int = 0, endpoint: str = ""):
|
maybe_applied: 쓰기 요청(PUT/POST/DELETE)이 카페24에 **도달했을 수도** 있는가.
|
||||||
|
응답을 받기 전에 끊겼거나(읽기 타임아웃 등) 5xx 를 받은 시도가 한 번이라도
|
||||||
|
있으면 True — 반영됐는지 모르므로 호출부는 재적용하지 말고 "확인 필요"로 둔다.
|
||||||
|
연결 자체가 안 된 경우(ConnectError)와 4xx 는 반영되지 않은 것이 확실하다.
|
||||||
|
"""
|
||||||
|
|
||||||
|
def __init__(self, message: str, *, status: int = 0, endpoint: str = "", maybe_applied: bool = False):
|
||||||
super().__init__(message)
|
super().__init__(message)
|
||||||
self.status = status
|
self.status = status
|
||||||
self.endpoint = endpoint
|
self.endpoint = endpoint
|
||||||
|
self.maybe_applied = maybe_applied
|
||||||
|
|
||||||
@property
|
@property
|
||||||
def retryable(self) -> bool:
|
def retryable(self) -> bool:
|
||||||
|
|||||||
@@ -22,6 +22,7 @@ from dataclasses import dataclass
|
|||||||
from typing import Any
|
from typing import Any
|
||||||
|
|
||||||
from .client import Cafe24Client
|
from .client import Cafe24Client
|
||||||
|
from .errors import Cafe24Error
|
||||||
|
|
||||||
# 카페24 상품 목록 API 의 1회 최대 조회 수
|
# 카페24 상품 목록 API 의 1회 최대 조회 수
|
||||||
PAGE_LIMIT = 100
|
PAGE_LIMIT = 100
|
||||||
@@ -476,26 +477,55 @@ def wait_for_variants(
|
|||||||
return latest
|
return latest
|
||||||
|
|
||||||
|
|
||||||
|
VARIANT_CHUNK = 100 # 카페24 문서상 PUT variants 1회 최대 건수
|
||||||
|
|
||||||
|
# update_variants 행별 결과 상태
|
||||||
|
VARIANT_OK = "ok" # 카페24가 받아들임
|
||||||
|
VARIANT_FAILED = "failed" # 거절 — 반영되지 않음이 확실
|
||||||
|
VARIANT_UNKNOWN = "unknown" # 요청이 도달했을 수 있으나 응답을 못 받음 — 반영 여부 모름
|
||||||
|
|
||||||
|
|
||||||
def update_variants(
|
def update_variants(
|
||||||
client: Cafe24Client, product_no: int, requests: list[dict[str, Any]]
|
client: Cafe24Client, product_no: int, requests: list[dict[str, Any]], *, shop_no: int = 1
|
||||||
) -> list[dict[str, Any]]:
|
) -> list[dict[str, Any]]:
|
||||||
"""여러 품목 부분 수정. 100건씩 나눠 보낸다(문서상 1회 100건 제한)."""
|
"""여러 품목 부분 수정 — **행별 결과**를 돌려준다(요청 순서 그대로).
|
||||||
|
|
||||||
|
[{"variant_code": "...", "status": "ok"|"failed"|"unknown",
|
||||||
|
"error": "", "variant": {카페24 응답의 그 품목 — 없으면 {}}}]
|
||||||
|
|
||||||
|
100건씩 나눠 보낸다(문서상 1회 100건 제한). 한 묶음이 실패해도 멈추지 않고 다음
|
||||||
|
묶음을 보낸다 — 앞 묶음이 이미 반영됐는데 전체를 실패로 알리면 화면과 카페24가
|
||||||
|
어긋나고, 사용자가 반영된 행까지 다시 보내게 된다. 호출부는 ok 인 행만 반영됨으로
|
||||||
|
기록한다.
|
||||||
|
"""
|
||||||
no = int(product_no)
|
no = int(product_no)
|
||||||
out: list[dict[str, Any]] = []
|
out: list[dict[str, Any]] = []
|
||||||
for start in range(0, len(requests), 100):
|
for start in range(0, len(requests), VARIANT_CHUNK):
|
||||||
chunk = requests[start : start + 100]
|
chunk = requests[start : start + VARIANT_CHUNK]
|
||||||
if not chunk:
|
if not chunk:
|
||||||
continue
|
continue
|
||||||
payload = client.put(
|
try:
|
||||||
f"/admin/products/{no}/variants", json={"shop_no": 1, "requests": chunk}, product_no=no
|
payload = client.put(
|
||||||
)
|
f"/admin/products/{no}/variants", json={"shop_no": int(shop_no), "requests": chunk}, product_no=no
|
||||||
|
)
|
||||||
|
except Cafe24Error as exc:
|
||||||
|
status = VARIANT_UNKNOWN if getattr(exc, "maybe_applied", False) else VARIANT_FAILED
|
||||||
|
for row in chunk:
|
||||||
|
out.append({"variant_code": str(row.get("variant_code") or ""), "status": status,
|
||||||
|
"error": str(exc), "variant": {}})
|
||||||
|
continue
|
||||||
result = payload.get("variants") if isinstance(payload, dict) else None
|
result = payload.get("variants") if isinstance(payload, dict) else None
|
||||||
|
returned: list[dict[str, Any]] = []
|
||||||
if isinstance(result, list):
|
if isinstance(result, list):
|
||||||
out.extend(result)
|
returned = [r for r in result if isinstance(r, dict)]
|
||||||
elif isinstance(result, dict):
|
elif isinstance(result, dict):
|
||||||
out.append(result)
|
returned = [result]
|
||||||
elif isinstance(payload.get("variant"), dict):
|
elif isinstance(payload, dict) and isinstance(payload.get("variant"), dict):
|
||||||
out.append(payload["variant"])
|
returned = [payload["variant"]]
|
||||||
|
by_code = {str(r.get("variant_code") or ""): r for r in returned}
|
||||||
|
for row in chunk:
|
||||||
|
code = str(row.get("variant_code") or "")
|
||||||
|
out.append({"variant_code": code, "status": VARIANT_OK, "error": "", "variant": by_code.get(code, {})})
|
||||||
return out
|
return out
|
||||||
|
|
||||||
|
|
||||||
|
|||||||
@@ -0,0 +1,345 @@
|
|||||||
|
"""Google 드라이브에 올려 둔 엑셀(.xlsx) 파일을 시트처럼 고쳐 쓰기(쿠팡 밀크런 출고리스트, 2026-10-23).
|
||||||
|
|
||||||
|
구글 시트 문서가 아니라 드라이브의 .xlsx 파일이면 Sheets API 로는 쓸 수 없다. 그래서
|
||||||
|
파일을 내려받아(openpyxl) 고친 뒤 같은 파일 id 에 내용을 다시 올린다(링크·공유·이름 그대로).
|
||||||
|
|
||||||
|
- 인증은 google_drive 와 같다(서비스 계정 우선, 없으면 OAuth 리프레시 토큰 — Drive 권한 포함).
|
||||||
|
- `GoogleSheetsWriter` 와 같은 메서드(sheet_titles·read_ranges·append_block·write_table·delete_sheet·lock)를
|
||||||
|
같은 인자로 제공한다 → cupang 라우터는 어느 쪽인지 몰라도 된다(`file_kind` 로 골라 씀).
|
||||||
|
- `with writer.lock:` 안의 호출은 내려받은 사본 하나를 같이 쓰고, 블록이 끝날 때 바뀐 게 있으면 한 번만 올린다.
|
||||||
|
잠금 밖에서 부른 메서드는 호출마다 내려받고(바뀌면) 올린다.
|
||||||
|
- 올리기 직전에 파일 version 을 다시 보고, 그 사이 누가 고쳤으면 `XlsxChangedError` — 덮어쓰지 않는다
|
||||||
|
(호출부가 처음부터 다시 시도).
|
||||||
|
- 비밀값은 로그·화면에 출력하지 않는다.
|
||||||
|
"""
|
||||||
|
|
||||||
|
from __future__ import annotations
|
||||||
|
|
||||||
|
import re
|
||||||
|
import threading
|
||||||
|
from io import BytesIO
|
||||||
|
from typing import Any
|
||||||
|
|
||||||
|
from app.integrations.google_drive import GoogleDriveError, GoogleDriveFiles, _friendly_drive
|
||||||
|
|
||||||
|
XLSX_MIME = "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet"
|
||||||
|
SHEETS_MIME = "application/vnd.google-apps.spreadsheet"
|
||||||
|
_RANGE_RE = re.compile(r"^([A-Z]+)(\d*)(?::([A-Z]+)(\d*))?$")
|
||||||
|
|
||||||
|
# 같은 파일을 두 요청이 동시에 내려받아 고치면 나중 것이 앞의 것을 지우므로 한 번에 하나씩.
|
||||||
|
_LOCK = threading.RLock()
|
||||||
|
_KIND_CACHE: dict[str, str] = {}
|
||||||
|
|
||||||
|
|
||||||
|
class XlsxChangedError(RuntimeError):
|
||||||
|
"""내려받은 뒤 올리기 전에 다른 사람이 파일을 고쳤다."""
|
||||||
|
|
||||||
|
|
||||||
|
def _col_num(letters: str) -> int:
|
||||||
|
n = 0
|
||||||
|
for ch in letters:
|
||||||
|
n = n * 26 + (ord(ch) - 64)
|
||||||
|
return n
|
||||||
|
|
||||||
|
|
||||||
|
def _parse_range(a1: str) -> tuple[str, int, int, int | None, int | None]:
|
||||||
|
""""'시트'!F6:F" → (시트, 첫 행, 첫 열, 끝 행|None, 끝 열|None). 끝이 비면 시트 끝까지."""
|
||||||
|
sheet, _, ref = a1.rpartition("!")
|
||||||
|
if sheet.startswith("'") and sheet.endswith("'"):
|
||||||
|
sheet = sheet[1:-1].replace("''", "'")
|
||||||
|
m = _RANGE_RE.match(ref.upper())
|
||||||
|
if not sheet or not m:
|
||||||
|
raise ValueError(f"지원하지 않는 범위: {a1}")
|
||||||
|
c1, r1, c2, r2 = m.groups()
|
||||||
|
if c2 is None: # 셀 하나
|
||||||
|
c2, r2 = c1, r1
|
||||||
|
return sheet, int(r1 or 1), _col_num(c1), (int(r2) if r2 else None), _col_num(c2)
|
||||||
|
|
||||||
|
|
||||||
|
def _text(value: Any) -> str:
|
||||||
|
"""Sheets API 의 FORMATTED_VALUE 처럼 문자열로(정수인 실수는 소수점 없이)."""
|
||||||
|
if value is None:
|
||||||
|
return ""
|
||||||
|
if isinstance(value, float) and value.is_integer():
|
||||||
|
return str(int(value))
|
||||||
|
return str(value)
|
||||||
|
|
||||||
|
|
||||||
|
def _put(cell: Any, value: Any) -> None:
|
||||||
|
"""Sheets 의 USER_ENTERED 처럼 앞의 작은따옴표는 "글자 그대로" 표시로 보고 떼어 낸다."""
|
||||||
|
if isinstance(value, str) and value.startswith("'"):
|
||||||
|
cell.value = value[1:]
|
||||||
|
cell.data_type = "s" # '=' 로 시작해도 수식이 되지 않게
|
||||||
|
else:
|
||||||
|
cell.value = value
|
||||||
|
|
||||||
|
|
||||||
|
class DriveXlsxWriter(GoogleDriveFiles):
|
||||||
|
"""드라이브 .xlsx 파일 하나를 GoogleSheetsWriter 처럼 다룬다(spreadsheet_id = 드라이브 파일 id)."""
|
||||||
|
|
||||||
|
def __init__(self) -> None:
|
||||||
|
super().__init__()
|
||||||
|
self._depth = 0
|
||||||
|
self._book: dict[str, Any] | None = None # {"id", "wb", "version", "dirty"}
|
||||||
|
|
||||||
|
# ── 내려받기 / 올리기 ───────────────────────────
|
||||||
|
def file_kind(self, file_id: str) -> str:
|
||||||
|
""""xlsx" | "sheets" | 그 밖의 mimeType. 실패는 GoogleDriveError(사유)."""
|
||||||
|
if file_id in _KIND_CACHE:
|
||||||
|
return _KIND_CACHE[file_id]
|
||||||
|
meta = self._meta(file_id, "mimeType")
|
||||||
|
mime = str(meta.get("mimeType") or "")
|
||||||
|
kind = "xlsx" if mime == XLSX_MIME else "sheets" if mime == SHEETS_MIME else mime
|
||||||
|
_KIND_CACHE[file_id] = kind
|
||||||
|
return kind
|
||||||
|
|
||||||
|
def _meta(self, file_id: str, fields: str) -> dict[str, Any]:
|
||||||
|
self._check()
|
||||||
|
try:
|
||||||
|
return self._service().files().get(fileId=file_id, fields=fields, supportsAllDrives=True).execute()
|
||||||
|
except Exception as exc: # noqa: BLE001
|
||||||
|
raise self._error(exc) from None
|
||||||
|
|
||||||
|
@staticmethod
|
||||||
|
def _error(exc: Exception) -> GoogleDriveError:
|
||||||
|
text = _friendly_drive(exc).replace("업무 파일 폴더", "출고리스트 엑셀 파일")
|
||||||
|
return GoogleDriveError(text)
|
||||||
|
|
||||||
|
def _open(self, file_id: str) -> dict[str, Any]:
|
||||||
|
from openpyxl import load_workbook
|
||||||
|
|
||||||
|
version = str(self._meta(file_id, "version").get("version") or "")
|
||||||
|
try:
|
||||||
|
data = self._service().files().get_media(fileId=file_id, supportsAllDrives=True).execute()
|
||||||
|
except Exception as exc: # noqa: BLE001
|
||||||
|
raise self._error(exc) from None
|
||||||
|
return {"id": file_id, "wb": load_workbook(BytesIO(data)), "version": version, "dirty": False}
|
||||||
|
|
||||||
|
def _save(self, book: dict[str, Any]) -> None:
|
||||||
|
from googleapiclient.http import MediaIoBaseUpload
|
||||||
|
|
||||||
|
now = str(self._meta(book["id"], "version").get("version") or "")
|
||||||
|
if book["version"] and now != book["version"]:
|
||||||
|
raise XlsxChangedError("출고리스트 엑셀 파일이 그 사이 바뀌었습니다.")
|
||||||
|
out = BytesIO()
|
||||||
|
book["wb"].save(out)
|
||||||
|
out.seek(0)
|
||||||
|
try:
|
||||||
|
self._service().files().update(
|
||||||
|
fileId=book["id"], media_body=MediaIoBaseUpload(out, mimetype=XLSX_MIME, resumable=False),
|
||||||
|
fields="id", supportsAllDrives=True,
|
||||||
|
).execute()
|
||||||
|
except Exception as exc: # noqa: BLE001
|
||||||
|
raise self._error(exc) from None
|
||||||
|
|
||||||
|
class _Session:
|
||||||
|
def __init__(self, writer: "DriveXlsxWriter") -> None:
|
||||||
|
self.w = writer
|
||||||
|
|
||||||
|
def __enter__(self) -> "DriveXlsxWriter":
|
||||||
|
_LOCK.acquire()
|
||||||
|
self.w._depth += 1
|
||||||
|
return self.w
|
||||||
|
|
||||||
|
def __exit__(self, exc_type: Any, *_: Any) -> None:
|
||||||
|
w = self.w
|
||||||
|
try:
|
||||||
|
w._depth -= 1
|
||||||
|
if w._depth == 0:
|
||||||
|
book, w._book = w._book, None
|
||||||
|
if exc_type is None and book is not None and book["dirty"]:
|
||||||
|
w._save(book)
|
||||||
|
finally:
|
||||||
|
_LOCK.release()
|
||||||
|
|
||||||
|
@property
|
||||||
|
def lock(self) -> "DriveXlsxWriter._Session":
|
||||||
|
"""이 블록 안의 호출은 내려받은 사본 하나를 같이 쓰고, 끝날 때 바뀐 게 있으면 한 번 올린다."""
|
||||||
|
return DriveXlsxWriter._Session(self)
|
||||||
|
|
||||||
|
def _wb(self, file_id: str) -> Any:
|
||||||
|
if self._book is None or self._book["id"] != file_id:
|
||||||
|
if self._book is not None and self._book["dirty"]:
|
||||||
|
self._save(self._book)
|
||||||
|
self._book = self._open(file_id)
|
||||||
|
return self._book["wb"]
|
||||||
|
|
||||||
|
def _touch(self) -> None:
|
||||||
|
if self._book is not None:
|
||||||
|
self._book["dirty"] = True
|
||||||
|
|
||||||
|
@staticmethod
|
||||||
|
def _url(file_id: str) -> str:
|
||||||
|
return f"https://docs.google.com/spreadsheets/d/{file_id}/edit"
|
||||||
|
|
||||||
|
# ── GoogleSheetsWriter 와 같은 메서드 ────────────
|
||||||
|
def sheet_titles(self, *, spreadsheet_id: str) -> list[str]:
|
||||||
|
with self.lock:
|
||||||
|
return list(self._wb(spreadsheet_id).sheetnames)
|
||||||
|
|
||||||
|
def read_ranges(self, *, spreadsheet_id: str, ranges: list[str], chunk: int = 50) -> list[list[list[Any]]]:
|
||||||
|
"""범위마다 값의 2차원 목록(문자열) — Sheets API 처럼 뒤쪽 빈 칸·빈 행은 잘라 낸다."""
|
||||||
|
del chunk
|
||||||
|
with self.lock:
|
||||||
|
wb = self._wb(spreadsheet_id)
|
||||||
|
out: list[list[list[Any]]] = []
|
||||||
|
for a1 in ranges:
|
||||||
|
title, r1, c1, r2, c2 = _parse_range(a1)
|
||||||
|
if title not in wb.sheetnames:
|
||||||
|
out.append([])
|
||||||
|
continue
|
||||||
|
ws = wb[title]
|
||||||
|
rows = [
|
||||||
|
[_text(v) for v in row]
|
||||||
|
for row in ws.iter_rows(min_row=r1, max_row=r2 or ws.max_row, min_col=c1,
|
||||||
|
max_col=c2 or ws.max_column, values_only=True)
|
||||||
|
]
|
||||||
|
for row in rows:
|
||||||
|
while row and row[-1] == "":
|
||||||
|
row.pop()
|
||||||
|
while rows and not rows[-1]:
|
||||||
|
rows.pop()
|
||||||
|
out.append(rows)
|
||||||
|
return out
|
||||||
|
|
||||||
|
def append_block(
|
||||||
|
self,
|
||||||
|
*,
|
||||||
|
spreadsheet_id: str,
|
||||||
|
title: str,
|
||||||
|
cells: dict[tuple[int, int], Any],
|
||||||
|
merges: list[tuple[int, int, int, int]],
|
||||||
|
first_row: int,
|
||||||
|
last_row: int,
|
||||||
|
first_col: int,
|
||||||
|
last_col: int,
|
||||||
|
left_cols: tuple[int, ...] = (9,),
|
||||||
|
highlight: str = "",
|
||||||
|
) -> dict[str, Any]:
|
||||||
|
"""이미 있는 시트의 first_row~last_row 에 표 한 덩어리(위쪽 내용은 그대로). 서식은 GoogleSheetsWriter 와 같다."""
|
||||||
|
from openpyxl.styles import PatternFill
|
||||||
|
|
||||||
|
with self.lock:
|
||||||
|
wb = self._wb(spreadsheet_id)
|
||||||
|
if title not in wb.sheetnames:
|
||||||
|
raise LookupError(f"시트 '{title}' 이(가) 없습니다.")
|
||||||
|
ws = wb[title]
|
||||||
|
for (r, c), value in cells.items():
|
||||||
|
_put(ws.cell(row=r, column=c), value)
|
||||||
|
for (r1, c1, r2, c2) in merges:
|
||||||
|
ws.merge_cells(start_row=r1, start_column=c1, end_row=r2, end_column=c2)
|
||||||
|
fill = PatternFill("solid", fgColor=highlight) if highlight else PatternFill(fill_type=None)
|
||||||
|
_style_rows(ws, first_row, last_row, first_col, last_col, left_cols=left_cols, fill=fill)
|
||||||
|
self._touch()
|
||||||
|
return {
|
||||||
|
"created": False, "title": title, "first_row": first_row, "last_row": last_row,
|
||||||
|
"url": self._url(spreadsheet_id),
|
||||||
|
}
|
||||||
|
|
||||||
|
def delete_sheet(self, *, spreadsheet_id: str, title: str) -> dict[str, Any]:
|
||||||
|
"""시트 1장 삭제. 없으면 missing, 문서에 그 하나뿐이면 내용만 비운다(cleared)."""
|
||||||
|
with self.lock:
|
||||||
|
wb = self._wb(spreadsheet_id)
|
||||||
|
if title not in wb.sheetnames:
|
||||||
|
return {"ok": True, "action": "missing", "title": title}
|
||||||
|
if len(wb.sheetnames) <= 1:
|
||||||
|
_replace_sheet(wb, title)
|
||||||
|
action = "cleared"
|
||||||
|
else:
|
||||||
|
wb.remove(wb[title])
|
||||||
|
wb.active = min(wb.index(wb.active) if wb.active is not None else 0, len(wb.sheetnames) - 1)
|
||||||
|
action = "deleted"
|
||||||
|
self._touch()
|
||||||
|
return {"ok": True, "action": action, "title": title}
|
||||||
|
|
||||||
|
def write_table(
|
||||||
|
self,
|
||||||
|
*,
|
||||||
|
spreadsheet_id: str,
|
||||||
|
title: str,
|
||||||
|
cells: dict[tuple[int, int], Any],
|
||||||
|
merges: list[tuple[int, int, int, int]],
|
||||||
|
header_row: int,
|
||||||
|
first_data_row: int,
|
||||||
|
last_row: int,
|
||||||
|
first_col: int,
|
||||||
|
last_col: int,
|
||||||
|
title_row: int,
|
||||||
|
widths: dict[int, int],
|
||||||
|
header_bg: str = "",
|
||||||
|
row_highlights: list[tuple[int, int, str]] | None = None,
|
||||||
|
) -> dict[str, Any]:
|
||||||
|
"""시트를 만들고(있으면 새로 갈아 끼우고) 표를 통째로 기록한다. 좌표 1-based, 색은 "RRGGBB"."""
|
||||||
|
from openpyxl.styles import Alignment, Font, PatternFill
|
||||||
|
from openpyxl.utils import get_column_letter
|
||||||
|
|
||||||
|
with self.lock:
|
||||||
|
wb = self._wb(spreadsheet_id)
|
||||||
|
created = title not in wb.sheetnames
|
||||||
|
ws = _replace_sheet(wb, title)
|
||||||
|
for (r, c), value in cells.items():
|
||||||
|
_put(ws.cell(row=r, column=c), value)
|
||||||
|
for (r1, c1, r2, c2) in merges:
|
||||||
|
ws.merge_cells(start_row=r1, start_column=c1, end_row=r2, end_column=c2)
|
||||||
|
|
||||||
|
center = Alignment(horizontal="center", vertical="center", wrap_text=True)
|
||||||
|
head = ws.cell(row=title_row, column=first_col)
|
||||||
|
head.font = Font(size=16, bold=True)
|
||||||
|
head.alignment = center
|
||||||
|
ws.row_dimensions[title_row].height = 28
|
||||||
|
header_fill = PatternFill("solid", fgColor=header_bg) if header_bg else PatternFill(fill_type=None)
|
||||||
|
_style_rows(ws, header_row, header_row, first_col, last_col, left_cols=(), fill=header_fill)
|
||||||
|
for col in range(first_col, last_col + 1):
|
||||||
|
ws.cell(row=header_row, column=col).font = Font(bold=True)
|
||||||
|
if last_row >= first_data_row:
|
||||||
|
_style_rows(ws, first_data_row, last_row, first_col, last_col, left_cols=(9,), fill=None)
|
||||||
|
for (r1, r2, color) in (row_highlights or []):
|
||||||
|
fill = PatternFill("solid", fgColor=color)
|
||||||
|
for row in range(r1, r2 + 1):
|
||||||
|
for col in range(first_col, last_col + 1):
|
||||||
|
ws.cell(row=row, column=col).fill = fill
|
||||||
|
for col, px in widths.items():
|
||||||
|
ws.column_dimensions[get_column_letter(col)].width = round(px / 7.0, 2)
|
||||||
|
self._touch()
|
||||||
|
return {"created": created, "title": title, "url": self._url(spreadsheet_id)}
|
||||||
|
|
||||||
|
|
||||||
|
def _replace_sheet(wb: Any, title: str) -> Any:
|
||||||
|
"""같은 이름의 빈 시트로 갈아 끼운다(탭 위치 유지). 없으면 맨 뒤에 새로."""
|
||||||
|
if title in wb.sheetnames:
|
||||||
|
index = wb.sheetnames.index(title)
|
||||||
|
wb.remove(wb[title])
|
||||||
|
return wb.create_sheet(title, index)
|
||||||
|
return wb.create_sheet(title)
|
||||||
|
|
||||||
|
|
||||||
|
def _style_rows(
|
||||||
|
ws: Any, r1: int, r2: int, c1: int, c2: int, *, left_cols: tuple[int, ...], fill: Any
|
||||||
|
) -> None:
|
||||||
|
"""가운데 정렬·줄바꿈·얇은 검은 테두리, left_cols 만 왼쪽 정렬. fill 이 None 이면 배경은 그대로."""
|
||||||
|
from openpyxl.styles import Alignment, Border, Side
|
||||||
|
|
||||||
|
thin = Side(style="thin", color="000000")
|
||||||
|
box = Border(left=thin, right=thin, top=thin, bottom=thin)
|
||||||
|
center = Alignment(horizontal="center", vertical="center", wrap_text=True)
|
||||||
|
left = Alignment(horizontal="left", vertical="center", wrap_text=True)
|
||||||
|
for row in range(r1, r2 + 1):
|
||||||
|
for col in range(c1, c2 + 1):
|
||||||
|
cell = ws.cell(row=row, column=col)
|
||||||
|
cell.border = box
|
||||||
|
cell.alignment = left if col in left_cols else center
|
||||||
|
if fill is not None:
|
||||||
|
cell.fill = fill
|
||||||
|
|
||||||
|
|
||||||
|
_WRITER: DriveXlsxWriter | None = None
|
||||||
|
_WRITER_LOCK = threading.Lock()
|
||||||
|
|
||||||
|
|
||||||
|
def get_writer() -> DriveXlsxWriter:
|
||||||
|
"""프로세스당 하나(설정이 비어 있으면 매번 다시 확인)."""
|
||||||
|
global _WRITER
|
||||||
|
with _WRITER_LOCK:
|
||||||
|
if _WRITER is None or not _WRITER.enabled:
|
||||||
|
_WRITER = DriveXlsxWriter()
|
||||||
|
return _WRITER
|
||||||
@@ -0,0 +1,209 @@
|
|||||||
|
"""Google 드라이브 — 업무 파일 올리기(설명란·보드 카드·세부 업무에 파일 끌어 놓기, 2026-10-19).
|
||||||
|
|
||||||
|
인증은 google_slides 와 같은 설정(서비스 계정 우선, 없으면 OAuth 리프레시 토큰 — Drive 권한 포함)을 쓴다.
|
||||||
|
|
||||||
|
- 최상위 폴더 `PROJECT_DRIVE_FOLDER_ID`(기본 = 업무 파일 폴더). 그 아래 `프로젝트/섹션/업무/세부 업무` 폴더를 이름으로
|
||||||
|
찾고 없으면 만든다(휴지통 폴더 제외). 같은 경로를 두 사람이 동시에 만들지 않게 폴더 찾기·만들기는 한 번에 하나씩.
|
||||||
|
- 올린 파일은 appProperties `dbxTaskId` = 업무 id — 설명란에서 링크를 지우면 **우리가 올린 파일만** 휴지통으로 보낸다
|
||||||
|
(다른 사람이 붙여 넣은 드라이브 링크는 건드리지 않음). 링크를 되살리면(되돌리기·잘라 붙이기) 휴지통에서 꺼낸다.
|
||||||
|
휴지통 파일은 드라이브가 30일 뒤 지운다.
|
||||||
|
- 서비스 계정은 내 드라이브 저장 용량이 없어 "공유 드라이브" 폴더여야 올라간다(OAuth 토큰이면 그 사용자 드라이브도 됨).
|
||||||
|
- 비밀값(키/토큰)은 로그·화면에 절대 출력하지 않는다. 라이브러리·설정이 없으면 `enabled = False`.
|
||||||
|
"""
|
||||||
|
|
||||||
|
from __future__ import annotations
|
||||||
|
|
||||||
|
import os
|
||||||
|
import re
|
||||||
|
import threading
|
||||||
|
from typing import Any, BinaryIO, Iterable
|
||||||
|
|
||||||
|
from app.integrations.google_slides import GoogleSlidesClient, _friendly
|
||||||
|
|
||||||
|
DEFAULT_FOLDER_ID = "1Zdak2FtACRJ6peOnA9zD22hsbbsTixJG"
|
||||||
|
FOLDER_MIME = "application/vnd.google-apps.folder"
|
||||||
|
TASK_KEY = "dbxTaskId"
|
||||||
|
CHUNK = 8 * 1024 * 1024
|
||||||
|
# 설명란 링크에서 드라이브 파일 id — 우리가 넣는 링크 모양(https://drive.google.com/file/d/<id>/view)
|
||||||
|
FILE_LINK_RE = re.compile(r"https://drive\.google\.com/file/d/([A-Za-z0-9_-]{10,})")
|
||||||
|
|
||||||
|
# 폴더 찾기·만들기는 한 번에 하나(같은 폴더가 두 개 생기지 않게). 파일 올리기·휴지통은 호출마다 따로 만든
|
||||||
|
# 서비스 객체로(googleapiclient 의 HTTP 는 스레드 안전하지 않다) — 큰 파일이 다른 사람 업로드를 막지 않게.
|
||||||
|
_FOLDER_LOCK = threading.Lock()
|
||||||
|
|
||||||
|
|
||||||
|
class GoogleDriveError(RuntimeError):
|
||||||
|
"""화면에 보여도 되는 사유(비밀값 없음)."""
|
||||||
|
|
||||||
|
|
||||||
|
def root_folder_id() -> str:
|
||||||
|
return (os.getenv("PROJECT_DRIVE_FOLDER_ID") or "").strip() or DEFAULT_FOLDER_ID
|
||||||
|
|
||||||
|
|
||||||
|
def file_url(file_id: str) -> str:
|
||||||
|
return f"https://drive.google.com/file/d/{file_id}/view"
|
||||||
|
|
||||||
|
|
||||||
|
def file_ids_in(html: str) -> set[str]:
|
||||||
|
"""설명 HTML 안의 드라이브 파일 링크 id 들."""
|
||||||
|
return set(FILE_LINK_RE.findall(html or ""))
|
||||||
|
|
||||||
|
|
||||||
|
def folder_name(name: Any) -> str:
|
||||||
|
"""폴더 이름 — 앞뒤 공백·줄바꿈 정리, 너무 길면 자름, 비면 "(이름 없음)"."""
|
||||||
|
s = re.sub(r"\s+", " ", str(name or "")).strip()[:120]
|
||||||
|
return s or "(이름 없음)"
|
||||||
|
|
||||||
|
|
||||||
|
def _q(value: str) -> str:
|
||||||
|
"""Drive 검색어 따옴표 안 글자(역슬래시·작은따옴표 이스케이프)."""
|
||||||
|
return value.replace("\\", "\\\\").replace("'", "\\'")
|
||||||
|
|
||||||
|
|
||||||
|
class GoogleDriveFiles(GoogleSlidesClient):
|
||||||
|
"""google_slides 의 인증(서비스 계정·OAuth)을 그대로 쓰고 Drive 만 연다."""
|
||||||
|
|
||||||
|
def __init__(self) -> None: # noqa: D107 — 부모 __init__ 대신(Slides 서비스는 만들지 않음)
|
||||||
|
self.enabled = False
|
||||||
|
self.reason = ""
|
||||||
|
self.auth_mode = ""
|
||||||
|
self._creds: Any = None
|
||||||
|
try:
|
||||||
|
import googleapiclient.discovery # noqa: F401
|
||||||
|
import googleapiclient.http # noqa: F401
|
||||||
|
except ImportError:
|
||||||
|
self.reason = "google-api-python-client 미설치"
|
||||||
|
return
|
||||||
|
creds = self._service_account_creds()
|
||||||
|
if creds is None:
|
||||||
|
creds = self._oauth_creds()
|
||||||
|
if creds is None:
|
||||||
|
if not self.reason:
|
||||||
|
self.reason = "Google 인증 미설정(GOOGLE_SHEETS_CREDENTIALS 또는 GOOGLE_SLIDES_OAUTH_REFRESH_TOKEN 필요)"
|
||||||
|
return
|
||||||
|
self._creds = creds
|
||||||
|
self.enabled = True
|
||||||
|
|
||||||
|
def _service(self) -> Any:
|
||||||
|
from googleapiclient.discovery import build
|
||||||
|
|
||||||
|
return build("drive", "v3", credentials=self._creds, cache_discovery=False)
|
||||||
|
|
||||||
|
def _check(self) -> None:
|
||||||
|
if not self.enabled:
|
||||||
|
raise GoogleDriveError(self.reason or "Google 드라이브 연동이 꺼져 있습니다.")
|
||||||
|
|
||||||
|
# ────────────────────────────────────────────────
|
||||||
|
def ensure_folder_path(self, names: Iterable[str], *, root: str | None = None) -> str:
|
||||||
|
"""root 아래 names 순서대로 폴더를 찾거나 만들고 마지막 폴더 id."""
|
||||||
|
self._check()
|
||||||
|
parent = root or root_folder_id()
|
||||||
|
with _FOLDER_LOCK:
|
||||||
|
try:
|
||||||
|
drive = self._service()
|
||||||
|
for raw in names:
|
||||||
|
name = folder_name(raw)
|
||||||
|
q = (f"'{_q(parent)}' in parents and name = '{_q(name)}' and mimeType = '{FOLDER_MIME}' "
|
||||||
|
"and trashed = false")
|
||||||
|
res = drive.files().list(
|
||||||
|
q=q, fields="files(id)", pageSize=1, supportsAllDrives=True, includeItemsFromAllDrives=True,
|
||||||
|
corpora="allDrives", orderBy="createdTime",
|
||||||
|
).execute()
|
||||||
|
found = res.get("files") or []
|
||||||
|
if found:
|
||||||
|
parent = found[0]["id"]
|
||||||
|
continue
|
||||||
|
parent = drive.files().create(
|
||||||
|
body={"name": name, "mimeType": FOLDER_MIME, "parents": [parent]},
|
||||||
|
fields="id", supportsAllDrives=True,
|
||||||
|
).execute()["id"]
|
||||||
|
except GoogleDriveError:
|
||||||
|
raise
|
||||||
|
except Exception as exc: # noqa: BLE001
|
||||||
|
raise GoogleDriveError(_friendly_drive(exc)) from None
|
||||||
|
return parent
|
||||||
|
|
||||||
|
def upload(self, *, folder_id: str, name: str, stream: BinaryIO, mimetype: str, task_id: int) -> dict[str, Any]:
|
||||||
|
"""폴더에 파일 하나 → {id, name, url}. 이름은 원래 파일 이름.확장자 그대로."""
|
||||||
|
self._check()
|
||||||
|
from googleapiclient.http import MediaIoBaseUpload
|
||||||
|
|
||||||
|
try:
|
||||||
|
media = MediaIoBaseUpload(stream, mimetype=mimetype or "application/octet-stream", chunksize=CHUNK,
|
||||||
|
resumable=True)
|
||||||
|
meta = {"name": name, "parents": [folder_id], "appProperties": {TASK_KEY: str(int(task_id))}}
|
||||||
|
f = self._service().files().create(body=meta, media_body=media, fields="id,name",
|
||||||
|
supportsAllDrives=True).execute()
|
||||||
|
except Exception as exc: # noqa: BLE001
|
||||||
|
raise GoogleDriveError(_friendly_drive(exc)) from None
|
||||||
|
return {"id": f["id"], "name": f.get("name") or name, "url": file_url(f["id"])}
|
||||||
|
|
||||||
|
def ours(self, file_id: str) -> dict[str, Any] | None:
|
||||||
|
"""우리가 올린 파일이면 {trashed, task_id}, 아니면(남의 파일·없는 파일·권한 없음) None."""
|
||||||
|
self._check()
|
||||||
|
try:
|
||||||
|
f = self._service().files().get(fileId=file_id, fields="trashed,appProperties",
|
||||||
|
supportsAllDrives=True).execute()
|
||||||
|
except Exception: # noqa: BLE001 — 지워졌거나 볼 수 없는 파일은 건드리지 않는다
|
||||||
|
return None
|
||||||
|
tid = (f.get("appProperties") or {}).get(TASK_KEY)
|
||||||
|
if not tid:
|
||||||
|
return None
|
||||||
|
return {"trashed": bool(f.get("trashed")), "task_id": tid}
|
||||||
|
|
||||||
|
def move_to(self, file_id: str, folder_id: str, *, task_id: int) -> bool:
|
||||||
|
"""그 업무가 올린 파일(appProperties dbxTaskId == task_id)이면 folder_id 로 옮긴다 — 옮겼으면 True.
|
||||||
|
남의 파일·다른 업무가 올린 파일(링크만 붙여 넣은 것)·이미 그 폴더에 있는 파일은 그대로 둔다."""
|
||||||
|
self._check()
|
||||||
|
try:
|
||||||
|
drive = self._service()
|
||||||
|
f = drive.files().get(fileId=file_id, fields="parents,appProperties",
|
||||||
|
supportsAllDrives=True).execute()
|
||||||
|
except Exception: # noqa: BLE001 — 지워졌거나 볼 수 없는 파일은 건드리지 않는다
|
||||||
|
return False
|
||||||
|
if (f.get("appProperties") or {}).get(TASK_KEY) != str(int(task_id)):
|
||||||
|
return False
|
||||||
|
parents = [p for p in (f.get("parents") or []) if p]
|
||||||
|
if parents == [folder_id]:
|
||||||
|
return False
|
||||||
|
try:
|
||||||
|
drive.files().update(fileId=file_id, addParents=folder_id,
|
||||||
|
removeParents=",".join(p for p in parents if p != folder_id),
|
||||||
|
fields="id", supportsAllDrives=True).execute()
|
||||||
|
except Exception as exc: # noqa: BLE001
|
||||||
|
raise GoogleDriveError(_friendly_drive(exc)) from None
|
||||||
|
return True
|
||||||
|
|
||||||
|
def set_trashed(self, file_id: str, trashed: bool) -> None:
|
||||||
|
self._check()
|
||||||
|
try:
|
||||||
|
self._service().files().update(fileId=file_id, body={"trashed": bool(trashed)},
|
||||||
|
supportsAllDrives=True).execute()
|
||||||
|
except Exception as exc: # noqa: BLE001
|
||||||
|
raise GoogleDriveError(_friendly_drive(exc)) from None
|
||||||
|
|
||||||
|
|
||||||
|
def _friendly_drive(exc: Exception) -> str:
|
||||||
|
status = getattr(getattr(exc, "resp", None), "status", None)
|
||||||
|
text = str(exc)
|
||||||
|
if "storageQuotaExceeded" in text or "do not have storage quota" in text:
|
||||||
|
return ("서비스 계정은 내 드라이브에 파일을 올릴 수 없습니다 — 업무 파일 폴더를 공유 드라이브에 두거나 "
|
||||||
|
"OAuth 토큰(GOOGLE_SLIDES_OAUTH_REFRESH_TOKEN)을 쓰세요.")
|
||||||
|
if status == 404:
|
||||||
|
return "업무 파일 폴더를 찾을 수 없습니다(PROJECT_DRIVE_FOLDER_ID·폴더 공유 권한 확인)."
|
||||||
|
if status == 403 and "insufficient" not in text.lower():
|
||||||
|
return "Google 드라이브 접근이 거부되었습니다(폴더 편집 권한·Drive API 사용 설정 확인)."
|
||||||
|
return _friendly(exc).replace("Google 슬라이드 처리 실패", "Google 드라이브 처리 실패")
|
||||||
|
|
||||||
|
|
||||||
|
_CLIENT: GoogleDriveFiles | None = None
|
||||||
|
_CLIENT_LOCK = threading.Lock()
|
||||||
|
|
||||||
|
|
||||||
|
def get_client() -> GoogleDriveFiles:
|
||||||
|
"""프로세스당 하나(설정이 비어 있으면 매번 다시 확인 — .env 를 고치고 재시작 없이도 사유가 갱신되게)."""
|
||||||
|
global _CLIENT
|
||||||
|
with _CLIENT_LOCK:
|
||||||
|
if _CLIENT is None or not _CLIENT.enabled:
|
||||||
|
_CLIENT = GoogleDriveFiles()
|
||||||
|
return _CLIENT
|
||||||
@@ -42,6 +42,37 @@ def _hex_color(value: str) -> dict[str, float]:
|
|||||||
}
|
}
|
||||||
|
|
||||||
|
|
||||||
|
def a1_sheet(title: str) -> str:
|
||||||
|
"""A1 표기용 시트 이름 — 작은따옴표로 감싸고 안의 ' 는 '' 로."""
|
||||||
|
return "'" + title.replace("'", "''") + "'"
|
||||||
|
|
||||||
|
|
||||||
|
def col_letter(col: int) -> str:
|
||||||
|
"""1-based 열 번호 → 열 문자(A, B, …, AA)."""
|
||||||
|
letters = ""
|
||||||
|
while col > 0:
|
||||||
|
col, rem = divmod(col - 1, 26)
|
||||||
|
letters = chr(65 + rem) + letters
|
||||||
|
return letters
|
||||||
|
|
||||||
|
|
||||||
|
def _repeat_cell(
|
||||||
|
sheet_id: int, r1: int, c1: int, r2: int, c2: int, fmt: dict[str, Any], fields: str
|
||||||
|
) -> dict[str, Any]:
|
||||||
|
"""1-based 양끝 포함 범위에 같은 서식을 입히는 요청."""
|
||||||
|
return {
|
||||||
|
"repeatCell": {
|
||||||
|
"range": {
|
||||||
|
"sheetId": sheet_id,
|
||||||
|
"startRowIndex": r1 - 1, "endRowIndex": r2,
|
||||||
|
"startColumnIndex": c1 - 1, "endColumnIndex": c2,
|
||||||
|
},
|
||||||
|
"cell": {"userEnteredFormat": fmt},
|
||||||
|
"fields": fields,
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
# 웹 핸들러가 sync def(스레드풀)라 여러 요청이 동시에 이 writer 를 쓸 수 있다.
|
# 웹 핸들러가 sync def(스레드풀)라 여러 요청이 동시에 이 writer 를 쓸 수 있다.
|
||||||
# googleapiclient 의 HTTP 클라이언트(httplib2)는 스레드 안전하지 않고, 같은 날짜
|
# googleapiclient 의 HTTP 클라이언트(httplib2)는 스레드 안전하지 않고, 같은 날짜
|
||||||
# 시트를 동시에 지우고/쓰면 내용이 섞이므로 시트 작업은 한 번에 하나씩만 한다.
|
# 시트를 동시에 지우고/쓰면 내용이 섞이므로 시트 작업은 한 번에 하나씩만 한다.
|
||||||
@@ -169,6 +200,144 @@ class GoogleSheetsWriter:
|
|||||||
).execute()
|
).execute()
|
||||||
return int(res["replies"][0]["addSheet"]["properties"]["sheetId"])
|
return int(res["replies"][0]["addSheet"]["properties"]["sheetId"])
|
||||||
|
|
||||||
|
@property
|
||||||
|
def lock(self) -> Any:
|
||||||
|
"""읽고 → 쓰기를 한 덩어리로 묶을 때 쓰는 잠금(같은 시트에 동시에 덧붙이지 않게).
|
||||||
|
|
||||||
|
RLock 이라 잡은 채로 이 writer 의 다른 메서드를 불러도 된다."""
|
||||||
|
return _LOCK
|
||||||
|
|
||||||
|
@_serialized
|
||||||
|
def sheet_titles(self, *, spreadsheet_id: str) -> list[str]:
|
||||||
|
"""문서의 시트 이름 목록(탭 순서)."""
|
||||||
|
if not self.enabled:
|
||||||
|
raise RuntimeError(self.reason or "Google Sheets 미설정")
|
||||||
|
meta = self._service.spreadsheets().get(
|
||||||
|
spreadsheetId=spreadsheet_id, fields="sheets.properties.title"
|
||||||
|
).execute()
|
||||||
|
return [str(sh.get("properties", {}).get("title") or "") for sh in meta.get("sheets", [])]
|
||||||
|
|
||||||
|
@_serialized
|
||||||
|
def read_ranges(
|
||||||
|
self, *, spreadsheet_id: str, ranges: list[str], chunk: int = 50
|
||||||
|
) -> list[list[list[Any]]]:
|
||||||
|
"""A1 범위 여러 개의 값(범위마다 2차원 목록). 요청 하나가 너무 길지 않게 나눠 읽는다."""
|
||||||
|
if not self.enabled:
|
||||||
|
raise RuntimeError(self.reason or "Google Sheets 미설정")
|
||||||
|
out: list[list[list[Any]]] = []
|
||||||
|
for i in range(0, len(ranges), chunk):
|
||||||
|
part = ranges[i:i + chunk]
|
||||||
|
res = self._service.spreadsheets().values().batchGet(
|
||||||
|
spreadsheetId=spreadsheet_id, ranges=part
|
||||||
|
).execute()
|
||||||
|
got = res.get("valueRanges", [])
|
||||||
|
out.extend(vr.get("values", []) for vr in got)
|
||||||
|
out.extend([] for _ in range(len(part) - len(got)))
|
||||||
|
return out
|
||||||
|
|
||||||
|
@_serialized
|
||||||
|
def append_block(
|
||||||
|
self,
|
||||||
|
*,
|
||||||
|
spreadsheet_id: str,
|
||||||
|
title: str,
|
||||||
|
cells: dict[tuple[int, int], Any],
|
||||||
|
merges: list[tuple[int, int, int, int]],
|
||||||
|
first_row: int,
|
||||||
|
last_row: int,
|
||||||
|
first_col: int,
|
||||||
|
last_col: int,
|
||||||
|
left_cols: tuple[int, ...] = (9,),
|
||||||
|
highlight: str = "",
|
||||||
|
) -> dict[str, Any]:
|
||||||
|
"""이미 있는 시트의 first_row~last_row 에 표 한 덩어리를 쓴다(위쪽 내용은 그대로).
|
||||||
|
|
||||||
|
서식은 write_table 의 데이터 행과 같다 — 가운데 정렬·줄바꿈·테두리, left_cols 만 왼쪽 정렬,
|
||||||
|
highlight("RRGGBB")가 있으면 그 덩어리 배경색. 좌표는 1-based."""
|
||||||
|
if not self.enabled:
|
||||||
|
raise RuntimeError(self.reason or "Google Sheets 미설정")
|
||||||
|
|
||||||
|
meta = self._service.spreadsheets().get(
|
||||||
|
spreadsheetId=spreadsheet_id,
|
||||||
|
fields="sheets.properties(sheetId,title,gridProperties.rowCount)",
|
||||||
|
).execute()
|
||||||
|
props = next(
|
||||||
|
(sh.get("properties", {}) for sh in meta.get("sheets", [])
|
||||||
|
if sh.get("properties", {}).get("title") == title),
|
||||||
|
None,
|
||||||
|
)
|
||||||
|
if props is None:
|
||||||
|
raise LookupError(f"시트를 찾을 수 없습니다: {title}")
|
||||||
|
sheet_id = int(props.get("sheetId"))
|
||||||
|
row_count = int(props.get("gridProperties", {}).get("rowCount") or 0)
|
||||||
|
|
||||||
|
requests: list[dict[str, Any]] = []
|
||||||
|
if row_count < last_row:
|
||||||
|
# 격자보다 아래에는 값을 쓸 수 없으므로 행을 먼저 늘린다
|
||||||
|
requests.append({"appendDimension": {
|
||||||
|
"sheetId": sheet_id, "dimension": "ROWS", "length": last_row - row_count,
|
||||||
|
}})
|
||||||
|
for (r1, c1, r2, c2) in merges:
|
||||||
|
requests.append({
|
||||||
|
"mergeCells": {
|
||||||
|
"mergeType": "MERGE_ALL",
|
||||||
|
"range": {
|
||||||
|
"sheetId": sheet_id,
|
||||||
|
"startRowIndex": r1 - 1, "endRowIndex": r2,
|
||||||
|
"startColumnIndex": c1 - 1, "endColumnIndex": c2,
|
||||||
|
},
|
||||||
|
}
|
||||||
|
})
|
||||||
|
requests.append(_repeat_cell(
|
||||||
|
sheet_id, first_row, first_col, last_row, last_col,
|
||||||
|
{"horizontalAlignment": "CENTER", "verticalAlignment": "MIDDLE", "wrapStrategy": "WRAP"},
|
||||||
|
"userEnteredFormat(horizontalAlignment,verticalAlignment,wrapStrategy)",
|
||||||
|
))
|
||||||
|
for col in left_cols:
|
||||||
|
requests.append(_repeat_cell(
|
||||||
|
sheet_id, first_row, col, last_row, col,
|
||||||
|
{"horizontalAlignment": "LEFT"}, "userEnteredFormat(horizontalAlignment)",
|
||||||
|
))
|
||||||
|
if highlight:
|
||||||
|
requests.append(_repeat_cell(
|
||||||
|
sheet_id, first_row, first_col, last_row, last_col,
|
||||||
|
{"backgroundColor": _hex_color(highlight)}, "userEnteredFormat(backgroundColor)",
|
||||||
|
))
|
||||||
|
border = {"style": "SOLID", "color": {"red": 0, "green": 0, "blue": 0}}
|
||||||
|
requests.append({
|
||||||
|
"updateBorders": {
|
||||||
|
"range": {
|
||||||
|
"sheetId": sheet_id,
|
||||||
|
"startRowIndex": first_row - 1, "endRowIndex": last_row,
|
||||||
|
"startColumnIndex": first_col - 1, "endColumnIndex": last_col,
|
||||||
|
},
|
||||||
|
"top": border, "bottom": border, "left": border, "right": border,
|
||||||
|
"innerHorizontal": border, "innerVertical": border,
|
||||||
|
}
|
||||||
|
})
|
||||||
|
self._service.spreadsheets().batchUpdate(
|
||||||
|
spreadsheetId=spreadsheet_id, body={"requests": requests}
|
||||||
|
).execute()
|
||||||
|
|
||||||
|
matrix = [
|
||||||
|
[cells.get((r, c), "") for c in range(first_col, last_col + 1)]
|
||||||
|
for r in range(first_row, last_row + 1)
|
||||||
|
]
|
||||||
|
self._service.spreadsheets().values().update(
|
||||||
|
spreadsheetId=spreadsheet_id,
|
||||||
|
range=f"{a1_sheet(title)}!{col_letter(first_col)}{first_row}",
|
||||||
|
valueInputOption="USER_ENTERED",
|
||||||
|
body={"values": matrix},
|
||||||
|
).execute()
|
||||||
|
|
||||||
|
return {
|
||||||
|
"created": False,
|
||||||
|
"title": title,
|
||||||
|
"first_row": first_row,
|
||||||
|
"last_row": last_row,
|
||||||
|
"url": f"https://docs.google.com/spreadsheets/d/{spreadsheet_id}/edit#gid={sheet_id}",
|
||||||
|
}
|
||||||
|
|
||||||
@_serialized
|
@_serialized
|
||||||
def delete_sheet(self, *, spreadsheet_id: str, title: str) -> dict[str, Any]:
|
def delete_sheet(self, *, spreadsheet_id: str, title: str) -> dict[str, Any]:
|
||||||
"""이름이 정확히 일치하는 시트 1장을 삭제한다.
|
"""이름이 정확히 일치하는 시트 1장을 삭제한다.
|
||||||
@@ -263,17 +432,7 @@ class GoogleSheetsWriter:
|
|||||||
})
|
})
|
||||||
|
|
||||||
def _fmt(r1: int, c1: int, r2: int, c2: int, fmt: dict[str, Any], fields: str) -> dict[str, Any]:
|
def _fmt(r1: int, c1: int, r2: int, c2: int, fmt: dict[str, Any], fields: str) -> dict[str, Any]:
|
||||||
return {
|
return _repeat_cell(sheet_id, r1, c1, r2, c2, fmt, fields)
|
||||||
"repeatCell": {
|
|
||||||
"range": {
|
|
||||||
"sheetId": sheet_id,
|
|
||||||
"startRowIndex": r1 - 1, "endRowIndex": r2,
|
|
||||||
"startColumnIndex": c1 - 1, "endColumnIndex": c2,
|
|
||||||
},
|
|
||||||
"cell": {"userEnteredFormat": fmt},
|
|
||||||
"fields": fields,
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
requests.append(_fmt(
|
requests.append(_fmt(
|
||||||
title_row, first_col, title_row, last_col,
|
title_row, first_col, title_row, last_col,
|
||||||
|
|||||||
@@ -0,0 +1,184 @@
|
|||||||
|
"""Google 슬라이드(회의록 보드) 공통 계층 — 공유 드라이브 폴더에 빈 슬라이드를 만들거나 찾는다.
|
||||||
|
|
||||||
|
인증은 google_sheets 와 같은 설정을 쓰되 권한 범위(scope)가 다르다(Drive + Slides).
|
||||||
|
설정된 쪽을 자동 선택(서비스 계정 우선).
|
||||||
|
|
||||||
|
1) 사용자 OAuth 리프레시 토큰
|
||||||
|
· `GOOGLE_SLIDES_OAUTH_REFRESH_TOKEN` — 없으면 `GOOGLE_SHEETS_OAUTH_REFRESH_TOKEN`
|
||||||
|
토큰은 Drive·Slides 권한까지 받아야 한다: `python scripts/google_sheets_authorize.py`(스프레드시트·Drive·Slides 한 번에)
|
||||||
|
· `GOOGLE_SHEETS_OAUTH_CLIENT_ID` / `..._SECRET`(없으면 로그인용 `GOOGLE_CLIENT_ID` / `GOOGLE_CLIENT_SECRET`)
|
||||||
|
2) 서비스 계정 JSON — `GOOGLE_SHEETS_CREDENTIALS` / `GOOGLE_SHEETS_CREDENTIALS_JSON`
|
||||||
|
서비스 계정 이메일을 대상 공유 드라이브의 **콘텐츠 관리자** 이상으로 추가해야 한다.
|
||||||
|
|
||||||
|
- 회의록 보드 폴더: `MEETING_BOARD_FOLDER_ID`(기본 = 회의록 보드 공유 드라이브).
|
||||||
|
- 같은 주차 보드를 다시 누르면 새로 만들지 않고 Drive 파일 appProperties(`dbxMeetingWeek` = 주차 시작일)로 찾는다
|
||||||
|
— 파일 이름을 바꿔도 같은 보드가 열린다. 휴지통에 버리면 다음에 새로 만든다.
|
||||||
|
- 비밀값(키/토큰)은 로그·화면에 절대 출력하지 않는다. 라이브러리·설정이 없으면 `enabled = False`.
|
||||||
|
"""
|
||||||
|
|
||||||
|
from __future__ import annotations
|
||||||
|
|
||||||
|
import json
|
||||||
|
import os
|
||||||
|
import re
|
||||||
|
import threading
|
||||||
|
from typing import Any
|
||||||
|
|
||||||
|
SCOPES = ["https://www.googleapis.com/auth/drive", "https://www.googleapis.com/auth/presentations"]
|
||||||
|
TOKEN_URI = "https://oauth2.googleapis.com/token"
|
||||||
|
DEFAULT_BOARD_FOLDER_ID = "0AGF3CIEboPQiUk9PVA"
|
||||||
|
PRESENTATION_MIME = "application/vnd.google-apps.presentation"
|
||||||
|
WEEK_KEY = "dbxMeetingWeek"
|
||||||
|
|
||||||
|
# googleapiclient 의 HTTP 클라이언트는 스레드 안전하지 않고, 같은 주차를 두 사람이 동시에 누르면
|
||||||
|
# 보드가 두 개 생길 수 있으므로 찾기·만들기는 한 번에 하나씩.
|
||||||
|
_LOCK = threading.Lock()
|
||||||
|
|
||||||
|
|
||||||
|
class GoogleSlidesError(RuntimeError):
|
||||||
|
"""화면에 보여도 되는 사유(비밀값 없음)."""
|
||||||
|
|
||||||
|
|
||||||
|
def board_folder_id() -> str:
|
||||||
|
return (os.getenv("MEETING_BOARD_FOLDER_ID") or "").strip() or DEFAULT_BOARD_FOLDER_ID
|
||||||
|
|
||||||
|
|
||||||
|
def board_url(file_id: str) -> str:
|
||||||
|
return f"https://docs.google.com/presentation/d/{file_id}/edit"
|
||||||
|
|
||||||
|
|
||||||
|
class GoogleSlidesClient:
|
||||||
|
def __init__(self) -> None:
|
||||||
|
self.enabled = False
|
||||||
|
self.reason = ""
|
||||||
|
self.auth_mode = ""
|
||||||
|
self._drive: Any = None
|
||||||
|
self._slides: Any = None
|
||||||
|
try:
|
||||||
|
from googleapiclient.discovery import build
|
||||||
|
except ImportError:
|
||||||
|
self.reason = "google-api-python-client 미설치"
|
||||||
|
return
|
||||||
|
creds = self._service_account_creds()
|
||||||
|
if creds is None:
|
||||||
|
creds = self._oauth_creds()
|
||||||
|
if creds is None:
|
||||||
|
if not self.reason:
|
||||||
|
self.reason = "Google 인증 미설정(GOOGLE_SLIDES_OAUTH_REFRESH_TOKEN 또는 GOOGLE_SHEETS_* 설정 필요)"
|
||||||
|
return
|
||||||
|
try:
|
||||||
|
self._drive = build("drive", "v3", credentials=creds, cache_discovery=False)
|
||||||
|
self._slides = build("slides", "v1", credentials=creds, cache_discovery=False)
|
||||||
|
except Exception as exc: # noqa: BLE001 — 사유만(비밀값 미출력)
|
||||||
|
self.reason = f"Google 클라이언트 생성 실패: {type(exc).__name__}"
|
||||||
|
return
|
||||||
|
self.enabled = True
|
||||||
|
|
||||||
|
# ── 인증(google_sheets 와 같은 설정, 범위만 Drive·Slides) ──
|
||||||
|
def _service_account_creds(self) -> Any:
|
||||||
|
raw = (os.getenv("GOOGLE_SHEETS_CREDENTIALS_JSON") or "").strip()
|
||||||
|
path = (os.getenv("GOOGLE_SHEETS_CREDENTIALS") or "").strip()
|
||||||
|
if not raw and not path:
|
||||||
|
return None
|
||||||
|
try:
|
||||||
|
info = json.loads(raw) if raw else json.loads(open(path, encoding="utf-8").read())
|
||||||
|
from google.oauth2.service_account import Credentials
|
||||||
|
|
||||||
|
creds = Credentials.from_service_account_info(info, scopes=SCOPES)
|
||||||
|
except Exception as exc: # noqa: BLE001
|
||||||
|
self.reason = f"서비스 계정 인증 실패: {type(exc).__name__}"
|
||||||
|
return None
|
||||||
|
self.auth_mode = "service_account"
|
||||||
|
return creds
|
||||||
|
|
||||||
|
def _oauth_creds(self) -> Any:
|
||||||
|
token = (os.getenv("GOOGLE_SLIDES_OAUTH_REFRESH_TOKEN") or os.getenv("GOOGLE_SHEETS_OAUTH_REFRESH_TOKEN") or "").strip()
|
||||||
|
if not token:
|
||||||
|
return None
|
||||||
|
cid = (os.getenv("GOOGLE_SHEETS_OAUTH_CLIENT_ID") or os.getenv("GOOGLE_CLIENT_ID") or "").strip()
|
||||||
|
secret = (os.getenv("GOOGLE_SHEETS_OAUTH_CLIENT_SECRET") or os.getenv("GOOGLE_CLIENT_SECRET") or "").strip()
|
||||||
|
if not cid or not secret:
|
||||||
|
self.reason = "GOOGLE_SHEETS_OAUTH_CLIENT_ID/SECRET 미설정"
|
||||||
|
return None
|
||||||
|
try:
|
||||||
|
from google.oauth2.credentials import Credentials
|
||||||
|
|
||||||
|
creds = Credentials(token=None, refresh_token=token, token_uri=TOKEN_URI,
|
||||||
|
client_id=cid, client_secret=secret, scopes=SCOPES)
|
||||||
|
except Exception as exc: # noqa: BLE001
|
||||||
|
self.reason = f"OAuth 자격 생성 실패: {type(exc).__name__}"
|
||||||
|
return None
|
||||||
|
self.auth_mode = "oauth"
|
||||||
|
return creds
|
||||||
|
|
||||||
|
# ────────────────────────────────────────────────
|
||||||
|
def open_week_board(self, *, folder_id: str, week_key: str, title: str) -> dict[str, Any]:
|
||||||
|
"""그 주차 보드(빈 슬라이드)를 찾고, 없으면 폴더에 만든다 → {id, url, created}."""
|
||||||
|
if not self.enabled:
|
||||||
|
raise GoogleSlidesError(self.reason or "Google 슬라이드 연동이 꺼져 있습니다.")
|
||||||
|
with _LOCK:
|
||||||
|
try:
|
||||||
|
found = self._find(folder_id, week_key)
|
||||||
|
if found:
|
||||||
|
return {"id": found, "url": board_url(found), "created": False}
|
||||||
|
file_id = self._create_blank(folder_id, week_key, title)
|
||||||
|
except GoogleSlidesError:
|
||||||
|
raise
|
||||||
|
except Exception as exc: # noqa: BLE001
|
||||||
|
raise GoogleSlidesError(_friendly(exc)) from None
|
||||||
|
return {"id": file_id, "url": board_url(file_id), "created": True}
|
||||||
|
|
||||||
|
def _find(self, folder_id: str, week_key: str) -> str | None:
|
||||||
|
q = (f"'{folder_id}' in parents and trashed = false and mimeType = '{PRESENTATION_MIME}' "
|
||||||
|
f"and appProperties has {{ key='{WEEK_KEY}' and value='{week_key}' }}")
|
||||||
|
res = self._drive.files().list(
|
||||||
|
q=q, fields="files(id)", pageSize=1, supportsAllDrives=True, includeItemsFromAllDrives=True,
|
||||||
|
corpora="allDrives",
|
||||||
|
).execute()
|
||||||
|
files = res.get("files") or []
|
||||||
|
return files[0]["id"] if files else None
|
||||||
|
|
||||||
|
def _create_blank(self, folder_id: str, week_key: str, title: str) -> str:
|
||||||
|
meta = {"name": title, "mimeType": PRESENTATION_MIME, "parents": [folder_id],
|
||||||
|
"appProperties": {WEEK_KEY: week_key}}
|
||||||
|
file_id = self._drive.files().create(body=meta, fields="id", supportsAllDrives=True).execute()["id"]
|
||||||
|
# 새 프레젠테이션의 첫 장은 "제목·부제목" 틀(TITLE 레이아웃) — 틀 없는 빈 장(BLANK) 하나만 남긴다
|
||||||
|
pres = self._slides.presentations().get(presentationId=file_id, fields="slides.objectId").execute()
|
||||||
|
reqs: list[dict[str, Any]] = [{"createSlide": {"insertionIndex": 0, "slideLayoutReference": {"predefinedLayout": "BLANK"}}}]
|
||||||
|
reqs += [{"deleteObject": {"objectId": s["objectId"]}} for s in pres.get("slides") or []]
|
||||||
|
self._slides.presentations().batchUpdate(presentationId=file_id, body={"requests": reqs}).execute()
|
||||||
|
return file_id
|
||||||
|
|
||||||
|
|
||||||
|
def _friendly(exc: Exception) -> str:
|
||||||
|
"""Google API 오류 → 화면용 문구(비밀값·원문 응답 미포함)."""
|
||||||
|
status = getattr(getattr(exc, "resp", None), "status", None)
|
||||||
|
text = str(exc)
|
||||||
|
# 토큰 갱신 실패(RefreshError) — Google 이 준 OAuth 오류 코드(비밀값 아님)를 보여 원인을 바로 알 수 있게
|
||||||
|
m = re.search(r"\b(invalid_scope|invalid_grant|invalid_client|unauthorized_client|deleted_client|access_denied|invalid_request)\b", text)
|
||||||
|
code = m.group(1) if m else ""
|
||||||
|
if code in ("unauthorized_client", "invalid_client", "deleted_client"):
|
||||||
|
return (f"Google 토큰 갱신 실패({code}) — 토큰을 발급한 OAuth 클라이언트와 서버 .env 의 "
|
||||||
|
"GOOGLE_SHEETS_OAUTH_CLIENT_ID/SECRET(없으면 GOOGLE_CLIENT_ID/SECRET)이 다릅니다.")
|
||||||
|
if "invalid_scope" in text or "insufficient" in text.lower() or "ACCESS_TOKEN_SCOPE_INSUFFICIENT" in text:
|
||||||
|
return "Google 권한(Drive·Slides)이 없는 토큰입니다. 토큰을 다시 발급해 주세요(scripts/google_sheets_authorize.py)."
|
||||||
|
if "invalid_grant" in text:
|
||||||
|
return "Google 토큰이 만료·폐기되었습니다. 토큰을 다시 발급해 주세요."
|
||||||
|
if status == 404:
|
||||||
|
return "회의록 보드 폴더를 찾을 수 없습니다(MEETING_BOARD_FOLDER_ID·공유 드라이브 접근 권한 확인)."
|
||||||
|
if status == 403:
|
||||||
|
return "Google Drive·Slides 접근이 거부되었습니다(API 사용 설정·공유 드라이브 권한 확인)."
|
||||||
|
return f"Google 슬라이드 처리 실패({type(exc).__name__}{f' {status}' if status else ''}{f' {code}' if code else ''})."
|
||||||
|
|
||||||
|
|
||||||
|
_CLIENT: GoogleSlidesClient | None = None
|
||||||
|
_CLIENT_LOCK = threading.Lock()
|
||||||
|
|
||||||
|
|
||||||
|
def get_client() -> GoogleSlidesClient:
|
||||||
|
"""프로세스당 하나(설정이 비어 있으면 매번 다시 확인 — .env 를 고치고 재시작 없이도 사유가 갱신되게)."""
|
||||||
|
global _CLIENT
|
||||||
|
with _CLIENT_LOCK:
|
||||||
|
if _CLIENT is None or not _CLIENT.enabled:
|
||||||
|
_CLIENT = GoogleSlidesClient()
|
||||||
|
return _CLIENT
|
||||||
@@ -44,9 +44,12 @@ def send_email(
|
|||||||
body: str,
|
body: str,
|
||||||
html: str | None = None,
|
html: str | None = None,
|
||||||
from_name: str = "DBX ERP",
|
from_name: str = "DBX ERP",
|
||||||
|
reply_to: str = "",
|
||||||
) -> bool:
|
) -> bool:
|
||||||
"""단순 텍스트(+선택 HTML) 메일 1건 발송.
|
"""단순 텍스트(+선택 HTML) 메일 1건 발송.
|
||||||
|
|
||||||
|
reply_to — 받는 사람이 [답장]하면 갈 주소(예: 휴가 메일 = 처리한 사람, 2026-10-27). 보내는 주소는 늘 SMTP_FROM.
|
||||||
|
|
||||||
반환: 성공 True / 비활성·실패 False. 예외를 밖으로 던지지 않는다.
|
반환: 성공 True / 비활성·실패 False. 예외를 밖으로 던지지 않는다.
|
||||||
"""
|
"""
|
||||||
host = _env("SMTP_HOST")
|
host = _env("SMTP_HOST")
|
||||||
@@ -71,6 +74,8 @@ def send_email(
|
|||||||
msg["Subject"] = subject
|
msg["Subject"] = subject
|
||||||
msg["From"] = formataddr((from_name, sender))
|
msg["From"] = formataddr((from_name, sender))
|
||||||
msg["To"] = ", ".join(recipients)
|
msg["To"] = ", ".join(recipients)
|
||||||
|
if reply_to and "@" in reply_to:
|
||||||
|
msg["Reply-To"] = formataddr((from_name, reply_to.strip()))
|
||||||
msg.set_content(body)
|
msg.set_content(body)
|
||||||
if html:
|
if html:
|
||||||
msg.add_alternative(html, subtype="html")
|
msg.add_alternative(html, subtype="html")
|
||||||
|
|||||||
+144
-5
@@ -2,7 +2,7 @@ import inspect
|
|||||||
import os
|
import os
|
||||||
from contextlib import asynccontextmanager
|
from contextlib import asynccontextmanager
|
||||||
from pathlib import Path
|
from pathlib import Path
|
||||||
from typing import Any
|
from typing import Any, Literal
|
||||||
|
|
||||||
from authlib.integrations.starlette_client import OAuth, OAuthError
|
from authlib.integrations.starlette_client import OAuth, OAuthError
|
||||||
from dotenv import load_dotenv
|
from dotenv import load_dotenv
|
||||||
@@ -15,6 +15,8 @@ from pydantic import BaseModel
|
|||||||
from starlette.middleware.sessions import SessionMiddleware
|
from starlette.middleware.sessions import SessionMiddleware
|
||||||
|
|
||||||
from .modules.cafe24 import build_cafe24_store
|
from .modules.cafe24 import build_cafe24_store
|
||||||
|
from .modules.asset import build_asset_store
|
||||||
|
from .modules.asset import router as asset_router
|
||||||
from .modules.cafe24 import router as cafe24_router
|
from .modules.cafe24 import router as cafe24_router
|
||||||
from .modules.cupang import build_cupang_store, build_itemcode_reader
|
from .modules.cupang import build_cupang_store, build_itemcode_reader
|
||||||
from .modules.cupang import router as cupang_router
|
from .modules.cupang import router as cupang_router
|
||||||
@@ -22,8 +24,16 @@ from .modules.dispatch import build_dispatch_store
|
|||||||
from .modules.dispatch import router as dispatch_router
|
from .modules.dispatch import router as dispatch_router
|
||||||
from .modules.expense import CategoryStore, build_expense_store
|
from .modules.expense import CategoryStore, build_expense_store
|
||||||
from .modules.expense import router as expense_router
|
from .modules.expense import router as expense_router
|
||||||
|
from .modules.inout import build_inout_items, build_inout_store
|
||||||
|
from .modules.inout import router as inout_router
|
||||||
|
from .modules.live import build_live_store
|
||||||
|
from .modules.live import router as live_router
|
||||||
from .modules.malaysia import build_malaysia_itemcode, build_malaysia_store
|
from .modules.malaysia import build_malaysia_itemcode, build_malaysia_store
|
||||||
from .modules.malaysia import router as malaysia_router
|
from .modules.malaysia import router as malaysia_router
|
||||||
|
from .modules.notice import build_notice_store
|
||||||
|
from .modules.notice import router as notice_router
|
||||||
|
from .modules.outreach import build_outreach_store
|
||||||
|
from .modules.outreach import router as outreach_router
|
||||||
from .modules.performance import build_performance_store
|
from .modules.performance import build_performance_store
|
||||||
from .modules.performance import router as performance_router
|
from .modules.performance import router as performance_router
|
||||||
from .modules.project import build_project_store
|
from .modules.project import build_project_store
|
||||||
@@ -33,6 +43,8 @@ from .modules.vacation import router as vacation_router
|
|||||||
from .store import (
|
from .store import (
|
||||||
APPROVER_KEYS,
|
APPROVER_KEYS,
|
||||||
MODULE_KEYS,
|
MODULE_KEYS,
|
||||||
|
ROLE_LABELS,
|
||||||
|
ROLES,
|
||||||
SUPER_ADMIN_EMAIL,
|
SUPER_ADMIN_EMAIL,
|
||||||
UserStore,
|
UserStore,
|
||||||
allowed_modules,
|
allowed_modules,
|
||||||
@@ -52,6 +64,12 @@ MODULE_LABELS: dict[str, str] = {
|
|||||||
"project": "프로젝트 관리",
|
"project": "프로젝트 관리",
|
||||||
"cafe24": "카페24 상품관리",
|
"cafe24": "카페24 상품관리",
|
||||||
"performance": "실적",
|
"performance": "실적",
|
||||||
|
"asset": "자산관리",
|
||||||
|
"inout": "입출고 관리",
|
||||||
|
"outreach": "안내문 발송",
|
||||||
|
"live": "라이브 커머스",
|
||||||
|
"live_host": "라이브 호스트 등록",
|
||||||
|
"live_host_edit": "라이브 호스트 수정",
|
||||||
"expense_approver": "개인경비",
|
"expense_approver": "개인경비",
|
||||||
"vacation_approver": "휴가",
|
"vacation_approver": "휴가",
|
||||||
}
|
}
|
||||||
@@ -110,10 +128,14 @@ def build_google_oauth() -> OAuth:
|
|||||||
async def _lifespan(app_: FastAPI): # noqa: ANN201
|
async def _lifespan(app_: FastAPI): # noqa: ANN201
|
||||||
"""앱 시작 시 백그라운드 작업 시작.
|
"""앱 시작 시 백그라운드 작업 시작.
|
||||||
- 프로젝트 업무 마감 알림(매일 1회, 기본 09시 KST) 스레드.
|
- 프로젝트 업무 마감 알림(매일 1회, 기본 09시 KST) 스레드.
|
||||||
PROJECT_REMINDERS=false 면 안 돈다. 상세는 app/modules/project/reminders.py."""
|
PROJECT_REMINDERS=false 면 안 돈다. 상세는 app/modules/project/reminders.py.
|
||||||
|
- 실적 매출 자동 업데이트(09~19시 정각·30분, 최근 10일) 스레드.
|
||||||
|
PERFORMANCE_AUTO_SYNC=false 면 안 돈다. 상세는 app/modules/performance/auto_sync.py."""
|
||||||
|
from .modules.performance.auto_sync import start_auto_sync_thread # noqa: WPS433
|
||||||
from .modules.project.reminders import start_reminder_thread # noqa: WPS433
|
from .modules.project.reminders import start_reminder_thread # noqa: WPS433
|
||||||
|
|
||||||
start_reminder_thread(getattr(app_.state, "project_store", None))
|
start_reminder_thread(getattr(app_.state, "project_store", None))
|
||||||
|
start_auto_sync_thread(app_.state)
|
||||||
yield
|
yield
|
||||||
|
|
||||||
|
|
||||||
@@ -140,6 +162,11 @@ _MODULE_TEMPLATE_DIRS = [
|
|||||||
BASE_DIR / "modules" / "project" / "templates",
|
BASE_DIR / "modules" / "project" / "templates",
|
||||||
BASE_DIR / "modules" / "cafe24" / "templates",
|
BASE_DIR / "modules" / "cafe24" / "templates",
|
||||||
BASE_DIR / "modules" / "performance" / "templates",
|
BASE_DIR / "modules" / "performance" / "templates",
|
||||||
|
BASE_DIR / "modules" / "asset" / "templates",
|
||||||
|
BASE_DIR / "modules" / "notice" / "templates",
|
||||||
|
BASE_DIR / "modules" / "inout" / "templates",
|
||||||
|
BASE_DIR / "modules" / "outreach" / "templates",
|
||||||
|
BASE_DIR / "modules" / "live" / "templates",
|
||||||
]
|
]
|
||||||
templates = Jinja2Templates(directory=str(BASE_DIR / "templates"))
|
templates = Jinja2Templates(directory=str(BASE_DIR / "templates"))
|
||||||
templates.env.loader = ChoiceLoader(
|
templates.env.loader = ChoiceLoader(
|
||||||
@@ -202,6 +229,18 @@ app.state.cafe24_store = build_cafe24_store(dsn=env("CAFE24_DB_URL") or None)
|
|||||||
# 실적(쇼핑몰 통합 매출): PERFORMANCE_DB_URL 없으면 store=None(라우터가 "설정 필요" 안내).
|
# 실적(쇼핑몰 통합 매출): PERFORMANCE_DB_URL 없으면 store=None(라우터가 "설정 필요" 안내).
|
||||||
# 쇼핑몰 API 인증정보는 설정 화면에서 입력 → APP_ENCRYPTION_KEY 로 암호화해 performance_db 에 저장.
|
# 쇼핑몰 API 인증정보는 설정 화면에서 입력 → APP_ENCRYPTION_KEY 로 암호화해 performance_db 에 저장.
|
||||||
app.state.performance_store = build_performance_store(dsn=env("PERFORMANCE_DB_URL") or None)
|
app.state.performance_store = build_performance_store(dsn=env("PERFORMANCE_DB_URL") or None)
|
||||||
|
app.state.asset_store = build_asset_store(dsn=env("ASSET_DB_URL") or None)
|
||||||
|
# 긴급 공지(ERP 전체 화면 가운데): project_db 024 — 프로젝트 저장소의 연결 풀을 같이 쓴다(없으면 None → 503).
|
||||||
|
app.state.notice_store = build_notice_store(app.state.project_store)
|
||||||
|
# 입출고 관리(본사 → 공장 발주, 물류 입고, 미입고): INOUT_DB_URL 없으면 store=None(라우터가 "설정 필요" 안내).
|
||||||
|
# 제품은 itemcode_db 단품(single_items) 읽기 전용 — ITEMCODE_DB_URL 재사용.
|
||||||
|
app.state.inout_store = build_inout_store(dsn=env("INOUT_DB_URL") or None)
|
||||||
|
app.state.inout_items = build_inout_items()
|
||||||
|
# 안내문 발송(메일 일괄·인스타 DM 반자동): OUTREACH_DB_URL 없으면 store=None(화면이 "설정 필요" 안내).
|
||||||
|
# 메일은 보내는 사람 본인 Gmail — 입출고 Gmail 연결(inout_store.inout_gmail_tokens)을 같이 쓴다.
|
||||||
|
app.state.outreach_store = build_outreach_store(dsn=env("OUTREACH_DB_URL") or None)
|
||||||
|
# 라이브 커머스(말레이시아 방송 호스트·스케줄): LIVE_DB_URL 없으면 store=None(화면이 "설정 필요" 안내).
|
||||||
|
app.state.live_store = build_live_store(dsn=env("LIVE_DB_URL") or None)
|
||||||
|
|
||||||
# 모듈 라우터 등록 — 신규 모듈 추가 시 여기 한 줄.
|
# 모듈 라우터 등록 — 신규 모듈 추가 시 여기 한 줄.
|
||||||
app.include_router(expense_router)
|
app.include_router(expense_router)
|
||||||
@@ -212,6 +251,11 @@ app.include_router(dispatch_router)
|
|||||||
app.include_router(project_router)
|
app.include_router(project_router)
|
||||||
app.include_router(cafe24_router)
|
app.include_router(cafe24_router)
|
||||||
app.include_router(performance_router)
|
app.include_router(performance_router)
|
||||||
|
app.include_router(asset_router)
|
||||||
|
app.include_router(notice_router)
|
||||||
|
app.include_router(inout_router)
|
||||||
|
app.include_router(outreach_router)
|
||||||
|
app.include_router(live_router)
|
||||||
|
|
||||||
|
|
||||||
def public_url_for(request: Request, route_name: str) -> str:
|
def public_url_for(request: Request, route_name: str) -> str:
|
||||||
@@ -376,7 +420,7 @@ def _menu_items_for(user_rec: dict[str, Any]) -> list[dict[str, Any]]:
|
|||||||
},
|
},
|
||||||
{
|
{
|
||||||
"key": "project",
|
"key": "project",
|
||||||
"title": "프로젝트 관리",
|
"title": "Project",
|
||||||
"subtitle": "Projects",
|
"subtitle": "Projects",
|
||||||
"description": "프로젝트·서브프로젝트·업무를 달력/타임라인/보드로 관리합니다(아사나식).",
|
"description": "프로젝트·서브프로젝트·업무를 달력/타임라인/보드로 관리합니다(아사나식).",
|
||||||
"url": "/project/",
|
"url": "/project/",
|
||||||
@@ -404,7 +448,43 @@ def _menu_items_for(user_rec: dict[str, Any]) -> list[dict[str, Any]]:
|
|||||||
"status": "ready",
|
"status": "ready",
|
||||||
"category": "관리",
|
"category": "관리",
|
||||||
},
|
},
|
||||||
|
{
|
||||||
|
"key": "inout",
|
||||||
|
"title": "입출고 관리",
|
||||||
|
"subtitle": "Inbound",
|
||||||
|
"description": "본사에서 공장으로 넣은 제작 발주와 물류 입고 수량을 맞춰 보고, 미입고·초과 입고를 관리합니다.",
|
||||||
|
"url": "/inout/",
|
||||||
|
"health_url": "/inout/health",
|
||||||
|
"status": "ready",
|
||||||
|
"category": "운영",
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"key": "outreach",
|
||||||
|
"title": "안내문 발송",
|
||||||
|
"subtitle": "Outreach",
|
||||||
|
"description": "이메일·인스타그램 리스트에 이름을 넣은 안내문을 메일로 일괄 발송하고 인스타 DM 을 보냅니다.",
|
||||||
|
"url": "/outreach/",
|
||||||
|
"health_url": "/outreach/health",
|
||||||
|
"status": "ready",
|
||||||
|
"category": "운영",
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"key": "live",
|
||||||
|
"title": "라이브 커머스",
|
||||||
|
"card_title": "라이브 커머스 · Live Commerce", # 메인 카드만 한글·영문 둘 다(사이드바는 짧게)
|
||||||
|
"subtitle": "Malaysia",
|
||||||
|
"description": "말레이시아 라이브 방송의 호스트 정보와 방송 스케줄·판매금액·결과 이미지를 관리합니다.",
|
||||||
|
"url": "/live/",
|
||||||
|
"health_url": "/live/health",
|
||||||
|
"status": "ready",
|
||||||
|
"category": "운영",
|
||||||
|
},
|
||||||
]
|
]
|
||||||
|
items.append({
|
||||||
|
"key": "asset", "title": "자산관리", "subtitle": "Asset Management",
|
||||||
|
"description": "사무집기·전산장비의 배정·반납·구매 이력과 HWiNFO 컴퓨터 사양을 관리합니다.",
|
||||||
|
"url": "/asset/", "health_url": "/asset/health", "status": "ready", "category": "관리",
|
||||||
|
})
|
||||||
allowed = allowed_modules(user_rec)
|
allowed = allowed_modules(user_rec)
|
||||||
for item in items:
|
for item in items:
|
||||||
item["allowed"] = item["key"] in allowed
|
item["allowed"] = item["key"] in allowed
|
||||||
@@ -414,6 +494,10 @@ def _menu_items_for(user_rec: dict[str, Any]) -> list[dict[str, Any]]:
|
|||||||
def _icon_svg(name: str) -> str:
|
def _icon_svg(name: str) -> str:
|
||||||
"""좌측 사이드바용 인라인 아이콘. 외부 의존 없는 작은 SVG."""
|
"""좌측 사이드바용 인라인 아이콘. 외부 의존 없는 작은 SVG."""
|
||||||
paths = {
|
paths = {
|
||||||
|
"inout": '<path d="M3 7l9-4 9 4v10l-9 4-9-4z"/><path d="M3 7l9 4 9-4"/><path d="M12 11v10"/>',
|
||||||
|
"outreach": '<path d="M22 2 11 13"/><path d="M22 2 15 22l-4-9-9-4z"/>',
|
||||||
|
"live": '<rect x="2" y="6" width="14" height="12" rx="2"/><path d="m16 11 6-4v10l-6-4"/>',
|
||||||
|
"asset": '<rect x="3" y="3" width="18" height="13" rx="2"/><path d="M8 21h8M12 16v5"/><path d="M7 7h10M7 11h6"/>',
|
||||||
"home": '<path d="M3 11 12 3l9 8"/><path d="M5 10v10h14V10"/>',
|
"home": '<path d="M3 11 12 3l9 8"/><path d="M5 10v10h14V10"/>',
|
||||||
"expense": '<rect x="3" y="6" width="18" height="13" rx="2"/><path d="M3 10h18"/><path d="M7 15h4"/>',
|
"expense": '<rect x="3" y="6" width="18" height="13" rx="2"/><path d="M3 10h18"/><path d="M7 15h4"/>',
|
||||||
"vacation": '<path d="M8 2v4"/><path d="M16 2v4"/><rect x="3" y="6" width="18" height="15" rx="2"/><path d="M3 11h18"/>',
|
"vacation": '<path d="M8 2v4"/><path d="M16 2v4"/><rect x="3" y="6" width="18" height="15" rx="2"/><path d="M3 11h18"/>',
|
||||||
@@ -476,16 +560,36 @@ def build_erp_nav(
|
|||||||
return items
|
return items
|
||||||
|
|
||||||
|
|
||||||
|
def _login_orbit_names(limit: int = 40) -> list[str]:
|
||||||
|
"""로그인 화면 왼쪽 패널 — King 주위를 도는 사용자 아이디(이메일 @ 앞, 첫 글자 대문자). 이메일·실명은 내보내지 않는다."""
|
||||||
|
names: set[str] = set()
|
||||||
|
try:
|
||||||
|
users = user_store.list_all()
|
||||||
|
except Exception: # noqa: BLE001 — 장식이라 실패해도 로그인 화면은 그대로
|
||||||
|
return []
|
||||||
|
for u in users:
|
||||||
|
email = str(u.get("email") or "").lower().strip()
|
||||||
|
local = email.split("@", 1)[0]
|
||||||
|
if not local or email == SUPER_ADMIN_EMAIL:
|
||||||
|
continue
|
||||||
|
names.add(local[:1].upper() + local[1:])
|
||||||
|
return sorted(names)[:limit]
|
||||||
|
|
||||||
|
|
||||||
|
def _render_login(request: Request) -> HTMLResponse:
|
||||||
|
return render_template(request, "login.html", {"orbit_names": _login_orbit_names()})
|
||||||
|
|
||||||
|
|
||||||
@app.get("/", response_class=HTMLResponse)
|
@app.get("/", response_class=HTMLResponse)
|
||||||
async def home(request: Request) -> HTMLResponse:
|
async def home(request: Request) -> HTMLResponse:
|
||||||
sess = get_session_user(request)
|
sess = get_session_user(request)
|
||||||
if not sess:
|
if not sess:
|
||||||
return render_template(request, "login.html")
|
return _render_login(request)
|
||||||
user_rec = user_store.get(sess["email"])
|
user_rec = user_store.get(sess["email"])
|
||||||
if user_rec is None:
|
if user_rec is None:
|
||||||
# 도메인은 통과했으나 저장소에 없음 — 세션 정리 후 재로그인
|
# 도메인은 통과했으나 저장소에 없음 — 세션 정리 후 재로그인
|
||||||
request.session.clear()
|
request.session.clear()
|
||||||
return render_template(request, "login.html")
|
return _render_login(request)
|
||||||
|
|
||||||
# 슈퍼 관리자 → 업무 모듈 선택 화면(main.html).
|
# 슈퍼 관리자 → 업무 모듈 선택 화면(main.html).
|
||||||
# 일반 사용자 → ERP 메인(좌측 메뉴 + 우측 콘텐츠).
|
# 일반 사용자 → ERP 메인(좌측 메뉴 + 우측 콘텐츠).
|
||||||
@@ -608,6 +712,39 @@ async def healthz() -> dict[str, str]:
|
|||||||
return {"status": "ok"}
|
return {"status": "ok"}
|
||||||
|
|
||||||
|
|
||||||
|
@app.get("/api/auth/check")
|
||||||
|
async def external_module_auth(
|
||||||
|
request: Request, module: Literal["corm", "order"]
|
||||||
|
) -> JSONResponse:
|
||||||
|
"""외부 서비스 접근을 ERP의 현재 사용자/권한으로 판단한다.
|
||||||
|
|
||||||
|
세션에 권한을 복제하지 않는다. 삭제·권한 해제는 다음 요청부터 반영된다.
|
||||||
|
호출 서비스는 브라우저의 세션 쿠키만 전달하며 이메일을 지정할 수 없다.
|
||||||
|
"""
|
||||||
|
headers = {"Cache-Control": "no-store", "Vary": "Cookie"}
|
||||||
|
user = get_current_user_record(request)
|
||||||
|
if user is None:
|
||||||
|
return JSONResponse(
|
||||||
|
{"detail": "로그인이 필요합니다."}, status_code=401, headers=headers
|
||||||
|
)
|
||||||
|
if not has_module(user, module):
|
||||||
|
return JSONResponse(
|
||||||
|
{"detail": "모듈 접근 권한이 없습니다."}, status_code=403, headers=headers
|
||||||
|
)
|
||||||
|
return JSONResponse(
|
||||||
|
{
|
||||||
|
"module": module,
|
||||||
|
"user": {
|
||||||
|
"email": user["email"],
|
||||||
|
"name": user.get("name", ""),
|
||||||
|
"role": user.get("role", "user"),
|
||||||
|
"is_super_admin": bool(user.get("is_super_admin")),
|
||||||
|
},
|
||||||
|
},
|
||||||
|
headers=headers,
|
||||||
|
)
|
||||||
|
|
||||||
|
|
||||||
# ── 관리자 페이지 ──────────────────────────────────────────────
|
# ── 관리자 페이지 ──────────────────────────────────────────────
|
||||||
@app.get("/admin", response_class=HTMLResponse)
|
@app.get("/admin", response_class=HTMLResponse)
|
||||||
async def admin_page(request: Request) -> HTMLResponse:
|
async def admin_page(request: Request) -> HTMLResponse:
|
||||||
@@ -631,6 +768,8 @@ async def admin_page(request: Request) -> HTMLResponse:
|
|||||||
"module_keys": list(MODULE_KEYS),
|
"module_keys": list(MODULE_KEYS),
|
||||||
"module_labels": MODULE_LABELS,
|
"module_labels": MODULE_LABELS,
|
||||||
"approver_keys": list(APPROVER_KEYS),
|
"approver_keys": list(APPROVER_KEYS),
|
||||||
|
"roles": list(ROLES),
|
||||||
|
"role_labels": ROLE_LABELS,
|
||||||
"super_admin_email": SUPER_ADMIN_EMAIL,
|
"super_admin_email": SUPER_ADMIN_EMAIL,
|
||||||
"is_admin": True,
|
"is_admin": True,
|
||||||
},
|
},
|
||||||
|
|||||||
@@ -0,0 +1,9 @@
|
|||||||
|
# [자산] 자산관리 모듈 — `app/modules/asset/`, `asset_db`
|
||||||
|
|
||||||
|
> 이 모듈만 고칠 때 읽는 요약. 상세는 `docs/ASSET_MODULE.md`.
|
||||||
|
> 정적 파일: `app/static/asset.css`, `app/static/asset.js`. 템플릿: `templates/`.
|
||||||
|
|
||||||
|
- 진입 `/asset/`, 권한키 `asset`. 사무집기·전산장비 개별 자산번호 등록.
|
||||||
|
- 배정/반납/상태·구매/보증·활동 이력, HWiNFO XML 사양/보고서 보존(`hwinfo.py`), 사진 갤러리(`media.py`), 보고서 모니터 자산(`monitors.py`).
|
||||||
|
- 삭제는 수퍼관리자(`SUPER_ADMIN_EMAIL`)만 — 이력/원본 보존.
|
||||||
|
- `ASSET_DB_URL` 미설정 시 저장 비활성, XML 분석 미리보기는 가능.
|
||||||
@@ -0,0 +1,9 @@
|
|||||||
|
"""Company asset management; PostgreSQL only, never creates databases at startup."""
|
||||||
|
from .router import router
|
||||||
|
|
||||||
|
|
||||||
|
def build_asset_store(*, dsn: str | None):
|
||||||
|
if not dsn:
|
||||||
|
return None
|
||||||
|
from .db import AssetStore
|
||||||
|
return AssetStore(dsn)
|
||||||
@@ -0,0 +1,282 @@
|
|||||||
|
"""자산·보고서·이력을 함께 저장합니다. DB 생성은 사용자가 서버에서 SQL로 진행합니다."""
|
||||||
|
from __future__ import annotations
|
||||||
|
|
||||||
|
import uuid
|
||||||
|
from datetime import date, datetime
|
||||||
|
from decimal import Decimal
|
||||||
|
|
||||||
|
from psycopg.rows import dict_row
|
||||||
|
from psycopg.types.json import Jsonb
|
||||||
|
from psycopg_pool import ConnectionPool
|
||||||
|
|
||||||
|
from .store import AssetConflict, transition
|
||||||
|
from .media import MAX_PHOTOS
|
||||||
|
from .monitors import compatible_monitor, monitor_devices
|
||||||
|
|
||||||
|
FIELDS = ("tag", "name", "category", "manufacturer", "model", "serial", "location", "department",
|
||||||
|
"purchased_on", "purchase_cost", "vendor", "warranty_until", "notes")
|
||||||
|
SORTS = {"updated": "a.updated_at DESC", "name": "a.name ASC", "tag": "a.tag ASC",
|
||||||
|
"cost": "a.purchase_cost DESC NULLS LAST", "warranty": "a.warranty_until ASC NULLS LAST"}
|
||||||
|
|
||||||
|
|
||||||
|
def serialize(row):
|
||||||
|
if row is None:
|
||||||
|
return None
|
||||||
|
return {k: (v.isoformat() if isinstance(v, (date, datetime)) else str(v) if isinstance(v, Decimal) else v)
|
||||||
|
for k, v in row.items()}
|
||||||
|
|
||||||
|
|
||||||
|
def filters(q="", category="", status="", location="", assignee="", warranty=False, group=""):
|
||||||
|
conditions, params = ["a.deleted_at IS NULL"], []
|
||||||
|
if q:
|
||||||
|
# %와 _도 입력한 글자 그대로 검색합니다. 검색어는 SQL과 분리해서 전달합니다.
|
||||||
|
value = "%" + q.replace("\\", "\\\\").replace("%", "\\%").replace("_", "\\_") + "%"
|
||||||
|
conditions.append("(concat_ws(' ',a.tag,a.name,a.model,a.serial,a.manufacturer,a.location,a.department,a.assignee_email) ILIKE %s)")
|
||||||
|
params.append(value)
|
||||||
|
for col, value in (("category", category), ("status", status), ("location", location), ("assignee_email", assignee)):
|
||||||
|
if value:
|
||||||
|
conditions.append(f"a.{col} = %s")
|
||||||
|
params.append(value)
|
||||||
|
if warranty:
|
||||||
|
conditions.append("a.warranty_until BETWEEN (now() AT TIME ZONE 'Asia/Seoul')::date AND (now() AT TIME ZONE 'Asia/Seoul')::date + 30 AND a.status <> 'retired'")
|
||||||
|
if group == "furniture":
|
||||||
|
conditions.append("a.category IN ('desk','chair','furniture')")
|
||||||
|
elif group == "computer":
|
||||||
|
conditions.append("a.category NOT IN ('desk','chair','furniture')")
|
||||||
|
return " AND ".join(conditions), params
|
||||||
|
|
||||||
|
|
||||||
|
class AssetStore:
|
||||||
|
def __init__(self, dsn):
|
||||||
|
self._pool = ConnectionPool(dsn, min_size=0, max_size=5, timeout=5, open=False,
|
||||||
|
kwargs={"row_factory": dict_row, "autocommit": True})
|
||||||
|
self._pool.open(wait=False)
|
||||||
|
|
||||||
|
def close(self):
|
||||||
|
self._pool.close()
|
||||||
|
|
||||||
|
def health(self):
|
||||||
|
with self._pool.connection(timeout=5) as conn:
|
||||||
|
conn.execute("SELECT id,deleted_at FROM assets LIMIT 1")
|
||||||
|
conn.execute("SELECT id FROM asset_photos LIMIT 0")
|
||||||
|
conn.execute("SELECT monitor_key FROM asset_monitor_links LIMIT 0")
|
||||||
|
|
||||||
|
def list_assets(self, *, page=1, page_size=25, sort="updated", **kwargs):
|
||||||
|
# 전체 개수와 목록을 같은 시점의 데이터로 읽어 페이지 숫자가 어긋나지 않게 합니다.
|
||||||
|
where, params = filters(**kwargs)
|
||||||
|
with self._pool.connection() as conn, conn.transaction():
|
||||||
|
conn.execute("SET TRANSACTION ISOLATION LEVEL REPEATABLE READ READ ONLY")
|
||||||
|
total = conn.execute(f"SELECT count(*) AS n FROM assets a WHERE {where}", params).fetchone()["n"]
|
||||||
|
rows = conn.execute(
|
||||||
|
f"SELECT a.*,r.parsed->'summary' AS specs,r.uploaded_at AS report_at FROM assets a "
|
||||||
|
"LEFT JOIN asset_reports r ON r.id=a.latest_report_id "
|
||||||
|
f"WHERE {where} ORDER BY {SORTS.get(sort, SORTS['updated'])},a.id LIMIT %s OFFSET %s",
|
||||||
|
[*params, page_size, (page - 1) * page_size]).fetchall()
|
||||||
|
return {"items": [serialize(r) for r in rows], "total": total, "page": page, "page_size": page_size}
|
||||||
|
|
||||||
|
def dashboard(self):
|
||||||
|
with self._pool.connection() as conn, conn.transaction():
|
||||||
|
conn.execute("SET TRANSACTION ISOLATION LEVEL REPEATABLE READ READ ONLY")
|
||||||
|
totals = conn.execute("""SELECT count(*) AS total,
|
||||||
|
count(*) FILTER(WHERE status='available') AS available,
|
||||||
|
count(*) FILTER(WHERE status='in_use') AS in_use,
|
||||||
|
count(*) FILTER(WHERE status='maintenance') AS maintenance,
|
||||||
|
count(*) FILTER(WHERE status='lost') AS lost,
|
||||||
|
count(*) FILTER(WHERE status='retired') AS retired,
|
||||||
|
coalesce(sum(purchase_cost) FILTER(WHERE status<>'retired'),0) AS purchase_total,
|
||||||
|
count(*) FILTER(WHERE status<>'retired' AND warranty_until BETWEEN
|
||||||
|
(now() AT TIME ZONE 'Asia/Seoul')::date AND (now() AT TIME ZONE 'Asia/Seoul')::date+30) AS warranty_soon
|
||||||
|
FROM assets WHERE deleted_at IS NULL""").fetchone()
|
||||||
|
categories = conn.execute("SELECT category,count(*) AS count FROM assets WHERE deleted_at IS NULL GROUP BY category ORDER BY count(*) DESC,category").fetchall()
|
||||||
|
locations = conn.execute("SELECT DISTINCT location FROM assets WHERE location<>'' AND deleted_at IS NULL ORDER BY location").fetchall()
|
||||||
|
activity = conn.execute("SELECT e.*,a.tag,a.name FROM asset_events e JOIN assets a ON a.id=e.asset_id WHERE a.deleted_at IS NULL ORDER BY e.id DESC LIMIT 12").fetchall()
|
||||||
|
return {"totals": serialize(totals), "categories": categories, "locations": [r["location"] for r in locations],
|
||||||
|
"activity": [serialize(r) for r in activity]}
|
||||||
|
|
||||||
|
def detail(self, asset_id):
|
||||||
|
with self._pool.connection() as conn, conn.transaction():
|
||||||
|
conn.execute("SET TRANSACTION ISOLATION LEVEL REPEATABLE READ READ ONLY")
|
||||||
|
asset = conn.execute("SELECT * FROM assets WHERE id=%s AND deleted_at IS NULL", (asset_id,)).fetchone()
|
||||||
|
if not asset:
|
||||||
|
raise KeyError(asset_id)
|
||||||
|
reports = conn.execute("SELECT id,filename,sha256,uploaded_at,actor,parsed->'summary' AS summary,parsed->>'scan_time' AS scan_time FROM asset_reports WHERE asset_id=%s ORDER BY uploaded_at DESC,id DESC", (asset_id,)).fetchall()
|
||||||
|
report = conn.execute("SELECT id,filename,uploaded_at,parsed FROM asset_reports WHERE id=%s AND asset_id=%s", (asset["latest_report_id"], asset_id)).fetchone() if asset["latest_report_id"] else None
|
||||||
|
events = conn.execute("SELECT * FROM asset_events WHERE asset_id=%s ORDER BY id DESC LIMIT 200", (asset_id,)).fetchall()
|
||||||
|
photos = conn.execute("SELECT id,filename,width,height,uploaded_at,actor FROM asset_photos WHERE asset_id=%s ORDER BY uploaded_at DESC,id", (asset_id,)).fetchall()
|
||||||
|
monitors = self._monitor_matches(conn, asset_id, report["parsed"]) if report else []
|
||||||
|
return {"asset": serialize(asset), "report": serialize(report), "reports": [serialize(r) for r in reports],
|
||||||
|
"events": [serialize(r) for r in events], "photos": [serialize(r) for r in photos], "monitors": monitors}
|
||||||
|
|
||||||
|
@staticmethod
|
||||||
|
def _lock(conn, asset_id, version):
|
||||||
|
# 같은 자산을 동시에 변경할 때 먼저 저장한 사용자의 값을 보호합니다.
|
||||||
|
asset = conn.execute("SELECT * FROM assets WHERE id=%s AND deleted_at IS NULL FOR UPDATE", (asset_id,)).fetchone()
|
||||||
|
if not asset or asset.get("deleted_at"):
|
||||||
|
raise KeyError(asset_id)
|
||||||
|
if asset["version"] != version:
|
||||||
|
raise AssetConflict("다른 사용자가 수정했습니다. 상세 화면을 새로 열고 다시 시도하세요.")
|
||||||
|
return asset
|
||||||
|
|
||||||
|
@staticmethod
|
||||||
|
def _event(conn, asset_id, actor, kind, note, changes):
|
||||||
|
conn.execute("INSERT INTO asset_events(asset_id,actor,kind,note,changes) VALUES(%s,%s,%s,%s,%s)",
|
||||||
|
(asset_id, actor, kind, note, Jsonb(changes)))
|
||||||
|
|
||||||
|
def create(self, payload, actor, report=None):
|
||||||
|
with self._pool.connection() as conn, conn.transaction():
|
||||||
|
return self._create(conn, payload, actor, report)
|
||||||
|
|
||||||
|
def _create(self, conn, payload, actor, report=None):
|
||||||
|
# 모니터 등록도 같은 트랜잭션 안에서 자산 생성과 연결을 함께 처리합니다.
|
||||||
|
data = payload.model_dump()
|
||||||
|
asset_id = uuid.uuid4().hex
|
||||||
|
if not data["tag"]:
|
||||||
|
data["tag"] = "AST-" + str(conn.execute("SELECT nextval('asset_tag_seq') AS n").fetchone()["n"]).zfill(6)
|
||||||
|
conn.execute(f"INSERT INTO assets(id,{','.join(FIELDS)}) VALUES({','.join(['%s'] * (len(FIELDS) + 1))})",
|
||||||
|
[asset_id, *[data[k] for k in FIELDS]])
|
||||||
|
self._event(conn, asset_id, actor, "create", "자산 등록", {"after": serialize(data)})
|
||||||
|
if report:
|
||||||
|
if data["category"] != "computer":
|
||||||
|
raise ValueError("HWiNFO 보고서는 컴퓨터 자산에만 연결할 수 있습니다.")
|
||||||
|
self._save_report(conn, asset_id, actor, *report)
|
||||||
|
return asset_id
|
||||||
|
|
||||||
|
def update(self, asset_id, payload, actor):
|
||||||
|
data = payload.model_dump(exclude={"version"})
|
||||||
|
with self._pool.connection() as conn, conn.transaction():
|
||||||
|
old = self._lock(conn, asset_id, payload.version)
|
||||||
|
if old["latest_report_id"] and data["category"] != "computer":
|
||||||
|
raise ValueError("사양 보고서가 연결된 자산은 컴퓨터 분류를 유지해야 합니다.")
|
||||||
|
if not data["tag"]:
|
||||||
|
data["tag"] = old["tag"]
|
||||||
|
changes = {k: {"before": serialize(old)[k], "after": serialize(data)[k]} for k in FIELDS if old[k] != data[k]}
|
||||||
|
if changes:
|
||||||
|
conn.execute(f"UPDATE assets SET {','.join(k+'=%s' for k in FIELDS)},version=version+1,updated_at=now() WHERE id=%s",
|
||||||
|
[*[data[k] for k in FIELDS], asset_id])
|
||||||
|
self._event(conn, asset_id, actor, "update", "자산 정보 수정", changes)
|
||||||
|
|
||||||
|
def action(self, asset_id, payload, actor):
|
||||||
|
with self._pool.connection() as conn, conn.transaction():
|
||||||
|
old = self._lock(conn, asset_id, payload.version)
|
||||||
|
status, assignee = transition(old, payload)
|
||||||
|
location = payload.location or old["location"]
|
||||||
|
conn.execute("UPDATE assets SET status=%s,assignee_email=%s,location=%s,version=version+1,updated_at=now() WHERE id=%s",
|
||||||
|
(status, assignee, location, asset_id))
|
||||||
|
changes = {k: {"before": old[k], "after": value} for k, value in
|
||||||
|
(("status", status), ("assignee_email", assignee), ("location", location)) if old[k] != value}
|
||||||
|
self._event(conn, asset_id, actor, payload.action, payload.note, changes)
|
||||||
|
|
||||||
|
def _save_report(self, conn, asset_id, actor, filename, raw, parsed):
|
||||||
|
# 원본과 분석 결과를 함께 저장하고 최신 보고서만 교체합니다. 이전 보고서는 남습니다.
|
||||||
|
existing = conn.execute("SELECT id FROM asset_reports WHERE asset_id=%s AND sha256=%s", (asset_id, parsed["sha256"])).fetchone()
|
||||||
|
if existing:
|
||||||
|
raise AssetConflict("이 자산에 동일한 보고서가 이미 등록되어 있습니다.")
|
||||||
|
report_id = uuid.uuid4().hex
|
||||||
|
conn.execute("INSERT INTO asset_reports(id,asset_id,filename,sha256,raw_xml,parsed,actor) VALUES(%s,%s,%s,%s,%s,%s,%s)",
|
||||||
|
(report_id, asset_id, filename, parsed["sha256"], raw, Jsonb(parsed), actor))
|
||||||
|
conn.execute("UPDATE assets SET latest_report_id=%s,version=version+1,updated_at=now() WHERE id=%s", (report_id, asset_id))
|
||||||
|
self._event(conn, asset_id, actor, "report", filename, {"report_id": report_id, "summary": parsed["summary"]})
|
||||||
|
return report_id
|
||||||
|
|
||||||
|
def attach_report(self, asset_id, version, actor, filename, raw, parsed):
|
||||||
|
with self._pool.connection() as conn, conn.transaction():
|
||||||
|
asset = self._lock(conn, asset_id, version)
|
||||||
|
if asset["category"] != "computer":
|
||||||
|
raise ValueError("HWiNFO 보고서는 컴퓨터 자산에만 연결할 수 있습니다.")
|
||||||
|
return self._save_report(conn, asset_id, actor, filename, raw, parsed)
|
||||||
|
|
||||||
|
def report(self, asset_id, report_id, *, raw=False):
|
||||||
|
columns = "r.filename,r.raw_xml" if raw else "r.id,r.filename,r.parsed,r.uploaded_at"
|
||||||
|
with self._pool.connection() as conn:
|
||||||
|
row = conn.execute(f"SELECT {columns} FROM asset_reports r JOIN assets a ON a.id=r.asset_id WHERE r.asset_id=%s AND r.id=%s AND a.deleted_at IS NULL", (asset_id, report_id)).fetchone()
|
||||||
|
if not row:
|
||||||
|
raise KeyError(report_id)
|
||||||
|
return serialize(row)
|
||||||
|
|
||||||
|
def delete(self, asset_id, version, actor, note):
|
||||||
|
# 수퍼 관리자 삭제도 이력과 원본은 보존하고 대장·다운로드에서 제외합니다.
|
||||||
|
with self._pool.connection() as conn, conn.transaction():
|
||||||
|
self._lock(conn, asset_id, version)
|
||||||
|
self._event(conn, asset_id, actor, "delete", note, {})
|
||||||
|
conn.execute("UPDATE assets SET deleted_at=now(),deleted_by=%s,version=version+1,updated_at=now() WHERE id=%s", (actor, asset_id))
|
||||||
|
|
||||||
|
def add_photo(self, asset_id, version, actor, filename, image, mime, width, height):
|
||||||
|
with self._pool.connection() as conn, conn.transaction():
|
||||||
|
self._lock(conn, asset_id, version)
|
||||||
|
count = conn.execute("SELECT count(*) AS n FROM asset_photos WHERE asset_id=%s", (asset_id,)).fetchone()["n"]
|
||||||
|
if count >= MAX_PHOTOS:
|
||||||
|
raise ValueError(f"사진은 자산당 {MAX_PHOTOS}개까지 등록할 수 있습니다.")
|
||||||
|
photo_id = uuid.uuid4().hex
|
||||||
|
conn.execute("INSERT INTO asset_photos(id,asset_id,filename,image,mime,width,height,actor) VALUES(%s,%s,%s,%s,%s,%s,%s,%s)",
|
||||||
|
(photo_id, asset_id, filename, image, mime, width, height, actor))
|
||||||
|
conn.execute("UPDATE assets SET version=version+1,updated_at=now() WHERE id=%s", (asset_id,))
|
||||||
|
self._event(conn, asset_id, actor, "photo", filename, {"photo_id": photo_id})
|
||||||
|
return photo_id
|
||||||
|
|
||||||
|
def photo(self, asset_id, photo_id):
|
||||||
|
with self._pool.connection() as conn:
|
||||||
|
row = conn.execute("SELECT p.image,p.mime FROM asset_photos p JOIN assets a ON a.id=p.asset_id WHERE p.asset_id=%s AND p.id=%s AND a.deleted_at IS NULL", (asset_id, photo_id)).fetchone()
|
||||||
|
if not row:
|
||||||
|
raise KeyError(photo_id)
|
||||||
|
return row
|
||||||
|
|
||||||
|
@staticmethod
|
||||||
|
def _monitor_matches(conn, computer_id, parsed):
|
||||||
|
result = []
|
||||||
|
for device in monitor_devices(parsed):
|
||||||
|
linked = conn.execute("SELECT a.* FROM asset_monitor_links l JOIN assets a ON a.id=l.monitor_asset_id WHERE l.computer_id=%s AND l.monitor_key=%s AND a.category='monitor' AND a.deleted_at IS NULL", (computer_id, device["key"])).fetchone()
|
||||||
|
matches = conn.execute("SELECT * FROM assets WHERE category='monitor' AND deleted_at IS NULL AND lower(btrim(serial))=%s ORDER BY id LIMIT 21", (device["serial"].casefold(),)).fetchall() if device["serial"] else []
|
||||||
|
compatible = [a for a in matches if compatible_monitor(a, device)]
|
||||||
|
asset = linked or (compatible[0] if len(compatible) == 1 else None)
|
||||||
|
candidates = matches if not asset else []
|
||||||
|
# candidate_by — 후보가 같은 시리얼(같은 실물일 가능성)인지, 참고용 같은 모델·이름인지.
|
||||||
|
# 같은 모델은 여러 대일 수 있으므로(듀얼 모니터 등) 새 등록을 막지 않는다(2026-10-07).
|
||||||
|
candidate_by = "serial" if candidates else ""
|
||||||
|
if not asset and not candidates:
|
||||||
|
candidates = conn.execute("SELECT * FROM assets WHERE category='monitor' AND deleted_at IS NULL AND (lower(btrim(model))=%s OR lower(btrim(name))=%s) ORDER BY id LIMIT 20", (device["model"].casefold(), device["name"].casefold())).fetchall()
|
||||||
|
candidate_by = "model" if candidates else ""
|
||||||
|
result.append({**device, "asset": serialize(asset), "candidates": [serialize(r) for r in candidates],
|
||||||
|
"candidate_by": candidate_by,
|
||||||
|
"match": "linked" if linked else "serial" if asset else "unconfirmed"})
|
||||||
|
return result
|
||||||
|
|
||||||
|
def report_monitors(self, asset_id, report_id):
|
||||||
|
with self._pool.connection() as conn, conn.transaction():
|
||||||
|
conn.execute("SET TRANSACTION ISOLATION LEVEL REPEATABLE READ READ ONLY")
|
||||||
|
row = conn.execute("SELECT r.parsed FROM asset_reports r JOIN assets a ON a.id=r.asset_id WHERE r.asset_id=%s AND r.id=%s AND a.deleted_at IS NULL", (asset_id, report_id)).fetchone()
|
||||||
|
if not row:
|
||||||
|
raise KeyError(report_id)
|
||||||
|
return self._monitor_matches(conn, asset_id, row["parsed"])
|
||||||
|
|
||||||
|
def register_monitor(self, computer_id, index, payload, actor):
|
||||||
|
with self._pool.connection() as conn, conn.transaction():
|
||||||
|
computer = self._lock(conn, computer_id, payload.version)
|
||||||
|
if computer["category"] != "computer" or computer["latest_report_id"] != payload.report_id:
|
||||||
|
raise AssetConflict("최신 컴퓨터 보고서를 다시 열고 모니터를 등록하세요.")
|
||||||
|
row = conn.execute("SELECT parsed FROM asset_reports WHERE asset_id=%s AND id=%s", (computer_id, payload.report_id)).fetchone()
|
||||||
|
devices = monitor_devices(row["parsed"]) if row else []
|
||||||
|
if index < 0 or index >= len(devices):
|
||||||
|
raise KeyError(index)
|
||||||
|
device = devices[index]
|
||||||
|
# 서로 다른 컴퓨터에서 동일 시리얼을 동시에 등록하는 경우도 중복을 막습니다.
|
||||||
|
if device["serial"]:
|
||||||
|
conn.execute("SELECT pg_advisory_xact_lock(hashtextextended(%s,0))", ("asset-monitor:" + device["serial"].casefold(),))
|
||||||
|
if payload.asset_id:
|
||||||
|
target = conn.execute("SELECT * FROM assets WHERE id=%s AND deleted_at IS NULL FOR UPDATE", (payload.asset_id,)).fetchone()
|
||||||
|
if not target or target["category"] != "monitor":
|
||||||
|
raise ValueError("등록된 모니터 자산을 선택하세요.")
|
||||||
|
monitor_id = target["id"]
|
||||||
|
else:
|
||||||
|
match = self._monitor_matches(conn, computer_id, row["parsed"])[index]
|
||||||
|
# 같은 시리얼(같은 실물)만 막는다 — 같은 모델이지만 시리얼이 다른 모니터는 새 자산으로 등록된다.
|
||||||
|
if match["asset"] or match["candidate_by"] == "serial":
|
||||||
|
raise AssetConflict(f"같은 시리얼({device['serial']})의 모니터가 이미 등록되어 있습니다. 기존 자산에 연결하세요."
|
||||||
|
if device["serial"] else "이 모니터는 이미 자산에 연결되어 있습니다.")
|
||||||
|
# 보고서의 실제 시리얼을 유지해야 이후 보고서에서도 같은 장비를 찾습니다.
|
||||||
|
data = payload.asset.model_copy(update={"serial": device["serial"] or payload.asset.serial})
|
||||||
|
monitor_id = self._create(conn, data, actor)
|
||||||
|
conn.execute("INSERT INTO asset_monitor_links(computer_id,monitor_key,monitor_asset_id,actor) VALUES(%s,%s,%s,%s) ON CONFLICT(computer_id,monitor_key) DO UPDATE SET monitor_asset_id=EXCLUDED.monitor_asset_id,actor=EXCLUDED.actor,linked_at=now()",
|
||||||
|
(computer_id, device["key"], monitor_id, actor))
|
||||||
|
conn.execute("UPDATE assets SET version=version+1,updated_at=now() WHERE id=%s", (computer_id,))
|
||||||
|
self._event(conn, computer_id, actor, "monitor", "모니터 자산 연결", {"monitor_asset_id": monitor_id, "model": device["model"]})
|
||||||
|
return monitor_id
|
||||||
@@ -0,0 +1,129 @@
|
|||||||
|
"""HWiNFO XML을 부품별로 읽습니다. 외부 파일이나 엔티티는 열지 않습니다."""
|
||||||
|
from __future__ import annotations
|
||||||
|
|
||||||
|
import hashlib
|
||||||
|
import re
|
||||||
|
from datetime import datetime
|
||||||
|
from xml.etree.ElementTree import ParseError
|
||||||
|
|
||||||
|
from defusedxml.ElementTree import fromstring
|
||||||
|
from defusedxml.common import DefusedXmlException
|
||||||
|
|
||||||
|
MAX_REPORT_BYTES = 10 * 1024 * 1024
|
||||||
|
SECTION_LABELS = {
|
||||||
|
"SYSTEM": "시스템", "CPU": "프로세서", "MOBO": "메인보드 · BIOS",
|
||||||
|
"MEMORY": "메모리", "VIDEO": "그래픽", "MONITOR": "모니터",
|
||||||
|
"DRIVES": "저장장치", "NETWORK": "네트워크", "SOUND": "오디오",
|
||||||
|
"PORTS": "포트 · USB", "BUS": "버스 · 컨트롤러",
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
def _text(node, tag):
|
||||||
|
return (node.findtext(tag) or "").strip()
|
||||||
|
|
||||||
|
|
||||||
|
def _props(node):
|
||||||
|
return [{"label": _text(p, "Entry"), "value": _text(p, "Description"),
|
||||||
|
"type": _text(p, "PropertyType")} for p in node.findall("Property")]
|
||||||
|
|
||||||
|
|
||||||
|
def _pick(nodes, *, types=(), labels=()):
|
||||||
|
# 언어와 무관한 PropertyType을 먼저 사용하고, 없을 때 한글/영문 항목명을 찾습니다.
|
||||||
|
properties = [p for n in nodes for p in n["properties"]]
|
||||||
|
for kind in types:
|
||||||
|
for p in properties:
|
||||||
|
if p["type"] == kind and p["value"]:
|
||||||
|
return p["value"]
|
||||||
|
for label in labels:
|
||||||
|
for p in properties:
|
||||||
|
if p["label"].casefold() == label.casefold() and p["value"]:
|
||||||
|
return p["value"]
|
||||||
|
return ""
|
||||||
|
|
||||||
|
|
||||||
|
def parse_hwinfo(raw: bytes) -> dict:
|
||||||
|
if not raw or len(raw) > MAX_REPORT_BYTES:
|
||||||
|
raise ValueError("XML 보고서는 비어 있지 않은 10 MB 이하 파일이어야 합니다.")
|
||||||
|
try:
|
||||||
|
# HWiNFO의 DTD 선언은 허용하되 파일을 읽지 않습니다. 엔티티는 모두 차단합니다.
|
||||||
|
root = fromstring(raw, forbid_dtd=False, forbid_entities=True, forbid_external=True)
|
||||||
|
except (ParseError, DefusedXmlException, ValueError, LookupError) as exc:
|
||||||
|
raise ValueError("XML을 읽을 수 없습니다. HWiNFO XML 보고서인지 확인하세요.") from exc
|
||||||
|
if root.tag != "HWINFO" or len(root.findall("COMPUTER")) != 1:
|
||||||
|
raise ValueError("컴퓨터 한 대의 HWiNFO XML 보고서만 업로드할 수 있습니다.")
|
||||||
|
computer = root.find("COMPUTER")
|
||||||
|
sections = [{"key": "SYSTEM", "label": "시스템", "nodes": []}]
|
||||||
|
count = 0
|
||||||
|
|
||||||
|
def walk(node, path, result, depth=0):
|
||||||
|
nonlocal count
|
||||||
|
count += 1
|
||||||
|
if count > 30000 or depth > 64:
|
||||||
|
raise ValueError("보고서 구조가 너무 크거나 깊습니다.")
|
||||||
|
name = _text(node, "NodeName")
|
||||||
|
trail = path + ([name] if name else [])
|
||||||
|
props = _props(node)
|
||||||
|
if props:
|
||||||
|
result.append({"name": name or node.tag, "path": " › ".join(trail), "properties": props})
|
||||||
|
for child in node:
|
||||||
|
if child.tag in {"SubNodes", "SubNode"}:
|
||||||
|
walk(child, trail, result, depth + 1)
|
||||||
|
elif child.find("NodeName") is not None:
|
||||||
|
walk(child, trail, result, depth + 1)
|
||||||
|
|
||||||
|
sections[0]["nodes"] = [{"name": _text(computer, "NodeName") or "컴퓨터",
|
||||||
|
"path": "시스템", "properties": _props(computer)}]
|
||||||
|
subnodes = computer.find("SubNodes")
|
||||||
|
if subnodes is not None:
|
||||||
|
for node in subnodes:
|
||||||
|
group = {"key": node.tag, "label": SECTION_LABELS.get(node.tag, _text(node, "NodeName") or node.tag), "nodes": []}
|
||||||
|
walk(node, [], group["nodes"])
|
||||||
|
sections.append(group)
|
||||||
|
by_key = {s["key"]: s["nodes"] for s in sections}
|
||||||
|
get = lambda key, **kw: _pick(by_key.get(key, []), **kw)
|
||||||
|
summary = {
|
||||||
|
"computer_name": _text(computer, "NodeName") or get("SYSTEM", labels=("컴퓨터 이름", "Computer Name")),
|
||||||
|
"os": get("SYSTEM", labels=("운영 체제", "Operating System")),
|
||||||
|
"manufacturer": get("SYSTEM", labels=("컴퓨터 브랜드", "Computer Brand Name")),
|
||||||
|
"cpu": get("CPU", types=("CPU_NAME",), labels=("프로세서 이름", "Processor Name")),
|
||||||
|
"cores": get("CPU", labels=("프로세서 코어 수", "CPU 코어 수", "Number of CPU Cores", "Number of Processor Cores")),
|
||||||
|
"threads": get("CPU", labels=("논리 프로세서 수", "논리 CPU 수", "Number of Logical CPUs", "Number of Logical Processors")),
|
||||||
|
"motherboard": get("MOBO", types=("SYSTEM_MAINBOARD",)),
|
||||||
|
"bios": get("MOBO", labels=("BIOS 버전", "BIOS Version")),
|
||||||
|
"memory": get("MEMORY", labels=("총 메모리 크기", "Total Memory Size")),
|
||||||
|
"gpu": get("VIDEO", types=("GFXCARD_CHIPSET", "GFXCARD")),
|
||||||
|
"gpu_memory": get("VIDEO", labels=("그래픽 메모리", "Video Memory", "Video Memory Size")),
|
||||||
|
"serial": get("MOBO", labels=("제품 일련 번호", "Product Serial Number", "System Serial Number")),
|
||||||
|
}
|
||||||
|
if summary["serial"].casefold() in {"system serial number", "to be filled by o.e.m.", "default string", "none", "n/a"}:
|
||||||
|
summary["serial"] = ""
|
||||||
|
if not summary["memory"]:
|
||||||
|
mb = get("MEMORY", types=("SYSTEM_MEMORY",))
|
||||||
|
if re.fullmatch(r"\d+(\.\d+)?", mb):
|
||||||
|
summary["memory"] = f"{float(mb) / 1024:g} GiB"
|
||||||
|
devices = {}
|
||||||
|
for key, types, labels in [
|
||||||
|
("DRIVES", ("HDD",), ("드라이브 모델", "Drive Model")),
|
||||||
|
("MEMORY", (), ("모듈 부품 번호", "Module Part Number")),
|
||||||
|
("MONITOR", ("MONITOR",), ("모니터 이름", "Monitor Name")),
|
||||||
|
("NETWORK", ("NETCARD",), ("네트워크 카드", "Network Card")),
|
||||||
|
("VIDEO", ("GFXCARD_CHIPSET", "GFXCARD"), ("그래픽 프로세서", "Video Chipset")),
|
||||||
|
]:
|
||||||
|
devices[key] = []
|
||||||
|
for node in by_key.get(key, []):
|
||||||
|
model = _pick([node], types=types, labels=labels)
|
||||||
|
if model:
|
||||||
|
devices[key].append({"name": model, "node": node["name"], "properties": node["properties"]})
|
||||||
|
summary["drive_count"] = len(devices["DRIVES"])
|
||||||
|
summary["monitor_count"] = len(devices["MONITOR"])
|
||||||
|
if not summary["computer_name"] or not any(summary[k] for k in ("cpu", "motherboard", "memory", "gpu")):
|
||||||
|
raise ValueError("컴퓨터 이름과 하드웨어 사양이 포함된 HWiNFO 보고서가 필요합니다.")
|
||||||
|
scan_time = _text(computer, "ScanTime")
|
||||||
|
try:
|
||||||
|
scan_time = datetime.strptime(scan_time, "%d.%m.%Y %H:%M").isoformat(timespec="minutes")
|
||||||
|
except ValueError:
|
||||||
|
pass # 날짜 형식이 다르면 원래 보고서에 적힌 시각을 그대로 보존합니다.
|
||||||
|
warnings = [p["value"] for p in _props(computer) if p["label"] in ("가상 머신 경고", "Virtual Machine Warning") and p["value"]]
|
||||||
|
return {"summary": summary, "sections": sections, "devices": devices, "scan_time": scan_time,
|
||||||
|
"warnings": warnings, "sha256": hashlib.sha256(raw).hexdigest(),
|
||||||
|
"property_count": sum(len(n["properties"]) for s in sections for n in s["nodes"])}
|
||||||
@@ -0,0 +1,38 @@
|
|||||||
|
"""사진을 실제 이미지로 확인하고 위치 정보 등 메타데이터를 제거합니다."""
|
||||||
|
import io
|
||||||
|
import warnings
|
||||||
|
|
||||||
|
from PIL import Image, ImageOps, UnidentifiedImageError
|
||||||
|
|
||||||
|
MAX_PHOTO_BYTES = 8 * 1024 * 1024
|
||||||
|
MAX_STORED_BYTES = 5 * 1024 * 1024
|
||||||
|
MAX_PHOTOS = 10
|
||||||
|
|
||||||
|
|
||||||
|
def prepare_photo(raw):
|
||||||
|
if not raw or len(raw) > MAX_PHOTO_BYTES:
|
||||||
|
raise ValueError("사진은 비어 있지 않은 8 MB 이하 파일이어야 합니다.")
|
||||||
|
try:
|
||||||
|
with warnings.catch_warnings():
|
||||||
|
warnings.simplefilter("error", Image.DecompressionBombWarning)
|
||||||
|
with Image.open(io.BytesIO(raw)) as source:
|
||||||
|
if source.format not in {"JPEG", "PNG", "WEBP"}:
|
||||||
|
raise ValueError("JPG, PNG, WebP 사진만 등록할 수 있습니다.")
|
||||||
|
if source.width * source.height > 20_000_000:
|
||||||
|
raise ValueError("사진은 2천만 화소 이하로 등록하세요.")
|
||||||
|
source.load()
|
||||||
|
image = ImageOps.exif_transpose(source)
|
||||||
|
image.thumbnail((2400, 2400))
|
||||||
|
transparent = "A" in image.getbands() or "transparency" in image.info
|
||||||
|
mode = "RGBA" if transparent else "RGB"
|
||||||
|
# 새 캔버스에 복사해 EXIF, GPS, 촬영기기 정보를 저장하지 않습니다.
|
||||||
|
clean = Image.new(mode, image.size)
|
||||||
|
clean.paste(image.convert(mode))
|
||||||
|
output = io.BytesIO()
|
||||||
|
clean.save(output, format="PNG" if transparent else "JPEG", **({} if transparent else {"quality": 88}))
|
||||||
|
data = output.getvalue()
|
||||||
|
if len(data) > MAX_STORED_BYTES:
|
||||||
|
raise ValueError("사진을 압축해 다시 등록하세요. 저장 크기는 5 MB 이하입니다.")
|
||||||
|
return data, "image/png" if transparent else "image/jpeg", clean.width, clean.height
|
||||||
|
except (UnidentifiedImageError, OSError, SyntaxError, Image.DecompressionBombError, Image.DecompressionBombWarning) as exc:
|
||||||
|
raise ValueError("사진을 읽을 수 없습니다. 정상적인 JPG, PNG, WebP 파일을 선택하세요.") from exc
|
||||||
@@ -0,0 +1,47 @@
|
|||||||
|
"""이전 보고서에도 적용할 수 있도록 저장된 모니터 항목에서 식별 정보를 읽습니다."""
|
||||||
|
import hashlib
|
||||||
|
import re
|
||||||
|
|
||||||
|
|
||||||
|
def usable_serial(value):
|
||||||
|
value = value.strip()
|
||||||
|
if value.casefold() in {"", "unknown", "n/a", "none", "not specified", "serial number", "알 수 없음"}:
|
||||||
|
return ""
|
||||||
|
if re.fullmatch(r"[0\s-]+", value):
|
||||||
|
return ""
|
||||||
|
return value
|
||||||
|
|
||||||
|
|
||||||
|
def compatible_monitor(asset, device):
|
||||||
|
"""다른 제조사나 다른 모델이 같은 시리얼을 쓰면 자동 연결하지 않습니다."""
|
||||||
|
def normalized(value):
|
||||||
|
return "".join(c for c in value.casefold() if c.isalnum())
|
||||||
|
brand = normalized(asset.get("manufacturer", ""))
|
||||||
|
reported_brand = normalized(device["manufacturer"])
|
||||||
|
if brand and reported_brand and brand != reported_brand:
|
||||||
|
return False
|
||||||
|
model = normalized(asset.get("model", ""))
|
||||||
|
if not model:
|
||||||
|
return True
|
||||||
|
return any(model == value or len(model) >= 4 and model in value
|
||||||
|
for value in (normalized(device["model"]), normalized(device["name"])))
|
||||||
|
|
||||||
|
|
||||||
|
def monitor_devices(parsed):
|
||||||
|
devices = []
|
||||||
|
for index, item in enumerate(parsed.get("devices", {}).get("MONITOR", [])):
|
||||||
|
props = item.get("properties", [])
|
||||||
|
def pick(*labels, kind=""):
|
||||||
|
return next((p["value"].strip() for p in props if p.get("label", "").casefold() in
|
||||||
|
{label.casefold() for label in labels} or kind and p.get("type") == kind), "")
|
||||||
|
name = item.get("name", "모니터")
|
||||||
|
model = pick("모니터 이름(제조업체)", "Monitor Name (Manuf)", "Monitor Name (Manufacturer)") or name
|
||||||
|
serial = usable_serial(pick("일련 번호", "Serial Number", "Monitor Serial Number"))
|
||||||
|
instance = pick("디바이스 인스턴스 ID", "Device Instance ID", kind="DeviceInstanceId")
|
||||||
|
# 시리얼이 없는 장치는 모델명만으로 동일 자산이라고 판단하지 않습니다.
|
||||||
|
identity = ("serial:" + serial.casefold() + ":" + model.casefold()) if serial else (
|
||||||
|
"instance:" + instance.casefold() if instance else f"report:{parsed.get('sha256', '')}:{index}")
|
||||||
|
devices.append({"index": index, "key": hashlib.sha256(identity.encode()).hexdigest(),
|
||||||
|
"name": name, "model": model[:200], "serial": serial[:200],
|
||||||
|
"manufacturer": name.split(" ", 1)[0][:150], "properties": props})
|
||||||
|
return devices
|
||||||
@@ -0,0 +1,304 @@
|
|||||||
|
from __future__ import annotations
|
||||||
|
|
||||||
|
# 화면, 권한 검사, 파일 업로드를 담당합니다. 실제 저장은 db.py에서 처리합니다.
|
||||||
|
|
||||||
|
import io
|
||||||
|
import secrets
|
||||||
|
from contextlib import contextmanager
|
||||||
|
from typing import Annotated
|
||||||
|
from urllib.parse import quote
|
||||||
|
|
||||||
|
from fastapi import APIRouter, Depends, File, Form, HTTPException, Query, Request, UploadFile
|
||||||
|
from fastapi.responses import RedirectResponse, Response
|
||||||
|
from openpyxl import Workbook
|
||||||
|
from pydantic import ValidationError
|
||||||
|
from psycopg import Error as DBError
|
||||||
|
from psycopg.errors import UniqueViolation
|
||||||
|
from psycopg_pool import PoolTimeout
|
||||||
|
from starlette.concurrency import run_in_threadpool
|
||||||
|
|
||||||
|
from .hwinfo import MAX_REPORT_BYTES, parse_hwinfo
|
||||||
|
from .store import ActionInput, AssetConflict, AssetInput, AssetUpdate, CATEGORIES, STATUSES
|
||||||
|
from .store import DeleteInput, MonitorInput
|
||||||
|
from .media import MAX_PHOTO_BYTES, prepare_photo
|
||||||
|
|
||||||
|
router = APIRouter(prefix="/asset", tags=["asset"])
|
||||||
|
|
||||||
|
|
||||||
|
def _user(request: Request):
|
||||||
|
from app.main import get_current_user_record
|
||||||
|
from app.store import has_module
|
||||||
|
user = get_current_user_record(request)
|
||||||
|
if not user:
|
||||||
|
raise HTTPException(401, "로그인이 필요합니다.")
|
||||||
|
if not has_module(user, "asset"):
|
||||||
|
raise HTTPException(403, "자산관리 권한이 없습니다.")
|
||||||
|
return user
|
||||||
|
|
||||||
|
|
||||||
|
def _write(request: Request, user=Depends(_user)):
|
||||||
|
expected = request.session.get("asset_csrf", "")
|
||||||
|
token = request.headers.get("x-asset-csrf", "")
|
||||||
|
if not expected or not secrets.compare_digest(expected, token):
|
||||||
|
raise HTTPException(403, "화면을 새로 열고 다시 시도하세요.")
|
||||||
|
return user
|
||||||
|
|
||||||
|
|
||||||
|
def _super(user):
|
||||||
|
from app.store import SUPER_ADMIN_EMAIL
|
||||||
|
return user.get("email", "").lower() == SUPER_ADMIN_EMAIL
|
||||||
|
|
||||||
|
|
||||||
|
def _super_write(user=Depends(_write)):
|
||||||
|
if not _super(user):
|
||||||
|
raise HTTPException(403, "수퍼 관리자만 자산을 삭제할 수 있습니다.")
|
||||||
|
return user
|
||||||
|
|
||||||
|
|
||||||
|
def _store(request):
|
||||||
|
store = getattr(request.app.state, "asset_store", None)
|
||||||
|
if store is None:
|
||||||
|
raise HTTPException(503, "자산관리 DB 설정이 필요합니다. 관리자에게 문의하세요.")
|
||||||
|
return store
|
||||||
|
|
||||||
|
|
||||||
|
@contextmanager
|
||||||
|
def _errors():
|
||||||
|
try:
|
||||||
|
yield
|
||||||
|
except AssetConflict as exc:
|
||||||
|
raise HTTPException(409, str(exc)) from exc
|
||||||
|
except KeyError as exc:
|
||||||
|
raise HTTPException(404, "자산 또는 보고서를 찾을 수 없습니다.") from exc
|
||||||
|
except ValueError as exc:
|
||||||
|
raise HTTPException(422, str(exc)) from exc
|
||||||
|
except UniqueViolation as exc:
|
||||||
|
raise HTTPException(409, "이미 등록된 자산번호입니다. 다른 번호를 사용하세요.") from exc
|
||||||
|
except (DBError, PoolTimeout) as exc:
|
||||||
|
# DB 오류에 접속 비밀번호가 섞일 수 있어 원문 대신 일반 안내만 보여줍니다.
|
||||||
|
raise HTTPException(503, "자산관리 DB에 연결할 수 없습니다. 설정과 초기화를 확인하세요.") from exc
|
||||||
|
|
||||||
|
|
||||||
|
@router.get("/")
|
||||||
|
def index(request: Request):
|
||||||
|
from app.main import build_erp_nav, get_current_user_record, render_template
|
||||||
|
from app.store import has_module, is_admin
|
||||||
|
user = get_current_user_record(request)
|
||||||
|
if not user:
|
||||||
|
return RedirectResponse("/login", 303)
|
||||||
|
if not has_module(user, "asset"):
|
||||||
|
return render_template(request, "denied.html", {"reason": "자산관리 권한이 없습니다.", "user": user,
|
||||||
|
"is_admin": is_admin(user)}, status_code=403)
|
||||||
|
request.session.setdefault("asset_csrf", secrets.token_urlsafe(32))
|
||||||
|
return render_template(request, "asset/index.html", {
|
||||||
|
"user": user, "is_admin": is_admin(user), "nav_items": build_erp_nav(user, active="asset"),
|
||||||
|
"page_title": "자산관리", "page_subtitle": "사무집기부터 컴퓨터 사양까지, 회사 자산을 한곳에서",
|
||||||
|
"categories": CATEGORIES, "statuses": STATUSES, "csrf_token": request.session["asset_csrf"],
|
||||||
|
"configured": getattr(request.app.state, "asset_store", None) is not None,
|
||||||
|
"can_delete": _super(user),
|
||||||
|
})
|
||||||
|
|
||||||
|
|
||||||
|
@router.get("/health")
|
||||||
|
def health(request: Request, user=Depends(_user)):
|
||||||
|
with _errors():
|
||||||
|
_store(request).health()
|
||||||
|
return {"ok": True}
|
||||||
|
|
||||||
|
|
||||||
|
@router.get("/api/bootstrap")
|
||||||
|
def bootstrap(request: Request, user=Depends(_user)):
|
||||||
|
from app.main import user_store
|
||||||
|
with _errors():
|
||||||
|
data = _store(request).dashboard()
|
||||||
|
data["users"] = [{"email": u["email"], "name": u.get("name") or u["email"]} for u in user_store.list_all()]
|
||||||
|
return data
|
||||||
|
|
||||||
|
|
||||||
|
def _query(q="", category="", status="", location="", assignee="", warranty=False, group=""):
|
||||||
|
if category and category not in CATEGORIES or status and status not in STATUSES:
|
||||||
|
raise HTTPException(422, "분류 또는 상태 필터가 올바르지 않습니다.")
|
||||||
|
if group not in {"", "computer", "furniture"}:
|
||||||
|
raise HTTPException(422, "자산 구분 필터가 올바르지 않습니다.")
|
||||||
|
return dict(q=q, category=category, status=status, location=location, assignee=assignee, warranty=warranty, group=group)
|
||||||
|
|
||||||
|
|
||||||
|
@router.get("/api/assets")
|
||||||
|
def assets(request: Request, q: str = Query("", max_length=200), category: str = "", status: str = "",
|
||||||
|
location: str = Query("", max_length=150), assignee: str = Query("", max_length=254), warranty: bool = False,
|
||||||
|
page: int = Query(1, ge=1, le=100000), page_size: int = Query(25, ge=1, le=100),
|
||||||
|
sort: str = "updated", group: str = "", user=Depends(_user)):
|
||||||
|
with _errors():
|
||||||
|
return _store(request).list_assets(page=page, page_size=page_size, sort=sort,
|
||||||
|
**_query(q, category, status, location, assignee, warranty, group))
|
||||||
|
|
||||||
|
|
||||||
|
@router.get("/api/export")
|
||||||
|
def export(request: Request, q: str = Query("", max_length=200), category: str = "", status: str = "",
|
||||||
|
location: str = Query("", max_length=150), assignee: str = Query("", max_length=254), warranty: bool = False,
|
||||||
|
group: str = "", user=Depends(_user)):
|
||||||
|
from app.timezone import today_kst
|
||||||
|
with _errors():
|
||||||
|
data = _store(request).list_assets(page=1, page_size=10001, **_query(q, category, status, location, assignee, warranty, group))
|
||||||
|
if data["total"] > 10000:
|
||||||
|
raise HTTPException(422, "한 번에 10,000개까지 내보낼 수 있습니다. 필터를 좁혀주세요.")
|
||||||
|
book = Workbook()
|
||||||
|
sheet = book.active
|
||||||
|
sheet.title = "자산대장"
|
||||||
|
headers = ["자산번호", "자산명", "분류", "상태", "제조사", "모델", "시리얼", "위치", "부서", "사용자", "구매일", "구매금액(원)", "구매처", "보증종료", "메모", "CPU", "메모리", "GPU", "운영체제"]
|
||||||
|
sheet.append(headers)
|
||||||
|
for row in data["items"]:
|
||||||
|
specs = row.get("specs") or {}
|
||||||
|
values = [row["tag"], row["name"], CATEGORIES[row["category"]], STATUSES[row["status"]],
|
||||||
|
*[row[k] for k in ("manufacturer", "model", "serial", "location", "department", "assignee_email", "purchased_on")],
|
||||||
|
float(row["purchase_cost"]) if row["purchase_cost"] is not None else None,
|
||||||
|
row["vendor"], row["warranty_until"], row["notes"], *[specs.get(k, "") for k in ("cpu", "memory", "gpu", "os")]]
|
||||||
|
sheet.append(values)
|
||||||
|
# =로 시작하는 자산명도 엑셀 수식 대신 일반 글자로 저장합니다.
|
||||||
|
for cell in sheet[sheet.max_row]:
|
||||||
|
if isinstance(cell.value, str):
|
||||||
|
cell.data_type = "s"
|
||||||
|
sheet.freeze_panes = "C2"
|
||||||
|
sheet.auto_filter.ref = sheet.dimensions
|
||||||
|
from openpyxl.styles import Font, PatternFill
|
||||||
|
from openpyxl.utils import get_column_letter
|
||||||
|
for cell in sheet[1]:
|
||||||
|
cell.font = Font(bold=True, color="FFFFFF")
|
||||||
|
cell.fill = PatternFill("solid", fgColor="171717")
|
||||||
|
for i in range(1, len(headers) + 1):
|
||||||
|
sheet.column_dimensions[get_column_letter(i)].width = 22 if i > 2 else 28
|
||||||
|
buffer = io.BytesIO()
|
||||||
|
book.save(buffer)
|
||||||
|
return Response(buffer.getvalue(), media_type="application/vnd.openxmlformats-officedocument.spreadsheetml.sheet",
|
||||||
|
headers={"Content-Disposition": f'attachment; filename="assets-{today_kst().isoformat()}.xlsx"'})
|
||||||
|
|
||||||
|
|
||||||
|
@router.post("/api/assets")
|
||||||
|
def create(request: Request, payload: AssetInput, user=Depends(_write)):
|
||||||
|
with _errors():
|
||||||
|
asset_id = _store(request).create(payload, user["email"])
|
||||||
|
return {"id": asset_id}
|
||||||
|
|
||||||
|
|
||||||
|
@router.get("/api/assets/{asset_id}")
|
||||||
|
def detail(request: Request, asset_id: str, user=Depends(_user)):
|
||||||
|
with _errors():
|
||||||
|
return _store(request).detail(asset_id)
|
||||||
|
|
||||||
|
|
||||||
|
@router.put("/api/assets/{asset_id}")
|
||||||
|
def update(request: Request, asset_id: str, payload: AssetUpdate, user=Depends(_write)):
|
||||||
|
with _errors():
|
||||||
|
_store(request).update(asset_id, payload, user["email"])
|
||||||
|
return {"ok": True}
|
||||||
|
|
||||||
|
|
||||||
|
@router.delete("/api/assets/{asset_id}")
|
||||||
|
def delete(request: Request, asset_id: str, payload: DeleteInput, user=Depends(_super_write)):
|
||||||
|
with _errors():
|
||||||
|
_store(request).delete(asset_id, payload.version, user["email"], payload.note)
|
||||||
|
return {"ok": True}
|
||||||
|
|
||||||
|
|
||||||
|
@router.post("/api/assets/{asset_id}/photos")
|
||||||
|
async def add_photo(request: Request, asset_id: str, file: Annotated[UploadFile, File()],
|
||||||
|
version: Annotated[int, Form(ge=1)], user=Depends(_write)):
|
||||||
|
filename = (file.filename or "photo.jpg").replace("\\", "/").rsplit("/", 1)[-1]
|
||||||
|
try:
|
||||||
|
if len(filename) > 200 or any(ord(c) < 32 for c in filename):
|
||||||
|
raise HTTPException(422, "사진 파일 이름을 확인하세요.")
|
||||||
|
raw = await file.read(MAX_PHOTO_BYTES + 1)
|
||||||
|
finally:
|
||||||
|
await file.close()
|
||||||
|
with _errors():
|
||||||
|
image, mime, width, height = await run_in_threadpool(prepare_photo, raw)
|
||||||
|
photo_id = await run_in_threadpool(_store(request).add_photo, asset_id, version, user["email"], filename, image, mime, width, height)
|
||||||
|
return {"id": photo_id}
|
||||||
|
|
||||||
|
|
||||||
|
@router.get("/api/assets/{asset_id}/photos/{photo_id}")
|
||||||
|
def photo(request: Request, asset_id: str, photo_id: str, user=Depends(_user)):
|
||||||
|
with _errors():
|
||||||
|
row = _store(request).photo(asset_id, photo_id)
|
||||||
|
return Response(bytes(row["image"]), media_type=row["mime"],
|
||||||
|
headers={"X-Content-Type-Options": "nosniff", "Cache-Control": "no-store"})
|
||||||
|
|
||||||
|
|
||||||
|
@router.get("/api/assets/{asset_id}/reports/{report_id}/monitors")
|
||||||
|
def report_monitors(request: Request, asset_id: str, report_id: str, user=Depends(_user)):
|
||||||
|
with _errors():
|
||||||
|
return {"items": _store(request).report_monitors(asset_id, report_id)}
|
||||||
|
|
||||||
|
|
||||||
|
@router.post("/api/assets/{asset_id}/monitors/{index}")
|
||||||
|
def register_monitor(request: Request, asset_id: str, index: int, payload: MonitorInput, user=Depends(_write)):
|
||||||
|
with _errors():
|
||||||
|
monitor_id = _store(request).register_monitor(asset_id, index, payload, user["email"])
|
||||||
|
return {"id": monitor_id}
|
||||||
|
|
||||||
|
|
||||||
|
@router.post("/api/assets/{asset_id}/actions")
|
||||||
|
def action(request: Request, asset_id: str, payload: ActionInput, user=Depends(_write)):
|
||||||
|
from app.main import user_store
|
||||||
|
if payload.action == "checkout" and not user_store.get(payload.assignee_email.lower()):
|
||||||
|
raise HTTPException(422, "등록된 회사 사용자를 선택하세요.")
|
||||||
|
with _errors():
|
||||||
|
_store(request).action(asset_id, payload, user["email"])
|
||||||
|
return {"ok": True}
|
||||||
|
|
||||||
|
|
||||||
|
async def _report_file(file):
|
||||||
|
filename = (file.filename or "report.xml").replace("\\", "/").rsplit("/", 1)[-1]
|
||||||
|
if not filename.lower().endswith(".xml") or len(filename) > 200 or any(ord(c) < 32 for c in filename):
|
||||||
|
raise HTTPException(422, "이름이 200자 이하인 XML 보고서를 선택하세요.")
|
||||||
|
try:
|
||||||
|
raw = await file.read(MAX_REPORT_BYTES + 1)
|
||||||
|
finally:
|
||||||
|
await file.close()
|
||||||
|
with _errors():
|
||||||
|
parsed = await run_in_threadpool(parse_hwinfo, raw)
|
||||||
|
return filename, raw, parsed
|
||||||
|
|
||||||
|
|
||||||
|
@router.post("/api/reports/preview")
|
||||||
|
async def preview(file: Annotated[UploadFile, File()], user=Depends(_write)):
|
||||||
|
filename, raw, parsed = await _report_file(file)
|
||||||
|
return {"filename": filename, "summary": parsed["summary"], "scan_time": parsed["scan_time"],
|
||||||
|
"property_count": parsed["property_count"], "warnings": parsed["warnings"]}
|
||||||
|
|
||||||
|
|
||||||
|
@router.post("/api/reports/import")
|
||||||
|
async def import_report(request: Request, file: Annotated[UploadFile, File()], payload: Annotated[str, Form(max_length=20000)], user=Depends(_write)):
|
||||||
|
with _errors():
|
||||||
|
try:
|
||||||
|
data = AssetInput.model_validate_json(payload)
|
||||||
|
except ValidationError as exc:
|
||||||
|
raise HTTPException(422, "자산명·분류·구매일·금액을 확인하세요.") from exc
|
||||||
|
report = await _report_file(file)
|
||||||
|
with _errors():
|
||||||
|
asset_id = await run_in_threadpool(_store(request).create, data, user["email"], report)
|
||||||
|
return {"id": asset_id}
|
||||||
|
|
||||||
|
|
||||||
|
@router.post("/api/assets/{asset_id}/reports")
|
||||||
|
async def attach(request: Request, asset_id: str, file: Annotated[UploadFile, File()],
|
||||||
|
version: Annotated[int, Form(ge=1)], user=Depends(_write)):
|
||||||
|
filename, raw, parsed = await _report_file(file)
|
||||||
|
with _errors():
|
||||||
|
report_id = await run_in_threadpool(_store(request).attach_report, asset_id, version, user["email"], filename, raw, parsed)
|
||||||
|
return {"id": report_id}
|
||||||
|
|
||||||
|
|
||||||
|
@router.get("/api/assets/{asset_id}/reports/{report_id}")
|
||||||
|
def report_detail(request: Request, asset_id: str, report_id: str, user=Depends(_user)):
|
||||||
|
with _errors():
|
||||||
|
return _store(request).report(asset_id, report_id)
|
||||||
|
|
||||||
|
|
||||||
|
@router.get("/api/assets/{asset_id}/reports/{report_id}/download")
|
||||||
|
def download(request: Request, asset_id: str, report_id: str, user=Depends(_user)):
|
||||||
|
with _errors():
|
||||||
|
row = _store(request).report(asset_id, report_id, raw=True)
|
||||||
|
return Response(bytes(row["raw_xml"]), media_type="application/octet-stream",
|
||||||
|
headers={"Content-Disposition": f"attachment; filename=hwinfo.xml; filename*=UTF-8''{quote(row['filename'], safe='')}",
|
||||||
|
"X-Content-Type-Options": "nosniff", "Cache-Control": "no-store"})
|
||||||
@@ -0,0 +1,106 @@
|
|||||||
|
"""Asset validation and lifecycle rules, shared by API and storage."""
|
||||||
|
from datetime import date
|
||||||
|
from decimal import Decimal
|
||||||
|
|
||||||
|
from pydantic import BaseModel, ConfigDict, Field, field_validator, model_validator
|
||||||
|
|
||||||
|
CATEGORIES = {"computer": "컴퓨터", "monitor": "모니터", "mouse": "마우스", "keyboard": "키보드",
|
||||||
|
"camera": "카메라", "hub": "허브 · 네트워크", "lighting": "조명", "desk": "책상",
|
||||||
|
"chair": "의자", "furniture": "기타 사무집기", "equipment": "기타 전산장비"}
|
||||||
|
STATUSES = {"available": "사용 가능", "in_use": "사용 중", "maintenance": "수리 중", "lost": "분실", "retired": "폐기"}
|
||||||
|
|
||||||
|
|
||||||
|
class AssetInput(BaseModel):
|
||||||
|
model_config = ConfigDict(extra="forbid", str_strip_whitespace=True)
|
||||||
|
tag: str = Field(default="", max_length=64)
|
||||||
|
name: str = Field(min_length=1, max_length=200)
|
||||||
|
category: str
|
||||||
|
manufacturer: str = Field(default="", max_length=150)
|
||||||
|
model: str = Field(default="", max_length=200)
|
||||||
|
serial: str = Field(default="", max_length=200)
|
||||||
|
location: str = Field(default="", max_length=150)
|
||||||
|
department: str = Field(default="", max_length=100)
|
||||||
|
purchased_on: date | None = None
|
||||||
|
purchase_cost: Decimal | None = Field(default=None, ge=0, le=10**12, decimal_places=2)
|
||||||
|
vendor: str = Field(default="", max_length=200)
|
||||||
|
warranty_until: date | None = None
|
||||||
|
notes: str = Field(default="", max_length=10000)
|
||||||
|
|
||||||
|
@field_validator("category")
|
||||||
|
@classmethod
|
||||||
|
def valid_category(cls, value):
|
||||||
|
if value not in CATEGORIES:
|
||||||
|
raise ValueError("자산 분류가 올바르지 않습니다.")
|
||||||
|
return value
|
||||||
|
|
||||||
|
@model_validator(mode="after")
|
||||||
|
def valid_dates(self):
|
||||||
|
if self.purchased_on and self.warranty_until and self.warranty_until < self.purchased_on:
|
||||||
|
raise ValueError("보증 종료일은 구매일 이후여야 합니다.")
|
||||||
|
return self
|
||||||
|
|
||||||
|
|
||||||
|
class AssetUpdate(AssetInput):
|
||||||
|
version: int = Field(ge=1)
|
||||||
|
|
||||||
|
|
||||||
|
class DeleteInput(BaseModel):
|
||||||
|
model_config = ConfigDict(extra="forbid", str_strip_whitespace=True)
|
||||||
|
version: int = Field(ge=1)
|
||||||
|
note: str = Field(min_length=1, max_length=2000)
|
||||||
|
|
||||||
|
|
||||||
|
class MonitorInput(BaseModel):
|
||||||
|
model_config = ConfigDict(extra="forbid", str_strip_whitespace=True)
|
||||||
|
version: int = Field(ge=1)
|
||||||
|
report_id: str = Field(min_length=1, max_length=64)
|
||||||
|
asset: AssetInput | None = None
|
||||||
|
asset_id: str = Field(default="", max_length=64)
|
||||||
|
|
||||||
|
@model_validator(mode="after")
|
||||||
|
def require_target(self):
|
||||||
|
if bool(self.asset) == bool(self.asset_id):
|
||||||
|
raise ValueError("등록할 정보 또는 연결할 모니터 자산 중 하나를 지정하세요.")
|
||||||
|
if self.asset and self.asset.category != "monitor":
|
||||||
|
raise ValueError("모니터 분류로 등록하세요.")
|
||||||
|
return self
|
||||||
|
|
||||||
|
|
||||||
|
class ActionInput(BaseModel):
|
||||||
|
model_config = ConfigDict(extra="forbid", str_strip_whitespace=True)
|
||||||
|
version: int = Field(ge=1)
|
||||||
|
action: str
|
||||||
|
assignee_email: str = Field(default="", max_length=254)
|
||||||
|
location: str = Field(default="", max_length=150)
|
||||||
|
note: str = Field(default="", max_length=2000)
|
||||||
|
|
||||||
|
@model_validator(mode="after")
|
||||||
|
def require_reason(self):
|
||||||
|
if self.action in {"lost", "retired"} and not self.note:
|
||||||
|
raise ValueError("분실·폐기 사유를 입력하세요.")
|
||||||
|
return self
|
||||||
|
|
||||||
|
|
||||||
|
class AssetConflict(ValueError):
|
||||||
|
pass
|
||||||
|
|
||||||
|
|
||||||
|
def transition(asset, payload: ActionInput):
|
||||||
|
state = asset["status"]
|
||||||
|
if payload.action == "checkout":
|
||||||
|
if state != "available" or not payload.assignee_email:
|
||||||
|
raise ValueError("사용 가능한 자산을 선택하고 배정할 사용자를 지정하세요.")
|
||||||
|
return "in_use", payload.assignee_email.lower()
|
||||||
|
if payload.action == "checkin":
|
||||||
|
if state != "in_use":
|
||||||
|
raise ValueError("사용 중인 자산만 반납할 수 있습니다.")
|
||||||
|
return "available", ""
|
||||||
|
if payload.action == "maintenance" and state == "available":
|
||||||
|
return "maintenance", ""
|
||||||
|
if payload.action == "available" and state in {"maintenance", "lost", "retired"}:
|
||||||
|
return "available", ""
|
||||||
|
if payload.action == "lost" and state in {"available", "in_use", "maintenance"}:
|
||||||
|
return "lost", asset.get("assignee_email", "")
|
||||||
|
if payload.action == "retired" and state in {"available", "maintenance", "lost"}:
|
||||||
|
return "retired", ""
|
||||||
|
raise ValueError("현재 상태에서 처리할 수 없습니다. 배정된 자산은 먼저 반납하세요.")
|
||||||
@@ -0,0 +1,70 @@
|
|||||||
|
{% extends "erp_base.html" %}
|
||||||
|
{% set force_sidebar_collapsed = true %}
|
||||||
|
{% block head_extra %}<link rel="stylesheet" href="/static/asset.css?v=20261006c">{% endblock %}
|
||||||
|
{% block content %}
|
||||||
|
<div id="asset-app" class="am-workspace" data-csrf="{{ csrf_token }}" data-configured="{{ 'true' if configured else 'false' }}" data-can-delete="{{ 'true' if can_delete else 'false' }}">
|
||||||
|
<aside class="am-nav" aria-label="자산관리 탐색">
|
||||||
|
<div class="am-nav-brand"><span class="am-mark">A</span><div><strong>회사 자산</strong><small>ASSET MANAGEMENT</small></div></div>
|
||||||
|
<button class="am-nav-link is-active" data-view="all"><span>전체 자산</span><span id="am-nav-total" class="am-count">—</span></button>
|
||||||
|
<button class="am-nav-link" data-view="computer"><span>컴퓨터 · 전산장비</span></button>
|
||||||
|
<button class="am-nav-link" data-view="furniture"><span>사무실 · 집기</span></button>
|
||||||
|
<p class="am-nav-label">자산 상태</p>
|
||||||
|
{% for key,label in statuses.items() %}<button class="am-nav-link" data-state="{{ key }}"><span><i class="am-dot am-dot-{{ key }}"></i>{{ label }}</span><span class="am-count" id="am-count-{{ key }}">—</span></button>{% endfor %}
|
||||||
|
<p class="am-nav-label">확인할 항목</p>
|
||||||
|
<button class="am-nav-link" data-view="warranty"><span>보증 만료 예정</span><span class="am-count" id="am-count-warranty">—</span></button>
|
||||||
|
<div class="am-nav-foot"><strong>자산 한 개, 기록 하나</strong><p>개별 자산번호로 등록하고<br>배정부터 폐기까지 추적하세요.</p><button class="am-text-btn" id="am-help-open">사용 안내 ↗</button></div>
|
||||||
|
</aside>
|
||||||
|
<section class="am-main" aria-label="자산대장">
|
||||||
|
<div class="am-heading"><div><p class="am-eyebrow">COMPANY INVENTORY</p><h2>회사 자산 대장</h2><p>어떤 자산이, 어디에, 누구에게 있는지 확인하세요.</p></div><div class="am-heading-actions"><button class="erp-btn erp-btn-outline" id="am-import">↑ HWiNFO 보고서</button><button class="erp-btn erp-btn-primary" id="am-create" {% if not configured %}disabled{% endif %}>+ 자산 등록</button></div></div>
|
||||||
|
{% if not configured %}<div class="am-notice" role="status"><strong>자산관리 저장소 설정이 필요합니다.</strong><p>관리자가 자산관리 DB를 연결하면 등록·배정·반납을 사용할 수 있습니다. HWiNFO 보고서는 지금도 분석 결과를 미리 볼 수 있습니다.</p></div>{% endif %}
|
||||||
|
<div id="am-message" class="am-message" role="status" aria-live="polite" hidden></div>
|
||||||
|
<div class="am-kpis" aria-label="자산 현황">
|
||||||
|
<button data-kpi="all" class="am-kpi"><span>전체 자산</span><strong id="am-total">—</strong><small>회사에 등록된 자산</small></button>
|
||||||
|
<button data-kpi="in_use" class="am-kpi"><span><i class="am-dot am-dot-in_use"></i>사용 중</span><strong id="am-in_use">—</strong><small>직원에게 배정된 자산</small></button>
|
||||||
|
<button data-kpi="available" class="am-kpi"><span><i class="am-dot am-dot-available"></i>사용 가능</span><strong id="am-available">—</strong><small>새로 배정할 수 있는 자산</small></button>
|
||||||
|
<button data-kpi="maintenance" class="am-kpi"><span><i class="am-dot am-dot-maintenance"></i>수리 중</span><strong id="am-maintenance">—</strong><small>점검 · 수리 중인 자산</small></button>
|
||||||
|
<button data-kpi="warranty" class="am-kpi"><span>보증 만료 예정</span><strong id="am-warranty_soon">—</strong><small>오늘부터 30일 이내</small></button>
|
||||||
|
</div>
|
||||||
|
<div class="am-register">
|
||||||
|
<div class="am-register-head"><div><h3 id="am-list-title">전체 자산</h3><span id="am-result-count">자산을 불러오는 중</span></div><div><button class="am-text-btn" id="am-refresh" aria-label="자산 새로고침">↻ 새로고침</button><button class="erp-btn erp-btn-outline" id="am-export" {% if not configured %}disabled{% endif %}>엑셀 내보내기 ↓</button></div></div>
|
||||||
|
<form class="am-filters" id="am-filters" role="search">
|
||||||
|
<label class="am-search"><span aria-hidden="true">⌕</span><input id="am-query" type="search" maxlength="200" placeholder="자산명, 번호, 모델, 시리얼 검색" aria-label="자산 검색"></label>
|
||||||
|
<select id="am-category" aria-label="분류"><option value="">모든 분류</option>{% for key,label in categories.items() %}<option value="{{ key }}">{{ label }}</option>{% endfor %}</select>
|
||||||
|
<select id="am-status" aria-label="상태"><option value="">모든 상태</option>{% for key,label in statuses.items() %}<option value="{{ key }}">{{ label }}</option>{% endfor %}</select>
|
||||||
|
<select id="am-location" aria-label="위치"><option value="">모든 위치</option></select>
|
||||||
|
<select id="am-assignee" aria-label="배정 사용자"><option value="">모든 사용자</option></select>
|
||||||
|
<select id="am-sort" aria-label="정렬"><option value="updated">최근 변경순</option><option value="name">자산명순</option><option value="tag">자산번호순</option><option value="cost">구매금액순</option><option value="warranty">보증종료순</option></select>
|
||||||
|
<button type="button" class="am-text-btn" id="am-reset">초기화</button>
|
||||||
|
</form>
|
||||||
|
<div class="am-table-scroll"><table class="am-table"><thead><tr><th>자산</th><th>분류</th><th>상태</th><th>사용자 / 위치</th><th>구매금액</th><th>보증 종료</th><th>사양</th></tr></thead><tbody id="am-rows"><tr><td colspan="7" class="am-empty">{% if configured %}자산을 불러오는 중입니다.{% else %}등록된 자산이 여기에 표시됩니다.{% endif %}</td></tr></tbody></table></div>
|
||||||
|
<div class="am-pagination"><span id="am-page-info">—</span><div><button class="erp-btn erp-btn-outline" id="am-prev" disabled>← 이전</button><span id="am-page-number">1</span><button class="erp-btn erp-btn-outline" id="am-next" disabled>다음 →</button></div></div>
|
||||||
|
</div>
|
||||||
|
<div class="am-bottom"><section class="am-panel"><div class="am-panel-head"><h3>자산 구성</h3><span>분류별 등록 수</span></div><div id="am-breakdown" class="am-breakdown"><p class="am-muted">등록된 자산이 없습니다.</p></div><div class="am-value"><span>보유 자산 구매금액 <small>폐기 제외 · 입력된 금액 기준</small></span><strong id="am-value">—</strong></div></section><section class="am-panel"><div class="am-panel-head"><h3>최근 활동</h3><span>등록 · 배정 · 반납 · 변경</span></div><div id="am-activity" class="am-activity"><p class="am-muted">활동 이력이 여기에 표시됩니다.</p></div></section></div>
|
||||||
|
</section>
|
||||||
|
</div>
|
||||||
|
<dialog id="am-detail" class="am-drawer" aria-labelledby="am-detail-title"><div class="am-dialog-head"><div><small id="am-detail-tag">자산 상세</small><h2 id="am-detail-title">자산 정보</h2></div><button type="button" class="am-close" data-close="am-detail" aria-label="자산 상세 닫기">×</button></div><div id="am-detail-content"></div></dialog>
|
||||||
|
<dialog id="am-editor" class="am-dialog" aria-labelledby="am-editor-title"><div class="am-dialog-head"><div><small>ASSET REGISTER</small><h2 id="am-editor-title">자산 등록</h2></div><button type="button" class="am-close" data-close="am-editor" aria-label="등록 창 닫기">×</button></div><form id="am-editor-form" class="am-form"><div class="am-form-grid">
|
||||||
|
<label>자산명 <span>*</span><input name="name" maxlength="200" required placeholder="예: 디자인팀 데스크톱"></label>
|
||||||
|
<label>자산번호<input name="tag" maxlength="64" placeholder="비워두면 자동 발급 (AST-000001)"></label>
|
||||||
|
<label>분류 <span>*</span><select name="category" required>{% for key,label in categories.items() %}<option value="{{ key }}">{{ label }}</option>{% endfor %}</select></label>
|
||||||
|
<label>제조사<input name="manufacturer" maxlength="150" placeholder="예: Dell, 시디즈"></label>
|
||||||
|
<label>모델<input name="model" maxlength="200"></label><label>시리얼 번호<input name="serial" maxlength="200"></label>
|
||||||
|
<label>위치<input name="location" maxlength="150" list="am-locations" placeholder="예: 본사 3층 디자인팀"></label><label>부서<input name="department" maxlength="100"></label>
|
||||||
|
<label>구매일<input type="date" name="purchased_on"></label><label>구매금액 (원)<input type="number" name="purchase_cost" min="0" max="1000000000000" step="0.01" placeholder="미입력 가능"></label>
|
||||||
|
<label>구매처<input name="vendor" maxlength="200"></label><label>보증 종료일<input type="date" name="warranty_until"></label>
|
||||||
|
<label class="am-wide">메모<textarea name="notes" maxlength="10000" rows="3" placeholder="관리에 필요한 추가 정보를 입력하세요."></textarea></label>
|
||||||
|
</div><p class="am-form-hint">같은 모델도 자산번호를 각각 발급합니다. 사용자 배정은 등록 후 상세 화면에서 진행합니다.</p><div class="am-form-error" role="alert" hidden></div><div class="am-dialog-footer"><button type="button" class="erp-btn erp-btn-outline" data-close="am-editor">취소</button><button type="submit" class="erp-btn erp-btn-primary">자산 저장</button></div></form></dialog>
|
||||||
|
<dialog id="am-upload" class="am-dialog am-upload-dialog" aria-labelledby="am-upload-title"><div class="am-dialog-head"><div><small>HWiNFO XML IMPORT</small><h2 id="am-upload-title">컴퓨터 보고서 가져오기</h2></div><button type="button" class="am-close" data-close="am-upload" aria-label="업로드 창 닫기">×</button></div><form id="am-upload-form" class="am-form">
|
||||||
|
<p class="am-form-hint" id="am-upload-hint">HWiNFO에서 저장한 XML 보고서를 선택하세요. 사양을 분석한 뒤 자산으로 등록합니다.</p>
|
||||||
|
<label class="am-drop" id="am-drop"><span class="am-upload-icon">↑</span><strong>XML 보고서 선택</strong><span>파일을 여기에 놓거나 클릭하세요 · 최대 10 MB</span><input type="file" id="am-report-file" accept=".xml" aria-label="HWiNFO XML 보고서 선택" required></label>
|
||||||
|
<div id="am-report-preview" hidden></div>
|
||||||
|
<div id="am-import-fields" class="am-form-grid" hidden><label>자산명 <span>*</span><input id="am-import-name" maxlength="200" required></label><label>위치<input id="am-import-location" maxlength="150" list="am-locations" placeholder="예: 본사 3층"></label></div>
|
||||||
|
<div class="am-form-error" role="alert" hidden></div><div class="am-dialog-footer"><span id="am-upload-status" class="am-muted"></span><button type="button" class="erp-btn erp-btn-outline" data-close="am-upload">취소</button><button type="submit" class="erp-btn erp-btn-primary" id="am-import-save" disabled>자산으로 등록</button></div>
|
||||||
|
</form></dialog>
|
||||||
|
<dialog id="am-action" class="am-dialog am-action-dialog" aria-labelledby="am-action-title"><div class="am-dialog-head"><div><small id="am-action-tag"></small><h2 id="am-action-title">자산 배정</h2></div><button type="button" class="am-close" data-close="am-action" aria-label="처리 창 닫기">×</button></div><form id="am-action-form" class="am-form"><p id="am-action-hint" class="am-form-hint"></p><label id="am-action-user-label">배정할 사용자 <span>*</span><select id="am-action-user"><option value="">사용자 선택</option></select></label><label>자산 위치<input id="am-action-location" list="am-locations" maxlength="150"></label><label>처리 메모<textarea id="am-action-note" maxlength="2000" rows="3" placeholder="배정 사유, 반납 상태, 수리 내용 등을 기록하세요."></textarea></label><div class="am-form-error" role="alert" hidden></div><div class="am-dialog-footer"><button type="button" class="erp-btn erp-btn-outline" data-close="am-action">취소</button><button type="submit" class="erp-btn erp-btn-primary" id="am-action-save">처리하기</button></div></form></dialog>
|
||||||
|
<dialog id="am-help" class="am-dialog" aria-labelledby="am-help-title"><div class="am-dialog-head"><h2 id="am-help-title">자산관리 사용 안내</h2><button class="am-close" data-close="am-help" aria-label="사용 안내 닫기">×</button></div><div class="am-form am-help"><h3>01. 자산 등록</h3><p>책상·의자·마우스 등은 개별 자산으로 등록합니다. 자산번호를 비워두면 자동 발급합니다. 컴퓨터는 HWiNFO 보고서를 가져오면 이름과 주요 사양을 확인하고 등록할 수 있습니다.</p><h3>02. 배정과 반납</h3><p>사용 가능한 자산을 등록된 회사 사용자에게 배정합니다. 사용 중인 자산은 반납 후 수리·폐기할 수 있습니다. 위치·사유와 처리자가 이력에 남습니다. 분실 처리 시 기존 배정 사용자도 기록됩니다.</p><h3>03. 컴퓨터 사양</h3><p>HWiNFO → 보고서 저장 → XML 형식을 선택합니다. 핵심 사양, 부품별 상세와 보고서 전체 항목을 볼 수 있습니다. 재업로드할 때 컴퓨터 이름을 확인하세요. 이전 보고서와 원본 XML은 보존됩니다.</p><h3>04. 찾기와 내보내기</h3><p>검색·분류·상태·위치·사용자 필터를 조합합니다. 엑셀 내보내기는 현재 필터에 해당하는 자산 전체를 포함하며 최대 10,000개입니다. 보증 만료 예정은 오늘부터 30일 이내입니다.</p><p class="am-form-hint">보고서에는 시리얼·MAC 주소 등 회사 장비 정보가 포함될 수 있습니다. 자산관리 권한을 가진 사용자만 조회할 수 있습니다.</p></div></dialog>
|
||||||
|
<datalist id="am-locations"></datalist>
|
||||||
|
<dialog id="am-photo" class="am-dialog" aria-labelledby="am-photo-title"><div class="am-dialog-head"><h2 id="am-photo-title">자산 사진 등록</h2><button type="button" class="am-close" data-close="am-photo" aria-label="사진 등록 닫기">×</button></div><form id="am-photo-form" class="am-form"><p class="am-form-hint">JPG · PNG · WebP, 파일당 8 MB 이하 · 자산당 최대 10장. 촬영 위치 정보는 제거해 보관합니다.</p><label>사진 선택<input id="am-photo-file" type="file" accept="image/jpeg,image/png,image/webp" required></label><div class="am-form-error" role="alert" hidden></div><div class="am-dialog-footer"><button type="button" class="erp-btn erp-btn-outline" data-close="am-photo">취소</button><button type="submit" class="erp-btn erp-btn-primary">사진 저장</button></div></form></dialog>
|
||||||
|
<dialog id="am-delete" class="am-dialog" aria-labelledby="am-delete-title"><div class="am-dialog-head"><h2 id="am-delete-title">자산 삭제</h2><button type="button" class="am-close" data-close="am-delete" aria-label="삭제 창 닫기">×</button></div><form id="am-delete-form" class="am-form"><p class="am-warning" id="am-delete-hint"></p><p class="am-form-hint">자산대장과 현황에서 제외됩니다. 사진·보고서·처리 이력은 보존됩니다.</p><label>삭제할 자산번호 확인<input id="am-delete-confirm" required autocomplete="off"></label><label>삭제 사유<textarea id="am-delete-note" required maxlength="2000" rows="3"></textarea></label><div class="am-form-error" role="alert" hidden></div><div class="am-dialog-footer"><button type="button" class="erp-btn erp-btn-outline" data-close="am-delete">취소</button><button type="submit" class="erp-btn am-danger">자산 삭제</button></div></form></dialog>
|
||||||
|
{% endblock %}
|
||||||
|
{% block scripts %}<script id="am-config" type="application/json">{{ {"categories":categories,"statuses":statuses}|tojson }}</script><script src="/static/asset.js?v=20261007a" defer></script>{% endblock %}
|
||||||
@@ -0,0 +1,47 @@
|
|||||||
|
# [카페24] 카페24 상품관리 모듈 — `app/modules/cafe24/`, `cafe24_db`
|
||||||
|
|
||||||
|
> 이 모듈만 고칠 때 읽는 요약. 상세는 `docs/CAFE24_MODULE.md`(큰 문서 — `grep -n '^#'` 로 목차 보고 필요한 절만 읽기).
|
||||||
|
> 정적 파일: `app/static/cafe24.css`, `cafe24-options.js`. 템플릿: `templates/`. 테스트: `tests/`.
|
||||||
|
> 공통 API 계층: `app/integrations/cafe24/` — **실적 모듈 카페24 어댑터도 같은 토큰을 씀**, 바꾸면 실적 영향 확인.
|
||||||
|
> 배포 시 이 모듈 변경이면 worker 도 같이 재빌드 — compose 서비스명 `cafe24-worker`(컨테이너명 `dbx-cafe24-worker` 아님): `docker compose up -d --build --no-deps web cafe24-worker`.
|
||||||
|
|
||||||
|
## 기능
|
||||||
|
|
||||||
|
- 카페24 관리자에 들어가지 않고 상품 상세페이지(description HTML) 조회·편집·즉시적용·예약적용·버전 이력.
|
||||||
|
- 3분할 화면(목록 | HTML 편집기 | 상품 정보 패널). 목록에 64x64 대표 이미지(`tiny_image`, 없으면 `detail_image`).
|
||||||
|
- HTML 편집기에서 `<img>` 태그에 마우스를 올리면 태그를 오렌지색으로 칠하고 화면 오른쪽에 폭 500px·창 높이로 파일명과 미리보기(상대 경로는 `CAFE24_SHOP_URL` 루트 기준, 색칠 한도 `HL_LIMIT` 초과 소스는 미동작).
|
||||||
|
- HTML 편집기에서 커서가 `<img>` 태그 안 어디에 있든 Ctrl+↑/↓ 로 `src` 파일명(`.jpg`/`.gif`/`.png`) 번호 변경. 없음 → `_2` → `_3` …, 이미 `_숫자` 면 다음 숫자부터. 내릴 때는 원래 번호(없었으면 원래 이름) 아래로 안 감 — 다른 편집이 끼거나 다른 이미지로 옮기면 그때 번호가 새 원래 번호.
|
||||||
|
- 정보 패널(`routes_product_info.py`, `_side.html`)에서 상품명·판매가·공급가·소비자가, 대표이미지, 옵션(생성/이름·썸네일·표시방식 수정/삭제)·품목(자체코드·추가금액·진열·판매) 수정.
|
||||||
|
품목 진열·판매는 `CAFE24_SHOP_NOS`(예 1,2,3)의 모든 멀티쇼핑몰에 같은 값으로 보냄(추가금액 등은 기본몰만).
|
||||||
|
- 대표이미지는 `POST /admin/products/{no}/images` 에 base64 data URI + `image_upload_type=A`.
|
||||||
|
NNEditor 업로드 경로를 PUT `detail_image` 에 넣는 방식은 적용 안 됨.
|
||||||
|
- 옵션/품목 팝업 「판매 가격」 열: 기본 정보 판매가 + 추가금액을 보여주고, 입력하면 추가금액을 역산(`cafe24-options.js` `bindSalePrice`). 저장되는 값은 추가금액뿐.
|
||||||
|
- 기본 정보에서 판매가를 바꾸면 같은 잠금 안에서 품목 추가금액을 (옛 판매가 − 새 판매가)만큼 옮겨 품목 판매 가격을 유지(`_keep_variant_sale_prices`, `store.shift_additional_amounts`). 공급가·소비자가는 품목과 무관. 판매가는 이미 반영됐으므로 품목 조정 실패는 화면 메시지(`variants_error`)로만.
|
||||||
|
- 옵션/품목 팝업 「재고관리」(use_inventory)·「재고」(quantity)·「품절표시」(display_soldout) 열: 같은 PUT variants 로 기본몰에만 보냄(재고는 쇼핑몰 공통).
|
||||||
|
- 옵션/품목 팝업 옵션값 이름·자체 품목코드·추가금액·판매 가격·재고 칸: Enter·↓ 아래 행, ↑ 위 행 같은 열로 이동(한글 조합 중에는 이동 안 함).
|
||||||
|
- 옵션/품목 팝업(단일 옵션 화면) 「모바일 스와이프 복사(코드)」: `// 상품명` + `"품목코드": "/web/…썸네일 경로",` 줄들을 클립보드로
|
||||||
|
(`cafe24-options.js` `swipeCode` — 행에 지금 보이는 썸네일 기준, 도메인/CDN 은 떼고 `/web/` 부터).
|
||||||
|
「모바일 스와이프 복사(이름)」은 키가 품목코드 대신 옵션값 이름(`swipeCode(tbody, true)`, 품목코드 있는 행만).
|
||||||
|
- 예약(편집기 아래 「예약 적용」): 대표 이미지(썸네일) · 상세페이지 · 진열 · 판매를 지정 시각에. 대표 이미지 파일은 `cafe24_schedule_images`(마이그레이션 006)에 보관, worker 가 이미지 먼저 교체.
|
||||||
|
- 권한키 `cafe24`(연결/해제는 admin 전용).
|
||||||
|
|
||||||
|
## 규칙
|
||||||
|
|
||||||
|
- **카페24 PUT options 는 옵션값 추가를 오류 없이 무시한다** — 기존 옵션에 행 추가는 「옵션 재생성」(DELETE → POST, 품목코드 새로 부여)으로만. 저장 버튼이 새 행을 보면 재생성 확인창으로 넘긴다.
|
||||||
|
|
||||||
|
- 카페24 OAuth/API 클라이언트는 향후 주문관리와 공유하기 위해 **공통 계층 `app/integrations/cafe24/`** 에 둔다 — 라우터에서 `httpx`/`requests` 직접 호출 금지.
|
||||||
|
- 토큰은 Fernet 암호화 저장(`CAFE24_TOKEN_SECRET`), 로그/화면에 토큰·시크릿 절대 미출력.
|
||||||
|
- 쓰기 직전 항상 카페24 현재 HTML 을 다시 읽어 `BACKUP` revision 생성(로컬 값을 현재값으로 가정 금지).
|
||||||
|
- 디자인 FTP(스와이프·상품상세) 쓰기는 임시 파일 → 검증 → rename. **카페24 FTP 는 허용 확장자만 받으므로 임시 이름도 원래 확장자로 끝나야 함**(`x_cf24tmp_<tag>.js`, `design_ftp.temp_names`). `x.js.cf24tmp-…` 는 `550 Operation not permitted`.
|
||||||
|
- 예약은 DB 저장 + 별도 worker(`worker.py`, compose 서비스 `cafe24-worker`, 컨테이너 `dbx-cafe24-worker`)가 처리 — 웹 프로세스에서 대기하지 않는다.
|
||||||
|
|
||||||
|
## 읽기 지연 ("마지막 쓰기가 권위")
|
||||||
|
|
||||||
|
- **카페24 관리자 API 는 PUT 뒤 한동안 GET 에서 예전 값을 돌려준다(읽기 지연)** — 우리 캐시 문제가 아니다.
|
||||||
|
- 상세설명: 카페24 값이 최근 revision 중 하나와 같으면 지연으로 보고 마지막 MANUAL/SCHEDULED 를 표시·지문 기준으로 씀(`store.resolve_description`).
|
||||||
|
- 스칼라(상품명·가격·이미지·진열/판매): PUT 응답 스냅샷(`cafe24_products.last_write_snapshot`, 마이그레이션 004)과 GET 의 `updated_date` 를 비교해 덮어씌움(`store.overlay_recent_write`).
|
||||||
|
- 진열/판매만 바꾼 PUT 은 `updated_date` 가 안 오를 수 있음 → **같은 시각 + 값 다름 = 지연**.
|
||||||
|
- 단건 GET 뿐 아니라 **목록·예약 미리보기도 보정** 필수(`store.overlay_product_rows`). 빠뜨리면 "진열/중지 바꿔도 반영 안 됨"으로 보임.
|
||||||
|
- 유예시간 `CAFE24_READ_LAG_GRACE_MIN`(기본 360분).
|
||||||
|
- 쓰기 후 화면은 PUT 응답으로 그리고 다시 GET 하지 않는다.
|
||||||
|
- API 문서 예제는 apidocs.cafe24.com 청크 JS 에서 추출(예전 `/docs/code` JSON 은 404).
|
||||||
@@ -42,6 +42,15 @@ def read_lag_grace_minutes() -> int:
|
|||||||
return store.parse_grace_minutes(os.getenv("CAFE24_READ_LAG_GRACE_MIN"))
|
return store.parse_grace_minutes(os.getenv("CAFE24_READ_LAG_GRACE_MIN"))
|
||||||
|
|
||||||
|
|
||||||
|
def shop_nos() -> list[int]:
|
||||||
|
"""품목 진열·판매를 함께 맞출 멀티쇼핑몰 번호. `CAFE24_SHOP_NOS`(예: 1,2,3), 기본 [1]."""
|
||||||
|
import os # noqa: WPS433
|
||||||
|
|
||||||
|
from . import store # noqa: WPS433
|
||||||
|
|
||||||
|
return store.parse_shop_nos(os.getenv("CAFE24_SHOP_NOS"))
|
||||||
|
|
||||||
|
|
||||||
def require_user(request: Request) -> dict[str, Any]:
|
def require_user(request: Request) -> dict[str, Any]:
|
||||||
from app.main import get_current_user_record # noqa: WPS433
|
from app.main import get_current_user_record # noqa: WPS433
|
||||||
from app.store import has_module # noqa: WPS433
|
from app.store import has_module # noqa: WPS433
|
||||||
@@ -96,11 +105,11 @@ def guard(request: Request):
|
|||||||
반환이 tuple 이면 (store, user), 아니면 그대로 응답으로 돌려준다.
|
반환이 tuple 이면 (store, user), 아니면 그대로 응답으로 돌려준다.
|
||||||
"""
|
"""
|
||||||
from app.main import get_current_user_record, render_template # noqa: WPS433
|
from app.main import get_current_user_record, render_template # noqa: WPS433
|
||||||
from app.store import has_module, is_admin # noqa: WPS433
|
from app.store import has_module, is_admin, login_redirect # noqa: WPS433
|
||||||
|
|
||||||
user = get_current_user_record(request)
|
user = get_current_user_record(request)
|
||||||
if user is None:
|
if user is None:
|
||||||
return RedirectResponse(url="/login", status_code=303)
|
return login_redirect(request)
|
||||||
if not has_module(user, MODULE_KEY):
|
if not has_module(user, MODULE_KEY):
|
||||||
return render_template(
|
return render_template(
|
||||||
request,
|
request,
|
||||||
|
|||||||
+547
-105
@@ -14,10 +14,12 @@ API 로그에는 토큰/시크릿을 넣지 않는다.
|
|||||||
from __future__ import annotations
|
from __future__ import annotations
|
||||||
|
|
||||||
import logging
|
import logging
|
||||||
|
import uuid
|
||||||
from contextlib import contextmanager
|
from contextlib import contextmanager
|
||||||
from datetime import date, datetime
|
from datetime import date, datetime
|
||||||
from typing import Any, Iterator
|
from typing import Any, Iterator
|
||||||
|
|
||||||
|
from psycopg import errors as pg_errors
|
||||||
from psycopg.rows import dict_row
|
from psycopg.rows import dict_row
|
||||||
from psycopg_pool import ConnectionPool
|
from psycopg_pool import ConnectionPool
|
||||||
|
|
||||||
@@ -97,6 +99,315 @@ class Cafe24Store:
|
|||||||
def close(self) -> None:
|
def close(self) -> None:
|
||||||
self._pool.close()
|
self._pool.close()
|
||||||
|
|
||||||
|
# ════════════════════════════════════════════════════════════
|
||||||
|
# 마이그레이션 005(쓰기 안전장치) 적용 여부
|
||||||
|
# 쓰기 경로는 잠금·시도 기록 없이 카페24에 쓰지 않는다 — 적용 전이면 거부한다.
|
||||||
|
# 읽기 경로는 005 가 없어도 동작하게 둔다(배포 순서가 어긋나도 화면은 열린다).
|
||||||
|
# ════════════════════════════════════════════════════════════
|
||||||
|
_schema_ok = False
|
||||||
|
|
||||||
|
def write_schema_ready(self) -> bool:
|
||||||
|
if self._schema_ok:
|
||||||
|
return True
|
||||||
|
with self._pool.connection() as conn:
|
||||||
|
row = conn.execute(
|
||||||
|
"""
|
||||||
|
SELECT to_regclass('public.cafe24_write_locks') IS NOT NULL
|
||||||
|
AND to_regclass('public.cafe24_write_attempts') IS NOT NULL
|
||||||
|
AND EXISTS (SELECT 1 FROM information_schema.columns
|
||||||
|
WHERE table_name = 'cafe24_product_schedules'
|
||||||
|
AND column_name = 'lease_token')
|
||||||
|
AND EXISTS (SELECT 1 FROM information_schema.columns
|
||||||
|
WHERE table_name = 'cafe24_product_revisions'
|
||||||
|
AND column_name = 'source') AS ok
|
||||||
|
"""
|
||||||
|
).fetchone()
|
||||||
|
self._schema_ok = bool(row and row.get("ok"))
|
||||||
|
return self._schema_ok
|
||||||
|
|
||||||
|
# ════════════════════════════════════════════════════════════
|
||||||
|
# 쓰기 잠금 (lease) — 웹 여러 프로세스 + 예약 worker 가 공유한다.
|
||||||
|
# 같은 lock_key 는 한 번에 하나만 잡는다. 만료(expires_at)가 지나면 다른 쪽이
|
||||||
|
# 가져갈 수 있다(잡은 프로세스가 죽어도 영구히 막히지 않는다). 원격 쓰기 직전
|
||||||
|
# renew_lock 으로 "아직 내 잠금인가"를 확인한다(펜싱) — 아니면 쓰지 않는다.
|
||||||
|
# ════════════════════════════════════════════════════════════
|
||||||
|
def acquire_lock(self, key: str, *, owner: str, purpose: str, ttl_seconds: int) -> str | None:
|
||||||
|
"""잠금을 잡으면 token, 남이 잡고 있으면 None."""
|
||||||
|
token = uuid.uuid4().hex
|
||||||
|
with self._pool.connection() as conn:
|
||||||
|
row = conn.execute(
|
||||||
|
"""
|
||||||
|
INSERT INTO cafe24_write_locks (lock_key, owner, token, purpose, acquired_at, expires_at)
|
||||||
|
VALUES (%s, %s, %s, %s, now(), now() + %s * interval '1 second')
|
||||||
|
ON CONFLICT (lock_key) DO UPDATE SET
|
||||||
|
owner = EXCLUDED.owner, token = EXCLUDED.token, purpose = EXCLUDED.purpose,
|
||||||
|
acquired_at = now(), expires_at = EXCLUDED.expires_at
|
||||||
|
WHERE cafe24_write_locks.expires_at < now()
|
||||||
|
RETURNING token
|
||||||
|
""",
|
||||||
|
(key, (owner or "")[:200], token, (purpose or "")[:200], max(1, int(ttl_seconds))),
|
||||||
|
).fetchone()
|
||||||
|
return str(row["token"]) if row else None
|
||||||
|
|
||||||
|
def renew_lock(self, key: str, token: str, *, ttl_seconds: int) -> bool:
|
||||||
|
"""아직 내 잠금이고 만료 전이면 연장하고 True. 이미 넘어갔으면 False."""
|
||||||
|
with self._pool.connection() as conn:
|
||||||
|
row = conn.execute(
|
||||||
|
"""
|
||||||
|
UPDATE cafe24_write_locks
|
||||||
|
SET expires_at = now() + %s * interval '1 second'
|
||||||
|
WHERE lock_key = %s AND token = %s AND expires_at > now()
|
||||||
|
RETURNING lock_key
|
||||||
|
""",
|
||||||
|
(max(1, int(ttl_seconds)), key, token),
|
||||||
|
).fetchone()
|
||||||
|
return row is not None
|
||||||
|
|
||||||
|
def release_lock(self, key: str, token: str) -> None:
|
||||||
|
with self._pool.connection() as conn:
|
||||||
|
conn.execute(
|
||||||
|
"DELETE FROM cafe24_write_locks WHERE lock_key = %s AND token = %s",
|
||||||
|
(key, token),
|
||||||
|
)
|
||||||
|
|
||||||
|
def lock_holder(self, key: str) -> dict[str, Any]:
|
||||||
|
"""지금 잠금을 잡고 있는 쪽(안내 문구용). 없거나 만료됐으면 {}."""
|
||||||
|
with self._pool.connection() as conn:
|
||||||
|
row = conn.execute(
|
||||||
|
"""
|
||||||
|
SELECT owner, purpose, acquired_at, expires_at FROM cafe24_write_locks
|
||||||
|
WHERE lock_key = %s AND expires_at > now()
|
||||||
|
""",
|
||||||
|
(key,),
|
||||||
|
).fetchone()
|
||||||
|
return self._serialize(row)
|
||||||
|
|
||||||
|
# ════════════════════════════════════════════════════════════
|
||||||
|
# 쓰기 시도 기록 (cafe24_write_attempts) — 운영용 가변 표.
|
||||||
|
# 원격 PUT 직전에 STARTED 로 남기고, 결과에 따라 상태를 바꾼다.
|
||||||
|
# ════════════════════════════════════════════════════════════
|
||||||
|
_ATTEMPT_FIELDS: tuple[str, ...] = (
|
||||||
|
"product_no", "mall_id", "shop_no", "origin", "schedule_id", "actor",
|
||||||
|
"backup_revision_id", "observed_digest", "base_digest", "target_digest",
|
||||||
|
"target_html", "target_revision_id", "set_display", "set_selling", "memo",
|
||||||
|
)
|
||||||
|
|
||||||
|
def start_attempt(self, **fields: Any) -> int:
|
||||||
|
cols = [k for k in self._ATTEMPT_FIELDS if k in fields]
|
||||||
|
values = [fields[k] for k in cols]
|
||||||
|
with self._pool.connection() as conn:
|
||||||
|
row = conn.execute(
|
||||||
|
f"""
|
||||||
|
INSERT INTO cafe24_write_attempts ({", ".join(cols)}, status)
|
||||||
|
VALUES ({", ".join(["%s"] * len(cols))}, %s)
|
||||||
|
RETURNING id
|
||||||
|
""",
|
||||||
|
(*values, store.ATTEMPT_STARTED),
|
||||||
|
).fetchone()
|
||||||
|
return int(row["id"]) if row else 0
|
||||||
|
|
||||||
|
def update_attempt(
|
||||||
|
self,
|
||||||
|
attempt_id: int,
|
||||||
|
*,
|
||||||
|
status: str | None = None,
|
||||||
|
error: str | None = None,
|
||||||
|
remote_updated_at: str | None = None,
|
||||||
|
remote_ok: bool = False,
|
||||||
|
resolved_by: str | None = None,
|
||||||
|
only_from: tuple[str, ...] | None = None,
|
||||||
|
) -> bool:
|
||||||
|
"""상태 전이. only_from 을 주면 그 상태에서만 바꾼다(늦게 도착한 갱신 무시)."""
|
||||||
|
sets: list[str] = []
|
||||||
|
args: list[Any] = []
|
||||||
|
if status is not None:
|
||||||
|
sets.append("status = %s")
|
||||||
|
args.append(status)
|
||||||
|
if error is not None:
|
||||||
|
sets.append("error = %s")
|
||||||
|
args.append((error or "")[:1000])
|
||||||
|
if remote_updated_at is not None:
|
||||||
|
sets.append("remote_updated_at = %s")
|
||||||
|
args.append(str(remote_updated_at or ""))
|
||||||
|
if remote_ok:
|
||||||
|
sets.append("remote_at = COALESCE(remote_at, now())")
|
||||||
|
if resolved_by is not None:
|
||||||
|
sets.append("resolved_by = %s")
|
||||||
|
args.append(resolved_by[:200])
|
||||||
|
if not sets:
|
||||||
|
return False
|
||||||
|
where = "id = %s"
|
||||||
|
args.append(int(attempt_id))
|
||||||
|
if only_from:
|
||||||
|
where += " AND status = ANY(%s)"
|
||||||
|
args.append(list(only_from))
|
||||||
|
with self._pool.connection() as conn:
|
||||||
|
row = conn.execute(
|
||||||
|
f"UPDATE cafe24_write_attempts SET {', '.join(sets)} WHERE {where} RETURNING id",
|
||||||
|
args,
|
||||||
|
).fetchone()
|
||||||
|
return row is not None
|
||||||
|
|
||||||
|
def record_attempt_revision(
|
||||||
|
self,
|
||||||
|
attempt_id: int,
|
||||||
|
*,
|
||||||
|
revision_type: str,
|
||||||
|
memo: str,
|
||||||
|
created_by: str,
|
||||||
|
source: str = "",
|
||||||
|
source_revision_id: int | None = None,
|
||||||
|
) -> int:
|
||||||
|
"""원격 반영된 시도의 버전(MANUAL/SCHEDULED/ROLLBACK)을 남기고 RECORDED 로 바꾼다.
|
||||||
|
|
||||||
|
한 트랜잭션에서 한다 — 시도 행을 잠그고, 이미 기록돼 있으면 그 버전 id 를 돌려준다
|
||||||
|
(기록 복구가 두 번 돌아도 버전이 둘 생기지 않는다). 내용은 시도에 보관한
|
||||||
|
target_html(없으면 target_revision_id 의 내용)이다. 기록 뒤 target_html 은 비운다.
|
||||||
|
"""
|
||||||
|
with self._pool.connection() as conn:
|
||||||
|
with conn.transaction():
|
||||||
|
att = conn.execute(
|
||||||
|
"""
|
||||||
|
SELECT a.*, COALESCE(NULLIF(a.target_html, ''), t.html_content, '') AS body
|
||||||
|
FROM cafe24_write_attempts a
|
||||||
|
LEFT JOIN cafe24_product_revisions t ON t.id = a.target_revision_id
|
||||||
|
WHERE a.id = %s
|
||||||
|
FOR UPDATE OF a
|
||||||
|
""",
|
||||||
|
(int(attempt_id),),
|
||||||
|
).fetchone()
|
||||||
|
if att is None:
|
||||||
|
return 0
|
||||||
|
if att.get("applied_revision_id"):
|
||||||
|
return int(att["applied_revision_id"])
|
||||||
|
row = conn.execute(
|
||||||
|
"""
|
||||||
|
INSERT INTO cafe24_product_revisions
|
||||||
|
(product_no, html_content, revision_type, memo, created_by,
|
||||||
|
mall_id, shop_no, source, source_revision_id)
|
||||||
|
VALUES (%s,%s,%s,%s,%s,%s,%s,%s,%s)
|
||||||
|
RETURNING id
|
||||||
|
""",
|
||||||
|
(
|
||||||
|
int(att["product_no"]), att["body"] or "",
|
||||||
|
store.normalize_revision_type(revision_type), (memo or "")[:500],
|
||||||
|
created_by or "", att.get("mall_id") or "", int(att.get("shop_no") or 1),
|
||||||
|
source or "", source_revision_id,
|
||||||
|
),
|
||||||
|
).fetchone()
|
||||||
|
revision_id = int(row["id"])
|
||||||
|
conn.execute(
|
||||||
|
"""
|
||||||
|
UPDATE cafe24_write_attempts
|
||||||
|
SET status = %s, applied_revision_id = %s, target_html = '',
|
||||||
|
remote_at = COALESCE(remote_at, now())
|
||||||
|
WHERE id = %s
|
||||||
|
""",
|
||||||
|
(store.ATTEMPT_RECORDED, revision_id, int(attempt_id)),
|
||||||
|
)
|
||||||
|
return revision_id
|
||||||
|
|
||||||
|
def get_attempt(self, attempt_id: int) -> dict[str, Any]:
|
||||||
|
with self._pool.connection() as conn:
|
||||||
|
row = conn.execute(
|
||||||
|
"SELECT * FROM cafe24_write_attempts WHERE id = %s", (int(attempt_id),)
|
||||||
|
).fetchone()
|
||||||
|
return self._serialize(row)
|
||||||
|
|
||||||
|
def latest_attempt_for_schedule(self, schedule_id: int) -> dict[str, Any]:
|
||||||
|
with self._pool.connection() as conn:
|
||||||
|
row = conn.execute(
|
||||||
|
"""
|
||||||
|
SELECT * FROM cafe24_write_attempts WHERE schedule_id = %s
|
||||||
|
ORDER BY created_at DESC, id DESC LIMIT 1
|
||||||
|
""",
|
||||||
|
(int(schedule_id),),
|
||||||
|
).fetchone()
|
||||||
|
return self._serialize(row)
|
||||||
|
|
||||||
|
def open_attempts(self, product_no: int, *, since: datetime) -> list[dict[str, Any]]:
|
||||||
|
"""결과 확정이 필요한 시도(STARTED/REMOTE_OK/UNKNOWN), 유예시간 안, 오래된 순.
|
||||||
|
|
||||||
|
005 적용 전이면 빈 목록(읽기 경로는 막지 않는다)."""
|
||||||
|
try:
|
||||||
|
with self._pool.connection() as conn:
|
||||||
|
rows = conn.execute(
|
||||||
|
"""
|
||||||
|
SELECT id, product_no, origin, schedule_id, actor, status, target_digest,
|
||||||
|
target_revision_id, backup_revision_id, set_display, set_selling,
|
||||||
|
error, created_at, remote_at, memo
|
||||||
|
FROM cafe24_write_attempts
|
||||||
|
WHERE product_no = %s AND status = ANY(%s) AND created_at >= %s
|
||||||
|
ORDER BY created_at ASC, id ASC
|
||||||
|
""",
|
||||||
|
(int(product_no), list(store.ATTEMPT_OPEN), since),
|
||||||
|
).fetchall()
|
||||||
|
except (pg_errors.UndefinedTable, pg_errors.UndefinedColumn):
|
||||||
|
return []
|
||||||
|
return [self._serialize(r) for r in rows]
|
||||||
|
|
||||||
|
def attempts_needing_record(self, *, since: datetime, limit: int = 20) -> list[dict[str, Any]]:
|
||||||
|
"""원격 반영됐는데 버전 기록이 안 된 시도(REMOTE_OK) — worker 가 기록을 채운다."""
|
||||||
|
with self._pool.connection() as conn:
|
||||||
|
rows = conn.execute(
|
||||||
|
"""
|
||||||
|
SELECT id, product_no, origin, schedule_id, actor, memo, target_revision_id, target_digest
|
||||||
|
FROM cafe24_write_attempts
|
||||||
|
WHERE status = %s AND created_at >= %s
|
||||||
|
ORDER BY created_at ASC, id ASC LIMIT %s
|
||||||
|
""",
|
||||||
|
(store.ATTEMPT_REMOTE_OK, since, max(1, int(limit))),
|
||||||
|
).fetchall()
|
||||||
|
return [self._serialize(r) for r in rows]
|
||||||
|
|
||||||
|
def write_lineage(self, product_no: int, *, since: datetime, limit: int = 30) -> list[dict[str, Any]]:
|
||||||
|
"""원격 반영이 **확인된** 상세설명 쓰기(REMOTE_OK/RECORDED), 최신 순.
|
||||||
|
|
||||||
|
읽기 지연 판정의 유일한 근거다. 충돌로 거절된 적용의 백업, 예약 초안, 실패·결과
|
||||||
|
모름 시도는 들어오지 않는다. 첫 행에만 html_content(마지막으로 쓴 HTML)를 채운다.
|
||||||
|
created_at 은 원격 반영 시각(remote_at)이다. 005 적용 전이면 빈 목록.
|
||||||
|
"""
|
||||||
|
try:
|
||||||
|
with self._pool.connection() as conn:
|
||||||
|
rows = conn.execute(
|
||||||
|
"""
|
||||||
|
SELECT id, origin, actor, status, schedule_id, observed_digest, base_digest,
|
||||||
|
target_digest, remote_updated_at, remote_at, applied_revision_id,
|
||||||
|
target_revision_id
|
||||||
|
FROM cafe24_write_attempts
|
||||||
|
WHERE product_no = %s AND status = ANY(%s) AND target_digest <> ''
|
||||||
|
AND remote_at >= %s
|
||||||
|
ORDER BY remote_at DESC, id DESC
|
||||||
|
LIMIT %s
|
||||||
|
""",
|
||||||
|
(int(product_no), list(store.ATTEMPT_CONFIRMED), since, max(1, int(limit))),
|
||||||
|
).fetchall()
|
||||||
|
if not rows:
|
||||||
|
return []
|
||||||
|
top = conn.execute(
|
||||||
|
"""
|
||||||
|
SELECT COALESCE(NULLIF(a.target_html, ''), r.html_content, t.html_content, '') AS body
|
||||||
|
FROM cafe24_write_attempts a
|
||||||
|
LEFT JOIN cafe24_product_revisions r ON r.id = a.applied_revision_id
|
||||||
|
LEFT JOIN cafe24_product_revisions t ON t.id = a.target_revision_id
|
||||||
|
WHERE a.id = %s
|
||||||
|
""",
|
||||||
|
(rows[0]["id"],),
|
||||||
|
).fetchone()
|
||||||
|
except (pg_errors.UndefinedTable, pg_errors.UndefinedColumn):
|
||||||
|
return []
|
||||||
|
out: list[dict[str, Any]] = []
|
||||||
|
for index, row in enumerate(rows):
|
||||||
|
item = dict(row)
|
||||||
|
at = item.get("remote_at")
|
||||||
|
if isinstance(at, datetime) and at.tzinfo is None:
|
||||||
|
at = at.replace(tzinfo=KST)
|
||||||
|
item["created_at"] = at
|
||||||
|
item["created_by"] = item.get("actor") or ""
|
||||||
|
item["html_content"] = (top or {}).get("body", "") if index == 0 else ""
|
||||||
|
out.append(item)
|
||||||
|
return out
|
||||||
|
|
||||||
# ════════════════════════════════════════════════════════════
|
# ════════════════════════════════════════════════════════════
|
||||||
# OAuth 토큰 — app/integrations/cafe24/tokens.py 가 요구하는 3개 메서드
|
# OAuth 토큰 — app/integrations/cafe24/tokens.py 가 요구하는 3개 메서드
|
||||||
# ════════════════════════════════════════════════════════════
|
# ════════════════════════════════════════════════════════════
|
||||||
@@ -281,31 +592,38 @@ class Cafe24Store:
|
|||||||
# 마이그레이션 004 의 두 컬럼(last_write_snapshot, last_written_at)을 쓴다.
|
# 마이그레이션 004 의 두 컬럼(last_write_snapshot, last_written_at)을 쓴다.
|
||||||
# 스냅샷 JSON 모양:
|
# 스냅샷 JSON 모양:
|
||||||
# {"product": {"data": {...store.SNAPSHOT_FIELDS...}, "written_at": ISO},
|
# {"product": {"data": {...store.SNAPSHOT_FIELDS...}, "written_at": ISO},
|
||||||
# "options": {"data": {...GET/PUT options 응답...}, "written_at": ISO},
|
# "options": {"data": {...GET/PUT options 응답..., "_before_signature", "_recent_values"},
|
||||||
# "variants": {"data": {variant_code: {...}}, "written_at": ISO}}
|
# "written_at": ISO},
|
||||||
|
# "variants": {"data": {variant_code: {필드..., "_at", "_deleted"?}}, "written_at": ISO}}
|
||||||
# 섹션별로 따로 갱신한다(가격만 바꿨는데 옵션 스냅샷이 사라지면 안 된다).
|
# 섹션별로 따로 갱신한다(가격만 바꿨는데 옵션 스냅샷이 사라지면 안 된다).
|
||||||
def save_write_snapshot(self, product_no: int, section: str, data: Any) -> None:
|
# 품목은 코드별·필드별로 병합한다(store.merge_variant_snapshot). 품목 전체 초기화
|
||||||
|
# (옵션 삭제·재생성)는 replace=True 로 명시한다 — {} 를 넘기는 것은 "변경 없음"이다.
|
||||||
|
def save_write_snapshot(self, product_no: int, section: str, data: Any, *, replace: bool = False) -> None:
|
||||||
from psycopg.types.json import Jsonb # noqa: WPS433
|
from psycopg.types.json import Jsonb # noqa: WPS433
|
||||||
|
|
||||||
no = int(product_no)
|
no = int(product_no)
|
||||||
if no <= 0 or section not in ("product", "options", "variants"):
|
if no <= 0 or section not in ("product", "options", "variants"):
|
||||||
return
|
return
|
||||||
|
now_iso = datetime.now(KST).isoformat(timespec="seconds")
|
||||||
with self._pool.connection() as conn:
|
with self._pool.connection() as conn:
|
||||||
with conn.transaction():
|
with conn.transaction():
|
||||||
|
# 행이 없으면 먼저 만든다 — FOR UPDATE 가 잠글 행이 있어야 동시 저장이
|
||||||
|
# 서로의 병합 결과를 덮지 않는다.
|
||||||
|
conn.execute(
|
||||||
|
"INSERT INTO cafe24_products (product_no) VALUES (%s) ON CONFLICT (product_no) DO NOTHING",
|
||||||
|
(no,),
|
||||||
|
)
|
||||||
row = conn.execute(
|
row = conn.execute(
|
||||||
"SELECT last_write_snapshot FROM cafe24_products WHERE product_no = %s FOR UPDATE",
|
"SELECT last_write_snapshot FROM cafe24_products WHERE product_no = %s FOR UPDATE",
|
||||||
(no,),
|
(no,),
|
||||||
).fetchone()
|
).fetchone()
|
||||||
current = dict(row["last_write_snapshot"]) if row and row.get("last_write_snapshot") else {}
|
current = dict(row["last_write_snapshot"]) if row and row.get("last_write_snapshot") else {}
|
||||||
if section == "variants" and isinstance(data, dict):
|
if section == "variants":
|
||||||
# 품목은 코드별로 누적 병합 — 일부만 바꿔도 이전에 바꾼 것을 잃지 않게.
|
previous = (current.get("variants") or {}).get("data") or {}
|
||||||
merged = dict((current.get("variants") or {}).get("data") or {})
|
data = store.merge_variant_snapshot(
|
||||||
merged.update(data)
|
previous, data if isinstance(data, dict) else {}, at=now_iso, replace=replace
|
||||||
data = merged
|
)
|
||||||
current[section] = {
|
current[section] = {"data": data, "written_at": now_iso}
|
||||||
"data": data,
|
|
||||||
"written_at": datetime.now(KST).isoformat(timespec="seconds"),
|
|
||||||
}
|
|
||||||
product = data if section == "product" and isinstance(data, dict) else {}
|
product = data if section == "product" and isinstance(data, dict) else {}
|
||||||
conn.execute(
|
conn.execute(
|
||||||
"""
|
"""
|
||||||
@@ -345,51 +663,35 @@ class Cafe24Store:
|
|||||||
return {}
|
return {}
|
||||||
return dict(row["last_write_snapshot"])
|
return dict(row["last_write_snapshot"])
|
||||||
|
|
||||||
# ── 읽기 지연 판정용 revision 조회 ──
|
def get_recent_product_snapshots(self, grace_minutes: int) -> dict[int, dict[str, Any]]:
|
||||||
def latest_write_revision(self, product_no: int, *, since: datetime) -> dict[str, Any] | None:
|
"""유예시간 안에 쓴 상품들의 product 스냅샷 섹션 {product_no: {"data", "written_at"}}.
|
||||||
"""유예시간 안의 가장 최근 '쓰기' revision(MANUAL/SCHEDULED/ROLLBACK) — HTML 포함."""
|
|
||||||
with self._pool.connection() as conn:
|
|
||||||
row = conn.execute(
|
|
||||||
"""
|
|
||||||
SELECT id, product_no, revision_type, html_content, memo, created_by, created_at
|
|
||||||
FROM cafe24_product_revisions
|
|
||||||
WHERE product_no = %s
|
|
||||||
AND revision_type = ANY(%s)
|
|
||||||
AND created_at >= %s
|
|
||||||
ORDER BY created_at DESC, id DESC
|
|
||||||
LIMIT 1
|
|
||||||
""",
|
|
||||||
(int(product_no), list(store.WRITE_REVISION_TYPES), since),
|
|
||||||
).fetchone()
|
|
||||||
if not row:
|
|
||||||
return None
|
|
||||||
out = dict(row)
|
|
||||||
at = out.get("created_at")
|
|
||||||
if isinstance(at, datetime) and at.tzinfo is None:
|
|
||||||
out["created_at"] = at.replace(tzinfo=KST)
|
|
||||||
return out
|
|
||||||
|
|
||||||
def revision_digests(self, product_no: int, *, since: datetime) -> set[str]:
|
목록 화면이 상품마다 따로 조회하지 않고 한 번에 지연 보정하기 위한 것이다.
|
||||||
"""유예시간 안의 revision 들의 내용 해시(store.content_digest 와 같은 md5 hex).
|
섹션별 written_at 판정은 store.overlay_recent_write 가 다시 한다.
|
||||||
|
|
||||||
내용을 통째로 옮기지 않고 DB 에서 해시만 계산한다(상세페이지는 수 MB 일 수 있다).
|
|
||||||
md5 를 쓰는 이유: 모든 PostgreSQL 버전에 있고, 여기서는 충돌 저항이 아니라
|
|
||||||
"같은 내용인가"만 필요하다.
|
|
||||||
"""
|
"""
|
||||||
with self._pool.connection() as conn:
|
with self._pool.connection() as conn:
|
||||||
rows = conn.execute(
|
rows = conn.execute(
|
||||||
"""
|
"""
|
||||||
SELECT md5(html_content) AS digest
|
SELECT product_no, last_write_snapshot -> 'product' AS product
|
||||||
FROM cafe24_product_revisions
|
FROM cafe24_products
|
||||||
WHERE product_no = %s AND created_at >= %s
|
WHERE last_written_at >= now() - make_interval(mins => %s)
|
||||||
|
AND last_write_snapshot ? 'product'
|
||||||
""",
|
""",
|
||||||
(int(product_no), since),
|
(max(0, int(grace_minutes)),),
|
||||||
).fetchall()
|
).fetchall()
|
||||||
return {str(r["digest"]) for r in rows if r.get("digest")}
|
return {
|
||||||
|
int(r["product_no"]): dict(r["product"])
|
||||||
|
for r in rows if isinstance(r.get("product"), dict)
|
||||||
|
}
|
||||||
|
|
||||||
# ════════════════════════════════════════════════════════════
|
# ════════════════════════════════════════════════════════════
|
||||||
# 상세페이지 HTML 버전 (append-only — UPDATE/DELETE 하지 않는다)
|
# 상세페이지 HTML 버전 (append-only — UPDATE/DELETE 하지 않는다)
|
||||||
# 쓰기 직전 BACKUP 을 남기는 것이 유일한 복구 수단이다.
|
# 쓰기 직전 BACKUP 을 남기는 것이 유일한 복구 수단이다.
|
||||||
|
# 읽기 지연 판정은 이 표가 아니라 cafe24_write_attempts(확인된 쓰기)를 본다 —
|
||||||
|
# 여기에는 충돌로 거절된 적용의 백업·예약 초안처럼 카페24에 올라간 적 없는 값도
|
||||||
|
# 들어 있기 때문이다(write_lineage 참고).
|
||||||
|
# 메타데이터(마이그레이션 005): mall_id·shop_no(복원 시 일치 검사), source
|
||||||
|
# (BACKUP 이 카페24 관측값인지, 지연 중이라 마지막 확인된 쓰기인지), source_revision_id.
|
||||||
# ════════════════════════════════════════════════════════════
|
# ════════════════════════════════════════════════════════════
|
||||||
def add_revision(
|
def add_revision(
|
||||||
self,
|
self,
|
||||||
@@ -399,13 +701,18 @@ class Cafe24Store:
|
|||||||
revision_type: str,
|
revision_type: str,
|
||||||
memo: str = "",
|
memo: str = "",
|
||||||
created_by: str = "",
|
created_by: str = "",
|
||||||
|
mall_id: str = "",
|
||||||
|
shop_no: int = 1,
|
||||||
|
source: str = "",
|
||||||
|
source_revision_id: int | None = None,
|
||||||
) -> int:
|
) -> int:
|
||||||
with self._pool.connection() as conn:
|
with self._pool.connection() as conn:
|
||||||
row = conn.execute(
|
row = conn.execute(
|
||||||
"""
|
"""
|
||||||
INSERT INTO cafe24_product_revisions
|
INSERT INTO cafe24_product_revisions
|
||||||
(product_no, html_content, revision_type, memo, created_by)
|
(product_no, html_content, revision_type, memo, created_by,
|
||||||
VALUES (%s,%s,%s,%s,%s)
|
mall_id, shop_no, source, source_revision_id)
|
||||||
|
VALUES (%s,%s,%s,%s,%s,%s,%s,%s,%s)
|
||||||
RETURNING id
|
RETURNING id
|
||||||
""",
|
""",
|
||||||
(
|
(
|
||||||
@@ -414,24 +721,33 @@ class Cafe24Store:
|
|||||||
store.normalize_revision_type(revision_type),
|
store.normalize_revision_type(revision_type),
|
||||||
(memo or "")[:500],
|
(memo or "")[:500],
|
||||||
created_by or "",
|
created_by or "",
|
||||||
|
mall_id or "",
|
||||||
|
int(shop_no or 1),
|
||||||
|
source or "",
|
||||||
|
source_revision_id,
|
||||||
),
|
),
|
||||||
).fetchone()
|
).fetchone()
|
||||||
return int(row["id"]) if row else 0
|
return int(row["id"]) if row else 0
|
||||||
|
|
||||||
def list_revisions(self, product_no: int, *, limit: int = 20) -> list[dict[str, Any]]:
|
def list_revisions(self, product_no: int, *, limit: int = 20) -> list[dict[str, Any]]:
|
||||||
"""버전 목록. html_content 는 수 MB 일 수 있어 길이만 계산해서 준다."""
|
"""버전 목록. html_content 는 수 MB 일 수 있어 길이만 계산해서 준다.
|
||||||
with self._pool.connection() as conn:
|
|
||||||
rows = conn.execute(
|
005 적용 전이면 출처(source) 없이 돌려준다(읽기 경로는 막지 않는다)."""
|
||||||
"""
|
sql = """
|
||||||
SELECT id, product_no, revision_type, memo, created_by, created_at,
|
SELECT id, product_no, revision_type, memo, created_by, created_at,
|
||||||
length(html_content) AS html_length
|
length(html_content) AS html_length{extra}
|
||||||
FROM cafe24_product_revisions
|
FROM cafe24_product_revisions
|
||||||
WHERE product_no = %s
|
WHERE product_no = %s
|
||||||
ORDER BY created_at DESC, id DESC
|
ORDER BY created_at DESC, id DESC
|
||||||
LIMIT %s
|
LIMIT %s
|
||||||
""",
|
"""
|
||||||
(int(product_no), max(1, min(int(limit), 200))),
|
args = (int(product_no), max(1, min(int(limit), 200)))
|
||||||
).fetchall()
|
try:
|
||||||
|
with self._pool.connection() as conn:
|
||||||
|
rows = conn.execute(sql.format(extra=", source, source_revision_id, mall_id"), args).fetchall()
|
||||||
|
except pg_errors.UndefinedColumn:
|
||||||
|
with self._pool.connection() as conn:
|
||||||
|
rows = conn.execute(sql.format(extra=""), args).fetchall()
|
||||||
return [self._serialize(r) for r in rows]
|
return [self._serialize(r) for r in rows]
|
||||||
|
|
||||||
def get_revision(self, revision_id: int) -> dict[str, Any]:
|
def get_revision(self, revision_id: int) -> dict[str, Any]:
|
||||||
@@ -503,27 +819,41 @@ class Cafe24Store:
|
|||||||
set_selling: bool | None,
|
set_selling: bool | None,
|
||||||
memo: str = "",
|
memo: str = "",
|
||||||
created_by: str = "",
|
created_by: str = "",
|
||||||
|
image: bytes | None = None,
|
||||||
|
image_type: str = "",
|
||||||
|
image_name: str = "",
|
||||||
) -> int:
|
) -> int:
|
||||||
|
"""예약 등록. image 가 있으면 파일을 cafe24_schedule_images 에 같은 트랜잭션으로 남긴다(006).
|
||||||
|
|
||||||
|
이미지 없는 예약은 006 컬럼을 쓰지 않는다 — 마이그레이션 전에도 기존 예약 등록이 깨지지 않게.
|
||||||
|
"""
|
||||||
|
cols = ["product_no", "scheduled_at", "revision_id", "set_display", "set_selling", "memo", "created_by"]
|
||||||
|
vals: list[Any] = [int(product_no), scheduled_at, revision_id, set_display, set_selling,
|
||||||
|
(memo or "")[:500], created_by or ""]
|
||||||
|
if image:
|
||||||
|
cols += ["image_type", "image_name"]
|
||||||
|
vals += [image_type, (image_name or "")[:200]]
|
||||||
|
with self._pool.connection() as conn:
|
||||||
|
with conn.transaction():
|
||||||
|
row = conn.execute(
|
||||||
|
f"INSERT INTO cafe24_product_schedules ({', '.join(cols)}) " # noqa: S608 — 고정 컬럼명만
|
||||||
|
f"VALUES ({', '.join(['%s'] * len(cols))}) RETURNING id",
|
||||||
|
vals,
|
||||||
|
).fetchone()
|
||||||
|
if row and image:
|
||||||
|
conn.execute(
|
||||||
|
"INSERT INTO cafe24_schedule_images (schedule_id, data) VALUES (%s, %s)",
|
||||||
|
(row["id"], image),
|
||||||
|
)
|
||||||
|
return int(row["id"]) if row else 0
|
||||||
|
|
||||||
|
def get_schedule_image(self, schedule_id: int) -> bytes:
|
||||||
|
"""예약 대표 이미지 파일. 없으면 b""."""
|
||||||
with self._pool.connection() as conn:
|
with self._pool.connection() as conn:
|
||||||
row = conn.execute(
|
row = conn.execute(
|
||||||
"""
|
"SELECT data FROM cafe24_schedule_images WHERE schedule_id = %s", (int(schedule_id),)
|
||||||
INSERT INTO cafe24_product_schedules
|
|
||||||
(product_no, scheduled_at, revision_id, set_display, set_selling,
|
|
||||||
memo, created_by)
|
|
||||||
VALUES (%s,%s,%s,%s,%s,%s,%s)
|
|
||||||
RETURNING id
|
|
||||||
""",
|
|
||||||
(
|
|
||||||
int(product_no),
|
|
||||||
scheduled_at,
|
|
||||||
revision_id,
|
|
||||||
set_display,
|
|
||||||
set_selling,
|
|
||||||
(memo or "")[:500],
|
|
||||||
created_by or "",
|
|
||||||
),
|
|
||||||
).fetchone()
|
).fetchone()
|
||||||
return int(row["id"]) if row else 0
|
return bytes(row["data"]) if row else b""
|
||||||
|
|
||||||
def list_schedules(self, *, limit: int = 200) -> list[dict[str, Any]]:
|
def list_schedules(self, *, limit: int = 200) -> list[dict[str, Any]]:
|
||||||
"""예약 목록. 대기 중인 것을 먼저, 그다음 최근 처리 순."""
|
"""예약 목록. 대기 중인 것을 먼저, 그다음 최근 처리 순."""
|
||||||
@@ -568,18 +898,24 @@ class Cafe24Store:
|
|||||||
)
|
)
|
||||||
return True
|
return True
|
||||||
|
|
||||||
@contextmanager
|
# ── 예약 실행 lease (마이그레이션 005) ──
|
||||||
def claim_due_schedule(self, *, now: datetime) -> Iterator[dict[str, Any] | None]:
|
# PROCESSING 은 lease_expires_at 까지만 유효하다. worker 가 죽으면 만료 후
|
||||||
"""실행할 예약 1건을 잡아 PROCESSING 으로 바꾼다(worker 전용).
|
# claim_expired_schedules 로 다른(또는 재기동한) worker 가 가져가 시도 기록을 보고
|
||||||
|
# 성공/재시도/확인 필요로 나눈다(worker.recover_expired). 모든 상태 변경은
|
||||||
|
# lease_token 이 맞을 때만 한다 — 만료 뒤 늦게 끝난 worker 가 결과를 덮지 않게.
|
||||||
|
def claim_due_schedule(self, *, now: datetime, owner: str, ttl_seconds: int) -> dict[str, Any] | None:
|
||||||
|
"""실행할 예약 1건을 잡아 PROCESSING + lease 로 바꾼다(worker 전용).
|
||||||
|
|
||||||
`FOR UPDATE SKIP LOCKED` 로 잠그므로 worker 가 여러 개 떠 있어도 같은 예약을
|
`FOR UPDATE SKIP LOCKED` 로 잠그므로 worker 가 여러 개 떠 있어도 같은 예약을
|
||||||
두 번 실행하지 않는다. 재시도 대기(next_retry_at)가 남아 있으면 건너뛴다.
|
두 번 잡지 않는다. 재시도 대기(next_retry_at)가 남아 있으면 건너뛴다.
|
||||||
|
반환 행의 lease_token 으로 renew/finish 한다.
|
||||||
"""
|
"""
|
||||||
|
token = uuid.uuid4().hex
|
||||||
with self._pool.connection() as conn:
|
with self._pool.connection() as conn:
|
||||||
with conn.transaction():
|
with conn.transaction():
|
||||||
row = conn.execute(
|
row = conn.execute(
|
||||||
"""
|
"""
|
||||||
SELECT * FROM cafe24_product_schedules
|
SELECT id FROM cafe24_product_schedules
|
||||||
WHERE status = 'PENDING'
|
WHERE status = 'PENDING'
|
||||||
AND scheduled_at <= %s
|
AND scheduled_at <= %s
|
||||||
AND (next_retry_at IS NULL OR next_retry_at <= %s)
|
AND (next_retry_at IS NULL OR next_retry_at <= %s)
|
||||||
@@ -589,48 +925,154 @@ class Cafe24Store:
|
|||||||
""",
|
""",
|
||||||
(now, now),
|
(now, now),
|
||||||
).fetchone()
|
).fetchone()
|
||||||
if row is not None:
|
if row is None:
|
||||||
conn.execute(
|
return None
|
||||||
"""
|
claimed = conn.execute(
|
||||||
UPDATE cafe24_product_schedules
|
"""
|
||||||
SET status = 'PROCESSING', started_at = now(), last_error = ''
|
UPDATE cafe24_product_schedules
|
||||||
WHERE id = %s
|
SET status = 'PROCESSING', started_at = now(), last_error = '',
|
||||||
""",
|
lease_owner = %s, lease_token = %s,
|
||||||
(row["id"],),
|
lease_expires_at = now() + %s * interval '1 second'
|
||||||
|
WHERE id = %s
|
||||||
|
RETURNING *
|
||||||
|
""",
|
||||||
|
((owner or "")[:200], token, max(1, int(ttl_seconds)), row["id"]),
|
||||||
|
).fetchone()
|
||||||
|
return dict(claimed) if claimed else None
|
||||||
|
|
||||||
|
def claim_expired_schedules(
|
||||||
|
self, *, owner: str, ttl_seconds: int, legacy_minutes: int, limit: int = 20
|
||||||
|
) -> list[dict[str, Any]]:
|
||||||
|
"""lease 가 만료된 PROCESSING 예약을 이 worker 에게 다시 lease 한다(복구 전용).
|
||||||
|
|
||||||
|
lease 컬럼이 비어 있는 옛 행(005 이전에 PROCESSING 이 된 것)은 started_at 이
|
||||||
|
legacy_minutes 보다 오래됐으면 만료로 본다.
|
||||||
|
"""
|
||||||
|
with self._pool.connection() as conn:
|
||||||
|
with conn.transaction():
|
||||||
|
rows = conn.execute(
|
||||||
|
"""
|
||||||
|
WITH picked AS (
|
||||||
|
SELECT id FROM cafe24_product_schedules
|
||||||
|
WHERE status = 'PROCESSING'
|
||||||
|
AND (lease_expires_at < now()
|
||||||
|
OR (lease_expires_at IS NULL
|
||||||
|
AND COALESCE(started_at, updated_at)
|
||||||
|
< now() - %s * interval '1 minute'))
|
||||||
|
ORDER BY id
|
||||||
|
LIMIT %s
|
||||||
|
FOR UPDATE SKIP LOCKED
|
||||||
)
|
)
|
||||||
yield dict(row) if row is not None else None
|
UPDATE cafe24_product_schedules s
|
||||||
|
SET lease_owner = %s,
|
||||||
|
lease_token = md5(random()::text || clock_timestamp()::text || s.id::text),
|
||||||
|
lease_expires_at = now() + %s * interval '1 second'
|
||||||
|
FROM picked
|
||||||
|
WHERE s.id = picked.id
|
||||||
|
RETURNING s.*
|
||||||
|
""",
|
||||||
|
(max(1, int(legacy_minutes)), max(1, int(limit)), (owner or "")[:200],
|
||||||
|
max(1, int(ttl_seconds))),
|
||||||
|
).fetchall()
|
||||||
|
return [dict(r) for r in rows]
|
||||||
|
|
||||||
|
def renew_schedule_lease(self, schedule_id: int, token: str, *, ttl_seconds: int) -> bool:
|
||||||
|
"""아직 내 lease 면 연장하고 True. 만료돼 넘어갔으면 False — 카페24에 쓰지 않는다."""
|
||||||
|
with self._pool.connection() as conn:
|
||||||
|
row = conn.execute(
|
||||||
|
"""
|
||||||
|
UPDATE cafe24_product_schedules
|
||||||
|
SET lease_expires_at = now() + %s * interval '1 second'
|
||||||
|
WHERE id = %s AND status = 'PROCESSING' AND lease_token = %s
|
||||||
|
AND lease_expires_at > now()
|
||||||
|
RETURNING id
|
||||||
|
""",
|
||||||
|
(max(1, int(ttl_seconds)), int(schedule_id), token),
|
||||||
|
).fetchone()
|
||||||
|
return row is not None
|
||||||
|
|
||||||
def finish_schedule(
|
def finish_schedule(
|
||||||
self,
|
self,
|
||||||
schedule_id: int,
|
schedule_id: int,
|
||||||
*,
|
*,
|
||||||
|
token: str,
|
||||||
status: str,
|
status: str,
|
||||||
error: str = "",
|
error: str = "",
|
||||||
next_retry_at: datetime | None = None,
|
next_retry_at: datetime | None = None,
|
||||||
retry_count: int | None = None,
|
retry_count: int | None = None,
|
||||||
) -> None:
|
) -> bool:
|
||||||
"""예약 종료 처리. 재시도로 되돌릴 때는 status='PENDING' + next_retry_at."""
|
"""예약 종료 처리(lease 가 내 것일 때만). 재시도로 되돌릴 때는 status='PENDING' + next_retry_at.
|
||||||
|
|
||||||
|
반환: 반영했으면 True. lease 를 잃었으면 False(다른 worker 가 복구 중 — 덮지 않는다).
|
||||||
|
"""
|
||||||
|
normalized = store.normalize_schedule_status(status)
|
||||||
with self._pool.connection() as conn:
|
with self._pool.connection() as conn:
|
||||||
conn.execute(
|
row = conn.execute(
|
||||||
"""
|
"""
|
||||||
UPDATE cafe24_product_schedules
|
UPDATE cafe24_product_schedules
|
||||||
SET status = %s,
|
SET status = %s,
|
||||||
last_error = %s,
|
last_error = %s,
|
||||||
next_retry_at = %s,
|
next_retry_at = %s,
|
||||||
retry_count = COALESCE(%s, retry_count),
|
retry_count = COALESCE(%s, retry_count),
|
||||||
|
lease_owner = '', lease_token = '', lease_expires_at = NULL,
|
||||||
completed_at = CASE WHEN %s IN ('SUCCESS','FAILED','CANCELLED')
|
completed_at = CASE WHEN %s IN ('SUCCESS','FAILED','CANCELLED')
|
||||||
THEN now() ELSE completed_at END
|
THEN now() ELSE completed_at END
|
||||||
WHERE id = %s
|
WHERE id = %s AND status = 'PROCESSING' AND lease_token = %s
|
||||||
|
RETURNING id
|
||||||
""",
|
""",
|
||||||
(
|
(normalized, (error or "")[:1000], next_retry_at, retry_count, normalized,
|
||||||
store.normalize_schedule_status(status),
|
int(schedule_id), token),
|
||||||
(error or "")[:1000],
|
).fetchone()
|
||||||
next_retry_at,
|
return row is not None
|
||||||
retry_count,
|
|
||||||
store.normalize_schedule_status(status),
|
def get_schedule(self, schedule_id: int) -> dict[str, Any]:
|
||||||
int(schedule_id),
|
with self._pool.connection() as conn:
|
||||||
),
|
row = conn.execute(
|
||||||
)
|
"SELECT * FROM cafe24_product_schedules WHERE id = %s", (int(schedule_id),)
|
||||||
|
).fetchone()
|
||||||
|
return self._serialize(row)
|
||||||
|
|
||||||
|
def review_schedule(
|
||||||
|
self, schedule_id: int, *, status: str, note: str, actor: str, action: str
|
||||||
|
) -> dict[str, Any]:
|
||||||
|
"""확인 필요(NEEDS_REVIEW) 예약을 사람이 확정한다 — SUCCESS / FAILED / PENDING(다시 실행).
|
||||||
|
|
||||||
|
SUCCESS 가 아니면 그 예약의 열린 쓰기 시도(STARTED/UNKNOWN)를 ABANDONED 로 닫는다
|
||||||
|
(반영 안 됨으로 확정 / 재실행으로 대체). SUCCESS 면 호출부가 버전 기록을 채운다.
|
||||||
|
반환: 바뀐 예약 행. NEEDS_REVIEW 가 아니었으면 {}.
|
||||||
|
"""
|
||||||
|
normalized = store.normalize_schedule_status(status)
|
||||||
|
with self._pool.connection() as conn:
|
||||||
|
with conn.transaction():
|
||||||
|
row = conn.execute(
|
||||||
|
"""
|
||||||
|
UPDATE cafe24_product_schedules
|
||||||
|
SET status = %s, last_error = %s,
|
||||||
|
next_retry_at = CASE WHEN %s = 'PENDING' THEN now() ELSE NULL END,
|
||||||
|
completed_at = CASE WHEN %s IN ('SUCCESS','FAILED') THEN now() ELSE NULL END
|
||||||
|
WHERE id = %s AND status = 'NEEDS_REVIEW'
|
||||||
|
RETURNING *
|
||||||
|
""",
|
||||||
|
(normalized, (note or "")[:1000], normalized, normalized, int(schedule_id)),
|
||||||
|
).fetchone()
|
||||||
|
if row is None:
|
||||||
|
return {}
|
||||||
|
if normalized != store.STATUS_SUCCESS:
|
||||||
|
conn.execute(
|
||||||
|
"""
|
||||||
|
UPDATE cafe24_write_attempts
|
||||||
|
SET status = %s, resolved_by = %s
|
||||||
|
WHERE schedule_id = %s AND status = ANY(%s)
|
||||||
|
""",
|
||||||
|
(store.ATTEMPT_ABANDONED, (actor or "")[:200], int(schedule_id),
|
||||||
|
[store.ATTEMPT_STARTED, store.ATTEMPT_UNKNOWN]),
|
||||||
|
)
|
||||||
|
self._insert_audit(
|
||||||
|
conn, actor=actor, action=f"schedule_review:{action}",
|
||||||
|
product_no=row["product_no"], schedule_id=row["id"], result="SUCCESS",
|
||||||
|
detail=note,
|
||||||
|
)
|
||||||
|
return self._serialize(row)
|
||||||
|
|
||||||
# ════════════════════════════════════════════════════════════
|
# ════════════════════════════════════════════════════════════
|
||||||
# 직렬화 — datetime → KST ISO, date → ISO (다른 모듈과 동일)
|
# 직렬화 — datetime → KST ISO, date → ISO (다른 모듈과 동일)
|
||||||
|
|||||||
@@ -13,8 +13,11 @@
|
|||||||
다른 데이터를 다루지만, 여기는 파일마다 경로만 다르고 나머지는 동일하다).
|
다른 데이터를 다루지만, 여기는 파일마다 경로만 다르고 나머지는 동일하다).
|
||||||
|
|
||||||
쓰기 순서는 상세페이지 적용과 동일한 원칙을 따른다:
|
쓰기 순서는 상세페이지 적용과 동일한 원칙을 따른다:
|
||||||
FTP 에서 현재 내용을 다시 읽는다(로컬 값을 현재값으로 가정하지 않는다)
|
파일별 DB 잠금(writes.write_lock, 'design:{file_key}')
|
||||||
→ BACKUP 버전 저장 → 지문 대조(충돌 시 거부) → FTP 에 쓴다
|
→ FTP 에서 현재 내용을 다시 읽는다(로컬 값을 현재값으로 가정하지 않는다)
|
||||||
|
→ BACKUP 버전 저장 → 지문 대조(충돌 시 거부)
|
||||||
|
→ 임시 파일 업로드·검증 → 교체 직전 원본 재확인 → 이름 바꾸기로 교체
|
||||||
|
(design_ftp.write_text_file — 원본에 직접 STOR 하지 않는다)
|
||||||
→ MANUAL 버전 + 감사로그
|
→ MANUAL 버전 + 감사로그
|
||||||
|
|
||||||
핸들러는 `async def` 가 아니라 `def`(동기)다 — FTP 호출이 블로킹이므로
|
핸들러는 `async def` 가 아니라 `def`(동기)다 — FTP 호출이 블로킹이므로
|
||||||
@@ -24,12 +27,14 @@ FastAPI 스레드풀에서 돌게 둔다(다른 cafe24 라우트와 동일한
|
|||||||
from __future__ import annotations
|
from __future__ import annotations
|
||||||
|
|
||||||
import logging
|
import logging
|
||||||
|
from urllib.parse import quote
|
||||||
|
|
||||||
from fastapi import APIRouter, Form, HTTPException, Request
|
from fastapi import APIRouter, Form, HTTPException, Request
|
||||||
from fastapi.responses import HTMLResponse, RedirectResponse
|
from fastapi.responses import HTMLResponse, RedirectResponse
|
||||||
|
|
||||||
from app.integrations.cafe24 import (
|
from app.integrations.cafe24 import (
|
||||||
DESIGN_FILE_SPECS,
|
DESIGN_FILE_SPECS,
|
||||||
|
Cafe24FtpConflict,
|
||||||
Cafe24FtpError,
|
Cafe24FtpError,
|
||||||
design_file_label,
|
design_file_label,
|
||||||
design_file_path,
|
design_file_path,
|
||||||
@@ -38,7 +43,7 @@ from app.integrations.cafe24 import (
|
|||||||
load_ftp_config,
|
load_ftp_config,
|
||||||
)
|
)
|
||||||
|
|
||||||
from . import store
|
from . import store, writes
|
||||||
from .common import base_ctx, guard
|
from .common import base_ctx, guard
|
||||||
from .routes_products import _no_store
|
from .routes_products import _no_store
|
||||||
|
|
||||||
@@ -128,74 +133,76 @@ def design_file_apply(
|
|||||||
st, user = checked
|
st, user = checked
|
||||||
actor = str(user.get("email") or "")
|
actor = str(user.get("email") or "")
|
||||||
back = f"/cafe24/design/{file_key}"
|
back = f"/cafe24/design/{file_key}"
|
||||||
|
action = f"apply_design:{file_key}"
|
||||||
|
|
||||||
|
def go(*, msg: str = "", err: str = "") -> RedirectResponse:
|
||||||
|
key, text = ("err", err) if err else ("msg", msg)
|
||||||
|
return RedirectResponse(url=f"{back}?{key}={quote(text, safe='')}", status_code=303)
|
||||||
|
|
||||||
path = design_file_path(file_key)
|
path = design_file_path(file_key)
|
||||||
ftp_config = _ftp_config()
|
ftp_config = _ftp_config()
|
||||||
if not ftp_config.configured:
|
if not ftp_config.configured:
|
||||||
return RedirectResponse(
|
return go(err="FTP 설정이 필요합니다: " + ", ".join(ftp_config.missing))
|
||||||
url=f"{back}?err=" + "FTP 설정이 필요합니다: " + ", ".join(ftp_config.missing),
|
|
||||||
status_code=303,
|
|
||||||
)
|
|
||||||
|
|
||||||
# 브라우저 textarea 는 줄바꿈을 CRLF 로 보낸다 — 그대로 저장하면 실제 수정이
|
# 브라우저 textarea 는 줄바꿈을 CRLF 로 보낸다 — 그대로 저장하면 실제 수정이
|
||||||
# 없어도 매번 파일 전체의 줄바꿈이 바뀌어(지문 비교·"변경 없음" 판정이 어긋난다).
|
# 없어도 매번 파일 전체의 줄바꿈이 바뀌어(지문 비교·"변경 없음" 판정이 어긋난다).
|
||||||
submitted = content.replace("\r\n", "\n")
|
submitted = content.replace("\r\n", "\n")
|
||||||
if not submitted.strip():
|
if not submitted.strip():
|
||||||
return RedirectResponse(
|
return go(err="내용이 비어 있습니다. 파일을 비우려면 FTP 로 직접 하세요.")
|
||||||
url=f"{back}?err=" + "내용이 비어 있습니다. 파일을 비우려면 FTP 로 직접 하세요.",
|
|
||||||
status_code=303,
|
|
||||||
)
|
|
||||||
|
|
||||||
|
# 같은 파일을 두 사람이 동시에 적용하지 못하게 파일별 DB 잠금 안에서 한다.
|
||||||
try:
|
try:
|
||||||
current = design_ftp.read_text_file(ftp_config, path)
|
with writes.write_lock(st, writes.design_lock_key(file_key), actor=actor, purpose=f"{file_key} 적용"):
|
||||||
except Cafe24FtpError as exc:
|
try:
|
||||||
st.log_audit(
|
current = design_ftp.read_text_file(ftp_config, path)
|
||||||
actor=actor, action=f"apply_design:{file_key}", result="FAIL",
|
except Cafe24FtpError as exc:
|
||||||
detail=f"현재값 조회 실패: {exc}",
|
writes.audit_safe(st, actor=actor, action=action, result="FAIL", detail=f"현재값 조회 실패: {exc}")
|
||||||
)
|
return go(err=f"현재 파일을 읽지 못해 중단했습니다: {exc}")
|
||||||
return RedirectResponse(url=f"{back}?err=현재 파일을 읽지 못해 중단했습니다: {exc}", status_code=303)
|
|
||||||
|
|
||||||
backup_id = st.add_design_revision(
|
backup_id = st.add_design_revision(
|
||||||
file_key=file_key, content=current, revision_type=store.REVISION_BACKUP,
|
file_key=file_key, content=current, revision_type=store.REVISION_BACKUP,
|
||||||
memo="적용 직전 자동 백업", created_by=actor,
|
memo="적용 직전 자동 백업", created_by=actor,
|
||||||
)
|
)
|
||||||
|
|
||||||
if base_fingerprint and base_fingerprint != store.fingerprint(current):
|
if base_fingerprint and base_fingerprint != store.fingerprint(current):
|
||||||
st.log_audit(
|
writes.audit_safe(st, actor=actor, action=action, revision_id=backup_id,
|
||||||
actor=actor, action=f"apply_design:{file_key}", revision_id=backup_id,
|
result="FAIL", detail="충돌 — 편집 중 파일이 변경됨")
|
||||||
result="FAIL", detail="충돌 — 편집 중 파일이 변경됨",
|
return go(err="편집하는 동안 파일이 변경되었습니다. 새로고침해 현재 내용을 확인한 뒤 다시 적용하세요.")
|
||||||
)
|
|
||||||
return RedirectResponse(
|
|
||||||
url=f"{back}?err=편집하는 동안 파일이 변경되었습니다. 새로고침해 현재 내용을 확인한 뒤 다시 적용하세요.",
|
|
||||||
status_code=303,
|
|
||||||
)
|
|
||||||
|
|
||||||
if submitted == current:
|
if submitted == current:
|
||||||
return RedirectResponse(url=f"{back}?msg=변경된 내용이 없어 적용하지 않았습니다.", status_code=303)
|
return go(msg="변경된 내용이 없어 적용하지 않았습니다.")
|
||||||
|
|
||||||
try:
|
try:
|
||||||
design_ftp.write_text_file(ftp_config, path, submitted)
|
# 임시 파일 업로드 → 검증 → 교체 직전 원본 재확인(current 와 같아야) → 이름 바꾸기.
|
||||||
except Cafe24FtpError as exc:
|
design_ftp.write_text_file(ftp_config, path, submitted, expected_current=current)
|
||||||
st.log_audit(
|
except Cafe24FtpConflict as exc:
|
||||||
actor=actor, action=f"apply_design:{file_key}", revision_id=backup_id,
|
writes.audit_safe(st, actor=actor, action=action, revision_id=backup_id,
|
||||||
result="FAIL", detail=str(exc),
|
result="FAIL", detail=f"충돌 — 교체 직전 파일이 변경됨: {exc}")
|
||||||
)
|
return go(err=f"{exc} (직전 내용은 버전 {backup_id} 로 보관됨)")
|
||||||
logger.warning("디자인 파일 적용 실패(%s): %s", file_key, exc)
|
except Cafe24FtpError as exc:
|
||||||
return RedirectResponse(
|
maybe = bool(getattr(exc, "maybe_applied", False))
|
||||||
url=f"{back}?err=적용에 실패했습니다: {exc} (직전 내용은 버전 {backup_id} 로 보관됨)",
|
writes.audit_safe(st, actor=actor, action=action, revision_id=backup_id,
|
||||||
status_code=303,
|
result="UNKNOWN" if maybe else "FAIL", detail=str(exc))
|
||||||
)
|
logger.warning("디자인 파일 적용 실패(%s): %s", file_key, exc)
|
||||||
|
return go(err=f"적용에 실패했습니다: {exc} (직전 내용은 버전 {backup_id} 로 보관됨)")
|
||||||
|
|
||||||
revision_id = st.add_design_revision(
|
# 파일은 이미 바뀌었다 — 여기서의 기록 실패는 "적용 실패"가 아니다.
|
||||||
file_key=file_key, content=submitted, revision_type=store.REVISION_MANUAL,
|
record_note = ""
|
||||||
memo=memo, created_by=actor,
|
try:
|
||||||
)
|
revision_id = st.add_design_revision(
|
||||||
st.log_audit(
|
file_key=file_key, content=submitted, revision_type=store.REVISION_MANUAL,
|
||||||
actor=actor, action=f"apply_design:{file_key}", revision_id=revision_id, result="SUCCESS",
|
memo=memo, created_by=actor,
|
||||||
detail=f"{len(submitted)}자 적용 (백업 {backup_id})",
|
)
|
||||||
|
except Exception: # noqa: BLE001
|
||||||
|
logger.exception("디자인 파일(%s) 적용 후 버전 기록 실패", file_key)
|
||||||
|
revision_id = None
|
||||||
|
record_note = " ※ 파일은 적용됐지만 버전 기록 저장에 실패했습니다 — 다시 적용하지 마세요."
|
||||||
|
except (writes.WriteBusy, writes.WriteSetupError) as exc:
|
||||||
|
return go(err=str(exc))
|
||||||
|
|
||||||
|
writes.audit_safe(
|
||||||
|
st, actor=actor, action=action, revision_id=revision_id, result="SUCCESS",
|
||||||
|
detail=f"{len(submitted)}자 적용 (백업 {backup_id}, 임시 파일 교체 방식)" + (" / 버전 기록 실패" if record_note else ""),
|
||||||
)
|
)
|
||||||
logger.info("디자인 파일 적용(%s) (%s)", file_key, actor)
|
logger.info("디자인 파일 적용(%s) (%s)", file_key, actor)
|
||||||
return RedirectResponse(
|
return go(msg=f"적용했습니다. 직전 내용은 버전 {backup_id} 로 보관됩니다.{record_note}")
|
||||||
url=f"{back}?msg=적용했습니다. 직전 내용은 버전 {backup_id} 로 보관됩니다.",
|
|
||||||
status_code=303,
|
|
||||||
)
|
|
||||||
|
|||||||
@@ -9,15 +9,20 @@
|
|||||||
PUT /products/{no}/options 옵션명 · 옵션값 이름/이미지/표시방식 수정
|
PUT /products/{no}/options 옵션명 · 옵션값 이름/이미지/표시방식 수정
|
||||||
DELETE /products/{no}/options 옵션 삭제 (품목도 함께 삭제 — 확인 후)
|
DELETE /products/{no}/options 옵션 삭제 (품목도 함께 삭제 — 확인 후)
|
||||||
POST /products/{no}/options/image 옵션값 썸네일 업로드만 (경로 반환)
|
POST /products/{no}/options/image 옵션값 썸네일 업로드만 (경로 반환)
|
||||||
PUT /products/{no}/variants 품목 자체코드 · 추가금액 · 진열 · 판매
|
PUT /products/{no}/variants 품목 자체코드 · 추가금액 · 진열 · 판매 (행별 결과)
|
||||||
|
|
||||||
공통 규칙
|
공통 규칙
|
||||||
- 카페24 호출은 `app.integrations.cafe24` 만 통한다(httpx 직접 호출 금지).
|
- 카페24 호출은 `app.integrations.cafe24` 만 통한다(httpx 직접 호출 금지).
|
||||||
|
- 쓰기는 상품별 DB 잠금(writes.write_lock) 안에서 한다 — 같은 상품을 웹 여러
|
||||||
|
프로세스·예약 worker 가 동시에 쓰지 않게. 못 잡으면 409.
|
||||||
- 쓰기 전에 현재값을 읽되, **읽기 지연을 보정한 유효 현재값**과 비교해 바뀐
|
- 쓰기 전에 현재값을 읽되, **읽기 지연을 보정한 유효 현재값**과 비교해 바뀐
|
||||||
것만 보낸다(routes_products.load_product). 이걸 안 하면 "A→B 로 바꾼 직후
|
것만 보낸다(routes_products.load_product). 이걸 안 하면 "A→B 로 바꾼 직후
|
||||||
다시 B→A" 가 카페24의 예전 값(A)과 같다고 판단돼 무시된다.
|
다시 B→A" 가 카페24의 예전 값(A)과 같다고 판단돼 무시된다.
|
||||||
- PUT 응답이 곧 현재값이다. 응답을 스냅샷(`save_write_snapshot`)에 남기고 화면도
|
- PUT 응답이 곧 현재값이다. 응답을 스냅샷(`save_write_snapshot`)에 남기고 화면도
|
||||||
응답으로 그린다 — 다시 GET 하지 않는다(GET 은 한동안 예전 값을 돌려준다).
|
응답으로 그린다 — 다시 GET 하지 않는다(GET 은 한동안 예전 값을 돌려준다).
|
||||||
|
PUT 이 성공한 뒤의 기록 실패는 쓰기 실패로 알리지 않는다(재전송을 부르지 않게).
|
||||||
|
- 품목은 **품목코드**(안정 식별자)로 짝짓는다. 옵션값 이름을 바꾼 직후 GET 품목이
|
||||||
|
예전 이름을 돌려줘도 스냅샷의 품목코드별 표기로 바로잡는다(store.apply_variant_patch).
|
||||||
- 모든 쓰기는 감사로그(`cafe24_audit_logs`)에 남긴다.
|
- 모든 쓰기는 감사로그(`cafe24_audit_logs`)에 남긴다.
|
||||||
"""
|
"""
|
||||||
|
|
||||||
@@ -31,9 +36,9 @@ from fastapi import APIRouter, Body, File, HTTPException, Request, UploadFile
|
|||||||
from app.integrations.cafe24 import Cafe24Error, build_cafe24_api, products
|
from app.integrations.cafe24 import Cafe24Error, build_cafe24_api, products
|
||||||
from app.timezone import now_kst
|
from app.timezone import now_kst
|
||||||
|
|
||||||
from . import store
|
from . import store, writes
|
||||||
from .common import read_lag_grace_minutes, require_store
|
from .common import read_lag_grace_minutes, require_store, shop_nos
|
||||||
from .routes_products import load_product, remember_write
|
from .routes_products import load_product, locked_json, remember_write
|
||||||
|
|
||||||
logger = logging.getLogger("cafe24.product_info")
|
logger = logging.getLogger("cafe24.product_info")
|
||||||
|
|
||||||
@@ -110,41 +115,76 @@ def product_basic(
|
|||||||
raise HTTPException(status_code=400, detail="바꿀 항목이 없습니다.")
|
raise HTTPException(status_code=400, detail="바꿀 항목이 없습니다.")
|
||||||
|
|
||||||
api = build_cafe24_api(st)
|
api = build_cafe24_api(st)
|
||||||
try:
|
with locked_json(st, product_no, actor=actor, purpose="상품명·가격 변경"):
|
||||||
current, _ = load_product(st, api, product_no)
|
try:
|
||||||
except Cafe24Error as exc:
|
current, _ = load_product(st, api, product_no)
|
||||||
st.log_audit(actor=actor, action="update_basic", product_no=product_no,
|
except Cafe24Error as exc:
|
||||||
result="FAIL", detail=f"현재값 조회 실패: {exc}")
|
writes.audit_safe(st, actor=actor, action="update_basic", product_no=product_no,
|
||||||
raise _http_from_cafe24(exc) from exc
|
result="FAIL", detail=f"현재값 조회 실패: {exc}")
|
||||||
if not current:
|
raise _http_from_cafe24(exc) from exc
|
||||||
raise HTTPException(status_code=404, detail="카페24에서 상품을 찾지 못했습니다.")
|
if not current:
|
||||||
|
raise HTTPException(status_code=404, detail="카페24에서 상품을 찾지 못했습니다.")
|
||||||
|
|
||||||
changes: dict[str, str] = {}
|
changes: dict[str, str] = {}
|
||||||
before: dict[str, str] = {}
|
before: dict[str, str] = {}
|
||||||
for key, value in want.items():
|
for key, value in want.items():
|
||||||
old = str(current.get(key) or "")
|
old = str(current.get(key) or "")
|
||||||
same = old == value if key == "product_name" else store.price_equal(old, value)
|
same = old == value if key == "product_name" else store.price_equal(old, value)
|
||||||
if not same:
|
if not same:
|
||||||
changes[key] = value
|
changes[key] = value
|
||||||
before[key] = old
|
before[key] = old
|
||||||
if not changes:
|
if not changes:
|
||||||
return {"ok": True, "changed": [], "product": _scalar_view(current)}
|
return {"ok": True, "changed": [], "product": _scalar_view(current)}
|
||||||
|
|
||||||
try:
|
try:
|
||||||
updated = products.update_product(api.client, product_no, **changes)
|
updated = products.update_product(api.client, product_no, **changes)
|
||||||
except Cafe24Error as exc:
|
except Cafe24Error as exc:
|
||||||
st.log_audit(actor=actor, action="update_basic", product_no=product_no,
|
writes.audit_safe(st, actor=actor, action="update_basic", product_no=product_no,
|
||||||
result="FAIL", detail=f"{changes} 실패: {exc}")
|
result="FAIL", detail=f"{changes} 실패: {exc}")
|
||||||
logger.warning("카페24 상품 %s 기본정보 변경 실패: %s", product_no, exc)
|
logger.warning("카페24 상품 %s 기본정보 변경 실패: %s", product_no, exc)
|
||||||
raise _http_from_cafe24(exc) from exc
|
raise _http_from_cafe24(exc) from exc
|
||||||
|
|
||||||
remember_write(st, product_no, updated if isinstance(updated, dict) else {})
|
remember_write(st, product_no, updated if isinstance(updated, dict) else {})
|
||||||
|
shifted = (_keep_variant_sale_prices(st, api, product_no, before["price"], changes["price"])
|
||||||
|
if "price" in changes else {})
|
||||||
merged = {**current, **(updated if isinstance(updated, dict) else {}), **changes}
|
merged = {**current, **(updated if isinstance(updated, dict) else {}), **changes}
|
||||||
detail = ", ".join(f"{k}: '{before[k]}' → '{v}'" for k, v in changes.items())
|
detail = ", ".join(f"{k}: '{before[k]}' → '{v}'" for k, v in changes.items())
|
||||||
st.log_audit(actor=actor, action="update_basic", product_no=product_no,
|
if shifted.get("detail"):
|
||||||
result="SUCCESS", detail=detail)
|
detail += f" / 품목 추가금액 조정: {shifted['detail']}"
|
||||||
|
writes.audit_safe(st, actor=actor, action="update_basic", product_no=product_no,
|
||||||
|
result="SUCCESS", detail=detail)
|
||||||
logger.info("카페24 상품 %s 기본정보 변경 (%s): %s", product_no, actor, detail)
|
logger.info("카페24 상품 %s 기본정보 변경 (%s): %s", product_no, actor, detail)
|
||||||
return {"ok": True, "changed": list(changes.keys()), "product": _scalar_view(merged)}
|
return {"ok": True, "changed": list(changes.keys()), "product": _scalar_view(merged),
|
||||||
|
"variants_shifted": shifted.get("count", 0), "variants_error": shifted.get("error", "")}
|
||||||
|
|
||||||
|
|
||||||
|
def _keep_variant_sale_prices(st: Any, api: Any, product_no: int, old_price: str, new_price: str) -> dict[str, Any]:
|
||||||
|
"""판매가가 바뀐 뒤 품목 판매 가격(판매가 + 추가금액)이 그대로이도록 추가금액을 옮긴다.
|
||||||
|
|
||||||
|
판매가는 이미 반영됐으므로 실패해도 예외를 올리지 않고 {"error": …} 로 알린다.
|
||||||
|
반환 {"count": 반영된 품목 수, "error": 사유, "detail": 감사 로그용}.
|
||||||
|
"""
|
||||||
|
try:
|
||||||
|
variants = _load_options_and_variants(st, api, product_no)["effective_variants"]
|
||||||
|
requests = store.build_variant_updates(store.shift_additional_amounts(variants, old_price, new_price))
|
||||||
|
except (Cafe24Error, ValueError) as exc:
|
||||||
|
logger.warning("카페24 상품 %s 품목 추가금액 조정 준비 실패: %s", product_no, exc)
|
||||||
|
return {"error": f"품목 추가금액 조정 실패: {exc}", "detail": f"실패 {exc}"}
|
||||||
|
if not requests:
|
||||||
|
return {}
|
||||||
|
results = products.update_variants(api.client, product_no, requests)
|
||||||
|
sent = {r["variant_code"]: r["additional_amount"] for r in requests}
|
||||||
|
ok = {r["variant_code"]: sent[r["variant_code"]] for r in results if r["status"] == products.VARIANT_OK}
|
||||||
|
bad = [r for r in results if r["status"] != products.VARIANT_OK]
|
||||||
|
if ok:
|
||||||
|
_save_snapshot_safe(st, product_no, "variants", {c: {"additional_amount": a} for c, a in ok.items()})
|
||||||
|
detail = "; ".join(f"{c}={a}" for c, a in ok.items())
|
||||||
|
error = ""
|
||||||
|
if bad:
|
||||||
|
error = f"품목 {len(bad)}건 추가금액 조정 실패 — {bad[0]['error']} (옵션/품목 창에서 확인하세요)"
|
||||||
|
detail += f" / 실패 {len(bad)}건: {bad[0]['error']}"
|
||||||
|
logger.warning("카페24 상품 %s 품목 추가금액 조정 %s건 실패: %s", product_no, len(bad), bad[0]["error"])
|
||||||
|
return {"count": len(ok), "error": error, "detail": detail}
|
||||||
|
|
||||||
|
|
||||||
# ════════════════════════════════════════════════════════════
|
# ════════════════════════════════════════════════════════════
|
||||||
@@ -169,30 +209,31 @@ def product_image(
|
|||||||
data = _read_image(file)
|
data = _read_image(file)
|
||||||
|
|
||||||
api = build_cafe24_api(st)
|
api = build_cafe24_api(st)
|
||||||
try:
|
with locked_json(st, product_no, actor=actor, purpose="대표 이미지 교체"):
|
||||||
current, _ = load_product(st, api, product_no)
|
try:
|
||||||
except Cafe24Error as exc:
|
current, _ = load_product(st, api, product_no)
|
||||||
raise _http_from_cafe24(exc) from exc
|
except Cafe24Error as exc:
|
||||||
if not current:
|
raise _http_from_cafe24(exc) from exc
|
||||||
raise HTTPException(status_code=404, detail="카페24에서 상품을 찾지 못했습니다.")
|
if not current:
|
||||||
before = str(current.get("detail_image") or "")
|
raise HTTPException(status_code=404, detail="카페24에서 상품을 찾지 못했습니다.")
|
||||||
|
before = str(current.get("detail_image") or "")
|
||||||
|
|
||||||
try:
|
try:
|
||||||
images = products.set_main_image(
|
images = products.set_main_image(
|
||||||
api.client, product_no, data, content_type=(file.content_type or "").lower()
|
api.client, product_no, data, content_type=(file.content_type or "").lower()
|
||||||
)
|
)
|
||||||
if not images.get("detail_image"):
|
if not images.get("detail_image"):
|
||||||
raise Cafe24Error("카페24가 등록된 이미지 경로를 돌려주지 않았습니다.")
|
raise Cafe24Error("카페24가 등록된 이미지 경로를 돌려주지 않았습니다.")
|
||||||
except Cafe24Error as exc:
|
except Cafe24Error as exc:
|
||||||
st.log_audit(actor=actor, action="set_main_image", product_no=product_no,
|
writes.audit_safe(st, actor=actor, action="set_main_image", product_no=product_no,
|
||||||
result="FAIL", detail=f"등록 실패: {exc}")
|
result="FAIL", detail=f"등록 실패: {exc}")
|
||||||
logger.warning("카페24 상품 %s 대표이미지 변경 실패: %s", product_no, exc)
|
logger.warning("카페24 상품 %s 대표이미지 변경 실패: %s", product_no, exc)
|
||||||
raise _http_from_cafe24(exc) from exc
|
raise _http_from_cafe24(exc) from exc
|
||||||
|
|
||||||
merged = {**current, **images, "updated_date": now_kst().isoformat(timespec="seconds")}
|
merged = {**current, **images, "updated_date": now_kst().isoformat(timespec="seconds")}
|
||||||
remember_write(st, product_no, merged)
|
remember_write(st, product_no, merged)
|
||||||
st.log_audit(actor=actor, action="set_main_image", product_no=product_no,
|
writes.audit_safe(st, actor=actor, action="set_main_image", product_no=product_no,
|
||||||
result="SUCCESS", detail=f"'{before}' → '{images['detail_image']}'")
|
result="SUCCESS", detail=f"'{before}' → '{images['detail_image']}'")
|
||||||
logger.info("카페24 상품 %s 대표이미지 변경 (%s)", product_no, actor)
|
logger.info("카페24 상품 %s 대표이미지 변경 (%s)", product_no, actor)
|
||||||
return {"ok": True, "product": _scalar_view(merged)}
|
return {"ok": True, "product": _scalar_view(merged)}
|
||||||
|
|
||||||
@@ -208,12 +249,15 @@ def _variant_view(v: dict[str, Any]) -> dict[str, Any]:
|
|||||||
{"name": str(o.get("name") or ""), "value": str(o.get("value") or "")}
|
{"name": str(o.get("name") or ""), "value": str(o.get("value") or "")}
|
||||||
for o in opts if isinstance(o, dict)
|
for o in opts if isinstance(o, dict)
|
||||||
],
|
],
|
||||||
|
# 첫 옵션의 옵션값 번호(value_no) — 화면이 이름보다 먼저 이것으로 옵션값과 짝짓는다.
|
||||||
|
"value_no": v.get("value_no"),
|
||||||
"custom_variant_code": str(v.get("custom_variant_code") or ""),
|
"custom_variant_code": str(v.get("custom_variant_code") or ""),
|
||||||
"additional_amount": str(v.get("additional_amount") or "0.00"),
|
"additional_amount": str(v.get("additional_amount") or "0.00"),
|
||||||
"display": products._flag(v.get("display")), # noqa: SLF001
|
"display": products._flag(v.get("display")), # noqa: SLF001
|
||||||
"selling": products._flag(v.get("selling")), # noqa: SLF001
|
"selling": products._flag(v.get("selling")), # noqa: SLF001
|
||||||
"quantity": v.get("quantity"),
|
"quantity": v.get("quantity"),
|
||||||
"use_inventory": products._flag(v.get("use_inventory"), default=False), # noqa: SLF001
|
"use_inventory": products._flag(v.get("use_inventory"), default=False), # noqa: SLF001
|
||||||
|
"display_soldout": products._flag(v.get("display_soldout"), default=False), # noqa: SLF001
|
||||||
"image": str(v.get("image") or ""),
|
"image": str(v.get("image") or ""),
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -238,6 +282,7 @@ def _options_view(option: dict[str, Any]) -> dict[str, Any]:
|
|||||||
"option_link_image": str(v.get("option_link_image") or ""),
|
"option_link_image": str(v.get("option_link_image") or ""),
|
||||||
"option_color": str(v.get("option_color") or ""),
|
"option_color": str(v.get("option_color") or ""),
|
||||||
"value_no": v.get("value_no"),
|
"value_no": v.get("value_no"),
|
||||||
|
"pending": bool(v.get("pending")),
|
||||||
}
|
}
|
||||||
for v in values if isinstance(v, dict)
|
for v in values if isinstance(v, dict)
|
||||||
],
|
],
|
||||||
@@ -252,43 +297,125 @@ def _options_view(option: dict[str, Any]) -> dict[str, Any]:
|
|||||||
}
|
}
|
||||||
|
|
||||||
|
|
||||||
def _apply_variant_snapshot(st: Any, product_no: int, variants: list[dict[str, Any]]) -> list[dict[str, Any]]:
|
def _snapshot_sections(st: Any, product_no: int) -> tuple[dict[str, Any], dict[str, Any]]:
|
||||||
"""GET 품목 목록에 유예시간 안의 우리 쓰기(스냅샷)를 덮어씌운다.
|
"""(옵션 섹션, 품목 섹션) — 각각 {"data":…, "written_at":…} 또는 {}."""
|
||||||
|
snap = st.get_write_snapshot(product_no) or {}
|
||||||
|
return snap.get("options") or {}, snap.get("variants") or {}
|
||||||
|
|
||||||
삭제한 품목(`{"_deleted": true}`)은 카페24 GET 이 한동안 계속 돌려주므로 걸러낸다.
|
|
||||||
"""
|
def _within(written_at: object) -> bool:
|
||||||
section = (st.get_write_snapshot(product_no) or {}).get("variants") or {}
|
return store.within_grace(written_at, grace_minutes=read_lag_grace_minutes())
|
||||||
|
|
||||||
|
|
||||||
|
def _patch_variants(section: dict[str, Any], variants: list[dict[str, Any]]) -> list[dict[str, Any]]:
|
||||||
|
"""GET 품목 목록에 품목코드별 쓰기 기록을 덮어씌운다(삭제한 품목은 뺀다)."""
|
||||||
data = section.get("data") or {}
|
data = section.get("data") or {}
|
||||||
if not data or not store.within_grace(section.get("written_at"), grace_minutes=read_lag_grace_minutes()):
|
if not isinstance(data, dict) or not data:
|
||||||
return variants
|
return list(variants)
|
||||||
out = []
|
out = []
|
||||||
for v in variants:
|
for v in variants:
|
||||||
code = str(v.get("variant_code") or "")
|
patched = store.apply_variant_patch(
|
||||||
patch = data.get(code)
|
v, data.get(str(v.get("variant_code") or "")),
|
||||||
if isinstance(patch, dict) and patch.get("_deleted"):
|
section_written_at=section.get("written_at"), grace_minutes=read_lag_grace_minutes(),
|
||||||
continue
|
)
|
||||||
out.append({**v, **patch} if isinstance(patch, dict) else v)
|
if patched is not None:
|
||||||
|
out.append(patched)
|
||||||
return out
|
return out
|
||||||
|
|
||||||
|
|
||||||
def _apply_options_snapshot(st: Any, product_no: int, option: dict[str, Any]) -> dict[str, Any]:
|
def _annotate(option: dict[str, Any], variants: list[dict[str, Any]], recent: list[str]) -> tuple[dict, list]:
|
||||||
"""GET 옵션이 우리 마지막 쓰기와 다르고 유예시간 안이면 스냅샷(우리 쓰기)을 쓴다."""
|
"""옵션 1개 상품: 품목에 첫 옵션값 번호(value_no)를, 품목이 아직 안 보이는 최근 추가
|
||||||
section = (st.get_write_snapshot(product_no) or {}).get("options") or {}
|
옵션값에 pending 표시를 붙인다(화면이 "품목 없는 옵션값"으로 오해하지 않게)."""
|
||||||
data = section.get("data")
|
groups = option.get("options") if isinstance(option.get("options"), list) else []
|
||||||
if not isinstance(data, dict) or not store.within_grace(
|
if len(groups) != 1 or not isinstance(groups[0], dict):
|
||||||
section.get("written_at"), grace_minutes=read_lag_grace_minutes()
|
return option, variants
|
||||||
):
|
values = [v for v in (groups[0].get("option_value") or []) if isinstance(v, dict)]
|
||||||
return option
|
by_text = {str(v.get("option_text") or ""): v.get("value_no") for v in values}
|
||||||
return data
|
used: set[str] = set()
|
||||||
|
out_variants = []
|
||||||
|
for v in variants:
|
||||||
|
opts = v.get("options") if isinstance(v.get("options"), list) else []
|
||||||
|
first = str(opts[0].get("value") or "") if opts and isinstance(opts[0], dict) else ""
|
||||||
|
used.add(first)
|
||||||
|
out_variants.append({**v, "value_no": by_text.get(first)} if first in by_text else v)
|
||||||
|
recent_set = set(recent or [])
|
||||||
|
new_values = [
|
||||||
|
{**v, "pending": True} if str(v.get("option_text") or "") in recent_set
|
||||||
|
and str(v.get("option_text") or "") not in used else v
|
||||||
|
for v in values
|
||||||
|
]
|
||||||
|
return {**option, "options": [{**groups[0], "option_value": new_values}]}, out_variants
|
||||||
|
|
||||||
|
|
||||||
def _load_options_and_variants(st: Any, api: Any, product_no: int) -> dict[str, Any]:
|
def _load_options_and_variants(st: Any, api: Any, product_no: int) -> dict[str, Any]:
|
||||||
option = _apply_options_snapshot(st, product_no, products.get_options(api.client, product_no))
|
raw_option = products.get_options(api.client, product_no)
|
||||||
view = _options_view(option)
|
osec, vsec = _snapshot_sections(st, product_no)
|
||||||
|
option, _stale = store.overlay_options(
|
||||||
|
raw_option, snapshot=osec.get("data"), written_at=osec.get("written_at"),
|
||||||
|
grace_minutes=read_lag_grace_minutes(),
|
||||||
|
)
|
||||||
|
raw_variants: list[dict[str, Any]] = []
|
||||||
variants: list[dict[str, Any]] = []
|
variants: list[dict[str, Any]] = []
|
||||||
if view["has_option"]:
|
if products._flag(option.get("has_option"), default=False): # noqa: SLF001
|
||||||
variants = _apply_variant_snapshot(st, product_no, products.list_variants(api.client, product_no))
|
raw_variants = products.list_variants(api.client, product_no)
|
||||||
return {"option": view, "variants": [_variant_view(v) for v in variants], "raw_options": option}
|
variants = _patch_variants(vsec, raw_variants)
|
||||||
|
recent = _recent_values(osec)
|
||||||
|
shown_option, shown_variants = _annotate(option, variants, recent)
|
||||||
|
return {
|
||||||
|
"option": _options_view(shown_option),
|
||||||
|
"variants": [_variant_view(v) for v in shown_variants],
|
||||||
|
"raw_option": raw_option,
|
||||||
|
"effective_option": option,
|
||||||
|
"raw_variants": raw_variants,
|
||||||
|
"effective_variants": variants,
|
||||||
|
"options_section": osec,
|
||||||
|
"variants_section": vsec,
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
def _recent_values(osec: dict[str, Any]) -> list[str]:
|
||||||
|
data = osec.get("data") if isinstance(osec.get("data"), dict) else {}
|
||||||
|
if not data or not _within(osec.get("written_at")):
|
||||||
|
return []
|
||||||
|
return [str(v) for v in (data.get("_recent_values") or [])]
|
||||||
|
|
||||||
|
|
||||||
|
def _prior_signatures(osec: dict[str, Any]) -> list[str]:
|
||||||
|
data = osec.get("data") if isinstance(osec.get("data"), dict) else {}
|
||||||
|
if not data or not _within(osec.get("written_at")):
|
||||||
|
return []
|
||||||
|
return [str(s) for s in (data.get("_before_signatures") or []) if isinstance(s, str)]
|
||||||
|
|
||||||
|
|
||||||
|
def _unique(items: list[Any]) -> list[Any]:
|
||||||
|
out: list[Any] = []
|
||||||
|
for item in items:
|
||||||
|
if item not in out:
|
||||||
|
out.append(item)
|
||||||
|
return out
|
||||||
|
|
||||||
|
|
||||||
|
def _options_snapshot(
|
||||||
|
written: dict[str, Any], *, befores: list[dict[str, Any]], osec: dict[str, Any], recent: list[str]
|
||||||
|
) -> dict[str, Any]:
|
||||||
|
"""옵션 스냅샷 = 카페24 응답 + 쓰기 직전 모양들의 서명 + 최근 추가한 옵션값."""
|
||||||
|
signatures = _unique(_prior_signatures(osec) + [store.options_signature(b) for b in befores if b])
|
||||||
|
texts = {
|
||||||
|
str(v.get("option_text") or "")
|
||||||
|
for o in (written.get("options") or []) if isinstance(o, dict)
|
||||||
|
for v in (o.get("option_value") or []) if isinstance(v, dict)
|
||||||
|
}
|
||||||
|
keep = [t for t in _unique(_recent_values(osec) + list(recent)) if t in texts]
|
||||||
|
return {**written, "_before_signatures": signatures, "_recent_values": keep}
|
||||||
|
|
||||||
|
|
||||||
|
def _save_snapshot_safe(st: Any, product_no: int, section: str, data: Any, **kw: Any) -> str:
|
||||||
|
try:
|
||||||
|
st.save_write_snapshot(product_no, section, data, **kw)
|
||||||
|
except Exception as exc: # noqa: BLE001 — 카페24에는 이미 반영됐다
|
||||||
|
logger.exception("상품 %s %s 스냅샷 저장 실패", product_no, section)
|
||||||
|
return f"{type(exc).__name__}: {exc}"
|
||||||
|
return ""
|
||||||
|
|
||||||
|
|
||||||
@product_info_router.get("/products/{product_no}/options")
|
@product_info_router.get("/products/{product_no}/options")
|
||||||
@@ -322,29 +449,40 @@ def options_create(
|
|||||||
)
|
)
|
||||||
except ValueError as exc:
|
except ValueError as exc:
|
||||||
raise HTTPException(status_code=400, detail=str(exc)) from exc
|
raise HTTPException(status_code=400, detail=str(exc)) from exc
|
||||||
|
values = [v["option_text"] for v in body["options"][0]["option_value"]]
|
||||||
|
|
||||||
api = build_cafe24_api(st)
|
api = build_cafe24_api(st)
|
||||||
try:
|
with locked_json(st, product_no, actor=actor, purpose="옵션 생성"):
|
||||||
existing = products.get_options(api.client, product_no)
|
try:
|
||||||
if products._flag(existing.get("has_option"), default=False): # noqa: SLF001
|
existing = products.get_options(api.client, product_no)
|
||||||
raise HTTPException(status_code=409, detail="이미 옵션이 있는 상품입니다. 수정하거나 삭제한 뒤 다시 만드세요.")
|
if products._flag(existing.get("has_option"), default=False): # noqa: SLF001
|
||||||
created = products.create_options(api.client, product_no, body)
|
raise HTTPException(status_code=409, detail="이미 옵션이 있는 상품입니다. 수정하거나 삭제한 뒤 다시 만드세요.")
|
||||||
except Cafe24Error as exc:
|
created = products.create_options(api.client, product_no, body)
|
||||||
st.log_audit(actor=actor, action="create_options", product_no=product_no,
|
except Cafe24Error as exc:
|
||||||
result="FAIL", detail=f"{body['options'][0]['option_name']} 실패: {exc}")
|
writes.audit_safe(st, actor=actor, action="create_options", product_no=product_no,
|
||||||
raise _http_from_cafe24(exc) from exc
|
result="FAIL", detail=f"{body['options'][0]['option_name']} 실패: {exc}")
|
||||||
|
raise _http_from_cafe24(exc) from exc
|
||||||
|
|
||||||
st.save_write_snapshot(product_no, "options", created)
|
osec, _vsec = _snapshot_sections(st, product_no)
|
||||||
values = [v["option_text"] for v in body["options"][0]["option_value"]]
|
record_error = _save_snapshot_safe(
|
||||||
st.log_audit(actor=actor, action="create_options", product_no=product_no, result="SUCCESS",
|
st, product_no, "options",
|
||||||
detail=f"옵션 '{body['options'][0]['option_name']}' 생성: {', '.join(values)}")
|
_options_snapshot(created, befores=[existing], osec=osec, recent=values),
|
||||||
|
)
|
||||||
|
# 새 옵션의 품목은 새 품목코드다 — 이전 품목 기록은 모두 버린다(전체 초기화).
|
||||||
|
record_error = record_error or _save_snapshot_safe(st, product_no, "variants", {}, replace=True)
|
||||||
|
# 카페24가 자동 생성한 품목(코드 부여)을 바로 돌려준다 — 읽기 지연이 있어 짧게 재시도.
|
||||||
|
# 화면은 이 코드로 자체코드·추가금액을 이어서 PUT 한다. 다 안 보이면 pending 으로 표시.
|
||||||
|
variants = products.wait_for_variants(api.client, product_no, len(values))
|
||||||
|
writes.audit_safe(st, actor=actor, action="create_options", product_no=product_no, result="SUCCESS",
|
||||||
|
detail=f"옵션 '{body['options'][0]['option_name']}' 생성: {', '.join(values)}")
|
||||||
logger.info("카페24 상품 %s 옵션 생성 (%s)", product_no, actor)
|
logger.info("카페24 상품 %s 옵션 생성 (%s)", product_no, actor)
|
||||||
# 카페24가 자동 생성한 품목(코드 부여)을 바로 돌려준다 — 읽기 지연이 있어 짧게 재시도.
|
|
||||||
# 화면은 이 코드로 자체코드·추가금액을 이어서 PUT 한다.
|
|
||||||
variants = products.wait_for_variants(api.client, product_no, len(values))
|
|
||||||
if len(variants) < len(values):
|
if len(variants) < len(values):
|
||||||
logger.warning("카페24 상품 %s 옵션 생성 후 품목 %s/%s 건만 조회됨", product_no, len(variants), len(values))
|
logger.warning("카페24 상품 %s 옵션 생성 후 품목 %s/%s 건만 조회됨", product_no, len(variants), len(values))
|
||||||
return {"ok": True, "option": _options_view(created), "variants": [_variant_view(v) for v in variants]}
|
shown_option, shown_variants = _annotate(created, variants, values)
|
||||||
|
return {"ok": True, "option": _options_view(shown_option),
|
||||||
|
"variants": [_variant_view(v) for v in shown_variants],
|
||||||
|
"missing_variants": max(0, len(values) - len(variants)),
|
||||||
|
"record_warning": record_error}
|
||||||
|
|
||||||
|
|
||||||
@product_info_router.put("/products/{product_no}/options")
|
@product_info_router.put("/products/{product_no}/options")
|
||||||
@@ -358,6 +496,8 @@ def options_update(
|
|||||||
카페24 PUT 은 `original_options`(수정 전)와 `options`(수정 후)를 짝지어 받는다.
|
카페24 PUT 은 `original_options`(수정 전)와 `options`(수정 후)를 짝지어 받는다.
|
||||||
수정 전 값은 화면이 들고 있던 것이 아니라 **지금 카페24에서 다시 읽은 값**(읽기
|
수정 전 값은 화면이 들고 있던 것이 아니라 **지금 카페24에서 다시 읽은 값**(읽기
|
||||||
지연 보정 후)을 쓴다 — 그래야 다른 곳에서 바뀐 이름과 어긋나지 않는다.
|
지연 보정 후)을 쓴다 — 그래야 다른 곳에서 바뀐 이름과 어긋나지 않는다.
|
||||||
|
이름을 바꾸면 품목코드별로 새 표기를 스냅샷에 남긴다(GET 품목이 예전 이름을
|
||||||
|
돌려주는 동안에도 품목이 옵션값과 제대로 짝지어 보이게).
|
||||||
"""
|
"""
|
||||||
st, user = require_store(request)
|
st, user = require_store(request)
|
||||||
actor = str(user.get("email") or "")
|
actor = str(user.get("email") or "")
|
||||||
@@ -366,64 +506,77 @@ def options_update(
|
|||||||
raise HTTPException(status_code=400, detail="옵션 목록이 비어 있습니다.")
|
raise HTTPException(status_code=400, detail="옵션 목록이 비어 있습니다.")
|
||||||
|
|
||||||
api = build_cafe24_api(st)
|
api = build_cafe24_api(st)
|
||||||
try:
|
with locked_json(st, product_no, actor=actor, purpose="옵션 수정"):
|
||||||
loaded = _load_options_and_variants(st, api, product_no)
|
try:
|
||||||
except Cafe24Error as exc:
|
loaded = _load_options_and_variants(st, api, product_no)
|
||||||
raise _http_from_cafe24(exc) from exc
|
except Cafe24Error as exc:
|
||||||
if not loaded["option"]["has_option"]:
|
raise _http_from_cafe24(exc) from exc
|
||||||
raise HTTPException(status_code=409, detail="옵션이 없는 상품입니다. 먼저 옵션을 만드세요.")
|
if not loaded["option"]["has_option"]:
|
||||||
original = loaded["option"]["options"]
|
raise HTTPException(status_code=409, detail="옵션이 없는 상품입니다. 먼저 옵션을 만드세요.")
|
||||||
try:
|
original = loaded["option"]["options"]
|
||||||
body = store.build_update_options_request(
|
try:
|
||||||
original, edited, option_list_type=str(payload.get("option_list_type") or ""),
|
body = store.build_update_options_request(
|
||||||
allow_append=True,
|
original, edited, option_list_type=str(payload.get("option_list_type") or ""),
|
||||||
|
)
|
||||||
|
except ValueError as exc:
|
||||||
|
raise HTTPException(status_code=400, detail=str(exc)) from exc
|
||||||
|
if loaded["option"]["option_preset_code"]:
|
||||||
|
body["option_preset_code"] = loaded["option"]["option_preset_code"]
|
||||||
|
|
||||||
|
try:
|
||||||
|
updated = products.update_options(api.client, product_no, body)
|
||||||
|
except Cafe24Error as exc:
|
||||||
|
writes.audit_safe(st, actor=actor, action="update_options", product_no=product_no,
|
||||||
|
result="FAIL", detail=str(exc))
|
||||||
|
logger.warning("카페24 상품 %s 옵션 수정 실패: %s", product_no, exc)
|
||||||
|
raise _http_from_cafe24(exc) from exc
|
||||||
|
|
||||||
|
# ── 여기부터는 카페24에 반영된 뒤 — 기록 실패는 경고로만 알린다 ──
|
||||||
|
record_error = _save_snapshot_safe(
|
||||||
|
st, product_no, "options",
|
||||||
|
_options_snapshot(updated, befores=[loaded["raw_option"], loaded["effective_option"]],
|
||||||
|
osec=loaded["options_section"], recent=[]),
|
||||||
)
|
)
|
||||||
except ValueError as exc:
|
# 이름 바꾸기 표(수정 전 → 수정 후) — 위치로 짝지어진다(build_update_options_request).
|
||||||
raise HTTPException(status_code=400, detail=str(exc)) from exc
|
rename: dict[tuple[str, str], tuple[str, str]] = {}
|
||||||
if loaded["option"]["option_preset_code"]:
|
for o, n in zip(original, body["options"]):
|
||||||
body["option_preset_code"] = loaded["option"]["option_preset_code"]
|
for ov, nv in zip(o["option_value"], n["option_value"]):
|
||||||
# 뒤에 덧붙인 옵션값 수 — 카페24가 받아들이면 품목을 자동 생성한다(재시도 조회).
|
rename[(o["option_name"], ov["option_text"])] = (n["option_name"], nv["option_text"])
|
||||||
added = sum(
|
raw_labels = {str(v.get("variant_code") or ""): v.get("options") for v in loaded["raw_variants"]}
|
||||||
max(0, len(n["option_value"]) - len(o["option_value"]))
|
previous = (loaded["variants_section"].get("data") or {}) if _within(
|
||||||
for o, n in zip(body["original_options"], body["options"])
|
loaded["variants_section"].get("written_at")) else {}
|
||||||
)
|
label_patch: dict[str, Any] = {}
|
||||||
|
renamed_variants: list[dict[str, Any]] = []
|
||||||
try:
|
for v in loaded["effective_variants"]:
|
||||||
updated = products.update_options(api.client, product_no, body)
|
code = str(v.get("variant_code") or "")
|
||||||
except Cafe24Error as exc:
|
current = store.labels_as_json(v.get("options"))
|
||||||
st.log_audit(actor=actor, action="update_options", product_no=product_no,
|
new = [
|
||||||
result="FAIL", detail=str(exc))
|
dict(zip(("name", "value"), rename.get((o["name"], o["value"]), (o["name"], o["value"]))))
|
||||||
logger.warning("카페24 상품 %s 옵션 수정 실패: %s", product_no, exc)
|
for o in current
|
||||||
raise _http_from_cafe24(exc) from exc
|
]
|
||||||
|
renamed_variants.append({**v, "options": new})
|
||||||
st.save_write_snapshot(product_no, "options", updated)
|
if new != current and code:
|
||||||
summary = "; ".join(
|
prior = previous.get(code) if isinstance(previous.get(code), dict) else {}
|
||||||
f"{o['option_name']}: " + ", ".join(v["option_text"] for v in o["option_value"])
|
history = [
|
||||||
for o in body["options"]
|
[{"name": a, "value": b} for a, b in labels]
|
||||||
) + (f" (+{added} 추가)" if added else "")
|
for labels in store.label_history(prior.get("_options_before"))
|
||||||
st.log_audit(actor=actor, action="update_options", product_no=product_no,
|
]
|
||||||
result="SUCCESS", detail=summary[:900])
|
befores = _unique(history + [current, store.labels_as_json(raw_labels.get(code))])
|
||||||
|
label_patch[code] = {"options": new, "_options_before": [b for b in befores if b != new]}
|
||||||
|
if label_patch:
|
||||||
|
record_error = record_error or _save_snapshot_safe(st, product_no, "variants", label_patch)
|
||||||
|
summary = "; ".join(
|
||||||
|
f"{o['option_name']}: " + ", ".join(v["option_text"] for v in o["option_value"])
|
||||||
|
for o in body["options"]
|
||||||
|
)
|
||||||
|
writes.audit_safe(st, actor=actor, action="update_options", product_no=product_no,
|
||||||
|
result="SUCCESS", detail=summary[:900])
|
||||||
logger.info("카페24 상품 %s 옵션 수정 (%s)", product_no, actor)
|
logger.info("카페24 상품 %s 옵션 수정 (%s)", product_no, actor)
|
||||||
|
|
||||||
if added:
|
shown_option, shown_variants = _annotate(updated, renamed_variants, [])
|
||||||
# 새 옵션값의 품목코드를 받아 돌려준다 — 화면이 자체코드/추가금액을 이어서 PUT 한다.
|
return {"ok": True, "option": _options_view(shown_option),
|
||||||
fresh = products.wait_for_variants(api.client, product_no, len(loaded["variants"]) + added)
|
"variants": [_variant_view(v) for v in shown_variants],
|
||||||
fresh = _apply_variant_snapshot(st, product_no, fresh)
|
"record_warning": record_error}
|
||||||
return {"ok": True, "option": _options_view(updated), "variants": [_variant_view(v) for v in fresh],
|
|
||||||
"added": added}
|
|
||||||
|
|
||||||
# 품목의 옵션값 표기는 이름을 바꾼 만큼 달라진다 — 응답값으로 다시 맞춘다.
|
|
||||||
variants = loaded["variants"]
|
|
||||||
rename: dict[tuple[str, str], tuple[str, str]] = {}
|
|
||||||
for o, n in zip(original, body["options"]):
|
|
||||||
for ov, nv in zip(o["option_value"], n["option_value"]):
|
|
||||||
rename[(o["option_name"], ov["option_text"])] = (n["option_name"], nv["option_text"])
|
|
||||||
for v in variants:
|
|
||||||
v["options"] = [
|
|
||||||
dict(zip(("name", "value"), rename.get((opt["name"], opt["value"]), (opt["name"], opt["value"]))))
|
|
||||||
for opt in v["options"]
|
|
||||||
]
|
|
||||||
return {"ok": True, "option": _options_view(updated), "variants": variants}
|
|
||||||
|
|
||||||
|
|
||||||
@product_info_router.delete("/products/{product_no}/options")
|
@product_info_router.delete("/products/{product_no}/options")
|
||||||
@@ -432,22 +585,29 @@ def options_delete(request: Request, product_no: int) -> dict[str, Any]:
|
|||||||
st, user = require_store(request)
|
st, user = require_store(request)
|
||||||
actor = str(user.get("email") or "")
|
actor = str(user.get("email") or "")
|
||||||
api = build_cafe24_api(st)
|
api = build_cafe24_api(st)
|
||||||
try:
|
with locked_json(st, product_no, actor=actor, purpose="옵션 삭제"):
|
||||||
before = products.get_options(api.client, product_no)
|
try:
|
||||||
products.delete_options(api.client, product_no)
|
before = products.get_options(api.client, product_no)
|
||||||
except Cafe24Error as exc:
|
products.delete_options(api.client, product_no)
|
||||||
st.log_audit(actor=actor, action="delete_options", product_no=product_no,
|
except Cafe24Error as exc:
|
||||||
result="FAIL", detail=str(exc))
|
writes.audit_safe(st, actor=actor, action="delete_options", product_no=product_no,
|
||||||
raise _http_from_cafe24(exc) from exc
|
result="FAIL", detail=str(exc))
|
||||||
names = ", ".join(
|
raise _http_from_cafe24(exc) from exc
|
||||||
str(o.get("option_name") or "") for o in (before.get("options") or []) if isinstance(o, dict)
|
names = ", ".join(
|
||||||
)
|
str(o.get("option_name") or "") for o in (before.get("options") or []) if isinstance(o, dict)
|
||||||
st.save_write_snapshot(product_no, "options", {"has_option": "F", "options": []})
|
)
|
||||||
st.save_write_snapshot(product_no, "variants", {})
|
osec, _vsec = _snapshot_sections(st, product_no)
|
||||||
st.log_audit(actor=actor, action="delete_options", product_no=product_no,
|
record_error = _save_snapshot_safe(
|
||||||
result="SUCCESS", detail=f"삭제된 옵션: {names or '(없음)'}")
|
st, product_no, "options",
|
||||||
|
_options_snapshot({"has_option": "F", "options": []}, befores=[before], osec=osec, recent=[]),
|
||||||
|
)
|
||||||
|
# 품목 전체 초기화 — 빈 dict 병합(=변경 없음)이 아니라 명시적 replace.
|
||||||
|
record_error = record_error or _save_snapshot_safe(st, product_no, "variants", {}, replace=True)
|
||||||
|
writes.audit_safe(st, actor=actor, action="delete_options", product_no=product_no,
|
||||||
|
result="SUCCESS", detail=f"삭제된 옵션: {names or '(없음)'}")
|
||||||
logger.info("카페24 상품 %s 옵션 삭제 (%s)", product_no, actor)
|
logger.info("카페24 상품 %s 옵션 삭제 (%s)", product_no, actor)
|
||||||
return {"ok": True, "option": _options_view({"has_option": "F"}), "variants": []}
|
return {"ok": True, "option": _options_view({"has_option": "F"}), "variants": [],
|
||||||
|
"record_warning": record_error}
|
||||||
|
|
||||||
|
|
||||||
@product_info_router.post("/products/{product_no}/options/image")
|
@product_info_router.post("/products/{product_no}/options/image")
|
||||||
@@ -464,13 +624,13 @@ def option_image_upload(
|
|||||||
try:
|
try:
|
||||||
path = products.upload_image_bytes(api.client, data)
|
path = products.upload_image_bytes(api.client, data)
|
||||||
except Cafe24Error as exc:
|
except Cafe24Error as exc:
|
||||||
st.log_audit(actor=actor, action="upload_option_image", product_no=product_no,
|
writes.audit_safe(st, actor=actor, action="upload_option_image", product_no=product_no,
|
||||||
result="FAIL", detail=str(exc))
|
result="FAIL", detail=str(exc))
|
||||||
raise _http_from_cafe24(exc) from exc
|
raise _http_from_cafe24(exc) from exc
|
||||||
if not path:
|
if not path:
|
||||||
raise HTTPException(status_code=502, detail="카페24가 업로드 경로를 돌려주지 않았습니다.")
|
raise HTTPException(status_code=502, detail="카페24가 업로드 경로를 돌려주지 않았습니다.")
|
||||||
st.log_audit(actor=actor, action="upload_option_image", product_no=product_no,
|
writes.audit_safe(st, actor=actor, action="upload_option_image", product_no=product_no,
|
||||||
result="SUCCESS", detail=path)
|
result="SUCCESS", detail=path)
|
||||||
return {"ok": True, "path": path}
|
return {"ok": True, "path": path}
|
||||||
|
|
||||||
|
|
||||||
@@ -483,18 +643,20 @@ def variant_delete(request: Request, product_no: int, variant_code: str) -> dict
|
|||||||
if not store.VARIANT_CODE_RE.match(code):
|
if not store.VARIANT_CODE_RE.match(code):
|
||||||
raise HTTPException(status_code=400, detail=f"품목코드 형식이 올바르지 않습니다: {code}")
|
raise HTTPException(status_code=400, detail=f"품목코드 형식이 올바르지 않습니다: {code}")
|
||||||
api = build_cafe24_api(st)
|
api = build_cafe24_api(st)
|
||||||
try:
|
with locked_json(st, product_no, actor=actor, purpose="품목 삭제"):
|
||||||
products.delete_variant(api.client, product_no, code)
|
try:
|
||||||
except Cafe24Error as exc:
|
products.delete_variant(api.client, product_no, code)
|
||||||
st.log_audit(actor=actor, action="delete_variant", product_no=product_no,
|
except Cafe24Error as exc:
|
||||||
result="FAIL", detail=f"{code}: {exc}")
|
writes.audit_safe(st, actor=actor, action="delete_variant", product_no=product_no,
|
||||||
raise _http_from_cafe24(exc) from exc
|
result="FAIL", detail=f"{code}: {exc}")
|
||||||
# 카페24 GET 은 한동안 삭제된 품목을 계속 돌려준다 — 스냅샷에 삭제 표식을 남겨 걸러낸다.
|
raise _http_from_cafe24(exc) from exc
|
||||||
st.save_write_snapshot(product_no, "variants", {code: {"_deleted": True}})
|
# 카페24 GET 은 한동안 삭제된 품목을 계속 돌려준다 — 삭제 표식을 남겨 걸러낸다.
|
||||||
st.log_audit(actor=actor, action="delete_variant", product_no=product_no,
|
# 표식은 이후 늦게 도착한 수정이 있어도 유지된다(store.merge_variant_snapshot).
|
||||||
result="SUCCESS", detail=code)
|
record_error = _save_snapshot_safe(st, product_no, "variants", {code: {"_deleted": True}})
|
||||||
|
writes.audit_safe(st, actor=actor, action="delete_variant", product_no=product_no,
|
||||||
|
result="SUCCESS", detail=code)
|
||||||
logger.info("카페24 상품 %s 품목 %s 삭제 (%s)", product_no, code, actor)
|
logger.info("카페24 상품 %s 품목 %s 삭제 (%s)", product_no, code, actor)
|
||||||
return {"ok": True, "variant_code": code}
|
return {"ok": True, "variant_code": code, "record_warning": record_error}
|
||||||
|
|
||||||
|
|
||||||
@product_info_router.put("/products/{product_no}/variants")
|
@product_info_router.put("/products/{product_no}/variants")
|
||||||
@@ -503,7 +665,14 @@ def variants_update(
|
|||||||
product_no: int,
|
product_no: int,
|
||||||
payload: dict[str, Any] = Body(default_factory=dict),
|
payload: dict[str, Any] = Body(default_factory=dict),
|
||||||
) -> dict[str, Any]:
|
) -> dict[str, Any]:
|
||||||
"""품목 여러 건의 자체코드 · 추가금액 · 진열 · 판매를 한 번에 바꾼다."""
|
"""품목 여러 건의 자체코드 · 추가금액 · 진열 · 판매 · 재고(사용·수량·품절표시)를 한 번에 바꾼다 — **행별 결과**.
|
||||||
|
|
||||||
|
응답 {"ok": 전부 성공?, "partial": 일부만?, "updated": {code: 반영된 값},
|
||||||
|
"failed": {code: 사유}, "unknown": {code: 사유}}
|
||||||
|
100건 묶음 중 일부가 실패해도 성공한 행은 성공으로 기록·표시한다(화면이 그 행을
|
||||||
|
다시 보내지 않게). 하나도 반영되지 않았으면 502.
|
||||||
|
진열·판매는 `CAFE24_SHOP_NOS` 의 다른 쇼핑몰에도 같은 값으로 보낸다 — 실패는 "shop_failed".
|
||||||
|
"""
|
||||||
st, user = require_store(request)
|
st, user = require_store(request)
|
||||||
actor = str(user.get("email") or "")
|
actor = str(user.get("email") or "")
|
||||||
rows = payload.get("rows")
|
rows = payload.get("rows")
|
||||||
@@ -517,31 +686,70 @@ def variants_update(
|
|||||||
raise HTTPException(status_code=400, detail="바뀐 값이 없습니다.")
|
raise HTTPException(status_code=400, detail="바뀐 값이 없습니다.")
|
||||||
|
|
||||||
api = build_cafe24_api(st)
|
api = build_cafe24_api(st)
|
||||||
try:
|
with locked_json(st, product_no, actor=actor, purpose="품목 수정"):
|
||||||
results = products.update_variants(api.client, product_no, requests)
|
results = products.update_variants(api.client, product_no, requests)
|
||||||
except Cafe24Error as exc:
|
|
||||||
st.log_audit(actor=actor, action="update_variants", product_no=product_no,
|
|
||||||
result="FAIL", detail=f"{len(requests)}건 실패: {exc}")
|
|
||||||
logger.warning("카페24 상품 %s 품목 수정 실패: %s", product_no, exc)
|
|
||||||
raise _http_from_cafe24(exc) from exc
|
|
||||||
|
|
||||||
# 우리가 보낸 값이 곧 현재값이다(카페24가 받아들였으므로). 응답에 담긴 값이 있으면
|
# 카페24가 받아들인 행만 현재값으로 기록한다. 응답에 담긴 값이 있으면 그것을 우선한다.
|
||||||
# 그것을 우선한다.
|
sent = {r["variant_code"]: {k: v for k, v in r.items() if k != "variant_code"} for r in requests}
|
||||||
by_code: dict[str, dict[str, Any]] = {}
|
by_code: dict[str, dict[str, Any]] = {}
|
||||||
for r in requests:
|
failed: dict[str, str] = {}
|
||||||
by_code[r["variant_code"]] = {k: v for k, v in r.items() if k != "variant_code"}
|
unknown: dict[str, str] = {}
|
||||||
for r in results:
|
for result in results:
|
||||||
code = str(r.get("variant_code") or "")
|
code = result["variant_code"]
|
||||||
if code in by_code:
|
if result["status"] == products.VARIANT_OK:
|
||||||
for key in ("custom_variant_code", "additional_amount", "display", "selling", "display_order"):
|
patch = dict(sent.get(code) or {})
|
||||||
if key in r and r[key] is not None:
|
for key in ("custom_variant_code", "additional_amount", "display", "selling", "display_order",
|
||||||
by_code[code][key] = r[key]
|
"use_inventory", "display_soldout", "quantity"):
|
||||||
st.save_write_snapshot(product_no, "variants", by_code)
|
value = (result.get("variant") or {}).get(key)
|
||||||
|
if value is not None:
|
||||||
|
patch[key] = value
|
||||||
|
by_code[code] = patch
|
||||||
|
elif result["status"] == products.VARIANT_UNKNOWN:
|
||||||
|
unknown[code] = result["error"]
|
||||||
|
else:
|
||||||
|
failed[code] = result["error"]
|
||||||
|
record_error = _save_snapshot_safe(st, product_no, "variants", by_code) if by_code else ""
|
||||||
|
|
||||||
|
# 멀티쇼핑몰: 진열·판매는 쇼핑몰마다 따로라 기본몰(1)에 반영된 행의 진열·판매만
|
||||||
|
# 다른 쇼핑몰에도 똑같이 보낸다. 추가금액(통화가 다름)·자체코드·순서는 보내지 않는다.
|
||||||
|
flags = [
|
||||||
|
{"variant_code": code, **{k: sent[code][k] for k in ("display", "selling") if k in sent[code]}}
|
||||||
|
for code in by_code if {"display", "selling"} & set(sent.get(code) or {})
|
||||||
|
]
|
||||||
|
shop_failed: dict[str, str] = {}
|
||||||
|
for shop in (shop_nos()[1:] if flags else []):
|
||||||
|
bad = [r for r in products.update_variants(api.client, product_no, flags, shop_no=shop)
|
||||||
|
if r["status"] != products.VARIANT_OK]
|
||||||
|
if bad:
|
||||||
|
shop_failed[str(shop)] = f"{len(bad)}건 — {bad[0]['error']}"
|
||||||
|
|
||||||
detail = "; ".join(
|
detail = "; ".join(
|
||||||
f"{code}: " + ", ".join(f"{k}={v}" for k, v in patch.items()) for code, patch in by_code.items()
|
f"{code}: " + ", ".join(f"{k}={v}" for k, v in patch.items()) for code, patch in by_code.items()
|
||||||
)
|
)
|
||||||
st.log_audit(actor=actor, action="update_variants", product_no=product_no,
|
if flags and len(shop_nos()) > 1:
|
||||||
result="SUCCESS", detail=detail[:900])
|
detail = f"[진열·판매 쇼핑몰 {','.join(map(str, shop_nos()))}] " + detail
|
||||||
logger.info("카페24 상품 %s 품목 %s건 수정 (%s)", product_no, len(by_code), actor)
|
if shop_failed:
|
||||||
return {"ok": True, "updated": {code: _variant_view({"variant_code": code, **patch})
|
detail += " / 다른 쇼핑몰 실패: " + "; ".join(f"{s}번 {e}" for s, e in shop_failed.items())
|
||||||
for code, patch in by_code.items()}}
|
if failed or unknown:
|
||||||
|
detail = (f"성공 {len(by_code)} / 실패 {len(failed)} / 결과 모름 {len(unknown)} — " + detail)
|
||||||
|
first = next(iter({**failed, **unknown}.values()), "")
|
||||||
|
detail += f" / 오류: {first}"
|
||||||
|
result_label = "SUCCESS" if not (failed or unknown) else ("PARTIAL" if by_code else "FAIL")
|
||||||
|
writes.audit_safe(st, actor=actor, action="update_variants", product_no=product_no,
|
||||||
|
result=result_label, detail=detail[:900])
|
||||||
|
if not by_code:
|
||||||
|
first = next(iter({**failed, **unknown}.values()), "알 수 없는 오류")
|
||||||
|
note = " (일부는 반영됐을 수 있습니다 — 다시 불러와 확인하세요)" if unknown else ""
|
||||||
|
logger.warning("카페24 상품 %s 품목 수정 실패: %s", product_no, first)
|
||||||
|
raise HTTPException(status_code=502, detail=f"{first}{note}")
|
||||||
|
logger.info("카페24 상품 %s 품목 %s건 수정 (%s, 실패 %s, 모름 %s)",
|
||||||
|
product_no, len(by_code), actor, len(failed), len(unknown))
|
||||||
|
return {
|
||||||
|
"ok": not (failed or unknown),
|
||||||
|
"partial": bool(failed or unknown),
|
||||||
|
"updated": {code: _variant_view({"variant_code": code, **patch}) for code, patch in by_code.items()},
|
||||||
|
"failed": failed,
|
||||||
|
"unknown": unknown,
|
||||||
|
"shop_failed": shop_failed,
|
||||||
|
"record_warning": record_error,
|
||||||
|
}
|
||||||
|
|||||||
@@ -50,10 +50,11 @@ PC/모바일은 구분하지 않는다 — 적용 시 `description` 만 쓰고
|
|||||||
from __future__ import annotations
|
from __future__ import annotations
|
||||||
|
|
||||||
import logging
|
import logging
|
||||||
|
from contextlib import contextmanager
|
||||||
from datetime import timedelta
|
from datetime import timedelta
|
||||||
from decimal import Decimal
|
from decimal import Decimal
|
||||||
from typing import Any
|
from typing import Any, Iterator
|
||||||
from urllib.parse import urlencode
|
from urllib.parse import quote, urlencode
|
||||||
|
|
||||||
from fastapi import APIRouter, Body, Form, HTTPException, Request
|
from fastapi import APIRouter, Body, Form, HTTPException, Request
|
||||||
from fastapi.responses import HTMLResponse, RedirectResponse
|
from fastapi.responses import HTMLResponse, RedirectResponse
|
||||||
@@ -61,7 +62,7 @@ from fastapi.responses import HTMLResponse, RedirectResponse
|
|||||||
from app.integrations.cafe24 import Cafe24Error, build_cafe24_api, products
|
from app.integrations.cafe24 import Cafe24Error, build_cafe24_api, products
|
||||||
from app.timezone import now_kst
|
from app.timezone import now_kst
|
||||||
|
|
||||||
from . import store
|
from . import store, writes
|
||||||
from .common import base_ctx, guard, read_lag_grace_minutes, require_store
|
from .common import base_ctx, guard, read_lag_grace_minutes, require_store
|
||||||
|
|
||||||
logger = logging.getLogger("cafe24.products")
|
logger = logging.getLogger("cafe24.products")
|
||||||
@@ -121,11 +122,22 @@ def _short_dt(value: Any) -> str:
|
|||||||
return text.replace("T", " ")[:16]
|
return text.replace("T", " ")[:16]
|
||||||
|
|
||||||
|
|
||||||
|
def _iso(value: Any) -> str:
|
||||||
|
"""datetime 이면 KST ISO, 아니면 문자열 그대로."""
|
||||||
|
if hasattr(value, "astimezone"):
|
||||||
|
from app.timezone import KST # noqa: WPS433
|
||||||
|
|
||||||
|
aware = value if value.tzinfo else value.replace(tzinfo=KST)
|
||||||
|
return aware.astimezone(KST).isoformat(timespec="seconds")
|
||||||
|
return str(value or "")
|
||||||
|
|
||||||
|
|
||||||
def _row_for_list(raw: dict[str, Any]) -> dict[str, Any]:
|
def _row_for_list(raw: dict[str, Any]) -> dict[str, Any]:
|
||||||
"""왼쪽 목록에 쓸 필드만 — 상품번호·상품명·진열·판매·최근수정."""
|
"""왼쪽 목록에 쓸 필드만 — 상품번호·대표 이미지·상품명·진열·판매·최근수정."""
|
||||||
normalized = products.normalize_product(raw)
|
normalized = products.normalize_product(raw)
|
||||||
return {
|
return {
|
||||||
"product_no": normalized["product_no"],
|
"product_no": normalized["product_no"],
|
||||||
|
"thumb": str(raw.get("tiny_image") or raw.get("detail_image") or ""),
|
||||||
"product_name": normalized["product_name"],
|
"product_name": normalized["product_name"],
|
||||||
"display": normalized["display"],
|
"display": normalized["display"],
|
||||||
"selling": normalized["selling"],
|
"selling": normalized["selling"],
|
||||||
@@ -187,30 +199,34 @@ def load_product(st: Any, api: Any, product_no: int) -> tuple[dict[str, Any], bo
|
|||||||
|
|
||||||
|
|
||||||
def resolve_description(
|
def resolve_description(
|
||||||
st: Any, product_no: int, cafe24_html: str
|
st: Any, product_no: int, cafe24_html: str, *, fetched_updated: object = None
|
||||||
) -> tuple[str, str, dict[str, Any] | None]:
|
) -> tuple[str, str, dict[str, Any] | None]:
|
||||||
"""(유효 HTML, 상태, 마지막 쓰기 revision). 상태는 store.SYNC_*."""
|
"""(유효 HTML, 상태, 마지막 확인된 쓰기). 상태는 store.SYNC_*.
|
||||||
grace = read_lag_grace_minutes()
|
|
||||||
since = now_kst() - timedelta(minutes=grace)
|
근거는 원격 반영이 확인된 쓰기(cafe24_write_attempts)뿐이다 — writes.resolve_effective.
|
||||||
last_write = st.latest_write_revision(product_no, since=since)
|
"""
|
||||||
if not last_write:
|
return writes.resolve_effective(st, product_no, cafe24_html, fetched_updated=fetched_updated)
|
||||||
return cafe24_html, store.SYNC_NONE, None
|
|
||||||
digests = st.revision_digests(product_no, since=since)
|
|
||||||
effective, state = store.resolve_description(
|
|
||||||
cafe24_html, last_write=last_write, known_digests=digests, grace_minutes=grace
|
|
||||||
)
|
|
||||||
return effective, state, last_write
|
|
||||||
|
|
||||||
|
|
||||||
def remember_write(st: Any, product_no: int, updated: dict[str, Any]) -> dict[str, Any]:
|
def remember_write(st: Any, product_no: int, updated: dict[str, Any]) -> dict[str, Any]:
|
||||||
"""PUT 응답(상품 dict)을 캐시·스냅샷에 남긴다. 정규화된 캐시 행을 돌려준다."""
|
"""PUT 응답(상품 dict)을 캐시·스냅샷에 남긴다. 정규화된 캐시 행을 돌려준다.
|
||||||
info = products.normalize_product(updated) if updated else {}
|
|
||||||
if info.get("product_no"):
|
카페24에는 이미 반영된 뒤라 기록 실패로 예외를 내지 않는다(로그만 — writes 참고).
|
||||||
st.upsert_products([info])
|
"""
|
||||||
st.save_write_snapshot(product_no, "product", store.product_snapshot(updated))
|
info, _error = writes.remember_product_write(st, product_no, updated)
|
||||||
return info
|
return info
|
||||||
|
|
||||||
|
|
||||||
|
@contextmanager
|
||||||
|
def locked_json(st: Any, product_no: int, *, actor: str, purpose: str) -> Iterator[Any]:
|
||||||
|
"""JSON API 용 상품 쓰기 잠금 — 못 잡으면 409, 스키마가 없으면 503."""
|
||||||
|
try:
|
||||||
|
with writes.write_lock(st, writes.product_lock_key(product_no), actor=actor, purpose=purpose) as lock:
|
||||||
|
yield lock
|
||||||
|
except (writes.WriteBusy, writes.WriteSetupError) as exc:
|
||||||
|
raise HTTPException(status_code=exc.http_status, detail=str(exc)) from exc
|
||||||
|
|
||||||
|
|
||||||
def _info(product: dict[str, Any]) -> dict[str, Any]:
|
def _info(product: dict[str, Any]) -> dict[str, Any]:
|
||||||
"""편집기·정보 패널 공용 상품 요약."""
|
"""편집기·정보 패널 공용 상품 요약."""
|
||||||
info = products.normalize_product(product) if product else {}
|
info = products.normalize_product(product) if product else {}
|
||||||
@@ -245,11 +261,27 @@ def _editor_ctx(st: Any, product_no: int) -> dict[str, Any]:
|
|||||||
product, scalar_stale = load_product(st, api, product_no)
|
product, scalar_stale = load_product(st, api, product_no)
|
||||||
desc = products.descriptions_from_product(product)
|
desc = products.descriptions_from_product(product)
|
||||||
st.upsert_products([products.normalize_product(product)])
|
st.upsert_products([products.normalize_product(product)])
|
||||||
html_effective, sync_state, last_write = resolve_description(st, product_no, desc.description)
|
html_effective, sync_state, last_write = resolve_description(
|
||||||
|
st, product_no, desc.description, fetched_updated=product.get("updated_date")
|
||||||
|
)
|
||||||
except Cafe24Error as exc:
|
except Cafe24Error as exc:
|
||||||
error = str(exc)
|
error = str(exc)
|
||||||
logger.warning("카페24 상품 %s 조회 실패: %s", product_no, exc)
|
logger.warning("카페24 상품 %s 조회 실패: %s", product_no, exc)
|
||||||
|
|
||||||
|
# 반영 여부를 모르는 이전 시도 — 편집기 위에 확정 버튼과 함께 보여준다.
|
||||||
|
# (REMOTE_OK 는 반영이 확인된 것이라 여기 올리지 않는다 — 기록은 자동 복구된다.)
|
||||||
|
since = now_kst() - timedelta(minutes=read_lag_grace_minutes())
|
||||||
|
open_attempts = [
|
||||||
|
{**a, "label": writes.describe_attempt(a),
|
||||||
|
"status_label": "결과 모름" if a.get("status") == store.ATTEMPT_UNKNOWN else "중단됨"}
|
||||||
|
for a in st.open_attempts(product_no, since=since)
|
||||||
|
if a.get("status") in (store.ATTEMPT_STARTED, store.ATTEMPT_UNKNOWN)
|
||||||
|
]
|
||||||
|
revisions = [
|
||||||
|
{**r, "type_label": store.REVISION_LABELS.get(str(r.get("revision_type") or ""), "")}
|
||||||
|
for r in st.list_revisions(product_no, limit=20)
|
||||||
|
]
|
||||||
|
|
||||||
return {
|
return {
|
||||||
"product_no": product_no,
|
"product_no": product_no,
|
||||||
# 고객이 보는 상세페이지 주소 (CAFE24_SHOP_URL, 없으면 카페24 기본 도메인)
|
# 고객이 보는 상세페이지 주소 (CAFE24_SHOP_URL, 없으면 카페24 기본 도메인)
|
||||||
@@ -268,9 +300,10 @@ def _editor_ctx(st: Any, product_no: int) -> dict[str, Any]:
|
|||||||
"sync_pending": sync_state == store.SYNC_PENDING,
|
"sync_pending": sync_state == store.SYNC_PENDING,
|
||||||
"sync_external": sync_state == store.SYNC_EXTERNAL,
|
"sync_external": sync_state == store.SYNC_EXTERNAL,
|
||||||
"scalar_stale": scalar_stale,
|
"scalar_stale": scalar_stale,
|
||||||
"last_write_at": _short_dt(last_write.get("created_at").isoformat() if last_write and last_write.get("created_at") else ""),
|
"last_write_at": _short_dt(_iso(last_write.get("created_at")) if last_write else ""),
|
||||||
"last_write_by": (last_write or {}).get("created_by") or "",
|
"last_write_by": (last_write or {}).get("created_by") or "",
|
||||||
"revisions": st.list_revisions(product_no, limit=20),
|
"revisions": revisions,
|
||||||
|
"open_attempts": open_attempts,
|
||||||
"editor_error": error,
|
"editor_error": error,
|
||||||
"option_display_types": store.OPTION_DISPLAY_LABELS,
|
"option_display_types": store.OPTION_DISPLAY_LABELS,
|
||||||
}
|
}
|
||||||
@@ -296,6 +329,13 @@ def product_list(request: Request) -> HTMLResponse:
|
|||||||
error = ""
|
error = ""
|
||||||
try:
|
try:
|
||||||
raw_rows, truncated = products.list_all_products(api.client, product_name=keyword)
|
raw_rows, truncated = products.list_all_products(api.client, product_name=keyword)
|
||||||
|
# 목록 API 도 쓰기 직후 한동안 예전 값을 준다 — 진열/판매 등을 최근 쓰기로 보정한다.
|
||||||
|
try:
|
||||||
|
snapshots = st.get_recent_product_snapshots(read_lag_grace_minutes())
|
||||||
|
except Exception: # noqa: BLE001 — 보정 실패는 목록 표시를 막지 않는다
|
||||||
|
logger.exception("카페24 최근 쓰기 스냅샷 조회 실패")
|
||||||
|
snapshots = {}
|
||||||
|
raw_rows = store.overlay_product_rows(raw_rows, snapshots, grace_minutes=read_lag_grace_minutes())
|
||||||
st.upsert_products([products.normalize_product(r) for r in raw_rows])
|
st.upsert_products([products.normalize_product(r) for r in raw_rows])
|
||||||
total = len(raw_rows)
|
total = len(raw_rows)
|
||||||
rows = [_row_for_list(r) for r in raw_rows]
|
rows = [_row_for_list(r) for r in raw_rows]
|
||||||
@@ -384,33 +424,34 @@ def product_rename(
|
|||||||
raise HTTPException(status_code=400, detail=f"상품명은 {NAME_MAX}자를 넘을 수 없습니다.")
|
raise HTTPException(status_code=400, detail=f"상품명은 {NAME_MAX}자를 넘을 수 없습니다.")
|
||||||
|
|
||||||
api = build_cafe24_api(st)
|
api = build_cafe24_api(st)
|
||||||
try:
|
with locked_json(st, product_no, actor=actor, purpose="상품명 변경"):
|
||||||
current, _ = load_product(st, api, product_no)
|
try:
|
||||||
except Cafe24Error as exc:
|
current, _ = load_product(st, api, product_no)
|
||||||
st.log_audit(
|
except Cafe24Error as exc:
|
||||||
actor=actor, action="rename_product", product_no=product_no,
|
writes.audit_safe(
|
||||||
result="FAIL", detail=f"현재값 조회 실패: {exc}",
|
st, actor=actor, action="rename_product", product_no=product_no,
|
||||||
)
|
result="FAIL", detail=f"현재값 조회 실패: {exc}",
|
||||||
raise HTTPException(status_code=502, detail=f"카페24 현재값을 읽지 못했습니다: {exc}") from exc
|
)
|
||||||
|
raise HTTPException(status_code=502, detail=f"카페24 현재값을 읽지 못했습니다: {exc}") from exc
|
||||||
|
|
||||||
before = str(current.get("product_name") or "")
|
before = str(current.get("product_name") or "")
|
||||||
if before == name:
|
if before == name:
|
||||||
return {"ok": True, "product_name": before, "changed": False}
|
return {"ok": True, "product_name": before, "changed": False}
|
||||||
|
|
||||||
try:
|
try:
|
||||||
updated = products.update_product(api.client, product_no, product_name=name)
|
updated = products.update_product(api.client, product_no, product_name=name)
|
||||||
except Cafe24Error as exc:
|
except Cafe24Error as exc:
|
||||||
st.log_audit(
|
writes.audit_safe(
|
||||||
actor=actor, action="rename_product", product_no=product_no,
|
st, actor=actor, action="rename_product", product_no=product_no,
|
||||||
result="FAIL", detail=f"'{before}' → '{name}' 실패: {exc}",
|
result="FAIL", detail=f"'{before}' → '{name}' 실패: {exc}",
|
||||||
)
|
)
|
||||||
logger.warning("카페24 상품 %s 이름 변경 실패: %s", product_no, exc)
|
logger.warning("카페24 상품 %s 이름 변경 실패: %s", product_no, exc)
|
||||||
raise HTTPException(status_code=502, detail=str(exc)) from exc
|
raise HTTPException(status_code=502, detail=str(exc)) from exc
|
||||||
|
|
||||||
info = remember_write(st, product_no, updated)
|
info = remember_write(st, product_no, updated)
|
||||||
after = str(info.get("product_name") or name)
|
after = str(info.get("product_name") or name)
|
||||||
st.log_audit(
|
writes.audit_safe(
|
||||||
actor=actor, action="rename_product", product_no=product_no,
|
st, actor=actor, action="rename_product", product_no=product_no,
|
||||||
result="SUCCESS", detail=f"'{before}' → '{after}'",
|
result="SUCCESS", detail=f"'{before}' → '{after}'",
|
||||||
)
|
)
|
||||||
logger.info("카페24 상품 %s 이름 변경 (%s)", product_no, actor)
|
logger.info("카페24 상품 %s 이름 변경 (%s)", product_no, actor)
|
||||||
@@ -442,31 +483,32 @@ def product_status(
|
|||||||
want = bool(payload.get("value"))
|
want = bool(payload.get("value"))
|
||||||
|
|
||||||
api = build_cafe24_api(st)
|
api = build_cafe24_api(st)
|
||||||
try:
|
with locked_json(st, product_no, actor=actor, purpose="진열/판매 변경"):
|
||||||
updated = products.update_product(api.client, product_no, **{field: want})
|
|
||||||
except Cafe24Error as exc:
|
|
||||||
st.log_audit(
|
|
||||||
actor=actor, action=f"set_{field}", product_no=product_no,
|
|
||||||
result="FAIL", detail=f"{want} 설정 실패: {exc}",
|
|
||||||
)
|
|
||||||
logger.warning("카페24 상품 %s %s 변경 실패: %s", product_no, field, exc)
|
|
||||||
raise HTTPException(status_code=502, detail=str(exc)) from exc
|
|
||||||
|
|
||||||
# 응답이 상품 dict 면 그것이 곧 현재 상태다. 모양이 다르면(방어) 다시 조회한다.
|
|
||||||
if "display" not in updated or "selling" not in updated:
|
|
||||||
try:
|
try:
|
||||||
updated, _ = load_product(st, api, product_no)
|
updated = products.update_product(api.client, product_no, **{field: want})
|
||||||
except Cafe24Error as exc: # 쓰기는 됐다 — 화면만 요청값으로 맞춘다.
|
except Cafe24Error as exc:
|
||||||
logger.warning("카페24 상품 %s 상태 재조회 실패: %s", product_no, exc)
|
writes.audit_safe(
|
||||||
updated = {}
|
st, actor=actor, action=f"set_{field}", product_no=product_no,
|
||||||
|
result="FAIL", detail=f"{want} 설정 실패: {exc}",
|
||||||
|
)
|
||||||
|
logger.warning("카페24 상품 %s %s 변경 실패: %s", product_no, field, exc)
|
||||||
|
raise HTTPException(status_code=502, detail=str(exc)) from exc
|
||||||
|
|
||||||
info = remember_write(st, product_no, updated)
|
# 응답이 상품 dict 면 그것이 곧 현재 상태다. 모양이 다르면(방어) 다시 조회한다.
|
||||||
|
if "display" not in updated or "selling" not in updated:
|
||||||
|
try:
|
||||||
|
updated, _ = load_product(st, api, product_no)
|
||||||
|
except Cafe24Error as exc: # 쓰기는 됐다 — 화면만 요청값으로 맞춘다.
|
||||||
|
logger.warning("카페24 상품 %s 상태 재조회 실패: %s", product_no, exc)
|
||||||
|
updated = {}
|
||||||
|
|
||||||
|
info = remember_write(st, product_no, updated)
|
||||||
state = {
|
state = {
|
||||||
"display": bool(info.get("display", want if field == "display" else True)),
|
"display": bool(info.get("display", want if field == "display" else True)),
|
||||||
"selling": bool(info.get("selling", want if field == "selling" else True)),
|
"selling": bool(info.get("selling", want if field == "selling" else True)),
|
||||||
}
|
}
|
||||||
st.log_audit(
|
writes.audit_safe(
|
||||||
actor=actor, action=f"set_{field}", product_no=product_no,
|
st, actor=actor, action=f"set_{field}", product_no=product_no,
|
||||||
result="SUCCESS", detail=f"{field}={'T' if want else 'F'}",
|
result="SUCCESS", detail=f"{field}={'T' if want else 'F'}",
|
||||||
)
|
)
|
||||||
logger.info("카페24 상품 %s %s=%s (%s)", product_no, field, want, actor)
|
logger.info("카페24 상품 %s %s=%s (%s)", product_no, field, want, actor)
|
||||||
@@ -479,6 +521,95 @@ def product_redirect(request: Request, product_no: int):
|
|||||||
return RedirectResponse(url=f"/cafe24/?selected={product_no}", status_code=303)
|
return RedirectResponse(url=f"/cafe24/?selected={product_no}", status_code=303)
|
||||||
|
|
||||||
|
|
||||||
|
def _back_url(product_no: int, list_query: str) -> str:
|
||||||
|
"""적용 후 돌아갈 주소 — 검색·필터를 유지한 채 같은 상품이 선택된 화면."""
|
||||||
|
base = f"/cafe24/?{list_query}" if list_query else f"/cafe24/?selected={product_no}"
|
||||||
|
return base if f"selected={product_no}" in base else f"{base}&selected={product_no}"
|
||||||
|
|
||||||
|
|
||||||
|
def _with_msg(back: str, *, msg: str = "", err: str = "") -> str:
|
||||||
|
"""안내 문구를 쿼리에 붙인다. 문구 안의 &·#·% 가 주소를 깨지 않게 인코딩한다."""
|
||||||
|
key, text = ("err", err) if err else ("msg", msg)
|
||||||
|
return f"{back}&{key}={quote(text, safe='')}"
|
||||||
|
|
||||||
|
|
||||||
|
def _run_description_write(
|
||||||
|
st: Any,
|
||||||
|
user: dict[str, Any],
|
||||||
|
product_no: int,
|
||||||
|
*,
|
||||||
|
html: str,
|
||||||
|
base_fingerprint: str,
|
||||||
|
memo: str,
|
||||||
|
list_query: str,
|
||||||
|
origin: str,
|
||||||
|
action: str,
|
||||||
|
target_revision_id: int | None = None,
|
||||||
|
) -> RedirectResponse:
|
||||||
|
"""즉시 적용·버전 복원 공용 — writes.write_product 를 잠금 안에서 부르고 결과를 안내한다."""
|
||||||
|
actor = str(user.get("email") or "")
|
||||||
|
back = _back_url(product_no, list_query)
|
||||||
|
verb = "복원" if origin == store.ORIGIN_ROLLBACK else "적용"
|
||||||
|
api = build_cafe24_api(st)
|
||||||
|
try:
|
||||||
|
with writes.write_lock(
|
||||||
|
st, writes.product_lock_key(product_no), actor=actor, purpose=f"상세설명 {verb}"
|
||||||
|
) as lock:
|
||||||
|
outcome = writes.write_product(
|
||||||
|
st, api, product_no,
|
||||||
|
lock=lock, origin=origin, actor=actor, html=html,
|
||||||
|
base_fingerprint=base_fingerprint, target_revision_id=target_revision_id,
|
||||||
|
memo=memo, skip_if_same=True,
|
||||||
|
)
|
||||||
|
except (writes.WriteSetupError, writes.WriteBusy, writes.WriteBlocked, writes.WriteConflict) as exc:
|
||||||
|
detail = "충돌 — 편집 중 카페24 값이 변경됨" if isinstance(exc, writes.WriteConflict) else str(exc)
|
||||||
|
writes.audit_safe(st, actor=actor, action=action, product_no=product_no,
|
||||||
|
revision_id=exc.backup_id or None, result="FAIL", detail=detail)
|
||||||
|
return RedirectResponse(url=_with_msg(back, err=str(exc)), status_code=303)
|
||||||
|
except writes.RemoteWriteUnknown as exc:
|
||||||
|
writes.audit_safe(st, actor=actor, action=action, product_no=product_no,
|
||||||
|
revision_id=exc.backup_id or None, result="UNKNOWN",
|
||||||
|
detail=f"시도 #{exc.attempt_id} 반영 여부 모름: {exc}")
|
||||||
|
logger.warning("카페24 상품 %s %s 결과 모름(시도 #%s): %s", product_no, verb, exc.attempt_id, exc)
|
||||||
|
return RedirectResponse(url=_with_msg(back, err=(
|
||||||
|
f"카페24 응답을 받지 못해 {verb} 여부를 알 수 없습니다({exc}). 다시 {verb}하지 말고 "
|
||||||
|
f"쇼핑몰에서 확인한 뒤 편집기 위 안내에서 결과를 확정하세요. "
|
||||||
|
f"(직전 내용은 버전 {exc.backup_id} 로 보관됨)")), status_code=303)
|
||||||
|
except writes.RemoteWriteFailed as exc:
|
||||||
|
writes.audit_safe(st, actor=actor, action=action, product_no=product_no,
|
||||||
|
revision_id=exc.backup_id or None, result="FAIL", detail=str(exc))
|
||||||
|
logger.warning("카페24 상품 %s %s 실패: %s", product_no, verb, exc)
|
||||||
|
return RedirectResponse(url=_with_msg(back, err=(
|
||||||
|
f"{verb}에 실패했습니다: {exc} (직전 내용은 버전 {exc.backup_id} 로 보관됨)")), status_code=303)
|
||||||
|
except Cafe24Error as exc:
|
||||||
|
writes.audit_safe(st, actor=actor, action=action, product_no=product_no,
|
||||||
|
result="FAIL", detail=f"현재값 조회 실패: {exc}")
|
||||||
|
return RedirectResponse(url=_with_msg(back, err=f"카페24 현재값을 읽지 못해 중단했습니다: {exc}"),
|
||||||
|
status_code=303)
|
||||||
|
|
||||||
|
if not outcome.changed:
|
||||||
|
return RedirectResponse(url=_with_msg(back, msg=f"변경된 내용이 없어 {verb}하지 않았습니다."), status_code=303)
|
||||||
|
|
||||||
|
detail = (
|
||||||
|
f"{len(html)}자 {verb} (백업 {outcome.backup_id}, 시도 #{outcome.attempt_id}, 모바일 PC와 동일 유지, "
|
||||||
|
f"카페24 재조회 {'확인' if outcome.confirmed else '지연 — 마지막 적용값 표시'})"
|
||||||
|
)
|
||||||
|
if target_revision_id:
|
||||||
|
detail += f" / 원본 버전 {target_revision_id}"
|
||||||
|
if outcome.record_error:
|
||||||
|
detail += f" / 기록 실패(자동 복구 예정): {outcome.record_error}"
|
||||||
|
writes.audit_safe(st, actor=actor, action=action, product_no=product_no,
|
||||||
|
revision_id=outcome.revision_id or None, result="SUCCESS", detail=detail)
|
||||||
|
logger.info("카페24 상품 %s 상세설명 %s (%s, 재조회 확인=%s)", product_no, verb, actor, outcome.confirmed)
|
||||||
|
note = "" if outcome.confirmed else " 카페24 관리자 API 반영은 잠시 늦을 수 있어 방금 적용한 내용을 표시합니다."
|
||||||
|
if outcome.record_error:
|
||||||
|
note += " ※ 카페24에는 반영됐지만 버전 기록 저장에 실패했습니다 — 자동으로 복구하니 다시 적용하지 마세요."
|
||||||
|
return RedirectResponse(
|
||||||
|
url=_with_msg(back, msg=f"카페24에 {verb}했습니다. 직전 내용은 버전 {outcome.backup_id} 로 보관됩니다.{note}"),
|
||||||
|
status_code=303,
|
||||||
|
)
|
||||||
|
|
||||||
|
|
||||||
@products_router.post("/products/{product_no}/apply")
|
@products_router.post("/products/{product_no}/apply")
|
||||||
def product_apply(
|
def product_apply(
|
||||||
request: Request,
|
request: Request,
|
||||||
@@ -490,125 +621,165 @@ def product_apply(
|
|||||||
):
|
):
|
||||||
"""편집한 HTML 을 카페24에 즉시 적용한다.
|
"""편집한 HTML 을 카페24에 즉시 적용한다.
|
||||||
|
|
||||||
순서를 지키는 것이 이 함수의 핵심이다.
|
순서(writes.write_product): 상품 잠금 → 카페24 현재값 재조회(로컬 값을 현재값으로
|
||||||
1) 카페24에서 **현재** HTML 을 다시 읽는다(로컬 값을 현재값으로 믿지 않는다)
|
믿지 않는다) → 결과 모르는 이전 시도 확인 → 유효 현재값(읽기 지연 보정) → BACKUP
|
||||||
2) 읽기 지연을 판정해 **유효 현재값**을 정한다(예전 값을 돌려주는 중이면
|
← 유일한 복구 수단 → 지문 대조(충돌 거부) → 시도 기록 → PUT → 버전·스냅샷 기록.
|
||||||
우리 마지막 쓰기가 현재값이다)
|
|
||||||
3) 그 값으로 BACKUP 버전을 남긴다 ← 유일한 복구 수단
|
|
||||||
4) 편집 시작 시점의 지문과 비교해 충돌이면 거부한다
|
|
||||||
5) 쓰고, 스냅샷·MANUAL 버전·감사로그를 남긴다
|
|
||||||
|
|
||||||
PC/모바일을 구분하지 않는다 — 두 필드에 같은 HTML 을 쓴다. 분리 사용 상품의
|
PC/모바일을 구분하지 않는다 — description 만 쓰고 separated_mobile_description="F".
|
||||||
모바일 내용이 PC 와 달랐다면 덮어쓰기 전에 그 내용도 BACKUP 으로 남긴다.
|
분리 사용 상품의 모바일 내용이 PC 와 달랐다면 덮어쓰기 전에 그 내용도 BACKUP 으로 남긴다.
|
||||||
"""
|
"""
|
||||||
checked = guard(request)
|
checked = guard(request)
|
||||||
if not isinstance(checked, tuple):
|
if not isinstance(checked, tuple):
|
||||||
return checked
|
return checked
|
||||||
st, user = checked
|
st, user = checked
|
||||||
|
|
||||||
actor = str(user.get("email") or "")
|
|
||||||
# 적용 후에는 검색·필터를 유지한 채 같은 상품이 선택된 화면으로 돌아온다.
|
|
||||||
base = f"/cafe24/?{list_query}" if list_query else f"/cafe24/?selected={product_no}"
|
|
||||||
back = base if f"selected={product_no}" in base else f"{base}&selected={product_no}"
|
|
||||||
|
|
||||||
# 화면에서 보던 그대로(정리된 소스)를 카페24에 반영한다. 한글 이미지 경로는
|
# 화면에서 보던 그대로(정리된 소스)를 카페24에 반영한다. 한글 이미지 경로는
|
||||||
# 원래의 퍼센트 인코딩으로 되돌린다.
|
# 원래의 퍼센트 인코딩으로 되돌린다.
|
||||||
submitted = store.format_html(store.encode_html_urls(html or ""))
|
submitted = store.format_html(store.encode_html_urls(html or ""))
|
||||||
if not submitted.strip():
|
if not submitted.strip():
|
||||||
return RedirectResponse(
|
return RedirectResponse(
|
||||||
url=f"{back}&err=내용이 비어 있습니다. 상세페이지를 비우려면 카페24 관리자에서 하세요.",
|
url=_with_msg(_back_url(product_no, list_query),
|
||||||
|
err="내용이 비어 있습니다. 상세페이지를 비우려면 카페24 관리자에서 하세요."),
|
||||||
status_code=303,
|
status_code=303,
|
||||||
)
|
)
|
||||||
|
return _run_description_write(
|
||||||
|
st, user, product_no,
|
||||||
|
html=submitted, base_fingerprint=base_fingerprint, memo=memo, list_query=list_query,
|
||||||
|
origin=store.ORIGIN_MANUAL, action="apply_description",
|
||||||
|
)
|
||||||
|
|
||||||
api = build_cafe24_api(st)
|
|
||||||
|
# ════════════════════════════════════════════════════════════
|
||||||
|
# 버전 이력 — 원문 확인 · 선택 복원
|
||||||
|
# 자동 복원(예약 종료 후 되돌리기)은 쓰지 않는다. 사람이 버전을 골라 누를 때만
|
||||||
|
# 정상 쓰기 경로(잠금·백업·지문 대조·시도 기록)로 한 번 적용하고 ROLLBACK 을 남긴다.
|
||||||
|
# ════════════════════════════════════════════════════════════
|
||||||
|
def _revision_for(st: Any, product_no: int, revision_id: int) -> dict[str, Any]:
|
||||||
|
"""이 쇼핑몰·이 상품의 버전만 돌려준다. 아니면 404(다른 상품 버전을 주소로 못 끌어온다)."""
|
||||||
|
from app.integrations.cafe24 import load_config # noqa: WPS433
|
||||||
|
|
||||||
|
revision = st.get_revision(revision_id)
|
||||||
|
if not revision or int(revision.get("product_no") or 0) != int(product_no):
|
||||||
|
raise HTTPException(status_code=404, detail="이 상품의 버전을 찾을 수 없습니다.")
|
||||||
|
mall = load_config().mall_id
|
||||||
|
rev_mall = str(revision.get("mall_id") or "")
|
||||||
|
# mall_id 가 빈 행은 005 이전 기록이다 — cafe24_db 는 쇼핑몰 1개 전용이라 같은 쇼핑몰로 본다.
|
||||||
|
if rev_mall and mall and rev_mall != mall:
|
||||||
|
raise HTTPException(status_code=404, detail="다른 쇼핑몰의 버전입니다.")
|
||||||
|
if int(revision.get("shop_no") or 1) != 1:
|
||||||
|
raise HTTPException(status_code=404, detail="다른 멀티쇼핑몰(shop_no)의 버전입니다.")
|
||||||
|
return revision
|
||||||
|
|
||||||
|
|
||||||
|
@products_router.get("/products/{product_no}/revisions/{revision_id}")
|
||||||
|
def revision_detail(request: Request, product_no: int, revision_id: int) -> dict[str, Any]:
|
||||||
|
"""버전 원문(JSON). 화면은 textContent 로만 넣는다(HTML 로 해석하지 않는다)."""
|
||||||
|
st, _user = require_store(request)
|
||||||
|
revision = _revision_for(st, product_no, revision_id)
|
||||||
|
body = str(revision.get("html_content") or "")
|
||||||
|
rtype = str(revision.get("revision_type") or "")
|
||||||
|
return {
|
||||||
|
"ok": True,
|
||||||
|
"revision": {
|
||||||
|
"id": revision.get("id"),
|
||||||
|
"product_no": revision.get("product_no"),
|
||||||
|
"revision_type": rtype,
|
||||||
|
"type_label": store.REVISION_LABELS.get(rtype, rtype),
|
||||||
|
"source": revision.get("source") or "",
|
||||||
|
"created_at": revision.get("created_at") or "",
|
||||||
|
"created_by": revision.get("created_by") or "",
|
||||||
|
"memo": revision.get("memo") or "",
|
||||||
|
"length": len(body),
|
||||||
|
# 편집기와 같은 표시(이미지 경로의 %EC… 를 한글로). 복원은 저장된 원문 그대로 쓴다.
|
||||||
|
"html": store.decode_html_urls(body),
|
||||||
|
},
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
@products_router.post("/products/{product_no}/revisions/{revision_id}/restore")
|
||||||
|
def revision_restore(
|
||||||
|
request: Request,
|
||||||
|
product_no: int,
|
||||||
|
revision_id: int,
|
||||||
|
base_fingerprint: str = Form(""),
|
||||||
|
memo: str = Form(""),
|
||||||
|
list_query: str = Form(""),
|
||||||
|
):
|
||||||
|
"""고른 버전을 카페24에 다시 적용한다(ROLLBACK). 즉시 적용과 같은 경로·같은 보호."""
|
||||||
|
checked = guard(request)
|
||||||
|
if not isinstance(checked, tuple):
|
||||||
|
return checked
|
||||||
|
st, user = checked
|
||||||
|
back = _back_url(product_no, list_query)
|
||||||
try:
|
try:
|
||||||
current = products.fetch_descriptions(api.client, product_no)
|
revision = _revision_for(st, product_no, revision_id)
|
||||||
except Cafe24Error as exc:
|
except HTTPException as exc:
|
||||||
st.log_audit(
|
return RedirectResponse(url=_with_msg(back, err=str(exc.detail)), status_code=303)
|
||||||
actor=actor, action="apply_description", product_no=product_no,
|
body = str(revision.get("html_content") or "")
|
||||||
result="FAIL", detail=f"현재값 조회 실패: {exc}",
|
if not body.strip():
|
||||||
)
|
return RedirectResponse(url=_with_msg(back, err="내용이 빈 버전은 복원할 수 없습니다."), status_code=303)
|
||||||
return RedirectResponse(url=f"{back}&err=카페24 현재값을 읽지 못해 중단했습니다: {exc}", status_code=303)
|
if not base_fingerprint:
|
||||||
|
# 편집기가 본 현재값 없이 복원하면 그 사이 바뀐 내용을 모르고 덮는다.
|
||||||
# 읽기 지연 판정 — 카페24가 아직 예전 값을 돌려주면 우리 마지막 쓰기가 현재값이다.
|
|
||||||
effective, sync_state, _ = resolve_description(st, product_no, current.description)
|
|
||||||
pending = sync_state == store.SYNC_PENDING
|
|
||||||
|
|
||||||
backup_id = st.add_revision(
|
|
||||||
product_no=product_no,
|
|
||||||
html_content=effective,
|
|
||||||
revision_type=store.REVISION_BACKUP,
|
|
||||||
memo="적용 직전 자동 백업" + (" (카페24 읽기 지연 — 마지막 적용값 기준)" if pending else ""),
|
|
||||||
created_by=actor,
|
|
||||||
)
|
|
||||||
# 모바일 내용이 PC 와 달랐다면 그것도 따로 남긴다. 아래에서 모바일을 PC 와 같게
|
|
||||||
# 덮어쓰므로, 백업하지 않으면 그 내용을 되찾을 방법이 없다.
|
|
||||||
if current.mobile_description and current.mobile_description != current.description:
|
|
||||||
st.add_revision(
|
|
||||||
product_no=product_no,
|
|
||||||
html_content=current.mobile_description,
|
|
||||||
revision_type=store.REVISION_BACKUP,
|
|
||||||
memo="적용 직전 자동 백업 (모바일 — PC와 달랐던 내용)",
|
|
||||||
created_by=actor,
|
|
||||||
)
|
|
||||||
|
|
||||||
if base_fingerprint and base_fingerprint != store.fingerprint(effective):
|
|
||||||
st.log_audit(
|
|
||||||
actor=actor, action="apply_description", product_no=product_no,
|
|
||||||
revision_id=backup_id, result="FAIL", detail="충돌 — 편집 중 카페24 값이 변경됨",
|
|
||||||
)
|
|
||||||
return RedirectResponse(
|
return RedirectResponse(
|
||||||
url=f"{back}&err=편집하는 동안 카페24 값이 변경되었습니다. 새로고침해 현재 내용을 확인한 뒤 다시 적용하세요.",
|
url=_with_msg(back, err="편집기를 새로고침한 뒤 버전 이력에서 다시 복원하세요."), status_code=303
|
||||||
status_code=303,
|
|
||||||
)
|
)
|
||||||
|
note = f"버전 {revision_id} 복원" + (f" — {memo.strip()}" if memo.strip() else "")
|
||||||
|
return _run_description_write(
|
||||||
|
st, user, product_no,
|
||||||
|
html=body, base_fingerprint=base_fingerprint, memo=note, list_query=list_query,
|
||||||
|
origin=store.ORIGIN_ROLLBACK, action="restore_revision", target_revision_id=int(revision_id),
|
||||||
|
)
|
||||||
|
|
||||||
if submitted == effective:
|
|
||||||
return RedirectResponse(url=f"{back}&msg=변경된 내용이 없어 적용하지 않았습니다.", status_code=303)
|
# ════════════════════════════════════════════════════════════
|
||||||
|
# 반영 여부를 모르는 시도 — 사람이 쇼핑몰을 확인하고 확정한다
|
||||||
|
# ════════════════════════════════════════════════════════════
|
||||||
|
@products_router.post("/products/{product_no}/attempts/{attempt_id}/resolve")
|
||||||
|
def attempt_resolve(
|
||||||
|
request: Request,
|
||||||
|
product_no: int,
|
||||||
|
attempt_id: int,
|
||||||
|
result: str = Form(""),
|
||||||
|
list_query: str = Form(""),
|
||||||
|
):
|
||||||
|
"""applied = 반영됨(그 내용을 마지막 쓰기로 기록) / not_applied = 반영 안 됨(닫기).
|
||||||
|
|
||||||
|
예약에서 난 시도면 그 예약도 함께 완료/실패로 바꾼다. 다시 적용하는 것은 사람이
|
||||||
|
편집기에서 한다(자동 재적용 없음).
|
||||||
|
"""
|
||||||
|
checked = guard(request)
|
||||||
|
if not isinstance(checked, tuple):
|
||||||
|
return checked
|
||||||
|
st, user = checked
|
||||||
|
actor = str(user.get("email") or "")
|
||||||
|
back = _back_url(product_no, list_query)
|
||||||
|
if result not in ("applied", "not_applied"):
|
||||||
|
return RedirectResponse(url=_with_msg(back, err="확정할 결과를 고르세요."), status_code=303)
|
||||||
|
open_states = (store.ATTEMPT_STARTED, store.ATTEMPT_UNKNOWN)
|
||||||
try:
|
try:
|
||||||
# mobile_description 은 보내지 않는다 — update_descriptions 가
|
with writes.write_lock(st, writes.product_lock_key(product_no), actor=actor, purpose="적용 결과 확정"):
|
||||||
# separated_mobile_description="F" 로 "PC 상세설명과 동일"을 강제하고
|
attempt = st.get_attempt(attempt_id)
|
||||||
# 카페24가 모바일 값을 자동으로 맞춰준다(모바일도 항상 PC와 같다).
|
if (not attempt or int(attempt.get("product_no") or 0) != int(product_no)
|
||||||
updated = products.update_descriptions(api.client, product_no, description=submitted)
|
or attempt.get("status") not in open_states):
|
||||||
except Cafe24Error as exc:
|
return RedirectResponse(url=_with_msg(back, err="이미 확정됐거나 없는 시도입니다."), status_code=303)
|
||||||
st.log_audit(
|
schedule_id = attempt.get("schedule_id")
|
||||||
actor=actor, action="apply_description", product_no=product_no,
|
if result == "applied":
|
||||||
revision_id=backup_id, result="FAIL", detail=str(exc),
|
st.update_attempt(attempt_id, status=store.ATTEMPT_REMOTE_OK, remote_ok=True,
|
||||||
)
|
resolved_by=actor, only_from=open_states)
|
||||||
logger.warning("카페24 상품 %s 적용 실패: %s", product_no, exc)
|
revision_id = writes.record_attempt(st, attempt)
|
||||||
return RedirectResponse(
|
if schedule_id:
|
||||||
url=f"{back}&err=적용에 실패했습니다: {exc} (직전 내용은 버전 {backup_id} 로 보관됨)",
|
st.review_schedule(int(schedule_id), status=store.STATUS_SUCCESS,
|
||||||
status_code=303,
|
note=f"{actor} 가 반영됨으로 확정", actor=actor, action="applied")
|
||||||
)
|
text = f"시도 #{attempt_id} 를 반영됨으로 확정했습니다(버전 {revision_id})."
|
||||||
|
else:
|
||||||
# PUT 응답은 쓰기 직후의 실제 값 — 스냅샷으로 남긴다(상품명·가격·updated_date 등).
|
st.update_attempt(attempt_id, status=store.ATTEMPT_ABANDONED, resolved_by=actor,
|
||||||
remember_write(st, product_no, updated if isinstance(updated, dict) else {})
|
only_from=open_states)
|
||||||
|
if schedule_id:
|
||||||
# MANUAL revision 을 **먼저** 남긴다. 이것이 "마지막 쓰기" 기준이 되어, 카페24 GET 이
|
st.review_schedule(int(schedule_id), status=store.STATUS_FAILED,
|
||||||
# 한동안 예전 값을 돌려줘도 편집기는 방금 적용한 내용을 보여준다.
|
note=f"{actor} 가 반영 안 됨으로 확정", actor=actor, action="not_applied")
|
||||||
revision_id = st.add_revision(
|
text = f"시도 #{attempt_id} 를 반영 안 됨으로 확정했습니다. 필요하면 다시 적용하세요."
|
||||||
product_no=product_no,
|
except (writes.WriteBusy, writes.WriteSetupError) as exc:
|
||||||
html_content=submitted,
|
return RedirectResponse(url=_with_msg(back, err=str(exc)), status_code=303)
|
||||||
revision_type=store.REVISION_MANUAL,
|
writes.audit_safe(st, actor=actor, action=f"resolve_attempt:{result}", product_no=product_no,
|
||||||
memo=memo,
|
result="SUCCESS", detail=f"시도 #{attempt_id}")
|
||||||
created_by=actor,
|
return RedirectResponse(url=_with_msg(back, msg=text), status_code=303)
|
||||||
)
|
|
||||||
|
|
||||||
# 카페24 관리자 API 는 쓰기 직후 몇 초간 이전 값을 돌려줄 때가 있다(쇼핑몰
|
|
||||||
# 화면에는 바로 반영됨). 여기서 짧게 확인만 한다 — 확인이 안 돼도 화면은 위
|
|
||||||
# MANUAL revision 을 기준으로 그리므로 문제없다.
|
|
||||||
confirmed = products.wait_for_description(api.client, product_no, submitted)
|
|
||||||
|
|
||||||
st.log_audit(
|
|
||||||
actor=actor, action="apply_description", product_no=product_no,
|
|
||||||
revision_id=revision_id, result="SUCCESS",
|
|
||||||
detail=(
|
|
||||||
f"{len(submitted)}자 적용 (백업 {backup_id}, 모바일 PC와 동일 유지, "
|
|
||||||
f"카페24 재조회 {'확인' if confirmed else '지연 — 마지막 적용값 표시'})"
|
|
||||||
),
|
|
||||||
)
|
|
||||||
logger.info("카페24 상품 %s 상세설명 적용 (%s, 재조회 확인=%s)", product_no, actor, confirmed)
|
|
||||||
note = "" if confirmed else " 카페24 관리자 API 반영은 잠시 늦을 수 있어 방금 적용한 내용을 표시합니다."
|
|
||||||
return RedirectResponse(
|
|
||||||
url=f"{back}&msg=카페24에 적용했습니다. 직전 내용은 버전 {backup_id} 로 보관됩니다.{note}",
|
|
||||||
status_code=303,
|
|
||||||
)
|
|
||||||
|
|||||||
@@ -1,8 +1,9 @@
|
|||||||
"""카페24 예약관리 — 지정 시각에 상세페이지·진열/판매를 자동 적용.
|
"""카페24 예약관리 — 지정 시각에 대표 이미지·상세페이지·진열/판매를 자동 적용.
|
||||||
|
|
||||||
되돌리기(자동 복원)는 쓰지 않는다. 예약은 "그 시각에 이 내용을 적용" 하나뿐이다.
|
되돌리기(자동 복원)는 쓰지 않는다. 예약은 "그 시각에 이 내용을 적용" 하나뿐이다.
|
||||||
한 예약에서 세 가지를 각각 고를 수 있다.
|
한 예약에서 네 가지를 각각 고를 수 있다.
|
||||||
|
|
||||||
|
대표 이미지 고른 파일로 그 시각에 교체 (파일은 DB 보관 — 마이그레이션 006)
|
||||||
상세페이지 HTML 편집기에 있는 내용을 그 시각에 적용 (안 고르면 HTML 은 그대로)
|
상세페이지 HTML 편집기에 있는 내용을 그 시각에 적용 (안 고르면 HTML 은 그대로)
|
||||||
진열 진열 / 미진열 / 변경 없음
|
진열 진열 / 미진열 / 변경 없음
|
||||||
판매 판매 / 중지 / 변경 없음
|
판매 판매 / 중지 / 변경 없음
|
||||||
@@ -19,14 +20,15 @@ from __future__ import annotations
|
|||||||
|
|
||||||
import logging
|
import logging
|
||||||
|
|
||||||
from fastapi import APIRouter, Form, Request
|
from fastapi import APIRouter, File, Form, HTTPException, Request, UploadFile
|
||||||
from fastapi.responses import HTMLResponse, RedirectResponse
|
from fastapi.responses import HTMLResponse, RedirectResponse, Response
|
||||||
|
|
||||||
from app.integrations.cafe24 import Cafe24Error, build_cafe24_api, products
|
from app.integrations.cafe24 import Cafe24Error, build_cafe24_api, load_config, products
|
||||||
|
|
||||||
from . import store
|
from . import store, writes
|
||||||
from .common import base_ctx, guard
|
from .common import base_ctx, guard
|
||||||
from .routes_products import _no_store
|
from .routes_product_info import _read_image
|
||||||
|
from .routes_products import _no_store, load_product
|
||||||
|
|
||||||
logger = logging.getLogger("cafe24.schedules")
|
logger = logging.getLogger("cafe24.schedules")
|
||||||
|
|
||||||
@@ -53,8 +55,10 @@ def schedules_page(request: Request) -> HTMLResponse:
|
|||||||
has_html=bool(row.get("has_html")),
|
has_html=bool(row.get("has_html")),
|
||||||
set_display=row.get("set_display"),
|
set_display=row.get("set_display"),
|
||||||
set_selling=row.get("set_selling"),
|
set_selling=row.get("set_selling"),
|
||||||
|
has_image=bool(row.get("image_type")),
|
||||||
),
|
),
|
||||||
"editable": store.is_editable(row.get("status") or ""),
|
"editable": store.is_editable(row.get("status") or ""),
|
||||||
|
"needs_review": row.get("status") == store.STATUS_NEEDS_REVIEW,
|
||||||
}
|
}
|
||||||
)
|
)
|
||||||
|
|
||||||
@@ -62,9 +66,10 @@ def schedules_page(request: Request) -> HTMLResponse:
|
|||||||
ctx.update(
|
ctx.update(
|
||||||
{
|
{
|
||||||
"page_title": "카페24 — 예약관리",
|
"page_title": "카페24 — 예약관리",
|
||||||
"page_subtitle": "지정 시각에 상세페이지·진열/판매 자동 적용",
|
"page_subtitle": "지정 시각에 대표 이미지·상세페이지·진열/판매 자동 적용",
|
||||||
"rows": rows,
|
"rows": rows,
|
||||||
"pending": sum(1 for r in rows if r["status"] == store.STATUS_PENDING),
|
"pending": sum(1 for r in rows if r["status"] == store.STATUS_PENDING),
|
||||||
|
"review": sum(1 for r in rows if r["needs_review"]),
|
||||||
"flash": request.query_params.get("msg", ""),
|
"flash": request.query_params.get("msg", ""),
|
||||||
"flash_error": request.query_params.get("err", ""),
|
"flash_error": request.query_params.get("err", ""),
|
||||||
}
|
}
|
||||||
@@ -83,12 +88,14 @@ def schedule_create(
|
|||||||
set_selling: str = Form(""),
|
set_selling: str = Form(""),
|
||||||
memo: str = Form(""),
|
memo: str = Form(""),
|
||||||
list_query: str = Form(""),
|
list_query: str = Form(""),
|
||||||
|
image: UploadFile | None = File(None),
|
||||||
):
|
):
|
||||||
"""편집기에서 예약을 등록한다.
|
"""편집기에서 예약을 등록한다.
|
||||||
|
|
||||||
HTML 을 적용하는 예약이면 지금 편집기 내용을 DRAFT revision 으로 저장해 고정한다.
|
HTML 을 적용하는 예약이면 지금 편집기 내용을 DRAFT revision 으로 저장해 고정한다.
|
||||||
단건 적용과 같은 다듬기(URL 인코딩 → 소스 정리)를 거치므로, 예약이 실행됐을 때
|
단건 적용과 같은 다듬기(URL 인코딩 → 소스 정리)를 거치므로, 예약이 실행됐을 때
|
||||||
저장되는 값이 화면에서 본 것과 같다.
|
저장되는 값이 화면에서 본 것과 같다.
|
||||||
|
대표 이미지 파일을 고르면 파일을 DB 에 보관했다가 그 시각에 교체한다(마이그레이션 006).
|
||||||
"""
|
"""
|
||||||
checked = guard(request)
|
checked = guard(request)
|
||||||
if not isinstance(checked, tuple):
|
if not isinstance(checked, tuple):
|
||||||
@@ -103,9 +110,16 @@ def schedule_create(
|
|||||||
display_flag = store.parse_tristate(set_display)
|
display_flag = store.parse_tristate(set_display)
|
||||||
selling_flag = store.parse_tristate(set_selling)
|
selling_flag = store.parse_tristate(set_selling)
|
||||||
|
|
||||||
if not want_html and display_flag is None and selling_flag is None:
|
image_data = b""
|
||||||
|
if image is not None and image.filename: # 파일을 안 고르면 브라우저가 이름 없는 빈 파트를 보낸다
|
||||||
|
try:
|
||||||
|
image_data = _read_image(image)
|
||||||
|
except HTTPException as exc:
|
||||||
|
return RedirectResponse(url=f"{back}&err={exc.detail}", status_code=303)
|
||||||
|
|
||||||
|
if not want_html and display_flag is None and selling_flag is None and not image_data:
|
||||||
return RedirectResponse(
|
return RedirectResponse(
|
||||||
url=f"{back}&err=예약할 내용을 하나 이상 선택하세요(상세페이지 / 진열 / 판매).",
|
url=f"{back}&err=예약할 내용을 하나 이상 선택하세요(대표 이미지 / 상세페이지 / 진열 / 판매).",
|
||||||
status_code=303,
|
status_code=303,
|
||||||
)
|
)
|
||||||
|
|
||||||
@@ -114,6 +128,12 @@ def schedule_create(
|
|||||||
except ValueError as exc:
|
except ValueError as exc:
|
||||||
return RedirectResponse(url=f"{back}&err={exc}", status_code=303)
|
return RedirectResponse(url=f"{back}&err={exc}", status_code=303)
|
||||||
|
|
||||||
|
# 예약은 worker 가 잠금·시도 기록(마이그레이션 005)으로 실행한다 — 없으면 등록도 받지 않는다.
|
||||||
|
try:
|
||||||
|
writes.require_schema(st)
|
||||||
|
except writes.WriteSetupError as exc:
|
||||||
|
return RedirectResponse(url=f"{back}&err={exc}", status_code=303)
|
||||||
|
|
||||||
revision_id: int | None = None
|
revision_id: int | None = None
|
||||||
if want_html:
|
if want_html:
|
||||||
body = store.format_html(store.encode_html_urls(html or ""))
|
body = store.format_html(store.encode_html_urls(html or ""))
|
||||||
@@ -127,6 +147,7 @@ def schedule_create(
|
|||||||
revision_type=store.REVISION_DRAFT,
|
revision_type=store.REVISION_DRAFT,
|
||||||
memo=f"예약 등록 ({run_at.strftime('%Y-%m-%d %H:%M')} 적용 예정)",
|
memo=f"예약 등록 ({run_at.strftime('%Y-%m-%d %H:%M')} 적용 예정)",
|
||||||
created_by=actor,
|
created_by=actor,
|
||||||
|
mall_id=load_config().mall_id,
|
||||||
)
|
)
|
||||||
|
|
||||||
schedule_id = st.create_schedule(
|
schedule_id = st.create_schedule(
|
||||||
@@ -137,9 +158,12 @@ def schedule_create(
|
|||||||
set_selling=selling_flag,
|
set_selling=selling_flag,
|
||||||
memo=memo,
|
memo=memo,
|
||||||
created_by=actor,
|
created_by=actor,
|
||||||
|
image=image_data or None,
|
||||||
|
image_type=(image.content_type or "").lower() if image_data and image else "",
|
||||||
|
image_name=(image.filename or "") if image_data and image else "",
|
||||||
)
|
)
|
||||||
detail = store.describe_schedule_action(
|
detail = store.describe_schedule_action(
|
||||||
has_html=want_html, set_display=display_flag, set_selling=selling_flag
|
has_html=want_html, set_display=display_flag, set_selling=selling_flag, has_image=bool(image_data)
|
||||||
)
|
)
|
||||||
st.log_audit(
|
st.log_audit(
|
||||||
actor=actor, action="schedule_create", product_no=product_no,
|
actor=actor, action="schedule_create", product_no=product_no,
|
||||||
@@ -170,6 +194,20 @@ def schedule_cancel(request: Request, schedule_id: int):
|
|||||||
)
|
)
|
||||||
|
|
||||||
|
|
||||||
|
@schedules_router.get("/schedules/{schedule_id}/image")
|
||||||
|
def schedule_image(request: Request, schedule_id: int):
|
||||||
|
"""예약해 둔 대표 이미지 미리보기(목록 썸네일)."""
|
||||||
|
checked = guard(request)
|
||||||
|
if not isinstance(checked, tuple):
|
||||||
|
return checked
|
||||||
|
st, _user = checked
|
||||||
|
row = st.get_schedule(schedule_id)
|
||||||
|
data = st.get_schedule_image(schedule_id) if row.get("image_type") else b""
|
||||||
|
if not data:
|
||||||
|
return Response(status_code=404)
|
||||||
|
return Response(content=data, media_type=str(row["image_type"]), headers={"Cache-Control": "private, max-age=3600"})
|
||||||
|
|
||||||
|
|
||||||
@schedules_router.get("/schedules/preview/{product_no}")
|
@schedules_router.get("/schedules/preview/{product_no}")
|
||||||
def schedule_current_flags(request: Request, product_no: int) -> dict:
|
def schedule_current_flags(request: Request, product_no: int) -> dict:
|
||||||
"""예약 폼의 기본값을 위해 현재 진열/판매 상태를 알려준다(JSON, 읽기 전용)."""
|
"""예약 폼의 기본값을 위해 현재 진열/판매 상태를 알려준다(JSON, 읽기 전용)."""
|
||||||
@@ -178,7 +216,7 @@ def schedule_current_flags(request: Request, product_no: int) -> dict:
|
|||||||
st, _user = require_store(request)
|
st, _user = require_store(request)
|
||||||
api = build_cafe24_api(st)
|
api = build_cafe24_api(st)
|
||||||
try:
|
try:
|
||||||
raw = products.get_product(api.client, product_no)
|
raw, _ = load_product(st, api, product_no) # 방금 바꾼 진열/판매가 지연으로 예전 값이 되지 않게
|
||||||
except Cafe24Error as exc:
|
except Cafe24Error as exc:
|
||||||
return {"product_no": product_no, "error": str(exc)}
|
return {"product_no": product_no, "error": str(exc)}
|
||||||
normalized = products.normalize_product(raw)
|
normalized = products.normalize_product(raw)
|
||||||
@@ -187,3 +225,51 @@ def schedule_current_flags(request: Request, product_no: int) -> dict:
|
|||||||
"display": normalized["display"],
|
"display": normalized["display"],
|
||||||
"selling": normalized["selling"],
|
"selling": normalized["selling"],
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
||||||
|
# 확인 필요(NEEDS_REVIEW) 예약의 사람 확정 — 반영 여부를 모르는 채로 worker 가 멈춘 것.
|
||||||
|
# applied = 쇼핑몰에 반영돼 있음(완료 + 버전 기록) / rerun = 다시 실행 / close = 실패로 종료.
|
||||||
|
_REVIEW_ACTIONS = {
|
||||||
|
"applied": (store.STATUS_SUCCESS, "반영됨으로 확정"),
|
||||||
|
"rerun": (store.STATUS_PENDING, "다시 실행"),
|
||||||
|
"close": (store.STATUS_FAILED, "실패로 종료"),
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
@schedules_router.post("/schedules/{schedule_id}/review")
|
||||||
|
def schedule_review(request: Request, schedule_id: int, action: str = Form("")):
|
||||||
|
"""확인 필요 예약을 확정한다. 자동으로 다시 실행하지 않는다 — 사람이 쇼핑몰을 보고 고른다."""
|
||||||
|
checked = guard(request)
|
||||||
|
if not isinstance(checked, tuple):
|
||||||
|
return checked
|
||||||
|
st, user = checked
|
||||||
|
actor = str(user.get("email") or "")
|
||||||
|
if action not in _REVIEW_ACTIONS:
|
||||||
|
return RedirectResponse(url="/cafe24/schedules?err=확정할 동작을 고르세요.", status_code=303)
|
||||||
|
status, label = _REVIEW_ACTIONS[action]
|
||||||
|
row = st.get_schedule(schedule_id)
|
||||||
|
if not row or row.get("status") != store.STATUS_NEEDS_REVIEW:
|
||||||
|
return RedirectResponse(
|
||||||
|
url=f"/cafe24/schedules?err=예약 #{schedule_id} 은 확인 필요 상태가 아닙니다.", status_code=303
|
||||||
|
)
|
||||||
|
product_no = int(row.get("product_no") or 0)
|
||||||
|
try:
|
||||||
|
with writes.write_lock(st, writes.product_lock_key(product_no), actor=actor, purpose="예약 결과 확정"):
|
||||||
|
attempt = st.latest_attempt_for_schedule(schedule_id)
|
||||||
|
open_attempt = attempt if attempt.get("status") in (store.ATTEMPT_STARTED, store.ATTEMPT_UNKNOWN) else {}
|
||||||
|
if action == "applied":
|
||||||
|
if not open_attempt:
|
||||||
|
return RedirectResponse(
|
||||||
|
url=f"/cafe24/schedules?err=예약 #{schedule_id} 에는 확정할 적용 시도가 없습니다 — "
|
||||||
|
"다시 실행하거나 실패로 종료하세요.",
|
||||||
|
status_code=303,
|
||||||
|
)
|
||||||
|
st.update_attempt(int(open_attempt["id"]), status=store.ATTEMPT_REMOTE_OK, remote_ok=True,
|
||||||
|
resolved_by=actor,
|
||||||
|
only_from=(store.ATTEMPT_STARTED, store.ATTEMPT_UNKNOWN))
|
||||||
|
writes.record_attempt(st, open_attempt)
|
||||||
|
st.review_schedule(schedule_id, status=status, note=f"{actor} — {label}", actor=actor, action=action)
|
||||||
|
except (writes.WriteBusy, writes.WriteSetupError) as exc:
|
||||||
|
return RedirectResponse(url=f"/cafe24/schedules?err={exc}", status_code=303)
|
||||||
|
logger.info("카페24 예약 #%s 확인 필요 → %s (%s)", schedule_id, label, actor)
|
||||||
|
return RedirectResponse(url=f"/cafe24/schedules?msg=예약 #{schedule_id} — {label}", status_code=303)
|
||||||
|
|||||||
+328
-25
@@ -6,6 +6,7 @@
|
|||||||
from __future__ import annotations
|
from __future__ import annotations
|
||||||
|
|
||||||
import hashlib
|
import hashlib
|
||||||
|
import json
|
||||||
import re
|
import re
|
||||||
from datetime import datetime, timedelta
|
from datetime import datetime, timedelta
|
||||||
from urllib.parse import quote
|
from urllib.parse import quote
|
||||||
@@ -44,6 +45,9 @@ STATUS_PROCESSING = "PROCESSING"
|
|||||||
STATUS_SUCCESS = "SUCCESS"
|
STATUS_SUCCESS = "SUCCESS"
|
||||||
STATUS_FAILED = "FAILED"
|
STATUS_FAILED = "FAILED"
|
||||||
STATUS_CANCELLED = "CANCELLED"
|
STATUS_CANCELLED = "CANCELLED"
|
||||||
|
# 원격 반영 여부를 모른다(네트워크 끊김·worker 중단) — 사람이 카페24를 보고 확정한다.
|
||||||
|
# 자동으로 PENDING 에 돌려 재적용하지 않는다(마이그레이션 005).
|
||||||
|
STATUS_NEEDS_REVIEW = "NEEDS_REVIEW"
|
||||||
|
|
||||||
SCHEDULE_STATUSES: tuple[str, ...] = (
|
SCHEDULE_STATUSES: tuple[str, ...] = (
|
||||||
STATUS_PENDING,
|
STATUS_PENDING,
|
||||||
@@ -51,6 +55,7 @@ SCHEDULE_STATUSES: tuple[str, ...] = (
|
|||||||
STATUS_SUCCESS,
|
STATUS_SUCCESS,
|
||||||
STATUS_FAILED,
|
STATUS_FAILED,
|
||||||
STATUS_CANCELLED,
|
STATUS_CANCELLED,
|
||||||
|
STATUS_NEEDS_REVIEW,
|
||||||
)
|
)
|
||||||
|
|
||||||
SCHEDULE_STATUS_LABELS: dict[str, str] = {
|
SCHEDULE_STATUS_LABELS: dict[str, str] = {
|
||||||
@@ -59,8 +64,36 @@ SCHEDULE_STATUS_LABELS: dict[str, str] = {
|
|||||||
STATUS_SUCCESS: "완료",
|
STATUS_SUCCESS: "완료",
|
||||||
STATUS_FAILED: "실패",
|
STATUS_FAILED: "실패",
|
||||||
STATUS_CANCELLED: "취소",
|
STATUS_CANCELLED: "취소",
|
||||||
|
STATUS_NEEDS_REVIEW: "확인 필요",
|
||||||
}
|
}
|
||||||
|
|
||||||
|
# ── 쓰기 시도 상태 (cafe24_write_attempts.status, 마이그레이션 005) ──
|
||||||
|
ATTEMPT_STARTED = "STARTED" # PUT 직전 기록. 이대로 남으면 결과를 모른다.
|
||||||
|
ATTEMPT_REMOTE_OK = "REMOTE_OK" # 카페24 반영 성공, 로컬 버전 기록 전(기록 복구 필요)
|
||||||
|
ATTEMPT_RECORDED = "RECORDED" # 반영 성공 + 버전 기록 완료
|
||||||
|
ATTEMPT_REMOTE_FAILED = "REMOTE_FAILED" # 카페24가 거절 — 반영되지 않은 것이 확실
|
||||||
|
ATTEMPT_UNKNOWN = "UNKNOWN" # 반영 여부 모름 → 사람 확인
|
||||||
|
ATTEMPT_ABANDONED = "ABANDONED" # 사람이 "반영 안 됨"으로 확정 / 재실행으로 대체
|
||||||
|
# 원격 반영이 확인된 시도 — 읽기 지연 판정의 근거는 이것뿐이다.
|
||||||
|
ATTEMPT_CONFIRMED: tuple[str, ...] = (ATTEMPT_REMOTE_OK, ATTEMPT_RECORDED)
|
||||||
|
# 결과 확정이 필요한 시도 — 이것이 남아 있으면 같은 상품 상세설명을 다시 쓰지 않는다.
|
||||||
|
ATTEMPT_OPEN: tuple[str, ...] = (ATTEMPT_STARTED, ATTEMPT_REMOTE_OK, ATTEMPT_UNKNOWN)
|
||||||
|
|
||||||
|
ORIGIN_MANUAL = "MANUAL"
|
||||||
|
ORIGIN_SCHEDULED = "SCHEDULED"
|
||||||
|
ORIGIN_ROLLBACK = "ROLLBACK"
|
||||||
|
# 시도 출처 → 성공 시 남길 버전 종류
|
||||||
|
ORIGIN_REVISION_TYPE: dict[str, str] = {
|
||||||
|
ORIGIN_MANUAL: "MANUAL",
|
||||||
|
ORIGIN_SCHEDULED: "SCHEDULED",
|
||||||
|
ORIGIN_ROLLBACK: "ROLLBACK",
|
||||||
|
}
|
||||||
|
|
||||||
|
# ── BACKUP 출처 (cafe24_product_revisions.source) ──
|
||||||
|
SOURCE_OBSERVED = "OBSERVED" # 카페24 GET 으로 읽은 값 그대로
|
||||||
|
SOURCE_LAST_WRITE = "LAST_WRITE" # 카페24가 읽기 지연 중 — 우리 마지막(확인된) 쓰기를 현재값으로 봄
|
||||||
|
SOURCE_REVISION = "REVISION" # ROLLBACK — 과거 버전을 그대로 다시 올림
|
||||||
|
|
||||||
# 사용자가 손댈 수 있는 상태 — PROCESSING/SUCCESS 는 임의 변경 금지
|
# 사용자가 손댈 수 있는 상태 — PROCESSING/SUCCESS 는 임의 변경 금지
|
||||||
EDITABLE_STATUSES: tuple[str, ...] = (STATUS_PENDING,)
|
EDITABLE_STATUSES: tuple[str, ...] = (STATUS_PENDING,)
|
||||||
|
|
||||||
@@ -419,10 +452,12 @@ def parse_schedule_at(value: object, *, now: datetime | None = None) -> datetime
|
|||||||
|
|
||||||
|
|
||||||
def describe_schedule_action(
|
def describe_schedule_action(
|
||||||
*, has_html: bool, set_display: bool | None, set_selling: bool | None
|
*, has_html: bool, set_display: bool | None, set_selling: bool | None, has_image: bool = False
|
||||||
) -> str:
|
) -> str:
|
||||||
"""예약 내용을 한 줄로 요약(목록·로그 표시용)."""
|
"""예약 내용을 한 줄로 요약(목록·로그 표시용)."""
|
||||||
parts: list[str] = []
|
parts: list[str] = []
|
||||||
|
if has_image:
|
||||||
|
parts.append("대표이미지")
|
||||||
if has_html:
|
if has_html:
|
||||||
parts.append("상세페이지")
|
parts.append("상세페이지")
|
||||||
if set_display is not None:
|
if set_display is not None:
|
||||||
@@ -471,6 +506,15 @@ WRITE_REVISION_TYPES: tuple[str, ...] = (REVISION_MANUAL, REVISION_SCHEDULED, RE
|
|||||||
DEFAULT_READ_LAG_GRACE_MIN = 360
|
DEFAULT_READ_LAG_GRACE_MIN = 360
|
||||||
|
|
||||||
|
|
||||||
|
def parse_shop_nos(value: object) -> list[int]:
|
||||||
|
"""`CAFE24_SHOP_NOS`("1,2,3") → [1, 2, 3]. 기본 쇼핑몰 1 은 항상 맨 앞, 잘못된 값은 버린다."""
|
||||||
|
out = [1]
|
||||||
|
for part in str(value or "").replace(" ", "").split(","):
|
||||||
|
if part.isdigit() and int(part) > 0 and int(part) not in out:
|
||||||
|
out.append(int(part))
|
||||||
|
return out
|
||||||
|
|
||||||
|
|
||||||
def parse_grace_minutes(value: object, default: int = DEFAULT_READ_LAG_GRACE_MIN) -> int:
|
def parse_grace_minutes(value: object, default: int = DEFAULT_READ_LAG_GRACE_MIN) -> int:
|
||||||
try:
|
try:
|
||||||
minutes = int(str(value or "").strip())
|
minutes = int(str(value or "").strip())
|
||||||
@@ -509,11 +553,20 @@ def resolve_description(
|
|||||||
known_digests: set[str] | frozenset[str],
|
known_digests: set[str] | frozenset[str],
|
||||||
grace_minutes: int,
|
grace_minutes: int,
|
||||||
now: datetime | None = None,
|
now: datetime | None = None,
|
||||||
|
fetched_updated: object = None,
|
||||||
) -> tuple[str, str]:
|
) -> tuple[str, str]:
|
||||||
"""(화면·적용에 쓸 유효 HTML, 상태) 를 돌려준다.
|
"""(화면·적용에 쓸 유효 HTML, 상태) 를 돌려준다.
|
||||||
|
|
||||||
last_write: 최근 쓰기 revision — {"html_content", "created_at"}.
|
last_write: **원격 반영이 확인된** 마지막 쓰기 — {"html_content", "created_at",
|
||||||
known_digests: 유예시간 안의 revision 들의 내용 해시(`content_digest()` 결과) 집합.
|
"remote_updated_at"(선택: 그 PUT 응답의 updated_date)}.
|
||||||
|
known_digests: 확인된 쓰기들이 **덮어쓴 값**(쓰기 직전 관측값·기준값)과 쓴 값의
|
||||||
|
내용 해시(`content_digest()`) 집합. 충돌로 거절된 적용의 백업, 예약 초안처럼
|
||||||
|
카페24에 올라간 적 없는 값은 넣지 않는다 — 넣으면 관리자에서 직접 고친 값이
|
||||||
|
우연히 그와 같을 때 "읽기 지연"으로 오판해 그 수정을 덮어쓴다.
|
||||||
|
fetched_updated: 이번 GET 의 updated_date. 마지막 쓰기의 PUT 응답 updated_date 보다
|
||||||
|
**뒤**라면 GET 은 우리 쓰기 이후의 레코드다 — 지연이 아니므로 카페24 값을 믿는다
|
||||||
|
(관리자가 우리 적용 뒤 예전 값으로 되돌린 경우를 구분한다). 같거나 판단할 수
|
||||||
|
없으면 내용 해시로 판정한다.
|
||||||
"""
|
"""
|
||||||
if not last_write:
|
if not last_write:
|
||||||
return cafe24_html, SYNC_NONE
|
return cafe24_html, SYNC_NONE
|
||||||
@@ -523,11 +576,29 @@ def resolve_description(
|
|||||||
last_html = str(last_write.get("html_content") or "")
|
last_html = str(last_write.get("html_content") or "")
|
||||||
if cafe24_html == last_html:
|
if cafe24_html == last_html:
|
||||||
return cafe24_html, SYNC_SYNCED
|
return cafe24_html, SYNC_SYNCED
|
||||||
|
fetched_at = _as_aware(fetched_updated)
|
||||||
|
written_at = _as_aware(last_write.get("remote_updated_at"))
|
||||||
|
if fetched_at is not None and written_at is not None and fetched_at > written_at:
|
||||||
|
return cafe24_html, SYNC_EXTERNAL
|
||||||
if content_digest(cafe24_html) in known_digests:
|
if content_digest(cafe24_html) in known_digests:
|
||||||
return last_html, SYNC_PENDING
|
return last_html, SYNC_PENDING
|
||||||
return cafe24_html, SYNC_EXTERNAL
|
return cafe24_html, SYNC_EXTERNAL
|
||||||
|
|
||||||
|
|
||||||
|
def lineage_digests(lineage: list[dict]) -> set[str]:
|
||||||
|
"""확인된 쓰기 목록 → 읽기 지연 판정에 쓸 내용 해시 집합.
|
||||||
|
|
||||||
|
각 쓰기의 직전 관측값(observed)·기준값(base)·쓴 값(target). 빈 해시는 뺀다.
|
||||||
|
"""
|
||||||
|
out: set[str] = set()
|
||||||
|
for item in lineage or []:
|
||||||
|
for key in ("observed_digest", "base_digest", "target_digest"):
|
||||||
|
value = str(item.get(key) or "")
|
||||||
|
if value:
|
||||||
|
out.add(value)
|
||||||
|
return out
|
||||||
|
|
||||||
|
|
||||||
def content_digest(html: str) -> str:
|
def content_digest(html: str) -> str:
|
||||||
"""revision 내용 대조용 md5 hex — DB 의 `md5(html_content)` 와 같은 값.
|
"""revision 내용 대조용 md5 hex — DB 의 `md5(html_content)` 와 같은 값.
|
||||||
|
|
||||||
@@ -580,6 +651,12 @@ def overlay_recent_write(
|
|||||||
보다 GET 의 updated_date 가 **이전**이면 GET 이 아직 예전 레코드를 돌려주는
|
보다 GET 의 updated_date 가 **이전**이면 GET 이 아직 예전 레코드를 돌려주는
|
||||||
것이다. 우리 서버 시계와 비교하지 않으므로 시계 차이에 영향받지 않는다.
|
것이다. 우리 서버 시계와 비교하지 않으므로 시계 차이에 영향받지 않는다.
|
||||||
날짜가 없어 판정할 수 없으면 카페24 값을 그대로 둔다.
|
날짜가 없어 판정할 수 없으면 카페24 값을 그대로 둔다.
|
||||||
|
|
||||||
|
두 updated_date 가 **같을** 때: 카페24는 진열/판매만 바꾼 PUT 에서 updated_date 를
|
||||||
|
올리지 않을 수 있다. 그러면 지연된 GET 도 같은 시각을 돌려주므로 "같다 = 따라잡음"
|
||||||
|
으로 보면 예전 진열/판매가 그대로 보인다(실제 발생 — 바꿔도 반영 안 된 것처럼 보임).
|
||||||
|
같은 시각인데 값이 다르면 카페24 기준으로 그 뒤 수정된 근거가 없으므로 지연으로 본다.
|
||||||
|
GET 이 **이후** 시각이면 관리자 등에서 다시 고친 것 — 카페24 값을 믿는다.
|
||||||
반환: (병합된 상품 dict, 지연 여부)
|
반환: (병합된 상품 dict, 지연 여부)
|
||||||
"""
|
"""
|
||||||
if not snapshot:
|
if not snapshot:
|
||||||
@@ -588,7 +665,9 @@ def overlay_recent_write(
|
|||||||
return fetched, False
|
return fetched, False
|
||||||
fetched_at = _as_aware(fetched.get("updated_date"))
|
fetched_at = _as_aware(fetched.get("updated_date"))
|
||||||
snap_at = _as_aware(snapshot.get("updated_date"))
|
snap_at = _as_aware(snapshot.get("updated_date"))
|
||||||
if fetched_at is None or snap_at is None or fetched_at >= snap_at:
|
if fetched_at is None or snap_at is None or fetched_at > snap_at:
|
||||||
|
return fetched, False
|
||||||
|
if fetched_at == snap_at and not _snapshot_differs(fetched, snapshot):
|
||||||
return fetched, False
|
return fetched, False
|
||||||
merged = dict(fetched)
|
merged = dict(fetched)
|
||||||
for key in SNAPSHOT_FIELDS:
|
for key in SNAPSHOT_FIELDS:
|
||||||
@@ -598,6 +677,216 @@ def overlay_recent_write(
|
|||||||
return merged, True
|
return merged, True
|
||||||
|
|
||||||
|
|
||||||
|
def _snapshot_differs(fetched: dict, snapshot: dict) -> bool:
|
||||||
|
"""GET 에 있는 스냅샷 필드 중 값이 다른 것이 있는가(문자열로 비교 — 둘 다 카페24 원본 모양)."""
|
||||||
|
for key in SNAPSHOT_FIELDS:
|
||||||
|
if key == "updated_date" or key not in snapshot or key not in fetched:
|
||||||
|
continue
|
||||||
|
if fetched[key] is None:
|
||||||
|
continue
|
||||||
|
if str(fetched[key]) != str(snapshot[key]):
|
||||||
|
return True
|
||||||
|
return False
|
||||||
|
|
||||||
|
|
||||||
|
def overlay_product_rows(
|
||||||
|
rows: list[dict],
|
||||||
|
snapshots: dict,
|
||||||
|
*,
|
||||||
|
grace_minutes: int,
|
||||||
|
now: datetime | None = None,
|
||||||
|
) -> list[dict]:
|
||||||
|
"""목록(GET /admin/products) 행마다 최근 쓰기 스냅샷을 덮어씌운다.
|
||||||
|
|
||||||
|
snapshots: {product_no: {"data": 스냅샷, "written_at": ISO}} — 스냅샷 product 섹션.
|
||||||
|
목록 API 도 단건 GET 과 똑같이 읽기 지연이 있다. 보정하지 않으면 진열/판매를 바꾼
|
||||||
|
뒤 목록을 다시 불러올 때 예전 상태로 보이고(필터에 걸려 사라지기도 한다), 그 값이
|
||||||
|
캐시(cafe24_products)에도 다시 저장된다.
|
||||||
|
"""
|
||||||
|
if not snapshots:
|
||||||
|
return rows
|
||||||
|
out: list[dict] = []
|
||||||
|
for row in rows:
|
||||||
|
try:
|
||||||
|
no = int(row.get("product_no") or 0)
|
||||||
|
except (TypeError, ValueError):
|
||||||
|
no = 0
|
||||||
|
section = snapshots.get(no) if no else None
|
||||||
|
if isinstance(section, dict) and section.get("data"):
|
||||||
|
row, _ = overlay_recent_write(
|
||||||
|
row, snapshot=section.get("data"), written_at=section.get("written_at"),
|
||||||
|
grace_minutes=grace_minutes, now=now,
|
||||||
|
)
|
||||||
|
out.append(row)
|
||||||
|
return out
|
||||||
|
|
||||||
|
|
||||||
|
# ── 품목 스냅샷: 코드별 · 필드별 병합 ──
|
||||||
|
# 스냅샷 모양: {variant_code: {필드: 값, ..., "_at": ISO, "_deleted": bool,
|
||||||
|
# "options": [{name,value}...], "_options_before": [...]}}
|
||||||
|
def merge_variant_snapshot(current: dict | None, patch: dict | None, *, at: str, replace: bool = False) -> dict:
|
||||||
|
"""품목 스냅샷 병합.
|
||||||
|
|
||||||
|
- 같은 품목의 이전 필드는 유지하고 새로 쓴 필드만 덮는다. (예전에는 품목 단위로
|
||||||
|
통째로 바꿔서, 자체코드를 고친 뒤 진열만 바꾸면 자체코드 기록이 사라졌다.)
|
||||||
|
- replace=True 는 전체 초기화(옵션 삭제·재생성) — 이전 품목 기록을 모두 버린다.
|
||||||
|
빈 patch({}) 를 "초기화" 로 해석하지 않는다(병합에서 {} 는 아무것도 안 바꾼다).
|
||||||
|
- 삭제 표식(_deleted)은 한 번 붙으면 유지한다. 삭제 뒤에 늦게 도착한 수정이
|
||||||
|
그 품목을 되살리지 않게 한다.
|
||||||
|
- 품목마다 기록 시각(_at)을 남겨 유예시간을 품목별로 판정한다.
|
||||||
|
"""
|
||||||
|
base: dict = {} if replace else {
|
||||||
|
str(code): dict(fields) for code, fields in (current or {}).items() if isinstance(fields, dict)
|
||||||
|
}
|
||||||
|
for code, fields in (patch or {}).items():
|
||||||
|
if not isinstance(fields, dict):
|
||||||
|
continue
|
||||||
|
code = str(code)
|
||||||
|
entry = base.get(code, {})
|
||||||
|
if entry.get("_deleted") and not fields.get("_deleted"):
|
||||||
|
continue # 삭제된 품목에 대한 늦은 수정 — 되살리지 않는다
|
||||||
|
if fields.get("_deleted"):
|
||||||
|
base[code] = {"_deleted": True, "_at": at}
|
||||||
|
continue
|
||||||
|
entry.update(fields)
|
||||||
|
entry["_at"] = at
|
||||||
|
base[code] = entry
|
||||||
|
return base
|
||||||
|
|
||||||
|
|
||||||
|
def _labels(options: object) -> list[tuple[str, str]]:
|
||||||
|
if not isinstance(options, list):
|
||||||
|
return []
|
||||||
|
return [
|
||||||
|
(str(o.get("name") or ""), str(o.get("value") or ""))
|
||||||
|
for o in options if isinstance(o, dict)
|
||||||
|
]
|
||||||
|
|
||||||
|
|
||||||
|
def apply_variant_patch(
|
||||||
|
variant: dict,
|
||||||
|
patch: dict | None,
|
||||||
|
*,
|
||||||
|
section_written_at: object,
|
||||||
|
grace_minutes: int,
|
||||||
|
now: datetime | None = None,
|
||||||
|
) -> dict | None:
|
||||||
|
"""GET 품목 1건에 우리 쓰기 기록을 덮어씌운다. 삭제한 품목이면 None.
|
||||||
|
|
||||||
|
옵션 표기(options)는 **품목코드**(안정 식별자)로 짝지은 기록이다. 옵션값 이름을
|
||||||
|
바꾼 직후 GET 품목이 아직 예전 이름을 돌려주면(읽기 지연) 이름으로는 짝이 안 맞아
|
||||||
|
정상 품목이 "품목 없는 옵션값"으로 보였다. 그래서
|
||||||
|
- GET 표기가 쓰기 직전 표기들(_options_before) 중 하나 → 지연 → 우리가 쓴 표기로
|
||||||
|
- GET 표기 == 우리가 쓴 표기 → 이미 따라잡음
|
||||||
|
- 둘 다 아님 → 관리자에서 다시 고침 → GET 을 믿는다
|
||||||
|
_options_before 는 유예시간 안에 연달아 바꾼 이전 표기를 모두 담은 목록이다
|
||||||
|
(A→B→C 직후 GET 이 A 를 돌려줘도 지연으로 본다).
|
||||||
|
"""
|
||||||
|
if not isinstance(patch, dict) or not patch:
|
||||||
|
return variant
|
||||||
|
at = patch.get("_at") or section_written_at
|
||||||
|
if not within_grace(at, grace_minutes=grace_minutes, now=now):
|
||||||
|
return variant
|
||||||
|
if patch.get("_deleted"):
|
||||||
|
return None
|
||||||
|
out = dict(variant)
|
||||||
|
for key, value in patch.items():
|
||||||
|
if key.startswith("_") or key == "options":
|
||||||
|
continue
|
||||||
|
out[key] = value
|
||||||
|
if "options" in patch:
|
||||||
|
current = _labels(variant.get("options"))
|
||||||
|
wanted = _labels(patch.get("options"))
|
||||||
|
befores = label_history(patch.get("_options_before"))
|
||||||
|
if current != wanted and (patch.get("_options_before") is None or current in befores):
|
||||||
|
out["options"] = [{"name": n, "value": v} for n, v in wanted]
|
||||||
|
return out
|
||||||
|
|
||||||
|
|
||||||
|
def label_history(raw: object) -> list[list[tuple[str, str]]]:
|
||||||
|
"""_options_before → 표기 목록의 목록. 옛 모양(표기 하나 = dict 목록)도 받는다."""
|
||||||
|
if not isinstance(raw, list) or not raw:
|
||||||
|
return []
|
||||||
|
if all(isinstance(item, dict) for item in raw):
|
||||||
|
return [_labels(raw)]
|
||||||
|
return [_labels(item) for item in raw if isinstance(item, list)]
|
||||||
|
|
||||||
|
|
||||||
|
def labels_as_json(options: object) -> list[dict]:
|
||||||
|
"""표기(options) → 스냅샷 저장 모양 [{name, value}]."""
|
||||||
|
return [{"name": n, "value": v} for n, v in _labels(options)]
|
||||||
|
|
||||||
|
|
||||||
|
# ── 옵션 스냅샷: 쓰기 직전 모양과 비교해 지연/외부 변경을 가린다 ──
|
||||||
|
def options_signature(option: object) -> str:
|
||||||
|
"""옵션 dict 의 비교용 서명 — 옵션 사용 여부, 옵션명·표시방식, 옵션값 이름·이미지."""
|
||||||
|
if not isinstance(option, dict):
|
||||||
|
return ""
|
||||||
|
raw = option.get("has_option")
|
||||||
|
has = raw is True or str(raw or "").strip().upper() in ("T", "TRUE", "1", "Y")
|
||||||
|
groups = []
|
||||||
|
if has:
|
||||||
|
for o in option.get("options") or []:
|
||||||
|
if not isinstance(o, dict):
|
||||||
|
continue
|
||||||
|
values = [
|
||||||
|
[str(v.get("option_text") or ""), str(v.get("option_image_file") or ""),
|
||||||
|
str(v.get("option_link_image") or "")]
|
||||||
|
for v in (o.get("option_value") or []) if isinstance(v, dict)
|
||||||
|
]
|
||||||
|
groups.append([str(o.get("option_name") or ""), str(o.get("option_display_type") or ""), values])
|
||||||
|
return json.dumps([has, groups], ensure_ascii=False, sort_keys=True)
|
||||||
|
|
||||||
|
|
||||||
|
def overlay_options(
|
||||||
|
fetched: dict,
|
||||||
|
*,
|
||||||
|
snapshot: dict | None,
|
||||||
|
written_at: object,
|
||||||
|
grace_minutes: int,
|
||||||
|
now: datetime | None = None,
|
||||||
|
) -> tuple[dict, bool]:
|
||||||
|
"""(보여줄 옵션 dict, 지연 여부). 스냅샷에 `_before_signatures`(쓰기 직전 모양들의
|
||||||
|
서명 — 유예시간 안에 연달아 바꾼 이전 모양 포함)가 있으면 GET 이 그중 하나일 때만
|
||||||
|
지연으로 본다 — 관리자에서 다시 고친 옵션을 유예시간 동안 덮지 않게.
|
||||||
|
서명 목록이 없는 옛 스냅샷은 예전처럼 유예시간 안이면 스냅샷을 쓴다."""
|
||||||
|
if not isinstance(snapshot, dict) or not snapshot:
|
||||||
|
return fetched, False
|
||||||
|
if not within_grace(written_at, grace_minutes=grace_minutes, now=now):
|
||||||
|
return fetched, False
|
||||||
|
got = options_signature(fetched)
|
||||||
|
if got == options_signature(snapshot):
|
||||||
|
return fetched, False
|
||||||
|
befores = snapshot.get("_before_signatures")
|
||||||
|
if isinstance(befores, list) and got not in befores:
|
||||||
|
return fetched, False
|
||||||
|
return snapshot, True
|
||||||
|
|
||||||
|
|
||||||
|
# ── 예약 worker 가 lease 만료된 PROCESSING 을 복구할 때의 판정 ──
|
||||||
|
RECOVER_SUCCESS = "SUCCESS" # 이미 반영·기록됨
|
||||||
|
RECOVER_RECORD = "RECORD" # 반영됨 — 버전 기록만 채우고 SUCCESS
|
||||||
|
RECOVER_RETRY = "RETRY" # 반영 안 됨이 확실 — 재시도 예산 안에서 다시 대기
|
||||||
|
RECOVER_FAIL = "FAIL" # 반영 안 됨 + 재시도 예산 소진
|
||||||
|
RECOVER_REVIEW = "REVIEW" # 반영 여부 모름 — NEEDS_REVIEW (자동 재적용 금지)
|
||||||
|
|
||||||
|
|
||||||
|
def recovery_decision(attempt: dict | None, retry_count: object) -> tuple[str, str]:
|
||||||
|
"""(판정, 사람이 읽을 사유). attempt 는 그 예약의 가장 최근 쓰기 시도(없으면 None)."""
|
||||||
|
if not attempt:
|
||||||
|
note = "worker 가 카페24에 쓰기 전에 중단되었습니다"
|
||||||
|
return (RECOVER_RETRY if can_retry(retry_count) else RECOVER_FAIL), note
|
||||||
|
status = str(attempt.get("status") or "")
|
||||||
|
if status == ATTEMPT_RECORDED:
|
||||||
|
return RECOVER_SUCCESS, "카페24 반영·기록이 끝난 뒤 중단되었습니다"
|
||||||
|
if status == ATTEMPT_REMOTE_OK:
|
||||||
|
return RECOVER_RECORD, "카페24에는 반영됐고 로컬 기록 전에 중단되었습니다"
|
||||||
|
if status in (ATTEMPT_REMOTE_FAILED, ATTEMPT_ABANDONED):
|
||||||
|
note = "카페24가 요청을 반영하지 않았습니다"
|
||||||
|
return (RECOVER_RETRY if can_retry(retry_count) else RECOVER_FAIL), note
|
||||||
|
return RECOVER_REVIEW, "카페24에 쓰는 도중 중단되어 반영 여부를 알 수 없습니다 — 쇼핑몰에서 확인하세요"
|
||||||
|
|
||||||
|
|
||||||
# ════════════════════════════════════════════════════════════
|
# ════════════════════════════════════════════════════════════
|
||||||
# 기본 정보(상품명·가격) 입력 검증 — 오른쪽 정보 패널
|
# 기본 정보(상품명·가격) 입력 검증 — 오른쪽 정보 패널
|
||||||
# ════════════════════════════════════════════════════════════
|
# ════════════════════════════════════════════════════════════
|
||||||
@@ -695,16 +984,15 @@ def build_update_options_request(
|
|||||||
edited: list[dict],
|
edited: list[dict],
|
||||||
*,
|
*,
|
||||||
option_list_type: str = "",
|
option_list_type: str = "",
|
||||||
allow_append: bool = False,
|
|
||||||
) -> dict:
|
) -> dict:
|
||||||
"""옵션명/옵션값(이름·이미지·색상·표시방식) 수정 요청.
|
"""옵션명/옵션값(이름·이미지·색상·표시방식) 수정 요청.
|
||||||
|
|
||||||
카페24 PUT options 는 `original_options`(수정 전) 와 `options`(수정 후) 를
|
카페24 PUT options 는 `original_options`(수정 전) 와 `options`(수정 후) 를
|
||||||
**위치**로 짝지어 이름을 바꾼다. 그래서
|
**위치**로 짝지어 이름을 바꾼다. 옵션값 개수는 바꿀 수 없다:
|
||||||
- 옵션값을 **뒤에 덧붙이는** 것(`allow_append`)만 허용한다 — 앞쪽 위치는 그대로라
|
- **추가**: 카페24 문서상 PUT 은 옵션 항목 추가를 지원하지 않는다 — 실물에서
|
||||||
기존 이름이 밀리지 않는다(카페24가 추가를 거부하면 그 오류가 그대로 올라온다).
|
덧붙여 보내도 오류 없이 무시되어 "저장했는데 사라짐"이 됐다(2026-11-06).
|
||||||
- 옵션값 **삭제**(개수 감소)는 거부한다 — 중간을 빼면 뒤 값들이 한 칸씩 당겨져
|
추가는 옵션 재생성(삭제 후 POST)으로 한다.
|
||||||
엉뚱한 품목의 이름이 바뀐다. 정리는 옵션 재생성(삭제 후 생성)으로 한다.
|
- **삭제**: 중간을 빼면 뒤 값들이 한 칸씩 당겨져 엉뚱한 품목의 이름이 바뀐다.
|
||||||
original: GET 응답의 options 그대로. edited: 화면에서 보낸 같은 모양의 목록.
|
original: GET 응답의 options 그대로. edited: 화면에서 보낸 같은 모양의 목록.
|
||||||
"""
|
"""
|
||||||
if len(original) != len(edited):
|
if len(original) != len(edited):
|
||||||
@@ -719,10 +1007,10 @@ def build_update_options_request(
|
|||||||
f"옵션 「{o.get('option_name')}」 의 옵션값을 줄일 수 없습니다. "
|
f"옵션 「{o.get('option_name')}」 의 옵션값을 줄일 수 없습니다. "
|
||||||
"옵션값 삭제는 카페24 API 가 지원하지 않습니다 — 옵션 재생성으로 정리하세요."
|
"옵션값 삭제는 카페24 API 가 지원하지 않습니다 — 옵션 재생성으로 정리하세요."
|
||||||
)
|
)
|
||||||
if len(e_vals) > len(o_vals) and not allow_append:
|
if len(e_vals) > len(o_vals):
|
||||||
raise ValueError(
|
raise ValueError(
|
||||||
f"옵션 「{o.get('option_name')}」 의 옵션값 개수가 카페24와 다릅니다. "
|
f"옵션 「{o.get('option_name')}」 에 옵션값을 추가할 수 없습니다. "
|
||||||
"다시 읽은 뒤 수정하세요."
|
"카페24 API 는 기존 옵션에 옵션값 추가를 지원하지 않습니다 — 「옵션 재생성」으로 추가하세요."
|
||||||
)
|
)
|
||||||
name = str(e.get("option_name") or "").strip()
|
name = str(e.get("option_name") or "").strip()
|
||||||
if not name:
|
if not name:
|
||||||
@@ -758,17 +1046,6 @@ def build_update_options_request(
|
|||||||
n_item[key] = value
|
n_item[key] = value
|
||||||
orig_entry["option_value"].append(o_item)
|
orig_entry["option_value"].append(o_item)
|
||||||
new_entry["option_value"].append(n_item)
|
new_entry["option_value"].append(n_item)
|
||||||
# 덧붙이는 새 옵션값 — 수정 전 목록에는 없고 수정 후 목록 끝에만 있다.
|
|
||||||
for ev in e_vals[len(o_vals):]:
|
|
||||||
text = str(ev.get("option_text") or "").strip()
|
|
||||||
if not text:
|
|
||||||
raise ValueError("추가할 옵션값 이름은 비울 수 없습니다.")
|
|
||||||
n_item = {"option_text": text}
|
|
||||||
for key in ("option_image_file", "option_link_image", "option_color"):
|
|
||||||
value = str(ev.get(key) or "").strip()
|
|
||||||
if value:
|
|
||||||
n_item[key] = value
|
|
||||||
new_entry["option_value"].append(n_item)
|
|
||||||
orig_out.append(orig_entry)
|
orig_out.append(orig_entry)
|
||||||
new_out.append(new_entry)
|
new_out.append(new_entry)
|
||||||
request: dict = {"original_options": orig_out, "options": new_out}
|
request: dict = {"original_options": orig_out, "options": new_out}
|
||||||
@@ -794,6 +1071,24 @@ def parse_additional_amount(value: object) -> str | None:
|
|||||||
return f"{number}.00"
|
return f"{number}.00"
|
||||||
|
|
||||||
|
|
||||||
|
def shift_additional_amounts(variants: list[dict], old_price: object, new_price: object) -> list[dict]:
|
||||||
|
"""판매가 old → new 일 때 품목 판매 가격(판매가 + 추가금액)이 그대로이도록 추가금액을 옮긴 행들.
|
||||||
|
|
||||||
|
build_variant_updates 에 그대로 넣는 화면 행 모양. 판매가가 같거나 숫자가 아니면 [].
|
||||||
|
"""
|
||||||
|
try:
|
||||||
|
delta = int(round(float(old_price))) - int(round(float(new_price))) # type: ignore[arg-type]
|
||||||
|
except (TypeError, ValueError):
|
||||||
|
return []
|
||||||
|
if not delta:
|
||||||
|
return []
|
||||||
|
return [
|
||||||
|
{"variant_code": str(v["variant_code"]),
|
||||||
|
"additional_amount": str(int(round(float(v.get("additional_amount") or 0))) + delta)}
|
||||||
|
for v in variants if v.get("variant_code")
|
||||||
|
]
|
||||||
|
|
||||||
|
|
||||||
def build_variant_updates(rows: list[dict]) -> list[dict]:
|
def build_variant_updates(rows: list[dict]) -> list[dict]:
|
||||||
"""화면 행 목록 → PUT /variants `requests` 배열. 바뀔 것이 없는 행은 뺀다."""
|
"""화면 행 목록 → PUT /variants `requests` 배열. 바뀔 것이 없는 행은 뺀다."""
|
||||||
out: list[dict] = []
|
out: list[dict] = []
|
||||||
@@ -811,9 +1106,17 @@ def build_variant_updates(rows: list[dict]) -> list[dict]:
|
|||||||
amount = parse_additional_amount(row["additional_amount"])
|
amount = parse_additional_amount(row["additional_amount"])
|
||||||
if amount is not None:
|
if amount is not None:
|
||||||
item["additional_amount"] = amount
|
item["additional_amount"] = amount
|
||||||
for flag in ("display", "selling"):
|
for flag in ("display", "selling", "use_inventory", "display_soldout"):
|
||||||
if row.get(flag) is not None:
|
if row.get(flag) is not None:
|
||||||
item[flag] = "T" if parse_tristate(row[flag]) else "F"
|
item[flag] = "T" if parse_tristate(row[flag]) else "F"
|
||||||
|
if row.get("quantity") is not None and str(row["quantity"]).strip() != "":
|
||||||
|
try:
|
||||||
|
qty = int(str(row["quantity"]).strip().replace(",", ""))
|
||||||
|
except ValueError:
|
||||||
|
raise ValueError("재고 수량은 숫자여야 합니다.") from None
|
||||||
|
if not 0 <= qty <= ADDITIONAL_AMOUNT_MAX:
|
||||||
|
raise ValueError("재고 수량은 0 이상이어야 합니다.")
|
||||||
|
item["quantity"] = qty
|
||||||
# 진열 순서(1~300) — 카페24 문서: 조합형 옵션 품목에만. 화면의 드래그 정렬이 보낸다.
|
# 진열 순서(1~300) — 카페24 문서: 조합형 옵션 품목에만. 화면의 드래그 정렬이 보낸다.
|
||||||
if row.get("display_order") is not None:
|
if row.get("display_order") is not None:
|
||||||
try:
|
try:
|
||||||
|
|||||||
@@ -0,0 +1,113 @@
|
|||||||
|
"""일회성 — 모든 옵션 상품의 품목 진열·판매를 기본몰(1) 값으로 다른 멀티쇼핑몰에 맞춘다.
|
||||||
|
|
||||||
|
# 미리보기(쓰지 않음): 바뀔 품목만 출력
|
||||||
|
docker exec dbx-main python -m app.modules.cafe24.sync_variant_flags --shops 3,4
|
||||||
|
# 실제 반영 — 출력(바꾸기 전 값 포함)을 파일로 남겨 둔다
|
||||||
|
docker exec dbx-main python -m app.modules.cafe24.sync_variant_flags --shops 3,4 --apply > sync.log
|
||||||
|
|
||||||
|
기본몰 값은 화면과 같은 기준(읽기 지연 보정)으로 읽는다. 다른 쇼핑몰에 없는 품목은 건너뛴다.
|
||||||
|
진열·판매만 보낸다(추가금액·자체코드는 건드리지 않음). 출력의 BEFORE 줄 = 되돌릴 때 쓸 원래 값.
|
||||||
|
"""
|
||||||
|
from __future__ import annotations
|
||||||
|
|
||||||
|
import argparse
|
||||||
|
import json
|
||||||
|
import os
|
||||||
|
import sys
|
||||||
|
from typing import Any
|
||||||
|
|
||||||
|
|
||||||
|
def plan_flag_sync(base: list[dict[str, Any]], shop_variants: list[dict[str, Any]]) -> list[dict[str, Any]]:
|
||||||
|
"""기본몰 품목(display/selling = bool) vs 다른 쇼핑몰 GET 품목('T'/'F') → 바꿀 PUT 요청."""
|
||||||
|
from app.integrations.cafe24 import products # noqa: WPS433
|
||||||
|
|
||||||
|
other = {str(v.get("variant_code") or ""): v for v in shop_variants}
|
||||||
|
out = []
|
||||||
|
for v in base:
|
||||||
|
o = other.get(v["variant_code"])
|
||||||
|
if o is None:
|
||||||
|
continue
|
||||||
|
req = {k: ("T" if v[k] else "F") for k in ("display", "selling")
|
||||||
|
if products._flag(o.get(k)) != v[k]} # noqa: SLF001
|
||||||
|
if req:
|
||||||
|
out.append({"variant_code": v["variant_code"], **req})
|
||||||
|
return out
|
||||||
|
|
||||||
|
|
||||||
|
def main(argv: list[str] | None = None) -> int:
|
||||||
|
from app.integrations.cafe24 import build_cafe24_api # noqa: WPS433
|
||||||
|
|
||||||
|
from . import build_cafe24_store # noqa: WPS433
|
||||||
|
|
||||||
|
ap =argparse.ArgumentParser()
|
||||||
|
ap.add_argument("--shops", required=True, help="맞출 쇼핑몰 번호(쉼표), 예: 3,4")
|
||||||
|
ap.add_argument("--apply", action="store_true", help="실제로 카페24에 쓴다(없으면 미리보기)")
|
||||||
|
args = ap.parse_args(argv)
|
||||||
|
shops = [int(s) for s in args.shops.split(",") if s.strip().isdigit() and int(s) > 1]
|
||||||
|
if not shops:
|
||||||
|
print("--shops 에 2 이상 쇼핑몰 번호가 필요합니다.", file=sys.stderr)
|
||||||
|
return 2
|
||||||
|
|
||||||
|
st = build_cafe24_store(dsn=os.environ["CAFE24_DB_URL"])
|
||||||
|
try:
|
||||||
|
return _run(st, build_cafe24_api(st), shops, args.apply)
|
||||||
|
finally:
|
||||||
|
st.close()
|
||||||
|
|
||||||
|
|
||||||
|
def _run(st: Any, api: Any, shops: list[int], apply: bool) -> int:
|
||||||
|
from app.integrations.cafe24 import products # noqa: WPS433
|
||||||
|
|
||||||
|
from . import writes # noqa: WPS433
|
||||||
|
from .routes_product_info import _load_options_and_variants # noqa: WPS433
|
||||||
|
|
||||||
|
items, truncated = products.list_all_products(api.client)
|
||||||
|
if truncated:
|
||||||
|
print("상품이 상한(1000)을 넘어 일부만 처리합니다.", file=sys.stderr)
|
||||||
|
mode = "APPLY" if apply else "DRY-RUN"
|
||||||
|
total = failed = 0
|
||||||
|
for item in items:
|
||||||
|
no = int(item["product_no"])
|
||||||
|
if str(item.get("has_option") or "T") == "F":
|
||||||
|
continue
|
||||||
|
try:
|
||||||
|
base = _load_options_and_variants(st, api, no)["variants"]
|
||||||
|
except Exception as exc: # noqa: BLE001 — 한 상품 실패가 나머지를 막지 않게
|
||||||
|
print(f"ERROR {no} 기본몰 조회 실패: {exc}")
|
||||||
|
failed += 1
|
||||||
|
continue
|
||||||
|
for shop in shops:
|
||||||
|
try:
|
||||||
|
got = api.client.get(f"/admin/products/{no}/variants", params={"shop_no": shop}, product_no=no)
|
||||||
|
except Exception as exc: # noqa: BLE001
|
||||||
|
print(f"ERROR {no} shop {shop} 조회 실패: {exc}")
|
||||||
|
failed += 1
|
||||||
|
continue
|
||||||
|
shop_vars = got.get("variants") if isinstance(got.get("variants"), list) else []
|
||||||
|
reqs = plan_flag_sync(base, shop_vars)
|
||||||
|
if not reqs:
|
||||||
|
continue
|
||||||
|
before = {str(v.get("variant_code")): {"display": v.get("display"), "selling": v.get("selling")}
|
||||||
|
for v in shop_vars if str(v.get("variant_code")) in {r["variant_code"] for r in reqs}}
|
||||||
|
print("BEFORE " + json.dumps({"product_no": no, "shop_no": shop, "variants": before}, ensure_ascii=False))
|
||||||
|
print(f"{mode} {no} shop {shop}: {len(reqs)}건 " + json.dumps(reqs, ensure_ascii=False))
|
||||||
|
total += len(reqs)
|
||||||
|
if not apply:
|
||||||
|
continue
|
||||||
|
bad = [r for r in products.update_variants(api.client, no, reqs, shop_no=shop)
|
||||||
|
if r["status"] != products.VARIANT_OK]
|
||||||
|
failed += len(bad)
|
||||||
|
writes.audit_safe(
|
||||||
|
st, actor="SYNC_SHOPS", action="update_variants", product_no=no,
|
||||||
|
result="FAIL" if bad else "SUCCESS",
|
||||||
|
detail=(f"[쇼핑몰 {shop} 진열·판매 = 기본몰] " + json.dumps(reqs, ensure_ascii=False)
|
||||||
|
+ (f" / 실패 {len(bad)}: {bad[0]['error']}" if bad else ""))[:900],
|
||||||
|
)
|
||||||
|
if bad:
|
||||||
|
print(f"ERROR {no} shop {shop}: 실패 {len(bad)}건 — {bad[0]['error']}")
|
||||||
|
print(f"{mode} 끝 — 상품 {len(items)}개 확인, 바꿀/바꾼 품목 {total}건, 오류 {failed}건")
|
||||||
|
return 1 if failed else 0
|
||||||
|
|
||||||
|
|
||||||
|
if __name__ == "__main__":
|
||||||
|
raise SystemExit(main())
|
||||||
@@ -14,6 +14,33 @@
|
|||||||
{# 읽기 지연 배너 — 카페24 관리자 API 가 아직 이전 값을 돌려주는 동안에는 마지막으로
|
{# 읽기 지연 배너 — 카페24 관리자 API 가 아직 이전 값을 돌려주는 동안에는 마지막으로
|
||||||
적용한 내용(MANUAL/SCHEDULED revision)을 편집기에 보여준다. 쇼핑몰 화면에는 이미
|
적용한 내용(MANUAL/SCHEDULED revision)을 편집기에 보여준다. 쇼핑몰 화면에는 이미
|
||||||
반영돼 있다(실물 관찰). 지문도 이 값으로 만들어 다음 적용이 충돌로 오판되지 않는다. #}
|
반영돼 있다(실물 관찰). 지문도 이 값으로 만들어 다음 적용이 충돌로 오판되지 않는다. #}
|
||||||
|
{# 반영 여부를 모르는 이전 적용 — 네트워크가 끊겼거나 처리 도중 멈춘 것. 확정 전에는 이 상품
|
||||||
|
상세설명을 다시 쓰지 않는다(재적용 금지). 쇼핑몰을 보고 사람이 결과를 고른다.
|
||||||
|
카페24 값이 그 적용 내용과 같아지면 다음 적용 때 자동으로 "반영됨"이 된다. #}
|
||||||
|
{% for att in open_attempts or [] %}
|
||||||
|
<div class="cf24-flash cf24-flash-err cf24-attempt" data-attempt-id="{{ att.id }}">
|
||||||
|
<strong>적용 결과 확인 필요</strong> — {{ att.label }} · {{ att.status_label }}{% if att.error %} ({{ att.error }}){% endif %}.
|
||||||
|
쇼핑몰 상세페이지를 열어 이 적용이 반영됐는지 확인한 뒤 고르세요. 확정하기 전에는 이 상품 상세설명을 다시 적용할 수 없습니다.
|
||||||
|
<span class="cf24-attempt-actions">
|
||||||
|
<form method="post" action="/cafe24/products/{{ product_no }}/attempts/{{ att.id }}/resolve" style="display:inline;"
|
||||||
|
data-erp-confirm="쇼핑몰에서 이 적용 내용이 보이는 것을 확인했나요? 반영됨으로 기록합니다.">
|
||||||
|
<input type="hidden" name="result" value="applied" />
|
||||||
|
<input type="hidden" name="list_query" value="{{ list_query }}" />
|
||||||
|
<button type="submit" class="erp-btn erp-btn-outline cf24-btn-inline">반영됨</button>
|
||||||
|
</form>
|
||||||
|
<form method="post" action="/cafe24/products/{{ product_no }}/attempts/{{ att.id }}/resolve" style="display:inline;"
|
||||||
|
data-erp-confirm="이 적용이 쇼핑몰에 반영되지 않은 것을 확인했나요? 반영 안 됨으로 닫습니다(다시 적용은 직접 하세요).">
|
||||||
|
<input type="hidden" name="result" value="not_applied" />
|
||||||
|
<input type="hidden" name="list_query" value="{{ list_query }}" />
|
||||||
|
<button type="submit" class="erp-btn erp-btn-outline cf24-btn-inline">반영 안 됨</button>
|
||||||
|
</form>
|
||||||
|
</span>
|
||||||
|
</div>
|
||||||
|
{% endfor %}
|
||||||
|
|
||||||
|
{# 적용·예약이 오류로 돌아왔을 때 브라우저에 남겨 둔 편집본을 여기서 되살린다(products.html JS). #}
|
||||||
|
<div id="cf24-draft-slot"></div>
|
||||||
|
|
||||||
{% if sync_pending %}
|
{% if sync_pending %}
|
||||||
<div class="cf24-flash cf24-flash-warn" id="cf24-sync-banner">
|
<div class="cf24-flash cf24-flash-warn" id="cf24-sync-banner">
|
||||||
<strong>카페24 반영 대기 중</strong> — 카페24 관리자 API 가 아직 이전 소스를 돌려주고 있어
|
<strong>카페24 반영 대기 중</strong> — 카페24 관리자 API 가 아직 이전 소스를 돌려주고 있어
|
||||||
@@ -95,7 +122,7 @@
|
|||||||
<input type="hidden" name="list_query" value="{{ list_query }}" />
|
<input type="hidden" name="list_query" value="{{ list_query }}" />
|
||||||
|
|
||||||
<div class="cf24-editor-bar">
|
<div class="cf24-editor-bar">
|
||||||
<span class="cf24-shortcuts">단축키: 주석토글[Ctrl+/] · 줄 복사[Alt+Shift+↑↓] · 줄 이동[Alt+↑↓] · 줄 삭제[Shift+Del]</span>
|
<span class="cf24-shortcuts">단축키: 주석토글[Ctrl+/] · 줄 복사[Alt+Shift+↑↓] · 줄 이동[Alt+↑↓] · 줄 삭제[Shift+Del] · 이미지 번호[Ctrl+↑↓]</span>
|
||||||
<span class="cf24-editor-bar-right">
|
<span class="cf24-editor-bar-right">
|
||||||
<input class="cf24-memo" type="text" name="memo" maxlength="200"
|
<input class="cf24-memo" type="text" name="memo" maxlength="200"
|
||||||
placeholder="변경 메모 (버전 이력에 남습니다)" />
|
placeholder="변경 메모 (버전 이력에 남습니다)" />
|
||||||
@@ -129,7 +156,7 @@
|
|||||||
<details class="cf24-details">
|
<details class="cf24-details">
|
||||||
<summary>예약 적용 — 지정한 시각에 자동 반영</summary>
|
<summary>예약 적용 — 지정한 시각에 자동 반영</summary>
|
||||||
<form class="cf24-schedule-form" id="cf24-schedule-form" method="post"
|
<form class="cf24-schedule-form" id="cf24-schedule-form" method="post"
|
||||||
action="/cafe24/schedules"
|
action="/cafe24/schedules" enctype="multipart/form-data"
|
||||||
data-confirm="지정한 시각에 자동으로 반영됩니다. 예약을 등록할까요?">
|
data-confirm="지정한 시각에 자동으로 반영됩니다. 예약을 등록할까요?">
|
||||||
<input type="hidden" name="product_no" value="{{ product_no }}" />
|
<input type="hidden" name="product_no" value="{{ product_no }}" />
|
||||||
<input type="hidden" name="list_query" value="{{ list_query }}" />
|
<input type="hidden" name="list_query" value="{{ list_query }}" />
|
||||||
@@ -178,6 +205,15 @@
|
|||||||
<option value="off">중지</option>
|
<option value="off">중지</option>
|
||||||
</select>
|
</select>
|
||||||
</label>
|
</label>
|
||||||
|
{# 대표 이미지(썸네일) — 고르면 그 시각에 교체. 파일은 DB 에 보관했다가 worker 가 올린다. #}
|
||||||
|
<div class="cf24-schedule-wide cf24-schedule-image">
|
||||||
|
<span>대표 이미지</span>
|
||||||
|
<label class="cf24-file-pick">
|
||||||
|
<input type="file" name="image" id="cf24-schedule-image" accept="image/jpeg,image/png,image/gif,image/webp" />
|
||||||
|
<span class="erp-btn erp-btn-outline">파일 선택</span>
|
||||||
|
<span class="cf24-file-name" id="cf24-schedule-image-name">변경 없음</span>
|
||||||
|
</label>
|
||||||
|
</div>
|
||||||
<label class="cf24-schedule-wide">
|
<label class="cf24-schedule-wide">
|
||||||
<span>메모</span>
|
<span>메모</span>
|
||||||
<input class="cf24-schedule-input" type="text" name="memo" maxlength="200"
|
<input class="cf24-schedule-input" type="text" name="memo" maxlength="200"
|
||||||
@@ -194,33 +230,46 @@
|
|||||||
<a class="erp-btn erp-btn-outline" href="/cafe24/schedules">예약 목록</a>
|
<a class="erp-btn erp-btn-outline" href="/cafe24/schedules">예약 목록</a>
|
||||||
</div>
|
</div>
|
||||||
<p class="cf24-muted" style="margin:8px 0 0;">
|
<p class="cf24-muted" style="margin:8px 0 0;">
|
||||||
진열·판매만 바꾸려면 위 체크를 해제하세요. 셋 중 하나 이상은 선택해야 합니다.
|
대표 이미지·진열·판매만 바꾸려면 위 체크를 해제하세요. 넷 중 하나 이상은 선택해야 합니다.
|
||||||
|
대표 이미지는 JPG·PNG·GIF·WEBP, 10MB 이하(목록/축소 이미지는 카페24가 자동 생성).
|
||||||
</p>
|
</p>
|
||||||
</form>
|
</form>
|
||||||
</details>
|
</details>
|
||||||
|
|
||||||
<details class="cf24-details">
|
<details class="cf24-details" id="cf24-history">
|
||||||
<summary>버전 이력 {% if revisions %}({{ revisions | length }}건){% endif %}</summary>
|
<summary>버전 이력 {% if revisions %}({{ revisions | length }}건){% endif %}</summary>
|
||||||
{% if revisions %}
|
{% if revisions %}
|
||||||
<div class="cf24-scroll">
|
<div class="cf24-scroll">
|
||||||
<table class="erp-table cf24-compact">
|
<table class="erp-table cf24-compact">
|
||||||
<thead>
|
<thead>
|
||||||
<tr><th>시각</th><th>유형</th><th>길이</th><th>작업자</th><th>메모</th></tr>
|
<tr><th>시각</th><th>유형</th><th>길이</th><th>작업자</th><th>메모</th><th></th></tr>
|
||||||
</thead>
|
</thead>
|
||||||
<tbody>
|
<tbody>
|
||||||
{% for rev in revisions %}
|
{% for rev in revisions %}
|
||||||
<tr>
|
<tr>
|
||||||
<td class="cf24-nowrap">{{ rev.created_at }}</td>
|
<td class="cf24-nowrap">{{ rev.created_at }}</td>
|
||||||
<td class="cf24-nowrap"><code>{{ rev.revision_type }}</code></td>
|
<td class="cf24-nowrap" title="{{ rev.type_label }}">
|
||||||
|
<code>{{ rev.revision_type }}</code>
|
||||||
|
{% if rev.source == 'LAST_WRITE' %}<span class="cf24-muted" title="카페24가 읽기 지연 중이라 마지막으로 확인된 적용값을 백업했습니다">지연</span>{% endif %}
|
||||||
|
</td>
|
||||||
<td class="cf24-nowrap">{{ rev.html_length }}자</td>
|
<td class="cf24-nowrap">{{ rev.html_length }}자</td>
|
||||||
<td class="cf24-nowrap">{{ rev.created_by or '—' }}</td>
|
<td class="cf24-nowrap">{{ rev.created_by or '—' }}</td>
|
||||||
<td>{{ rev.memo or '' }}</td>
|
<td>{{ rev.memo or '' }}</td>
|
||||||
|
<td class="cf24-nowrap">
|
||||||
|
{% if rev.html_length %}
|
||||||
|
<button type="button" class="erp-btn erp-btn-outline cf24-btn-inline" data-rev-view="{{ rev.id }}">원문</button>
|
||||||
|
{% endif %}
|
||||||
|
</td>
|
||||||
</tr>
|
</tr>
|
||||||
{% endfor %}
|
{% endfor %}
|
||||||
</tbody>
|
</tbody>
|
||||||
</table>
|
</table>
|
||||||
</div>
|
</div>
|
||||||
<p class="cf24-muted">버전 선택 복원은 Phase 6 에서 붙습니다. 내용은 모두 보관됩니다.</p>
|
<p class="cf24-muted">
|
||||||
|
「원문」에서 그 버전의 소스를 확인·복사하고, 필요하면 「이 버전으로 복원」으로 카페24에 다시 적용합니다.
|
||||||
|
복원도 적용과 같은 순서(현재값 재조회 → 직전 내용 자동 백업 → 편집 중 변경 확인)를 거치며 이력에
|
||||||
|
<code>ROLLBACK</code> 으로 남습니다. 자동 복원(예약 종료 후 되돌리기)은 쓰지 않습니다.
|
||||||
|
</p>
|
||||||
{% else %}
|
{% else %}
|
||||||
<p class="cf24-muted">아직 이 상품의 변경 이력이 없습니다.</p>
|
<p class="cf24-muted">아직 이 상품의 변경 이력이 없습니다.</p>
|
||||||
{% endif %}
|
{% endif %}
|
||||||
|
|||||||
@@ -1,5 +1,5 @@
|
|||||||
{# 카페24 모듈 공용 상단 탭. active_tab: products | design:pc_detail | design:mobile_detail | design:swiper | schedules | system #}
|
{# 카페24 모듈 공용 상단 탭. active_tab: products | design:pc_detail | design:mobile_detail | design:swiper | schedules | system #}
|
||||||
<div class="erp-page-actions" style="display:flex;gap:8px;flex-wrap:wrap;align-items:center;">
|
<div class="erp-page-actions" style="display:flex;gap:8px;flex-wrap:wrap;align-items:center;margin-bottom:10px;">
|
||||||
<a class="erp-btn {% if active_tab=='products' %}erp-btn-primary{% else %}erp-btn-outline{% endif %}"
|
<a class="erp-btn {% if active_tab=='products' %}erp-btn-primary{% else %}erp-btn-outline{% endif %}"
|
||||||
href="/cafe24/">상품관리</a>
|
href="/cafe24/">상품관리</a>
|
||||||
<a class="erp-btn {% if active_tab=='design:pc_detail' %}erp-btn-primary{% else %}erp-btn-outline{% endif %}"
|
<a class="erp-btn {% if active_tab=='design:pc_detail' %}erp-btn-primary{% else %}erp-btn-outline{% endif %}"
|
||||||
|
|||||||
@@ -1,7 +1,7 @@
|
|||||||
{% extends "erp_base.html" %}
|
{% extends "erp_base.html" %}
|
||||||
|
|
||||||
{% block head_extra %}
|
{% block head_extra %}
|
||||||
<link rel="stylesheet" href="/static/cafe24.css?v=20260819c" />
|
<link rel="stylesheet" href="/static/cafe24.css?v=20261110a" />
|
||||||
{% endblock %}
|
{% endblock %}
|
||||||
|
|
||||||
{% block content %}
|
{% block content %}
|
||||||
|
|||||||
@@ -1,7 +1,7 @@
|
|||||||
{% extends "erp_base.html" %}
|
{% extends "erp_base.html" %}
|
||||||
|
|
||||||
{% block head_extra %}
|
{% block head_extra %}
|
||||||
<link rel="stylesheet" href="/static/cafe24.css?v=20260918e" />
|
<link rel="stylesheet" href="/static/cafe24.css?v=20261110a" />
|
||||||
{% endblock %}
|
{% endblock %}
|
||||||
|
|
||||||
{% block content %}
|
{% block content %}
|
||||||
@@ -45,6 +45,7 @@
|
|||||||
<thead>
|
<thead>
|
||||||
<tr>
|
<tr>
|
||||||
<th class="cf24-col-no" data-sort-key="no" data-sort-type="num">번호</th>
|
<th class="cf24-col-no" data-sort-key="no" data-sort-type="num">번호</th>
|
||||||
|
<th class="cf24-col-thumb"></th>
|
||||||
<th class="cf24-col-name" data-sort-key="name" data-sort-type="text">상품명</th>
|
<th class="cf24-col-name" data-sort-key="name" data-sort-type="text">상품명</th>
|
||||||
<th class="cf24-col-flag" data-sort-key="display" data-sort-type="num">진열</th>
|
<th class="cf24-col-flag" data-sort-key="display" data-sort-type="num">진열</th>
|
||||||
<th class="cf24-col-flag" data-sort-key="selling" data-sort-type="num">판매</th>
|
<th class="cf24-col-flag" data-sort-key="selling" data-sort-type="num">판매</th>
|
||||||
@@ -60,6 +61,7 @@
|
|||||||
data-selling="{{ 1 if r.selling else 0 }}"
|
data-selling="{{ 1 if r.selling else 0 }}"
|
||||||
data-updated="{{ r.updated_date }}">
|
data-updated="{{ r.updated_date }}">
|
||||||
<td class="cf24-col-no">{{ r.product_no }}</td>
|
<td class="cf24-col-no">{{ r.product_no }}</td>
|
||||||
|
<td class="cf24-col-thumb"><img class="cf24-thumb" {% if r.thumb %}src="{{ r.thumb }}"{% endif %} loading="lazy" alt="" /></td>
|
||||||
<td class="cf24-col-name" title="{{ r.product_name }}">
|
<td class="cf24-col-name" title="{{ r.product_name }}">
|
||||||
<a href="/cafe24/?{{ qs }}selected={{ r.product_no }}">{{ r.product_name }}</a>
|
<a href="/cafe24/?{{ qs }}selected={{ r.product_no }}">{{ r.product_name }}</a>
|
||||||
</td>
|
</td>
|
||||||
@@ -122,10 +124,13 @@
|
|||||||
<div class="cf24-modal-body cf24-options-body" id="cf24-options-body"></div>
|
<div class="cf24-modal-body cf24-options-body" id="cf24-options-body"></div>
|
||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
|
{# 소스의 <img> 위에 마우스를 올리면 화면 오른쪽에 뜨는 미리보기 — setupCodeEditor 가 켜고 끈다. #}
|
||||||
|
<div class="cf24-img-preview" id="cf24-img-preview" hidden><div class="cf24-img-preview-name"></div><img alt="이미지를 불러올 수 없습니다" /></div>
|
||||||
{% endblock %}
|
{% endblock %}
|
||||||
|
|
||||||
{% block scripts %}
|
{% block scripts %}
|
||||||
<script src="/static/cafe24-options.js?v=20260928c"></script>
|
<script src="/static/cafe24-options.js?v=20261110c"></script>
|
||||||
<script>
|
<script>
|
||||||
(function () {
|
(function () {
|
||||||
var pane = document.getElementById("cf24-editor-pane");
|
var pane = document.getElementById("cf24-editor-pane");
|
||||||
@@ -164,14 +169,42 @@
|
|||||||
last = TOKEN_RE.lastIndex;
|
last = TOKEN_RE.lastIndex;
|
||||||
if (m[1]) { out += '<span class="cf24-t-com">' + esc(m[1]) + "</span>"; continue; }
|
if (m[1]) { out += '<span class="cf24-t-com">' + esc(m[1]) + "</span>"; continue; }
|
||||||
if (m[2]) { out += '<span class="cf24-t-doc">' + esc(m[2]) + "</span>"; continue; }
|
if (m[2]) { out += '<span class="cf24-t-doc">' + esc(m[2]) + "</span>"; continue; }
|
||||||
out += '<span class="cf24-t-pun">' + esc(m[3]) + "</span>" +
|
var tag = '<span class="cf24-t-pun">' + esc(m[3]) + "</span>" +
|
||||||
'<span class="cf24-t-tag">' + esc(m[4]) + "</span>" +
|
'<span class="cf24-t-tag">' + esc(m[4]) + "</span>" +
|
||||||
paintAttrs(m[5]) +
|
paintAttrs(m[5]) +
|
||||||
'<span class="cf24-t-pun">' + esc(m[6]) + "</span>";
|
'<span class="cf24-t-pun">' + esc(m[6]) + "</span>";
|
||||||
|
out += /^img$/i.test(m[4]) ? '<span class="cf24-t-img">' + tag + "</span>" : tag;
|
||||||
}
|
}
|
||||||
return out + esc(src.slice(last));
|
return out + esc(src.slice(last));
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// 상대 경로는 쇼핑몰 루트 기준이다: ../img/a.jpg → https://쇼핑몰/img/a.jpg
|
||||||
|
function imgPreviewUrl(tag) {
|
||||||
|
var m = tag.match(/\ssrc\s*=\s*(?:"([^"]*)"|'([^']*)'|([^\s>]+))/i);
|
||||||
|
var src = m && (m[1] || m[2] || m[3]);
|
||||||
|
var shop = document.getElementById("cf24-url");
|
||||||
|
if (!src || !shop) return "";
|
||||||
|
try { return new URL(src, new URL("/", shop.value)).href; }
|
||||||
|
catch (err) { return ""; }
|
||||||
|
}
|
||||||
|
|
||||||
|
function imgFileName(url) {
|
||||||
|
var name = new URL(url).pathname.split("/").pop();
|
||||||
|
// URL 이 한글 파일명을 %XX 로 바꿔 놓으므로 되돌린다.
|
||||||
|
try { return decodeURIComponent(name); }
|
||||||
|
catch (err) { return name; }
|
||||||
|
}
|
||||||
|
|
||||||
|
function showImgPreview(url) {
|
||||||
|
var box = document.getElementById("cf24-img-preview");
|
||||||
|
var img = box.lastElementChild;
|
||||||
|
if (url && img.getAttribute("src") !== url) {
|
||||||
|
img.src = url;
|
||||||
|
box.firstElementChild.textContent = imgFileName(url);
|
||||||
|
}
|
||||||
|
box.hidden = !url;
|
||||||
|
}
|
||||||
|
|
||||||
function setupCodeEditor() {
|
function setupCodeEditor() {
|
||||||
var ta = document.getElementById("cf24-html-pc");
|
var ta = document.getElementById("cf24-html-pc");
|
||||||
var hl = document.getElementById("cf24-hl-pc");
|
var hl = document.getElementById("cf24-hl-pc");
|
||||||
@@ -337,6 +370,62 @@
|
|||||||
applyEdit(from, to, "", lineFrom + col, lineFrom + col);
|
applyEdit(from, to, "", lineFrom + col, lineFrom + col);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/* Ctrl+↑/↓ — 커서가 <img> 태그 안 어디에 있든 src 파일명(.jpg/.gif/.png)의 번호를 바꾼다.
|
||||||
|
a.jpg → a_2.jpg → a_3.jpg …, a_5.jpg → a_6.jpg …. 내릴 때는 원래 번호(없었으면 원래 이름) 아래로 안 간다.
|
||||||
|
원래 번호는 imgStep 에 기억한다 — 이 단축키 말고 소스가 바뀌거나 다른 이미지로 옮기면 그때 번호가 새 원래 번호.
|
||||||
|
조건이 안 맞으면 false — 브라우저 기본 동작을 막지 않는다. */
|
||||||
|
var imgStep = null;
|
||||||
|
|
||||||
|
function stepImgSuffix(up) {
|
||||||
|
var at = ta.selectionStart, value = ta.value;
|
||||||
|
if (at !== ta.selectionEnd) return false;
|
||||||
|
|
||||||
|
var tagRe = /<img\s(?:"[^"]*"|'[^']*'|[^>"'])*>/gi, tag;
|
||||||
|
while ((tag = tagRe.exec(value)) && tagRe.lastIndex <= at);
|
||||||
|
if (!tag || tag.index >= at) return false;
|
||||||
|
|
||||||
|
var src = tag[0].match(/\ssrc\s*=\s*(?:"([^"]*)|'([^']*)|([^\s>"']+))/i);
|
||||||
|
var path = src && (src[1] || src[2] || src[3]);
|
||||||
|
var file = path && path.match(/^(.*)\.(?:jpg|gif|png)(?=[?#]|$)/i);
|
||||||
|
if (!file) return false;
|
||||||
|
|
||||||
|
var ext = tag.index + src.index + src[0].length - path.length + file[1].length; // 확장자 시작 위치
|
||||||
|
var num = file[1].match(/_(\d{1,15})$/); // 16자리부터는 숫자 계산이 어긋나 번호로 보지 않는다
|
||||||
|
var orig = imgStep && imgStep.value === value && imgStep.ext === ext ? imgStep.orig : (num ? num[1] : "");
|
||||||
|
var n = num ? Number(num[1]) : 1;
|
||||||
|
if (!up && n <= (orig ? Number(orig) : 1)) return true; // 원래 번호 아래로는 안 간다
|
||||||
|
|
||||||
|
var next = up ? n + 1 : n - 1;
|
||||||
|
// a_01 → a_02 처럼 원래 자릿수를 유지한다.
|
||||||
|
var text = !orig && next < 2 ? "" : "_" + String(next).padStart(orig.length, "0");
|
||||||
|
var from = ext - (num ? num[0].length : 0);
|
||||||
|
var caret = at >= ext ? at + text.length - (ext - from) : at <= from ? at : from + text.length;
|
||||||
|
applyEdit(from, ext, text, caret, caret);
|
||||||
|
imgStep = { value: ta.value, ext: from + text.length, orig: orig };
|
||||||
|
return true;
|
||||||
|
}
|
||||||
|
|
||||||
|
/* 이미지 미리보기 — 맨 위 textarea 를 판정에서 잠깐 빼고 색칠 층의 <img> 를 찾는다.
|
||||||
|
글자 폭을 계산하지 않아 한글·탭·여러 줄 태그에서도 위치가 어긋나지 않는다.
|
||||||
|
shortcut: HL_LIMIT 초과 소스는 색칠을 안 해 미리보기도 안 뜬다, 그런 상품이 나오면 글자 위치 계산으로 교체. */
|
||||||
|
var hoverTag = null;
|
||||||
|
|
||||||
|
function setHoverTag(tag) {
|
||||||
|
if (tag === hoverTag) return;
|
||||||
|
if (hoverTag) hoverTag.classList.remove("cf24-t-img-on");
|
||||||
|
if (tag) tag.classList.add("cf24-t-img-on");
|
||||||
|
hoverTag = tag;
|
||||||
|
showImgPreview(tag ? imgPreviewUrl(tag.textContent) : "");
|
||||||
|
}
|
||||||
|
|
||||||
|
ta.addEventListener("mousemove", function (e) {
|
||||||
|
ta.style.pointerEvents = "none";
|
||||||
|
var el = document.elementFromPoint(e.clientX, e.clientY);
|
||||||
|
ta.style.pointerEvents = "";
|
||||||
|
setHoverTag(el && el.closest(".cf24-t-img"));
|
||||||
|
});
|
||||||
|
ta.addEventListener("mouseleave", function () { setHoverTag(null); });
|
||||||
|
|
||||||
ta.addEventListener("scroll", sync);
|
ta.addEventListener("scroll", sync);
|
||||||
ta.addEventListener("input", function () { dirty = true; refresh(); });
|
ta.addEventListener("input", function () { dirty = true; refresh(); });
|
||||||
ta.addEventListener("keydown", function (e) {
|
ta.addEventListener("keydown", function (e) {
|
||||||
@@ -356,6 +445,10 @@
|
|||||||
else moveLines(isDown);
|
else moveLines(isDown);
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
|
if (e.ctrlKey && !e.altKey && !e.metaKey && !e.shiftKey && (isUp || isDown) && stepImgSuffix(isUp)) {
|
||||||
|
e.preventDefault();
|
||||||
|
return;
|
||||||
|
}
|
||||||
// Shift+Delete — 줄 삭제. (윈도우 기본 동작인 "잘라내기"를 대신한다)
|
// Shift+Delete — 줄 삭제. (윈도우 기본 동작인 "잘라내기"를 대신한다)
|
||||||
if (e.shiftKey && !e.ctrlKey && !e.altKey && !e.metaKey &&
|
if (e.shiftKey && !e.ctrlKey && !e.altKey && !e.metaKey &&
|
||||||
(e.key === "Delete" || e.code === "Delete")) {
|
(e.key === "Delete" || e.code === "Delete")) {
|
||||||
@@ -470,6 +563,17 @@
|
|||||||
// 날짜·시간도 두 개의 별도 input 값을 합쳐 서버가 기대하는 형식으로 만든다.
|
// 날짜·시간도 두 개의 별도 input 값을 합쳐 서버가 기대하는 형식으로 만든다.
|
||||||
var schedForm = pane.querySelector("#cf24-schedule-form");
|
var schedForm = pane.querySelector("#cf24-schedule-form");
|
||||||
if (schedForm) {
|
if (schedForm) {
|
||||||
|
var schedImg = schedForm.querySelector("#cf24-schedule-image");
|
||||||
|
var schedImgName = schedForm.querySelector("#cf24-schedule-image-name");
|
||||||
|
if (schedImg) schedImg.addEventListener("change", function () {
|
||||||
|
var f = schedImg.files && schedImg.files[0];
|
||||||
|
if (f && f.size > 10 * 1024 * 1024) {
|
||||||
|
window.erpAlert("10MB 를 넘는 파일은 올릴 수 없습니다.");
|
||||||
|
schedImg.value = "";
|
||||||
|
f = null;
|
||||||
|
}
|
||||||
|
schedImgName.textContent = f ? f.name + " (" + Math.round(f.size / 1024) + "KB) — 그 시각에 교체" : "변경 없음";
|
||||||
|
});
|
||||||
schedForm.addEventListener("submit", function (e) {
|
schedForm.addEventListener("submit", function (e) {
|
||||||
var box = document.getElementById("cf24-html-pc");
|
var box = document.getElementById("cf24-html-pc");
|
||||||
var holder = document.getElementById("cf24-schedule-html");
|
var holder = document.getElementById("cf24-schedule-html");
|
||||||
@@ -485,7 +589,8 @@
|
|||||||
// 확인창이 비동기라 일단 제출을 멈추고, 확인을 받으면 다시 보낸다.
|
// 확인창이 비동기라 일단 제출을 멈추고, 확인을 받으면 다시 보낸다.
|
||||||
// (required 검사는 이미 통과한 뒤라 form.submit() 으로 보내도 안전하다)
|
// (required 검사는 이미 통과한 뒤라 form.submit() 으로 보내도 안전하다)
|
||||||
e.preventDefault();
|
e.preventDefault();
|
||||||
window.erpConfirm(schedForm.dataset.confirm).then(function (ok) {
|
var imgFile = schedImg && schedImg.files && schedImg.files[0];
|
||||||
|
window.erpConfirm(schedForm.dataset.confirm + (imgFile ? "\n\n대표 이미지: 「" + imgFile.name + "」(으)로 교체" : "")).then(function (ok) {
|
||||||
if (!ok) return;
|
if (!ok) return;
|
||||||
dirty = false; // 예약 등록으로 화면을 떠나므로 편집 중 경고를 끈다.
|
dirty = false; // 예약 등록으로 화면을 떠나므로 편집 중 경고를 끈다.
|
||||||
schedForm.submit();
|
schedForm.submit();
|
||||||
@@ -824,6 +929,7 @@
|
|||||||
window.erpAlert("상품명은 비울 수 없습니다.");
|
window.erpAlert("상품명은 비울 수 없습니다.");
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
|
if ("price" in payload) lines.push("\n※ 옵션 품목은 판매 가격이 그대로이도록 추가금액을 함께 조정합니다.");
|
||||||
window.erpConfirm("다음 항목을 카페24에 바로 반영합니다. 계속할까요?\n\n" + lines.join("\n"))
|
window.erpConfirm("다음 항목을 카페24에 바로 반영합니다. 계속할까요?\n\n" + lines.join("\n"))
|
||||||
.then(function (ok) {
|
.then(function (ok) {
|
||||||
if (!ok) return;
|
if (!ok) return;
|
||||||
@@ -838,7 +944,10 @@
|
|||||||
form.querySelector('[name="retail_price"]').value = p.retail_price ? String(parseInt(p.retail_price, 10)) : "";
|
form.querySelector('[name="retail_price"]').value = p.retail_price ? String(parseInt(p.retail_price, 10)) : "";
|
||||||
commitValues(form);
|
commitValues(form);
|
||||||
if (p.product_name) paintTitle(p.product_name);
|
if (p.product_name) paintTitle(p.product_name);
|
||||||
setMsg(msg, (data.changed && data.changed.length) ? "카페24에 반영했습니다." : "변경된 값이 없어 보내지 않았습니다.", "is-ok");
|
var done = (data.changed && data.changed.length) ? "카페24에 반영했습니다." : "변경된 값이 없어 보내지 않았습니다.";
|
||||||
|
if (data.variants_shifted) done += " 품목 " + data.variants_shifted + "건 추가금액 조정.";
|
||||||
|
if (data.variants_error) setMsg(msg, done + " " + data.variants_error, "is-err");
|
||||||
|
else setMsg(msg, done, "is-ok");
|
||||||
})
|
})
|
||||||
.catch(function (err) { setMsg(msg, "실패: " + err.message, "is-err"); })
|
.catch(function (err) { setMsg(msg, "실패: " + err.message, "is-err"); })
|
||||||
.then(function () { btn.disabled = false; });
|
.then(function () { btn.disabled = false; });
|
||||||
@@ -864,6 +973,8 @@
|
|||||||
if (link) { link.href = p.detail_image; link.classList.remove("is-hidden"); }
|
if (link) { link.href = p.detail_image; link.classList.remove("is-hidden"); }
|
||||||
if (empty) empty.classList.add("is-hidden");
|
if (empty) empty.classList.add("is-hidden");
|
||||||
}
|
}
|
||||||
|
var thumb = document.querySelector('#cf24-list tr.cf24-row[data-no="' + no + '"] .cf24-thumb');
|
||||||
|
if (thumb && (p.tiny_image || p.detail_image)) thumb.src = bust(p.tiny_image || p.detail_image);
|
||||||
root.querySelectorAll("[data-image-key]").forEach(function (el) {
|
root.querySelectorAll("[data-image-key]").forEach(function (el) {
|
||||||
var v = p[el.dataset.imageKey];
|
var v = p[el.dataset.imageKey];
|
||||||
if (!v) return;
|
if (!v) return;
|
||||||
|
|||||||
@@ -1,7 +1,7 @@
|
|||||||
{% extends "erp_base.html" %}
|
{% extends "erp_base.html" %}
|
||||||
|
|
||||||
{% block head_extra %}
|
{% block head_extra %}
|
||||||
<link rel="stylesheet" href="/static/cafe24.css?v=20260819c" />
|
<link rel="stylesheet" href="/static/cafe24.css?v=20261110a" />
|
||||||
{% endblock %}
|
{% endblock %}
|
||||||
|
|
||||||
{% block content %}
|
{% block content %}
|
||||||
@@ -13,7 +13,7 @@
|
|||||||
<div class="erp-card cf24-card">
|
<div class="erp-card cf24-card">
|
||||||
<div class="cf24-card-head">
|
<div class="cf24-card-head">
|
||||||
<h3>예약 목록</h3>
|
<h3>예약 목록</h3>
|
||||||
<span class="cf24-muted">대기 {{ pending }}건 · 최근 200건</span>
|
<span class="cf24-muted">대기 {{ pending }}건{% if review %} · <strong class="cf24-err">확인 필요 {{ review }}건</strong>{% endif %} · 최근 200건</span>
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
<p class="cf24-note">
|
<p class="cf24-note">
|
||||||
@@ -22,6 +22,11 @@
|
|||||||
적용 직전 내용은 상품별 <code>BACKUP</code> 버전으로 보관됩니다.
|
적용 직전 내용은 상품별 <code>BACKUP</code> 버전으로 보관됩니다.
|
||||||
<strong>대기</strong> 상태인 예약만 취소할 수 있습니다.
|
<strong>대기</strong> 상태인 예약만 취소할 수 있습니다.
|
||||||
</p>
|
</p>
|
||||||
|
<p class="cf24-note">
|
||||||
|
<strong>확인 필요</strong> — 카페24에 쓰는 도중 응답이 끊겼거나 worker 가 멈춰 반영 여부를 알 수 없는 예약입니다.
|
||||||
|
자동으로 다시 실행하지 않습니다. 쇼핑몰에서 상세페이지·진열/판매를 확인한 뒤
|
||||||
|
「반영됨」(완료로 기록) · 「다시 실행」 · 「실패로 종료」 중 하나를 고르세요.
|
||||||
|
</p>
|
||||||
|
|
||||||
{% if rows %}
|
{% if rows %}
|
||||||
<div class="cf24-scroll">
|
<div class="cf24-scroll">
|
||||||
@@ -32,7 +37,7 @@
|
|||||||
<th style="width:130px;">예정 시각</th>
|
<th style="width:130px;">예정 시각</th>
|
||||||
<th style="width:66px;">상품</th>
|
<th style="width:66px;">상품</th>
|
||||||
<th>상품명</th>
|
<th>상품명</th>
|
||||||
<th style="width:150px;">적용 내용</th>
|
<th style="width:170px;">적용 내용</th>
|
||||||
<th style="width:96px;">상태</th>
|
<th style="width:96px;">상태</th>
|
||||||
<th>메모 / 오류</th>
|
<th>메모 / 오류</th>
|
||||||
<th style="width:130px;">등록자</th>
|
<th style="width:130px;">등록자</th>
|
||||||
@@ -48,17 +53,19 @@
|
|||||||
<a href="/cafe24/?selected={{ r.product_no }}">{{ r.product_no }}</a>
|
<a href="/cafe24/?selected={{ r.product_no }}">{{ r.product_no }}</a>
|
||||||
</td>
|
</td>
|
||||||
<td>{{ r.product_name or '—' }}</td>
|
<td>{{ r.product_name or '—' }}</td>
|
||||||
<td class="cf24-nowrap">{{ r.action_label }}</td>
|
<td class="cf24-nowrap">{{ r.action_label }}
|
||||||
|
{% if r.image_type %}<a href="/cafe24/schedules/{{ r.id }}/image" target="_blank" rel="noopener" title="{{ r.image_name }}"><img class="cf24-sched-img" src="/cafe24/schedules/{{ r.id }}/image" alt="{{ r.image_name }}" loading="lazy" /></a>{% endif %}</td>
|
||||||
<td class="cf24-nowrap">
|
<td class="cf24-nowrap">
|
||||||
{% if r.status == 'SUCCESS' %}<span class="erp-badge cf24-badge-ok">{{ r.status_label }}</span>
|
{% if r.status == 'SUCCESS' %}<span class="erp-badge cf24-badge-ok">{{ r.status_label }}</span>
|
||||||
{% elif r.status == 'FAILED' %}<span class="cf24-err">{{ r.status_label }}</span>
|
{% elif r.status == 'FAILED' %}<span class="cf24-err">{{ r.status_label }}</span>
|
||||||
{% elif r.status == 'PENDING' %}<span class="cf24-warn">{{ r.status_label }}</span>
|
{% elif r.status == 'PENDING' %}<span class="cf24-warn">{{ r.status_label }}</span>
|
||||||
|
{% elif r.status == 'NEEDS_REVIEW' %}<span class="erp-badge cf24-badge-off">{{ r.status_label }}</span>
|
||||||
{% else %}<span class="cf24-muted">{{ r.status_label }}</span>{% endif %}
|
{% else %}<span class="cf24-muted">{{ r.status_label }}</span>{% endif %}
|
||||||
{% if r.retry_count %}<span class="cf24-muted">({{ r.retry_count }}회)</span>{% endif %}
|
{% if r.retry_count %}<span class="cf24-muted">({{ r.retry_count }}회)</span>{% endif %}
|
||||||
</td>
|
</td>
|
||||||
<td>
|
<td>
|
||||||
{{ r.memo or '' }}
|
{{ r.memo or '' }}
|
||||||
{% if r.last_error %}<div class="cf24-err">{{ r.last_error }}</div>{% endif %}
|
{% if r.last_error %}<div class="{{ 'cf24-muted' if r.status == 'SUCCESS' else 'cf24-err' }}">{{ r.last_error }}</div>{% endif %}
|
||||||
</td>
|
</td>
|
||||||
<td class="cf24-nowrap">{{ r.created_by or '—' }}</td>
|
<td class="cf24-nowrap">{{ r.created_by or '—' }}</td>
|
||||||
<td class="cf24-nowrap">
|
<td class="cf24-nowrap">
|
||||||
@@ -67,6 +74,22 @@
|
|||||||
data-erp-confirm="예약 #{{ r.id }} 을 취소할까요?">
|
data-erp-confirm="예약 #{{ r.id }} 을 취소할까요?">
|
||||||
<button type="submit" class="erp-btn erp-btn-outline">취소</button>
|
<button type="submit" class="erp-btn erp-btn-outline">취소</button>
|
||||||
</form>
|
</form>
|
||||||
|
{% elif r.needs_review %}
|
||||||
|
<form method="post" action="/cafe24/schedules/{{ r.id }}/review" class="cf24-review-form"
|
||||||
|
data-erp-confirm="쇼핑몰에서 반영된 것을 확인했나요? 예약 #{{ r.id }} 을 완료로 기록합니다.">
|
||||||
|
<input type="hidden" name="action" value="applied" />
|
||||||
|
<button type="submit" class="erp-btn erp-btn-outline">반영됨</button>
|
||||||
|
</form>
|
||||||
|
<form method="post" action="/cafe24/schedules/{{ r.id }}/review" class="cf24-review-form"
|
||||||
|
data-erp-confirm="예약 #{{ r.id }} 을 다시 실행합니다. 이미 반영돼 있었다면 같은 내용을 한 번 더 적용합니다. 계속할까요?">
|
||||||
|
<input type="hidden" name="action" value="rerun" />
|
||||||
|
<button type="submit" class="erp-btn erp-btn-outline">다시 실행</button>
|
||||||
|
</form>
|
||||||
|
<form method="post" action="/cafe24/schedules/{{ r.id }}/review" class="cf24-review-form"
|
||||||
|
data-erp-confirm="예약 #{{ r.id }} 을 실패로 종료할까요?">
|
||||||
|
<input type="hidden" name="action" value="close" />
|
||||||
|
<button type="submit" class="erp-btn erp-btn-outline">실패로 종료</button>
|
||||||
|
</form>
|
||||||
{% endif %}
|
{% endif %}
|
||||||
</td>
|
</td>
|
||||||
</tr>
|
</tr>
|
||||||
|
|||||||
@@ -1,7 +1,7 @@
|
|||||||
{% extends "erp_base.html" %}
|
{% extends "erp_base.html" %}
|
||||||
|
|
||||||
{% block head_extra %}
|
{% block head_extra %}
|
||||||
<link rel="stylesheet" href="/static/cafe24.css?v=20260819c" />
|
<link rel="stylesheet" href="/static/cafe24.css?v=20261110a" />
|
||||||
{% endblock %}
|
{% endblock %}
|
||||||
|
|
||||||
{% block content %}
|
{% block content %}
|
||||||
|
|||||||
@@ -0,0 +1,546 @@
|
|||||||
|
"""카페24 모듈 단위 테스트용 대역 — 메모리 저장소 · 가짜 카페24 · 가짜 FTP.
|
||||||
|
|
||||||
|
실제 DB 의 동작(잠금 만료, SKIP LOCKED, JSONB 병합 등)은 이 대역으로 증명되지 않는다.
|
||||||
|
그 부분은 test_cafe24_db.py(격리된 로컬 PostgreSQL)가 검증한다. 여기서는 쓰기 순서와
|
||||||
|
분기(백업·충돌·결과 분류·복구 판정)를 빠르게 확인한다.
|
||||||
|
"""
|
||||||
|
|
||||||
|
from __future__ import annotations
|
||||||
|
|
||||||
|
import copy
|
||||||
|
import ftplib
|
||||||
|
import itertools
|
||||||
|
import uuid
|
||||||
|
from contextlib import contextmanager
|
||||||
|
from datetime import datetime, timedelta
|
||||||
|
from typing import Any
|
||||||
|
|
||||||
|
from app.integrations.cafe24.errors import Cafe24ApiError
|
||||||
|
from app.modules.cafe24 import store
|
||||||
|
from app.timezone import KST, now_kst
|
||||||
|
|
||||||
|
|
||||||
|
class MemoryStore:
|
||||||
|
"""Cafe24Store 가 writes/worker/라우터에 주는 메서드를 메모리로 흉내낸다."""
|
||||||
|
|
||||||
|
def __init__(self) -> None:
|
||||||
|
self._ids = itertools.count(1)
|
||||||
|
self.revisions: dict[int, dict[str, Any]] = {}
|
||||||
|
self.attempts: dict[int, dict[str, Any]] = {}
|
||||||
|
self.locks: dict[str, dict[str, Any]] = {}
|
||||||
|
self.schedules: dict[int, dict[str, Any]] = {}
|
||||||
|
self.snapshots: dict[int, dict[str, Any]] = {}
|
||||||
|
self.audits: list[dict[str, Any]] = []
|
||||||
|
self.products: dict[int, dict[str, Any]] = {}
|
||||||
|
self.fail_on: set[str] = set() # 이 메서드 이름이 들어 있으면 예외(기록 실패 재현)
|
||||||
|
self.schema_ok = True
|
||||||
|
|
||||||
|
def _maybe_fail(self, name: str) -> None:
|
||||||
|
if name in self.fail_on:
|
||||||
|
raise RuntimeError(f"DB 장애({name})")
|
||||||
|
|
||||||
|
# ── 스키마 ──
|
||||||
|
def write_schema_ready(self) -> bool:
|
||||||
|
return self.schema_ok
|
||||||
|
|
||||||
|
# ── 잠금 ──
|
||||||
|
def acquire_lock(self, key, *, owner, purpose, ttl_seconds):
|
||||||
|
now = now_kst()
|
||||||
|
held = self.locks.get(key)
|
||||||
|
if held and held["expires_at"] > now:
|
||||||
|
return None
|
||||||
|
token = uuid.uuid4().hex
|
||||||
|
self.locks[key] = {"owner": owner, "purpose": purpose, "token": token,
|
||||||
|
"expires_at": now + timedelta(seconds=ttl_seconds)}
|
||||||
|
return token
|
||||||
|
|
||||||
|
def renew_lock(self, key, token, *, ttl_seconds):
|
||||||
|
held = self.locks.get(key)
|
||||||
|
if not held or held["token"] != token or held["expires_at"] <= now_kst():
|
||||||
|
return False
|
||||||
|
held["expires_at"] = now_kst() + timedelta(seconds=ttl_seconds)
|
||||||
|
return True
|
||||||
|
|
||||||
|
def release_lock(self, key, token):
|
||||||
|
if self.locks.get(key, {}).get("token") == token:
|
||||||
|
del self.locks[key]
|
||||||
|
|
||||||
|
def lock_holder(self, key):
|
||||||
|
held = self.locks.get(key)
|
||||||
|
return dict(held) if held and held["expires_at"] > now_kst() else {}
|
||||||
|
|
||||||
|
def expire_lock(self, key):
|
||||||
|
if key in self.locks:
|
||||||
|
self.locks[key]["expires_at"] = now_kst() - timedelta(seconds=1)
|
||||||
|
|
||||||
|
# ── 버전 ──
|
||||||
|
def add_revision(self, *, product_no, html_content, revision_type, memo="", created_by="",
|
||||||
|
mall_id="", shop_no=1, source="", source_revision_id=None):
|
||||||
|
self._maybe_fail("add_revision")
|
||||||
|
rid = next(self._ids)
|
||||||
|
self.revisions[rid] = {
|
||||||
|
"id": rid, "product_no": int(product_no), "html_content": html_content or "",
|
||||||
|
"revision_type": store.normalize_revision_type(revision_type), "memo": memo,
|
||||||
|
"created_by": created_by, "mall_id": mall_id, "shop_no": shop_no, "source": source,
|
||||||
|
"source_revision_id": source_revision_id, "created_at": now_kst().isoformat(),
|
||||||
|
}
|
||||||
|
return rid
|
||||||
|
|
||||||
|
def get_revision(self, revision_id):
|
||||||
|
return dict(self.revisions.get(int(revision_id), {}))
|
||||||
|
|
||||||
|
def list_revisions(self, product_no, *, limit=20):
|
||||||
|
rows = [dict(r, html_length=len(r["html_content"])) for r in self.revisions.values()
|
||||||
|
if r["product_no"] == int(product_no)]
|
||||||
|
return sorted(rows, key=lambda r: -r["id"])[:limit]
|
||||||
|
|
||||||
|
def of_type(self, revision_type):
|
||||||
|
return [r for r in self.revisions.values() if r["revision_type"] == revision_type]
|
||||||
|
|
||||||
|
# ── 쓰기 시도 ──
|
||||||
|
def start_attempt(self, **fields):
|
||||||
|
self._maybe_fail("start_attempt")
|
||||||
|
aid = next(self._ids)
|
||||||
|
row = {"id": aid, "status": store.ATTEMPT_STARTED, "error": "", "remote_updated_at": "",
|
||||||
|
"remote_at": None, "resolved_by": "", "applied_revision_id": None,
|
||||||
|
"created_at": now_kst(), "target_html": "", "target_revision_id": None,
|
||||||
|
"observed_digest": "", "base_digest": "", "target_digest": "", "schedule_id": None,
|
||||||
|
"set_display": None, "set_selling": None, "memo": "", "actor": "", "origin": "MANUAL"}
|
||||||
|
row.update(fields)
|
||||||
|
self.attempts[aid] = row
|
||||||
|
return aid
|
||||||
|
|
||||||
|
def update_attempt(self, attempt_id, *, status=None, error=None, remote_updated_at=None,
|
||||||
|
remote_ok=False, resolved_by=None, only_from=None):
|
||||||
|
self._maybe_fail("update_attempt")
|
||||||
|
row = self.attempts.get(int(attempt_id))
|
||||||
|
if not row or (only_from and row["status"] not in only_from):
|
||||||
|
return False
|
||||||
|
if status is not None:
|
||||||
|
row["status"] = status
|
||||||
|
if error is not None:
|
||||||
|
row["error"] = error
|
||||||
|
if remote_updated_at is not None:
|
||||||
|
row["remote_updated_at"] = remote_updated_at
|
||||||
|
if remote_ok and row["remote_at"] is None:
|
||||||
|
row["remote_at"] = now_kst()
|
||||||
|
if resolved_by is not None:
|
||||||
|
row["resolved_by"] = resolved_by
|
||||||
|
return True
|
||||||
|
|
||||||
|
def record_attempt_revision(self, attempt_id, *, revision_type, memo, created_by, source="",
|
||||||
|
source_revision_id=None):
|
||||||
|
self._maybe_fail("record_attempt_revision")
|
||||||
|
row = self.attempts[int(attempt_id)]
|
||||||
|
if row.get("applied_revision_id"):
|
||||||
|
return row["applied_revision_id"]
|
||||||
|
body = row.get("target_html") or self.revisions.get(row.get("target_revision_id") or 0, {}).get("html_content", "")
|
||||||
|
rid = self.add_revision(product_no=row["product_no"], html_content=body, revision_type=revision_type,
|
||||||
|
memo=memo, created_by=created_by, mall_id=row.get("mall_id", ""),
|
||||||
|
source=source, source_revision_id=source_revision_id)
|
||||||
|
row.update(status=store.ATTEMPT_RECORDED, applied_revision_id=rid, target_html="")
|
||||||
|
if row["remote_at"] is None:
|
||||||
|
row["remote_at"] = now_kst()
|
||||||
|
return rid
|
||||||
|
|
||||||
|
def get_attempt(self, attempt_id):
|
||||||
|
return dict(self.attempts.get(int(attempt_id), {}))
|
||||||
|
|
||||||
|
def latest_attempt_for_schedule(self, schedule_id):
|
||||||
|
rows = [a for a in self.attempts.values() if a.get("schedule_id") == int(schedule_id)]
|
||||||
|
return dict(max(rows, key=lambda a: a["id"])) if rows else {}
|
||||||
|
|
||||||
|
def open_attempts(self, product_no, *, since):
|
||||||
|
return [dict(a) for a in sorted(self.attempts.values(), key=lambda a: a["id"])
|
||||||
|
if a["product_no"] == int(product_no) and a["status"] in store.ATTEMPT_OPEN
|
||||||
|
and a["created_at"] >= since]
|
||||||
|
|
||||||
|
def attempts_needing_record(self, *, since, limit=20):
|
||||||
|
return [dict(a) for a in self.attempts.values()
|
||||||
|
if a["status"] == store.ATTEMPT_REMOTE_OK and a["created_at"] >= since][:limit]
|
||||||
|
|
||||||
|
def write_lineage(self, product_no, *, since, limit=30):
|
||||||
|
rows = [a for a in self.attempts.values()
|
||||||
|
if a["product_no"] == int(product_no) and a["status"] in store.ATTEMPT_CONFIRMED
|
||||||
|
and a["target_digest"] and a["remote_at"] and a["remote_at"] >= since]
|
||||||
|
rows.sort(key=lambda a: (a["remote_at"], a["id"]), reverse=True)
|
||||||
|
out = []
|
||||||
|
for i, a in enumerate(rows[:limit]):
|
||||||
|
body = ""
|
||||||
|
if i == 0:
|
||||||
|
body = (a.get("target_html")
|
||||||
|
or self.revisions.get(a.get("applied_revision_id") or 0, {}).get("html_content")
|
||||||
|
or self.revisions.get(a.get("target_revision_id") or 0, {}).get("html_content") or "")
|
||||||
|
out.append({**a, "created_at": a["remote_at"], "created_by": a.get("actor", ""), "html_content": body})
|
||||||
|
return out
|
||||||
|
|
||||||
|
# ── 상품 캐시 · 스냅샷 ──
|
||||||
|
def upsert_products(self, rows):
|
||||||
|
self._maybe_fail("upsert_products")
|
||||||
|
for r in rows:
|
||||||
|
self.products[int(r["product_no"])] = dict(r)
|
||||||
|
return len(rows)
|
||||||
|
|
||||||
|
def save_write_snapshot(self, product_no, section, data, *, replace=False):
|
||||||
|
self._maybe_fail("save_write_snapshot")
|
||||||
|
at = now_kst().isoformat(timespec="seconds")
|
||||||
|
current = self.snapshots.setdefault(int(product_no), {})
|
||||||
|
if section == "variants":
|
||||||
|
previous = (current.get("variants") or {}).get("data") or {}
|
||||||
|
data = store.merge_variant_snapshot(previous, data, at=at, replace=replace)
|
||||||
|
current[section] = {"data": data, "written_at": at}
|
||||||
|
|
||||||
|
def get_write_snapshot(self, product_no):
|
||||||
|
return dict(self.snapshots.get(int(product_no), {}))
|
||||||
|
|
||||||
|
def get_recent_product_snapshots(self, grace_minutes):
|
||||||
|
return {no: dict(snap["product"]) for no, snap in self.snapshots.items() if snap.get("product")}
|
||||||
|
|
||||||
|
# ── 예약 ──
|
||||||
|
def add_schedule(self, **fields):
|
||||||
|
sid = next(self._ids)
|
||||||
|
row = {"id": sid, "product_no": 131, "revision_id": None, "set_display": None, "set_selling": None,
|
||||||
|
"status": store.STATUS_PENDING, "retry_count": 0, "next_retry_at": None, "last_error": "",
|
||||||
|
"scheduled_at": now_kst() - timedelta(minutes=1), "lease_token": "", "lease_owner": "",
|
||||||
|
"lease_expires_at": None, "started_at": None}
|
||||||
|
row.update(fields)
|
||||||
|
self.schedules[sid] = row
|
||||||
|
return sid
|
||||||
|
|
||||||
|
def claim_due_schedule(self, *, now, owner, ttl_seconds):
|
||||||
|
due = [s for s in sorted(self.schedules.values(), key=lambda s: (s["scheduled_at"], s["id"]))
|
||||||
|
if s["status"] == store.STATUS_PENDING and s["scheduled_at"] <= now
|
||||||
|
and (s["next_retry_at"] is None or s["next_retry_at"] <= now)]
|
||||||
|
if not due:
|
||||||
|
return None
|
||||||
|
row = due[0]
|
||||||
|
row.update(status=store.STATUS_PROCESSING, lease_owner=owner, lease_token=uuid.uuid4().hex,
|
||||||
|
lease_expires_at=now_kst() + timedelta(seconds=ttl_seconds), started_at=now_kst(),
|
||||||
|
last_error="")
|
||||||
|
return dict(row)
|
||||||
|
|
||||||
|
def claim_expired_schedules(self, *, owner, ttl_seconds, legacy_minutes, limit=20):
|
||||||
|
out = []
|
||||||
|
for row in self.schedules.values():
|
||||||
|
if row["status"] != store.STATUS_PROCESSING:
|
||||||
|
continue
|
||||||
|
expired = row["lease_expires_at"] is not None and row["lease_expires_at"] < now_kst()
|
||||||
|
legacy = row["lease_expires_at"] is None and (row["started_at"] or now_kst()) < now_kst() - timedelta(minutes=legacy_minutes)
|
||||||
|
if expired or legacy:
|
||||||
|
row.update(lease_owner=owner, lease_token=uuid.uuid4().hex,
|
||||||
|
lease_expires_at=now_kst() + timedelta(seconds=ttl_seconds))
|
||||||
|
out.append(dict(row))
|
||||||
|
return out[:limit]
|
||||||
|
|
||||||
|
def renew_schedule_lease(self, schedule_id, token, *, ttl_seconds):
|
||||||
|
row = self.schedules.get(int(schedule_id))
|
||||||
|
if (not row or row["status"] != store.STATUS_PROCESSING or row["lease_token"] != token
|
||||||
|
or row["lease_expires_at"] <= now_kst()):
|
||||||
|
return False
|
||||||
|
row["lease_expires_at"] = now_kst() + timedelta(seconds=ttl_seconds)
|
||||||
|
return True
|
||||||
|
|
||||||
|
def finish_schedule(self, schedule_id, *, token, status, error="", next_retry_at=None, retry_count=None):
|
||||||
|
self._maybe_fail("finish_schedule")
|
||||||
|
row = self.schedules.get(int(schedule_id))
|
||||||
|
if not row or row["status"] != store.STATUS_PROCESSING or row["lease_token"] != token:
|
||||||
|
return False
|
||||||
|
row.update(status=store.normalize_schedule_status(status), last_error=error, next_retry_at=next_retry_at,
|
||||||
|
lease_token="", lease_owner="", lease_expires_at=None)
|
||||||
|
if retry_count is not None:
|
||||||
|
row["retry_count"] = retry_count
|
||||||
|
return True
|
||||||
|
|
||||||
|
def expire_schedule_lease(self, schedule_id):
|
||||||
|
self.schedules[int(schedule_id)]["lease_expires_at"] = now_kst() - timedelta(seconds=1)
|
||||||
|
|
||||||
|
def get_schedule(self, schedule_id):
|
||||||
|
return dict(self.schedules.get(int(schedule_id), {}))
|
||||||
|
|
||||||
|
def review_schedule(self, schedule_id, *, status, note, actor, action):
|
||||||
|
row = self.schedules.get(int(schedule_id))
|
||||||
|
if not row or row["status"] != store.STATUS_NEEDS_REVIEW:
|
||||||
|
return {}
|
||||||
|
row.update(status=status, last_error=note,
|
||||||
|
next_retry_at=now_kst() if status == store.STATUS_PENDING else None)
|
||||||
|
if status != store.STATUS_SUCCESS:
|
||||||
|
for a in self.attempts.values():
|
||||||
|
if a.get("schedule_id") == int(schedule_id) and a["status"] in (store.ATTEMPT_STARTED, store.ATTEMPT_UNKNOWN):
|
||||||
|
a.update(status=store.ATTEMPT_ABANDONED, resolved_by=actor)
|
||||||
|
return dict(row)
|
||||||
|
|
||||||
|
# ── 감사 ──
|
||||||
|
def log_audit(self, **fields):
|
||||||
|
self._maybe_fail("log_audit")
|
||||||
|
self.audits.append(fields)
|
||||||
|
|
||||||
|
def log_api_call(self, **_fields):
|
||||||
|
pass
|
||||||
|
|
||||||
|
|
||||||
|
class FakeConfig:
|
||||||
|
mall_id = "testmall"
|
||||||
|
shop_base = "https://testmall.cafe24.com"
|
||||||
|
|
||||||
|
def product_url(self, no):
|
||||||
|
return f"https://testmall.cafe24.com/product/detail.html?product_no={no}"
|
||||||
|
|
||||||
|
|
||||||
|
class FakeCafe24:
|
||||||
|
"""카페24 상품 API 대역 — 상세설명·진열/판매·updated_date 를 들고 있고,
|
||||||
|
읽기 지연(lag)·PUT 실패·응답 유실을 흉내낸다."""
|
||||||
|
|
||||||
|
def __init__(self, description: str = "<p>A</p>", *, product_no: int = 131):
|
||||||
|
self.product_no = product_no
|
||||||
|
self.state = {"product_no": product_no, "product_name": "상품", "product_code": "P000000B",
|
||||||
|
"description": description, "mobile_description": description,
|
||||||
|
"separated_mobile_description": "F", "display": "T", "selling": "T",
|
||||||
|
"updated_date": "2026-09-30T10:00:00+09:00"}
|
||||||
|
self.stale: dict | None = None # 설정하면 GET 이 이 값을 돌려준다(읽기 지연)
|
||||||
|
self.put_error: Exception | None = None
|
||||||
|
self.put_error_after_apply = False # True 면 반영한 뒤 오류(응답 유실)
|
||||||
|
self.calls: list[tuple] = []
|
||||||
|
self._clock = 0
|
||||||
|
self.option: dict = {"has_option": "F", "options": []}
|
||||||
|
self.variants: list = []
|
||||||
|
self.stale_option: dict | None = None # 설정하면 GET options 가 이 값을 돌려준다
|
||||||
|
self.stale_variants: list | None = None # 설정하면 GET variants 가 이 값을 돌려준다
|
||||||
|
self.hidden_variants = 0 # 새로 생긴 품목이 GET 에 늦게 나타나는 횟수
|
||||||
|
self.fail_variant_chunk = 0 # n번째 PUT variants 묶음을 실패시킨다
|
||||||
|
self.variant_error: Exception | None = None
|
||||||
|
self._variant_puts = 0
|
||||||
|
self._code_seq = 0
|
||||||
|
|
||||||
|
def external_edit(self, description: str) -> None:
|
||||||
|
"""카페24 관리자에서 사람이 직접 고친 것."""
|
||||||
|
self._tick()
|
||||||
|
self.state.update(description=description, mobile_description=description)
|
||||||
|
|
||||||
|
def _tick(self) -> None:
|
||||||
|
self._clock += 1
|
||||||
|
self.state["updated_date"] = (datetime(2026, 9, 30, 10, 0, tzinfo=KST)
|
||||||
|
+ timedelta(minutes=self._clock)).isoformat()
|
||||||
|
|
||||||
|
# Cafe24Client 흉내 — products.* 래퍼가 부르는 get/put
|
||||||
|
def get(self, path, **kw):
|
||||||
|
self.calls.append(("GET", path))
|
||||||
|
if path == f"/admin/products/{self.product_no}":
|
||||||
|
return {"product": dict(self.stale if self.stale is not None else self.state)}
|
||||||
|
out = self._options_call("GET", path, None)
|
||||||
|
return copy.deepcopy(out) if out is not None else {}
|
||||||
|
|
||||||
|
# ── 옵션 / 품목 ── (상태는 __init__ 에서 만든다)
|
||||||
|
|
||||||
|
def _new_code(self) -> str:
|
||||||
|
self._code_seq += 1
|
||||||
|
return f"P000000B{self._code_seq:04X}"
|
||||||
|
|
||||||
|
def _options_call(self, method, path, json):
|
||||||
|
no = self.product_no
|
||||||
|
req = (json or {}).get("request") or {}
|
||||||
|
if path == f"/admin/products/{no}/options":
|
||||||
|
if method == "GET":
|
||||||
|
return {"option": self.stale_option if self.stale_option is not None else self.option}
|
||||||
|
if method == "POST":
|
||||||
|
opt = req["options"][0]
|
||||||
|
values = [{"option_text": v["option_text"], "value_no": i + 1} for i, v in enumerate(opt["option_value"])]
|
||||||
|
self.option = {"has_option": "T", "option_type": "T", "option_list_type": "S",
|
||||||
|
"options": [{"option_name": opt["option_name"], "option_code": "O1",
|
||||||
|
"option_display_type": opt.get("option_display_type", "S"),
|
||||||
|
"option_value": values}]}
|
||||||
|
self.variants = [{"variant_code": self._new_code(), "options": [{"name": opt["option_name"], "value": v["option_text"]}],
|
||||||
|
"custom_variant_code": "", "additional_amount": "0.00", "display": "T", "selling": "T"}
|
||||||
|
for v in values]
|
||||||
|
return {"option": self.option}
|
||||||
|
if method == "PUT":
|
||||||
|
new = req["options"]
|
||||||
|
for gi, group in enumerate(new):
|
||||||
|
cur = self.option["options"][gi]
|
||||||
|
old_name = cur["option_name"]
|
||||||
|
old_values = [v["option_text"] for v in cur["option_value"]]
|
||||||
|
cur["option_name"] = group["option_name"]
|
||||||
|
vals = []
|
||||||
|
for vi, v in enumerate(group["option_value"]):
|
||||||
|
vals.append({"option_text": v["option_text"], "value_no": vi + 1,
|
||||||
|
"option_image_file": v.get("option_image_file", "")})
|
||||||
|
if vi < len(old_values):
|
||||||
|
for var in self.variants:
|
||||||
|
for o in var["options"]:
|
||||||
|
if o["name"] == old_name and o["value"] == old_values[vi]:
|
||||||
|
o["value"] = v["option_text"]
|
||||||
|
else:
|
||||||
|
self.variants.append({"variant_code": self._new_code(),
|
||||||
|
"options": [{"name": group["option_name"], "value": v["option_text"]}],
|
||||||
|
"custom_variant_code": "", "additional_amount": "0.00",
|
||||||
|
"display": "T", "selling": "T", "_new": True})
|
||||||
|
for var in self.variants:
|
||||||
|
for o in var["options"]:
|
||||||
|
if o["name"] == old_name:
|
||||||
|
o["name"] = group["option_name"]
|
||||||
|
cur["option_value"] = vals
|
||||||
|
return {"option": self.option}
|
||||||
|
if method == "DELETE":
|
||||||
|
self.option = {"has_option": "F", "options": []}
|
||||||
|
self.variants = []
|
||||||
|
return {"option": {"product_no": no}}
|
||||||
|
if path == f"/admin/products/{no}/variants":
|
||||||
|
if method == "GET":
|
||||||
|
if self.stale_variants is not None:
|
||||||
|
return {"variants": [dict(v) for v in self.stale_variants]}
|
||||||
|
shown = [dict(v) for v in self.variants]
|
||||||
|
if self.hidden_variants > 0:
|
||||||
|
self.hidden_variants -= 1
|
||||||
|
shown = [v for v in shown if not v.get("_new")]
|
||||||
|
return {"variants": shown}
|
||||||
|
if method == "PUT":
|
||||||
|
self._variant_puts += 1
|
||||||
|
if self.fail_variant_chunk and self._variant_puts == self.fail_variant_chunk:
|
||||||
|
raise self.variant_error or Cafe24ApiError("품목 수정 거절", status=422)
|
||||||
|
if (json or {}).get("shop_no", 1) != 1: # 다른 쇼핑몰 — 기본몰 상태는 그대로
|
||||||
|
return {"variants": [dict(r) for r in (json or {}).get("requests") or []]}
|
||||||
|
out = []
|
||||||
|
for r in (json or {}).get("requests") or []:
|
||||||
|
for var in self.variants:
|
||||||
|
if var["variant_code"] == r["variant_code"]:
|
||||||
|
var.update({k: v for k, v in r.items() if k != "variant_code"})
|
||||||
|
out.append(dict(var))
|
||||||
|
return {"variants": out}
|
||||||
|
if path.startswith(f"/admin/products/{no}/variants/") and method == "DELETE":
|
||||||
|
code = path.rsplit("/", 1)[1]
|
||||||
|
self.variants = [v for v in self.variants if v["variant_code"] != code]
|
||||||
|
return {"variant": {"variant_code": code}}
|
||||||
|
return None
|
||||||
|
|
||||||
|
def post(self, path, *, json=None, **kw):
|
||||||
|
self.calls.append(("POST", path, json))
|
||||||
|
if path == f"/admin/products/{self.product_no}/images": # 대표이미지 등록(A 타입)
|
||||||
|
self._tick()
|
||||||
|
n = sum(1 for c in self.calls if c[1] == path)
|
||||||
|
image = {k: f"/web/product/{k.split('_')[0]}/{self.product_no}_{n}.png"
|
||||||
|
for k in ("detail_image", "list_image", "tiny_image", "small_image")}
|
||||||
|
self.state.update(image)
|
||||||
|
return {"image": image}
|
||||||
|
out = self._options_call("POST", path, json)
|
||||||
|
return copy.deepcopy(out) if out is not None else {}
|
||||||
|
|
||||||
|
def delete(self, path, **kw):
|
||||||
|
self.calls.append(("DELETE", path))
|
||||||
|
out = self._options_call("DELETE", path, None)
|
||||||
|
return out if out is not None else {}
|
||||||
|
|
||||||
|
def put(self, path, *, json=None, **kw):
|
||||||
|
self.calls.append(("PUT", path, json))
|
||||||
|
if path != f"/admin/products/{self.product_no}":
|
||||||
|
out = self._options_call("PUT", path, json)
|
||||||
|
return copy.deepcopy(out) if out is not None else {}
|
||||||
|
if self.put_error is not None and not self.put_error_after_apply:
|
||||||
|
raise self.put_error
|
||||||
|
req = (json or {}).get("request", {})
|
||||||
|
self._tick()
|
||||||
|
for key in ("description", "display", "selling", "product_name", "separated_mobile_description"):
|
||||||
|
if key in req:
|
||||||
|
self.state[key] = req[key]
|
||||||
|
if "description" in req:
|
||||||
|
self.state["mobile_description"] = req["description"]
|
||||||
|
if self.put_error is not None:
|
||||||
|
raise self.put_error
|
||||||
|
return {"product": dict(self.state)}
|
||||||
|
|
||||||
|
def puts(self):
|
||||||
|
return [c for c in self.calls if c[0] == "PUT"]
|
||||||
|
|
||||||
|
|
||||||
|
class FakeApi:
|
||||||
|
def __init__(self, client):
|
||||||
|
self.client = client
|
||||||
|
self.config = FakeConfig()
|
||||||
|
|
||||||
|
|
||||||
|
def network_error(maybe_applied: bool = True) -> Cafe24ApiError:
|
||||||
|
return Cafe24ApiError("네트워크 오류 (ReadTimeout)", status=0, maybe_applied=maybe_applied)
|
||||||
|
|
||||||
|
|
||||||
|
class FakeFTP:
|
||||||
|
"""ftplib.FTP 대역 — RETR/STOR/RNFR·RNTO/DELE 를 메모리 파일로. 실패를 주입할 수 있다."""
|
||||||
|
|
||||||
|
files: dict[str, bytes] = {}
|
||||||
|
rename_mode = "overwrite" # overwrite | no_overwrite | unsupported
|
||||||
|
truncate_store = False # STOR 가 앞부분만 쓰고 끝난 것처럼
|
||||||
|
on_before_rename = None # 교체 직전 끼어들기(남이 원본을 바꿈 등)
|
||||||
|
log: list[tuple] = []
|
||||||
|
|
||||||
|
def __init__(self):
|
||||||
|
pass
|
||||||
|
|
||||||
|
def connect(self, host, port, timeout=None):
|
||||||
|
FakeFTP.log.append(("connect",))
|
||||||
|
|
||||||
|
def login(self, user, password):
|
||||||
|
pass
|
||||||
|
|
||||||
|
def set_pasv(self, value):
|
||||||
|
pass
|
||||||
|
|
||||||
|
def retrbinary(self, cmd, callback):
|
||||||
|
path = cmd.split(" ", 1)[1]
|
||||||
|
if path not in self.files:
|
||||||
|
raise ftplib.error_perm("550 No such file")
|
||||||
|
callback(self.files[path])
|
||||||
|
|
||||||
|
# 카페24 디자인 FTP 는 허용 확장자만 받는다(실물: `x.js.cf24tmp-…` STOR → 550).
|
||||||
|
ALLOWED_EXT = (".js", ".html", ".htm", ".css", ".json", ".txt", ".xml",
|
||||||
|
".jpg", ".jpeg", ".gif", ".png", ".svg", ".webp")
|
||||||
|
|
||||||
|
@classmethod
|
||||||
|
def _check_ext(cls, path):
|
||||||
|
if not path.lower().endswith(cls.ALLOWED_EXT):
|
||||||
|
raise ftplib.error_perm(f"550 {path}: Operation not permitted")
|
||||||
|
|
||||||
|
def storbinary(self, cmd, fp):
|
||||||
|
path = cmd.split(" ", 1)[1]
|
||||||
|
data = fp.read()
|
||||||
|
FakeFTP.log.append(("STOR", path))
|
||||||
|
self._check_ext(path)
|
||||||
|
self.files[path] = data[: len(data) // 2] if FakeFTP.truncate_store else data
|
||||||
|
|
||||||
|
def rename(self, src, dst):
|
||||||
|
FakeFTP.log.append(("RENAME", src, dst))
|
||||||
|
if FakeFTP.on_before_rename is not None:
|
||||||
|
hook, FakeFTP.on_before_rename = FakeFTP.on_before_rename, None
|
||||||
|
hook(self.files)
|
||||||
|
if FakeFTP.rename_mode == "unsupported":
|
||||||
|
raise ftplib.error_perm("502 RNFR not implemented")
|
||||||
|
if src not in self.files:
|
||||||
|
raise ftplib.error_perm("550 No such file")
|
||||||
|
self._check_ext(dst)
|
||||||
|
if dst in self.files and FakeFTP.rename_mode == "no_overwrite":
|
||||||
|
raise ftplib.error_perm("553 File exists")
|
||||||
|
self.files[dst] = self.files.pop(src)
|
||||||
|
|
||||||
|
def delete(self, path):
|
||||||
|
FakeFTP.log.append(("DELE", path))
|
||||||
|
self.files.pop(path, None)
|
||||||
|
|
||||||
|
def quit(self):
|
||||||
|
pass
|
||||||
|
|
||||||
|
def close(self):
|
||||||
|
pass
|
||||||
|
|
||||||
|
@classmethod
|
||||||
|
def reset(cls, files):
|
||||||
|
cls.files = dict(files)
|
||||||
|
cls.rename_mode = "overwrite"
|
||||||
|
cls.truncate_store = False
|
||||||
|
cls.on_before_rename = None
|
||||||
|
cls.log = []
|
||||||
|
|
||||||
|
|
||||||
|
@contextmanager
|
||||||
|
def patched_ftp():
|
||||||
|
saved = ftplib.FTP
|
||||||
|
ftplib.FTP = FakeFTP
|
||||||
|
try:
|
||||||
|
yield FakeFTP
|
||||||
|
finally:
|
||||||
|
ftplib.FTP = saved
|
||||||
File diff suppressed because it is too large
Load Diff
+256
-120
@@ -8,14 +8,28 @@
|
|||||||
웹 요청 안에서 기다리는 방식은 프록시 타임아웃·재기동에 그대로 무너진다.
|
웹 요청 안에서 기다리는 방식은 프록시 타임아웃·재기동에 그대로 무너진다.
|
||||||
compose 서비스 `dbx-cafe24-worker` 가 web 과 같은 이미지로 이 모듈을 돌린다.
|
compose 서비스 `dbx-cafe24-worker` 가 web 과 같은 이미지로 이 모듈을 돌린다.
|
||||||
|
|
||||||
한 번에 한 건씩 처리한다
|
한 번에 한 건씩, lease 로 잡는다 (마이그레이션 005)
|
||||||
`claim_due_schedule` 이 `FOR UPDATE SKIP LOCKED` 로 한 건을 잠그고 PROCESSING 으로
|
`claim_due_schedule` 이 `FOR UPDATE SKIP LOCKED` 로 한 건을 잡아 PROCESSING + lease
|
||||||
바꾼다. worker 가 실수로 두 개 떠도 같은 예약이 두 번 적용되지 않는다.
|
(만료 시각·token)로 바꾼다. worker 가 여럿이어도 같은 예약을 두 번 잡지 않는다.
|
||||||
|
카페24에 쓰기 직전 lease 를 연장해 "아직 내 것인가"를 확인하고(펜싱), 결과는
|
||||||
|
token 이 맞을 때만 남긴다 — 만료 뒤 늦게 끝난 worker 가 남의 결과를 덮지 않는다.
|
||||||
|
|
||||||
적용 순서는 화면 편집과 같다
|
적용 순서는 화면 편집과 같다 (writes.write_product 공용)
|
||||||
카페24 현재값 재조회 → BACKUP revision → PUT → SUCCESS + 감사로그
|
상품 잠금 → 카페24 현재값 재조회 → 유효 현재값(읽기 지연 보정) → BACKUP
|
||||||
실패하면 재시도 예산(store.MAX_RETRY) 안에서 간격을 두고 다시 시도하고,
|
→ 시도 기록 → PUT → 버전(SCHEDULED)·스냅샷 기록
|
||||||
소진되면 FAILED 로 확정한다. 되돌리기는 쓰지 않는다.
|
예약 직전 백업도 읽기 지연을 보정한 값이다(카페24가 아직 옛 HTML 을 돌려줘도
|
||||||
|
그것을 "직전 내용"으로 남기지 않는다). 백업의 source 로 관측값/확인된 적용값을 구분한다.
|
||||||
|
|
||||||
|
결과 분류
|
||||||
|
카페24가 거절 → 재시도 예산(store.MAX_RETRY) 안에서 간격을 두고 다시, 소진되면 FAILED
|
||||||
|
반영 여부 모름 → NEEDS_REVIEW (자동 재적용 금지 — 사람이 쇼핑몰을 보고 확정)
|
||||||
|
반영 성공·기록 실패 → SUCCESS + "기록 복구 필요" 메모. 기록은 다음 주기에 채운다(재적용 없음)
|
||||||
|
같은 상품을 다른 작업이 쓰는 중 → 재시도 횟수를 쓰지 않고 잠시 뒤 다시
|
||||||
|
|
||||||
|
중단 복구 (recover)
|
||||||
|
lease 가 만료된 PROCESSING 은 그 예약의 마지막 쓰기 시도를 보고 판정한다
|
||||||
|
(store.recovery_decision). 무조건 PENDING 으로 돌리지 않는다 — 카페24에 이미 반영됐을
|
||||||
|
수 있기 때문이다. 카페24 현재값이 예약 결과와 같으면 반영된 것으로 확정한다.
|
||||||
|
|
||||||
토큰 갱신은 TokenService 가 행 잠금 안에서 하므로 web 과 동시에 떠 있어도 안전하다.
|
토큰 갱신은 TokenService 가 행 잠금 안에서 하므로 web 과 동시에 떠 있어도 안전하다.
|
||||||
"""
|
"""
|
||||||
@@ -25,6 +39,7 @@ from __future__ import annotations
|
|||||||
import argparse
|
import argparse
|
||||||
import logging
|
import logging
|
||||||
import os
|
import os
|
||||||
|
import socket
|
||||||
import sys
|
import sys
|
||||||
import time
|
import time
|
||||||
from datetime import timedelta
|
from datetime import timedelta
|
||||||
@@ -33,141 +48,262 @@ from typing import Any
|
|||||||
from app.integrations.cafe24 import Cafe24Error, build_cafe24_api, products
|
from app.integrations.cafe24 import Cafe24Error, build_cafe24_api, products
|
||||||
from app.timezone import now_kst
|
from app.timezone import now_kst
|
||||||
|
|
||||||
from . import store
|
from . import store, writes
|
||||||
|
from .common import read_lag_grace_minutes
|
||||||
|
from .routes_products import load_product
|
||||||
|
|
||||||
logger = logging.getLogger("cafe24.worker")
|
logger = logging.getLogger("cafe24.worker")
|
||||||
|
|
||||||
ACTOR = "SCHEDULER"
|
ACTOR = "SCHEDULER"
|
||||||
|
DEFAULT_LEASE_SEC = 600 # 한 건 처리(현재값 조회 + PUT + 확인)에 넉넉한 시간
|
||||||
|
LEGACY_PROCESSING_MIN = 30 # lease 컬럼이 없는 옛 PROCESSING 을 만료로 볼 시간
|
||||||
|
BUSY_RETRY_SECONDS = 30 # 같은 상품을 다른 작업이 쓰는 중일 때 다시 볼 간격
|
||||||
|
SETUP_RETRY_SECONDS = 300 # 마이그레이션 미적용 등 설정 문제일 때 다시 볼 간격
|
||||||
|
|
||||||
|
|
||||||
def _apply(store_db: Any, api: Any, row: dict[str, Any]) -> str:
|
def lease_seconds() -> int:
|
||||||
"""예약 1건 적용. 성공 시 사람이 읽을 요약 문자열."""
|
try:
|
||||||
|
value = int(str(os.getenv("CAFE24_SCHEDULE_LEASE_SEC") or "").strip())
|
||||||
|
except ValueError:
|
||||||
|
return DEFAULT_LEASE_SEC
|
||||||
|
return max(60, value)
|
||||||
|
|
||||||
|
|
||||||
|
def worker_owner() -> str:
|
||||||
|
return f"{ACTOR}|{socket.gethostname()}:{os.getpid()}"
|
||||||
|
|
||||||
|
|
||||||
|
def _summary(row: dict[str, Any]) -> str:
|
||||||
|
return store.describe_schedule_action(
|
||||||
|
has_html=bool(row.get("revision_id")),
|
||||||
|
set_display=row.get("set_display"),
|
||||||
|
set_selling=row.get("set_selling"),
|
||||||
|
has_image=bool(row.get("image_type")),
|
||||||
|
)
|
||||||
|
|
||||||
|
|
||||||
|
def _apply_image(st: Any, api: Any, product_no: int, data: bytes, content_type: str) -> str:
|
||||||
|
"""예약 대표 이미지 교체(routes_product_info.product_image 와 같은 순서). 반환: 새 detail_image.
|
||||||
|
|
||||||
|
상세페이지·진열/판매보다 **먼저** 한다 — 뒤 단계가 실패해 재시도되면 같은 이미지를 한 번 더
|
||||||
|
올릴 뿐이라 안전하고, 앞 단계(시도 기록)가 SUCCESS 로 복구된 뒤 이미지가 빠지는 일이 없다.
|
||||||
|
"""
|
||||||
|
current, _ = load_product(st, api, product_no)
|
||||||
|
if not current:
|
||||||
|
raise Cafe24Error("카페24에서 상품을 찾지 못했습니다.")
|
||||||
|
images = products.set_main_image(api.client, product_no, data, content_type=content_type)
|
||||||
|
if not images.get("detail_image"):
|
||||||
|
raise Cafe24Error("카페24가 등록된 이미지 경로를 돌려주지 않았습니다.")
|
||||||
|
writes.remember_product_write(
|
||||||
|
st, product_no, {**current, **images, "updated_date": now_kst().isoformat(timespec="seconds")}
|
||||||
|
)
|
||||||
|
return str(images["detail_image"])
|
||||||
|
|
||||||
|
|
||||||
|
def _retry_or_fail(st: Any, row: dict[str, Any], token: str, error: str) -> str:
|
||||||
|
"""재시도 예산 안이면 PENDING + 대기, 아니면 FAILED. 반환: 결과 상태."""
|
||||||
|
retry_count = int(row.get("retry_count") or 0)
|
||||||
|
schedule_id = int(row["id"])
|
||||||
|
if store.can_retry(retry_count):
|
||||||
|
wait = store.retry_backoff_seconds(retry_count)
|
||||||
|
st.finish_schedule(
|
||||||
|
schedule_id, token=token, status=store.STATUS_PENDING, error=error,
|
||||||
|
next_retry_at=now_kst() + timedelta(seconds=wait), retry_count=retry_count + 1,
|
||||||
|
)
|
||||||
|
logger.warning("예약 #%s 상품 %s 실패 — %s초 후 재시도 (%s/%s): %s",
|
||||||
|
schedule_id, row.get("product_no"), wait, retry_count + 1, store.MAX_RETRY, error)
|
||||||
|
return store.STATUS_PENDING
|
||||||
|
st.finish_schedule(schedule_id, token=token, status=store.STATUS_FAILED, error=error)
|
||||||
|
writes.audit_safe(st, actor=ACTOR, action="schedule_apply", product_no=row.get("product_no"),
|
||||||
|
schedule_id=schedule_id, result="FAIL", detail=error)
|
||||||
|
logger.error("예약 #%s 상품 %s 최종 실패: %s", schedule_id, row.get("product_no"), error)
|
||||||
|
return store.STATUS_FAILED
|
||||||
|
|
||||||
|
|
||||||
|
def run_one(st: Any, api: Any, row: dict[str, Any]) -> str:
|
||||||
|
"""lease 로 잡은 예약 1건 실행. 반환: 남긴 상태(또는 'LEASE_LOST')."""
|
||||||
schedule_id = int(row["id"])
|
schedule_id = int(row["id"])
|
||||||
product_no = int(row["product_no"])
|
product_no = int(row["product_no"])
|
||||||
|
token = str(row.get("lease_token") or "")
|
||||||
|
lease = lease_seconds()
|
||||||
revision_id = row.get("revision_id")
|
revision_id = row.get("revision_id")
|
||||||
set_display = row.get("set_display")
|
set_display = row.get("set_display")
|
||||||
set_selling = row.get("set_selling")
|
set_selling = row.get("set_selling")
|
||||||
|
|
||||||
html: str | None = None
|
def fence() -> bool:
|
||||||
if revision_id:
|
return bool(st.renew_schedule_lease(schedule_id, token, ttl_seconds=lease))
|
||||||
revision = store_db.get_revision(int(revision_id))
|
|
||||||
if not revision:
|
|
||||||
raise Cafe24Error(f"예약이 가리키는 버전 {revision_id} 을 찾을 수 없습니다.")
|
|
||||||
html = revision.get("html_content") or ""
|
|
||||||
if not html.strip():
|
|
||||||
raise Cafe24Error(f"버전 {revision_id} 의 내용이 비어 있습니다.")
|
|
||||||
|
|
||||||
# 상세설명을 바꿀 때는 쓰기 직전 현재값을 읽어 백업한다(로컬 값을 믿지 않는다).
|
image_type = str(row.get("image_type") or "")
|
||||||
backup_id = 0
|
new_image = ""
|
||||||
if html is not None:
|
try:
|
||||||
current = products.fetch_descriptions(api.client, product_no)
|
html: str | None = None
|
||||||
backup_id = store_db.add_revision(
|
if revision_id:
|
||||||
product_no=product_no,
|
revision = st.get_revision(int(revision_id))
|
||||||
html_content=current.description,
|
if not revision:
|
||||||
revision_type=store.REVISION_BACKUP,
|
raise Cafe24Error(f"예약이 가리키는 버전 {revision_id} 을 찾을 수 없습니다.")
|
||||||
memo=f"예약 #{schedule_id} 적용 직전 자동 백업",
|
html = str(revision.get("html_content") or "")
|
||||||
created_by=ACTOR,
|
if not html.strip():
|
||||||
)
|
raise Cafe24Error(f"버전 {revision_id} 의 내용이 비어 있습니다.")
|
||||||
if current.mobile_description and current.mobile_description != current.description:
|
image = st.get_schedule_image(schedule_id) if image_type else b""
|
||||||
store_db.add_revision(
|
if image_type and not image:
|
||||||
product_no=product_no,
|
raise Cafe24Error("예약해 둔 대표 이미지 파일을 찾을 수 없습니다.")
|
||||||
html_content=current.mobile_description,
|
with writes.write_lock(
|
||||||
revision_type=store.REVISION_BACKUP,
|
st, writes.product_lock_key(product_no), actor=ACTOR,
|
||||||
memo=f"예약 #{schedule_id} 적용 직전 자동 백업 (모바일)",
|
purpose=f"예약 #{schedule_id} 실행", wait_seconds=0,
|
||||||
created_by=ACTOR,
|
) as lock:
|
||||||
)
|
if image:
|
||||||
|
if not fence():
|
||||||
|
raise writes.WriteBusy("예약 lease 를 잃었습니다 — 다른 worker 가 처리합니다.")
|
||||||
|
new_image = _apply_image(st, api, product_no, image, image_type)
|
||||||
|
outcome = writes.WriteOutcome()
|
||||||
|
if html is not None or set_display is not None or set_selling is not None:
|
||||||
|
outcome = writes.write_product(
|
||||||
|
st, api, product_no,
|
||||||
|
lock=lock, origin=store.ORIGIN_SCHEDULED, actor=ACTOR, html=html,
|
||||||
|
set_display=set_display, set_selling=set_selling,
|
||||||
|
schedule_id=schedule_id, target_revision_id=int(revision_id) if revision_id else None,
|
||||||
|
memo=f"예약 #{schedule_id} 적용", extra_fence=fence,
|
||||||
|
)
|
||||||
|
except writes.WriteSetupError as exc:
|
||||||
|
st.finish_schedule(schedule_id, token=token, status=store.STATUS_PENDING, error=str(exc),
|
||||||
|
next_retry_at=now_kst() + timedelta(seconds=SETUP_RETRY_SECONDS))
|
||||||
|
logger.error("예약 #%s 실행 보류 — %s", schedule_id, exc)
|
||||||
|
return store.STATUS_PENDING
|
||||||
|
except writes.WriteBusy as exc:
|
||||||
|
# 다른 작업이 같은 상품을 쓰는 중이거나 lease 를 잃었다. 재시도 횟수를 쓰지 않는다.
|
||||||
|
# (lease 를 잃었으면 finish 는 token 이 안 맞아 아무것도 바꾸지 않는다.)
|
||||||
|
done = st.finish_schedule(schedule_id, token=token, status=store.STATUS_PENDING, error=str(exc),
|
||||||
|
next_retry_at=now_kst() + timedelta(seconds=BUSY_RETRY_SECONDS))
|
||||||
|
logger.info("예약 #%s 상품 %s 보류(%s): %s", schedule_id, product_no, "재대기" if done else "lease 잃음", exc)
|
||||||
|
return store.STATUS_PENDING if done else "LEASE_LOST"
|
||||||
|
except (writes.WriteBlocked, writes.RemoteWriteUnknown) as exc:
|
||||||
|
st.finish_schedule(schedule_id, token=token, status=store.STATUS_NEEDS_REVIEW, error=str(exc))
|
||||||
|
writes.audit_safe(st, actor=ACTOR, action="schedule_apply", product_no=product_no,
|
||||||
|
schedule_id=schedule_id, result="UNKNOWN", detail=str(exc))
|
||||||
|
logger.error("예약 #%s 상품 %s 확인 필요: %s", schedule_id, product_no, exc)
|
||||||
|
return store.STATUS_NEEDS_REVIEW
|
||||||
|
except (writes.RemoteWriteFailed, Cafe24Error) as exc:
|
||||||
|
return _retry_or_fail(st, row, token, str(exc))
|
||||||
|
except Exception as exc: # noqa: BLE001 — 카페24에 쓰기 전의 사고(원격 이후는 write_product 가 삼킨다)
|
||||||
|
logger.exception("예약 #%s 처리 중 예상치 못한 오류(카페24 쓰기 전)", schedule_id)
|
||||||
|
return _retry_or_fail(st, row, token, f"{type(exc).__name__}: {exc}")
|
||||||
|
|
||||||
# PC/모바일은 구분하지 않는다 — mobile_description 은 보내지 않고
|
note = ""
|
||||||
# separated_mobile_description="F" 로 "PC 상세설명과 동일"을 강제한다.
|
if outcome.record_error:
|
||||||
# (mobile_description 을 직접 보내면 카페24가 그 설정을 "직접 등록"으로 바꿔버린다.)
|
note = f"카페24 반영 성공 · 로컬 기록 실패(자동 복구 예정, 재적용 안 함): {outcome.record_error}"
|
||||||
updated = products.update_product(
|
done = st.finish_schedule(schedule_id, token=token, status=store.STATUS_SUCCESS, error=note)
|
||||||
api.client,
|
if not done:
|
||||||
product_no,
|
# 반영은 됐다. 결과를 못 남겼어도 lease 만료 후 recover 가 시도 기록(REMOTE_OK/RECORDED)을
|
||||||
description=html,
|
# 보고 SUCCESS 로 확정한다 — 다시 적용하지 않는다.
|
||||||
separated_mobile_description="F" if html is not None else None,
|
logger.warning("예약 #%s 적용됨 — 결과 기록 실패(lease 잃음). 복구 단계가 확정합니다.", schedule_id)
|
||||||
display=set_display,
|
summary = _summary(row)
|
||||||
selling=set_selling,
|
writes.audit_safe(
|
||||||
|
st, actor=ACTOR, action="schedule_apply", product_no=product_no,
|
||||||
|
revision_id=outcome.revision_id or (int(revision_id) if revision_id else None),
|
||||||
|
schedule_id=schedule_id, result="SUCCESS",
|
||||||
|
detail=summary + (f" (백업 {outcome.backup_id})" if outcome.backup_id else "")
|
||||||
|
+ (f" / 대표이미지 → '{new_image}'" if new_image else "")
|
||||||
|
+ (f" / {note}" if note else ""),
|
||||||
)
|
)
|
||||||
# PUT 응답은 쓰기 직후의 실제 값이다 — 스냅샷으로 남겨 화면이 GET 의 읽기 지연에
|
logger.info("예약 #%s 상품 %s 적용 완료 — %s", schedule_id, product_no, summary)
|
||||||
# 흔들리지 않게 한다(routes_products._load_product 가 덮어씌운다).
|
return store.STATUS_SUCCESS
|
||||||
if isinstance(updated, dict) and updated.get("product_no"):
|
|
||||||
|
|
||||||
|
def _verify_attempt(st: Any, api: Any, attempt: dict[str, Any]) -> bool:
|
||||||
|
"""카페24 현재값이 그 시도의 결과와 같은가(같으면 반영된 것으로 확정해도 된다)."""
|
||||||
|
try:
|
||||||
|
product = products.get_product(api.client, int(attempt["product_no"]))
|
||||||
|
except Cafe24Error as exc:
|
||||||
|
logger.warning("시도 #%s 확인용 조회 실패: %s", attempt.get("id"), exc)
|
||||||
|
return False
|
||||||
|
return writes.attempt_matches_remote(attempt, product)
|
||||||
|
|
||||||
|
|
||||||
|
def recover_one(st: Any, api: Any, row: dict[str, Any]) -> str:
|
||||||
|
"""lease 만료 PROCESSING 1건 복구 판정 — 반환: 남긴 상태."""
|
||||||
|
schedule_id = int(row["id"])
|
||||||
|
token = str(row.get("lease_token") or "")
|
||||||
|
attempt = st.latest_attempt_for_schedule(schedule_id) or None
|
||||||
|
decision, note = store.recovery_decision(attempt, row.get("retry_count"))
|
||||||
|
note = f"중단 복구: {note}"
|
||||||
|
|
||||||
|
if decision == store.RECOVER_REVIEW and attempt:
|
||||||
try:
|
try:
|
||||||
store_db.save_write_snapshot(product_no, "product", store.product_snapshot(updated))
|
with writes.write_lock(st, writes.product_lock_key(int(row["product_no"])), actor=ACTOR,
|
||||||
except Exception: # noqa: BLE001 — 스냅샷 실패가 예약 결과를 바꾸면 안 된다.
|
purpose=f"예약 #{schedule_id} 복구 확인", wait_seconds=0):
|
||||||
logger.exception("예약 #%s 상품 %s 스냅샷 저장 실패", schedule_id, product_no)
|
if _verify_attempt(st, api, attempt):
|
||||||
if html is not None:
|
st.update_attempt(int(attempt["id"]), status=store.ATTEMPT_REMOTE_OK, remote_ok=True,
|
||||||
# 화면 편집(apply)과 동일 — 카페24 관리자 API 의 쓰기 직후 읽기 지연을
|
resolved_by="auto:카페24 값이 예약 결과와 같음",
|
||||||
# 여기서 짧게 흡수한다(쇼핑몰에는 바로 반영되지만 관리자 조회만 뒤쳐질 때가 있다).
|
only_from=(store.ATTEMPT_STARTED, store.ATTEMPT_UNKNOWN))
|
||||||
# 확인이 안 돼도 실패가 아니다 — 화면은 마지막 쓰기(SCHEDULED revision)를 기준으로
|
decision, note = store.RECOVER_RECORD, "중단 복구: 카페24 현재값이 예약 결과와 같아 반영됨으로 확정"
|
||||||
# 그린다. 여기서 SCHEDULED revision 을 남겨야 그 기준이 생긴다.
|
except writes.WriteBusy:
|
||||||
products.wait_for_description(api.client, product_no, html)
|
pass # 다음 주기에 다시 — 판정은 REVIEW 로 남긴다
|
||||||
store_db.add_revision(
|
if decision == store.RECOVER_RECORD and attempt:
|
||||||
product_no=product_no,
|
try:
|
||||||
html_content=html,
|
writes.record_attempt(st, attempt)
|
||||||
revision_type=store.REVISION_SCHEDULED,
|
except Exception as exc: # noqa: BLE001 — 반영은 됐다. 기록은 다음 주기에.
|
||||||
memo=f"예약 #{schedule_id} 적용",
|
logger.exception("예약 #%s 복구 중 버전 기록 실패", schedule_id)
|
||||||
created_by=ACTOR,
|
note += f" (버전 기록 실패 — 자동 재시도: {type(exc).__name__})"
|
||||||
)
|
decision = store.RECOVER_SUCCESS
|
||||||
|
|
||||||
summary = store.describe_schedule_action(
|
if decision == store.RECOVER_SUCCESS:
|
||||||
has_html=html is not None, set_display=set_display, set_selling=set_selling
|
st.finish_schedule(schedule_id, token=token, status=store.STATUS_SUCCESS, error=note)
|
||||||
|
status = store.STATUS_SUCCESS
|
||||||
|
elif decision == store.RECOVER_REVIEW:
|
||||||
|
st.finish_schedule(schedule_id, token=token, status=store.STATUS_NEEDS_REVIEW, error=note)
|
||||||
|
status = store.STATUS_NEEDS_REVIEW
|
||||||
|
else:
|
||||||
|
status = _retry_or_fail(st, row, token, note)
|
||||||
|
writes.audit_safe(st, actor=ACTOR, action="schedule_recover", product_no=row.get("product_no"),
|
||||||
|
schedule_id=schedule_id, result=status, detail=note)
|
||||||
|
logger.warning("예약 #%s 중단 복구 → %s (%s)", schedule_id, status, note)
|
||||||
|
return status
|
||||||
|
|
||||||
|
|
||||||
|
def record_pending_attempts(st: Any) -> int:
|
||||||
|
"""카페24에 반영됐는데 버전 기록이 빠진 시도(REMOTE_OK)의 기록을 채운다."""
|
||||||
|
since = now_kst() - timedelta(minutes=read_lag_grace_minutes())
|
||||||
|
done = 0
|
||||||
|
for attempt in st.attempts_needing_record(since=since):
|
||||||
|
try:
|
||||||
|
with writes.write_lock(st, writes.product_lock_key(int(attempt["product_no"])), actor=ACTOR,
|
||||||
|
purpose="기록 복구", wait_seconds=0):
|
||||||
|
writes.record_attempt(st, attempt)
|
||||||
|
done += 1
|
||||||
|
except writes.WriteBusy:
|
||||||
|
continue
|
||||||
|
except Exception: # noqa: BLE001
|
||||||
|
logger.exception("시도 #%s 기록 복구 실패", attempt.get("id"))
|
||||||
|
return done
|
||||||
|
|
||||||
|
|
||||||
|
def recover(st: Any, api: Any) -> int:
|
||||||
|
"""중단 복구 — 기록 복구 + lease 만료 PROCESSING 판정. 처리 건수."""
|
||||||
|
count = record_pending_attempts(st)
|
||||||
|
rows = st.claim_expired_schedules(
|
||||||
|
owner=worker_owner(), ttl_seconds=lease_seconds(), legacy_minutes=LEGACY_PROCESSING_MIN
|
||||||
)
|
)
|
||||||
store_db.log_audit(
|
for row in rows:
|
||||||
actor=ACTOR,
|
try:
|
||||||
action="schedule_apply",
|
recover_one(st, api, row)
|
||||||
product_no=product_no,
|
except Exception: # noqa: BLE001 — 한 건 때문에 나머지를 멈추지 않는다(lease 만료 후 다시)
|
||||||
revision_id=int(revision_id) if revision_id else None,
|
logger.exception("예약 #%s 복구 중 오류", row.get("id"))
|
||||||
schedule_id=schedule_id,
|
count += 1
|
||||||
result="SUCCESS",
|
return count
|
||||||
detail=summary + (f" (백업 {backup_id})" if backup_id else ""),
|
|
||||||
)
|
|
||||||
return summary
|
|
||||||
|
|
||||||
|
|
||||||
def process_once(store_db: Any, api: Any) -> int:
|
def process_once(st: Any, api: Any) -> int:
|
||||||
"""실행할 예약을 모두 처리한다. 처리한 건수를 돌려준다."""
|
"""중단 복구 후, 실행할 예약을 모두 처리한다. 처리한(잡은) 예약 건수를 돌려준다."""
|
||||||
|
try:
|
||||||
|
recover(st, api)
|
||||||
|
except Exception: # noqa: BLE001 — 복구 실패가 새 예약 실행을 막지 않게
|
||||||
|
logger.exception("중단 복구 단계 오류 — 다음 주기에 다시 시도")
|
||||||
handled = 0
|
handled = 0
|
||||||
while True:
|
while True:
|
||||||
with store_db.claim_due_schedule(now=now_kst()) as row:
|
row = st.claim_due_schedule(now=now_kst(), owner=worker_owner(), ttl_seconds=lease_seconds())
|
||||||
if row is None:
|
if row is None:
|
||||||
return handled
|
return handled
|
||||||
# 잠금은 여기서 이미 풀렸다. 상태가 PROCESSING 이라 다른 worker 가 집지 않는다.
|
run_one(st, api, row)
|
||||||
schedule_id = int(row["id"])
|
|
||||||
product_no = int(row["product_no"])
|
|
||||||
try:
|
|
||||||
summary = _apply(store_db, api, row)
|
|
||||||
except Cafe24Error as exc:
|
|
||||||
retry_count = int(row.get("retry_count") or 0)
|
|
||||||
if store.can_retry(retry_count):
|
|
||||||
wait = store.retry_backoff_seconds(retry_count)
|
|
||||||
store_db.finish_schedule(
|
|
||||||
schedule_id,
|
|
||||||
status=store.STATUS_PENDING,
|
|
||||||
error=str(exc),
|
|
||||||
next_retry_at=now_kst() + timedelta(seconds=wait),
|
|
||||||
retry_count=retry_count + 1,
|
|
||||||
)
|
|
||||||
logger.warning(
|
|
||||||
"예약 #%s 상품 %s 실패 — %s초 후 재시도 (%s/%s): %s",
|
|
||||||
schedule_id, product_no, wait, retry_count + 1, store.MAX_RETRY, exc,
|
|
||||||
)
|
|
||||||
else:
|
|
||||||
store_db.finish_schedule(
|
|
||||||
schedule_id, status=store.STATUS_FAILED, error=str(exc)
|
|
||||||
)
|
|
||||||
store_db.log_audit(
|
|
||||||
actor=ACTOR, action="schedule_apply", product_no=product_no,
|
|
||||||
schedule_id=schedule_id, result="FAIL", detail=str(exc),
|
|
||||||
)
|
|
||||||
logger.error("예약 #%s 상품 %s 최종 실패: %s", schedule_id, product_no, exc)
|
|
||||||
except Exception as exc: # noqa: BLE001 — 한 건의 사고가 worker 를 죽이면 안 된다.
|
|
||||||
store_db.finish_schedule(
|
|
||||||
schedule_id, status=store.STATUS_FAILED, error=f"{type(exc).__name__}: {exc}"
|
|
||||||
)
|
|
||||||
logger.exception("예약 #%s 처리 중 예상치 못한 오류", schedule_id)
|
|
||||||
else:
|
|
||||||
store_db.finish_schedule(schedule_id, status=store.STATUS_SUCCESS)
|
|
||||||
logger.info("예약 #%s 상품 %s 적용 완료 — %s", schedule_id, product_no, summary)
|
|
||||||
handled += 1
|
handled += 1
|
||||||
|
|
||||||
|
|
||||||
|
|||||||
@@ -0,0 +1,534 @@
|
|||||||
|
"""카페24 쓰기 공통 처리 — 잠금 · 유효 현재값 판정 · 백업 · 시도 기록 · 결과 분류.
|
||||||
|
|
||||||
|
상세설명(과 예약의 진열/판매)을 카페24에 쓰는 모든 경로 — 즉시 적용, 버전 복원,
|
||||||
|
예약 worker — 가 `write_product` 한 곳을 지난다. 경로마다 판정이 달라 생기던 문제
|
||||||
|
(예약 직전 백업이 지연된 옛 HTML 을 담는 등)를 막기 위해서다.
|
||||||
|
|
||||||
|
순서 (docs/CAFE24_MODULE.md 3-2, 3-5)
|
||||||
|
상품 잠금(DB lease) → 카페24 현재값 GET → 결과 모르는 이전 시도 확인
|
||||||
|
→ 유효 현재값(읽기 지연 보정) → BACKUP → 지문 대조(충돌 거부)
|
||||||
|
→ 잠금 펜싱 → 시도 기록(STARTED) → PUT
|
||||||
|
→ 원격 결과 분류(REMOTE_OK / REMOTE_FAILED / UNKNOWN)
|
||||||
|
→ 스냅샷 · 버전(MANUAL/SCHEDULED/ROLLBACK) 기록(RECORDED)
|
||||||
|
|
||||||
|
원칙
|
||||||
|
- 읽기 지연 판정의 근거는 **원격 반영이 확인된 쓰기**(cafe24_write_attempts 의
|
||||||
|
REMOTE_OK/RECORDED)뿐이다. 충돌로 거절된 적용의 백업·예약 초안은 넣지 않는다.
|
||||||
|
- PUT 이 성공한 뒤의 실패(스냅샷·버전 기록)는 "적용 실패"가 아니다. 결과에
|
||||||
|
record_error 로 알리고, 시도 기록(REMOTE_OK)에 남은 내용으로 나중에 복구한다.
|
||||||
|
재적용하지 않는다.
|
||||||
|
- 반영 여부를 모르는 시도(STARTED/UNKNOWN)가 남아 있으면 같은 상품 상세설명을
|
||||||
|
다시 쓰지 않는다(WriteBlocked). 카페24 값이 그 시도의 내용과 같으면 자동 확정.
|
||||||
|
- 잠금은 웹 여러 프로세스 + worker 가 공유하는 DB 표(cafe24_write_locks)다.
|
||||||
|
카페24 관리자 화면에서 사람이 동시에 고치는 것은 막을 수 없다 — 그것은 지문
|
||||||
|
대조(편집 시작 시점 값과 비교)로만 잡는다.
|
||||||
|
|
||||||
|
카페24 호출은 `app.integrations.cafe24` 만 쓴다(httpx 직접 호출 금지).
|
||||||
|
"""
|
||||||
|
|
||||||
|
from __future__ import annotations
|
||||||
|
|
||||||
|
import logging
|
||||||
|
import os
|
||||||
|
import socket
|
||||||
|
import time
|
||||||
|
from contextlib import contextmanager
|
||||||
|
from dataclasses import dataclass, field
|
||||||
|
from datetime import timedelta
|
||||||
|
from typing import Any, Callable, Iterator
|
||||||
|
|
||||||
|
from app.integrations.cafe24 import Cafe24Error, products
|
||||||
|
from app.timezone import now_kst
|
||||||
|
|
||||||
|
from . import store
|
||||||
|
from .common import read_lag_grace_minutes
|
||||||
|
|
||||||
|
logger = logging.getLogger("cafe24.writes")
|
||||||
|
|
||||||
|
DEFAULT_LOCK_TTL_SEC = 300 # 이미지 업로드(최대 120초 × 재시도)도 담을 만큼
|
||||||
|
DEFAULT_LOCK_WAIT_SEC = 3.0 # 웹 요청은 짧게만 기다린다 — 오래 걸리면 "수정 중" 안내
|
||||||
|
|
||||||
|
|
||||||
|
def _env_number(name: str, default: float) -> float:
|
||||||
|
try:
|
||||||
|
value = float(str(os.getenv(name) or "").strip())
|
||||||
|
except ValueError:
|
||||||
|
return default
|
||||||
|
return value if value >= 0 else default
|
||||||
|
|
||||||
|
|
||||||
|
def lock_ttl_seconds() -> int:
|
||||||
|
return max(30, int(_env_number("CAFE24_WRITE_LOCK_TTL_SEC", DEFAULT_LOCK_TTL_SEC)))
|
||||||
|
|
||||||
|
|
||||||
|
def lock_wait_seconds() -> float:
|
||||||
|
return min(30.0, _env_number("CAFE24_WRITE_LOCK_WAIT_SEC", DEFAULT_LOCK_WAIT_SEC))
|
||||||
|
|
||||||
|
|
||||||
|
# ════════════════════════════════════════════════════════════
|
||||||
|
# 예외 — http_status 는 JSON API 가 그대로 쓴다
|
||||||
|
# ════════════════════════════════════════════════════════════
|
||||||
|
class WriteError(Exception):
|
||||||
|
http_status = 500
|
||||||
|
|
||||||
|
def __init__(self, message: str, *, backup_id: int = 0, attempt_id: int = 0):
|
||||||
|
super().__init__(message)
|
||||||
|
self.backup_id = backup_id
|
||||||
|
self.attempt_id = attempt_id
|
||||||
|
|
||||||
|
|
||||||
|
class WriteSetupError(WriteError):
|
||||||
|
"""마이그레이션 005 미적용 등 — 안전장치 없이 쓰지 않는다."""
|
||||||
|
|
||||||
|
http_status = 503
|
||||||
|
|
||||||
|
|
||||||
|
class WriteBusy(WriteError):
|
||||||
|
"""다른 요청(또는 예약 실행)이 같은 대상을 쓰는 중이거나, 잠금을 잃었다."""
|
||||||
|
|
||||||
|
http_status = 409
|
||||||
|
|
||||||
|
|
||||||
|
class WriteConflict(WriteError):
|
||||||
|
"""편집 시작 뒤 카페24 값이 바뀌었다(지문 불일치)."""
|
||||||
|
|
||||||
|
http_status = 409
|
||||||
|
|
||||||
|
|
||||||
|
class WriteBlocked(WriteError):
|
||||||
|
"""반영 여부를 모르는 이전 시도가 남아 있다 — 사람이 확정하기 전에는 쓰지 않는다."""
|
||||||
|
|
||||||
|
http_status = 409
|
||||||
|
|
||||||
|
def __init__(self, message: str, *, attempts: list[dict[str, Any]] | None = None, **kw: Any):
|
||||||
|
super().__init__(message, **kw)
|
||||||
|
self.attempts = attempts or []
|
||||||
|
|
||||||
|
|
||||||
|
class RemoteWriteFailed(WriteError):
|
||||||
|
"""카페24가 거절 — 반영되지 않은 것이 확실하다."""
|
||||||
|
|
||||||
|
http_status = 502
|
||||||
|
|
||||||
|
|
||||||
|
class RemoteWriteUnknown(WriteError):
|
||||||
|
"""요청이 도달했을 수 있으나 응답을 못 받았다 — 반영 여부를 모른다. 재적용 금지."""
|
||||||
|
|
||||||
|
http_status = 502
|
||||||
|
|
||||||
|
|
||||||
|
# ════════════════════════════════════════════════════════════
|
||||||
|
# 잠금
|
||||||
|
# ════════════════════════════════════════════════════════════
|
||||||
|
def product_lock_key(product_no: int) -> str:
|
||||||
|
return f"product:{int(product_no)}"
|
||||||
|
|
||||||
|
|
||||||
|
def design_lock_key(file_key: str) -> str:
|
||||||
|
return f"design:{file_key}"
|
||||||
|
|
||||||
|
|
||||||
|
def lock_owner(actor: str) -> str:
|
||||||
|
"""잠금 소유자 표기 — '사람|호스트:pid'. 안내 문구에는 '|' 앞(사람)만 쓴다."""
|
||||||
|
return f"{actor or '-'}|{socket.gethostname()}:{os.getpid()}"
|
||||||
|
|
||||||
|
|
||||||
|
def require_schema(st: Any) -> None:
|
||||||
|
try:
|
||||||
|
ok = st.write_schema_ready()
|
||||||
|
except Exception as exc: # noqa: BLE001 — DB 접속 실패도 "쓰지 않음"으로
|
||||||
|
raise WriteSetupError(f"cafe24_db 상태를 확인하지 못해 카페24에 쓰지 않았습니다: {type(exc).__name__}") from exc
|
||||||
|
if not ok:
|
||||||
|
raise WriteSetupError(
|
||||||
|
"cafe24_db 마이그레이션 005(쓰기 안전장치)가 적용되지 않아 카페24에 쓰지 않았습니다. "
|
||||||
|
"관리자에게 scripts/sql/cafe24_db_005_write_safety.sql 적용을 요청하세요."
|
||||||
|
)
|
||||||
|
|
||||||
|
|
||||||
|
@dataclass
|
||||||
|
class WriteLock:
|
||||||
|
st: Any
|
||||||
|
key: str
|
||||||
|
token: str
|
||||||
|
ttl: int
|
||||||
|
|
||||||
|
def still_mine(self) -> bool:
|
||||||
|
"""아직 내 잠금이면 연장하고 True(펜싱). 만료돼 넘어갔으면 False."""
|
||||||
|
try:
|
||||||
|
return bool(self.st.renew_lock(self.key, self.token, ttl_seconds=self.ttl))
|
||||||
|
except Exception: # noqa: BLE001 — 확인할 수 없으면 쓰지 않는다
|
||||||
|
logger.exception("잠금 연장 실패 %s", self.key)
|
||||||
|
return False
|
||||||
|
|
||||||
|
|
||||||
|
@contextmanager
|
||||||
|
def write_lock(
|
||||||
|
st: Any,
|
||||||
|
key: str,
|
||||||
|
*,
|
||||||
|
actor: str,
|
||||||
|
purpose: str,
|
||||||
|
wait_seconds: float | None = None,
|
||||||
|
ttl_seconds: int | None = None,
|
||||||
|
) -> Iterator[WriteLock]:
|
||||||
|
"""DB 잠금을 잡은 채 작업한다. 못 잡으면 WriteBusy, 스키마가 없으면 WriteSetupError."""
|
||||||
|
require_schema(st)
|
||||||
|
ttl = int(ttl_seconds or lock_ttl_seconds())
|
||||||
|
wait = lock_wait_seconds() if wait_seconds is None else max(0.0, float(wait_seconds))
|
||||||
|
deadline = time.monotonic() + wait
|
||||||
|
while True:
|
||||||
|
token = st.acquire_lock(key, owner=lock_owner(actor), purpose=purpose, ttl_seconds=ttl)
|
||||||
|
if token:
|
||||||
|
break
|
||||||
|
if time.monotonic() >= deadline:
|
||||||
|
raise WriteBusy(_busy_message(st, key))
|
||||||
|
time.sleep(0.25)
|
||||||
|
lock = WriteLock(st=st, key=key, token=token, ttl=ttl)
|
||||||
|
try:
|
||||||
|
yield lock
|
||||||
|
finally:
|
||||||
|
try:
|
||||||
|
st.release_lock(key, token)
|
||||||
|
except Exception: # noqa: BLE001 — 못 풀어도 만료되면 풀린다
|
||||||
|
logger.exception("잠금 해제 실패 %s (만료 후 자동 해제)", key)
|
||||||
|
|
||||||
|
|
||||||
|
def _busy_message(st: Any, key: str) -> str:
|
||||||
|
try:
|
||||||
|
holder = st.lock_holder(key) or {}
|
||||||
|
except Exception: # noqa: BLE001
|
||||||
|
holder = {}
|
||||||
|
who = str(holder.get("owner") or "").split("|", 1)[0]
|
||||||
|
what = str(holder.get("purpose") or "")
|
||||||
|
detail = " · ".join(p for p in (what, who) if p and p != "-")
|
||||||
|
return "다른 작업이 같은 대상을 수정하고 있습니다" + (f"({detail})" if detail else "") + ". 잠시 후 다시 시도하세요."
|
||||||
|
|
||||||
|
|
||||||
|
# ════════════════════════════════════════════════════════════
|
||||||
|
# 유효 현재값 — 읽기 지연 보정 (확인된 쓰기만 근거)
|
||||||
|
# ════════════════════════════════════════════════════════════
|
||||||
|
def resolve_effective(
|
||||||
|
st: Any, product_no: int, cafe24_html: str, *, fetched_updated: object = None
|
||||||
|
) -> tuple[str, str, dict[str, Any] | None]:
|
||||||
|
"""(유효 HTML, 상태 store.SYNC_*, 마지막 확인된 쓰기)."""
|
||||||
|
grace = read_lag_grace_minutes()
|
||||||
|
since = now_kst() - timedelta(minutes=grace)
|
||||||
|
lineage = st.write_lineage(product_no, since=since)
|
||||||
|
if not lineage:
|
||||||
|
return cafe24_html, store.SYNC_NONE, None
|
||||||
|
last = lineage[0]
|
||||||
|
effective, state = store.resolve_description(
|
||||||
|
cafe24_html,
|
||||||
|
last_write=last,
|
||||||
|
known_digests=store.lineage_digests(lineage),
|
||||||
|
grace_minutes=grace,
|
||||||
|
fetched_updated=fetched_updated,
|
||||||
|
)
|
||||||
|
return effective, state, last
|
||||||
|
|
||||||
|
|
||||||
|
# ════════════════════════════════════════════════════════════
|
||||||
|
# 기록 — PUT 성공 뒤의 로컬 저장(실패해도 "적용 실패"가 아니다)
|
||||||
|
# ════════════════════════════════════════════════════════════
|
||||||
|
def remember_product_write(st: Any, product_no: int, updated: dict[str, Any]) -> tuple[dict[str, Any], str]:
|
||||||
|
"""PUT 응답(상품 dict)을 캐시·스냅샷에 남긴다. (정규화된 상품 행, 기록 오류 문자열)."""
|
||||||
|
if updated and not updated.get("product_no"):
|
||||||
|
# 응답에 상품번호가 빠져도 기록은 남긴다 — 안 남기면 지연 보정이 안 돼 예전 값이 보인다.
|
||||||
|
updated = {**updated, "product_no": int(product_no)}
|
||||||
|
info = products.normalize_product(updated) if updated else {}
|
||||||
|
if not info.get("product_no"):
|
||||||
|
return info, ""
|
||||||
|
try:
|
||||||
|
st.upsert_products([info])
|
||||||
|
st.save_write_snapshot(product_no, "product", store.product_snapshot(updated))
|
||||||
|
except Exception as exc: # noqa: BLE001 — 카페24에는 이미 반영됐다
|
||||||
|
logger.exception("상품 %s 쓰기 스냅샷 저장 실패", product_no)
|
||||||
|
return info, f"{type(exc).__name__}: {exc}"
|
||||||
|
return info, ""
|
||||||
|
|
||||||
|
|
||||||
|
def audit_safe(st: Any, **fields: Any) -> None:
|
||||||
|
"""감사로그 — 실패해도 호출부 결과를 바꾸지 않는다(이미 카페24에 반영된 뒤일 수 있다)."""
|
||||||
|
try:
|
||||||
|
st.log_audit(**fields)
|
||||||
|
except Exception: # noqa: BLE001
|
||||||
|
logger.exception("감사로그 기록 실패: %s", fields.get("action"))
|
||||||
|
|
||||||
|
|
||||||
|
def record_attempt(st: Any, attempt: dict[str, Any]) -> int:
|
||||||
|
"""원격 반영된 시도의 버전을 남기고 RECORDED 로 바꾼다(이미 있으면 그 id). 멱등.
|
||||||
|
|
||||||
|
진열/판매만 바꾼 시도(상세설명 없음)는 버전을 만들지 않고 상태만 RECORDED 로 둔다.
|
||||||
|
"""
|
||||||
|
if not attempt.get("target_digest") and not attempt.get("target_revision_id"):
|
||||||
|
st.update_attempt(int(attempt["id"]), status=store.ATTEMPT_RECORDED, remote_ok=True)
|
||||||
|
return 0
|
||||||
|
origin = str(attempt.get("origin") or store.ORIGIN_MANUAL)
|
||||||
|
revision_type = store.ORIGIN_REVISION_TYPE.get(origin, "MANUAL")
|
||||||
|
source = store.SOURCE_REVISION if origin == store.ORIGIN_ROLLBACK else ""
|
||||||
|
source_revision = attempt.get("target_revision_id") if origin != store.ORIGIN_MANUAL else None
|
||||||
|
return int(st.record_attempt_revision(
|
||||||
|
int(attempt["id"]),
|
||||||
|
revision_type=revision_type,
|
||||||
|
memo=str(attempt.get("memo") or ""),
|
||||||
|
created_by=str(attempt.get("actor") or ""),
|
||||||
|
source=source,
|
||||||
|
source_revision_id=int(source_revision) if source_revision else None,
|
||||||
|
))
|
||||||
|
|
||||||
|
|
||||||
|
def _flags_match(product: dict[str, Any], attempt: dict[str, Any]) -> bool:
|
||||||
|
for key in ("set_display", "set_selling"):
|
||||||
|
want = attempt.get(key)
|
||||||
|
if want is None:
|
||||||
|
continue
|
||||||
|
field_name = key.replace("set_", "")
|
||||||
|
if products._flag(product.get(field_name)) != bool(want): # noqa: SLF001 — 같은 규칙
|
||||||
|
return False
|
||||||
|
return True
|
||||||
|
|
||||||
|
|
||||||
|
def attempt_matches_remote(attempt: dict[str, Any], product: dict[str, Any]) -> bool:
|
||||||
|
"""카페24 현재값이 그 시도가 쓰려던 결과와 같은가(같으면 결과를 "반영됨"으로 확정해도 된다)."""
|
||||||
|
if not product:
|
||||||
|
return False
|
||||||
|
digest = str(attempt.get("target_digest") or "")
|
||||||
|
if digest and store.content_digest(str(product.get("description") or "")) != digest:
|
||||||
|
return False
|
||||||
|
if not digest and attempt.get("set_display") is None and attempt.get("set_selling") is None:
|
||||||
|
return False
|
||||||
|
return _flags_match(product, attempt)
|
||||||
|
|
||||||
|
|
||||||
|
def settle_open_attempts(
|
||||||
|
st: Any, product_no: int, *, product: dict[str, Any], actor: str = "SYSTEM"
|
||||||
|
) -> list[dict[str, Any]]:
|
||||||
|
"""열린 시도를 정리하고 **아직 결과를 모르는 것**만 돌려준다. 잠금 안에서 부른다.
|
||||||
|
|
||||||
|
REMOTE_OK → 버전 기록을 채운다(기록 복구)
|
||||||
|
STARTED / UNKNOWN → 카페24 현재값이 그 시도의 결과와 같으면 반영됨으로 확정
|
||||||
|
(예약이 "확인 필요"였다면 완료로 바꾼다). 다르면 남긴다.
|
||||||
|
"""
|
||||||
|
since = now_kst() - timedelta(minutes=read_lag_grace_minutes())
|
||||||
|
unresolved: list[dict[str, Any]] = []
|
||||||
|
for attempt in st.open_attempts(product_no, since=since):
|
||||||
|
status = attempt.get("status")
|
||||||
|
if status == store.ATTEMPT_REMOTE_OK:
|
||||||
|
try:
|
||||||
|
record_attempt(st, attempt)
|
||||||
|
except Exception: # noqa: BLE001 — 원격은 반영됨. 다음 기회에 다시.
|
||||||
|
logger.exception("시도 #%s 기록 복구 실패", attempt.get("id"))
|
||||||
|
continue
|
||||||
|
if attempt_matches_remote(attempt, product):
|
||||||
|
st.update_attempt(
|
||||||
|
int(attempt["id"]), status=store.ATTEMPT_REMOTE_OK, remote_ok=True,
|
||||||
|
resolved_by="auto:카페24 값이 요청 결과와 같음",
|
||||||
|
only_from=(store.ATTEMPT_STARTED, store.ATTEMPT_UNKNOWN),
|
||||||
|
)
|
||||||
|
try:
|
||||||
|
record_attempt(st, attempt)
|
||||||
|
except Exception: # noqa: BLE001
|
||||||
|
logger.exception("시도 #%s 기록 실패(자동 확정 후)", attempt.get("id"))
|
||||||
|
if attempt.get("schedule_id"):
|
||||||
|
st.review_schedule(
|
||||||
|
int(attempt["schedule_id"]), status=store.STATUS_SUCCESS,
|
||||||
|
note="자동 확인: 카페24 현재값이 예약 내용과 같습니다", actor=actor, action="auto_verify",
|
||||||
|
)
|
||||||
|
continue
|
||||||
|
unresolved.append(attempt)
|
||||||
|
return unresolved
|
||||||
|
|
||||||
|
|
||||||
|
def describe_attempt(attempt: dict[str, Any]) -> str:
|
||||||
|
origin = {store.ORIGIN_MANUAL: "즉시 적용", store.ORIGIN_SCHEDULED: "예약", store.ORIGIN_ROLLBACK: "복원"}.get(
|
||||||
|
str(attempt.get("origin") or ""), "적용")
|
||||||
|
when = str(attempt.get("created_at") or "").replace("T", " ")[:16]
|
||||||
|
who = str(attempt.get("actor") or "")
|
||||||
|
sched = f" · 예약 #{attempt['schedule_id']}" if attempt.get("schedule_id") else ""
|
||||||
|
return f"시도 #{attempt.get('id')} ({origin}{sched}, {when}{', ' + who if who else ''})"
|
||||||
|
|
||||||
|
|
||||||
|
# ════════════════════════════════════════════════════════════
|
||||||
|
# 본 처리
|
||||||
|
# ════════════════════════════════════════════════════════════
|
||||||
|
@dataclass
|
||||||
|
class WriteOutcome:
|
||||||
|
attempt_id: int = 0
|
||||||
|
backup_id: int = 0
|
||||||
|
revision_id: int = 0
|
||||||
|
changed: bool = True # False = 바뀐 것이 없어 PUT 하지 않음
|
||||||
|
pending: bool = False # 백업이 "마지막 확인된 쓰기" 기준이었나(카페24 읽기 지연)
|
||||||
|
recorded: bool = False # 버전 기록까지 끝났나
|
||||||
|
record_error: str = "" # PUT 성공 뒤 로컬 기록 실패 사유(재적용 금지 — 자동 복구)
|
||||||
|
confirmed: bool = False # PUT 뒤 GET 이 새 값을 돌려줬나
|
||||||
|
updated: dict[str, Any] = field(default_factory=dict)
|
||||||
|
|
||||||
|
|
||||||
|
def write_product(
|
||||||
|
st: Any,
|
||||||
|
api: Any,
|
||||||
|
product_no: int,
|
||||||
|
*,
|
||||||
|
lock: WriteLock,
|
||||||
|
origin: str,
|
||||||
|
actor: str,
|
||||||
|
html: str | None,
|
||||||
|
base_fingerprint: str | None = None,
|
||||||
|
set_display: bool | None = None,
|
||||||
|
set_selling: bool | None = None,
|
||||||
|
schedule_id: int | None = None,
|
||||||
|
target_revision_id: int | None = None,
|
||||||
|
memo: str = "",
|
||||||
|
skip_if_same: bool = False,
|
||||||
|
extra_fence: Callable[[], bool] | None = None,
|
||||||
|
wait_confirm: bool = True,
|
||||||
|
) -> WriteOutcome:
|
||||||
|
"""상세설명(html)·진열/판매를 카페24에 쓴다. 잠금(lock)을 잡은 채 부른다.
|
||||||
|
|
||||||
|
예외(아무것도 쓰지 않음): Cafe24Error(현재값 조회 실패), WriteBlocked, WriteConflict,
|
||||||
|
WriteBusy(펜싱 실패) / RemoteWriteFailed(거절) / RemoteWriteUnknown(반영 여부 모름).
|
||||||
|
PUT 성공 뒤의 로컬 기록 실패는 예외가 아니라 WriteOutcome.record_error 로 알린다.
|
||||||
|
"""
|
||||||
|
mall_id = str(getattr(api.config, "mall_id", "") or "")
|
||||||
|
shop_no = 1
|
||||||
|
out = WriteOutcome()
|
||||||
|
current_html: str | None = None
|
||||||
|
effective: str | None = None
|
||||||
|
|
||||||
|
if html is not None:
|
||||||
|
product = products.get_product(api.client, product_no)
|
||||||
|
if not product:
|
||||||
|
raise Cafe24Error("카페24에서 상품을 찾지 못했습니다.")
|
||||||
|
desc = products.descriptions_from_product(product)
|
||||||
|
current_html = desc.description
|
||||||
|
|
||||||
|
unresolved = [a for a in settle_open_attempts(st, product_no, product=product, actor=actor)
|
||||||
|
if a.get("target_digest")]
|
||||||
|
if unresolved:
|
||||||
|
names = ", ".join(describe_attempt(a) for a in unresolved[:3])
|
||||||
|
raise WriteBlocked(
|
||||||
|
f"이전 적용의 반영 여부를 아직 확인하지 못했습니다: {names}. "
|
||||||
|
"쇼핑몰에서 확인한 뒤 편집기 위 안내에서 결과를 확정하고 다시 시도하세요.",
|
||||||
|
attempts=unresolved,
|
||||||
|
)
|
||||||
|
|
||||||
|
effective, state, last = resolve_effective(
|
||||||
|
st, product_no, current_html, fetched_updated=product.get("updated_date")
|
||||||
|
)
|
||||||
|
out.pending = state == store.SYNC_PENDING
|
||||||
|
label = {store.ORIGIN_SCHEDULED: f"예약 #{schedule_id} 적용 직전 자동 백업",
|
||||||
|
store.ORIGIN_ROLLBACK: "복원 직전 자동 백업"}.get(origin, "적용 직전 자동 백업")
|
||||||
|
out.backup_id = st.add_revision(
|
||||||
|
product_no=product_no,
|
||||||
|
html_content=effective,
|
||||||
|
revision_type=store.REVISION_BACKUP,
|
||||||
|
memo=label + (" (카페24 읽기 지연 — 마지막으로 확인된 적용값 기준)" if out.pending else ""),
|
||||||
|
created_by=actor,
|
||||||
|
mall_id=mall_id,
|
||||||
|
shop_no=shop_no,
|
||||||
|
source=store.SOURCE_LAST_WRITE if out.pending else store.SOURCE_OBSERVED,
|
||||||
|
source_revision_id=(last or {}).get("applied_revision_id") if out.pending else None,
|
||||||
|
)
|
||||||
|
# 모바일이 PC 와 달랐다면 그것도 남긴다 — 아래 쓰기로 모바일이 PC 와 같아진다.
|
||||||
|
if desc.mobile_description and desc.mobile_description != desc.description:
|
||||||
|
st.add_revision(
|
||||||
|
product_no=product_no,
|
||||||
|
html_content=desc.mobile_description,
|
||||||
|
revision_type=store.REVISION_BACKUP,
|
||||||
|
memo=label + " (모바일 — PC와 달랐던 내용)",
|
||||||
|
created_by=actor,
|
||||||
|
mall_id=mall_id,
|
||||||
|
shop_no=shop_no,
|
||||||
|
source=store.SOURCE_OBSERVED,
|
||||||
|
)
|
||||||
|
if base_fingerprint and base_fingerprint != store.fingerprint(effective):
|
||||||
|
raise WriteConflict(
|
||||||
|
"편집하는 동안 카페24 값이 변경되었습니다. 새로고침해 현재 내용을 확인한 뒤 다시 적용하세요.",
|
||||||
|
backup_id=out.backup_id,
|
||||||
|
)
|
||||||
|
if skip_if_same and html == effective and set_display is None and set_selling is None:
|
||||||
|
out.changed = False
|
||||||
|
return out
|
||||||
|
|
||||||
|
# 펜싱 — 잠금이 만료돼 남에게 넘어갔으면 쓰지 않는다.
|
||||||
|
if not lock.still_mine() or (extra_fence is not None and not extra_fence()):
|
||||||
|
raise WriteBusy("작업 시간이 길어져 잠금이 만료되었습니다. 카페24에 쓰지 않았습니다 — 다시 시도하세요.",
|
||||||
|
backup_id=out.backup_id)
|
||||||
|
|
||||||
|
out.attempt_id = st.start_attempt(
|
||||||
|
product_no=int(product_no),
|
||||||
|
mall_id=mall_id,
|
||||||
|
shop_no=shop_no,
|
||||||
|
origin=origin,
|
||||||
|
schedule_id=schedule_id,
|
||||||
|
actor=actor,
|
||||||
|
backup_revision_id=out.backup_id or None,
|
||||||
|
observed_digest=store.content_digest(current_html) if current_html is not None else "",
|
||||||
|
base_digest=store.content_digest(effective) if effective is not None else "",
|
||||||
|
target_digest=store.content_digest(html) if html is not None else "",
|
||||||
|
# 예약·복원은 내용이 버전(target_revision_id)에 있다 — 즉시 적용만 시도에 보관한다.
|
||||||
|
target_html=html if (html is not None and not target_revision_id) else "",
|
||||||
|
target_revision_id=target_revision_id,
|
||||||
|
set_display=set_display,
|
||||||
|
set_selling=set_selling,
|
||||||
|
memo=(memo or "")[:500],
|
||||||
|
)
|
||||||
|
|
||||||
|
try:
|
||||||
|
updated = products.update_product(
|
||||||
|
api.client,
|
||||||
|
product_no,
|
||||||
|
description=html,
|
||||||
|
# PC/모바일 구분 안 함 — mobile_description 은 보내지 않고 "PC 와 동일"을 강제.
|
||||||
|
separated_mobile_description="F" if html is not None else None,
|
||||||
|
display=set_display,
|
||||||
|
selling=set_selling,
|
||||||
|
)
|
||||||
|
except Exception as exc: # noqa: BLE001 — 분류해서 다시 던진다
|
||||||
|
known = isinstance(exc, Cafe24Error)
|
||||||
|
unknown = (not known) or bool(getattr(exc, "maybe_applied", False))
|
||||||
|
message = str(exc) if known else f"{type(exc).__name__}: {exc}"
|
||||||
|
try:
|
||||||
|
st.update_attempt(
|
||||||
|
out.attempt_id,
|
||||||
|
status=store.ATTEMPT_UNKNOWN if unknown else store.ATTEMPT_REMOTE_FAILED,
|
||||||
|
error=message,
|
||||||
|
only_from=(store.ATTEMPT_STARTED,),
|
||||||
|
)
|
||||||
|
except Exception: # noqa: BLE001 — 기록 실패 시 STARTED 로 남는다(= 결과 모름, 안전 쪽)
|
||||||
|
logger.exception("시도 #%s 결과 기록 실패", out.attempt_id)
|
||||||
|
kind = RemoteWriteUnknown if unknown else RemoteWriteFailed
|
||||||
|
raise kind(message, backup_id=out.backup_id, attempt_id=out.attempt_id) from exc
|
||||||
|
|
||||||
|
# ── 여기부터는 카페24에 반영된 뒤다. 무엇이 실패해도 "적용 실패"가 아니다. ──
|
||||||
|
out.updated = updated if isinstance(updated, dict) else {}
|
||||||
|
errors: list[str] = []
|
||||||
|
try:
|
||||||
|
st.update_attempt(
|
||||||
|
out.attempt_id, status=store.ATTEMPT_REMOTE_OK, remote_ok=True,
|
||||||
|
remote_updated_at=str(out.updated.get("updated_date") or ""),
|
||||||
|
only_from=(store.ATTEMPT_STARTED,),
|
||||||
|
)
|
||||||
|
except Exception as exc: # noqa: BLE001
|
||||||
|
logger.exception("시도 #%s REMOTE_OK 기록 실패", out.attempt_id)
|
||||||
|
errors.append(f"시도 상태: {type(exc).__name__}")
|
||||||
|
if out.updated.get("product_no"):
|
||||||
|
_, snap_error = remember_product_write(st, product_no, out.updated)
|
||||||
|
if snap_error:
|
||||||
|
errors.append(f"스냅샷: {snap_error}")
|
||||||
|
try:
|
||||||
|
out.revision_id = record_attempt(st, {
|
||||||
|
"id": out.attempt_id, "origin": origin, "actor": actor, "memo": memo,
|
||||||
|
"target_revision_id": target_revision_id,
|
||||||
|
"target_digest": store.content_digest(html) if html is not None else "",
|
||||||
|
})
|
||||||
|
out.recorded = True
|
||||||
|
except Exception as exc: # noqa: BLE001
|
||||||
|
logger.exception("시도 #%s 버전 기록 실패", out.attempt_id)
|
||||||
|
errors.append(f"버전 기록: {type(exc).__name__}: {exc}")
|
||||||
|
out.record_error = "; ".join(errors)
|
||||||
|
|
||||||
|
if html is not None and wait_confirm:
|
||||||
|
# 카페24 관리자 API 의 쓰기 직후 읽기 지연을 짧게 흡수(확인 실패는 실패가 아니다).
|
||||||
|
out.confirmed = products.wait_for_description(api.client, product_no, html)
|
||||||
|
return out
|
||||||
@@ -0,0 +1,76 @@
|
|||||||
|
# [쿠팡] 쿠팡 밀크런 모듈 — `app/modules/cupang/`, `cupang_db`
|
||||||
|
|
||||||
|
> 이 모듈만 고칠 때 읽는 요약. 별도 상세 문서 없음 — 이 파일이 기준.
|
||||||
|
> 정적 파일: `app/static/cupang.css`, `app/static/cupang.js`. 템플릿: `templates/`.
|
||||||
|
> 상품은 `itemcode_db` 읽기 전용(`itemcode.py`).
|
||||||
|
|
||||||
|
## 출고 달력 / 상자 계산
|
||||||
|
|
||||||
|
- 출고 달력·상자 계산이 중심.
|
||||||
|
- 출고 묶음은 **상자 계산 화면의 [분배 확정] 으로만** 만든다. 신규 등록 폼 없음, `/cupang/new` 는 상자 계산으로 리다이렉트.
|
||||||
|
- 확정 조건: 미배분 상자 0 + 담긴 센터마다 출고방식(택배/파렛트) 선택.
|
||||||
|
- 확정 시 센터마다 출고 묶음 1건(`status=출고준비`, 센터입고일 = 출고일 + 1일).
|
||||||
|
- 상자 구성은 `cupang_shipments.box_plan` JSONB 에 스냅샷(혼합 상자 내용물·상자 종류 표시용).
|
||||||
|
- 출고리스트 엑셀 자동 다운로드(`GET /cupang/export.xlsx?date=`, 시트명 YYYYMMDD).
|
||||||
|
- 양식 생성은 `export.py` 한 곳에서 만들어 xlsx·구글시트가 공유.
|
||||||
|
- 작업 중 상태는 `cupang_box_calc_drafts` 에 이름 붙여 임시 저장/불러오기.
|
||||||
|
|
||||||
|
## 출고리스트 문서 동기화 (드라이브 엑셀 파일)
|
||||||
|
|
||||||
|
- 출고리스트 문서는 **구글 드라이브에 올린 .xlsx 파일**(`CUPANG_SHEET_ID`, 기본 `router.DEFAULT_SHEET_ID`
|
||||||
|
= `1J74op7lBZOgE27p4R28I3RWsv0EtXdii`). `router._sheet_target` 이 드라이브에서 형식을 보고 writer 를 고른다:
|
||||||
|
- .xlsx → `app/integrations/drive_xlsx.py` — 내려받아 openpyxl 로 고친 뒤 같은 파일 id 에 다시 올림
|
||||||
|
(인증은 google_drive 와 같음: 서비스 계정 또는 `GOOGLE_SLIDES_OAUTH_REFRESH_TOKEN`/`GOOGLE_SHEETS_OAUTH_REFRESH_TOKEN`, Drive 권한).
|
||||||
|
`with writer.lock:` 블록 = 내려받기 1번·올리기 1번. 올리기 직전 version 이 바뀌었으면(누가 고침) `_in_sheet` 가 처음부터 다시(3번).
|
||||||
|
- 구글 시트 문서 → 예전처럼 `google_sheets.py`(Sheets API). 드라이브 인증이 없을 때도 이쪽.
|
||||||
|
- 엑셀은 openpyxl 로 다시 저장하므로 파일 안 그림·차트는 사라진다(출고리스트에는 없음).
|
||||||
|
- 인증이 없으면 조용히 skip. 확정과 동시에 출고일 시트를 생성/덮어쓰기.
|
||||||
|
- 출고 삭제(건별/날짜 전체) 시에도 같은 날짜 시트 동기화 — 남은 출고가 있으면 다시 쓰고, 없으면 시트 삭제
|
||||||
|
(문서에 시트가 하나뿐이면 내용만 비움).
|
||||||
|
|
||||||
|
## 제품 포장무게
|
||||||
|
|
||||||
|
- 설정(제품명)에서 제품별 포장무게(g, `cupang_products.weight_g`, 마이그레이션 007 + 시드) 입력·표시·정렬.
|
||||||
|
- 출고 상세 상자 목록에 상자별 무게 합계(수량 × 지금 포장무게, `router._attach_box_weights`).
|
||||||
|
- 무게 없는 제품은 "일부 미입력".
|
||||||
|
- 화면은 kg 소수 첫째 자리 사사오입(`router._g_to_kg`) + 맨 아래 수량·무게 합계 행(앞 3열 병합).
|
||||||
|
- 표 칸 모두 가운데 정렬, 요약 카드와 20px 간격.
|
||||||
|
- 상자 목록 엑셀에도 무게(g) 열.
|
||||||
|
|
||||||
|
## 쿠팡 발주 엑셀 업로드
|
||||||
|
|
||||||
|
- 다중 업로드(`POST /cupang/api/box-calc/upload`, openpyxl).
|
||||||
|
- F13 입고예정일의 하루 전 = 출고일.
|
||||||
|
- 22행부터 B=쿠팡상품코드·F=센터명·G=수량을 읽어 `cupang_products.coupang_item_code` 로 제품 매칭 → 센터별 합산
|
||||||
|
→ 센터 단위로 상자 계산·자동 배분.
|
||||||
|
|
||||||
|
## 쿠팡 로켓 매출 (`/cupang/sales`)
|
||||||
|
|
||||||
|
- 테이블 `cupang_sales`·`cupang_sales_weekly`. 발주 라인별 공급가·원가·물류비·마진 표.
|
||||||
|
- 기간/센터/유형/검색 조회, 행 CRUD, 엑셀 다운로드.
|
||||||
|
- 구글 시트 양식 xlsx·csv 업로드(`sales_import.py`) — 같은 발주번호+SKU+출고일+센터+수량은 덮어씀.
|
||||||
|
- 광고비·할인 프로모션·장려금은 주차 단위(`cupang_sales_weekly`)로 보관, 순마진은 화면에서 계산.
|
||||||
|
- 초기 데이터는 `scripts/sql/cupang_sales_seed.sql`.
|
||||||
|
|
||||||
|
## 밀크런 출고리스트 작성 (팝업 → 드라이브 엑셀 파일, 2026-10-23)
|
||||||
|
|
||||||
|
- 첫 화면 "+ 신규 등록" 옆 엑셀색(#217346) 버튼 → 팝업(`index.html` + `static/cupang-outbound.js`).
|
||||||
|
팝업 높이 850px 고정(화면이 낮으면 화면 - 32px), 넘치면 팝업 안 스크롤, [취소]·[완료] 줄은 맨 아래(`.cpg-ol-box`).
|
||||||
|
상자 계산 없이 입고센터 여러 곳을 한 번에 **출고리스트 엑셀 파일에만** 적는다 — cupang_db 출고 묶음은 만들지 않는다(달력에 안 보임).
|
||||||
|
- 대상 파일은 `router._outbound_target` — `CUPANG_OUTBOUND_XLSX_ID`(기본 `DEFAULT_OUTBOUND_XLSX_ID` = `1J74op7lBZOgE27p4R28I3RWsv0EtXdii`),
|
||||||
|
항상 `drive_xlsx`. `CUPANG_SHEET_ID`(분배 확정 동기화)와 따로라 그게 구글 시트 문서여도 팝업은 엑셀에만 쓴다.
|
||||||
|
드라이브 인증이 없거나 파일이 .xlsx 가 아니면 구글 시트로 대신 쓰지 않고 503(사유 표시).
|
||||||
|
- 공통 입력: 작성일(기본 오늘)·출고일·센터입고일(출고일 고르면 +1일 자동)·작업자(기본 `export.WORKER`) — 날짜 칸은 프로젝트 날짜 팝업
|
||||||
|
(`PJLib.enhanceDateInput`, project.js 를 `PJ_LIB_ONLY` 로 로드).
|
||||||
|
- **입고센터 카드**(`#cpg-ol-center-tpl`, [+ 입고센터 추가]·[센터 삭제], 최대 20곳): 센터마다 입고센터(시트 F열 + 등록 센터, 직접 입력 가능),
|
||||||
|
출고방식(**기본 택배**/파렛트), 제품(코드표 `GET /cupang/api/products/all` 검색 → 코드·이름 자동, 수량 수기), 출고(수기).
|
||||||
|
카드 배경색은 센터마다 다르다(JS `recolor` → `data-tone` 0~7, 팝업에 나온 순서대로 배정·같은 센터는 같은 색·미선택은 회색, 색은 cupang.css).
|
||||||
|
- `POST /cupang/api/outbound-sheet` 본문 `{document_date, ship_date, center_arrival_date, worker, centers: [{center, ship_method, outbound, lines}]}`
|
||||||
|
(`centers` 없으면 본문 자체가 센터 1곳 — `_clean_outbound_entries`). 센터 순서대로 시트 `YYYYMMDD(요일)`(출고일) 맨 아래에
|
||||||
|
`export.build_block` 으로 덧붙임(순번 B열 이어짐, 파렛트 센터만 배경색). 시트가 없거나 5행 머리글이 없으면 첫 센터는 양식째 새로 쓴다(`write_table`).
|
||||||
|
전체가 `writer.lock` 한 덩어리 = 엑셀 내려받기 1번·올리기 1번(`_run_outbound_write`). 입고센터 후보는 `GET /cupang/api/outbound-sheet/centers`(10분 캐시).
|
||||||
|
- **진행 막대**: 팝업은 `?stream=1` 로 보내고 서버가 NDJSON 한 줄씩 `{progress, until, step}`(5 내려받기 → 40~80 센터별 추가 → 80 올리기)
|
||||||
|
… 마지막 `{done: true, ...결과}` 또는 `{error}`. 쓰기는 별도 스레드(잠금은 잡은 스레드에서 풀어야 함)가 하고 큐로 넘긴다.
|
||||||
|
화면은 단계 사이에도 다음 단계(until) 바로 앞까지 조금씩 채우고 %를 같이 표시, 실패면 빨강. 입력 오류(400)·설정 없음(503)은 스트림 전 보통 JSON.
|
||||||
|
- 주의: 같은 출고일에 [분배 확정]·출고 삭제가 일어나면 기존 동기화가 그 날짜 시트를 DB 기준으로 **통째로 다시 써서**
|
||||||
|
팝업으로 적은 줄이 사라진다.
|
||||||
@@ -36,10 +36,23 @@ class CupangDBStore:
|
|||||||
open=False,
|
open=False,
|
||||||
)
|
)
|
||||||
self._pool.open(wait=False)
|
self._pool.open(wait=False)
|
||||||
|
self._weight_col: bool | None = None # 마이그레이션 007(weight_g) 적용 여부 — 한 번 확인되면 기억
|
||||||
|
|
||||||
def close(self) -> None:
|
def close(self) -> None:
|
||||||
self._pool.close()
|
self._pool.close()
|
||||||
|
|
||||||
|
def weight_enabled(self) -> bool:
|
||||||
|
"""cupang_products.weight_g(포장무게, 마이그레이션 007) 가 있는가. 있으면 기억(없으면 다음에 다시 확인)."""
|
||||||
|
if self._weight_col:
|
||||||
|
return True
|
||||||
|
with self._pool.connection() as conn:
|
||||||
|
row = conn.execute(
|
||||||
|
"SELECT 1 FROM information_schema.columns "
|
||||||
|
"WHERE table_name = 'cupang_products' AND column_name = 'weight_g'"
|
||||||
|
).fetchone()
|
||||||
|
self._weight_col = row is not None
|
||||||
|
return self._weight_col
|
||||||
|
|
||||||
# ════════════════════════════════════════════════════════════
|
# ════════════════════════════════════════════════════════════
|
||||||
# 입고센터 (cupang_centers)
|
# 입고센터 (cupang_centers)
|
||||||
# ════════════════════════════════════════════════════════════
|
# ════════════════════════════════════════════════════════════
|
||||||
@@ -300,32 +313,39 @@ class CupangDBStore:
|
|||||||
product_name: str,
|
product_name: str,
|
||||||
coupang_item_code: str | None = None,
|
coupang_item_code: str | None = None,
|
||||||
sort_order: int = 0,
|
sort_order: int = 0,
|
||||||
|
weight_g: int | None = None,
|
||||||
) -> dict[str, Any]:
|
) -> dict[str, Any]:
|
||||||
"""제품 등록/수정.
|
"""제품 등록/수정.
|
||||||
|
|
||||||
coupang_item_code 가 None 이면 기존 값을 유지한다(빈 문자열은 지우기).
|
coupang_item_code 가 None 이면 기존 값을 유지한다(빈 문자열은 지우기).
|
||||||
|
weight_g(포장무게 g) 가 None 이면 기존 값을 유지한다(수기 추가에서 비워 두면 그대로). 007 미적용이면 무시.
|
||||||
"""
|
"""
|
||||||
code = (product_code or "").strip()
|
code = (product_code or "").strip()
|
||||||
name = (product_name or "").strip()
|
name = (product_name or "").strip()
|
||||||
cic = None if coupang_item_code is None else coupang_item_code.strip()
|
cic = None if coupang_item_code is None else coupang_item_code.strip()
|
||||||
if not code or not name:
|
if not code or not name:
|
||||||
raise ValueError("제품코드와 제품명 모두 필요합니다.")
|
raise ValueError("제품코드와 제품명 모두 필요합니다.")
|
||||||
|
weight = self.weight_enabled()
|
||||||
with self._pool.connection() as conn:
|
with self._pool.connection() as conn:
|
||||||
row = conn.execute(
|
row = conn.execute(
|
||||||
"""
|
"""
|
||||||
INSERT INTO cupang_products
|
INSERT INTO cupang_products
|
||||||
(product_code, product_name, coupang_item_code, sort_order)
|
(product_code, product_name, coupang_item_code, sort_order"""
|
||||||
VALUES (%(code)s, %(name)s, COALESCE(%(cic)s, ''), %(sort)s)
|
+ (", weight_g" if weight else "") + """)
|
||||||
|
VALUES (%(code)s, %(name)s, COALESCE(%(cic)s, ''), %(sort)s"""
|
||||||
|
+ (", %(w)s" if weight else "") + """)
|
||||||
ON CONFLICT (product_code) DO UPDATE
|
ON CONFLICT (product_code) DO UPDATE
|
||||||
SET product_name = EXCLUDED.product_name,
|
SET product_name = EXCLUDED.product_name,
|
||||||
coupang_item_code = COALESCE(
|
coupang_item_code = COALESCE(
|
||||||
%(cic)s, cupang_products.coupang_item_code
|
%(cic)s, cupang_products.coupang_item_code
|
||||||
),
|
),"""
|
||||||
|
+ ("\n weight_g = COALESCE(%(w)s, cupang_products.weight_g)," if weight else "")
|
||||||
|
+ """
|
||||||
sort_order = EXCLUDED.sort_order,
|
sort_order = EXCLUDED.sort_order,
|
||||||
active = TRUE
|
active = TRUE
|
||||||
RETURNING *
|
RETURNING *
|
||||||
""",
|
""",
|
||||||
{"code": code, "name": name, "cic": cic, "sort": sort_order},
|
{"code": code, "name": name, "cic": cic, "sort": sort_order, "w": weight_g},
|
||||||
).fetchone()
|
).fetchone()
|
||||||
return self._product_serialize(row)
|
return self._product_serialize(row)
|
||||||
|
|
||||||
@@ -345,8 +365,11 @@ class CupangDBStore:
|
|||||||
product_name: str,
|
product_name: str,
|
||||||
product_code: str,
|
product_code: str,
|
||||||
coupang_item_code: str = "",
|
coupang_item_code: str = "",
|
||||||
|
weight_g: Any = ...,
|
||||||
) -> dict[str, Any]:
|
) -> dict[str, Any]:
|
||||||
"""등록된 제품 수정(제품명/제품코드/쿠팡상품코드).
|
"""등록된 제품 수정(제품명/제품코드/쿠팡상품코드/포장무게).
|
||||||
|
|
||||||
|
weight_g: 정수 g 또는 None(지움). 넘기지 않으면(...) 그대로 — 007 미적용이면 무시.
|
||||||
|
|
||||||
제품코드가 바뀌면 같은 코드로 연결돼 있던 상자 규칙(cupang_box_rules)의
|
제품코드가 바뀌면 같은 코드로 연결돼 있던 상자 규칙(cupang_box_rules)의
|
||||||
product_code 도 함께 옮긴다(출고 라인은 과거 기록이라 스냅샷 유지).
|
product_code 도 함께 옮긴다(출고 라인은 과거 기록이라 스냅샷 유지).
|
||||||
@@ -356,6 +379,7 @@ class CupangDBStore:
|
|||||||
cic = (coupang_item_code or "").strip()
|
cic = (coupang_item_code or "").strip()
|
||||||
if not name or not code:
|
if not name or not code:
|
||||||
raise ValueError("제품코드와 제품명 모두 필요합니다.")
|
raise ValueError("제품코드와 제품명 모두 필요합니다.")
|
||||||
|
set_weight = weight_g is not ... and self.weight_enabled() # 트랜잭션 밖에서 확인(연결을 겹쳐 잡지 않게)
|
||||||
with self._pool.connection() as conn:
|
with self._pool.connection() as conn:
|
||||||
with conn.transaction():
|
with conn.transaction():
|
||||||
old = conn.execute(
|
old = conn.execute(
|
||||||
@@ -378,11 +402,12 @@ class CupangDBStore:
|
|||||||
UPDATE cupang_products
|
UPDATE cupang_products
|
||||||
SET product_name = %s,
|
SET product_name = %s,
|
||||||
product_code = %s,
|
product_code = %s,
|
||||||
coupang_item_code = %s
|
coupang_item_code = %s"""
|
||||||
|
+ (", weight_g = %s" if set_weight else "") + """
|
||||||
WHERE id = %s
|
WHERE id = %s
|
||||||
RETURNING *
|
RETURNING *
|
||||||
""",
|
""",
|
||||||
(name, code, cic, product_id),
|
(name, code, cic) + ((weight_g,) if set_weight else ()) + (product_id,),
|
||||||
).fetchone()
|
).fetchone()
|
||||||
if code != old_code:
|
if code != old_code:
|
||||||
# 새 코드로 된 규칙이 이미 있으면 옮기지 않는다(중복 방지).
|
# 새 코드로 된 규칙이 이미 있으면 옮기지 않는다(중복 방지).
|
||||||
@@ -1081,6 +1106,8 @@ class CupangDBStore:
|
|||||||
out["active"] = bool(out.get("active", True))
|
out["active"] = bool(out.get("active", True))
|
||||||
out["sort_order"] = int(out.get("sort_order", 0))
|
out["sort_order"] = int(out.get("sort_order", 0))
|
||||||
out["coupang_item_code"] = (out.get("coupang_item_code") or "").strip()
|
out["coupang_item_code"] = (out.get("coupang_item_code") or "").strip()
|
||||||
|
w = out.get("weight_g") # 007 미적용이면 키 없음 → None
|
||||||
|
out["weight_g"] = int(w) if w is not None else None
|
||||||
for k in ("created_at", "updated_at"):
|
for k in ("created_at", "updated_at"):
|
||||||
v = out.get(k)
|
v = out.get(k)
|
||||||
if isinstance(v, datetime):
|
if isinstance(v, datetime):
|
||||||
|
|||||||
@@ -94,37 +94,15 @@ def build_table(ship_date: str, shipments: list[dict[str, Any]]) -> dict[str, An
|
|||||||
row = FIRST_DATA_ROW
|
row = FIRST_DATA_ROW
|
||||||
seq = 0
|
seq = 0
|
||||||
for sh in shipments:
|
for sh in shipments:
|
||||||
lines = sh.get("lines") or []
|
block = build_block(sh, start_row=row, start_seq=seq)
|
||||||
if not lines:
|
if block is None:
|
||||||
continue
|
continue
|
||||||
start = row
|
cells.update(block["cells"])
|
||||||
for ln in lines:
|
merges.extend(block["merges"])
|
||||||
seq += 1
|
if block["is_pallet"]:
|
||||||
cells[(row, 2)] = seq
|
pallet_ranges.append((block["first_row"], block["last_row"]))
|
||||||
cells[(row, 8)] = ln.get("product_code") or ""
|
row = block["last_row"] + 1
|
||||||
cells[(row, 9)] = ln.get("product_name_snapshot") or ""
|
seq = block["last_seq"]
|
||||||
cells[(row, 10)] = int(ln.get("quantity") or 0)
|
|
||||||
row += 1
|
|
||||||
end = row - 1
|
|
||||||
|
|
||||||
method = sh.get("ship_method") or ""
|
|
||||||
if method == PALLET_METHOD:
|
|
||||||
pallet_ranges.append((start, end))
|
|
||||||
|
|
||||||
block = {
|
|
||||||
# 날짜는 요일까지 표기 — 2026-09-03(목)
|
|
||||||
3: with_dow(str(sh.get("document_date") or "")),
|
|
||||||
4: with_dow(str(sh.get("ship_date") or "")),
|
|
||||||
5: with_dow(str(sh.get("center_arrival_date") or "")),
|
|
||||||
6: sh.get("center_name_snapshot") or "",
|
|
||||||
7: method,
|
|
||||||
11: sh.get("outbound_summary") or "",
|
|
||||||
12: WORKER,
|
|
||||||
}
|
|
||||||
for col in MERGE_COLS:
|
|
||||||
cells[(start, col)] = block[col]
|
|
||||||
if end > start:
|
|
||||||
merges.append((start, col, end, col))
|
|
||||||
|
|
||||||
return {
|
return {
|
||||||
"title": title,
|
"title": title,
|
||||||
@@ -135,6 +113,53 @@ def build_table(ship_date: str, shipments: list[dict[str, Any]]) -> dict[str, An
|
|||||||
}
|
}
|
||||||
|
|
||||||
|
|
||||||
|
def build_block(sh: dict[str, Any], *, start_row: int, start_seq: int) -> dict[str, Any] | None:
|
||||||
|
"""출고 묶음(센터) 1건 → start_row 부터 품목 1줄 = 1행. 품목이 없으면 None.
|
||||||
|
|
||||||
|
build_table(시트 전체)과 출고리스트 직접 작성(기존 시트 아래에 덧붙임)이 같이 쓴다.
|
||||||
|
순번(B열)은 start_seq 다음 번호부터 이어진다.
|
||||||
|
"""
|
||||||
|
lines = sh.get("lines") or []
|
||||||
|
if not lines:
|
||||||
|
return None
|
||||||
|
cells: dict[tuple[int, int], Any] = {}
|
||||||
|
merges: list[tuple[int, int, int, int]] = []
|
||||||
|
row, seq = start_row, start_seq
|
||||||
|
for ln in lines:
|
||||||
|
seq += 1
|
||||||
|
cells[(row, 2)] = seq
|
||||||
|
cells[(row, 8)] = ln.get("product_code") or ""
|
||||||
|
cells[(row, 9)] = ln.get("product_name_snapshot") or ""
|
||||||
|
cells[(row, 10)] = int(ln.get("quantity") or 0)
|
||||||
|
row += 1
|
||||||
|
end = row - 1
|
||||||
|
|
||||||
|
method = sh.get("ship_method") or ""
|
||||||
|
block = {
|
||||||
|
# 날짜는 요일까지 표기 — 2026-09-03(목)
|
||||||
|
3: with_dow(str(sh.get("document_date") or "")),
|
||||||
|
4: with_dow(str(sh.get("ship_date") or "")),
|
||||||
|
5: with_dow(str(sh.get("center_arrival_date") or "")),
|
||||||
|
6: sh.get("center_name_snapshot") or "",
|
||||||
|
7: method,
|
||||||
|
11: sh.get("outbound_summary") or "",
|
||||||
|
12: sh.get("worker") or WORKER,
|
||||||
|
}
|
||||||
|
for col in MERGE_COLS:
|
||||||
|
cells[(start_row, col)] = block[col]
|
||||||
|
if end > start_row:
|
||||||
|
merges.append((start_row, col, end, col))
|
||||||
|
|
||||||
|
return {
|
||||||
|
"cells": cells,
|
||||||
|
"merges": merges,
|
||||||
|
"first_row": start_row,
|
||||||
|
"last_row": end,
|
||||||
|
"last_seq": seq,
|
||||||
|
"is_pallet": method == PALLET_METHOD,
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
def build_workbook(ship_date: str, shipments: list[dict[str, Any]]) -> Any:
|
def build_workbook(ship_date: str, shipments: list[dict[str, Any]]) -> Any:
|
||||||
"""xlsx 워크북(openpyxl). 시트명 = YYYYMMDD(요일)."""
|
"""xlsx 워크북(openpyxl). 시트명 = YYYYMMDD(요일)."""
|
||||||
from openpyxl import Workbook
|
from openpyxl import Workbook
|
||||||
@@ -193,10 +218,17 @@ def build_workbook(ship_date: str, shipments: list[dict[str, Any]]) -> Any:
|
|||||||
# ── 상자 목록(상자 번호별 내용물) ──────────────────────────────
|
# ── 상자 목록(상자 번호별 내용물) ──────────────────────────────
|
||||||
BOX_HEADERS = ["상자번호", "제품명", "제품코드", "수량"]
|
BOX_HEADERS = ["상자번호", "제품명", "제품코드", "수량"]
|
||||||
BOX_WIDTHS_PX = {1: 70, 2: 240, 3: 110, 4: 70}
|
BOX_WIDTHS_PX = {1: 70, 2: 240, 3: 110, 4: 70}
|
||||||
|
BOX_WEIGHT_HEADER = "무게(g)" # with_weight 일 때 5열 — 상자 무게 합계(상자번호처럼 상자 단위로 세로 병합)
|
||||||
|
BOX_WEIGHT_WIDTH_PX = 80
|
||||||
|
|
||||||
|
|
||||||
def build_box_list_workbook(shipment: dict[str, Any], box_list: list[dict[str, Any]]) -> Any:
|
def build_box_list_workbook(
|
||||||
"""상자 번호 · 제품명 · 제품코드 · 수량 한 줄씩. 시트명 = YYYYMMDD(요일)."""
|
shipment: dict[str, Any], box_list: list[dict[str, Any]], *, with_weight: bool = False
|
||||||
|
) -> Any:
|
||||||
|
"""상자 번호 · 제품명 · 제품코드 · 수량 한 줄씩. 시트명 = YYYYMMDD(요일).
|
||||||
|
|
||||||
|
with_weight 면 5열 "무게(g)" — 상자마다 box["weight_g"](라우터 _attach_box_weights), 모르면 빈칸."""
|
||||||
|
headers = BOX_HEADERS + ([BOX_WEIGHT_HEADER] if with_weight else [])
|
||||||
from openpyxl import Workbook
|
from openpyxl import Workbook
|
||||||
from openpyxl.styles import Alignment, Border, Font, PatternFill, Side
|
from openpyxl.styles import Alignment, Border, Font, PatternFill, Side
|
||||||
from openpyxl.utils import get_column_letter
|
from openpyxl.utils import get_column_letter
|
||||||
@@ -215,10 +247,10 @@ def build_box_list_workbook(shipment: dict[str, Any], box_list: list[dict[str, A
|
|||||||
|
|
||||||
ws.cell(row=1, column=1, value=f"{with_dow(ship_date)} {center} 상자 목록")
|
ws.cell(row=1, column=1, value=f"{with_dow(ship_date)} {center} 상자 목록")
|
||||||
ws.cell(row=1, column=1).font = Font(size=14, bold=True)
|
ws.cell(row=1, column=1).font = Font(size=14, bold=True)
|
||||||
ws.merge_cells(start_row=1, start_column=1, end_row=1, end_column=len(BOX_HEADERS))
|
ws.merge_cells(start_row=1, start_column=1, end_row=1, end_column=len(headers))
|
||||||
|
|
||||||
header_fill = PatternFill("solid", fgColor=HEADER_BG)
|
header_fill = PatternFill("solid", fgColor=HEADER_BG)
|
||||||
for idx, name in enumerate(BOX_HEADERS, start=1):
|
for idx, name in enumerate(headers, start=1):
|
||||||
cell = ws.cell(row=2, column=idx, value=name)
|
cell = ws.cell(row=2, column=idx, value=name)
|
||||||
cell.font = Font(bold=True)
|
cell.font = Font(bold=True)
|
||||||
cell.alignment = center_align
|
cell.alignment = center_align
|
||||||
@@ -235,18 +267,27 @@ def build_box_list_workbook(shipment: dict[str, Any], box_list: list[dict[str, A
|
|||||||
ws.cell(row=row, column=3, value=it.get("product_code") or "")
|
ws.cell(row=row, column=3, value=it.get("product_code") or "")
|
||||||
ws.cell(row=row, column=4, value=int(it.get("quantity") or 0))
|
ws.cell(row=row, column=4, value=int(it.get("quantity") or 0))
|
||||||
row += 1
|
row += 1
|
||||||
# 한 상자에 여러 제품이면 상자번호 칸을 세로로 합친다.
|
if with_weight and contents:
|
||||||
|
w = entry.get("weight_g")
|
||||||
|
ws.cell(row=first, column=5, value=(int(w) if w is not None else None))
|
||||||
|
ws.cell(row=first, column=5).number_format = "#,##0"
|
||||||
|
# 한 상자에 여러 제품이면 상자번호(·무게) 칸을 세로로 합친다.
|
||||||
if row - first > 1:
|
if row - first > 1:
|
||||||
ws.merge_cells(start_row=first, start_column=1, end_row=row - 1, end_column=1)
|
ws.merge_cells(start_row=first, start_column=1, end_row=row - 1, end_column=1)
|
||||||
|
if with_weight:
|
||||||
|
ws.merge_cells(start_row=first, start_column=5, end_row=row - 1, end_column=5)
|
||||||
|
|
||||||
last = row - 1
|
last = row - 1
|
||||||
for r in range(3, last + 1):
|
for r in range(3, last + 1):
|
||||||
for col in range(1, len(BOX_HEADERS) + 1):
|
for col in range(1, len(headers) + 1):
|
||||||
cell = ws.cell(row=r, column=col)
|
cell = ws.cell(row=r, column=col)
|
||||||
cell.border = box
|
cell.border = box
|
||||||
cell.alignment = left_align if col == 2 else center_align
|
cell.alignment = left_align if col == 2 else center_align
|
||||||
|
|
||||||
for col, px in BOX_WIDTHS_PX.items():
|
widths = dict(BOX_WIDTHS_PX)
|
||||||
|
if with_weight:
|
||||||
|
widths[5] = BOX_WEIGHT_WIDTH_PX
|
||||||
|
for col, px in widths.items():
|
||||||
ws.column_dimensions[get_column_letter(col)].width = round(px / PX_PER_CHAR, 2)
|
ws.column_dimensions[get_column_letter(col)].width = round(px / PX_PER_CHAR, 2)
|
||||||
ws.row_dimensions[1].height = 24
|
ws.row_dimensions[1].height = 24
|
||||||
|
|
||||||
|
|||||||
+465
-39
@@ -11,6 +11,7 @@ from __future__ import annotations
|
|||||||
|
|
||||||
import calendar as _calendar
|
import calendar as _calendar
|
||||||
import json
|
import json
|
||||||
|
from decimal import ROUND_HALF_UP, Decimal
|
||||||
from fractions import Fraction
|
from fractions import Fraction
|
||||||
from typing import Any
|
from typing import Any
|
||||||
|
|
||||||
@@ -21,8 +22,9 @@ from app.timezone import today_kst
|
|||||||
from fastapi import APIRouter, Body, Depends, File, Form, HTTPException, Request, UploadFile
|
from fastapi import APIRouter, Body, Depends, File, Form, HTTPException, Request, UploadFile
|
||||||
from fastapi.responses import HTMLResponse, JSONResponse, RedirectResponse
|
from fastapi.responses import HTMLResponse, JSONResponse, RedirectResponse
|
||||||
|
|
||||||
|
from .export import WORKER as OUTBOUND_WORKER
|
||||||
from .holidays import holiday_name, is_holiday
|
from .holidays import holiday_name, is_holiday
|
||||||
from .store import SHIP_METHODS
|
from .store import SHIP_METHODS, parse_weight_g
|
||||||
|
|
||||||
router = APIRouter(prefix="/cupang", tags=["cupang"])
|
router = APIRouter(prefix="/cupang", tags=["cupang"])
|
||||||
|
|
||||||
@@ -73,11 +75,11 @@ def _render_config_needed(request: Request, user: dict[str, Any]) -> HTMLRespons
|
|||||||
def _guard(request: Request) -> tuple[Any, dict[str, Any]] | HTMLResponse | RedirectResponse:
|
def _guard(request: Request) -> tuple[Any, dict[str, Any]] | HTMLResponse | RedirectResponse:
|
||||||
"""로그인+권한+store 점검을 한 번에. 페이지 핸들러 진입부에서 사용."""
|
"""로그인+권한+store 점검을 한 번에. 페이지 핸들러 진입부에서 사용."""
|
||||||
from app.main import get_current_user_record, render_template # noqa: WPS433
|
from app.main import get_current_user_record, render_template # noqa: WPS433
|
||||||
from app.store import has_module, is_admin # noqa: WPS433
|
from app.store import has_module, is_admin, login_redirect # noqa: WPS433
|
||||||
|
|
||||||
user = get_current_user_record(request)
|
user = get_current_user_record(request)
|
||||||
if user is None:
|
if user is None:
|
||||||
return RedirectResponse(url="/login", status_code=303)
|
return login_redirect(request)
|
||||||
if not has_module(user, "cupang"):
|
if not has_module(user, "cupang"):
|
||||||
return render_template(
|
return render_template(
|
||||||
request,
|
request,
|
||||||
@@ -221,6 +223,7 @@ def index(request: Request) -> HTMLResponse:
|
|||||||
"months": months,
|
"months": months,
|
||||||
"selected_date": sel,
|
"selected_date": sel,
|
||||||
"sel_shipments": sel_shipments,
|
"sel_shipments": sel_shipments,
|
||||||
|
"outbound_worker": OUTBOUND_WORKER,
|
||||||
},
|
},
|
||||||
)
|
)
|
||||||
|
|
||||||
@@ -242,21 +245,57 @@ def _shipments_for_date(store: Any, ship_date: str) -> list[dict[str, Any]]:
|
|||||||
return out
|
return out
|
||||||
|
|
||||||
|
|
||||||
|
# 출고리스트 문서 — 구글 드라이브에 올려 둔 엑셀(.xlsx) 파일(2026-10-23). 구글 시트 문서여도 된다.
|
||||||
|
DEFAULT_SHEET_ID = "1J74op7lBZOgE27p4R28I3RWsv0EtXdii"
|
||||||
|
|
||||||
|
|
||||||
def _sheet_target(store: Any) -> tuple[Any, str, dict[str, Any] | None]:
|
def _sheet_target(store: Any) -> tuple[Any, str, dict[str, Any] | None]:
|
||||||
"""(writer, spreadsheet_id, skip 사유) — 설정이 없으면 skip 정보를 돌려준다."""
|
"""(writer, 문서 id, skip 사유) — 쓸 수 없으면 skip 정보를 돌려준다.
|
||||||
|
|
||||||
|
문서 형식은 드라이브에서 보고 고른다 — .xlsx 파일이면 drive_xlsx(내려받아 고친 뒤 다시 올림),
|
||||||
|
구글 시트 문서면 google_sheets. 두 writer 는 같은 메서드를 갖는다."""
|
||||||
import os # noqa: WPS433
|
import os # noqa: WPS433
|
||||||
|
|
||||||
from app.integrations.google_sheets import get_writer # noqa: WPS433
|
from app.integrations import drive_xlsx, google_sheets # noqa: WPS433
|
||||||
|
|
||||||
spreadsheet_id = (os.getenv("CUPANG_SHEET_ID") or "").strip()
|
spreadsheet_id = (os.getenv("CUPANG_SHEET_ID") or "").strip() or DEFAULT_SHEET_ID
|
||||||
if not spreadsheet_id:
|
drive = drive_xlsx.get_writer()
|
||||||
return None, "", {"ok": False, "skipped": True, "reason": "CUPANG_SHEET_ID 미설정"}
|
if not drive.enabled:
|
||||||
writer = get_writer()
|
# 드라이브 인증이 없으면 예전처럼 Sheets API 로(구글 시트 문서일 때만 된다)
|
||||||
|
writer = google_sheets.get_writer()
|
||||||
|
if not writer.enabled:
|
||||||
|
return None, "", {"ok": False, "skipped": True, "reason": writer.reason}
|
||||||
|
return writer, spreadsheet_id, None
|
||||||
|
try:
|
||||||
|
kind = drive.file_kind(spreadsheet_id)
|
||||||
|
except Exception as exc: # noqa: BLE001 - 사유만(비밀값 없음)
|
||||||
|
return None, "", {"ok": False, "skipped": True, "reason": str(exc) or type(exc).__name__}
|
||||||
|
if kind == "xlsx":
|
||||||
|
return drive, spreadsheet_id, None
|
||||||
|
if kind != "sheets":
|
||||||
|
return None, "", {"ok": False, "skipped": True, "reason": f"엑셀·구글 시트 파일이 아닙니다({kind})"}
|
||||||
|
writer = google_sheets.get_writer()
|
||||||
if not writer.enabled:
|
if not writer.enabled:
|
||||||
return None, "", {"ok": False, "skipped": True, "reason": writer.reason}
|
return None, "", {"ok": False, "skipped": True, "reason": writer.reason}
|
||||||
return writer, spreadsheet_id, None
|
return writer, spreadsheet_id, None
|
||||||
|
|
||||||
|
|
||||||
|
def _in_sheet(writer: Any, fn: Any) -> Any:
|
||||||
|
"""`with writer.lock:` 안에서 fn() — 읽기~쓰기를 한 덩어리로.
|
||||||
|
|
||||||
|
엑셀 파일(drive_xlsx)은 내려받은 뒤 올리기 전에 누가 파일을 고쳤으면 처음부터 다시(최대 3번)."""
|
||||||
|
from app.integrations.drive_xlsx import XlsxChangedError # noqa: WPS433
|
||||||
|
|
||||||
|
for attempt in range(3):
|
||||||
|
try:
|
||||||
|
with writer.lock:
|
||||||
|
return fn()
|
||||||
|
except XlsxChangedError:
|
||||||
|
if attempt == 2:
|
||||||
|
raise
|
||||||
|
return None
|
||||||
|
|
||||||
|
|
||||||
def _sync_google_sheet_after_delete(store: Any, ship_date: str) -> dict[str, Any]:
|
def _sync_google_sheet_after_delete(store: Any, ship_date: str) -> dict[str, Any]:
|
||||||
"""출고 삭제 후 구글 시트를 현재 상태에 맞춘다.
|
"""출고 삭제 후 구글 시트를 현재 상태에 맞춘다.
|
||||||
|
|
||||||
@@ -274,7 +313,8 @@ def _sync_google_sheet_after_delete(store: Any, ship_date: str) -> dict[str, Any
|
|||||||
return _push_to_google_sheet(store, ship_date)
|
return _push_to_google_sheet(store, ship_date)
|
||||||
|
|
||||||
try:
|
try:
|
||||||
res = writer.delete_sheet(spreadsheet_id=spreadsheet_id, title=sheet_title(ship_date))
|
res = _in_sheet(writer, lambda: writer.delete_sheet(spreadsheet_id=spreadsheet_id,
|
||||||
|
title=sheet_title(ship_date)))
|
||||||
except Exception as exc: # noqa: BLE001 - 사유만 남긴다
|
except Exception as exc: # noqa: BLE001 - 사유만 남긴다
|
||||||
return {"ok": False, "skipped": False, "reason": f"{type(exc).__name__}: {exc}"}
|
return {"ok": False, "skipped": False, "reason": f"{type(exc).__name__}: {exc}"}
|
||||||
return {"ok": True, "skipped": False, **res}
|
return {"ok": True, "skipped": False, **res}
|
||||||
@@ -290,17 +330,12 @@ def _log_sheet(action: str, ship_date: str, res: dict[str, Any]) -> None:
|
|||||||
|
|
||||||
|
|
||||||
def _push_to_google_sheet(store: Any, ship_date: str) -> dict[str, Any]:
|
def _push_to_google_sheet(store: Any, ship_date: str) -> dict[str, Any]:
|
||||||
"""확정한 출고일을 Google 스프레드시트에 시트 1장으로 기록.
|
"""확정한 출고일을 출고리스트 문서(드라이브 엑셀 또는 구글 시트)에 시트 1장으로 기록.
|
||||||
|
|
||||||
- 대상 스프레드시트: 환경변수 `CUPANG_SHEET_ID`
|
- 대상 문서: 환경변수 `CUPANG_SHEET_ID`(기본 DEFAULT_SHEET_ID), 형식은 `_sheet_target` 이 고른다.
|
||||||
- 인증: 서비스 계정(app/integrations/google_sheets.py). 미설정이면 조용히 skip.
|
- 인증: 서비스 계정 또는 OAuth(app/integrations/drive_xlsx.py·google_sheets.py). 미설정이면 조용히 skip.
|
||||||
- 실패해도 출고 묶음 저장은 이미 끝났으므로 예외를 밖으로 던지지 않는다.
|
- 실패해도 출고 묶음 저장은 이미 끝났으므로 예외를 밖으로 던지지 않는다.
|
||||||
"""
|
"""
|
||||||
from .export import ( # noqa: WPS433
|
|
||||||
COL_FIRST, COL_LAST, FIRST_DATA_ROW, HEADER_BG, HEADER_ROW, PALLET_BG,
|
|
||||||
TITLE_ROW, WIDTHS_PX, build_table, sheet_title,
|
|
||||||
)
|
|
||||||
|
|
||||||
writer, spreadsheet_id, skip = _sheet_target(store)
|
writer, spreadsheet_id, skip = _sheet_target(store)
|
||||||
if skip:
|
if skip:
|
||||||
return skip
|
return skip
|
||||||
@@ -309,28 +344,356 @@ def _push_to_google_sheet(store: Any, ship_date: str) -> dict[str, Any]:
|
|||||||
if not shipments:
|
if not shipments:
|
||||||
return {"ok": False, "skipped": True, "reason": "해당 출고일의 출고 묶음 없음"}
|
return {"ok": False, "skipped": True, "reason": "해당 출고일의 출고 묶음 없음"}
|
||||||
|
|
||||||
table = build_table(ship_date, shipments)
|
|
||||||
try:
|
try:
|
||||||
res = writer.write_table(
|
res = _in_sheet(writer, lambda: _write_full_sheet(writer, spreadsheet_id, ship_date, shipments))
|
||||||
spreadsheet_id=spreadsheet_id,
|
|
||||||
title=sheet_title(ship_date),
|
|
||||||
cells=table["cells"],
|
|
||||||
merges=table["merges"],
|
|
||||||
header_row=HEADER_ROW,
|
|
||||||
first_data_row=FIRST_DATA_ROW,
|
|
||||||
last_row=table["last_row"],
|
|
||||||
first_col=COL_FIRST,
|
|
||||||
last_col=COL_LAST,
|
|
||||||
title_row=TITLE_ROW,
|
|
||||||
widths=WIDTHS_PX,
|
|
||||||
header_bg=HEADER_BG,
|
|
||||||
row_highlights=[(r1, r2, PALLET_BG) for (r1, r2) in table["pallet_ranges"]],
|
|
||||||
)
|
|
||||||
except Exception as exc: # noqa: BLE001 - 시트 기록 실패는 경고로만 알린다
|
except Exception as exc: # noqa: BLE001 - 시트 기록 실패는 경고로만 알린다
|
||||||
return {"ok": False, "skipped": False, "reason": f"{type(exc).__name__}: {exc}"}
|
return {"ok": False, "skipped": False, "reason": f"{type(exc).__name__}: {exc}"}
|
||||||
return {"ok": True, "skipped": False, **res}
|
return {"ok": True, "skipped": False, **res}
|
||||||
|
|
||||||
|
|
||||||
|
def _write_full_sheet(
|
||||||
|
writer: Any, spreadsheet_id: str, ship_date: str, shipments: list[dict[str, Any]]
|
||||||
|
) -> dict[str, Any]:
|
||||||
|
"""출고일 시트를 양식(1~5행)부터 통째로 다시 쓴다. 실패는 예외로 알린다."""
|
||||||
|
from .export import ( # noqa: WPS433
|
||||||
|
COL_FIRST, COL_LAST, FIRST_DATA_ROW, HEADER_BG, HEADER_ROW, PALLET_BG,
|
||||||
|
TITLE_ROW, WIDTHS_PX, build_table, sheet_title,
|
||||||
|
)
|
||||||
|
|
||||||
|
table = build_table(ship_date, shipments)
|
||||||
|
res = writer.write_table(
|
||||||
|
spreadsheet_id=spreadsheet_id,
|
||||||
|
title=sheet_title(ship_date),
|
||||||
|
cells=table["cells"],
|
||||||
|
merges=table["merges"],
|
||||||
|
header_row=HEADER_ROW,
|
||||||
|
first_data_row=FIRST_DATA_ROW,
|
||||||
|
last_row=table["last_row"],
|
||||||
|
first_col=COL_FIRST,
|
||||||
|
last_col=COL_LAST,
|
||||||
|
title_row=TITLE_ROW,
|
||||||
|
widths=WIDTHS_PX,
|
||||||
|
header_bg=HEADER_BG,
|
||||||
|
row_highlights=[(r1, r2, PALLET_BG) for (r1, r2) in table["pallet_ranges"]],
|
||||||
|
)
|
||||||
|
return {**res, "first_row": FIRST_DATA_ROW, "last_row": table["last_row"]}
|
||||||
|
|
||||||
|
|
||||||
|
# ════════════════════════════════════════════════════════════
|
||||||
|
# 밀크런 출고리스트 직접 작성 — 상자 계산 없이 팝업에서 입력한 센터 1곳을
|
||||||
|
# 출고리스트 문서(드라이브 엑셀 파일)의 출고일 시트(YYYYMMDD(요일)) 맨 아래에 덧붙인다. cupang_db 에는 저장하지 않는다.
|
||||||
|
# ════════════════════════════════════════════════════════════
|
||||||
|
OUTBOUND_SHEET_METHODS: tuple[str, ...] = ("파렛트", "택배")
|
||||||
|
_SHEET_CENTERS_TTL_SECONDS = 600
|
||||||
|
_sheet_centers_cache: dict[str, Any] = {"at": 0.0, "sheet": "", "names": []}
|
||||||
|
# 팝업이 쓰는 문서 — 항상 드라이브 엑셀(.xlsx) 파일. CUPANG_SHEET_ID(분배 확정 동기화)와 따로 둔다:
|
||||||
|
# 서버의 CUPANG_SHEET_ID 가 구글 시트 문서를 가리켜도 팝업은 엑셀 파일에만 쓴다(구글 시트로 대신 쓰지 않음).
|
||||||
|
DEFAULT_OUTBOUND_XLSX_ID = "1J74op7lBZOgE27p4R28I3RWsv0EtXdii"
|
||||||
|
|
||||||
|
|
||||||
|
def _outbound_target() -> tuple[Any, str, dict[str, Any] | None]:
|
||||||
|
"""(drive_xlsx writer, 엑셀 파일 id, skip 사유). 드라이브 인증이 없거나 .xlsx 가 아니면 skip."""
|
||||||
|
import os # noqa: WPS433
|
||||||
|
|
||||||
|
from app.integrations import drive_xlsx # noqa: WPS433
|
||||||
|
|
||||||
|
file_id = (os.getenv("CUPANG_OUTBOUND_XLSX_ID") or "").strip() or DEFAULT_OUTBOUND_XLSX_ID
|
||||||
|
writer = drive_xlsx.get_writer()
|
||||||
|
if not writer.enabled:
|
||||||
|
return None, "", {"ok": False, "skipped": True, "reason": writer.reason}
|
||||||
|
try:
|
||||||
|
kind = writer.file_kind(file_id)
|
||||||
|
except Exception as exc: # noqa: BLE001 - 사유만(비밀값 없음)
|
||||||
|
return None, "", {"ok": False, "skipped": True, "reason": str(exc) or type(exc).__name__}
|
||||||
|
if kind != "xlsx":
|
||||||
|
return None, "", {"ok": False, "skipped": True, "reason": f"출고리스트 파일이 엑셀(.xlsx)이 아닙니다({kind})"}
|
||||||
|
return writer, file_id, None
|
||||||
|
|
||||||
|
|
||||||
|
def _sheet_text(value: Any, *, label: str, max_len: int, required: bool = True) -> str:
|
||||||
|
text = str(value or "").strip()
|
||||||
|
if required and not text:
|
||||||
|
raise HTTPException(status_code=400, detail=f"{label}을(를) 입력해 주세요.")
|
||||||
|
if len(text) > max_len:
|
||||||
|
raise HTTPException(status_code=400, detail=f"{label}은(는) {max_len}자까지 입력할 수 있습니다.")
|
||||||
|
# USER_ENTERED 로 쓰므로 '=' 로 시작하면 수식이 된다 — 글자 그대로 남긴다.
|
||||||
|
return "'" + text if text.startswith("=") else text
|
||||||
|
|
||||||
|
|
||||||
|
def _sheet_date(value: Any, *, label: str) -> str:
|
||||||
|
try:
|
||||||
|
return _date.fromisoformat(str(value or "").strip()).isoformat()
|
||||||
|
except ValueError:
|
||||||
|
raise HTTPException(status_code=400, detail=f"{label}을(를) 선택해 주세요.") from None
|
||||||
|
|
||||||
|
|
||||||
|
def _clean_outbound_entry(payload: dict[str, Any]) -> dict[str, Any]:
|
||||||
|
"""팝업 입력 → export.build_block 이 읽는 출고 묶음 모양."""
|
||||||
|
method = str(payload.get("ship_method") or "").strip()
|
||||||
|
if method not in OUTBOUND_SHEET_METHODS:
|
||||||
|
raise HTTPException(status_code=400, detail="출고방식은 파렛트 또는 택배 중에서 골라 주세요.")
|
||||||
|
|
||||||
|
raw_lines = payload.get("lines")
|
||||||
|
if not isinstance(raw_lines, list) or not raw_lines:
|
||||||
|
raise HTTPException(status_code=400, detail="제품을 1개 이상 추가해 주세요.")
|
||||||
|
if len(raw_lines) > 100:
|
||||||
|
raise HTTPException(status_code=400, detail="제품은 한 번에 100줄까지 입력할 수 있습니다.")
|
||||||
|
lines = []
|
||||||
|
for i, ln in enumerate(raw_lines, start=1):
|
||||||
|
if not isinstance(ln, dict):
|
||||||
|
raise HTTPException(status_code=400, detail=f"{i}번째 제품 정보를 확인해 주세요.")
|
||||||
|
try:
|
||||||
|
qty = int(str(ln.get("quantity") or "").replace(",", "").strip())
|
||||||
|
except ValueError:
|
||||||
|
qty = 0
|
||||||
|
if not 1 <= qty <= 1_000_000:
|
||||||
|
raise HTTPException(status_code=400, detail=f"{i}번째 제품의 수량을 확인해 주세요.")
|
||||||
|
lines.append({
|
||||||
|
"product_code": _sheet_text(ln.get("code"), label=f"{i}번째 제품코드", max_len=60),
|
||||||
|
"product_name_snapshot": _sheet_text(ln.get("name"), label=f"{i}번째 제품명", max_len=200),
|
||||||
|
"quantity": qty,
|
||||||
|
})
|
||||||
|
|
||||||
|
return {
|
||||||
|
"document_date": _sheet_date(payload.get("document_date"), label="작성일"),
|
||||||
|
"ship_date": _sheet_date(payload.get("ship_date"), label="출고일"),
|
||||||
|
"center_arrival_date": _sheet_date(payload.get("center_arrival_date"), label="센터입고일"),
|
||||||
|
"center_name_snapshot": _sheet_text(payload.get("center"), label="입고센터", max_len=60),
|
||||||
|
"ship_method": method,
|
||||||
|
"outbound_summary": _sheet_text(payload.get("outbound"), label="출고", max_len=100, required=False),
|
||||||
|
"worker": _sheet_text(payload.get("worker") or OUTBOUND_WORKER, label="작업자", max_len=30),
|
||||||
|
"lines": lines,
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
def _sheet_centers(writer: Any, spreadsheet_id: str) -> list[str]:
|
||||||
|
"""출고리스트 문서의 모든 시트 F열(입고센터, 6행부터)에 적힌 센터 이름. 10분 캐시."""
|
||||||
|
import time # noqa: WPS433
|
||||||
|
|
||||||
|
from app.integrations.google_sheets import a1_sheet # noqa: WPS433
|
||||||
|
|
||||||
|
from .export import FIRST_DATA_ROW # noqa: WPS433
|
||||||
|
|
||||||
|
cache = _sheet_centers_cache
|
||||||
|
if cache["sheet"] == spreadsheet_id and time.monotonic() - cache["at"] < _SHEET_CENTERS_TTL_SECONDS:
|
||||||
|
return list(cache["names"])
|
||||||
|
with writer.lock: # 엑셀 파일이면 한 번만 내려받는다
|
||||||
|
titles = writer.sheet_titles(spreadsheet_id=spreadsheet_id)
|
||||||
|
columns = writer.read_ranges(
|
||||||
|
spreadsheet_id=spreadsheet_id,
|
||||||
|
ranges=[f"{a1_sheet(t)}!F{FIRST_DATA_ROW}:F" for t in titles],
|
||||||
|
)
|
||||||
|
names = sorted({
|
||||||
|
str(row[0]).strip() for rows in columns for row in rows if row and str(row[0]).strip()
|
||||||
|
})
|
||||||
|
cache.update(at=time.monotonic(), sheet=spreadsheet_id, names=names)
|
||||||
|
return list(names)
|
||||||
|
|
||||||
|
|
||||||
|
def _append_outbound_entry(writer: Any, spreadsheet_id: str, entry: dict[str, Any]) -> dict[str, Any]:
|
||||||
|
"""출고일 시트 맨 아래에 덧붙인다. 시트가 없거나 양식(5행 머리글)이 없으면 양식째 만든다."""
|
||||||
|
from app.integrations.google_sheets import a1_sheet, col_letter # noqa: WPS433
|
||||||
|
|
||||||
|
from .export import ( # noqa: WPS433
|
||||||
|
COL_FIRST, COL_LAST, FIRST_DATA_ROW, HEADER_ROW, PALLET_BG, build_block, sheet_title,
|
||||||
|
)
|
||||||
|
|
||||||
|
title = sheet_title(entry["ship_date"])
|
||||||
|
rows: list[list[Any]] = []
|
||||||
|
if title in writer.sheet_titles(spreadsheet_id=spreadsheet_id):
|
||||||
|
rows = writer.read_ranges(
|
||||||
|
spreadsheet_id=spreadsheet_id,
|
||||||
|
ranges=[f"{a1_sheet(title)}!A1:{col_letter(COL_LAST)}"],
|
||||||
|
)[0]
|
||||||
|
last_row = max(
|
||||||
|
(i for i, row in enumerate(rows, start=1) if any(str(v).strip() for v in row)), default=0
|
||||||
|
)
|
||||||
|
if last_row < HEADER_ROW:
|
||||||
|
return _write_full_sheet(writer, spreadsheet_id, entry["ship_date"], [entry])
|
||||||
|
|
||||||
|
# 순번(B열)은 시트에 이미 있는 가장 큰 번호 다음부터
|
||||||
|
last_seq = 0
|
||||||
|
for row in rows[FIRST_DATA_ROW - 1:]:
|
||||||
|
text = str(row[1]).strip() if len(row) > 1 else ""
|
||||||
|
if text.isdigit():
|
||||||
|
last_seq = max(last_seq, int(text))
|
||||||
|
block = build_block(entry, start_row=last_row + 1, start_seq=last_seq)
|
||||||
|
return writer.append_block(
|
||||||
|
spreadsheet_id=spreadsheet_id,
|
||||||
|
title=title,
|
||||||
|
cells=block["cells"],
|
||||||
|
merges=block["merges"],
|
||||||
|
first_row=block["first_row"],
|
||||||
|
last_row=block["last_row"],
|
||||||
|
first_col=COL_FIRST,
|
||||||
|
last_col=COL_LAST,
|
||||||
|
highlight=PALLET_BG if block["is_pallet"] else "",
|
||||||
|
)
|
||||||
|
|
||||||
|
|
||||||
|
@router.get("/api/outbound-sheet/centers")
|
||||||
|
def outbound_sheet_centers(
|
||||||
|
request: Request, _: dict[str, Any] = Depends(_require_user)
|
||||||
|
) -> JSONResponse:
|
||||||
|
"""입고센터 후보 — 출고리스트 문서에 적힌 센터 + 설정에 등록된 센터."""
|
||||||
|
store = _store(request)
|
||||||
|
names = {c["name"] for c in store.list_centers()} if store else set()
|
||||||
|
reason = ""
|
||||||
|
writer, spreadsheet_id, skip = _outbound_target()
|
||||||
|
if skip:
|
||||||
|
reason = str(skip.get("reason") or "")
|
||||||
|
else:
|
||||||
|
try:
|
||||||
|
names.update(_sheet_centers(writer, spreadsheet_id))
|
||||||
|
except Exception as exc: # noqa: BLE001 - 목록은 등록 센터만으로도 쓸 수 있다
|
||||||
|
reason = f"출고리스트 파일을 읽지 못했습니다({str(exc) or type(exc).__name__})"
|
||||||
|
return JSONResponse({"centers": sorted(names), "reason": reason})
|
||||||
|
|
||||||
|
|
||||||
|
_OUTBOUND_MAX_CENTERS = 20
|
||||||
|
|
||||||
|
|
||||||
|
def _clean_outbound_entries(payload: dict[str, Any]) -> list[dict[str, Any]]:
|
||||||
|
"""팝업 입력 → 입고센터마다 출고 묶음 1건.
|
||||||
|
|
||||||
|
공통(작성일·출고일·센터입고일·작업자) + `centers: [{center, ship_method, outbound, lines}]`.
|
||||||
|
`centers` 가 없으면 payload 자체를 센터 1곳으로 본다."""
|
||||||
|
raw = payload.get("centers")
|
||||||
|
if raw is None:
|
||||||
|
return [_clean_outbound_entry(payload)]
|
||||||
|
if not isinstance(raw, list) or not raw:
|
||||||
|
raise HTTPException(status_code=400, detail="입고센터를 1곳 이상 추가해 주세요.")
|
||||||
|
if len(raw) > _OUTBOUND_MAX_CENTERS:
|
||||||
|
raise HTTPException(status_code=400, detail=f"입고센터는 한 번에 {_OUTBOUND_MAX_CENTERS}곳까지 입력할 수 있습니다.")
|
||||||
|
common = {k: payload.get(k) for k in ("document_date", "ship_date", "center_arrival_date", "worker")}
|
||||||
|
entries = []
|
||||||
|
for i, c in enumerate(raw, start=1):
|
||||||
|
if not isinstance(c, dict):
|
||||||
|
raise HTTPException(status_code=400, detail=f"{i}번째 입고센터 정보를 확인해 주세요.")
|
||||||
|
try:
|
||||||
|
entries.append(_clean_outbound_entry({**c, **common}))
|
||||||
|
except HTTPException as exc:
|
||||||
|
prefix = f"{i}번째 입고센터: " if len(raw) > 1 else ""
|
||||||
|
raise HTTPException(status_code=exc.status_code, detail=prefix + str(exc.detail)) from None
|
||||||
|
return entries
|
||||||
|
|
||||||
|
|
||||||
|
def _run_outbound_write(
|
||||||
|
writer: Any, file_id: str, entries: list[dict[str, Any]], report: Any
|
||||||
|
) -> dict[str, Any]:
|
||||||
|
"""센터들을 차례로 출고일 시트 아래에 덧붙인다(엑셀은 내려받기·올리기 1번씩).
|
||||||
|
|
||||||
|
report(진행률, 다음 단계 진행률, 단계 이름) 로 진행 상황을 알린다. 실패는 HTTPException(502)."""
|
||||||
|
from app.integrations.drive_xlsx import XlsxChangedError # noqa: WPS433
|
||||||
|
from app.integrations.google_drive import GoogleDriveError # noqa: WPS433
|
||||||
|
|
||||||
|
ship_date = entries[0]["ship_date"]
|
||||||
|
n = len(entries)
|
||||||
|
|
||||||
|
def run() -> list[dict[str, Any]]:
|
||||||
|
report(5, 40, "출고리스트 엑셀 내려받는 중")
|
||||||
|
writer.sheet_titles(spreadsheet_id=file_id) # 이 덩어리에서 한 번 내려받는다
|
||||||
|
done = []
|
||||||
|
for i, entry in enumerate(entries):
|
||||||
|
report(40 + 40 * i // n, 40 + 40 * (i + 1) // n,
|
||||||
|
f"{entry['center_name_snapshot']} 추가 중 ({i + 1}/{n})")
|
||||||
|
done.append(_append_outbound_entry(writer, file_id, entry))
|
||||||
|
report(80, 100, "출고리스트 엑셀 올리는 중")
|
||||||
|
return done
|
||||||
|
|
||||||
|
try:
|
||||||
|
# 시트 끝 위치를 읽고 쓰는 사이에 다른 요청이 끼어들지 않게 한 덩어리로
|
||||||
|
results = _in_sheet(writer, run)
|
||||||
|
except Exception as exc: # noqa: BLE001 - 사유만 남긴다(비밀값 미출력)
|
||||||
|
_log_sheet("manual-append", ship_date, {"ok": False, "reason": type(exc).__name__})
|
||||||
|
if isinstance(exc, XlsxChangedError):
|
||||||
|
why = "다른 사람이 파일을 고치는 중입니다"
|
||||||
|
elif isinstance(exc, GoogleDriveError):
|
||||||
|
why = str(exc)
|
||||||
|
else:
|
||||||
|
why = type(exc).__name__
|
||||||
|
raise HTTPException(
|
||||||
|
status_code=502, detail=f"출고리스트 파일에 기록하지 못했습니다({why}). 잠시 후 다시 시도해 주세요."
|
||||||
|
) from exc
|
||||||
|
|
||||||
|
first, last = results[0], results[-1]
|
||||||
|
_log_sheet("manual-append", ship_date,
|
||||||
|
{"ok": True, "action": f"xlsx {file_id} centers {n} rows {first.get('first_row')}-{last.get('last_row')}"})
|
||||||
|
if _sheet_centers_cache["sheet"] == file_id:
|
||||||
|
_sheet_centers_cache["names"] = sorted(
|
||||||
|
{*_sheet_centers_cache["names"], *(e["center_name_snapshot"] for e in entries)})
|
||||||
|
return {
|
||||||
|
"ok": True,
|
||||||
|
"title": last.get("title"),
|
||||||
|
"url": last.get("url"),
|
||||||
|
"first_row": first.get("first_row"),
|
||||||
|
"last_row": last.get("last_row"),
|
||||||
|
"line_count": sum(len(e["lines"]) for e in entries),
|
||||||
|
"centers": [
|
||||||
|
{"center": e["center_name_snapshot"], "first_row": r.get("first_row"), "last_row": r.get("last_row"),
|
||||||
|
"line_count": len(e["lines"])}
|
||||||
|
for e, r in zip(entries, results)
|
||||||
|
],
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
@router.post("/api/outbound-sheet")
|
||||||
|
def outbound_sheet_write(
|
||||||
|
request: Request,
|
||||||
|
payload: dict[str, Any] = Body(...),
|
||||||
|
stream: bool = False,
|
||||||
|
_: dict[str, Any] = Depends(_require_user),
|
||||||
|
) -> Any:
|
||||||
|
"""출고리스트 엑셀에 센터들을 덧붙인다.
|
||||||
|
|
||||||
|
`?stream=1` 이면 한 줄에 JSON 하나씩(NDJSON) 진행 상황을 흘려보낸다 —
|
||||||
|
`{"progress", "until", "step"}` … 마지막에 `{"done": true, ...결과}` 또는 `{"error": 사유}`.
|
||||||
|
입력 오류(400)·설정 없음(503)은 흘려보내기 전에 보통 JSON 오류로 돌려준다."""
|
||||||
|
entries = _clean_outbound_entries(payload)
|
||||||
|
writer, file_id, skip = _outbound_target()
|
||||||
|
if skip:
|
||||||
|
_log_sheet("manual-append", entries[0]["ship_date"], skip)
|
||||||
|
raise HTTPException(
|
||||||
|
status_code=503, detail=f"출고리스트 엑셀 파일에 쓸 수 없습니다: {skip.get('reason') or '설정 확인 필요'}"
|
||||||
|
)
|
||||||
|
if not stream:
|
||||||
|
return JSONResponse(_run_outbound_write(writer, file_id, entries, lambda *_a: None))
|
||||||
|
|
||||||
|
import queue # noqa: WPS433
|
||||||
|
import threading # noqa: WPS433
|
||||||
|
|
||||||
|
from fastapi.responses import StreamingResponse # noqa: WPS433
|
||||||
|
|
||||||
|
events: Any = queue.Queue()
|
||||||
|
|
||||||
|
def work() -> None:
|
||||||
|
# 잠금(writer.lock)은 잡은 스레드에서 풀어야 하므로 쓰기 전체를 스레드 하나에서
|
||||||
|
try:
|
||||||
|
res = _run_outbound_write(
|
||||||
|
writer, file_id, entries,
|
||||||
|
lambda p, until, step: events.put({"progress": p, "until": until, "step": step}),
|
||||||
|
)
|
||||||
|
events.put({"progress": 100, "until": 100, "step": "완료", "done": True, **res})
|
||||||
|
except HTTPException as exc:
|
||||||
|
events.put({"error": str(exc.detail)})
|
||||||
|
except Exception as exc: # noqa: BLE001
|
||||||
|
events.put({"error": f"출고리스트 파일에 기록하지 못했습니다({type(exc).__name__})."})
|
||||||
|
finally:
|
||||||
|
events.put(None)
|
||||||
|
|
||||||
|
threading.Thread(target=work, name="cupang-outbound-write", daemon=True).start()
|
||||||
|
|
||||||
|
def lines() -> Any:
|
||||||
|
while True:
|
||||||
|
item = events.get()
|
||||||
|
if item is None:
|
||||||
|
return
|
||||||
|
yield json.dumps(item, ensure_ascii=False) + "\n"
|
||||||
|
|
||||||
|
return StreamingResponse(lines(), media_type="application/x-ndjson",
|
||||||
|
headers={"Cache-Control": "no-cache", "X-Accel-Buffering": "no"})
|
||||||
|
|
||||||
|
|
||||||
@router.get("/export.xlsx")
|
@router.get("/export.xlsx")
|
||||||
def export_shipments_xlsx(request: Request, date: str = "") -> Any:
|
def export_shipments_xlsx(request: Request, date: str = "") -> Any:
|
||||||
"""출고일 기준 출고리스트 엑셀 다운로드. 시트명 = YYYYMMDD."""
|
"""출고일 기준 출고리스트 엑셀 다운로드. 시트명 = YYYYMMDD."""
|
||||||
@@ -411,6 +774,19 @@ def detail(request: Request, shipment_id: int) -> HTMLResponse:
|
|||||||
]
|
]
|
||||||
calc = _compute_boxes(store, items)
|
calc = _compute_boxes(store, items)
|
||||||
total_qty = sum(it["quantity"] for it in items)
|
total_qty = sum(it["quantity"] for it in items)
|
||||||
|
box_list = _expand_box_list(ship, calc, items)
|
||||||
|
box_weight = _attach_box_weights(store, box_list)
|
||||||
|
# 상자 목록 합계 행 — 수량 합계와 무게 합계(kg, 소수 첫째 자리)
|
||||||
|
box_qty_total = sum(int(it.get("quantity") or 0) for b in box_list for it in (b.get("items") or []))
|
||||||
|
box_weight_total = None
|
||||||
|
box_weight_partial = False
|
||||||
|
if box_weight:
|
||||||
|
for b in box_list:
|
||||||
|
b["weight_kg"] = _g_to_kg(b.get("weight_g"))
|
||||||
|
if b.get("weight_g") is not None:
|
||||||
|
box_weight_total = (box_weight_total or 0) + int(b["weight_g"])
|
||||||
|
if b.get("weight_missing"):
|
||||||
|
box_weight_partial = True
|
||||||
|
|
||||||
return render_template(
|
return render_template(
|
||||||
request,
|
request,
|
||||||
@@ -424,7 +800,12 @@ def detail(request: Request, shipment_id: int) -> HTMLResponse:
|
|||||||
"shipment": ship,
|
"shipment": ship,
|
||||||
"items": items,
|
"items": items,
|
||||||
"calc": calc,
|
"calc": calc,
|
||||||
"box_list": _expand_box_list(ship, calc, items),
|
"box_list": box_list,
|
||||||
|
# 상자별 무게 합계(g) 칸 — 포장무게(마이그레이션 007) 가 있을 때만
|
||||||
|
"box_weight": box_weight,
|
||||||
|
"box_qty_total": box_qty_total,
|
||||||
|
"box_weight_total_kg": _g_to_kg(box_weight_total),
|
||||||
|
"box_weight_partial": box_weight_partial,
|
||||||
"total_qty": total_qty,
|
"total_qty": total_qty,
|
||||||
},
|
},
|
||||||
)
|
)
|
||||||
@@ -432,7 +813,7 @@ def detail(request: Request, shipment_id: int) -> HTMLResponse:
|
|||||||
|
|
||||||
@router.get("/{shipment_id:int}/boxes.xlsx")
|
@router.get("/{shipment_id:int}/boxes.xlsx")
|
||||||
def export_box_list_xlsx(request: Request, shipment_id: int) -> Any:
|
def export_box_list_xlsx(request: Request, shipment_id: int) -> Any:
|
||||||
"""상자 목록(상자번호·제품명·제품코드·수량) 엑셀 다운로드."""
|
"""상자 목록(상자번호·제품명·제품코드·수량·무게) 엑셀 다운로드."""
|
||||||
from io import BytesIO # noqa: WPS433
|
from io import BytesIO # noqa: WPS433
|
||||||
|
|
||||||
from fastapi.responses import StreamingResponse # noqa: WPS433
|
from fastapi.responses import StreamingResponse # noqa: WPS433
|
||||||
@@ -457,8 +838,9 @@ def export_box_list_xlsx(request: Request, shipment_id: int) -> Any:
|
|||||||
for ln in (ship.get("lines") or [])
|
for ln in (ship.get("lines") or [])
|
||||||
]
|
]
|
||||||
box_list = _expand_box_list(ship, _compute_boxes(store, items), items)
|
box_list = _expand_box_list(ship, _compute_boxes(store, items), items)
|
||||||
|
with_weight = _attach_box_weights(store, box_list)
|
||||||
|
|
||||||
wb = build_box_list_workbook(ship, box_list)
|
wb = build_box_list_workbook(ship, box_list, with_weight=with_weight)
|
||||||
buf = BytesIO()
|
buf = BytesIO()
|
||||||
wb.save(buf)
|
wb.save(buf)
|
||||||
buf.seek(0)
|
buf.seek(0)
|
||||||
@@ -1185,6 +1567,44 @@ def _compute_boxes(store: Any, raw_items: list[Any]) -> dict[str, Any]:
|
|||||||
}
|
}
|
||||||
|
|
||||||
|
|
||||||
|
def _g_to_kg(grams: Any) -> str | None:
|
||||||
|
"""g → kg 표시 글자 — 소수 둘째 자리에서 반올림(사사오입)해 첫째 자리까지. 예: 1,250g → "1.3"."""
|
||||||
|
if grams is None:
|
||||||
|
return None
|
||||||
|
kg = (Decimal(int(grams)) / 1000).quantize(Decimal("0.1"), rounding=ROUND_HALF_UP)
|
||||||
|
return f"{kg:,.1f}"
|
||||||
|
|
||||||
|
|
||||||
|
def _attach_box_weights(store: Any, box_list: list[dict[str, Any]]) -> bool:
|
||||||
|
"""상자마다 무게 합계(g) — 상자에 든 제품마다 수량 × 포장무게(설정(제품명)의 지금 값, cupang_products.weight_g).
|
||||||
|
|
||||||
|
상자에 넣는 값: weight_g = 아는 무게의 합(상자 안 제품 무게가 하나도 없으면 None),
|
||||||
|
weight_missing = 무게가 없는 제품코드 목록(일부만 없으면 합계는 그 제품을 뺀 값).
|
||||||
|
포장무게 칸(마이그레이션 007)이 없으면 아무것도 넣지 않고 False.
|
||||||
|
"""
|
||||||
|
if not store.weight_enabled():
|
||||||
|
return False
|
||||||
|
weights = {
|
||||||
|
str(p.get("product_code") or "").strip(): p.get("weight_g")
|
||||||
|
for p in store.list_products(include_inactive=True)
|
||||||
|
}
|
||||||
|
for box in box_list:
|
||||||
|
contents = box.get("items") or []
|
||||||
|
total, missing = 0, []
|
||||||
|
for it in contents:
|
||||||
|
code = str(it.get("product_code") or "").strip()
|
||||||
|
w = weights.get(code)
|
||||||
|
if w is None:
|
||||||
|
if code not in missing:
|
||||||
|
missing.append(code)
|
||||||
|
continue
|
||||||
|
total += int(w) * int(it.get("quantity") or 0)
|
||||||
|
known = any(weights.get(str(it.get("product_code") or "").strip()) is not None for it in contents)
|
||||||
|
box["weight_g"] = total if known else None
|
||||||
|
box["weight_missing"] = missing
|
||||||
|
return True
|
||||||
|
|
||||||
|
|
||||||
def _expand_box_list(
|
def _expand_box_list(
|
||||||
shipment: dict[str, Any], calc: dict[str, Any], items: list[dict[str, Any]]
|
shipment: dict[str, Any], calc: dict[str, Any], items: list[dict[str, Any]]
|
||||||
) -> list[dict[str, Any]]:
|
) -> list[dict[str, Any]]:
|
||||||
@@ -1349,6 +1769,8 @@ def products_page(request: Request) -> HTMLResponse:
|
|||||||
"page_subtitle": "왼쪽 itemcode_db 목록에서 선택해 등록하면 폼 드롭다운에 노출됩니다.",
|
"page_subtitle": "왼쪽 itemcode_db 목록에서 선택해 등록하면 폼 드롭다운에 노출됩니다.",
|
||||||
"products": store.list_products(include_inactive=True),
|
"products": store.list_products(include_inactive=True),
|
||||||
"registered_codes": [p["product_code"] for p in store.list_products(include_inactive=True)],
|
"registered_codes": [p["product_code"] for p in store.list_products(include_inactive=True)],
|
||||||
|
# 포장무게(g) — 마이그레이션 007 적용 전이면 무게 칸을 숨긴다
|
||||||
|
"weight_enabled": store.weight_enabled(),
|
||||||
"search_enabled": bool(reader and reader.enabled),
|
"search_enabled": bool(reader and reader.enabled),
|
||||||
"search_reason": (reader.reason if reader else ""),
|
"search_reason": (reader.reason if reader else ""),
|
||||||
},
|
},
|
||||||
@@ -1412,6 +1834,7 @@ def product_upsert(
|
|||||||
product_code: str = Form(...),
|
product_code: str = Form(...),
|
||||||
product_name: str = Form(...),
|
product_name: str = Form(...),
|
||||||
coupang_item_code: str = Form(""),
|
coupang_item_code: str = Form(""),
|
||||||
|
weight_g: str = Form(""),
|
||||||
sort_order: int = Form(0),
|
sort_order: int = Form(0),
|
||||||
user: dict[str, Any] = Depends(_require_user),
|
user: dict[str, Any] = Depends(_require_user),
|
||||||
) -> RedirectResponse:
|
) -> RedirectResponse:
|
||||||
@@ -1422,9 +1845,10 @@ def product_upsert(
|
|||||||
store.upsert_product(
|
store.upsert_product(
|
||||||
product_code=product_code,
|
product_code=product_code,
|
||||||
product_name=product_name,
|
product_name=product_name,
|
||||||
# 빈 값은 "미입력" 으로 보고 기존 쿠팡상품코드를 유지한다.
|
# 빈 값은 "미입력" 으로 보고 기존 쿠팡상품코드·포장무게를 유지한다.
|
||||||
coupang_item_code=(coupang_item_code.strip() or None),
|
coupang_item_code=(coupang_item_code.strip() or None),
|
||||||
sort_order=sort_order,
|
sort_order=sort_order,
|
||||||
|
weight_g=parse_weight_g(weight_g),
|
||||||
)
|
)
|
||||||
except ValueError as exc:
|
except ValueError as exc:
|
||||||
raise HTTPException(status_code=400, detail=str(exc))
|
raise HTTPException(status_code=400, detail=str(exc))
|
||||||
@@ -1457,7 +1881,8 @@ def product_edit(
|
|||||||
payload: dict[str, Any] = Body(...),
|
payload: dict[str, Any] = Body(...),
|
||||||
user: dict[str, Any] = Depends(_require_user),
|
user: dict[str, Any] = Depends(_require_user),
|
||||||
) -> JSONResponse:
|
) -> JSONResponse:
|
||||||
"""등록된 제품 수정. body: {product_name, product_code, coupang_item_code}."""
|
"""등록된 제품 수정. body: {product_name, product_code, coupang_item_code, weight_g?}.
|
||||||
|
weight_g 키가 있으면 저장(빈 값 = 지움), 없으면 무게는 그대로."""
|
||||||
store = _store(request)
|
store = _store(request)
|
||||||
if store is None:
|
if store is None:
|
||||||
raise HTTPException(status_code=503, detail="cupang_db 미설정")
|
raise HTTPException(status_code=503, detail="cupang_db 미설정")
|
||||||
@@ -1467,6 +1892,7 @@ def product_edit(
|
|||||||
product_name=str(payload.get("product_name") or ""),
|
product_name=str(payload.get("product_name") or ""),
|
||||||
product_code=str(payload.get("product_code") or ""),
|
product_code=str(payload.get("product_code") or ""),
|
||||||
coupang_item_code=str(payload.get("coupang_item_code") or ""),
|
coupang_item_code=str(payload.get("coupang_item_code") or ""),
|
||||||
|
weight_g=(parse_weight_g(payload.get("weight_g")) if "weight_g" in payload else ...),
|
||||||
)
|
)
|
||||||
except KeyError:
|
except KeyError:
|
||||||
raise HTTPException(status_code=404, detail="제품을 찾을 수 없습니다.")
|
raise HTTPException(status_code=404, detail="제품을 찾을 수 없습니다.")
|
||||||
|
|||||||
@@ -94,3 +94,32 @@ def compute_boxes(quantity: int, units_per_box: int | None) -> dict[str, Any]:
|
|||||||
"remainder_units": qty % upb,
|
"remainder_units": qty % upb,
|
||||||
"required_boxes": math.ceil(qty / upb),
|
"required_boxes": math.ceil(qty / upb),
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
||||||
|
# 제품 포장무게(g) — cupang_products.weight_g (마이그레이션 007). 0 ~ 1,000,000g, 정수.
|
||||||
|
WEIGHT_MAX_G = 1_000_000
|
||||||
|
|
||||||
|
|
||||||
|
def parse_weight_g(value: Any) -> int | None:
|
||||||
|
"""포장무게 입력 → 그램 정수. 빈 값은 None(미입력).
|
||||||
|
|
||||||
|
"1,070" · " 1,070 " · "1070g" · "1070.0" 처럼 쉼표·공백·g 단위가 붙어도 읽는다.
|
||||||
|
숫자가 아니거나 음수·소수(0.5g 등)·범위 밖이면 ValueError.
|
||||||
|
"""
|
||||||
|
if value is None:
|
||||||
|
return None
|
||||||
|
s = str(value).strip().replace(",", "").replace(" ", "")
|
||||||
|
if s.lower().endswith("g"):
|
||||||
|
s = s[:-1]
|
||||||
|
if not s:
|
||||||
|
return None
|
||||||
|
try:
|
||||||
|
f = float(s)
|
||||||
|
except ValueError:
|
||||||
|
raise ValueError(f"포장무게는 숫자(g)로 입력하세요: {value}")
|
||||||
|
if f != f or f < 0 or f != int(f):
|
||||||
|
raise ValueError(f"포장무게는 0 이상의 정수(g)로 입력하세요: {value}")
|
||||||
|
v = int(f)
|
||||||
|
if v > WEIGHT_MAX_G:
|
||||||
|
raise ValueError(f"포장무게가 너무 큽니다(최대 {WEIGHT_MAX_G:,}g): {value}")
|
||||||
|
return v
|
||||||
|
|||||||
@@ -1,6 +1,6 @@
|
|||||||
{% extends "erp_base.html" %}
|
{% extends "erp_base.html" %}
|
||||||
|
|
||||||
{% block head_extra %}<link rel="stylesheet" href="/static/cupang.css?v=20260904f" />{% endblock %}
|
{% block head_extra %}<link rel="stylesheet" href="/static/cupang.css?v=20261013b" />{% endblock %}
|
||||||
|
|
||||||
{% block content %}
|
{% block content %}
|
||||||
<section class="cpg">
|
<section class="cpg">
|
||||||
|
|||||||
@@ -1,6 +1,6 @@
|
|||||||
{% extends "erp_base.html" %}
|
{% extends "erp_base.html" %}
|
||||||
|
|
||||||
{% block head_extra %}<link rel="stylesheet" href="/static/cupang.css?v=20260904f" />{% endblock %}
|
{% block head_extra %}<link rel="stylesheet" href="/static/cupang.css?v=20261013b" />{% endblock %}
|
||||||
|
|
||||||
{% block content %}
|
{% block content %}
|
||||||
<section class="cpg">
|
<section class="cpg">
|
||||||
|
|||||||
@@ -1,6 +1,12 @@
|
|||||||
{% extends "erp_base.html" %}
|
{% extends "erp_base.html" %}
|
||||||
|
|
||||||
{% block head_extra %}<link rel="stylesheet" href="/static/cupang.css?v=20260904f" />{% endblock %}
|
{% block head_extra %}
|
||||||
|
{# 출고리스트 작성 팝업의 날짜 칸은 프로젝트 화면의 날짜 팝업을 그대로 쓴다 — project.js 는 PJ_LIB_ONLY 로 부품만 #}
|
||||||
|
<link rel="stylesheet" href="/static/project.css?v=20261111f" />
|
||||||
|
<link rel="stylesheet" href="/static/vendor/material-symbols/material-symbols.css" />
|
||||||
|
<link rel="stylesheet" href="/static/cupang.css?v=20261023d" />
|
||||||
|
<script>window.PJ_LIB_ONLY = true; window.PJ_HOLIDAYS = {{ (pj_kr_holidays or {}) | tojson }};</script>
|
||||||
|
{% endblock %}
|
||||||
|
|
||||||
{% block content %}
|
{% block content %}
|
||||||
<section class="cpg">
|
<section class="cpg">
|
||||||
@@ -9,6 +15,7 @@
|
|||||||
<div class="cpg-actions-grid">
|
<div class="cpg-actions-grid">
|
||||||
<div class="cpg-actions-main">
|
<div class="cpg-actions-main">
|
||||||
<a class="erp-btn erp-btn-primary" href="/cupang/box-calc">+ 신규 등록</a>
|
<a class="erp-btn erp-btn-primary" href="/cupang/box-calc">+ 신규 등록</a>
|
||||||
|
<button type="button" class="erp-btn cpg-btn-excel" id="cpg-ol-open">밀크런 출고리스트 작성</button>
|
||||||
<span class="cpg-settings-btns">
|
<span class="cpg-settings-btns">
|
||||||
<a class="erp-btn erp-btn-outline cpg-sales-link" href="/cupang/sales">쿠팡 로켓 매출</a>
|
<a class="erp-btn erp-btn-outline cpg-sales-link" href="/cupang/sales">쿠팡 로켓 매출</a>
|
||||||
<a class="erp-btn erp-btn-outline" href="/cupang/products">제품명 설정</a>
|
<a class="erp-btn erp-btn-outline" href="/cupang/products">제품명 설정</a>
|
||||||
@@ -168,10 +175,82 @@
|
|||||||
<input type="hidden" name="next" id="cpg-del-next" />
|
<input type="hidden" name="next" id="cpg-del-next" />
|
||||||
</form>
|
</form>
|
||||||
|
|
||||||
|
<!-- 밀크런 출고리스트 작성 팝업 — 완료하면 출고리스트 엑셀(구글 드라이브 .xlsx) 출고일 시트 아래에 덧붙인다 -->
|
||||||
|
<div class="cpg-modal" id="cpg-ol-dlg" hidden>
|
||||||
|
<div class="cpg-modal-back" data-ol-close></div>
|
||||||
|
<div class="cpg-modal-box cpg-ol-box" role="dialog" aria-modal="true" aria-labelledby="cpg-ol-title">
|
||||||
|
<h3 id="cpg-ol-title">밀크런 출고리스트 작성</h3>
|
||||||
|
|
||||||
|
<div class="cpg-ol-grid cpg-ol-grid-4">
|
||||||
|
<div class="erp-field"><span>작성일</span><input type="date" id="cpg-ol-doc-date" /></div>
|
||||||
|
<div class="erp-field"><span>출고일</span><input type="date" id="cpg-ol-ship-date" /></div>
|
||||||
|
<div class="erp-field"><span>센터입고일</span><input type="date" id="cpg-ol-arrival-date" /></div>
|
||||||
|
<label class="erp-field"><span>작업자</span>
|
||||||
|
<input class="erp-input" type="text" id="cpg-ol-worker" maxlength="30" value="{{ outbound_worker }}" /></label>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<!-- 입고센터 카드 — 센터마다 출고방식·제품·출고를 따로 입력(cupang-outbound.js 가 템플릿으로 만든다) -->
|
||||||
|
<div class="cpg-ol-centers" id="cpg-ol-centers"></div>
|
||||||
|
<button type="button" class="erp-btn erp-btn-outline cpg-ol-add-center" id="cpg-ol-add-center">+ 입고센터 추가</button>
|
||||||
|
<template id="cpg-ol-center-tpl">
|
||||||
|
<section class="cpg-ol-center">
|
||||||
|
<header class="cpg-ol-center-head">
|
||||||
|
<strong class="cpg-ol-center-no">입고센터 1</strong>
|
||||||
|
<button type="button" class="cpg-icon-btn is-danger cpg-ol-center-del">센터 삭제</button>
|
||||||
|
</header>
|
||||||
|
<div class="cpg-ol-grid">
|
||||||
|
<label class="erp-field"><span>입고센터</span>
|
||||||
|
<select class="erp-select cpg-ol-center-sel"><option value="">불러오는 중…</option></select></label>
|
||||||
|
<label class="erp-field"><span>출고방식</span>
|
||||||
|
<select class="erp-select cpg-ol-method">
|
||||||
|
<option value="택배">택배</option>
|
||||||
|
<option value="파렛트">파렛트</option>
|
||||||
|
</select></label>
|
||||||
|
<label class="erp-field"><span>출고</span>
|
||||||
|
<input class="erp-input cpg-ol-outbound" type="text" maxlength="100" placeholder="예) 2파렛트, 15박스" /></label>
|
||||||
|
<label class="erp-field cpg-ol-center-custom" hidden><span>새 입고센터</span>
|
||||||
|
<input class="erp-input cpg-ol-center-new" type="text" maxlength="60" placeholder="센터 이름" /></label>
|
||||||
|
</div>
|
||||||
|
<div class="erp-field"><span>제품 (코드표에서 검색해 추가)</span>
|
||||||
|
<div class="cpg-ol-search">
|
||||||
|
<input class="erp-input cpg-ol-search-input" type="search" autocomplete="off"
|
||||||
|
placeholder="제품코드 또는 제품명으로 검색" />
|
||||||
|
<ul class="cpg-ol-results" hidden></ul>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
<table class="cpg-ol-lines" hidden>
|
||||||
|
<thead><tr><th>제품코드</th><th>제품명</th><th>수량</th><th></th></tr></thead>
|
||||||
|
<tbody></tbody>
|
||||||
|
</table>
|
||||||
|
<p class="erp-muted cpg-ol-empty">위 검색창에서 제품을 골라 추가하세요.</p>
|
||||||
|
</section>
|
||||||
|
</template>
|
||||||
|
|
||||||
|
<p class="erp-muted cpg-ol-target" id="cpg-ol-target"></p>
|
||||||
|
<div class="cpg-ol-progress" id="cpg-ol-progress" hidden>
|
||||||
|
<div class="cpg-ol-progress-top">
|
||||||
|
<span id="cpg-ol-progress-step">준비 중</span>
|
||||||
|
<b id="cpg-ol-progress-pct">0%</b>
|
||||||
|
</div>
|
||||||
|
<div class="cpg-ol-progress-track" role="progressbar" aria-valuemin="0" aria-valuemax="100" aria-valuenow="0"
|
||||||
|
aria-label="기록 진행률" id="cpg-ol-progress-track">
|
||||||
|
<div class="cpg-ol-progress-bar" id="cpg-ol-progress-bar"></div>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
<p class="cpg-ol-error" id="cpg-ol-error" hidden></p>
|
||||||
|
<div class="cpg-ol-actions">
|
||||||
|
<button type="button" class="erp-btn erp-btn-outline" data-ol-close>취소</button>
|
||||||
|
<button type="button" class="erp-btn cpg-btn-excel" id="cpg-ol-submit">완료</button>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
|
||||||
</section>
|
</section>
|
||||||
{% endblock %}
|
{% endblock %}
|
||||||
|
|
||||||
{% block scripts %}
|
{% block scripts %}
|
||||||
|
<script src="/static/project.js?v=20261111d" defer></script>
|
||||||
|
<script src="/static/cupang-outbound.js?v=20261023d" defer></script>
|
||||||
<script>
|
<script>
|
||||||
(function () {
|
(function () {
|
||||||
var dlg = document.getElementById("cpg-del-dlg");
|
var dlg = document.getElementById("cpg-del-dlg");
|
||||||
|
|||||||
@@ -1,6 +1,6 @@
|
|||||||
{% extends "erp_base.html" %}
|
{% extends "erp_base.html" %}
|
||||||
|
|
||||||
{% block head_extra %}<link rel="stylesheet" href="/static/cupang.css?v=20260904f" />{% endblock %}
|
{% block head_extra %}<link rel="stylesheet" href="/static/cupang.css?v=20261013b" />{% endblock %}
|
||||||
|
|
||||||
{% block content %}
|
{% block content %}
|
||||||
<section class="cpg">
|
<section class="cpg">
|
||||||
@@ -34,6 +34,12 @@
|
|||||||
<input class="erp-input" type="text" name="product_code" required placeholder="예: MS-1012" /></label>
|
<input class="erp-input" type="text" name="product_code" required placeholder="예: MS-1012" /></label>
|
||||||
<label class="erp-field"><span>쿠팡상품코드</span>
|
<label class="erp-field"><span>쿠팡상품코드</span>
|
||||||
<input class="erp-input" type="text" name="coupang_item_code" placeholder="예: 1234567890" /></label>
|
<input class="erp-input" type="text" name="coupang_item_code" placeholder="예: 1234567890" /></label>
|
||||||
|
{% if weight_enabled %}
|
||||||
|
{# 포장무게(g) — 쉼표·g 붙여도 됨(1,070). 비워 두면 같은 제품코드의 기존 무게 유지 #}
|
||||||
|
<label class="erp-field cpg-weight-field"><span>포장무게(g)</span>
|
||||||
|
<input class="erp-input" type="text" name="weight_g" inputmode="numeric" autocomplete="off"
|
||||||
|
pattern="\s*[0-9][0-9,]*\s*(g|G)?\s*" title="숫자(g)로 입력하세요. 예: 1,070" placeholder="예: 1,070" /></label>
|
||||||
|
{% endif %}
|
||||||
<button type="submit" class="erp-btn erp-btn-primary">추가</button>
|
<button type="submit" class="erp-btn erp-btn-primary">추가</button>
|
||||||
</div>
|
</div>
|
||||||
</form>
|
</form>
|
||||||
@@ -60,6 +66,7 @@
|
|||||||
<th><button type="button" class="cpg-sort" data-sort-key="name">제품명<span class="cpg-sort-ind" aria-hidden="true"></span></button></th>
|
<th><button type="button" class="cpg-sort" data-sort-key="name">제품명<span class="cpg-sort-ind" aria-hidden="true"></span></button></th>
|
||||||
<th><button type="button" class="cpg-sort" data-sort-key="code">제품코드<span class="cpg-sort-ind" aria-hidden="true"></span></button></th>
|
<th><button type="button" class="cpg-sort" data-sort-key="code">제품코드<span class="cpg-sort-ind" aria-hidden="true"></span></button></th>
|
||||||
<th><button type="button" class="cpg-sort" data-sort-key="cpcode">쿠팡상품코드<span class="cpg-sort-ind" aria-hidden="true"></span></button></th>
|
<th><button type="button" class="cpg-sort" data-sort-key="cpcode">쿠팡상품코드<span class="cpg-sort-ind" aria-hidden="true"></span></button></th>
|
||||||
|
{% if weight_enabled %}<th class="cpg-weight-col"><button type="button" class="cpg-sort" data-sort-key="weight">포장무게<span class="cpg-sort-ind" aria-hidden="true"></span></button></th>{% endif %}
|
||||||
<th>상태</th>
|
<th>상태</th>
|
||||||
<th>동작</th>
|
<th>동작</th>
|
||||||
</tr>
|
</tr>
|
||||||
@@ -68,10 +75,12 @@
|
|||||||
{% for p in products %}
|
{% for p in products %}
|
||||||
<tr data-name="{{ p.product_name }}" data-code="{{ p.product_code }}"
|
<tr data-name="{{ p.product_name }}" data-code="{{ p.product_code }}"
|
||||||
data-cpcode="{{ p.coupang_item_code }}"
|
data-cpcode="{{ p.coupang_item_code }}"
|
||||||
|
data-weight="{{ p.weight_g if p.weight_g is not none else '' }}"
|
||||||
class="cpg-prod-row{% if not p.active %} is-inactive{% endif %}">
|
class="cpg-prod-row{% if not p.active %} is-inactive{% endif %}">
|
||||||
<td title="{{ p.product_name }}">{{ p.product_name }}</td>
|
<td title="{{ p.product_name }}">{{ p.product_name }}</td>
|
||||||
<td title="{{ p.product_code }}">{{ p.product_code }}</td>
|
<td title="{{ p.product_code }}">{{ p.product_code }}</td>
|
||||||
<td class="cpg-cpcode" title="{{ p.coupang_item_code }}">{% if p.coupang_item_code %}{{ p.coupang_item_code }}{% else %}<span class="erp-muted">—</span>{% endif %}</td>
|
<td class="cpg-cpcode" title="{{ p.coupang_item_code }}">{% if p.coupang_item_code %}{{ p.coupang_item_code }}{% else %}<span class="erp-muted">—</span>{% endif %}</td>
|
||||||
|
{% if weight_enabled %}<td class="cpg-weight-col">{% if p.weight_g is not none %}{{ "{:,}".format(p.weight_g) }}<span class="cpg-weight-unit">g</span>{% else %}<span class="erp-muted">—</span>{% endif %}</td>{% endif %}
|
||||||
<td>
|
<td>
|
||||||
<!-- 배지 자체가 토글 버튼: 클릭 → 활성/비활성 전환 -->
|
<!-- 배지 자체가 토글 버튼: 클릭 → 활성/비활성 전환 -->
|
||||||
<button type="button" class="erp-badge cpg-active-toggle
|
<button type="button" class="erp-badge cpg-active-toggle
|
||||||
@@ -92,7 +101,7 @@
|
|||||||
</tr>
|
</tr>
|
||||||
{% endfor %}
|
{% endfor %}
|
||||||
{% if not products %}
|
{% if not products %}
|
||||||
<tr class="cpg-no-sort"><td colspan="5" class="erp-muted">등록된 제품명이 없습니다. 왼쪽에서 선택해 등록하세요.</td></tr>
|
<tr class="cpg-no-sort"><td colspan="{{ 6 if weight_enabled else 5 }}" class="erp-muted">등록된 제품명이 없습니다. 왼쪽에서 선택해 등록하세요.</td></tr>
|
||||||
{% endif %}
|
{% endif %}
|
||||||
</tbody>
|
</tbody>
|
||||||
</table>
|
</table>
|
||||||
@@ -117,6 +126,10 @@
|
|||||||
rows.sort(function (a, b) {
|
rows.sort(function (a, b) {
|
||||||
var av = a.getAttribute("data-" + state.key) || "";
|
var av = a.getAttribute("data-" + state.key) || "";
|
||||||
var bv = b.getAttribute("data-" + state.key) || "";
|
var bv = b.getAttribute("data-" + state.key) || "";
|
||||||
|
if (state.key === "weight") { // 포장무게 — 숫자 크기순, 무게 없는 줄은 늘 맨 뒤
|
||||||
|
if (!av || !bv) return (av ? 0 : 1) - (bv ? 0 : 1);
|
||||||
|
return (Number(av) - Number(bv)) * state.dir;
|
||||||
|
}
|
||||||
return collator.compare(av, bv) * state.dir;
|
return collator.compare(av, bv) * state.dir;
|
||||||
});
|
});
|
||||||
rows.forEach(function (r) { tbody.appendChild(r); });
|
rows.forEach(function (r) { tbody.appendChild(r); });
|
||||||
@@ -150,6 +163,10 @@
|
|||||||
<input class="erp-input" type="text" id="cpg-edit-code" /></label>
|
<input class="erp-input" type="text" id="cpg-edit-code" /></label>
|
||||||
<label class="erp-field"><span>쿠팡상품코드</span>
|
<label class="erp-field"><span>쿠팡상품코드</span>
|
||||||
<input class="erp-input" type="text" id="cpg-edit-cpcode" placeholder="비우면 지워집니다" /></label>
|
<input class="erp-input" type="text" id="cpg-edit-cpcode" placeholder="비우면 지워집니다" /></label>
|
||||||
|
{% if weight_enabled %}
|
||||||
|
<label class="erp-field"><span>포장무게(g)</span>
|
||||||
|
<input class="erp-input" type="text" id="cpg-edit-weight" inputmode="numeric" autocomplete="off" placeholder="예: 1,070 (비우면 지워집니다)" /></label>
|
||||||
|
{% endif %}
|
||||||
<p class="erp-muted" id="cpg-edit-msg" style="margin:0;font-size:12px;"></p>
|
<p class="erp-muted" id="cpg-edit-msg" style="margin:0;font-size:12px;"></p>
|
||||||
<div class="cpg-dlg-actions erp-page-actions">
|
<div class="cpg-dlg-actions erp-page-actions">
|
||||||
<button type="button" class="erp-btn erp-btn-outline" data-edit-close>취소</button>
|
<button type="button" class="erp-btn erp-btn-outline" data-edit-close>취소</button>
|
||||||
@@ -167,6 +184,7 @@
|
|||||||
var elName = document.getElementById("cpg-edit-name");
|
var elName = document.getElementById("cpg-edit-name");
|
||||||
var elCode = document.getElementById("cpg-edit-code");
|
var elCode = document.getElementById("cpg-edit-code");
|
||||||
var elCp = document.getElementById("cpg-edit-cpcode");
|
var elCp = document.getElementById("cpg-edit-cpcode");
|
||||||
|
var elW = document.getElementById("cpg-edit-weight"); // 마이그레이션 007 전이면 없음
|
||||||
var elMsg = document.getElementById("cpg-edit-msg");
|
var elMsg = document.getElementById("cpg-edit-msg");
|
||||||
var saveBtn = document.getElementById("cpg-edit-save");
|
var saveBtn = document.getElementById("cpg-edit-save");
|
||||||
var editingId = null;
|
var editingId = null;
|
||||||
@@ -181,6 +199,10 @@
|
|||||||
elName.value = row.getAttribute("data-name") || "";
|
elName.value = row.getAttribute("data-name") || "";
|
||||||
elCode.value = row.getAttribute("data-code") || "";
|
elCode.value = row.getAttribute("data-code") || "";
|
||||||
elCp.value = row.getAttribute("data-cpcode") || "";
|
elCp.value = row.getAttribute("data-cpcode") || "";
|
||||||
|
if (elW) {
|
||||||
|
var w = row.getAttribute("data-weight") || "";
|
||||||
|
elW.value = w ? Number(w).toLocaleString("ko-KR") : "";
|
||||||
|
}
|
||||||
elMsg.textContent = "";
|
elMsg.textContent = "";
|
||||||
dlg.hidden = false;
|
dlg.hidden = false;
|
||||||
elName.focus();
|
elName.focus();
|
||||||
@@ -200,6 +222,12 @@
|
|||||||
product_code: (elCode.value || "").trim(),
|
product_code: (elCode.value || "").trim(),
|
||||||
coupang_item_code: (elCp.value || "").trim()
|
coupang_item_code: (elCp.value || "").trim()
|
||||||
};
|
};
|
||||||
|
if (elW) {
|
||||||
|
// 포장무게 — 쉼표·g 는 서버가 읽는다. 숫자가 아니면 여기서 먼저 막는다(빈 값 = 지움)
|
||||||
|
var wv = (elW.value || "").trim();
|
||||||
|
if (wv && !/^[0-9][0-9,]*\s*g?$/i.test(wv)) { elMsg.textContent = "포장무게는 숫자(g)로 입력하세요. 예: 1,070"; return; }
|
||||||
|
body.weight_g = wv;
|
||||||
|
}
|
||||||
if (!body.product_name || !body.product_code) {
|
if (!body.product_name || !body.product_code) {
|
||||||
elMsg.textContent = "제품명과 제품코드는 필수입니다."; return;
|
elMsg.textContent = "제품명과 제품코드는 필수입니다."; return;
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -1,6 +1,6 @@
|
|||||||
{% extends "erp_base.html" %}
|
{% extends "erp_base.html" %}
|
||||||
|
|
||||||
{% block head_extra %}<link rel="stylesheet" href="/static/cupang.css?v=20260904f" />{% endblock %}
|
{% block head_extra %}<link rel="stylesheet" href="/static/cupang.css?v=20261013b" />{% endblock %}
|
||||||
|
|
||||||
{% block content %}
|
{% block content %}
|
||||||
{# 쿠팡 로켓 매출 — 발주 라인별 공급가·원가·물류비·마진 #}
|
{# 쿠팡 로켓 매출 — 발주 라인별 공급가·원가·물류비·마진 #}
|
||||||
|
|||||||
@@ -1,6 +1,6 @@
|
|||||||
{% extends "erp_base.html" %}
|
{% extends "erp_base.html" %}
|
||||||
|
|
||||||
{% block head_extra %}<link rel="stylesheet" href="/static/cupang.css?v=20260904f" />{% endblock %}
|
{% block head_extra %}<link rel="stylesheet" href="/static/cupang.css?v=20261013b" />{% endblock %}
|
||||||
|
|
||||||
{% block content %}
|
{% block content %}
|
||||||
{# 출고 묶음 보기 — 상자 계산 화면과 같은 3열 구성. 읽기 전용(수정 없음). #}
|
{# 출고 묶음 보기 — 상자 계산 화면과 같은 3열 구성. 읽기 전용(수정 없음). #}
|
||||||
@@ -73,16 +73,17 @@
|
|||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
<div class="cpg-sum-scroll">
|
<div class="cpg-sum-scroll cpg-boxno-scroll">
|
||||||
<table class="erp-table cpg-boxno-table">
|
<table class="erp-table cpg-boxno-table">
|
||||||
<colgroup>
|
<colgroup>
|
||||||
<col class="cpg-boxno-c-no" />
|
<col class="cpg-boxno-c-no" />
|
||||||
<col class="cpg-boxno-c-name" />
|
<col class="cpg-boxno-c-name" />
|
||||||
<col class="cpg-boxno-c-code" />
|
<col class="cpg-boxno-c-code" />
|
||||||
<col class="cpg-boxno-c-qty" />
|
<col class="cpg-boxno-c-qty" />
|
||||||
|
{% if box_weight %}<col class="cpg-boxno-c-weight" />{% endif %}
|
||||||
</colgroup>
|
</colgroup>
|
||||||
<thead>
|
<thead>
|
||||||
<tr><th>상자번호</th><th>제품명</th><th>제품코드</th><th>수량</th></tr>
|
<tr><th>상자번호</th><th>제품명</th><th>제품코드</th><th>수량</th>{% if box_weight %}<th title="상자에 든 제품의 수량 × 포장무게(설정(제품명)) 합계">무게</th>{% endif %}</tr>
|
||||||
</thead>
|
</thead>
|
||||||
<tbody>
|
<tbody>
|
||||||
{% for b in box_list %}
|
{% for b in box_list %}
|
||||||
@@ -94,13 +95,40 @@
|
|||||||
<td title="{{ it.product_name }}">{{ it.product_name }}</td>
|
<td title="{{ it.product_name }}">{{ it.product_name }}</td>
|
||||||
<td class="cpg-boxno-code">{{ it.product_code }}</td>
|
<td class="cpg-boxno-code">{{ it.product_code }}</td>
|
||||||
<td class="cpg-calc-num">{{ it.quantity }}</td>
|
<td class="cpg-calc-num">{{ it.quantity }}</td>
|
||||||
|
{% if box_weight and loop.first %}
|
||||||
|
{# 상자 무게 합계 — 상자번호처럼 상자 단위로 한 칸. 무게 없는 제품이 있으면 표시 #}
|
||||||
|
{% set miss = b.weight_missing or [] %}
|
||||||
|
<td class="cpg-boxno-weight" rowspan="{{ b['items']|length }}"
|
||||||
|
{% if miss %}title="포장무게 미입력: {{ miss|join(', ') }}{% if b.weight_g is not none %} — 이 제품을 뺀 합계{% endif %} (설정(제품명)에서 입력)"{% endif %}>
|
||||||
|
{%- if b.weight_g is not none -%}
|
||||||
|
{{ b.weight_kg }}<span class="cpg-weight-unit">kg</span>{% if miss %}<span class="cpg-boxno-wmiss">일부 미입력</span>{% endif %}
|
||||||
|
{%- else -%}<span class="erp-muted">—</span>{%- endif -%}
|
||||||
|
</td>
|
||||||
|
{% endif %}
|
||||||
</tr>
|
</tr>
|
||||||
{% endfor %}
|
{% endfor %}
|
||||||
{% endfor %}
|
{% endfor %}
|
||||||
{% if not box_list %}
|
{% if not box_list %}
|
||||||
<tr><td colspan="4" class="erp-muted">상자 정보가 없습니다.</td></tr>
|
<tr><td colspan="{{ 5 if box_weight else 4 }}" class="erp-muted">상자 정보가 없습니다.</td></tr>
|
||||||
{% endif %}
|
{% endif %}
|
||||||
</tbody>
|
</tbody>
|
||||||
|
{% if box_list %}
|
||||||
|
{# 합계 행 — 수량 합계, 무게 합계(kg). 무게 없는 제품이 있으면 아는 무게만 더한 값 #}
|
||||||
|
<tfoot>
|
||||||
|
<tr class="cpg-boxno-total">
|
||||||
|
<td class="cpg-boxno-cell" colspan="3">합계</td>
|
||||||
|
<td class="cpg-calc-num">{{ "{:,}".format(box_qty_total) }}</td>
|
||||||
|
{% if box_weight %}
|
||||||
|
<td class="cpg-boxno-weight"
|
||||||
|
{% if box_weight_partial %}title="포장무게 미입력 제품이 있어 아는 무게만 더한 합계 (설정(제품명)에서 입력)"{% endif %}>
|
||||||
|
{%- if box_weight_total_kg is not none -%}
|
||||||
|
{{ box_weight_total_kg }}<span class="cpg-weight-unit">kg</span>{% if box_weight_partial %}<span class="cpg-boxno-wmiss">일부 미입력</span>{% endif %}
|
||||||
|
{%- else -%}<span class="erp-muted">—</span>{%- endif -%}
|
||||||
|
</td>
|
||||||
|
{% endif %}
|
||||||
|
</tr>
|
||||||
|
</tfoot>
|
||||||
|
{% endif %}
|
||||||
</table>
|
</table>
|
||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
|
|||||||
@@ -0,0 +1,14 @@
|
|||||||
|
# [배송] 말레이시아 배송 모듈 — `app/modules/dispatch/`, `dispatch_db`
|
||||||
|
|
||||||
|
> 이 모듈만 고칠 때 읽는 요약. 상세는 `docs/DISPATCH_MODULE.md`.
|
||||||
|
> 정적 파일: `app/static/dispatch/`. 템플릿: `templates/`. 테스트: `tests/`.
|
||||||
|
|
||||||
|
- TikTok·Shopee 출고관리. 권한키 `dispatch`.
|
||||||
|
- 플랫폼별 데이터 엑셀 업로드(TikTok = `03_TikTok_Order_Export.xlsx`, Shopee = `Packing List.Doorstep Delivery.xlsx`)
|
||||||
|
→ 1상자 = 1카드 출고 작업 리스트·SKU 피킹 요약·Kagayaku 전달표 자동 생성.
|
||||||
|
- 1상자 묶음 기준 Package ID > Tracking ID > Order ID, 같은 상자 같은 SKU 합산.
|
||||||
|
- 작업 상태 토글(`dispatch_logs` 기록).
|
||||||
|
- 받는 사람 이름/전화/주소는 상자 단위로 저장(작업 카드 표시 + 출고 엑셀 생성용) — **개인정보**, 로그·외부 전송 주의.
|
||||||
|
- 배치 다운로드 zip 에 업로드 원본 + 취합 출고 엑셀(`YYYY.MM.DD(Ddd)_tictoc|shopee.xlsx`) 포함.
|
||||||
|
- 기간별 발송 수량 엑셀(`/dispatch/period-export`, **수퍼 관리자 전용**): 날짜별·아이템별 수량(`_N` 배수 반영, 세트는 BOM 으로 낱개 분해) + 아이템×날짜 요약 시트 + 세트×날짜 요약 시트(낱개로 풀기 전 세트 수량).
|
||||||
|
- 엑셀은 openpyxl 파싱/생성.
|
||||||
@@ -309,6 +309,41 @@ class DispatchStore:
|
|||||||
for r in rows
|
for r in rows
|
||||||
]
|
]
|
||||||
|
|
||||||
|
def shipped_by_date_range(
|
||||||
|
self, *, date_from: str, date_to: str
|
||||||
|
) -> list[dict[str, Any]]:
|
||||||
|
"""기간(양끝 포함) 날짜·SKU별 합산 수량 — 기간별 발송 수량 엑셀용.
|
||||||
|
|
||||||
|
반환: [{"dispatch_date": "YYYY-MM-DD", "seller_sku", "product_name", "qty"}].
|
||||||
|
_N 배수 반영은 호출부(export)에서 한다.
|
||||||
|
"""
|
||||||
|
with self._pool.connection() as conn:
|
||||||
|
rows = conn.execute(
|
||||||
|
"""
|
||||||
|
SELECT b.dispatch_date, i.seller_sku,
|
||||||
|
MAX(i.product_name) AS product_name,
|
||||||
|
SUM(i.quantity)::int AS qty
|
||||||
|
FROM dispatch_items i
|
||||||
|
JOIN dispatch_parcels p ON p.id = i.parcel_id
|
||||||
|
JOIN dispatch_batches b ON b.id = p.batch_id
|
||||||
|
WHERE b.dispatch_date BETWEEN %s AND %s
|
||||||
|
GROUP BY b.dispatch_date, i.seller_sku
|
||||||
|
ORDER BY b.dispatch_date ASC, i.seller_sku ASC
|
||||||
|
""",
|
||||||
|
(date_from, date_to),
|
||||||
|
).fetchall()
|
||||||
|
return [
|
||||||
|
{
|
||||||
|
"dispatch_date": r["dispatch_date"].isoformat()
|
||||||
|
if isinstance(r["dispatch_date"], date)
|
||||||
|
else str(r["dispatch_date"] or ""),
|
||||||
|
"seller_sku": r["seller_sku"] or "",
|
||||||
|
"product_name": r["product_name"] or "",
|
||||||
|
"qty": int(r["qty"] or 0),
|
||||||
|
}
|
||||||
|
for r in rows
|
||||||
|
]
|
||||||
|
|
||||||
# ════════════════════════════════════════════════════════════
|
# ════════════════════════════════════════════════════════════
|
||||||
# 말레이시아 재고 차감 1회성 가드
|
# 말레이시아 재고 차감 1회성 가드
|
||||||
# ════════════════════════════════════════════════════════════
|
# ════════════════════════════════════════════════════════════
|
||||||
|
|||||||
@@ -246,6 +246,158 @@ def stock_filename(dispatch_date: str) -> str:
|
|||||||
return f"{stamp}_sabangnet_outbound.xlsx"
|
return f"{stamp}_sabangnet_outbound.xlsx"
|
||||||
|
|
||||||
|
|
||||||
|
# ── 기간별 발송 수량 엑셀(수퍼 관리자) ──
|
||||||
|
def missing_set_boms(
|
||||||
|
rows: list[dict[str, Any]], set_bom: dict[str, list[dict[str, Any]]]
|
||||||
|
) -> list[str]:
|
||||||
|
"""세트(MY-)인데 BOM 이 없어 낱개로 풀 수 없는 코드 목록(정렬)."""
|
||||||
|
return sorted({
|
||||||
|
b for b in (split_sku(r.get("seller_sku", ""))[0].strip().upper() for r in rows)
|
||||||
|
if b.startswith(_SET_PREFIX) and b not in set_bom
|
||||||
|
})
|
||||||
|
|
||||||
|
|
||||||
|
def aggregate_shipped(
|
||||||
|
rows: list[dict[str, Any]],
|
||||||
|
name_map: dict[str, str] | None = None,
|
||||||
|
set_bom: dict[str, list[dict[str, Any]]] | None = None,
|
||||||
|
) -> tuple[list[str], dict[str, str], dict[tuple[str, str], int]]:
|
||||||
|
"""날짜·SKU별 합산 행 → (날짜목록, {코드: 상품명}, {(날짜, 코드): 수량}).
|
||||||
|
|
||||||
|
seller_sku 의 _N 접미사는 배수로 곱해 실제 아이템코드로 합친다
|
||||||
|
(예: MT-0320_3 × 2 → MT-0320 6개). 세트(set_bom 에 있는 코드)는 구성 낱개로
|
||||||
|
풀어 (수량 × 구성수량) 을 낱개 코드에 더한다.
|
||||||
|
"""
|
||||||
|
name_map = name_map or {}
|
||||||
|
set_bom = set_bom or {}
|
||||||
|
dates: set[str] = set()
|
||||||
|
names: dict[str, str] = {}
|
||||||
|
qty: dict[tuple[str, str], int] = {}
|
||||||
|
|
||||||
|
def _add(d: str, code: str, n: int, fallback: str) -> None:
|
||||||
|
key = (d, code)
|
||||||
|
qty[key] = qty.get(key, 0) + n
|
||||||
|
if not names.get(code):
|
||||||
|
names[code] = resolve_product_name(code, name_map, fallback=fallback)
|
||||||
|
|
||||||
|
for r in rows:
|
||||||
|
base, mult = split_sku(r.get("seller_sku", ""))
|
||||||
|
code = base.strip().upper()
|
||||||
|
if not code:
|
||||||
|
continue
|
||||||
|
pieces = int(r.get("qty", 0) or 0) * mult
|
||||||
|
if pieces <= 0:
|
||||||
|
continue
|
||||||
|
d = r.get("dispatch_date", "") or ""
|
||||||
|
dates.add(d)
|
||||||
|
comps = set_bom.get(code)
|
||||||
|
if comps: # 세트 → 낱개 분해
|
||||||
|
for c in comps:
|
||||||
|
cc = str(c.get("component_code", "")).strip().upper()
|
||||||
|
n = pieces * int(c.get("component_qty", 0) or 0)
|
||||||
|
if cc and n > 0:
|
||||||
|
_add(d, cc, n, "")
|
||||||
|
else:
|
||||||
|
_add(d, code, pieces, r.get("product_name", "") or "")
|
||||||
|
return sorted(dates), names, qty
|
||||||
|
|
||||||
|
|
||||||
|
def build_period_xlsx(
|
||||||
|
*,
|
||||||
|
rows: list[dict[str, Any]],
|
||||||
|
date_from: str,
|
||||||
|
date_to: str,
|
||||||
|
name_map: dict[str, str] | None = None,
|
||||||
|
set_bom: dict[str, list[dict[str, Any]]] | None = None,
|
||||||
|
) -> bytes:
|
||||||
|
"""기간별 발송 수량 xlsx(세트는 낱개로 풀어 합산). 시트 3개.
|
||||||
|
|
||||||
|
- 「날짜별」: 발송 날짜 / 아이템 코드 / 상품이름 / 수량 (날짜·코드 오름차순, 맨 끝 합계)
|
||||||
|
- 「아이템별 요약」: 아이템 코드 / 상품이름 / 날짜1..N / 합계 (맨 끝 날짜별 합계 행)
|
||||||
|
- 「세트별 요약」: 세트 코드 / 상품이름 / 날짜1..N / 합계 — 낱개로 풀기 전 세트 단위 수량
|
||||||
|
"""
|
||||||
|
from openpyxl import Workbook # noqa: WPS433
|
||||||
|
from openpyxl.styles import Alignment, Font, PatternFill
|
||||||
|
from openpyxl.utils import get_column_letter
|
||||||
|
|
||||||
|
set_bom = set_bom or {}
|
||||||
|
dates, names, qty = aggregate_shipped(rows, name_map, set_bom)
|
||||||
|
codes = sorted(names)
|
||||||
|
# 세트 행만 BOM 없이 다시 합산하면 세트 단위 수량이 된다(_N 배수 반영은 같다).
|
||||||
|
set_rows = [r for r in rows if split_sku(r.get("seller_sku", ""))[0].strip().upper() in set_bom]
|
||||||
|
_sd, set_names, set_qty = aggregate_shipped(set_rows, name_map)
|
||||||
|
|
||||||
|
head_fill = PatternFill("solid", fgColor="E2E8F0")
|
||||||
|
head_font = Font(bold=True)
|
||||||
|
bold = Font(bold=True)
|
||||||
|
|
||||||
|
def _style_head(ws: Any) -> None:
|
||||||
|
for cell in ws[1]:
|
||||||
|
cell.fill = head_fill
|
||||||
|
cell.font = head_font
|
||||||
|
cell.alignment = Alignment(horizontal="center", vertical="center")
|
||||||
|
ws.freeze_panes = "A2"
|
||||||
|
|
||||||
|
wb = Workbook()
|
||||||
|
|
||||||
|
# 시트 1 — 날짜별 목록
|
||||||
|
ws = wb.active
|
||||||
|
ws.title = "날짜별"
|
||||||
|
headers = ["발송 날짜", "아이템 코드", "상품이름", "수량"]
|
||||||
|
ws.append(headers)
|
||||||
|
total = 0
|
||||||
|
for d in dates:
|
||||||
|
for code in codes:
|
||||||
|
n = qty.get((d, code))
|
||||||
|
if not n:
|
||||||
|
continue
|
||||||
|
ws.append([d, code, names.get(code, ""), n])
|
||||||
|
total += n
|
||||||
|
ws.append(["합계", "", "", total])
|
||||||
|
for cell in ws[ws.max_row]:
|
||||||
|
cell.font = bold
|
||||||
|
_style_head(ws)
|
||||||
|
_autosize(ws, headers)
|
||||||
|
|
||||||
|
# 시트 2·3 — 코드(행) × 날짜(열) 요약. 날짜 열은 두 시트 모두 전체 발송 날짜로 맞춘다.
|
||||||
|
def _pivot(title: str, code_label: str, p_names: dict[str, str],
|
||||||
|
p_qty: dict[tuple[str, str], int]) -> None:
|
||||||
|
p_codes = sorted(p_names)
|
||||||
|
ws2 = wb.create_sheet(title)
|
||||||
|
headers2 = [code_label, "상품이름", *dates, "합계"]
|
||||||
|
ws2.append(headers2)
|
||||||
|
for code in p_codes:
|
||||||
|
per_day = [p_qty.get((d, code), 0) for d in dates]
|
||||||
|
ws2.append([code, p_names.get(code, ""), *[n or None for n in per_day], sum(per_day)])
|
||||||
|
day_totals = [sum(p_qty.get((d, c), 0) for c in p_codes) for d in dates]
|
||||||
|
ws2.append(["합계", "", *day_totals, sum(day_totals)])
|
||||||
|
for cell in ws2[ws2.max_row]:
|
||||||
|
cell.font = bold
|
||||||
|
_style_head(ws2)
|
||||||
|
ws2.freeze_panes = "C2"
|
||||||
|
_autosize(ws2, headers2)
|
||||||
|
for i in range(3, len(headers2) + 1): # 날짜 열은 좁게 고정
|
||||||
|
ws2.column_dimensions[get_column_letter(i)].width = 12
|
||||||
|
|
||||||
|
_pivot("아이템별 요약", "아이템 코드", names, qty)
|
||||||
|
_pivot("세트별 요약", "세트 코드", set_names, set_qty)
|
||||||
|
|
||||||
|
wb.properties.title = f"말레이시아 발송 수량 {date_from} ~ {date_to}"
|
||||||
|
|
||||||
|
buf = io.BytesIO()
|
||||||
|
wb.save(buf)
|
||||||
|
return buf.getvalue()
|
||||||
|
|
||||||
|
|
||||||
|
def period_filename(date_from: str, date_to: str) -> str:
|
||||||
|
"""기간별 발송 수량 파일명: 2026.10.01-2026.10.28_shipped_qty.xlsx."""
|
||||||
|
def _stamp(v: str) -> str:
|
||||||
|
d = _parse_date(v)
|
||||||
|
return d.strftime("%Y.%m.%d") if d else (v or "").strip()
|
||||||
|
|
||||||
|
return f"{_stamp(date_from)}-{_stamp(date_to)}_shipped_qty.xlsx"
|
||||||
|
|
||||||
|
|
||||||
def _cell(value: Any) -> Any:
|
def _cell(value: Any) -> Any:
|
||||||
"""송장/전화번호 등이 숫자로 보이면 엑셀이 과학표기/반올림 하므로 문자열 보존."""
|
"""송장/전화번호 등이 숫자로 보이면 엑셀이 과학표기/반올림 하므로 문자열 보존."""
|
||||||
if isinstance(value, int):
|
if isinstance(value, int):
|
||||||
|
|||||||
@@ -131,11 +131,11 @@ def _render_config_needed(request: Request, user: dict[str, Any]) -> HTMLRespons
|
|||||||
def _guard(request: Request):
|
def _guard(request: Request):
|
||||||
"""로그인+권한+store 점검. 페이지 핸들러 진입부에서 사용."""
|
"""로그인+권한+store 점검. 페이지 핸들러 진입부에서 사용."""
|
||||||
from app.main import get_current_user_record, render_template # noqa: WPS433
|
from app.main import get_current_user_record, render_template # noqa: WPS433
|
||||||
from app.store import has_module, is_admin # noqa: WPS433
|
from app.store import has_module, is_admin, login_redirect # noqa: WPS433
|
||||||
|
|
||||||
user = get_current_user_record(request)
|
user = get_current_user_record(request)
|
||||||
if user is None:
|
if user is None:
|
||||||
return RedirectResponse(url="/login", status_code=303)
|
return login_redirect(request)
|
||||||
if not has_module(user, "dispatch"):
|
if not has_module(user, "dispatch"):
|
||||||
return render_template(
|
return render_template(
|
||||||
request,
|
request,
|
||||||
@@ -477,6 +477,72 @@ def stock_export(
|
|||||||
)
|
)
|
||||||
|
|
||||||
|
|
||||||
|
_PERIOD_MAX_DAYS = 366
|
||||||
|
|
||||||
|
|
||||||
|
@router.get("/period-export")
|
||||||
|
def period_export(
|
||||||
|
request: Request,
|
||||||
|
date_from: str,
|
||||||
|
date_to: str,
|
||||||
|
user: dict[str, Any] = Depends(_require_user),
|
||||||
|
) -> Response:
|
||||||
|
"""기간(양끝 포함) 날짜별·아이템별 발송 수량 xlsx — 슈퍼 관리자 전용.
|
||||||
|
|
||||||
|
seller_sku 의 _N 배수 반영, 세트(MY-)는 itemcode_db BOM 으로 낱개로 풀어 합산.
|
||||||
|
"""
|
||||||
|
if not bool(user.get("is_super_admin")):
|
||||||
|
raise HTTPException(status_code=403, detail="기간별 발송 수량은 슈퍼 관리자만 받을 수 있습니다.")
|
||||||
|
st = _store(request)
|
||||||
|
if st is None:
|
||||||
|
raise HTTPException(status_code=503, detail="dispatch_db 미설정")
|
||||||
|
d_from = export._parse_date(date_from)
|
||||||
|
d_to = export._parse_date(date_to)
|
||||||
|
if d_from is None or d_to is None:
|
||||||
|
raise HTTPException(status_code=400, detail="시작일·종료일을 YYYY-MM-DD 로 입력하세요.")
|
||||||
|
if d_from > d_to:
|
||||||
|
d_from, d_to = d_to, d_from
|
||||||
|
if (d_to - d_from).days + 1 > _PERIOD_MAX_DAYS:
|
||||||
|
raise HTTPException(status_code=400, detail=f"기간은 최대 {_PERIOD_MAX_DAYS}일까지 가능합니다.")
|
||||||
|
|
||||||
|
f, t = d_from.isoformat(), d_to.isoformat()
|
||||||
|
rows = st.shipped_by_date_range(date_from=f, date_to=t)
|
||||||
|
if not rows:
|
||||||
|
raise HTTPException(status_code=404, detail=f"{f} ~ {t} 기간의 발송 데이터가 없습니다.")
|
||||||
|
|
||||||
|
# 세트 BOM 이 없으면 낱개로 못 푼 채 파일이 만들어진다 — 조용히 틀리지 말고 알린다.
|
||||||
|
set_bom, _sab = _itemcode_bom_and_sabangnet(request)
|
||||||
|
missing_sets = export.missing_set_boms(rows, set_bom)
|
||||||
|
if missing_sets:
|
||||||
|
reader = getattr(request.app.state, "malaysia_itemcode", None)
|
||||||
|
hint = getattr(reader, "last_error", "") or getattr(reader, "reason", "")
|
||||||
|
detail = (
|
||||||
|
"세트 BOM 을 찾지 못해 낱개로 풀 수 없습니다: "
|
||||||
|
+ ", ".join(missing_sets)
|
||||||
|
+ ". itemcode_db 의 set_components 에 해당 세트 BOM 이 등록돼 있는지 확인하세요."
|
||||||
|
)
|
||||||
|
if hint:
|
||||||
|
detail += f" (itemcode 리더 오류: {hint})"
|
||||||
|
raise HTTPException(status_code=422, detail=detail)
|
||||||
|
|
||||||
|
xlsx_bytes = export.build_period_xlsx(
|
||||||
|
rows=rows, date_from=f, date_to=t,
|
||||||
|
name_map=_itemcode_name_map(request), set_bom=set_bom,
|
||||||
|
)
|
||||||
|
fname = export.period_filename(f, t)
|
||||||
|
headers = {
|
||||||
|
"Content-Disposition": (
|
||||||
|
f"attachment; filename=\"shipped_{f}_{t}.xlsx\"; "
|
||||||
|
f"filename*=UTF-8''{quote(fname)}"
|
||||||
|
)
|
||||||
|
}
|
||||||
|
return Response(
|
||||||
|
content=xlsx_bytes,
|
||||||
|
media_type="application/vnd.openxmlformats-officedocument.spreadsheetml.sheet",
|
||||||
|
headers=headers,
|
||||||
|
)
|
||||||
|
|
||||||
|
|
||||||
@router.post("/stock-deduct")
|
@router.post("/stock-deduct")
|
||||||
def stock_deduct(
|
def stock_deduct(
|
||||||
request: Request,
|
request: Request,
|
||||||
|
|||||||
@@ -114,7 +114,8 @@
|
|||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
<div class="erp-card dsp-calwrap">
|
<div class="dsp-calwrap" style="display:flex;flex-direction:column;gap:16px;">
|
||||||
|
<div class="erp-card" style="margin:0;">
|
||||||
<div class="cpg-card-head"><h3 style="margin:0;" data-ko="사방넷 출고 다운로드" data-en="Sabangnet Outbound Download">사방넷 출고 다운로드</h3></div>
|
<div class="cpg-card-head"><h3 style="margin:0;" data-ko="사방넷 출고 다운로드" data-en="Sabangnet Outbound Download">사방넷 출고 다운로드</h3></div>
|
||||||
<p class="erp-muted" style="margin:4px 0 10px;font-size:13px;"
|
<p class="erp-muted" style="margin:4px 0 10px;font-size:13px;"
|
||||||
data-ko="날짜를 클릭하면 그날 출고를 낱개로 분해한 사방넷 출고 엑셀을 받습니다. 사방넷에 올리면 출고로 잡혀 재고가 차감됩니다."
|
data-ko="날짜를 클릭하면 그날 출고를 낱개로 분해한 사방넷 출고 엑셀을 받습니다. 사방넷에 올리면 출고로 잡혀 재고가 차감됩니다."
|
||||||
@@ -143,6 +144,24 @@
|
|||||||
<div id="dsp-cal-deduct-note" class="erp-muted" style="font-size:12px;"></div>
|
<div id="dsp-cal-deduct-note" class="erp-muted" style="font-size:12px;"></div>
|
||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
|
{% if is_super %}
|
||||||
|
<div class="erp-card" style="margin:0;">
|
||||||
|
<div class="cpg-card-head"><h3 style="margin:0;" data-ko="기간별 발송 수량" data-en="Shipped Qty by Period">기간별 발송 수량</h3></div>
|
||||||
|
<p class="erp-muted" style="margin:4px 0 10px;font-size:13px;"
|
||||||
|
data-ko="기간 안 날짜별·아이템별 발송 수량을 엑셀로 받습니다. 세트는 낱개로 풀어 합산하고, 세트 수량은 별도 시트에 담습니다. (수퍼 관리자 전용)"
|
||||||
|
data-en="Download shipped quantities per date and item for the period. Sets are split into singles; set counts are on a separate sheet. (Super admin only)">기간 안 날짜별·아이템별 발송 수량을 엑셀로 받습니다. 세트는 낱개로 풀어 합산하고, 세트 수량은 별도 시트에 담습니다. (수퍼 관리자 전용)</p>
|
||||||
|
<div style="display:flex;align-items:center;gap:6px;flex-wrap:wrap;">
|
||||||
|
<input type="date" id="dsp-pe-from" class="erp-input" style="flex:1 1 120px;min-width:0;padding:7px 8px;border:1px solid #cbd5e1;border-radius:8px;" />
|
||||||
|
<span class="erp-muted">~</span>
|
||||||
|
<input type="date" id="dsp-pe-to" class="erp-input" style="flex:1 1 120px;min-width:0;padding:7px 8px;border:1px solid #cbd5e1;border-radius:8px;" />
|
||||||
|
</div>
|
||||||
|
<button type="button" id="dsp-pe-dl" class="erp-btn erp-btn-primary" style="margin-top:10px;width:100%;"
|
||||||
|
data-ko="📊 기간별 발송 수량 엑셀 다운로드" data-en="📊 Download Shipped Qty Excel">📊 기간별 발송 수량 엑셀 다운로드</button>
|
||||||
|
<div id="dsp-pe-note" class="erp-muted" style="font-size:12px;margin-top:6px;"></div>
|
||||||
|
</div>
|
||||||
|
{% endif %}
|
||||||
|
</div>
|
||||||
</div>
|
</div>
|
||||||
</section>
|
</section>
|
||||||
{% endblock %}
|
{% endblock %}
|
||||||
@@ -264,6 +283,53 @@
|
|||||||
render();
|
render();
|
||||||
})();
|
})();
|
||||||
|
|
||||||
|
// ── 기간별 발송 수량 엑셀(수퍼 관리자) ──
|
||||||
|
(function () {
|
||||||
|
var btn = document.getElementById('dsp-pe-dl');
|
||||||
|
if (!btn) return;
|
||||||
|
var fromEl = document.getElementById('dsp-pe-from');
|
||||||
|
var toEl = document.getElementById('dsp-pe-to');
|
||||||
|
var note = document.getElementById('dsp-pe-note');
|
||||||
|
function pad(n) { return (n < 10 ? '0' : '') + n; }
|
||||||
|
function iso(d) { return d.getFullYear() + '-' + pad(d.getMonth() + 1) + '-' + pad(d.getDate()); }
|
||||||
|
function en() { return (window.dspLang && window.dspLang() === 'en'); }
|
||||||
|
// 기본: 이번 달 1일 ~ 오늘
|
||||||
|
var now = new Date();
|
||||||
|
fromEl.value = iso(new Date(now.getFullYear(), now.getMonth(), 1));
|
||||||
|
toEl.value = iso(now);
|
||||||
|
|
||||||
|
btn.onclick = function () {
|
||||||
|
var f = fromEl.value, t = toEl.value;
|
||||||
|
if (!f || !t) { alert(en() ? 'Pick both dates.' : '시작일과 종료일을 고르세요.'); return; }
|
||||||
|
btn.disabled = true;
|
||||||
|
note.textContent = en() ? 'Preparing…' : '만드는 중…';
|
||||||
|
var url = '/dispatch/period-export?date_from=' + encodeURIComponent(f) + '&date_to=' + encodeURIComponent(t);
|
||||||
|
fetch(url)
|
||||||
|
.then(function (r) {
|
||||||
|
if (!r.ok) {
|
||||||
|
return r.json().catch(function () { return {}; }).then(function (j) {
|
||||||
|
throw new Error((j && j.detail) || ('HTTP ' + r.status));
|
||||||
|
});
|
||||||
|
}
|
||||||
|
var cd = r.headers.get('Content-Disposition') || '';
|
||||||
|
var m = cd.match(/filename\*=UTF-8''([^;]+)/);
|
||||||
|
var name = m ? decodeURIComponent(m[1]) : ('shipped_' + f + '_' + t + '.xlsx');
|
||||||
|
return r.blob().then(function (b) {
|
||||||
|
var a = document.createElement('a');
|
||||||
|
a.href = URL.createObjectURL(b);
|
||||||
|
a.download = name;
|
||||||
|
document.body.appendChild(a); a.click(); a.remove();
|
||||||
|
setTimeout(function () { URL.revokeObjectURL(a.href); }, 1000);
|
||||||
|
note.textContent = '';
|
||||||
|
});
|
||||||
|
})
|
||||||
|
.catch(function (e) {
|
||||||
|
note.textContent = (e && e.message) || (en() ? 'Failed' : '실패');
|
||||||
|
})
|
||||||
|
.then(function () { btn.disabled = false; });
|
||||||
|
};
|
||||||
|
})();
|
||||||
|
|
||||||
// ── 받는 사람 찾기(이름/주문/패키지/송장 번호 부분 일치) ──
|
// ── 받는 사람 찾기(이름/주문/패키지/송장 번호 부분 일치) ──
|
||||||
(function () {
|
(function () {
|
||||||
var wrap = document.getElementById('dsp-search');
|
var wrap = document.getElementById('dsp-search');
|
||||||
|
|||||||
@@ -0,0 +1,91 @@
|
|||||||
|
"""기간별 발송 수량 엑셀(export.aggregate_shipped / build_period_xlsx) 테스트.
|
||||||
|
|
||||||
|
DB 없이 집계·엑셀 생성만 검증한다.
|
||||||
|
python -m app.modules.dispatch.tests.test_period_export
|
||||||
|
또는 pytest 로 실행 가능.
|
||||||
|
"""
|
||||||
|
|
||||||
|
from __future__ import annotations
|
||||||
|
|
||||||
|
import io
|
||||||
|
|
||||||
|
from app.modules.dispatch import export
|
||||||
|
|
||||||
|
_ROWS = [
|
||||||
|
{"dispatch_date": "2026-10-02", "seller_sku": "MT-0320", "product_name": "A", "qty": 2},
|
||||||
|
{"dispatch_date": "2026-10-01", "seller_sku": "MT-0320_3", "product_name": "A", "qty": 1},
|
||||||
|
{"dispatch_date": "2026-10-01", "seller_sku": "mt-0320", "product_name": "A", "qty": 1},
|
||||||
|
{"dispatch_date": "2026-10-01", "seller_sku": "MY-0001", "product_name": "Set", "qty": 4},
|
||||||
|
{"dispatch_date": "2026-10-02", "seller_sku": "", "product_name": "", "qty": 9},
|
||||||
|
]
|
||||||
|
|
||||||
|
|
||||||
|
def test_aggregate_multiplier_and_merge():
|
||||||
|
"""_N 배수 반영 + 대소문자/접미사 다른 같은 코드 합산, 빈 코드 제외(BOM 없으면 세트 그대로)."""
|
||||||
|
dates, names, qty = export.aggregate_shipped(_ROWS, {"MT-0320": "상품A"})
|
||||||
|
assert dates == ["2026-10-01", "2026-10-02"], dates
|
||||||
|
assert qty[("2026-10-01", "MT-0320")] == 4 # 1×3 + 1
|
||||||
|
assert qty[("2026-10-02", "MT-0320")] == 2
|
||||||
|
assert qty[("2026-10-01", "MY-0001")] == 4
|
||||||
|
assert names["MT-0320"] == "상품A" # itemcode 이름 우선
|
||||||
|
assert names["MY-0001"] == "Set" # 없으면 파싱된 이름
|
||||||
|
|
||||||
|
|
||||||
|
_BOM = {"MY-0001": [
|
||||||
|
{"component_code": "MT-0320", "component_qty": 1},
|
||||||
|
{"component_code": "mt-0550", "component_qty": 2},
|
||||||
|
]}
|
||||||
|
|
||||||
|
|
||||||
|
def test_aggregate_explodes_sets():
|
||||||
|
"""세트는 BOM 으로 낱개 분해해 같은 날 같은 낱개 코드에 합산."""
|
||||||
|
dates, names, qty = export.aggregate_shipped(_ROWS, {"MT-0550": "상품B"}, _BOM)
|
||||||
|
assert ("2026-10-01", "MY-0001") not in qty
|
||||||
|
assert qty[("2026-10-01", "MT-0320")] == 8 # 1×3 + 1 + 세트 4×1
|
||||||
|
assert qty[("2026-10-01", "MT-0550")] == 8 # 세트 4×2
|
||||||
|
assert names["MT-0550"] == "상품B"
|
||||||
|
assert export.missing_set_boms(_ROWS, _BOM) == []
|
||||||
|
assert export.missing_set_boms(_ROWS, {}) == ["MY-0001"]
|
||||||
|
|
||||||
|
|
||||||
|
def test_build_period_xlsx_sheets():
|
||||||
|
from openpyxl import load_workbook
|
||||||
|
|
||||||
|
data = export.build_period_xlsx(
|
||||||
|
rows=_ROWS, date_from="2026-10-01", date_to="2026-10-02", name_map={}, set_bom=_BOM
|
||||||
|
)
|
||||||
|
wb = load_workbook(io.BytesIO(data))
|
||||||
|
assert wb.sheetnames == ["날짜별", "아이템별 요약", "세트별 요약"]
|
||||||
|
|
||||||
|
ws = wb["날짜별"]
|
||||||
|
rows = list(ws.iter_rows(values_only=True))
|
||||||
|
assert rows[0] == ("발송 날짜", "아이템 코드", "상품이름", "수량")
|
||||||
|
assert rows[1] == ("2026-10-01", "MT-0320", "A", 8)
|
||||||
|
assert rows[2] == ("2026-10-01", "MT-0550", None, 8)
|
||||||
|
assert rows[3] == ("2026-10-02", "MT-0320", "A", 2)
|
||||||
|
assert rows[-1][0] == "합계" and rows[-1][3] == 18
|
||||||
|
|
||||||
|
ws2 = wb["아이템별 요약"]
|
||||||
|
rows2 = list(ws2.iter_rows(values_only=True))
|
||||||
|
assert rows2[0] == ("아이템 코드", "상품이름", "2026-10-01", "2026-10-02", "합계")
|
||||||
|
assert rows2[1] == ("MT-0320", "A", 8, 2, 10)
|
||||||
|
assert rows2[2] == ("MT-0550", None, 8, None, 8)
|
||||||
|
assert rows2[3] == ("합계", None, 16, 2, 18)
|
||||||
|
|
||||||
|
# 세트는 낱개로 풀기 전 세트 단위 수량, 날짜 열은 전체 발송 날짜와 같다.
|
||||||
|
rows3 = list(wb["세트별 요약"].iter_rows(values_only=True))
|
||||||
|
assert rows3[0] == ("세트 코드", "상품이름", "2026-10-01", "2026-10-02", "합계")
|
||||||
|
assert rows3[1] == ("MY-0001", "Set", 4, None, 4)
|
||||||
|
assert rows3[2] == ("합계", None, 4, 0, 4)
|
||||||
|
|
||||||
|
|
||||||
|
def test_period_filename():
|
||||||
|
assert export.period_filename("2026-10-01", "2026-10-28") == "2026.10.01-2026.10.28_shipped_qty.xlsx"
|
||||||
|
|
||||||
|
|
||||||
|
if __name__ == "__main__":
|
||||||
|
test_aggregate_multiplier_and_merge()
|
||||||
|
test_aggregate_explodes_sets()
|
||||||
|
test_build_period_xlsx_sheets()
|
||||||
|
test_period_filename()
|
||||||
|
print("OK")
|
||||||
@@ -0,0 +1,4 @@
|
|||||||
|
# [경비] 개인경비 모듈 — `app/modules/expense/`, `expense_db`
|
||||||
|
|
||||||
|
> 이 모듈만 고칠 때 읽는 요약. 별도 상세 문서 없음 — 코드(`router.py`·`store.py`·`categories.py`)가 기준.
|
||||||
|
> 템플릿: `templates/`. DB 구성은 필요할 때만 `docs/DATABASES.md` 의 expense_db 절.
|
||||||
@@ -265,11 +265,11 @@ def expense_index(request: Request) -> HTMLResponse:
|
|||||||
get_current_user_record,
|
get_current_user_record,
|
||||||
render_template,
|
render_template,
|
||||||
)
|
)
|
||||||
from app.store import has_module, is_admin # noqa: WPS433
|
from app.store import has_module, is_admin, login_redirect # noqa: WPS433
|
||||||
|
|
||||||
user = get_current_user_record(request)
|
user = get_current_user_record(request)
|
||||||
if user is None:
|
if user is None:
|
||||||
return RedirectResponse(url="/login", status_code=303)
|
return login_redirect(request)
|
||||||
if not has_module(user, "expense"):
|
if not has_module(user, "expense"):
|
||||||
return render_template(
|
return render_template(
|
||||||
request,
|
request,
|
||||||
@@ -325,11 +325,11 @@ def pending_page(request: Request) -> HTMLResponse:
|
|||||||
get_current_user_record,
|
get_current_user_record,
|
||||||
render_template,
|
render_template,
|
||||||
)
|
)
|
||||||
from app.store import has_module, is_admin # noqa: WPS433
|
from app.store import has_module, is_admin, login_redirect # noqa: WPS433
|
||||||
|
|
||||||
user = get_current_user_record(request)
|
user = get_current_user_record(request)
|
||||||
if user is None:
|
if user is None:
|
||||||
return RedirectResponse(url="/login", status_code=303)
|
return login_redirect(request)
|
||||||
if not (is_admin(user) or has_module(user, "expense_approver")):
|
if not (is_admin(user) or has_module(user, "expense_approver")):
|
||||||
return render_template(
|
return render_template(
|
||||||
request,
|
request,
|
||||||
@@ -362,11 +362,11 @@ def reports_page(request: Request) -> HTMLResponse:
|
|||||||
get_current_user_record,
|
get_current_user_record,
|
||||||
render_template,
|
render_template,
|
||||||
)
|
)
|
||||||
from app.store import is_admin # noqa: WPS433
|
from app.store import is_admin, login_redirect # noqa: WPS433
|
||||||
|
|
||||||
user = get_current_user_record(request)
|
user = get_current_user_record(request)
|
||||||
if user is None:
|
if user is None:
|
||||||
return RedirectResponse(url="/login", status_code=303)
|
return login_redirect(request)
|
||||||
store = _store(request)
|
store = _store(request)
|
||||||
_require_db_store(store)
|
_require_db_store(store)
|
||||||
year_str = request.query_params.get("year") or str(now_kst().year)
|
year_str = request.query_params.get("year") or str(now_kst().year)
|
||||||
@@ -436,11 +436,11 @@ def approved_page(request: Request) -> HTMLResponse:
|
|||||||
get_current_user_record,
|
get_current_user_record,
|
||||||
render_template,
|
render_template,
|
||||||
)
|
)
|
||||||
from app.store import has_module, is_admin # noqa: WPS433
|
from app.store import has_module, is_admin, login_redirect # noqa: WPS433
|
||||||
|
|
||||||
user = get_current_user_record(request)
|
user = get_current_user_record(request)
|
||||||
if user is None:
|
if user is None:
|
||||||
return RedirectResponse(url="/login", status_code=303)
|
return login_redirect(request)
|
||||||
if not (is_admin(user) or has_module(user, "expense_approver")):
|
if not (is_admin(user) or has_module(user, "expense_approver")):
|
||||||
return render_template(
|
return render_template(
|
||||||
request,
|
request,
|
||||||
@@ -667,11 +667,11 @@ def settings_page(request: Request) -> HTMLResponse:
|
|||||||
get_current_user_record,
|
get_current_user_record,
|
||||||
render_template,
|
render_template,
|
||||||
)
|
)
|
||||||
from app.store import has_module, is_admin # noqa: WPS433
|
from app.store import has_module, is_admin, login_redirect # noqa: WPS433
|
||||||
|
|
||||||
user = get_current_user_record(request)
|
user = get_current_user_record(request)
|
||||||
if user is None:
|
if user is None:
|
||||||
return RedirectResponse(url="/login", status_code=303)
|
return login_redirect(request)
|
||||||
if not (is_admin(user) or has_module(user, "expense_approver")):
|
if not (is_admin(user) or has_module(user, "expense_approver")):
|
||||||
return render_template(
|
return render_template(
|
||||||
request,
|
request,
|
||||||
|
|||||||
@@ -0,0 +1,126 @@
|
|||||||
|
# [입출고] 입출고 관리 모듈 — `app/modules/inout/`, `inout_db`(2026-10-16)
|
||||||
|
|
||||||
|
> 이 모듈만 고칠 때 읽는 요약. 상세는 `docs/INOUT_MODULE.md`.
|
||||||
|
> 정적 파일: `app/static/inout.css`, `inout.js`. 템플릿: `templates/`.
|
||||||
|
> 상품은 `itemcode_db.single_items` 읽기 전용(`itemcode.py`). `APP_ENCRYPTION_KEY` 는 실적 모듈과 공유.
|
||||||
|
> 참고 모델: 이카운트 "발주 대비 미입고"·Odoo 분할 입고/종결.
|
||||||
|
|
||||||
|
## 발주 / 입고
|
||||||
|
|
||||||
|
- 본사 → 공장 제품 제작 발주(발주서 `PO-YYMMDD-NN`). 제품 = `itemcode_db.single_items` 단품만, 검색 `GET /inout/api/items`·저장 때 서버 재확인.
|
||||||
|
- 물류 입고를 여러 번 나눠 입력, 품목별 발주·입고·미입고.
|
||||||
|
- 미입고 현황(제품별 합계·발주별·지연).
|
||||||
|
- 발주 목록 상태 보기(진행 중·완료·종결·취소·전체)는 **사람마다 기억**(2026-11-04) — `inout_settings` 키 `list_status:{이메일}`(마이그레이션 없음, 005 미적용이면 기억만 안 함). 주소에 `status` 가 있으면 저장, 없으면 저장값, 그것도 없으면 진행 중.
|
||||||
|
- 발주 목록 **입고일** 열(2026-11-05, 입고 예정일과 발주 사이, `db.list_orders` `receipt_dates`) — 여러 날에 나눠 입고하면 칸 안에서 줄바꿈(오래된 날부터), 같은 날 여러 번은 한 번만, 입고 전 `-`.
|
||||||
|
- 발주 목록 거르기 줄(2026-11-05) — 상태·공장은 왼쪽, 발주일~[찾기]는 오른쪽(`.io-filter-right`).
|
||||||
|
- 발주 목록 표 머리글(2026-11-05, `.io-list-table`) = 가운데·굵게·`--text-caption` × 111% × 90%·회색 배경, 표 글자 전체도 원래의 90%. 미입고 현황 등 다른 표는 그대로.
|
||||||
|
- [남은 수량 모두 채우기]를 한 번 더 누르면(= [채운 수량 되돌리기]) 채우기 전 값으로(2026-10-19, `inout.js`).
|
||||||
|
- 초과 입고는 확인 화면 후 허용(트랜잭션 안에서 발주서 잠그고 판단, `confirm_over`).
|
||||||
|
- **전체 입고 완료(모든 품목 입고 ≥ 발주, 상태 done·over)면 더 입고 못 함**(2026-10-19) — 화면은 입고 칸·[입고 저장]·사진·[남은 수량 채우기]를 흐리게 disabled, 서버 `_add_receipt` 도 잠근 뒤 거절. 입고 기록을 지우면 다시 열림.
|
||||||
|
- 잔량 종결·취소(취소는 입고 없을 때만).
|
||||||
|
- 상태는 저장하지 않고 누적 입고로 계산(`store.order_status`).
|
||||||
|
- 모든 품목 입고완료·초과입고 = "✓ 전체 입고 완료"(초과면 "초과 포함", `order_badge`).
|
||||||
|
- 발주 삭제는 **수퍼관리자만**(발주 목록 🗑, `perms.super`, 입고·사진·메일 기록까지 CASCADE).
|
||||||
|
|
||||||
|
## 권한 / 옵션
|
||||||
|
|
||||||
|
- 권한키 `inout`(조회).
|
||||||
|
- **발주 담당·입고 담당·공장(담당자·연락처 따로, 002)은 모듈 옵션** — 상단 톱니 → 팝업(`/inout/settings?panel=1`, ERP 관리자, `inout_roles`·`inout_factories`). 관리자는 둘 다.
|
||||||
|
- 공용 `.erp-input`·`.erp-table-wrap` 겹침은 `.io` 안에서만 바로잡음.
|
||||||
|
- **입고 담당(발주 담당 아님)은 품목을 이름·발주 수량만**(`items_limited`), 옵션은 관리자만.
|
||||||
|
|
||||||
|
## 발주 메일 (003)
|
||||||
|
|
||||||
|
- 새 발주서 저장 → 미리보기 팝업(받는 사람 = 공장 이메일, 요약 표 본문) → 사람이 [메일 발송]을 눌러야 보냄.
|
||||||
|
- **발주 담당 본인 Gmail**(Gmail API `gmail.send`, 사람마다 [Gmail 연결] 1회 — 고른 구글 계정 = ERP 계정 확인). 갱신 토큰은 `APP_ENCRYPTION_KEY` AES-GCM 암호문(`gmail.py`).
|
||||||
|
**휴가 모듈도 같은 연결을 쓴다**(2026-10-27) — 휴가 옵션 [Gmail 연결]은 세션 `_gmail_origin=vacation` 을 달고 같은 콜백(`/inout/gmail/callback`)으로 돌아오며,
|
||||||
|
콜백이 `_gmail_callback_vacation`(휴가 권한 확인, 휴가 옵션으로 복귀)으로 넘긴다. 토큰 표·끊기는 공용 — 바꾸면 휴가 메일(`vacation/notify.py`)도 확인.
|
||||||
|
- 보낸 기록·재발송 확인.
|
||||||
|
- **본문 고치기**(2026-10-27): 발주 메일 미리보기 iframe 이 `designMode`(sandbox `allow-same-origin`, 스크립트 없음) — 고치면 [원래 본문으로]·닫을 때 확인,
|
||||||
|
보낼 때만 `html` 을 함께 POST → `store.clean_mail_html`(허용 태그·표·인라인 서식만, url()·이벤트·스크립트 제거) + 글 버전 `mail_html_to_text`. 안 고치면 서버 본문 그대로. 입고 요청 메일은 고치기 없음(cid 사진).
|
||||||
|
**서식 막대**(`initMail` 안 `RTE_BAR`, 안내문 발송 편집기와 같은 구성: 크기·굵게·기울임·밑줄·취소선·글자/배경 색·정렬·목록·링크·서식 지우기·되돌리기) = iframe `execCommand`(styleWithCSS → span style).
|
||||||
|
Quill 은 표를 못 담아 안 씀. 크기는 fontSize 7 → px span 으로 바꿔 끼움. 선택은 본문 문서의 현재 선택 우선(막대 mousedown 때 기억은 대비용). 서버는 `text-decoration-line` → `text-decoration`.
|
||||||
|
- **입고 담당 발주 알림 자동 발송**(2026-10-19): 발주 메일이 나가면 같은 Gmail 로 옵션 → 담당자의 입고 담당들에게 따로 보냄 — 제목은 발주 메일과 같고 내용은 발주번호·발주일·제품 코드·제품명·수량만(`store.order_notice_mail`, `router._send_order_notice`). 실패해도 공장 메일은 그대로(안내만), 미리보기 창에 받을 사람 안내.
|
||||||
|
- **참조 기본값 `king@dbxcorp.co.kr`**(2026-10-19) — 미리보기 참조 칸에 미리 들어감, 옵션 → 공장 탭 "발주 메일 참조"에서 고침(`inout_settings` `order_mail_cc`, 행이 없으면 기본값 — 저장만 005 필요).
|
||||||
|
|
||||||
|
- **간단 발주 메일**(2026-11-04): 공장 이름에 "대성화학"·"인천공장"이 들어가면(`store.SIMPLE_MAIL_FACTORIES`, 띄어쓰기 무시) 품목 표 = 번호·제품 코드·제품명·수량·**박스당 수량·박스 수**·비고만, 요약 표·글 본문에서도 금액·무게·PP·은을 뺀다(단가가 공장에 나가지 않게). 색상 줄 배경·합계 수량은 그대로.
|
||||||
|
박스 값은 발주 품목 사본이 아니라 **메일을 만들 때의 상품 정보**(`router._mail_order` → `store.line_boxes`, 뚜껑 있으면 통·뚜껑 따로, 입수 없으면 `-`). 다른 공장 메일엔 박스 칸 없음.
|
||||||
|
|
||||||
|
## 입고 요청 메일 (005, 2026-10-19)
|
||||||
|
|
||||||
|
- 입고 담당이 **입고 저장** → 발주서 화면 `?rmail={입고 id}` 로 미리보기 팝업이 바로 뜸 → [메일 발송](입고 담당 본인 Gmail, 발주 메일과 같은 연결 — Gmail 연결 권한은 발주·입고 담당 `_require(…, "mail")`). 입고 기록 줄 [보내기/다시 보내기]로 언제든.
|
||||||
|
- 받는 사람 = 옵션 → **물류센터** 탭 담당자 이메일(`inout_settings` `logistics_emails`), 참조 기본 = `receipt_mail_cc`(005 가 `king@dbxcorp.co.kr, bj@dbxcorp.co.kr` 넣음). 창에서 고칠 수 있음.
|
||||||
|
- 제목 `[입고 요청] yyyy년 mm월 dd일(요일) 입고 요청 합니다.`(입고일) · 본문 "입고된 아래 리스트 상품을 전산 등록 부탁드립니다." + 표(상품 이름·상품 코드·입고 수량·비고 = 발주 품목 줄 메모, 합계) + 메모 + **맨 아래 입고증 사진 = 본문 안 이미지**(CID `multipart/related`, 첨부 아님 — `gmail.build_message(inline_images=)`), 서버가 가로 600px 이하·비율 유지 JPEG 로 줄임(`store.mail_images`, EXIF 회전 반영, HEIC 는 빼고 안내). 미리보기는 cid → data: 로 바꿔 보여 줌.
|
||||||
|
- 보낸 기록 `inout_receipt_mails`(입고 지우면 CASCADE), 이미 보낸 입고는 `resend` 확인.
|
||||||
|
|
||||||
|
## 사방넷 입고 파일 (2026-10-19, 마이그레이션 없음)
|
||||||
|
|
||||||
|
- 입고 기록 줄 [사방넷 입고 파일](엑셀 초록 `#217346`) → `GET /inout/orders/{id}/receipts/{rid}/sabangnet.xlsx`(발주·입고 담당). 1행 제목 **A 상품코드 · B 가용수량 · C 불용수량**,
|
||||||
|
A = 코드표 `single_items.sabangnet_code`(`itemcode.sabangnet_codes`), B = 입고 수량, **C = 수량이 아니라 상품 이름**(사용자 지정). A·C 는 글자 칸(앞자리 0 보존).
|
||||||
|
- 사방넷 코드가 빈 품목이 있거나 코드표를 못 읽으면 파일을 만들지 않고 발주서로 돌아가 품목을 알려 준다(빈 칸 업로드 방지). 파일 이름 `사방넷_입고_{입고일}_{발주번호}.xlsx`.
|
||||||
|
|
||||||
|
## 입고증 사진 (003)
|
||||||
|
|
||||||
|
- 입고 저장 때 첨부(브라우저가 2000px JPEG 로 줄임, 10장·10MB, 파일 머리 검사, 입고와 한 트랜잭션, bytea).
|
||||||
|
- 썸네일·크게 보기·나중에 더하기. 초과 확인은 브라우저가 먼저(사진 유지).
|
||||||
|
- **돌리기**(2026-11-02) — 크게 보기 창 왼쪽·오른쪽 버튼(입고 담당) → `POST /inout/orders/{id}/photos/{pid}/rotate?degrees=90|270` → 서버가 **저장된 사진 자체**를 돌려 덮어씀(`store.rotate_image`, EXIF 회전을 픽셀에 반영, 같은 형식, JPEG 품질 92) — 원본 링크·입고 요청 메일도 돌린 사진. 되돌리기 = 반대로 돌리기. HEIC·움직이는 GIF 는 못 돌림(HEIC 은 버튼 숨김).
|
||||||
|
사진 응답은 `no-cache` + ETag(돌린 뒤 예전 사진이 캐시에 남지 않게).
|
||||||
|
|
||||||
|
## 상품 정보 (004, 옵션 세 번째 탭)
|
||||||
|
|
||||||
|
- 테이블 `inout_products`·`inout_products_excluded`.
|
||||||
|
- [단품 불러오기] = 코드표 단품 → 목록(값을 넣은 상품은 그대로·지운 단품은 다음에도 빠짐, 제외 목록에서 되살리기).
|
||||||
|
- 단가(원)·무게(개당 g = PP량)·은(Ag) 함유량(%) 수기 입력(은 g = 무게 × % 자동).
|
||||||
|
- 한 번 불러오면 발주서 제품은 이 목록에서. 발주 품목에 그때 값 사본(`unit_price`·`weight_g`·`silver_pct`).
|
||||||
|
- 발주서·메일에 금액(수량 × 단가)·PP·은 함유량과 합계.
|
||||||
|
- 발주서 화면 품목 표(`.io-items-table`, 2026-10-21): 제목 행 검정·굵게·가운데, 합계 줄 검정·굵게·제목 크기, "합계" = 1~3열 가운데.
|
||||||
|
열 **PP 사용량**·**은(Ag) 함유량** = 발주 수량 전체 사용량 kg(`store.line_usage` — 메일 표와 같은 값), 아래 작은 글씨 = 개당 g·%.
|
||||||
|
- **합계 줄(발주서 화면·발주 메일 표 같음)**: 금액 뒤 " 원", 무게 뒤 " kg", 무게는 소수 첫째 자리에서 반올림(정수 kg). 줄 값·메일 요약 표는 예전 자릿수 그대로.
|
||||||
|
- **발주 메일 표**(2026-10-19, `store.order_mail`): 전체 무게(kg) = 개당 g × 수량 · **PP 사용량(kg)** = 전체 무게 − 은 무게(은 함유량 왼쪽 열) · 은(Ag) 함유량 = `30% (76.5kg)`(괄호 = 전체 무게 × %, kg 소수 넷째). 합계 줄·요약(전체 무게·PP 사용량·은 총량)도 kg. 첫 요약 표는 항목·값 두 쌍씩 4열(4×4), 요청 사항은 맨 아래 한 줄 전체. 발주서 화면 표는 예전 그대로(PP g/개).
|
||||||
|
|
||||||
|
## 상품 그룹·색상 (006, 2026-10-21)
|
||||||
|
|
||||||
|
- 옵션 **상품 그룹** 탭(2026-10-21 상품 정보 탭에서 분리) = 그룹 표(`inout_product_groups`: 이름·은 함유량·색상·순서, `POST /inout/settings/groups`·`…/{id}/delete`).
|
||||||
|
상품 줄 **그룹** 고르기 → 그 상품의 은 함유량·색상 = 그룹 값(자기 값 칸은 숨김·보존, 그룹 지우면 자기 값으로). 그룹 없는 상품은 상품마다.
|
||||||
|
계산은 `db._PRODUCT_SELECT_006`(silver_pct·color = 그룹 적용 값, own_* = 자기 값) 한 곳 — 목록·발주서 제품 고르기·발주 품목 사본이 같은 값.
|
||||||
|
- 색상 = 색없음·오렌지·파랑·회색·아이보리색(`store.COLORS` 키 none·orange·blue·gray·ivory → 이름·칸 색), 화면은 색 사각형 + 이름(`_macros.swatch`).
|
||||||
|
- 발주 품목에 그때 색상 사본(`inout_order_lines.color`, 006 전 품목 NULL = 지금 상품 색상). **발주 메일 품목 표에서 색상 있는 품목 줄 전체 배경 = 그 색**(tr + 칸마다).
|
||||||
|
- 006 확인(`groups_ready`)은 연결을 열기 **전에** — 미적용이면 1분 기억(발주 저장 트랜잭션 안에서 두 번째 연결을 잡아 동시 발주에서 풀이 바닥났었다).
|
||||||
|
- 옵션 → 담당자 = 아이콘(구글 프로필 사진, 없으면 기본 아이콘) + 이름, 아래 이메일.
|
||||||
|
|
||||||
|
## 박스 입수·파렛트 (007, 2026-10-21)
|
||||||
|
|
||||||
|
- 옵션 → 상품 정보 **통 수량(박스)**·**뚜껑 수량(박스)** = 통·뚜껑이 한 박스에 몇 개(`inout_products.body_per_box`·`lid_per_box`, 1 이상 정수, 뚜껑 없으면 빈칸,
|
||||||
|
`store.validate_box_values`). 상품 정보 표 제목 행 = 가운데·굵게·13.2px(예전 12px × 110%).
|
||||||
|
- **새 발주서** 줄마다 "통·뚜껑 박스" 칸(`inout.js boxCell`) = 통 ⌈수량 ÷ 통 입수⌉박스 · 뚜껑 ⌈수량 ÷ 뚜껑 입수⌉박스, 힌트 = 통·뚜껑 입수의 **최소공배수**(둘 다 꽉 차는 수량 단위,
|
||||||
|
뚜껑 없으면 통 입수)와 지금 수량에 가까운 그 배수(누르면 수량 칸에), 배수면 "✓ 꽉 찹니다". 합계 줄 = 통·뚜껑·전체 박스 → **파렛트 ⌈전체 박스 ÷ 30⌉**(`store.PALLET_BOXES`) + 마지막 파렛트 박스 수.
|
||||||
|
- 수량 칸 오른쪽 **◀ ▶** = 공배수(`unitOf`)만큼 줄이기·늘리기 — 배수가 아니면 가까운 아래/위 배수로, 0 이면 빈칸. 제품을 안 골랐거나 입수가 없으면 못 누름.
|
||||||
|
- 합계 줄 파렛트 그림(`palletSvg`·`palletVis`, 6열 × 5행 박스 + 받침대) = 꽉 찬 파렛트(최대 10개 + "+N") · 잔량 파렛트(실린 박스만 색칠, 몇 %·몇 박스 더 실으면 한 파렛트), 딱 맞으면 "✓ 모든 파렛트가 꽉 찹니다".
|
||||||
|
- 품목 표 제목 행 = 가운데·굵게·`--text-caption` × 110%.
|
||||||
|
- 화면 계산만 — 발주 품목 사본·발주서 화면·**발주 메일에는 넣지 않음**(사용자 지정). 값은 지금 상품 정보(`_form_page` 의 `body_per_box`, `/api/items`).
|
||||||
|
- 007 확인 `db.boxes_ready`(groups_ready 와 같은 방식 — 연결 열기 전, 미적용 1분 기억). 그룹·색상 조회(`_PRODUCT_SELECT_006`)는 `p.*` 라 새 열이 따라온다.
|
||||||
|
|
||||||
|
## 봉투·백 (008, 2026-11-04)
|
||||||
|
|
||||||
|
- 이름에 **"미라클 봉투"·"미라클백"** 이 들어간 상품(`store.is_bag`, 저장 안 함 — 이름으로 판단) = 옵션 → 상품 정보에서 일반 상품과 **표를 나눔**(봉투·백 표가 위). 칸: **박스당 수량**(`body_per_box` 재사용)·**1파렛트당 박스 수량**(`inout_products.boxes_per_pallet`). 뚜껑 없음(저장하면 `lid_per_box` 는 NULL).
|
||||||
|
**단가·무게·은 칸 없음**(2026-11-04 사용자 지정) — 전에 넣은 값은 줄의 숨은 칸으로 저장 때 그대로 보내 지우지 않음. 그룹·색상 칸은 있음. 새 발주서 "단가 없는 N종"·발주서 화면과 발주 메일의 "단가 미입력 N종"(`store.order_totals`) 안내에서 봉투·백은 뺌.
|
||||||
|
- 새 발주서 합계 줄에 봉투·백 박스·파렛트를 **통·뚜껑과 따로** 표시: 파렛트 = ⌈Σ(박스 ÷ 그 상품 1파렛트 박스)⌉. 파렛트 그림도 통처럼(`palletVis(all, cap, mixed)`, 그림 칸은 60칸까지) — 1파렛트 박스 수가 다른 상품이 섞이면 가장 큰 값으로 환산해 잔량은 %만. 입수·1파렛트 값은 `store.box_info`(`_form_page`·`/api/items`).
|
||||||
|
- 008 확인 `db.bags_ready`(boxes_ready 와 같은 방식). 미적용이면 모두 일반 상품으로 동작.
|
||||||
|
|
||||||
|
## 오른쪽 달력 (2026-10-21)
|
||||||
|
|
||||||
|
- 입출고 **모든 화면** 2열(`.io-split` = 왼쪽 `section.io` | 오른쪽 `_calendar.html`, 1100px 미만은 한 열 270px). 스크롤해도 위에 붙음.
|
||||||
|
달력 크기 = 화면에 따라 270~396px(`clamp(270px, 20.7vw, 396px)`, 2026-11-05 90% 로 줄임, 높이 ×320/300) — 입출고 화면만 ERP 공용 최대 폭 1550px 를 풀어 넓은 화면 여백을 씀(2026-10-21 "여백이 많다, 더 키워 달라").
|
||||||
|
글자·칸은 달력 너비 기준 `cqw`(300px 일 때 1cqw = 3px)라 같은 비율로 커진다 — 새 크기 값도 px 대신 cqw 로.
|
||||||
|
- 프로젝트 달력 모양(일요일 시작·요일 줄 회색·오늘 검은 동그라미·토 파랑·일/공휴일 빨강 — 공휴일 표는 `project.store.holiday_name` 재사용).
|
||||||
|
공휴일 이름은 숫자 아래 한 줄(`.io-cal-hol`, 8.5px — 5글자까지 다 보임, 더 길면 … + 말풍선에 전체 이름).
|
||||||
|
- 날짜 칸 = 발주(발주일, 파랑)·입고(입고일, 초록) 건수(취소된 발주 제외), 누르면 그날 목록 팝업 → 발주서. 달 이동은 새로고침 없이 `GET /inout/api/calendar?month=YYYY-MM`(`db.calendar`).
|
||||||
|
- **메뉴를 옮겨도 달력은 다시 그리지 않음**(2026-10-21) — 마지막 달력(달·API 응답 글·칸 HTML)을 sessionStorage `io_cal_v1` 에 두고 `_calendar.html` 인라인 스크립트가 그리기 전에 붙임,
|
||||||
|
`inout.js` 는 서버 값을 다시 받아 **글이 달라졌을 때만** 다시 그린다(보던 달도 유지). `CAL_KEY` 는 `initCalendar` 안에 — 바깥 const 면 위에서 먼저 부를 때 TDZ 로 복원이 조용히 꺼진다.
|
||||||
|
|
||||||
|
## 시각 / 날짜
|
||||||
|
|
||||||
|
- 시각은 DB 시간대와 무관하게 KST 로 읽음(`db._KstTimestamptzLoader`).
|
||||||
|
- 날짜 서식은 모두 `yyyy.mm.dd(요일)`(`ymd`·`ymdhm` 매크로, `store.fmt_date`).
|
||||||
|
- **날짜 칸 = ERP 공용 달력**(2026-11-05, `erp-datepop`, `_datepop.html` + `inout.js` 머리) — 발주 목록 기간·발주일·입고 예정일·입고일. `input[type=date]` 는 숨긴 값 저장소(폼 전송 그대로), 국경일·대체공휴일 빨강·이름 + 마우스를 올리면 이름(`title`, 표 = `project.store.KR_HOLIDAYS`, `router._date_holidays`).
|
||||||
|
필수 칸은 [지우기] 없음(숨긴 required 칸이 비면 브라우저가 안내 없이 저장을 막는다), 잠긴 입고일은 버튼도 disabled. 테스트 `tests/js/inout_datepop.browser.test.js`(`render_inout.py`).
|
||||||
@@ -0,0 +1,32 @@
|
|||||||
|
"""입출고 관리(inout) 모듈 — 본사 → 공장 제품 제작 발주, 물류 입고(분할), 발주 대비 미입고·초과 관리.
|
||||||
|
|
||||||
|
- 라우터: `router.py` (prefix=/inout)
|
||||||
|
- 저장소: `db.py` (inout_db / PostgreSQL) + `store.py` (상태·검사, 순수 함수)
|
||||||
|
- 제품: `itemcode.py` — itemcode_db.single_items(단품) 읽기 전용(ITEMCODE_DB_URL 재사용)
|
||||||
|
- 템플릿: `templates/inout/`, 화면 스크립트·스타일 `static/inout.{js,css}`
|
||||||
|
|
||||||
|
INOUT_DB_URL 미설정이면 build_inout_store 가 None → 라우터가 "설정 필요" 안내(앱은 죽지 않음).
|
||||||
|
권한: 모듈 권한키 `inout`(조회), 발주 담당·입고 담당은 모듈 옵션(inout_roles)에서 지정, ERP 관리자는 둘 다 + 옵션.
|
||||||
|
상세 docs/INOUT_MODULE.md.
|
||||||
|
"""
|
||||||
|
|
||||||
|
from typing import Any
|
||||||
|
|
||||||
|
from .router import router
|
||||||
|
|
||||||
|
__all__ = ["router", "build_inout_store", "build_inout_items"]
|
||||||
|
|
||||||
|
|
||||||
|
def build_inout_store(*, dsn: str | None) -> Any:
|
||||||
|
if not dsn:
|
||||||
|
return None
|
||||||
|
from .db import InoutDBStore # 지연 import
|
||||||
|
|
||||||
|
return InoutDBStore(dsn)
|
||||||
|
|
||||||
|
|
||||||
|
def build_inout_items() -> Any:
|
||||||
|
"""코드표 단품 리더(ITEMCODE_DB_URL). 미설정이면 enabled=False."""
|
||||||
|
from .itemcode import SingleItemReader # 지연 import
|
||||||
|
|
||||||
|
return SingleItemReader()
|
||||||
@@ -0,0 +1,892 @@
|
|||||||
|
"""inout_db PostgreSQL 저장소 — 공장·담당자·발주서·입고.
|
||||||
|
|
||||||
|
- 드라이버: psycopg 3 + pool(다른 모듈과 같은 패턴), 연결 `INOUT_DB_URL`. 스키마는 scripts/sql/inout_db_init.sql(앱이 만들지 않음).
|
||||||
|
- 상태(발주·부분입고·입고완료·초과·종결·취소)는 저장하지 않고 품목별 누적 입고로 계산한다(store.order_status) — 어긋날 일이 없다.
|
||||||
|
- 쓰기는 한 트랜잭션. 입고 저장은 발주서 행을 잠그고(FOR UPDATE) 그 안에서 누적 입고를 다시 읽어 초과를 판단한다
|
||||||
|
(두 사람이 동시에 입고해도 초과 확인을 건너뛰지 않게).
|
||||||
|
"""
|
||||||
|
|
||||||
|
from __future__ import annotations
|
||||||
|
|
||||||
|
import time
|
||||||
|
from datetime import date, datetime
|
||||||
|
from typing import Any
|
||||||
|
|
||||||
|
from psycopg.errors import UndefinedColumn, UndefinedTable, UniqueViolation
|
||||||
|
from psycopg.rows import dict_row
|
||||||
|
from psycopg.types.datetime import TimestamptzLoader
|
||||||
|
from psycopg_pool import ConnectionPool
|
||||||
|
|
||||||
|
from app.timezone import KST
|
||||||
|
|
||||||
|
from . import store
|
||||||
|
|
||||||
|
|
||||||
|
_SCAN_LIMIT = 20000 # 목록에서 상태 거르기 전에 읽는 발주서 상한
|
||||||
|
|
||||||
|
# 상품 정보 + 그룹(006) — 그룹 상품은 그룹의 은 함유량·색상, 그룹 없는 상품은 자기 값(own_*).
|
||||||
|
# p.* 다음에 같은 이름(silver_pct·color)을 다시 고르면 dict_row 는 뒤의 값(그룹 적용 값)을 쓴다. p.* 라 007 박스 입수 등 새 열도 따라온다.
|
||||||
|
_PRODUCT_SELECT_006 = (
|
||||||
|
"SELECT p.*, g.name AS group_name, p.silver_pct AS own_silver_pct, COALESCE(p.color, 'none') AS own_color, "
|
||||||
|
"CASE WHEN g.id IS NULL THEN p.silver_pct ELSE g.silver_pct END AS silver_pct, "
|
||||||
|
"CASE WHEN g.id IS NULL THEN COALESCE(p.color, 'none') ELSE g.color END AS color "
|
||||||
|
"FROM inout_products p LEFT JOIN inout_product_groups g ON g.id = p.group_id"
|
||||||
|
)
|
||||||
|
|
||||||
|
|
||||||
|
class OverReceipt(Exception):
|
||||||
|
"""확인 없이 발주보다 많이 입고하려 함 — over = [{item_code, item_name, ordered, after, over}]."""
|
||||||
|
|
||||||
|
def __init__(self, over: list[dict[str, Any]]) -> None:
|
||||||
|
super().__init__("초과 입고")
|
||||||
|
self.over = over
|
||||||
|
|
||||||
|
|
||||||
|
def _norm_email(e: str) -> str:
|
||||||
|
return (e or "").strip().lower()
|
||||||
|
|
||||||
|
|
||||||
|
class _KstTimestamptzLoader(TimestamptzLoader):
|
||||||
|
"""TIMESTAMPTZ → 한국 시각(KST) datetime. 화면·메일에 찍는 시각(입력·보낸 시각 등)이 DB 서버 시간대(보통 UTC)와 무관하게."""
|
||||||
|
|
||||||
|
def load(self, data: Any) -> datetime:
|
||||||
|
return super().load(data).astimezone(KST)
|
||||||
|
|
||||||
|
|
||||||
|
def _kst_session(conn: Any) -> None:
|
||||||
|
# 세션 시간대(SET TIME ZONE)는 쓰지 않는다 — 'Asia/Seoul' 은 시간대 자료가 없는 서버에서 접속이 실패하고,
|
||||||
|
# 고정 오프셋은 psycopg 가 못 읽어 UTC 로 돌아간다. 읽을 때 파이썬에서 바꾼다.
|
||||||
|
conn.adapters.register_loader("timestamptz", _KstTimestamptzLoader)
|
||||||
|
|
||||||
|
|
||||||
|
class InoutDBStore:
|
||||||
|
def __init__(self, dsn: str, *, min_size: int = 1, max_size: int = 5):
|
||||||
|
self._pool = ConnectionPool(conninfo=dsn, min_size=min_size, max_size=max_size,
|
||||||
|
kwargs={"row_factory": dict_row, "autocommit": True}, configure=_kst_session, open=False)
|
||||||
|
self._pool.open(wait=False)
|
||||||
|
|
||||||
|
def close(self) -> None:
|
||||||
|
self._pool.close()
|
||||||
|
|
||||||
|
# ════════════════════════════════════════════════════════════
|
||||||
|
# 공장
|
||||||
|
# ════════════════════════════════════════════════════════════
|
||||||
|
def list_factories(self, *, include_inactive: bool = False) -> list[dict[str, Any]]:
|
||||||
|
where = "" if include_inactive else "WHERE f.is_active"
|
||||||
|
with self._pool.connection() as conn:
|
||||||
|
return conn.execute(
|
||||||
|
"SELECT f.*, (SELECT count(*) FROM inout_orders o WHERE o.factory_id = f.id) AS order_count "
|
||||||
|
f"FROM inout_factories f {where} ORDER BY f.is_active DESC, f.sort_order, f.name"
|
||||||
|
).fetchall()
|
||||||
|
|
||||||
|
def save_factory(self, *, factory_id: int | None, name: str, manager: str = "", contact: str = "", email: str = "",
|
||||||
|
memo: str = "", is_active: bool = True, sort_order: int = 0) -> int:
|
||||||
|
"""공장 추가·수정. 담당자(manager, 002)·연락처(contact)·이메일(email, 003 — 여러 개는 쉼표)."""
|
||||||
|
name = (name or "").strip()
|
||||||
|
if not name or len(name) > 100:
|
||||||
|
raise ValueError("공장 이름을 1~100자로 입력하세요.")
|
||||||
|
emails = ", ".join(store.parse_emails(email, label="공장 이메일"))
|
||||||
|
vals = (name, (manager or "").strip()[:100], (contact or "").strip()[:200], emails, (memo or "").strip()[:store.MEMO_MAX],
|
||||||
|
bool(is_active), int(sort_order))
|
||||||
|
try:
|
||||||
|
with self._pool.connection() as conn:
|
||||||
|
dup = conn.execute("SELECT id FROM inout_factories WHERE lower(name) = lower(%s) AND id <> %s",
|
||||||
|
(name, factory_id or 0)).fetchone()
|
||||||
|
if dup:
|
||||||
|
raise ValueError(f"같은 이름의 공장이 이미 있습니다: {name}")
|
||||||
|
if factory_id:
|
||||||
|
row = conn.execute(
|
||||||
|
"UPDATE inout_factories SET name=%s, manager=%s, contact=%s, email=%s, memo=%s, is_active=%s, sort_order=%s "
|
||||||
|
"WHERE id=%s RETURNING id", (*vals, factory_id)).fetchone()
|
||||||
|
if not row:
|
||||||
|
raise ValueError("공장을 찾을 수 없습니다.")
|
||||||
|
return int(row["id"])
|
||||||
|
return int(conn.execute(
|
||||||
|
"INSERT INTO inout_factories (name, manager, contact, email, memo, is_active, sort_order) "
|
||||||
|
"VALUES (%s,%s,%s,%s,%s,%s,%s) RETURNING id", vals).fetchone()["id"])
|
||||||
|
except UndefinedColumn:
|
||||||
|
raise ValueError("DB 마이그레이션 inout_db 002·003(공장 담당자·이메일 칸)이 아직 적용되지 않았습니다.") from None
|
||||||
|
|
||||||
|
def delete_factory(self, factory_id: int) -> None:
|
||||||
|
"""발주 기록이 없는 공장만 지운다(있으면 '사용 안 함'으로 숨김)."""
|
||||||
|
with self._pool.connection() as conn:
|
||||||
|
used = conn.execute("SELECT 1 FROM inout_orders WHERE factory_id=%s LIMIT 1", (factory_id,)).fetchone()
|
||||||
|
if used:
|
||||||
|
raise ValueError("발주 기록이 있는 공장은 지울 수 없습니다 — '사용 안 함'으로 바꾸세요.")
|
||||||
|
conn.execute("DELETE FROM inout_factories WHERE id=%s", (factory_id,))
|
||||||
|
|
||||||
|
# ════════════════════════════════════════════════════════════
|
||||||
|
# 담당자(발주 담당·입고 담당)
|
||||||
|
# ════════════════════════════════════════════════════════════
|
||||||
|
def list_roles(self) -> dict[str, list[str]]:
|
||||||
|
out: dict[str, list[str]] = {r: [] for r in store.ROLES}
|
||||||
|
with self._pool.connection() as conn:
|
||||||
|
for r in conn.execute("SELECT email, role FROM inout_roles ORDER BY email").fetchall():
|
||||||
|
out.setdefault(r["role"], []).append(r["email"])
|
||||||
|
return out
|
||||||
|
|
||||||
|
def roles_of(self, email: str) -> set[str]:
|
||||||
|
with self._pool.connection() as conn:
|
||||||
|
rows = conn.execute("SELECT role FROM inout_roles WHERE email=%s", (_norm_email(email),)).fetchall()
|
||||||
|
return {r["role"] for r in rows}
|
||||||
|
|
||||||
|
def set_role_members(self, role: str, emails: list[str], *, by: str) -> None:
|
||||||
|
"""그 역할 담당자를 통째로 바꾼다(한 트랜잭션)."""
|
||||||
|
if role not in store.ROLES:
|
||||||
|
raise ValueError("알 수 없는 담당 종류입니다.")
|
||||||
|
clean = sorted({_norm_email(e) for e in emails if _norm_email(e)})
|
||||||
|
with self._pool.connection() as conn, conn.transaction():
|
||||||
|
conn.execute("DELETE FROM inout_roles WHERE role=%s AND NOT (email = ANY(%s))", (role, clean))
|
||||||
|
for e in clean:
|
||||||
|
conn.execute("INSERT INTO inout_roles (email, role, created_by) VALUES (%s,%s,%s) ON CONFLICT DO NOTHING",
|
||||||
|
(e, role, _norm_email(by)))
|
||||||
|
|
||||||
|
# ════════════════════════════════════════════════════════════
|
||||||
|
# 발주서
|
||||||
|
# ════════════════════════════════════════════════════════════
|
||||||
|
def _ready_flags(self) -> tuple[bool, bool]:
|
||||||
|
"""(004 상품 정보, 006 그룹·색상) — 발주 저장 트랜잭션을 열기 전에 확인해 _insert_line 에 넘긴다."""
|
||||||
|
return self.products_ready(), self.groups_ready()
|
||||||
|
|
||||||
|
def _insert_line(self, conn: Any, order_id: int, line_no: int, ln: dict[str, Any], names: dict[str, str],
|
||||||
|
specs: dict[str, dict[str, Any]], ready: tuple[bool, bool]) -> None:
|
||||||
|
"""발주 품목 한 줄 — 004 가 적용됐으면 상품 정보의 단가·무게·은 함유량을(006 이면 색상도) 그때 값으로 함께 남긴다."""
|
||||||
|
products_ok, groups_ok = ready
|
||||||
|
if groups_ok: # 006 — 색상 사본도(그룹 상품은 그룹 색상)
|
||||||
|
sp = specs.get(ln["item_code"]) or {}
|
||||||
|
conn.execute("INSERT INTO inout_order_lines (order_id, line_no, item_code, item_name, qty, memo, unit_price, weight_g, silver_pct, color) "
|
||||||
|
"VALUES (%s,%s,%s,%s,%s,%s,%s,%s,%s,%s)",
|
||||||
|
(order_id, line_no, ln["item_code"], names.get(ln["item_code"], ""), ln["qty"], ln["memo"],
|
||||||
|
sp.get("unit_price"), sp.get("weight_g"), sp.get("silver_pct"), sp.get("color") or "none"))
|
||||||
|
elif products_ok:
|
||||||
|
sp = specs.get(ln["item_code"]) or {}
|
||||||
|
conn.execute("INSERT INTO inout_order_lines (order_id, line_no, item_code, item_name, qty, memo, unit_price, weight_g, silver_pct) "
|
||||||
|
"VALUES (%s,%s,%s,%s,%s,%s,%s,%s,%s)",
|
||||||
|
(order_id, line_no, ln["item_code"], names.get(ln["item_code"], ""), ln["qty"], ln["memo"],
|
||||||
|
sp.get("unit_price"), sp.get("weight_g"), sp.get("silver_pct")))
|
||||||
|
else:
|
||||||
|
conn.execute("INSERT INTO inout_order_lines (order_id, line_no, item_code, item_name, qty, memo) VALUES (%s,%s,%s,%s,%s,%s)",
|
||||||
|
(order_id, line_no, ln["item_code"], names.get(ln["item_code"], ""), ln["qty"], ln["memo"]))
|
||||||
|
|
||||||
|
def create_order(self, data: dict[str, Any], names: dict[str, str], *, by: str,
|
||||||
|
specs: dict[str, dict[str, Any]] | None = None) -> dict[str, Any]:
|
||||||
|
"""data = store.validate_order 결과, names = {코드: 단품 이름}, specs = {코드: 상품 정보 행}(004). 반환 {id, order_no}."""
|
||||||
|
ready = self._ready_flags()
|
||||||
|
with self._pool.connection() as conn, conn.transaction():
|
||||||
|
self._require_factory(conn, data["factory_id"])
|
||||||
|
conn.execute("SELECT pg_advisory_xact_lock(hashtext('inout_order_no'))")
|
||||||
|
prefix = store.order_no(data["order_date"], 0)[:-2]
|
||||||
|
# 순번은 숫자로 비교 — 글자 max 면 "-99" 가 "-100" 보다 커서 100번째부터 같은 번호가 나온다
|
||||||
|
row = conn.execute("SELECT max(substr(order_no, %s)::int) AS m FROM inout_orders "
|
||||||
|
"WHERE order_no LIKE %s AND substr(order_no, %s) ~ '^[0-9]{1,9}$'",
|
||||||
|
(len(prefix) + 1, prefix + "%", len(prefix) + 1)).fetchone()
|
||||||
|
seq = (row["m"] or 0) + 1 if row else 1
|
||||||
|
no = store.order_no(data["order_date"], seq)
|
||||||
|
oid = conn.execute(
|
||||||
|
"INSERT INTO inout_orders (order_no, factory_id, order_date, due_date, memo, created_by, updated_by) "
|
||||||
|
"VALUES (%s,%s,%s,%s,%s,%s,%s) RETURNING id",
|
||||||
|
(no, data["factory_id"], data["order_date"], data["due_date"], data["memo"], _norm_email(by), _norm_email(by)),
|
||||||
|
).fetchone()["id"]
|
||||||
|
for i, ln in enumerate(data["lines"], start=1):
|
||||||
|
self._insert_line(conn, oid, i, ln, names, specs or {}, ready)
|
||||||
|
return {"id": int(oid), "order_no": no}
|
||||||
|
|
||||||
|
def update_order(self, order_id: int, data: dict[str, Any], names: dict[str, str], *, by: str,
|
||||||
|
specs: dict[str, dict[str, Any]] | None = None) -> None:
|
||||||
|
"""머리글·품목 고치기. 입고된 품목은 뺄 수 없다(입고 기록이 사라지므로) — 수량은 바꿀 수 있다.
|
||||||
|
이미 있던 품목의 단가 등 사본은 그대로(발주 당시 값), 새로 넣은 품목만 지금 상품 정보 값으로(004)."""
|
||||||
|
ready = self._ready_flags()
|
||||||
|
with self._pool.connection() as conn, conn.transaction():
|
||||||
|
head = self._lock_order(conn, order_id)
|
||||||
|
if head["cancelled_at"]:
|
||||||
|
raise ValueError("취소된 발주서는 고칠 수 없습니다.")
|
||||||
|
self._require_factory(conn, data["factory_id"], allow_inactive_id=head["factory_id"])
|
||||||
|
existing = {r["item_code"]: r for r in conn.execute(
|
||||||
|
"SELECT l.id, l.item_code, COALESCE(sum(rl.qty), 0) AS received FROM inout_order_lines l "
|
||||||
|
"LEFT JOIN inout_receipt_lines rl ON rl.order_line_id = l.id WHERE l.order_id=%s GROUP BY l.id",
|
||||||
|
(order_id,)).fetchall()}
|
||||||
|
wanted = {ln["item_code"] for ln in data["lines"]}
|
||||||
|
blocked = [c for c, r in existing.items() if c not in wanted and int(r["received"]) > 0]
|
||||||
|
if blocked:
|
||||||
|
raise ValueError("입고 기록이 있는 품목은 뺄 수 없습니다: " + ", ".join(sorted(blocked)))
|
||||||
|
for code, r in existing.items():
|
||||||
|
if code not in wanted:
|
||||||
|
conn.execute("DELETE FROM inout_order_lines WHERE id=%s", (r["id"],))
|
||||||
|
for i, ln in enumerate(data["lines"], start=1):
|
||||||
|
if ln["item_code"] in existing:
|
||||||
|
conn.execute("UPDATE inout_order_lines SET line_no=%s, qty=%s, memo=%s WHERE id=%s",
|
||||||
|
(i, ln["qty"], ln["memo"], existing[ln["item_code"]]["id"]))
|
||||||
|
else:
|
||||||
|
self._insert_line(conn, order_id, i, ln, names, specs or {}, ready)
|
||||||
|
conn.execute("UPDATE inout_orders SET factory_id=%s, order_date=%s, due_date=%s, memo=%s, updated_by=%s WHERE id=%s",
|
||||||
|
(data["factory_id"], data["order_date"], data["due_date"], data["memo"], _norm_email(by), order_id))
|
||||||
|
|
||||||
|
def set_closed(self, order_id: int, *, closed: bool, reason: str = "", by: str) -> None:
|
||||||
|
"""종결(남은 미입고를 더 기다리지 않음) / 종결 풀기."""
|
||||||
|
with self._pool.connection() as conn, conn.transaction():
|
||||||
|
head = self._lock_order(conn, order_id)
|
||||||
|
if head["cancelled_at"]:
|
||||||
|
raise ValueError("취소된 발주서입니다.")
|
||||||
|
if closed:
|
||||||
|
conn.execute("UPDATE inout_orders SET closed_at=now(), closed_by=%s, close_reason=%s, updated_by=%s WHERE id=%s",
|
||||||
|
(_norm_email(by), (reason or "").strip()[:store.MEMO_MAX], _norm_email(by), order_id))
|
||||||
|
else:
|
||||||
|
conn.execute("UPDATE inout_orders SET closed_at=NULL, closed_by='', close_reason='', updated_by=%s WHERE id=%s",
|
||||||
|
(_norm_email(by), order_id))
|
||||||
|
|
||||||
|
def cancel_order(self, order_id: int, *, by: str) -> None:
|
||||||
|
"""잘못 넣은 발주 — 입고 기록이 없을 때만 취소(기록은 남김)."""
|
||||||
|
with self._pool.connection() as conn, conn.transaction():
|
||||||
|
self._lock_order(conn, order_id)
|
||||||
|
if conn.execute("SELECT 1 FROM inout_receipts WHERE order_id=%s LIMIT 1", (order_id,)).fetchone():
|
||||||
|
raise ValueError("입고 기록이 있는 발주서는 취소할 수 없습니다 — 남은 수량은 '종결'하세요.")
|
||||||
|
conn.execute("UPDATE inout_orders SET cancelled_at=now(), cancelled_by=%s, updated_by=%s WHERE id=%s",
|
||||||
|
(_norm_email(by), _norm_email(by), order_id))
|
||||||
|
|
||||||
|
def delete_order(self, order_id: int) -> dict[str, Any]:
|
||||||
|
"""발주서 완전 삭제(수퍼관리자) — 품목·입고 기록·입고증 사진·메일 기록까지 함께(CASCADE). 되돌릴 수 없다.
|
||||||
|
반환 {order_no, receipts} — 화면 안내·로그용."""
|
||||||
|
with self._pool.connection() as conn, conn.transaction():
|
||||||
|
self._lock_order(conn, order_id)
|
||||||
|
n = conn.execute("SELECT count(*) AS n FROM inout_receipts WHERE order_id=%s", (order_id,)).fetchone()["n"]
|
||||||
|
row = conn.execute("DELETE FROM inout_orders WHERE id=%s RETURNING order_no", (order_id,)).fetchone()
|
||||||
|
return {"order_no": row["order_no"], "receipts": int(n)}
|
||||||
|
|
||||||
|
def get_order(self, order_id: int) -> dict[str, Any] | None:
|
||||||
|
with self._pool.connection() as conn:
|
||||||
|
head = conn.execute(
|
||||||
|
# 담당자(manager)는 002 열 — 미적용 DB 에서도 깨지지 않게 to_jsonb 로 읽는다
|
||||||
|
"SELECT o.*, f.name AS factory_name, to_jsonb(f) ->> 'manager' AS factory_manager, f.contact AS factory_contact, "
|
||||||
|
"COALESCE(to_jsonb(f) ->> 'email', '') AS factory_email "
|
||||||
|
"FROM inout_orders o JOIN inout_factories f ON f.id = o.factory_id WHERE o.id=%s",
|
||||||
|
(order_id,)).fetchone()
|
||||||
|
if not head:
|
||||||
|
return None
|
||||||
|
lines = conn.execute(
|
||||||
|
"SELECT l.*, COALESCE(sum(rl.qty), 0)::int AS received FROM inout_order_lines l "
|
||||||
|
"LEFT JOIN inout_receipt_lines rl ON rl.order_line_id = l.id WHERE l.order_id=%s "
|
||||||
|
"GROUP BY l.id ORDER BY l.line_no", (order_id,)).fetchall()
|
||||||
|
receipts = conn.execute("SELECT * FROM inout_receipts WHERE order_id=%s ORDER BY receipt_date, id",
|
||||||
|
(order_id,)).fetchall()
|
||||||
|
rlines = conn.execute(
|
||||||
|
"SELECT rl.receipt_id, rl.order_line_id, rl.qty, l.item_code, l.item_name FROM inout_receipt_lines rl "
|
||||||
|
"JOIN inout_order_lines l ON l.id = rl.order_line_id JOIN inout_receipts r ON r.id = rl.receipt_id "
|
||||||
|
"WHERE r.order_id=%s ORDER BY l.line_no", (order_id,)).fetchall()
|
||||||
|
# 입고증 사진(목록만 — 내용은 /inout/photos/{id})·발주 메일 기록 — 003 미적용이면 빈 목록
|
||||||
|
try:
|
||||||
|
photos = conn.execute(
|
||||||
|
"SELECT p.id, p.receipt_id, p.filename, p.content_type, p.size_bytes FROM inout_receipt_photos p "
|
||||||
|
"JOIN inout_receipts r ON r.id = p.receipt_id WHERE r.order_id=%s ORDER BY p.id", (order_id,)).fetchall()
|
||||||
|
mails = conn.execute("SELECT * FROM inout_order_mails WHERE order_id=%s ORDER BY sent_at, id", (order_id,)).fetchall()
|
||||||
|
except UndefinedTable:
|
||||||
|
photos, mails = [], []
|
||||||
|
# 입고 요청 메일 기록(005) — 미적용이면 빈 목록
|
||||||
|
try:
|
||||||
|
rmails = conn.execute(
|
||||||
|
"SELECT m.* FROM inout_receipt_mails m JOIN inout_receipts r ON r.id = m.receipt_id "
|
||||||
|
"WHERE r.order_id=%s ORDER BY m.sent_at, m.id", (order_id,)).fetchall()
|
||||||
|
except UndefinedTable:
|
||||||
|
rmails = []
|
||||||
|
by_rmail: dict[int, list[dict[str, Any]]] = {}
|
||||||
|
for m in rmails:
|
||||||
|
by_rmail.setdefault(int(m["receipt_id"]), []).append(m)
|
||||||
|
by_photo: dict[int, list[dict[str, Any]]] = {}
|
||||||
|
for ph in photos:
|
||||||
|
by_photo.setdefault(int(ph["receipt_id"]), []).append(ph)
|
||||||
|
by_receipt: dict[int, list[dict[str, Any]]] = {}
|
||||||
|
for r in rlines:
|
||||||
|
by_receipt.setdefault(int(r["receipt_id"]), []).append(r)
|
||||||
|
if any("color" in ln and ln["color"] is None for ln in lines): # 006 전 품목 = 지금 상품 색상
|
||||||
|
cur = self.catalog_lookup([ln["item_code"] for ln in lines if ln["color"] is None])
|
||||||
|
for ln in lines:
|
||||||
|
if ln.get("color") is None and ln["item_code"] in cur:
|
||||||
|
ln["color"] = cur[ln["item_code"]].get("color")
|
||||||
|
lines = store.decorate_lines(lines)
|
||||||
|
status = store.order_status(lines, closed=bool(head["closed_at"]), cancelled=bool(head["cancelled_at"]))
|
||||||
|
return {**head, "lines": lines, "summary": store.summarize(lines), "status": status,
|
||||||
|
"status_label": store.ORDER_LABELS[status],
|
||||||
|
"receipts": [{**r, "lines": by_receipt.get(int(r["id"]), []), "photos": by_photo.get(int(r["id"]), []),
|
||||||
|
"mails": by_rmail.get(int(r["id"]), []),
|
||||||
|
"total": sum(int(x["qty"]) for x in by_receipt.get(int(r["id"]), []))} for r in receipts],
|
||||||
|
"mails": mails}
|
||||||
|
|
||||||
|
def list_orders(self, *, status: str = "active", factory_id: int | None = None, q: str = "",
|
||||||
|
date_from: date | None = None, date_to: date | None = None, limit: int = 500) -> list[dict[str, Any]]:
|
||||||
|
"""목록 — 상태는 품목 합계로 계산한 뒤 거른다. q = 발주번호·제품 코드·제품 이름."""
|
||||||
|
where, params = ["TRUE"], []
|
||||||
|
if factory_id:
|
||||||
|
where.append("o.factory_id = %s")
|
||||||
|
params.append(factory_id)
|
||||||
|
if date_from:
|
||||||
|
where.append("o.order_date >= %s")
|
||||||
|
params.append(date_from)
|
||||||
|
if date_to:
|
||||||
|
where.append("o.order_date <= %s")
|
||||||
|
params.append(date_to)
|
||||||
|
if q.strip():
|
||||||
|
like = "%" + q.strip().replace("\\", "\\\\").replace("%", "\\%").replace("_", "\\_") + "%"
|
||||||
|
where.append("(o.order_no ILIKE %s OR EXISTS (SELECT 1 FROM inout_order_lines x WHERE x.order_id = o.id "
|
||||||
|
"AND (x.item_code ILIKE %s OR x.item_name ILIKE %s)))")
|
||||||
|
params += [like, like, like]
|
||||||
|
with self._pool.connection() as conn:
|
||||||
|
heads = conn.execute(
|
||||||
|
"SELECT o.*, f.name AS factory_name FROM inout_orders o JOIN inout_factories f ON f.id = o.factory_id "
|
||||||
|
# 상태는 품목 합계로 계산해 아래에서 거르므로 넉넉히 읽는다(발주서는 많아야 연 수천 건)
|
||||||
|
f"WHERE {' AND '.join(where)} ORDER BY o.order_date DESC, o.id DESC LIMIT {_SCAN_LIMIT}", params
|
||||||
|
).fetchall()
|
||||||
|
ids = [h["id"] for h in heads]
|
||||||
|
lines = conn.execute(
|
||||||
|
"SELECT l.order_id, l.item_code, l.item_name, l.qty, COALESCE(sum(rl.qty), 0)::int AS received "
|
||||||
|
"FROM inout_order_lines l LEFT JOIN inout_receipt_lines rl ON rl.order_line_id = l.id "
|
||||||
|
"WHERE l.order_id = ANY(%s) GROUP BY l.id ORDER BY l.line_no", (ids,)).fetchall() if ids else []
|
||||||
|
# 입고일 열 — 같은 날 여러 번 입고해도 날짜는 하나
|
||||||
|
receipts = conn.execute("SELECT DISTINCT order_id, receipt_date FROM inout_receipts WHERE order_id = ANY(%s) "
|
||||||
|
"ORDER BY order_id, receipt_date", (ids,)).fetchall() if ids else []
|
||||||
|
by_order: dict[int, list[dict[str, Any]]] = {}
|
||||||
|
for ln in lines:
|
||||||
|
by_order.setdefault(int(ln["order_id"]), []).append(ln)
|
||||||
|
receipt_dates: dict[int, list[date]] = {}
|
||||||
|
for r in receipts:
|
||||||
|
receipt_dates.setdefault(int(r["order_id"]), []).append(r["receipt_date"])
|
||||||
|
allowed = store.STATUS_FILTERS.get(status, store.STATUS_FILTERS["active"])[1]
|
||||||
|
out = []
|
||||||
|
for h in heads:
|
||||||
|
ls = by_order.get(int(h["id"]), [])
|
||||||
|
st = store.order_status(ls, closed=bool(h["closed_at"]), cancelled=bool(h["cancelled_at"]))
|
||||||
|
if st not in allowed:
|
||||||
|
continue
|
||||||
|
names = [x["item_name"] or x["item_code"] for x in ls]
|
||||||
|
out.append({**h, "status": st, "status_label": store.ORDER_LABELS[st], "summary": store.summarize(ls),
|
||||||
|
"receipt_dates": receipt_dates.get(int(h["id"]), []), "line_count": len(ls), "items_label": (names[0] + (f" 외 {len(names) - 1}종" if len(names) > 1 else "")) if names else ""})
|
||||||
|
if len(out) >= limit:
|
||||||
|
break
|
||||||
|
return out
|
||||||
|
|
||||||
|
# ════════════════════════════════════════════════════════════
|
||||||
|
# 입고
|
||||||
|
# ════════════════════════════════════════════════════════════
|
||||||
|
def add_receipt(self, order_id: int, quantities: dict[int, Any], *, receipt_date: Any, memo: Any,
|
||||||
|
confirm_over: bool, by: str, photos: list[dict[str, Any]] | None = None) -> dict[str, Any]:
|
||||||
|
"""입고 1건 저장. 발주를 넘는 품목이 있는데 confirm_over 가 아니면 OverReceipt(아무것도 저장 안 함).
|
||||||
|
photos = store.validate_photos 결과(입고증) — 입고와 한 트랜잭션(사진 저장이 실패하면 입고도 저장 안 함)."""
|
||||||
|
try:
|
||||||
|
return self._add_receipt(order_id, quantities, receipt_date=receipt_date, memo=memo,
|
||||||
|
confirm_over=confirm_over, by=by, photos=photos or [])
|
||||||
|
except UndefinedTable:
|
||||||
|
raise ValueError("DB 마이그레이션 inout_db 003(입고증 사진)이 아직 적용되지 않아 사진을 저장할 수 없습니다 — "
|
||||||
|
"사진 없이 저장하거나 관리자에게 알려 주세요.") from None
|
||||||
|
|
||||||
|
def _add_receipt(self, order_id: int, quantities: dict[int, Any], *, receipt_date: Any, memo: Any,
|
||||||
|
confirm_over: bool, by: str, photos: list[dict[str, Any]]) -> dict[str, Any]:
|
||||||
|
with self._pool.connection() as conn, conn.transaction():
|
||||||
|
head = self._lock_order(conn, order_id)
|
||||||
|
if head["cancelled_at"]:
|
||||||
|
raise ValueError("취소된 발주서에는 입고할 수 없습니다.")
|
||||||
|
if head["closed_at"]:
|
||||||
|
raise ValueError("종결된 발주서입니다 — 입고하려면 발주 담당이 종결을 풀어야 합니다.")
|
||||||
|
lines = conn.execute(
|
||||||
|
"SELECT l.id, l.item_code, l.item_name, l.qty, COALESCE(sum(rl.qty), 0)::int AS received "
|
||||||
|
"FROM inout_order_lines l LEFT JOIN inout_receipt_lines rl ON rl.order_line_id = l.id "
|
||||||
|
"WHERE l.order_id=%s GROUP BY l.id", (order_id,)).fetchall()
|
||||||
|
# 전체 입고 완료(모든 품목 입고 ≥ 발주)면 더 받지 않는다(2026-10-19) — 화면은 버튼을 막고, 서버도 거절(잠근 뒤 판단)
|
||||||
|
if lines and all(int(x["received"]) >= int(x["qty"]) for x in lines):
|
||||||
|
raise ValueError("전체 입고가 완료된 발주서입니다 — 더 입고할 수 없습니다(잘못 넣은 입고는 입고 기록에서 지운 뒤 다시 넣으세요).")
|
||||||
|
data = store.validate_receipt(lines, quantities, receipt_date=receipt_date, memo=memo)
|
||||||
|
if data["over"] and not confirm_over:
|
||||||
|
raise OverReceipt(data["over"])
|
||||||
|
rid = conn.execute("INSERT INTO inout_receipts (order_id, receipt_date, memo, created_by) VALUES (%s,%s,%s,%s) RETURNING id",
|
||||||
|
(order_id, data["receipt_date"], data["memo"], _norm_email(by))).fetchone()["id"]
|
||||||
|
for it in data["items"]:
|
||||||
|
conn.execute("INSERT INTO inout_receipt_lines (receipt_id, order_line_id, qty) VALUES (%s,%s,%s)",
|
||||||
|
(rid, it["order_line_id"], it["qty"]))
|
||||||
|
self._insert_photos(conn, int(rid), photos, by)
|
||||||
|
return {"id": int(rid), "over": data["over"], "total": sum(it["qty"] for it in data["items"]), "photos": len(photos)}
|
||||||
|
|
||||||
|
# ── 입고증 사진(003) ──
|
||||||
|
@staticmethod
|
||||||
|
def _insert_photos(conn: Any, receipt_id: int, photos: list[dict[str, Any]], by: str) -> None:
|
||||||
|
for ph in photos:
|
||||||
|
conn.execute("INSERT INTO inout_receipt_photos (receipt_id, filename, content_type, size_bytes, data, created_by) "
|
||||||
|
"VALUES (%s,%s,%s,%s,%s,%s)",
|
||||||
|
(receipt_id, ph["filename"], ph["content_type"], len(ph["data"]), ph["data"], _norm_email(by)))
|
||||||
|
|
||||||
|
def add_receipt_photos(self, order_id: int, receipt_id: int, files: list[tuple[str, bytes]], *, by: str) -> int:
|
||||||
|
"""이미 있는 입고에 사진 더하기(빠뜨렸을 때). 장수 한도는 잠근 뒤 다시 센다. 반환 = 더한 장수."""
|
||||||
|
try:
|
||||||
|
with self._pool.connection() as conn, conn.transaction():
|
||||||
|
head = self._lock_order(conn, order_id)
|
||||||
|
if head["cancelled_at"]:
|
||||||
|
raise ValueError("취소된 발주서입니다.")
|
||||||
|
if not conn.execute("SELECT 1 FROM inout_receipts WHERE id=%s AND order_id=%s", (receipt_id, order_id)).fetchone():
|
||||||
|
raise ValueError("입고 기록을 찾을 수 없습니다.")
|
||||||
|
have = int(conn.execute("SELECT count(*) AS n FROM inout_receipt_photos WHERE receipt_id=%s",
|
||||||
|
(receipt_id,)).fetchone()["n"])
|
||||||
|
photos = store.validate_photos(files, existing=have)
|
||||||
|
if not photos:
|
||||||
|
raise ValueError("올릴 사진을 고르세요.")
|
||||||
|
self._insert_photos(conn, receipt_id, photos, by)
|
||||||
|
return len(photos)
|
||||||
|
except UndefinedTable:
|
||||||
|
raise ValueError("DB 마이그레이션 inout_db 003(입고증 사진)이 아직 적용되지 않았습니다.") from None
|
||||||
|
|
||||||
|
def delete_receipt_photo(self, order_id: int, photo_id: int) -> None:
|
||||||
|
with self._pool.connection() as conn, conn.transaction():
|
||||||
|
self._lock_order(conn, order_id)
|
||||||
|
row = conn.execute("DELETE FROM inout_receipt_photos p USING inout_receipts r "
|
||||||
|
"WHERE p.id=%s AND p.receipt_id = r.id AND r.order_id=%s RETURNING p.id",
|
||||||
|
(photo_id, order_id)).fetchone()
|
||||||
|
if not row:
|
||||||
|
raise ValueError("사진을 찾을 수 없습니다.")
|
||||||
|
|
||||||
|
def rotate_receipt_photo(self, order_id: int, photo_id: int, degrees: int) -> None:
|
||||||
|
"""저장된 사진 자체를 돌린다(2026-11-02) — 화면·원본·입고 요청 메일 모두 돌린 사진."""
|
||||||
|
with self._pool.connection() as conn, conn.transaction():
|
||||||
|
head = self._lock_order(conn, order_id)
|
||||||
|
if head["cancelled_at"]:
|
||||||
|
raise ValueError("취소된 발주서입니다.")
|
||||||
|
row = conn.execute("SELECT p.data FROM inout_receipt_photos p JOIN inout_receipts r ON r.id = p.receipt_id "
|
||||||
|
"WHERE p.id=%s AND r.order_id=%s", (photo_id, order_id)).fetchone()
|
||||||
|
if not row:
|
||||||
|
raise ValueError("사진을 찾을 수 없습니다.")
|
||||||
|
data = store.rotate_image(bytes(row["data"]), degrees)
|
||||||
|
conn.execute("UPDATE inout_receipt_photos SET data=%s, size_bytes=%s WHERE id=%s", (data, len(data), photo_id))
|
||||||
|
|
||||||
|
def get_photo(self, photo_id: int) -> dict[str, Any] | None:
|
||||||
|
"""사진 내용(+ 발주서 id) — 보여 주기용."""
|
||||||
|
try:
|
||||||
|
with self._pool.connection() as conn:
|
||||||
|
return conn.execute("SELECT p.id, p.filename, p.content_type, p.data, r.order_id FROM inout_receipt_photos p "
|
||||||
|
"JOIN inout_receipts r ON r.id = p.receipt_id WHERE p.id=%s", (photo_id,)).fetchone()
|
||||||
|
except UndefinedTable:
|
||||||
|
return None
|
||||||
|
|
||||||
|
# ════════════════════════════════════════════════════════════
|
||||||
|
# Gmail 연결(사람별, 갱신 토큰 암호문만) · 발주 메일 기록 — 003
|
||||||
|
# ════════════════════════════════════════════════════════════
|
||||||
|
def gmail_token(self, email: str) -> dict[str, Any] | None:
|
||||||
|
try:
|
||||||
|
with self._pool.connection() as conn:
|
||||||
|
return conn.execute("SELECT * FROM inout_gmail_tokens WHERE email=%s", (_norm_email(email),)).fetchone()
|
||||||
|
except UndefinedTable:
|
||||||
|
return None
|
||||||
|
|
||||||
|
def save_gmail_token(self, email: str, *, refresh_token_enc: str, scopes: str) -> None:
|
||||||
|
try:
|
||||||
|
with self._pool.connection() as conn:
|
||||||
|
conn.execute("INSERT INTO inout_gmail_tokens (email, refresh_token_enc, scopes, connected_at, last_error) "
|
||||||
|
"VALUES (%s,%s,%s,now(),'') ON CONFLICT (email) DO UPDATE SET refresh_token_enc=EXCLUDED.refresh_token_enc, "
|
||||||
|
"scopes=EXCLUDED.scopes, connected_at=now(), last_error=''",
|
||||||
|
(_norm_email(email), refresh_token_enc, scopes[:500]))
|
||||||
|
except UndefinedTable:
|
||||||
|
raise ValueError("DB 마이그레이션 inout_db 003(발주 메일)이 아직 적용되지 않았습니다.") from None
|
||||||
|
|
||||||
|
def delete_gmail_token(self, email: str) -> None:
|
||||||
|
try:
|
||||||
|
with self._pool.connection() as conn:
|
||||||
|
conn.execute("DELETE FROM inout_gmail_tokens WHERE email=%s", (_norm_email(email),))
|
||||||
|
except UndefinedTable:
|
||||||
|
pass
|
||||||
|
|
||||||
|
def mark_gmail(self, email: str, *, error: str = "") -> None:
|
||||||
|
"""보낸 뒤 — 성공이면 마지막 사용 시각, 실패면 오류 문구(비밀값 없음)."""
|
||||||
|
with self._pool.connection() as conn:
|
||||||
|
conn.execute("UPDATE inout_gmail_tokens SET last_used_at = CASE WHEN %s = '' THEN now() ELSE last_used_at END, "
|
||||||
|
"last_error=%s WHERE email=%s", (error[:300], error[:300], _norm_email(email)))
|
||||||
|
|
||||||
|
def add_order_mail(self, order_id: int, *, sent_by: str, to: list[str], cc: list[str], subject: str, gmail_id: str) -> None:
|
||||||
|
with self._pool.connection() as conn:
|
||||||
|
conn.execute("INSERT INTO inout_order_mails (order_id, sent_by, to_addrs, cc_addrs, subject, gmail_id) "
|
||||||
|
"VALUES (%s,%s,%s,%s,%s,%s)",
|
||||||
|
(order_id, _norm_email(sent_by), ", ".join(to), ", ".join(cc), subject[:300], gmail_id[:100]))
|
||||||
|
|
||||||
|
# ════════════════════════════════════════════════════════════
|
||||||
|
# 모듈 설정(물류센터 이메일·입고 요청 메일 참조) · 입고 요청 메일 기록 — 005
|
||||||
|
# ════════════════════════════════════════════════════════════
|
||||||
|
def settings_ready(self) -> bool:
|
||||||
|
with self._pool.connection() as conn:
|
||||||
|
return bool(conn.execute("SELECT to_regclass('public.inout_settings') IS NOT NULL AND "
|
||||||
|
"to_regclass('public.inout_receipt_mails') IS NOT NULL AS ok").fetchone()["ok"])
|
||||||
|
|
||||||
|
def get_settings(self) -> dict[str, str]:
|
||||||
|
"""설정 값 — 없는 키는 store.SETTING_DEFAULTS. 005 미적용이어도 기본값으로."""
|
||||||
|
out = dict(store.SETTING_DEFAULTS)
|
||||||
|
try:
|
||||||
|
with self._pool.connection() as conn:
|
||||||
|
for r in conn.execute("SELECT key, value FROM inout_settings").fetchall():
|
||||||
|
if r["key"] in out:
|
||||||
|
out[r["key"]] = r["value"]
|
||||||
|
except UndefinedTable:
|
||||||
|
pass
|
||||||
|
return out
|
||||||
|
|
||||||
|
def save_settings(self, values: dict[str, str], *, by: str) -> None:
|
||||||
|
try:
|
||||||
|
with self._pool.connection() as conn, conn.transaction():
|
||||||
|
for k, v in values.items():
|
||||||
|
conn.execute("INSERT INTO inout_settings (key, value, updated_by, updated_at) VALUES (%s,%s,%s,now()) "
|
||||||
|
"ON CONFLICT (key) DO UPDATE SET value=EXCLUDED.value, updated_by=EXCLUDED.updated_by, updated_at=now()",
|
||||||
|
(k, v, _norm_email(by)))
|
||||||
|
except UndefinedTable:
|
||||||
|
raise ValueError("DB 마이그레이션 inout_db 005(물류센터 이메일·입고 요청 메일)가 아직 적용되지 않았습니다.") from None
|
||||||
|
|
||||||
|
# 발주 목록 상태 거르기 — 사람마다 기억(2026-11-04). 같은 설정 표에 사람별 키(마이그레이션 없음), 005 미적용이면 기억만 안 한다.
|
||||||
|
def get_list_status(self, email: str) -> str:
|
||||||
|
try:
|
||||||
|
with self._pool.connection() as conn:
|
||||||
|
row = conn.execute("SELECT value FROM inout_settings WHERE key = %s",
|
||||||
|
("list_status:" + _norm_email(email),)).fetchone()
|
||||||
|
except UndefinedTable:
|
||||||
|
return ""
|
||||||
|
return row["value"] if row else ""
|
||||||
|
|
||||||
|
def save_list_status(self, email: str, status: str) -> None:
|
||||||
|
try:
|
||||||
|
self.save_settings({"list_status:" + _norm_email(email): status}, by=email)
|
||||||
|
except ValueError:
|
||||||
|
pass
|
||||||
|
|
||||||
|
def receipt_photo_data(self, receipt_id: int) -> list[dict[str, Any]]:
|
||||||
|
"""입고 1건의 사진 내용(메일 본문에 넣기) — 올린 순서."""
|
||||||
|
try:
|
||||||
|
with self._pool.connection() as conn:
|
||||||
|
return conn.execute("SELECT id, filename, content_type, data FROM inout_receipt_photos WHERE receipt_id=%s ORDER BY id",
|
||||||
|
(receipt_id,)).fetchall()
|
||||||
|
except UndefinedTable:
|
||||||
|
return []
|
||||||
|
|
||||||
|
def add_receipt_mail(self, receipt_id: int, *, sent_by: str, to: list[str], cc: list[str], subject: str, gmail_id: str) -> None:
|
||||||
|
try:
|
||||||
|
with self._pool.connection() as conn:
|
||||||
|
conn.execute("INSERT INTO inout_receipt_mails (receipt_id, sent_by, to_addrs, cc_addrs, subject, gmail_id) "
|
||||||
|
"VALUES (%s,%s,%s,%s,%s,%s)",
|
||||||
|
(receipt_id, _norm_email(sent_by), ", ".join(to), ", ".join(cc), subject[:300], gmail_id[:100]))
|
||||||
|
except UndefinedTable:
|
||||||
|
pass # 메일은 이미 나갔다 — 기록만 못 남김(005 미적용)
|
||||||
|
|
||||||
|
def delete_receipt(self, order_id: int, receipt_id: int, *, by: str) -> None:
|
||||||
|
"""잘못 넣은 입고 1건을 지운다(그 수량만큼 다시 미입고)."""
|
||||||
|
with self._pool.connection() as conn, conn.transaction():
|
||||||
|
head = self._lock_order(conn, order_id)
|
||||||
|
if head["cancelled_at"]:
|
||||||
|
raise ValueError("취소된 발주서입니다.")
|
||||||
|
row = conn.execute("DELETE FROM inout_receipts WHERE id=%s AND order_id=%s RETURNING id",
|
||||||
|
(receipt_id, order_id)).fetchone()
|
||||||
|
if not row:
|
||||||
|
raise ValueError("입고 기록을 찾을 수 없습니다.")
|
||||||
|
conn.execute("UPDATE inout_orders SET updated_by=%s WHERE id=%s", (_norm_email(by), order_id))
|
||||||
|
|
||||||
|
# ════════════════════════════════════════════════════════════
|
||||||
|
# 상품 정보(004) — 코드표 단품 + 단가·무게(개당 g)·은 함유량(%) 수기 입력, 지운 단품은 제외 목록
|
||||||
|
# ════════════════════════════════════════════════════════════
|
||||||
|
def products_ready(self) -> bool:
|
||||||
|
"""004 가 적용됐나(상품 표·발주 품목 값 칸). 한 번 확인되면 기억."""
|
||||||
|
if getattr(self, "_products_ok", False):
|
||||||
|
return True
|
||||||
|
with self._pool.connection() as conn:
|
||||||
|
ok = bool(conn.execute(
|
||||||
|
"SELECT to_regclass('public.inout_products') IS NOT NULL AND EXISTS (SELECT 1 FROM information_schema.columns "
|
||||||
|
"WHERE table_name = 'inout_order_lines' AND column_name = 'unit_price') AS ok").fetchone()["ok"])
|
||||||
|
self._products_ok = ok
|
||||||
|
return ok
|
||||||
|
|
||||||
|
def _need_products(self) -> None:
|
||||||
|
if not self.products_ready():
|
||||||
|
raise ValueError("DB 마이그레이션 inout_db 004(상품 정보)가 아직 적용되지 않았습니다.")
|
||||||
|
|
||||||
|
def list_products(self) -> list[dict[str, Any]]:
|
||||||
|
"""상품 정보 — 006 이면 그룹 이름·그룹 적용 값(silver_pct·color)·상품 자기 값(own_*)까지."""
|
||||||
|
if not self.products_ready():
|
||||||
|
return []
|
||||||
|
grouped = self.groups_ready()
|
||||||
|
with self._pool.connection() as conn:
|
||||||
|
if grouped:
|
||||||
|
return conn.execute(_PRODUCT_SELECT_006 + " ORDER BY p.item_code").fetchall()
|
||||||
|
return conn.execute("SELECT * FROM inout_products ORDER BY item_code").fetchall()
|
||||||
|
|
||||||
|
def list_excluded(self) -> list[dict[str, Any]]:
|
||||||
|
if not self.products_ready():
|
||||||
|
return []
|
||||||
|
with self._pool.connection() as conn:
|
||||||
|
return conn.execute("SELECT * FROM inout_products_excluded ORDER BY item_code").fetchall()
|
||||||
|
|
||||||
|
def import_products(self, items: list[dict[str, str]], *, by: str) -> dict[str, int]:
|
||||||
|
"""코드표 단품 → 상품 정보. 새 단품은 추가, 값(단가·무게·은 함유량)을 넣은 상품은 그대로(이름도),
|
||||||
|
값이 없는 상품은 이름만 최신으로, 제외 목록의 단품은 건너뛴다."""
|
||||||
|
self._need_products()
|
||||||
|
out = {"added": 0, "renamed": 0, "kept": 0, "excluded": 0, "same": 0}
|
||||||
|
with self._pool.connection() as conn, conn.transaction():
|
||||||
|
have = {r["item_code"]: r for r in conn.execute("SELECT * FROM inout_products FOR UPDATE").fetchall()}
|
||||||
|
skip = {r["item_code"] for r in conn.execute("SELECT item_code FROM inout_products_excluded").fetchall()}
|
||||||
|
for it in items:
|
||||||
|
code, name = it["code"].strip().upper(), (it.get("name") or "").strip()[:300]
|
||||||
|
if not code:
|
||||||
|
continue
|
||||||
|
if code in skip:
|
||||||
|
out["excluded"] += 1
|
||||||
|
elif code not in have:
|
||||||
|
conn.execute("INSERT INTO inout_products (item_code, item_name, updated_by) VALUES (%s,%s,%s) "
|
||||||
|
"ON CONFLICT (item_code) DO NOTHING", (code, name, _norm_email(by)))
|
||||||
|
have[code] = {"item_code": code}
|
||||||
|
out["added"] += 1
|
||||||
|
elif store.has_values(have[code]):
|
||||||
|
out["kept"] += 1
|
||||||
|
elif have[code].get("item_name") != name:
|
||||||
|
conn.execute("UPDATE inout_products SET item_name=%s, updated_at=now() WHERE item_code=%s", (name, code))
|
||||||
|
out["renamed"] += 1
|
||||||
|
else:
|
||||||
|
out["same"] += 1
|
||||||
|
return out
|
||||||
|
|
||||||
|
def save_products(self, rows: list[dict[str, Any]], *, by: str) -> int:
|
||||||
|
"""값 저장 — rows = [{code, unit_price, weight_g, silver_pct}](store.validate_product_values 를 거친 값). 한 트랜잭션.
|
||||||
|
006 이면 줄에 group_id·color(상품 자기 색상)도 — 그룹 상품의 은 함유량·색상은 그룹 값이 쓰인다."""
|
||||||
|
self._need_products()
|
||||||
|
grouped = self.groups_ready() and any("group_id" in r for r in rows)
|
||||||
|
boxed = self.boxes_ready() and any("body_per_box" in r for r in rows)
|
||||||
|
bagged = self.bags_ready() and any("boxes_per_pallet" in r for r in rows)
|
||||||
|
with self._pool.connection() as conn, conn.transaction():
|
||||||
|
if bagged: # 008 — 봉투·백 1파렛트당 박스 수량
|
||||||
|
for r in rows:
|
||||||
|
if "boxes_per_pallet" in r:
|
||||||
|
conn.execute("UPDATE inout_products SET boxes_per_pallet=%s WHERE item_code=%s", (r["boxes_per_pallet"], r["code"]))
|
||||||
|
if boxed: # 007 — 통·뚜껑 박스 입수(그룹과 무관, 상품마다)
|
||||||
|
for r in rows:
|
||||||
|
if "body_per_box" in r:
|
||||||
|
conn.execute("UPDATE inout_products SET body_per_box=%s, lid_per_box=%s WHERE item_code=%s",
|
||||||
|
(r.get("body_per_box"), r.get("lid_per_box"), r["code"]))
|
||||||
|
if grouped:
|
||||||
|
known = {int(g["id"]) for g in conn.execute("SELECT id FROM inout_product_groups").fetchall()}
|
||||||
|
for r in rows:
|
||||||
|
gid = r.get("group_id")
|
||||||
|
if gid is not None and int(gid) not in known:
|
||||||
|
raise ValueError(f"{r['code']}: 없는 그룹입니다(다른 사람이 지웠을 수 있음 — 옵션을 다시 여세요).")
|
||||||
|
hit = conn.execute(
|
||||||
|
"UPDATE inout_products SET unit_price=%s, weight_g=%s, silver_pct=%s, group_id=%s, color=%s, "
|
||||||
|
"updated_by=%s, updated_at=now() WHERE item_code=%s RETURNING item_code",
|
||||||
|
(r["unit_price"], r["weight_g"], r["silver_pct"], gid, r.get("color") or "none",
|
||||||
|
_norm_email(by), r["code"])).fetchone()
|
||||||
|
if not hit:
|
||||||
|
raise ValueError(f"상품 정보에 없는 단품입니다: {r['code']}")
|
||||||
|
return len(rows)
|
||||||
|
for r in rows:
|
||||||
|
hit = conn.execute("UPDATE inout_products SET unit_price=%s, weight_g=%s, silver_pct=%s, updated_by=%s, updated_at=now() "
|
||||||
|
"WHERE item_code=%s RETURNING item_code",
|
||||||
|
(r["unit_price"], r["weight_g"], r["silver_pct"], _norm_email(by), r["code"])).fetchone()
|
||||||
|
if not hit:
|
||||||
|
raise ValueError(f"상품 정보에 없는 단품입니다: {r['code']}")
|
||||||
|
return len(rows)
|
||||||
|
|
||||||
|
def exclude_product(self, code: str, *, by: str) -> None:
|
||||||
|
"""상품 정보에서 지우고 제외 목록에 — 다음 불러오기에서 빠진다(지난 발주서는 그대로)."""
|
||||||
|
self._need_products()
|
||||||
|
with self._pool.connection() as conn, conn.transaction():
|
||||||
|
row = conn.execute("DELETE FROM inout_products WHERE item_code=%s RETURNING item_name", (code,)).fetchone()
|
||||||
|
if not row:
|
||||||
|
raise ValueError("상품을 찾을 수 없습니다.")
|
||||||
|
conn.execute("INSERT INTO inout_products_excluded (item_code, item_name, excluded_by) VALUES (%s,%s,%s) "
|
||||||
|
"ON CONFLICT (item_code) DO UPDATE SET excluded_at=now(), excluded_by=EXCLUDED.excluded_by",
|
||||||
|
(code, row["item_name"], _norm_email(by)))
|
||||||
|
|
||||||
|
def restore_product(self, code: str, *, by: str) -> None:
|
||||||
|
"""제외 목록에서 되살리기 — 바로 상품 정보로(값은 빈칸)."""
|
||||||
|
self._need_products()
|
||||||
|
with self._pool.connection() as conn, conn.transaction():
|
||||||
|
row = conn.execute("DELETE FROM inout_products_excluded WHERE item_code=%s RETURNING item_name", (code,)).fetchone()
|
||||||
|
if not row:
|
||||||
|
raise ValueError("제외 목록에 없는 단품입니다.")
|
||||||
|
conn.execute("INSERT INTO inout_products (item_code, item_name, updated_by) VALUES (%s,%s,%s) ON CONFLICT DO NOTHING",
|
||||||
|
(code, row["item_name"], _norm_email(by)))
|
||||||
|
|
||||||
|
def catalog_count(self) -> int:
|
||||||
|
if not self.products_ready():
|
||||||
|
return 0
|
||||||
|
with self._pool.connection() as conn:
|
||||||
|
return int(conn.execute("SELECT count(*) AS n FROM inout_products").fetchone()["n"])
|
||||||
|
|
||||||
|
def catalog_search(self, q: str, *, limit: int = 30) -> list[dict[str, Any]]:
|
||||||
|
"""발주서 제품 고르기 — 상품 정보에서(지운 단품 제외). 코드 앞부분 일치 먼저."""
|
||||||
|
esc = (q or "").strip().replace("\\", "\\\\").replace("%", "\\%").replace("_", "\\_")
|
||||||
|
if not esc:
|
||||||
|
return []
|
||||||
|
args = {"q": f"%{esc}%", "p": f"{esc}%", "n": int(limit)}
|
||||||
|
grouped = self.groups_ready()
|
||||||
|
with self._pool.connection() as conn:
|
||||||
|
if grouped: # 그룹 상품은 그룹의 은 함유량·색상
|
||||||
|
return conn.execute(
|
||||||
|
_PRODUCT_SELECT_006 + " WHERE p.item_code ILIKE %(q)s OR p.item_name ILIKE %(q)s "
|
||||||
|
"ORDER BY (p.item_code ILIKE %(p)s) DESC, p.item_code LIMIT %(n)s", args).fetchall()
|
||||||
|
return conn.execute(
|
||||||
|
"SELECT * FROM inout_products "
|
||||||
|
"WHERE item_code ILIKE %(q)s OR item_name ILIKE %(q)s "
|
||||||
|
"ORDER BY (item_code ILIKE %(p)s) DESC, item_code LIMIT %(n)s", args).fetchall()
|
||||||
|
|
||||||
|
def catalog_lookup(self, codes: list[str]) -> dict[str, dict[str, Any]]:
|
||||||
|
if not codes or not self.products_ready():
|
||||||
|
return {}
|
||||||
|
grouped = self.groups_ready()
|
||||||
|
with self._pool.connection() as conn:
|
||||||
|
if grouped: # 발주 품목 사본 = 그룹 적용 값
|
||||||
|
rows = conn.execute(_PRODUCT_SELECT_006 + " WHERE p.item_code = ANY(%s)", ([c.upper() for c in codes],)).fetchall()
|
||||||
|
else:
|
||||||
|
rows = conn.execute("SELECT * FROM inout_products WHERE item_code = ANY(%s)", ([c.upper() for c in codes],)).fetchall()
|
||||||
|
return {r["item_code"]: r for r in rows}
|
||||||
|
|
||||||
|
# ════════════════════════════════════════════════════════════
|
||||||
|
# 상품 그룹(006) — 은 함유량·색상을 그룹에 한 번만. 그룹을 지우면 그 상품들은 그룹 없음(자기 값)으로.
|
||||||
|
# ════════════════════════════════════════════════════════════
|
||||||
|
def groups_ready(self) -> bool:
|
||||||
|
"""006 이 적용됐나(그룹 표·상품 group_id·발주 품목 color). 적용됐으면 계속, 아직이면 1분 동안 기억한다 —
|
||||||
|
부를 때마다 연결을 하나 더 잡지 않게(발주 저장 트랜잭션이 연결을 쥔 채 부르면 동시 발주에서 풀이 바닥난다).
|
||||||
|
그래서 연결을 열기 전에 먼저 부른다."""
|
||||||
|
if getattr(self, "_groups_ok", False):
|
||||||
|
return True
|
||||||
|
if time.monotonic() - getattr(self, "_groups_checked", -1e9) < 60:
|
||||||
|
return False
|
||||||
|
if not self.products_ready():
|
||||||
|
return False
|
||||||
|
with self._pool.connection() as conn:
|
||||||
|
ok = bool(conn.execute(
|
||||||
|
"SELECT to_regclass('public.inout_product_groups') IS NOT NULL "
|
||||||
|
"AND EXISTS (SELECT 1 FROM information_schema.columns WHERE table_name = 'inout_products' AND column_name = 'group_id') "
|
||||||
|
"AND EXISTS (SELECT 1 FROM information_schema.columns WHERE table_name = 'inout_order_lines' AND column_name = 'color') AS ok"
|
||||||
|
).fetchone()["ok"])
|
||||||
|
self._groups_ok = ok
|
||||||
|
self._groups_checked = time.monotonic()
|
||||||
|
return ok
|
||||||
|
|
||||||
|
def boxes_ready(self) -> bool:
|
||||||
|
"""007 이 적용됐나(상품 body_per_box·lid_per_box). groups_ready 와 같이 — 적용됐으면 계속, 아직이면 1분 기억, 연결 열기 전에 부른다."""
|
||||||
|
if getattr(self, "_boxes_ok", False):
|
||||||
|
return True
|
||||||
|
if time.monotonic() - getattr(self, "_boxes_checked", -1e9) < 60:
|
||||||
|
return False
|
||||||
|
if not self.products_ready():
|
||||||
|
return False
|
||||||
|
with self._pool.connection() as conn:
|
||||||
|
ok = bool(conn.execute(
|
||||||
|
"SELECT EXISTS (SELECT 1 FROM information_schema.columns WHERE table_name = 'inout_products' "
|
||||||
|
"AND column_name = 'lid_per_box') AS ok").fetchone()["ok"])
|
||||||
|
self._boxes_ok = ok
|
||||||
|
self._boxes_checked = time.monotonic()
|
||||||
|
return ok
|
||||||
|
|
||||||
|
def bags_ready(self) -> bool:
|
||||||
|
"""008 이 적용됐나(상품 boxes_per_pallet). boxes_ready 와 같은 방식."""
|
||||||
|
if getattr(self, "_bags_ok", False):
|
||||||
|
return True
|
||||||
|
if time.monotonic() - getattr(self, "_bags_checked", -1e9) < 60:
|
||||||
|
return False
|
||||||
|
if not self.products_ready():
|
||||||
|
return False
|
||||||
|
with self._pool.connection() as conn:
|
||||||
|
ok = bool(conn.execute(
|
||||||
|
"SELECT EXISTS (SELECT 1 FROM information_schema.columns WHERE table_name = 'inout_products' "
|
||||||
|
"AND column_name = 'boxes_per_pallet') AS ok").fetchone()["ok"])
|
||||||
|
self._bags_ok = ok
|
||||||
|
self._bags_checked = time.monotonic()
|
||||||
|
return ok
|
||||||
|
|
||||||
|
def _need_groups(self) -> None:
|
||||||
|
if not self.groups_ready():
|
||||||
|
raise ValueError("DB 마이그레이션 inout_db 006(상품 그룹·색상)이 아직 적용되지 않았습니다.")
|
||||||
|
|
||||||
|
def list_groups(self) -> list[dict[str, Any]]:
|
||||||
|
if not self.groups_ready():
|
||||||
|
return []
|
||||||
|
with self._pool.connection() as conn:
|
||||||
|
return conn.execute(
|
||||||
|
"SELECT g.*, (SELECT count(*) FROM inout_products p WHERE p.group_id = g.id)::int AS product_count "
|
||||||
|
"FROM inout_product_groups g ORDER BY g.sort_order, g.name").fetchall()
|
||||||
|
|
||||||
|
def save_group(self, *, group_id: int | None, name: str, silver_pct: Any, color: str, sort_order: int, by: str) -> int:
|
||||||
|
"""그룹 만들기·고치기(store.validate_group 를 거친 값). 같은 이름은 거절. 반환 = 그룹 id."""
|
||||||
|
self._need_groups()
|
||||||
|
try:
|
||||||
|
with self._pool.connection() as conn, conn.transaction():
|
||||||
|
if group_id:
|
||||||
|
row = conn.execute(
|
||||||
|
"UPDATE inout_product_groups SET name=%s, silver_pct=%s, color=%s, sort_order=%s, updated_by=%s, "
|
||||||
|
"updated_at=now() WHERE id=%s RETURNING id",
|
||||||
|
(name, silver_pct, color, sort_order, _norm_email(by), group_id)).fetchone()
|
||||||
|
if not row:
|
||||||
|
raise ValueError("그룹을 찾을 수 없습니다(다른 사람이 지웠을 수 있음).")
|
||||||
|
else:
|
||||||
|
row = conn.execute(
|
||||||
|
"INSERT INTO inout_product_groups (name, silver_pct, color, sort_order, updated_by) "
|
||||||
|
"VALUES (%s,%s,%s,%s,%s) RETURNING id",
|
||||||
|
(name, silver_pct, color, sort_order, _norm_email(by))).fetchone()
|
||||||
|
except UniqueViolation:
|
||||||
|
raise ValueError(f"같은 이름의 그룹이 있습니다: {name}") from None
|
||||||
|
return int(row["id"])
|
||||||
|
|
||||||
|
def delete_group(self, group_id: int) -> str:
|
||||||
|
"""그룹 지우기 — 그 그룹 상품은 그룹 없음(상품 자기 은 함유량·색상)으로. 지난 발주서는 그대로. 반환 = 이름."""
|
||||||
|
self._need_groups()
|
||||||
|
with self._pool.connection() as conn, conn.transaction():
|
||||||
|
row = conn.execute("DELETE FROM inout_product_groups WHERE id=%s RETURNING name", (group_id,)).fetchone()
|
||||||
|
if not row:
|
||||||
|
raise ValueError("그룹을 찾을 수 없습니다.")
|
||||||
|
return str(row["name"])
|
||||||
|
|
||||||
|
# ════════════════════════════════════════════════════════════
|
||||||
|
# 달력(2026-10-21) — 화면 오른쪽 달력에 날짜별 발주(발주일)·입고(입고일). 취소된 발주는 뺀다.
|
||||||
|
# ════════════════════════════════════════════════════════════
|
||||||
|
def calendar(self, start: date, end: date) -> dict[str, list[dict[str, Any]]]:
|
||||||
|
with self._pool.connection() as conn:
|
||||||
|
orders = conn.execute(
|
||||||
|
"SELECT o.id, o.order_no, o.order_date, f.name AS factory_name, "
|
||||||
|
"(SELECT COALESCE(sum(qty), 0) FROM inout_order_lines l WHERE l.order_id = o.id)::int AS qty, "
|
||||||
|
"(SELECT count(*) FROM inout_order_lines l WHERE l.order_id = o.id)::int AS kinds, "
|
||||||
|
"(SELECT l.item_name FROM inout_order_lines l WHERE l.order_id = o.id ORDER BY l.line_no LIMIT 1) AS first_item "
|
||||||
|
"FROM inout_orders o JOIN inout_factories f ON f.id = o.factory_id "
|
||||||
|
"WHERE o.cancelled_at IS NULL AND o.order_date BETWEEN %s AND %s ORDER BY o.order_date, o.id",
|
||||||
|
(start, end)).fetchall()
|
||||||
|
receipts = conn.execute(
|
||||||
|
"SELECT r.id, r.order_id, r.receipt_date, o.order_no, f.name AS factory_name, "
|
||||||
|
"COALESCE(sum(rl.qty), 0)::int AS qty "
|
||||||
|
"FROM inout_receipts r JOIN inout_orders o ON o.id = r.order_id JOIN inout_factories f ON f.id = o.factory_id "
|
||||||
|
"LEFT JOIN inout_receipt_lines rl ON rl.receipt_id = r.id "
|
||||||
|
"WHERE o.cancelled_at IS NULL AND r.receipt_date BETWEEN %s AND %s "
|
||||||
|
"GROUP BY r.id, o.order_no, f.name ORDER BY r.receipt_date, r.id",
|
||||||
|
(start, end)).fetchall()
|
||||||
|
return {"orders": orders, "receipts": receipts}
|
||||||
|
|
||||||
|
# ════════════════════════════════════════════════════════════
|
||||||
|
# 미입고 현황 — 진행 중(종결·취소 아님) 발주의 남은 수량, 그리고 초과 입고
|
||||||
|
# ════════════════════════════════════════════════════════════
|
||||||
|
def outstanding(self, *, factory_id: int | None = None, q: str = "") -> dict[str, list[dict[str, Any]]]:
|
||||||
|
where, params = ["o.closed_at IS NULL", "o.cancelled_at IS NULL"], []
|
||||||
|
if factory_id:
|
||||||
|
where.append("o.factory_id = %s")
|
||||||
|
params.append(factory_id)
|
||||||
|
if q.strip():
|
||||||
|
like = "%" + q.strip().replace("\\", "\\\\").replace("%", "\\%").replace("_", "\\_") + "%"
|
||||||
|
where.append("(l.item_code ILIKE %s OR l.item_name ILIKE %s OR o.order_no ILIKE %s)")
|
||||||
|
params += [like, like, like]
|
||||||
|
with self._pool.connection() as conn:
|
||||||
|
rows = conn.execute(
|
||||||
|
"SELECT o.id AS order_id, o.order_no, o.order_date, o.due_date, f.name AS factory_name, "
|
||||||
|
"l.item_code, l.item_name, l.qty, COALESCE(sum(rl.qty), 0)::int AS received "
|
||||||
|
"FROM inout_order_lines l JOIN inout_orders o ON o.id = l.order_id "
|
||||||
|
"JOIN inout_factories f ON f.id = o.factory_id "
|
||||||
|
"LEFT JOIN inout_receipt_lines rl ON rl.order_line_id = l.id "
|
||||||
|
f"WHERE {' AND '.join(where)} GROUP BY l.id, o.id, f.name "
|
||||||
|
"ORDER BY o.due_date NULLS LAST, o.order_date, o.id, l.line_no", params).fetchall()
|
||||||
|
rows = store.decorate_lines(rows)
|
||||||
|
return {"pending": [r for r in rows if r["remaining"] > 0], "over": [r for r in rows if r["over"] > 0]}
|
||||||
|
|
||||||
|
# ── 내부 ──
|
||||||
|
@staticmethod
|
||||||
|
def _lock_order(conn: Any, order_id: int) -> dict[str, Any]:
|
||||||
|
head = conn.execute("SELECT * FROM inout_orders WHERE id=%s FOR UPDATE", (order_id,)).fetchone()
|
||||||
|
if not head:
|
||||||
|
raise LookupError("발주서를 찾을 수 없습니다.")
|
||||||
|
return head
|
||||||
|
|
||||||
|
@staticmethod
|
||||||
|
def _require_factory(conn: Any, factory_id: int, *, allow_inactive_id: int | None = None) -> None:
|
||||||
|
row = conn.execute("SELECT is_active FROM inout_factories WHERE id=%s", (factory_id,)).fetchone()
|
||||||
|
if not row:
|
||||||
|
raise ValueError("공장을 찾을 수 없습니다.")
|
||||||
|
if not row["is_active"] and factory_id != allow_inactive_id:
|
||||||
|
raise ValueError("사용하지 않는 공장입니다(옵션에서 '사용'으로 바꾸세요).")
|
||||||
@@ -0,0 +1,192 @@
|
|||||||
|
"""발주 메일 — 발주 담당자 본인 Gmail 로 보내기(2026-10-16 사용자 요청, Gmail API).
|
||||||
|
|
||||||
|
연결(사람마다 한 번): [Gmail 연결] → 구글 동의 화면(로그인과 같은 OAuth 클라이언트 GOOGLE_CLIENT_ID, 범위 = gmail.send 만)
|
||||||
|
→ /inout/gmail/callback 에서 ① 고른 구글 계정이 ERP 로그인 계정과 같은지(다르면 거절 — 남의 메일함으로 보내지 않게)
|
||||||
|
② gmail.send 를 허락했는지 ③ 갱신 토큰이 왔는지 확인 → 갱신 토큰을 APP_ENCRYPTION_KEY(실적 모듈과 같은 마스터 키,
|
||||||
|
AES-256-GCM, AAD = inout:gmail:{email})로 암호화해 inout_gmail_tokens 에. 원문·접근 토큰은 저장·출력하지 않는다.
|
||||||
|
보내기: 갱신 토큰 → 접근 토큰(oauth2.googleapis.com/token) → gmail.users.messages.send(raw = RFC 822, 글 + HTML).
|
||||||
|
사람이 [메일 발송]을 눌렀을 때만 보낸다(자동 발송 없음). 연결이 끊겼으면(invalid_grant·권한 없음) 다시 연결 안내.
|
||||||
|
구글 클라우드 준비(관리자 1회): Gmail API 사용 설정 · OAuth 동의 화면에 …/auth/gmail.send 범위 추가 ·
|
||||||
|
OAuth 클라이언트의 승인된 리디렉션 URI 에 {PUBLIC_BASE_URL}/inout/gmail/callback 추가. 상세 docs/INOUT_MODULE.md.
|
||||||
|
"""
|
||||||
|
|
||||||
|
from __future__ import annotations
|
||||||
|
|
||||||
|
import base64
|
||||||
|
import os
|
||||||
|
from email.message import EmailMessage
|
||||||
|
from email.utils import formataddr
|
||||||
|
from typing import Any
|
||||||
|
|
||||||
|
import httpx
|
||||||
|
|
||||||
|
GMAIL_SCOPE = "https://www.googleapis.com/auth/gmail.send"
|
||||||
|
TOKEN_URI = "https://oauth2.googleapis.com/token"
|
||||||
|
SEND_URI = "https://gmail.googleapis.com/gmail/v1/users/me/messages/send"
|
||||||
|
REVOKE_URI = "https://oauth2.googleapis.com/revoke"
|
||||||
|
CLIENT_NAME = "inout_gmail"
|
||||||
|
|
||||||
|
|
||||||
|
class GmailNotConnected(Exception):
|
||||||
|
"""Gmail 연결이 없거나 끊김 — 다시 [Gmail 연결]."""
|
||||||
|
|
||||||
|
|
||||||
|
class GmailError(Exception):
|
||||||
|
"""보내기 실패(구글 오류 등) — 문구는 화면에 그대로(비밀값 없음)."""
|
||||||
|
|
||||||
|
|
||||||
|
def _http() -> httpx.Client:
|
||||||
|
"""HTTP 클라이언트 — 테스트가 바꿔 끼운다."""
|
||||||
|
return httpx.Client(timeout=20.0)
|
||||||
|
|
||||||
|
|
||||||
|
# ── 토큰 암호화(실적 모듈과 같은 마스터 키) ─────────────────
|
||||||
|
def _ring() -> Any:
|
||||||
|
from app.modules.performance.security.crypto import CryptoConfigError, KeyRing # noqa: WPS433
|
||||||
|
|
||||||
|
try:
|
||||||
|
return KeyRing.from_env()
|
||||||
|
except CryptoConfigError as exc:
|
||||||
|
raise GmailError(f"암호화 키가 없어 Gmail 연결을 저장할 수 없습니다 — {exc}") from None
|
||||||
|
|
||||||
|
|
||||||
|
def _aad(email: str) -> str:
|
||||||
|
return f"inout:gmail:{(email or '').strip().lower()}"
|
||||||
|
|
||||||
|
|
||||||
|
def encrypt_token(email: str, refresh_token: str) -> str:
|
||||||
|
from app.modules.performance.security.crypto import encrypt # noqa: WPS433
|
||||||
|
|
||||||
|
return encrypt(refresh_token, aad=_aad(email), ring=_ring())
|
||||||
|
|
||||||
|
|
||||||
|
def decrypt_token(email: str, enc: str) -> str:
|
||||||
|
from app.modules.performance.security.crypto import DecryptError, decrypt # noqa: WPS433
|
||||||
|
|
||||||
|
try:
|
||||||
|
return decrypt(enc, aad=_aad(email), ring=_ring())
|
||||||
|
except DecryptError:
|
||||||
|
raise GmailNotConnected("저장된 Gmail 연결을 읽을 수 없습니다(암호화 키가 바뀌었을 수 있음) — 다시 연결하세요.") from None
|
||||||
|
|
||||||
|
|
||||||
|
# ── OAuth 클라이언트(로그인과 같은 GOOGLE_CLIENT_ID, 범위만 다름) ──
|
||||||
|
def oauth_client() -> Any:
|
||||||
|
from app.main import env, oauth # noqa: WPS433
|
||||||
|
|
||||||
|
if not env("GOOGLE_CLIENT_ID") or not env("GOOGLE_CLIENT_SECRET"):
|
||||||
|
raise GmailError("GOOGLE_CLIENT_ID/SECRET 이 없어 Gmail 을 연결할 수 없습니다.")
|
||||||
|
client = oauth.create_client(CLIENT_NAME)
|
||||||
|
if client is None:
|
||||||
|
oauth.register(
|
||||||
|
name=CLIENT_NAME,
|
||||||
|
client_id=env("GOOGLE_CLIENT_ID"),
|
||||||
|
client_secret=env("GOOGLE_CLIENT_SECRET"),
|
||||||
|
server_metadata_url="https://accounts.google.com/.well-known/openid-configuration",
|
||||||
|
client_kwargs={"scope": f"openid email {GMAIL_SCOPE}"},
|
||||||
|
)
|
||||||
|
client = oauth.create_client(CLIENT_NAME)
|
||||||
|
return client
|
||||||
|
|
||||||
|
|
||||||
|
def check_grant(token: dict[str, Any], *, expected_email: str) -> tuple[str, str]:
|
||||||
|
"""콜백 토큰 확인 → (갱신 토큰, 허락된 범위). 계정이 다르거나 발송 권한·갱신 토큰이 없으면 GmailError."""
|
||||||
|
info = token.get("userinfo") or {}
|
||||||
|
got = str(info.get("email") or "").strip().lower()
|
||||||
|
want = (expected_email or "").strip().lower()
|
||||||
|
if not got or got != want:
|
||||||
|
raise GmailError(f"ERP 로그인 계정({want})과 다른 구글 계정({got or '알 수 없음'})을 골랐습니다 — 같은 계정으로 다시 연결하세요.")
|
||||||
|
scopes = str(token.get("scope") or "")
|
||||||
|
if GMAIL_SCOPE not in scopes.split():
|
||||||
|
raise GmailError("메일 보내기 권한(gmail.send)을 허락하지 않았습니다 — 동의 화면에서 체크한 뒤 다시 연결하세요.")
|
||||||
|
refresh = str(token.get("refresh_token") or "")
|
||||||
|
if not refresh:
|
||||||
|
raise GmailError("구글이 갱신 토큰을 주지 않았습니다 — 구글 계정 → 보안 → 타사 앱 접근에서 이 앱을 지우고 다시 연결하세요.")
|
||||||
|
return refresh, scopes
|
||||||
|
|
||||||
|
|
||||||
|
# ── 보내기 ──────────────────────────────────────────────
|
||||||
|
def _google_message(resp: httpx.Response) -> str:
|
||||||
|
try:
|
||||||
|
body = resp.json()
|
||||||
|
except ValueError:
|
||||||
|
return f"HTTP {resp.status_code}"
|
||||||
|
err = body.get("error")
|
||||||
|
if isinstance(err, dict):
|
||||||
|
return str(err.get("message") or err.get("status") or resp.status_code)[:200]
|
||||||
|
return str(body.get("error_description") or err or resp.status_code)[:200]
|
||||||
|
|
||||||
|
|
||||||
|
def access_token(refresh_token: str) -> str:
|
||||||
|
from app.main import env # noqa: WPS433
|
||||||
|
|
||||||
|
try:
|
||||||
|
with _http() as client:
|
||||||
|
resp = client.post(TOKEN_URI, data={"client_id": env("GOOGLE_CLIENT_ID"), "client_secret": env("GOOGLE_CLIENT_SECRET"),
|
||||||
|
"refresh_token": refresh_token, "grant_type": "refresh_token"})
|
||||||
|
except httpx.HTTPError as exc:
|
||||||
|
raise GmailError(f"구글 인증 서버에 연결하지 못했습니다({type(exc).__name__}).") from None
|
||||||
|
if resp.status_code != 200:
|
||||||
|
try:
|
||||||
|
code = str(resp.json().get("error") or "")
|
||||||
|
except ValueError:
|
||||||
|
code = ""
|
||||||
|
if code in ("invalid_grant", "unauthorized_client", "invalid_client"):
|
||||||
|
raise GmailNotConnected("Gmail 연결이 끊겼습니다(권한 취소·비밀번호 변경 등) — 다시 연결하세요.")
|
||||||
|
raise GmailError(f"구글 인증 실패: {_google_message(resp)}")
|
||||||
|
token = str(resp.json().get("access_token") or "")
|
||||||
|
if not token:
|
||||||
|
raise GmailError("구글 인증 서버가 접근 토큰을 주지 않았습니다.")
|
||||||
|
return token
|
||||||
|
|
||||||
|
|
||||||
|
def build_message(*, sender_name: str, sender_email: str, to: list[str], cc: list[str], subject: str,
|
||||||
|
text: str, html: str, inline_images: list[dict[str, Any]] | None = None) -> bytes:
|
||||||
|
"""글 + HTML(multipart/alternative). inline_images = [{cid, data(JPEG)}] 면 HTML 쪽을 multipart/related 로 만들어
|
||||||
|
<img src="cid:…"> 가 첨부가 아니라 본문 안 이미지로 보이게 한다(입고 요청 메일, 2026-10-19)."""
|
||||||
|
msg = EmailMessage()
|
||||||
|
msg["From"] = formataddr((sender_name or sender_email, sender_email))
|
||||||
|
msg["To"] = ", ".join(to)
|
||||||
|
if cc:
|
||||||
|
msg["Cc"] = ", ".join(cc)
|
||||||
|
msg["Subject"] = subject
|
||||||
|
msg.set_content(text)
|
||||||
|
msg.add_alternative(html, subtype="html")
|
||||||
|
if inline_images:
|
||||||
|
html_part = msg.get_payload()[1]
|
||||||
|
for im in inline_images: # 파일 이름은 붙이지 않는다 — 메일 프로그램이 첨부 목록에 따로 띄우지 않게
|
||||||
|
html_part.add_related(im["data"], maintype="image", subtype="jpeg", cid=f"<{im['cid']}>", disposition="inline")
|
||||||
|
return msg.as_bytes()
|
||||||
|
|
||||||
|
|
||||||
|
def send(refresh_token: str, raw: bytes) -> str:
|
||||||
|
"""보내고 Gmail 메시지 id 를 돌려준다."""
|
||||||
|
token = access_token(refresh_token)
|
||||||
|
body = {"raw": base64.urlsafe_b64encode(raw).decode("ascii")}
|
||||||
|
try:
|
||||||
|
with _http() as client:
|
||||||
|
resp = client.post(SEND_URI, json=body, headers={"Authorization": f"Bearer {token}"})
|
||||||
|
except httpx.HTTPError as exc:
|
||||||
|
raise GmailError(f"Gmail 에 연결하지 못했습니다({type(exc).__name__}).") from None
|
||||||
|
if resp.status_code in (401, 403):
|
||||||
|
msg = _google_message(resp)
|
||||||
|
if "has not been used" in msg or "disabled" in msg.lower():
|
||||||
|
raise GmailError(f"Gmail API 가 꺼져 있습니다 — 관리자가 구글 클라우드에서 Gmail API 를 사용 설정해야 합니다. ({msg})")
|
||||||
|
raise GmailNotConnected(f"Gmail 보내기 권한이 없습니다 — 다시 연결하세요. ({msg})")
|
||||||
|
if resp.status_code != 200:
|
||||||
|
raise GmailError(f"메일을 보내지 못했습니다: {_google_message(resp)}")
|
||||||
|
return str(resp.json().get("id") or "")
|
||||||
|
|
||||||
|
|
||||||
|
def revoke(refresh_token: str) -> None:
|
||||||
|
"""연결 끊기 — 구글 쪽 권한도 취소(실패해도 무시, 우리 쪽 토큰은 지운다)."""
|
||||||
|
try:
|
||||||
|
with _http() as client:
|
||||||
|
client.post(REVOKE_URI, data={"token": refresh_token})
|
||||||
|
except httpx.HTTPError:
|
||||||
|
pass
|
||||||
|
|
||||||
|
|
||||||
|
def configured() -> bool:
|
||||||
|
"""APP_ENCRYPTION_KEY·GOOGLE_CLIENT_ID/SECRET 이 있는지(화면 안내용)."""
|
||||||
|
return bool(os.getenv("APP_ENCRYPTION_KEY", "").strip() and os.getenv("GOOGLE_CLIENT_ID", "").strip()
|
||||||
|
and os.getenv("GOOGLE_CLIENT_SECRET", "").strip())
|
||||||
@@ -0,0 +1,103 @@
|
|||||||
|
"""itemcode_db 읽기 전용 — 단품(single_items)만 검색·확인.
|
||||||
|
|
||||||
|
입출고 발주서의 제품은 코드표 DB 의 단품 아이템에서만 고른다(2026-10-16 사용자 요청 — 세트는 공장 발주 대상이 아님).
|
||||||
|
itemcode_db 실제 스키마(운영 확인됨, malaysia/itemcode.py 와 같음): single_items(item_code, sabangnet_code, name).
|
||||||
|
환경변수 `ITEMCODE_DB_URL`(읽기 전용 역할 itemcode_ro) — cupang·malaysia 모듈과 공유.
|
||||||
|
미설정/실패 시 enabled=False, 빈 결과(앱/모듈을 죽이지 않음) — 그때 발주서 저장은 "코드표 연결 필요"로 막는다.
|
||||||
|
"""
|
||||||
|
|
||||||
|
from __future__ import annotations
|
||||||
|
|
||||||
|
import logging
|
||||||
|
import os
|
||||||
|
from typing import Any
|
||||||
|
|
||||||
|
logger = logging.getLogger("inout.itemcode")
|
||||||
|
|
||||||
|
_SEARCH_SQL = (
|
||||||
|
"SELECT item_code, name FROM single_items "
|
||||||
|
"WHERE item_code ILIKE %(q)s OR name ILIKE %(q)s "
|
||||||
|
"ORDER BY (item_code ILIKE %(prefix)s) DESC, item_code ASC LIMIT %(limit)s"
|
||||||
|
)
|
||||||
|
_LOOKUP_SQL = "SELECT item_code, name FROM single_items WHERE upper(item_code) = ANY(%(codes)s)"
|
||||||
|
|
||||||
|
|
||||||
|
class SingleItemReader:
|
||||||
|
def __init__(self, dsn: str | None = None) -> None:
|
||||||
|
self._pool: Any = None
|
||||||
|
self.enabled = False
|
||||||
|
self.reason = ""
|
||||||
|
self.last_error = ""
|
||||||
|
self._configure(dsn if dsn is not None else os.getenv("ITEMCODE_DB_URL", "").strip())
|
||||||
|
|
||||||
|
def _configure(self, dsn: str) -> None:
|
||||||
|
if not dsn:
|
||||||
|
self.reason = "ITEMCODE_DB_URL 미설정 — 코드표(단품) 조회 비활성."
|
||||||
|
return
|
||||||
|
try:
|
||||||
|
from psycopg.rows import dict_row
|
||||||
|
from psycopg_pool import ConnectionPool
|
||||||
|
|
||||||
|
self._pool = ConnectionPool(conninfo=dsn, min_size=1, max_size=3,
|
||||||
|
kwargs={"row_factory": dict_row, "autocommit": True}, open=False)
|
||||||
|
self._pool.open(wait=False)
|
||||||
|
self.enabled = True
|
||||||
|
except Exception as exc: # noqa: BLE001 — 설정/드라이버 문제로 모듈을 죽이지 않음
|
||||||
|
self.reason = f"itemcode_db 연결 풀 생성 실패: {type(exc).__name__}"
|
||||||
|
|
||||||
|
def search(self, query: str, *, limit: int = 30) -> list[dict[str, str]]:
|
||||||
|
"""코드·이름 부분 일치(코드 앞부분 일치 먼저). 반환 [{"code","name"}]. 실패는 빈 목록."""
|
||||||
|
q = (query or "").strip()
|
||||||
|
if not q or not self.enabled or not self._pool:
|
||||||
|
return []
|
||||||
|
esc = q.replace("\\", "\\\\").replace("%", "\\%").replace("_", "\\_")
|
||||||
|
rows = self._run(_SEARCH_SQL, {"q": f"%{esc}%", "prefix": f"{esc}%", "limit": int(limit)})
|
||||||
|
return [{"code": str(r["item_code"]).strip(), "name": str(r.get("name") or "").strip()} for r in rows or []]
|
||||||
|
|
||||||
|
def list_all(self, *, limit: int = 20000) -> list[dict[str, str]] | None:
|
||||||
|
"""단품 전체(옵션 → 상품 정보 → 단품 불러오기). 조회 불가면 None(빈 목록과 구분)."""
|
||||||
|
if not self.enabled or not self._pool:
|
||||||
|
return None
|
||||||
|
rows = self._run("SELECT item_code, name FROM single_items ORDER BY item_code LIMIT %(limit)s", {"limit": int(limit)})
|
||||||
|
if rows is None:
|
||||||
|
return None
|
||||||
|
return [{"code": str(r["item_code"]).strip().upper(), "name": str(r.get("name") or "").strip()} for r in rows if r.get("item_code")]
|
||||||
|
|
||||||
|
def lookup(self, codes: list[str]) -> dict[str, str] | None:
|
||||||
|
"""코드들 → {코드(대문자): 이름}. 단품 표에 없는 코드는 빠진다. 조회 불가면 None."""
|
||||||
|
if not self.enabled or not self._pool:
|
||||||
|
return None
|
||||||
|
wanted = sorted({c.strip().upper() for c in codes if c and c.strip()})
|
||||||
|
if not wanted:
|
||||||
|
return {}
|
||||||
|
rows = self._run(_LOOKUP_SQL, {"codes": wanted})
|
||||||
|
if rows is None:
|
||||||
|
return None
|
||||||
|
return {str(r["item_code"]).strip().upper(): str(r.get("name") or "").strip() for r in rows}
|
||||||
|
|
||||||
|
def sabangnet_codes(self, codes: list[str]) -> dict[str, str] | None:
|
||||||
|
"""코드들 → {코드(대문자): 사방넷 코드}(사방넷 입고 파일, 2026-10-19). 사방넷 코드가 빈 단품은 ''. 조회 불가면 None."""
|
||||||
|
if not self.enabled or not self._pool:
|
||||||
|
return None
|
||||||
|
wanted = sorted({c.strip().upper() for c in codes if c and c.strip()})
|
||||||
|
if not wanted:
|
||||||
|
return {}
|
||||||
|
rows = self._run("SELECT item_code, sabangnet_code FROM single_items WHERE upper(item_code) = ANY(%(codes)s)", {"codes": wanted})
|
||||||
|
if rows is None:
|
||||||
|
return None
|
||||||
|
return {str(r["item_code"]).strip().upper(): str(r.get("sabangnet_code") or "").strip() for r in rows}
|
||||||
|
|
||||||
|
def _run(self, sql: str, params: dict[str, Any]) -> list[dict[str, Any]] | None:
|
||||||
|
try:
|
||||||
|
with self._pool.connection() as conn:
|
||||||
|
rows = conn.execute(sql, params).fetchall()
|
||||||
|
self.last_error = ""
|
||||||
|
return rows
|
||||||
|
except Exception as exc: # noqa: BLE001 — 모듈을 죽이지 않음
|
||||||
|
self.last_error = f"{type(exc).__name__}"
|
||||||
|
logger.exception("itemcode(single_items) 조회 실패")
|
||||||
|
return None
|
||||||
|
|
||||||
|
def close(self) -> None:
|
||||||
|
if self._pool is not None:
|
||||||
|
self._pool.close()
|
||||||
File diff suppressed because it is too large
Load Diff
@@ -0,0 +1,998 @@
|
|||||||
|
"""입출고 관리 — 상수·검사·상태 계산(순수 함수, DB 없음).
|
||||||
|
|
||||||
|
흐름(2026-10-16 사용자 요청, 상용 ERP 참고 — 이카운트 "발주 대비 미입고 현황"·Odoo 분할 입고/잔량 종결):
|
||||||
|
발주 담당이 공장에 발주서(단품 코드·수량)를 넣고 → 물류에 들어올 때마다 입고 담당이 그날 들어온 수량을 입력(여러 번 나눠도 됨)
|
||||||
|
→ 품목마다 발주 − 누적 입고 = 미입고. 다 들어오면 입고완료, 더 들어오면 초과입고(확인 후 허용, 빨강 표시).
|
||||||
|
더 안 들어올 잔량은 발주 담당이 "종결"(이카운트 발주 종결 · Odoo No backorder) — 미입고 현황에서 빠지고 종결로 남는다.
|
||||||
|
"""
|
||||||
|
|
||||||
|
from __future__ import annotations
|
||||||
|
|
||||||
|
import html as _html
|
||||||
|
import html.parser as _html_parser
|
||||||
|
import re
|
||||||
|
from datetime import date, datetime
|
||||||
|
from decimal import ROUND_HALF_UP, Decimal, InvalidOperation
|
||||||
|
from typing import Any, Iterable
|
||||||
|
|
||||||
|
ROLE_ORDER = "order" # 발주 담당
|
||||||
|
ROLE_RECEIVE = "receive" # 입고 담당
|
||||||
|
ROLES = (ROLE_ORDER, ROLE_RECEIVE)
|
||||||
|
ROLE_LABELS = {ROLE_ORDER: "발주 담당", ROLE_RECEIVE: "입고 담당"}
|
||||||
|
|
||||||
|
MAX_QTY = 10_000_000
|
||||||
|
MAX_LINES = 200
|
||||||
|
MEMO_MAX = 500
|
||||||
|
|
||||||
|
# 품목 상태
|
||||||
|
LINE_NONE, LINE_PARTIAL, LINE_DONE, LINE_OVER = "none", "partial", "done", "over"
|
||||||
|
LINE_LABELS = {LINE_NONE: "미입고", LINE_PARTIAL: "부분입고", LINE_DONE: "입고완료", LINE_OVER: "초과입고"}
|
||||||
|
|
||||||
|
# 발주서 상태 — 진행(open·partial)은 미입고 현황에 나온다
|
||||||
|
ST_OPEN, ST_PARTIAL, ST_DONE, ST_OVER, ST_CLOSED, ST_CANCELLED = "open", "partial", "done", "over", "closed", "cancelled"
|
||||||
|
# 모든 품목이 입고완료·초과입고 = "전체 입고 완료"(2026-10-17 요청 — 초과가 있으면 화면에 "초과 포함"만 덧붙인다)
|
||||||
|
ORDER_LABELS = {ST_OPEN: "발주", ST_PARTIAL: "부분입고", ST_DONE: "전체 입고 완료", ST_OVER: "전체 입고 완료",
|
||||||
|
ST_CLOSED: "종결", ST_CANCELLED: "취소"}
|
||||||
|
ACTIVE_STATUSES = (ST_OPEN, ST_PARTIAL) # 아직 더 들어올 것이 있는 발주
|
||||||
|
STATUS_FILTERS = { # 목록 거르기
|
||||||
|
"active": ("진행 중", ACTIVE_STATUSES),
|
||||||
|
"done": ("완료", (ST_DONE, ST_OVER)),
|
||||||
|
"closed": ("종결·취소", (ST_CLOSED, ST_CANCELLED)),
|
||||||
|
"all": ("전체", tuple(ORDER_LABELS)),
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
WEEKDAYS_KO = "월화수목금토일"
|
||||||
|
|
||||||
|
|
||||||
|
def fmt_date(d: date | None) -> str:
|
||||||
|
"""날짜 서식 — 2026.10.17(토). 입출고 화면·메일 모두 이 모양(2026-10-17 요청). 화면 쪽은 _macros.html ymd 와 같다."""
|
||||||
|
if not d:
|
||||||
|
return ""
|
||||||
|
return f"{d:%Y.%m.%d}({WEEKDAYS_KO[d.weekday()]})"
|
||||||
|
|
||||||
|
|
||||||
|
def fmt_datetime(dt: datetime | None) -> str:
|
||||||
|
"""2026.10.17(토) 15:14 — 시각은 DB 에서 KST 로 읽는다(db._KstTimestamptzLoader)."""
|
||||||
|
return f"{fmt_date(dt)} {dt:%H:%M}" if dt else ""
|
||||||
|
|
||||||
|
|
||||||
|
def line_status(qty: int, received: int) -> str:
|
||||||
|
if received <= 0:
|
||||||
|
return LINE_NONE
|
||||||
|
if received < qty:
|
||||||
|
return LINE_PARTIAL
|
||||||
|
return LINE_DONE if received == qty else LINE_OVER
|
||||||
|
|
||||||
|
|
||||||
|
def order_status(lines: Iterable[dict[str, Any]], *, closed: bool = False, cancelled: bool = False) -> str:
|
||||||
|
"""lines: [{qty, received}]. 취소·종결이 먼저, 그다음 입고 합계로."""
|
||||||
|
if cancelled:
|
||||||
|
return ST_CANCELLED
|
||||||
|
if closed:
|
||||||
|
return ST_CLOSED
|
||||||
|
sts = [line_status(int(x["qty"]), int(x.get("received") or 0)) for x in lines]
|
||||||
|
if not sts or all(s == LINE_NONE for s in sts):
|
||||||
|
return ST_OPEN
|
||||||
|
if any(s in (LINE_NONE, LINE_PARTIAL) for s in sts):
|
||||||
|
return ST_PARTIAL
|
||||||
|
return ST_OVER if any(s == LINE_OVER for s in sts) else ST_DONE
|
||||||
|
|
||||||
|
|
||||||
|
def summarize(lines: list[dict[str, Any]]) -> dict[str, int]:
|
||||||
|
"""발주·입고·미입고(0 아래로 안 내려감)·초과 합계."""
|
||||||
|
ordered = sum(int(x["qty"]) for x in lines)
|
||||||
|
received = sum(int(x.get("received") or 0) for x in lines)
|
||||||
|
remaining = sum(max(int(x["qty"]) - int(x.get("received") or 0), 0) for x in lines)
|
||||||
|
over = sum(max(int(x.get("received") or 0) - int(x["qty"]), 0) for x in lines)
|
||||||
|
pct = min(100, round(received * 100 / ordered)) if ordered else 0
|
||||||
|
return {"ordered": ordered, "received": received, "remaining": remaining, "over": over, "pct": pct}
|
||||||
|
|
||||||
|
|
||||||
|
def decorate_lines(lines: list[dict[str, Any]]) -> list[dict[str, Any]]:
|
||||||
|
"""화면용 — 품목마다 미입고·초과·상태 이름."""
|
||||||
|
out = []
|
||||||
|
for x in lines:
|
||||||
|
qty, rec = int(x["qty"]), int(x.get("received") or 0)
|
||||||
|
st = line_status(qty, rec)
|
||||||
|
out.append({**x, "received": rec, "remaining": max(qty - rec, 0), "over": max(rec - qty, 0),
|
||||||
|
"status": st, "status_label": LINE_LABELS[st]})
|
||||||
|
return out
|
||||||
|
|
||||||
|
|
||||||
|
# ── 입력 검사 ────────────────────────────────────────────────
|
||||||
|
def parse_qty(raw: Any, *, label: str = "수량", allow_zero: bool = False) -> int:
|
||||||
|
s = str(raw if raw is not None else "").replace(",", "").strip()
|
||||||
|
if not s:
|
||||||
|
if allow_zero:
|
||||||
|
return 0
|
||||||
|
raise ValueError(f"{label}을(를) 입력하세요.")
|
||||||
|
try:
|
||||||
|
n = int(s)
|
||||||
|
except ValueError:
|
||||||
|
raise ValueError(f"{label}은(는) 정수로 입력하세요.") from None
|
||||||
|
if n < 0 or (n == 0 and not allow_zero):
|
||||||
|
raise ValueError(f"{label}은(는) {0 if allow_zero else 1} 이상이어야 합니다.")
|
||||||
|
if n > MAX_QTY:
|
||||||
|
raise ValueError(f"{label}이(가) 너무 큽니다.")
|
||||||
|
return n
|
||||||
|
|
||||||
|
|
||||||
|
def parse_date(raw: Any, *, label: str, required: bool = True) -> date | None:
|
||||||
|
s = str(raw or "").strip()
|
||||||
|
if not s:
|
||||||
|
if required:
|
||||||
|
raise ValueError(f"{label}을(를) 입력하세요.")
|
||||||
|
return None
|
||||||
|
try:
|
||||||
|
return date.fromisoformat(s)
|
||||||
|
except ValueError:
|
||||||
|
raise ValueError(f"{label} 형식이 올바르지 않습니다(YYYY-MM-DD).") from None
|
||||||
|
|
||||||
|
|
||||||
|
def validate_order(*, factory_id: Any, order_date: Any, due_date: Any, memo: Any,
|
||||||
|
codes: list[str], quantities: list[str], line_memos: list[str] | None = None) -> dict[str, Any]:
|
||||||
|
"""발주서 폼 → 정리된 값. 빈 줄(코드·수량 둘 다 없음)은 건너뛴다. 같은 제품 두 줄은 오류."""
|
||||||
|
errors: list[str] = []
|
||||||
|
try:
|
||||||
|
fid = int(str(factory_id or "").strip())
|
||||||
|
except ValueError:
|
||||||
|
fid = 0
|
||||||
|
if fid <= 0:
|
||||||
|
errors.append("공장을 고르세요.")
|
||||||
|
od = dd = None
|
||||||
|
try:
|
||||||
|
od = parse_date(order_date, label="발주일")
|
||||||
|
except ValueError as exc:
|
||||||
|
errors.append(str(exc))
|
||||||
|
try:
|
||||||
|
dd = parse_date(due_date, label="입고 예정일", required=False)
|
||||||
|
except ValueError as exc:
|
||||||
|
errors.append(str(exc))
|
||||||
|
if od and dd and dd < od:
|
||||||
|
errors.append("입고 예정일이 발주일보다 빠릅니다.")
|
||||||
|
line_memos = line_memos or []
|
||||||
|
lines: list[dict[str, Any]] = []
|
||||||
|
seen: set[str] = set()
|
||||||
|
for i, code in enumerate(codes):
|
||||||
|
code = (code or "").strip().upper()
|
||||||
|
raw_qty = quantities[i] if i < len(quantities) else ""
|
||||||
|
if not code and not str(raw_qty or "").strip():
|
||||||
|
continue
|
||||||
|
if not code:
|
||||||
|
errors.append(f"{i + 1}번째 줄: 제품을 고르세요.")
|
||||||
|
continue
|
||||||
|
if code in seen:
|
||||||
|
errors.append(f"{code}: 같은 제품이 두 줄에 있습니다 — 한 줄로 합쳐 주세요.")
|
||||||
|
continue
|
||||||
|
seen.add(code)
|
||||||
|
try:
|
||||||
|
qty = parse_qty(raw_qty, label=f"{code} 발주 수량")
|
||||||
|
except ValueError as exc:
|
||||||
|
errors.append(str(exc))
|
||||||
|
continue
|
||||||
|
lines.append({"item_code": code, "qty": qty,
|
||||||
|
"memo": str(line_memos[i] if i < len(line_memos) else "").strip()[:MEMO_MAX]})
|
||||||
|
if not lines and not any("줄" in e or "수량" in e for e in errors):
|
||||||
|
errors.append("발주할 제품을 한 줄 이상 넣으세요.")
|
||||||
|
if len(lines) > MAX_LINES:
|
||||||
|
errors.append(f"한 발주서에 {MAX_LINES}개 제품까지 넣을 수 있습니다.")
|
||||||
|
if errors:
|
||||||
|
raise ValueError("\n".join(errors))
|
||||||
|
return {"factory_id": fid, "order_date": od, "due_date": dd, "memo": str(memo or "").strip()[:MEMO_MAX], "lines": lines}
|
||||||
|
|
||||||
|
|
||||||
|
def validate_receipt(order_lines: list[dict[str, Any]], quantities: dict[int, Any], *,
|
||||||
|
receipt_date: Any, memo: Any) -> dict[str, Any]:
|
||||||
|
"""입고 입력 — quantities: {발주 줄 id: 입력값}. 빈칸·0 은 이번에 안 들어온 것.
|
||||||
|
over = 이번 입고로 발주를 넘는 품목(확인 받은 뒤 저장). order_lines 는 지금까지 누적 입고(received)를 포함."""
|
||||||
|
errors: list[str] = []
|
||||||
|
try:
|
||||||
|
rd = parse_date(receipt_date, label="입고일")
|
||||||
|
except ValueError as exc:
|
||||||
|
errors.append(str(exc))
|
||||||
|
rd = None
|
||||||
|
by_id = {int(x["id"]): x for x in order_lines}
|
||||||
|
items: list[dict[str, Any]] = []
|
||||||
|
over: list[dict[str, Any]] = []
|
||||||
|
for lid, raw in quantities.items():
|
||||||
|
line = by_id.get(int(lid))
|
||||||
|
if line is None:
|
||||||
|
errors.append("이 발주서에 없는 품목이 들어 있습니다.")
|
||||||
|
continue
|
||||||
|
try:
|
||||||
|
qty = parse_qty(raw, label=f"{line['item_code']} 입고 수량", allow_zero=True)
|
||||||
|
except ValueError as exc:
|
||||||
|
errors.append(str(exc))
|
||||||
|
continue
|
||||||
|
if qty == 0:
|
||||||
|
continue
|
||||||
|
items.append({"order_line_id": int(lid), "qty": qty})
|
||||||
|
after = int(line.get("received") or 0) + qty
|
||||||
|
if after > int(line["qty"]):
|
||||||
|
over.append({"item_code": line["item_code"], "item_name": line.get("item_name", ""),
|
||||||
|
"ordered": int(line["qty"]), "after": after, "over": after - int(line["qty"])})
|
||||||
|
if not items and not errors:
|
||||||
|
errors.append("입고 수량을 한 품목 이상 넣으세요.")
|
||||||
|
if errors:
|
||||||
|
raise ValueError("\n".join(errors))
|
||||||
|
return {"receipt_date": rd, "memo": str(memo or "").strip()[:MEMO_MAX], "items": items, "over": over}
|
||||||
|
|
||||||
|
|
||||||
|
def order_no(order_date: date, seq: int) -> str:
|
||||||
|
"""PO-YYMMDD-NN — 발주일 기준 그날 순번(01부터)."""
|
||||||
|
return f"PO-{order_date:%y%m%d}-{seq:02d}"
|
||||||
|
|
||||||
|
|
||||||
|
# ════════════════════════════════════════════════════════════
|
||||||
|
# 발주 메일(2026-10-16, 마이그레이션 003) — 받는 주소 검사, 본문(요약) 만들기. 보내기는 gmail.py
|
||||||
|
# ════════════════════════════════════════════════════════════
|
||||||
|
MAX_RECIPIENTS = 10
|
||||||
|
_EMAIL_RE = re.compile(r"^[A-Za-z0-9._%+\-']+@[A-Za-z0-9.\-]+\.[A-Za-z]{2,}$")
|
||||||
|
|
||||||
|
|
||||||
|
def parse_emails(raw: Any, *, label: str = "이메일", required: bool = False) -> list[str]:
|
||||||
|
"""'a@x.com, b@y.co.kr; c@z.com' → 주소 목록(순서 유지·중복 제거). 형식이 틀리면 ValueError."""
|
||||||
|
out: list[str] = []
|
||||||
|
for part in re.split(r"[\s,;]+", str(raw or "")):
|
||||||
|
if not part:
|
||||||
|
continue
|
||||||
|
if not _EMAIL_RE.match(part) or len(part) > 254:
|
||||||
|
raise ValueError(f"{label} 형식이 올바르지 않습니다: {part[:60]}")
|
||||||
|
if part.lower() not in [x.lower() for x in out]:
|
||||||
|
out.append(part)
|
||||||
|
if required and not out:
|
||||||
|
raise ValueError(f"{label}을(를) 입력하세요.")
|
||||||
|
if len(out) > MAX_RECIPIENTS:
|
||||||
|
raise ValueError(f"{label}은(는) {MAX_RECIPIENTS}개까지 넣을 수 있습니다.")
|
||||||
|
return out
|
||||||
|
|
||||||
|
|
||||||
|
# 간단 발주 메일(2026-11-04) — 이 공장들엔 품목 표를 번호·제품 코드·제품명·수량·박스당 수량·박스 수·비고만, 요약에서도 금액·무게·은을 뺀다.
|
||||||
|
SIMPLE_MAIL_FACTORIES = ("대성화학", "인천공장")
|
||||||
|
|
||||||
|
|
||||||
|
def is_simple_mail_factory(name: Any) -> bool:
|
||||||
|
"""이름 일부·띄어쓰기가 달라도 맞게 — 놓치면 단가가 공장에 나간다."""
|
||||||
|
compact = "".join(str(name or "").split())
|
||||||
|
return any(word in compact for word in SIMPLE_MAIL_FACTORIES)
|
||||||
|
|
||||||
|
|
||||||
|
def line_boxes(x: dict[str, Any]) -> dict[str, Any]:
|
||||||
|
"""간단 발주 메일 칸 — 박스당 수량·박스 수(올림). 뚜껑이 있으면 통·뚜껑 따로, 입수가 없으면 '-'(total None)."""
|
||||||
|
body, lid, qty = x.get("body_per_box"), x.get("lid_per_box"), int(x["qty"])
|
||||||
|
if not body:
|
||||||
|
return {"per": "-", "count": "-", "total": None}
|
||||||
|
boxes = -(-qty // body)
|
||||||
|
if not lid:
|
||||||
|
return {"per": f"{body:,}개", "count": f"{boxes:,}박스", "total": boxes}
|
||||||
|
lids = -(-qty // lid)
|
||||||
|
return {"per": f"통 {body:,}개 · 뚜껑 {lid:,}개", "count": f"통 {boxes:,} · 뚜껑 {lids:,}박스", "total": boxes + lids}
|
||||||
|
|
||||||
|
|
||||||
|
def order_mail(order: dict[str, Any], *, sender_name: str, sender_email: str) -> dict[str, str]:
|
||||||
|
"""발주서 → 메일 제목·글 본문·HTML 본문(요약). order = db.get_order 결과.
|
||||||
|
품목마다 단가·금액(수량 × 단가)·전체 무게(개당 g × 수량, kg)·PP 사용량(전체 무게 − 은 무게, kg)·은 함유량(%·전체 무게 × %, kg)
|
||||||
|
— 발주 품목에 남긴 그때 값(004). 없으면 '-'. (2026-10-19 — 예전엔 PP(g/개)·개당 은 g)"""
|
||||||
|
lines = order["lines"]
|
||||||
|
first = (lines[0]["item_name"] or lines[0]["item_code"]) if lines else ""
|
||||||
|
more = f" 외 {len(lines) - 1}종" if len(lines) > 1 else ""
|
||||||
|
subject = f"[발주] {order['order_no']} · {order['factory_name']} · {first}{more}"
|
||||||
|
total = sum(int(x["qty"]) for x in lines)
|
||||||
|
money = order_totals(lines)
|
||||||
|
due = fmt_date(order["due_date"]) if order.get("due_date") else "협의"
|
||||||
|
greet = f"{order['factory_manager']}님, 안녕하세요." if order.get("factory_manager") else "안녕하세요."
|
||||||
|
who = sender_name or sender_email
|
||||||
|
facts = [("발주번호", order["order_no"]), ("발주일", fmt_date(order["order_date"])),
|
||||||
|
("입고 예정일", due), ("품목", f"{len(lines)}종 · 총 {total:,}개")]
|
||||||
|
simple = is_simple_mail_factory(order.get("factory_name"))
|
||||||
|
ag_kg = money["silver_g"] / Decimal(1000) if money["silver_g"] is not None else None
|
||||||
|
if not simple:
|
||||||
|
if money["amount"] is not None:
|
||||||
|
note = f" (단가 미입력 {money['missing_price']}종 제외)" if money["missing_price"] else ""
|
||||||
|
facts.append(("발주 금액", f"{fmt_num(money['amount'])}원{note}"))
|
||||||
|
if money["pp_kg"] is not None:
|
||||||
|
facts.append(("전체 무게", f"{fmt_num(money['pp_kg'], 3)} kg"))
|
||||||
|
if money["pp_use_kg"] is not None:
|
||||||
|
facts.append(("PP 사용량", f"{fmt_num(money['pp_use_kg'], 3)} kg"))
|
||||||
|
if ag_kg is not None:
|
||||||
|
facts.append(("은(Ag) 총량", f"{fmt_num(ag_kg, 4)} kg"))
|
||||||
|
if order.get("memo"):
|
||||||
|
facts.append(("요청 사항", order["memo"]))
|
||||||
|
|
||||||
|
def cells(x: dict[str, Any]) -> dict[str, str]:
|
||||||
|
price, pct = to_dec(x.get("unit_price")), to_dec(x.get("silver_pct"))
|
||||||
|
amt = line_amount(int(x["qty"]), price)
|
||||||
|
use = line_usage(x)
|
||||||
|
total_kg, ag_kg = use["total_kg"], use["ag_kg"]
|
||||||
|
return {"price": fmt_num(price) if price is not None else "-", "amount": fmt_num(amt) if amt is not None else "-",
|
||||||
|
"weight": fmt_num(total_kg, 3) if total_kg is not None else "-",
|
||||||
|
"pp_use": fmt_num(total_kg - ag_kg, 3) if ag_kg is not None else "-",
|
||||||
|
"ag": (f"{fmt_num(pct, 4)}%" + (f" ({fmt_num(ag_kg, 4)}kg)" if ag_kg is not None else "")) if pct is not None else "-"}
|
||||||
|
|
||||||
|
# 글 본문(HTML 을 못 보는 메일 프로그램용)
|
||||||
|
text = [greet, "", "아래와 같이 제품 제작을 발주합니다.", ""]
|
||||||
|
text += [f"- {k}: {v}" for k, v in facts]
|
||||||
|
text += ["", "[발주 품목] 제품 코드 · 제품명 · 수량 · 박스당 수량 · 박스 수 · 비고" if simple else "[발주 품목] 수량 · 단가 · 금액 · 전체 무게 · PP 사용량 · 은 함유량"]
|
||||||
|
for i, x in enumerate(lines, start=1):
|
||||||
|
c = cells(x)
|
||||||
|
b = line_boxes(x)
|
||||||
|
if simple:
|
||||||
|
detail = f" · 박스당 {b['per']} · {b['count']}" if b["total"] is not None else ""
|
||||||
|
else:
|
||||||
|
detail = (f" · 단가 {c['price']} · 금액 {c['amount']}"
|
||||||
|
f" · 전체 무게 {c['weight'] + 'kg' if c['weight'] != '-' else '-'}"
|
||||||
|
f" · PP 사용량 {c['pp_use'] + 'kg' if c['pp_use'] != '-' else '-'} · 은 {c['ag']}")
|
||||||
|
text.append(f"{i}. {x['item_code']} {x['item_name']} — {int(x['qty']):,}개{detail}"
|
||||||
|
+ (f" ({x['memo']})" if x.get("memo") else ""))
|
||||||
|
text += ["", "입고 예정일까지 물류로 입고 부탁드리며, 일정이 바뀌면 회신 부탁드립니다.", "", f"발주 담당: {who} ({sender_email})"]
|
||||||
|
# HTML 본문 — 값은 모두 escape
|
||||||
|
e = _html.escape
|
||||||
|
td = "padding:6px 10px;border:1px solid #d9dce1;"
|
||||||
|
r = "text-align:right;white-space:nowrap;"
|
||||||
|
# 요약 표 = 항목·값 두 쌍씩 한 줄(4열, 2026-10-19 — 예전 2열 × 8행). 요청 사항(길 수 있음)은 맨 아래 한 줄 전체.
|
||||||
|
# 칸 높이는 글자 한 줄에 맞게 — 받은 메일(메일 프로그램)에서 칸이 크게 늘어나 보여 줄 높이·글자 크기·위아래 여백을 칸마다 못 박는다.
|
||||||
|
ftd = "padding:4px 10px;border:1px solid #d9dce1;font-size:14px;line-height:20px;height:20px;vertical-align:middle;white-space:nowrap;"
|
||||||
|
fth = f"{ftd}background:#f6f7f9;text-align:left;font-weight:700;"
|
||||||
|
pairs = [(k, v) for k, v in facts if k != "요청 사항"]
|
||||||
|
fact_rows = ""
|
||||||
|
for i in range(0, len(pairs), 2):
|
||||||
|
cols = "".join(f'<th style="{fth}">{e(k)}</th><td style="{ftd}">{e(str(v))}</td>' for k, v in pairs[i:i + 2])
|
||||||
|
if len(pairs[i:i + 2]) == 1:
|
||||||
|
cols += f'<th style="{fth}"></th><td style="{ftd}"></td>'
|
||||||
|
fact_rows += f"<tr>{cols}</tr>"
|
||||||
|
if order.get("memo"): # 요청 사항은 길면 줄을 바꿔야 하므로 높이를 고정하지 않는다
|
||||||
|
memo_td = "padding:4px 10px;border:1px solid #d9dce1;font-size:14px;line-height:20px;vertical-align:middle;"
|
||||||
|
fact_rows += (f'<tr><th style="{fth}">요청 사항</th>'
|
||||||
|
f'<td colspan="3" style="{memo_td}">{e(str(order["memo"]))}</td></tr>')
|
||||||
|
rows = []
|
||||||
|
for i, x in enumerate(lines, start=1):
|
||||||
|
c = cells(x)
|
||||||
|
# 색상 있는 품목(006) = 줄 전체 배경 그 색 — 메일 프로그램이 tr 배경을 무시하기도 해서 칸마다도 칠한다
|
||||||
|
hexc = color_hex(x.get("color"))
|
||||||
|
ctd = f"{td}background:{hexc};" if hexc else td
|
||||||
|
tr_style = f' style="background:{hexc}"' if hexc else ""
|
||||||
|
b = line_boxes(x)
|
||||||
|
detail = (f'<td style="{ctd}{r}">{e(b["per"])}</td><td style="{ctd}{r}">{e(b["count"])}</td>') if simple else (
|
||||||
|
f'<td style="{ctd}{r}">{e(c["price"])}</td><td style="{ctd}{r}">{e(c["amount"])}</td>'
|
||||||
|
f'<td style="{ctd}{r}">{e(c["weight"])}</td><td style="{ctd}{r}">{e(c["pp_use"])}</td><td style="{ctd}{r}">{e(c["ag"])}</td>')
|
||||||
|
rows.append(
|
||||||
|
f'<tr{tr_style}><td style="{ctd}text-align:center">{i}</td>'
|
||||||
|
f'<td style="{ctd}font-family:Consolas,monospace">{e(x["item_code"])}</td>'
|
||||||
|
f'<td style="{ctd}">{e(x["item_name"])}</td><td style="{ctd}{r}">{int(x["qty"]):,}</td>{detail}'
|
||||||
|
f'<td style="{ctd}">{e(x.get("memo") or "")}</td></tr>')
|
||||||
|
# 합계 줄(2026-10-21) — 금액 뒤 " 원", 무게 뒤 " kg", 무게는 소수 첫째 자리에서 반올림(정수 kg)
|
||||||
|
foot_amount = f'{fmt_num(money["amount"])} 원' if money["amount"] is not None else ""
|
||||||
|
foot_pp = f'{fmt_num(money["pp_kg"], 0)} kg' if money["pp_kg"] is not None else ""
|
||||||
|
foot_use = f'{fmt_num(money["pp_use_kg"], 0)} kg' if money["pp_use_kg"] is not None else ""
|
||||||
|
foot_ag = f'{fmt_num(ag_kg, 0)} kg' if ag_kg is not None else ""
|
||||||
|
bg = "background:#f6f7f9;"
|
||||||
|
box_totals = [t for t in (line_boxes(x)["total"] for x in lines) if t is not None]
|
||||||
|
foot_boxes = f"{sum(box_totals):,}박스" if box_totals else ""
|
||||||
|
if box_totals and len(box_totals) < len(lines):
|
||||||
|
foot_boxes += f" (미설정 {len(lines) - len(box_totals)}종 제외)"
|
||||||
|
head_detail = f'<th style="{td}">박스당 수량</th><th style="{td}">박스 수</th>' if simple else (
|
||||||
|
f'<th style="{td}">단가(원)</th><th style="{td}">금액(원)</th>'
|
||||||
|
f'<th style="{td}">전체 무게(kg)</th><th style="{td}">PP 사용량(kg)</th><th style="{td}">은(Ag) 함유량</th>')
|
||||||
|
foot_detail = f'<th style="{td}{bg}"></th><th style="{td}{bg}{r}">{e(foot_boxes)}</th>' if simple else (
|
||||||
|
f'<th style="{td}{bg}"></th><th style="{td}{bg}{r}">{e(foot_amount)}</th>'
|
||||||
|
f'<th style="{td}{bg}{r}">{e(foot_pp)}</th><th style="{td}{bg}{r}">{e(foot_use)}</th><th style="{td}{bg}{r}">{e(foot_ag)}</th>')
|
||||||
|
html = (
|
||||||
|
'<div style="font-family:\'Malgun Gothic\',\'Apple SD Gothic Neo\',sans-serif;font-size:14px;color:#1d1d1f;line-height:1.6">'
|
||||||
|
f"<p>{e(greet)}<br>아래와 같이 제품 제작을 발주합니다.</p>"
|
||||||
|
f'<table cellpadding="0" cellspacing="0" style="border-collapse:collapse;margin:8px 0 0">{fact_rows}</table>'
|
||||||
|
# 두 표 사이 18px — 표 margin 은 메일 프로그램마다 무시되기도 해서 높이 18px 빈 줄로 띄운다
|
||||||
|
'<div style="height:18px;line-height:18px;font-size:1px"> </div>'
|
||||||
|
'<table style="border-collapse:collapse;min-width:640px;margin:0">'
|
||||||
|
f'<thead><tr style="{bg}"><th style="{td}">{"번호" if simple else "No"}</th><th style="{td}">제품 코드</th><th style="{td}">제품명</th>'
|
||||||
|
f'<th style="{td}">수량</th>{head_detail}'
|
||||||
|
f'<th style="{td}">비고</th></tr></thead>'
|
||||||
|
f'<tbody>{"".join(rows)}</tbody>'
|
||||||
|
f'<tfoot><tr><th colspan="3" style="{td}{bg}text-align:right">합계</th>'
|
||||||
|
f'<th style="{td}{bg}{r}">{total:,}</th>{foot_detail}'
|
||||||
|
f'<th style="{td}{bg}"></th></tr></tfoot></table>'
|
||||||
|
"<p>입고 예정일까지 물류로 입고 부탁드리며, 일정이 바뀌면 회신 부탁드립니다.</p>"
|
||||||
|
f'<p style="color:#555">발주 담당: {e(who)} (<a href="mailto:{e(sender_email)}">{e(sender_email)}</a>)</p></div>'
|
||||||
|
)
|
||||||
|
return {"subject": subject, "text": "\n".join(text), "html": html}
|
||||||
|
|
||||||
|
|
||||||
|
# 발주 메일 본문 고치기(2026-10-27) — 미리보기 창에서 사람이 고친 HTML 을 그대로 보낸다.
|
||||||
|
# 표·서식(인라인 style)은 남기고 스크립트·이벤트 속성·외부 리소스(url()·img)는 뺀다. 글 버전은 고친 HTML 에서 다시 만든다.
|
||||||
|
MAIL_HTML_MAX = 300_000
|
||||||
|
_MAIL_TAGS = {"div", "p", "br", "span", "b", "strong", "i", "em", "u", "s", "strike", "font", "a", "ul", "ol", "li",
|
||||||
|
"h1", "h2", "h3", "h4", "blockquote", "sub", "sup", "hr",
|
||||||
|
"table", "thead", "tbody", "tfoot", "tr", "th", "td", "colgroup", "col", "caption"}
|
||||||
|
_MAIL_VOID = {"br", "hr", "col"}
|
||||||
|
_MAIL_DROP = {"script", "style", "iframe", "object", "embed", "head", "title", "template", "noscript", "svg", "math",
|
||||||
|
"textarea", "select", "button", "form", "input", "link", "meta"}
|
||||||
|
_MAIL_ATTRS = {"colspan", "rowspan", "cellpadding", "cellspacing", "border", "align", "valign", "width", "height", "color"}
|
||||||
|
_MAIL_STYLE_PROPS = {"color", "background", "background-color", "font-family", "font-size", "font-weight", "font-style",
|
||||||
|
"text-decoration", "text-align", "vertical-align", "white-space", "line-height", "height", "width",
|
||||||
|
"min-width", "max-width", "padding", "padding-top", "padding-right", "padding-bottom", "padding-left",
|
||||||
|
"margin", "margin-top", "margin-right", "margin-bottom", "margin-left", "border", "border-top",
|
||||||
|
"border-right", "border-bottom", "border-left", "border-color", "border-collapse", "border-spacing"}
|
||||||
|
_MAIL_STYLE_VALUE_RE = re.compile(r"^[#\w\s.,%()'\"-]{1,120}$")
|
||||||
|
_MAIL_ATTR_VALUE_RE = re.compile(r"^[#\w%.-]{1,20}$")
|
||||||
|
|
||||||
|
|
||||||
|
def _mail_style(value: str) -> str:
|
||||||
|
out = []
|
||||||
|
for decl in value.split(";"):
|
||||||
|
prop, _, val = decl.partition(":")
|
||||||
|
prop, val = prop.strip().lower(), val.strip()
|
||||||
|
if prop == "text-decoration-line": # 서식 막대(Chrome execCommand)가 밑줄·취소선을 이렇게 만든다 — 메일 프로그램은 text-decoration 만 아는 곳이 많다
|
||||||
|
prop = "text-decoration"
|
||||||
|
if prop in _MAIL_STYLE_PROPS and _MAIL_STYLE_VALUE_RE.match(val) and not re.search(r"url|expression|@import", val, re.I):
|
||||||
|
out.append(f"{prop}:{val}")
|
||||||
|
return ";".join(out)
|
||||||
|
|
||||||
|
|
||||||
|
class _MailSanitizer(_html_parser.HTMLParser):
|
||||||
|
def __init__(self) -> None:
|
||||||
|
super().__init__(convert_charrefs=True)
|
||||||
|
self.out: list[str] = []
|
||||||
|
self.stack: list[str] = []
|
||||||
|
self.skip = 0
|
||||||
|
|
||||||
|
def handle_starttag(self, tag: str, attrs: list[tuple[str, str | None]]) -> None:
|
||||||
|
if tag in _MAIL_DROP:
|
||||||
|
self.skip += 1
|
||||||
|
return
|
||||||
|
if self.skip or tag not in _MAIL_TAGS:
|
||||||
|
return
|
||||||
|
extra = ""
|
||||||
|
for k, v in attrs:
|
||||||
|
v = (v or "").strip()
|
||||||
|
if k == "style":
|
||||||
|
style = _mail_style(v)
|
||||||
|
if style:
|
||||||
|
extra += f' style="{_html.escape(style)}"'
|
||||||
|
elif k == "href" and tag == "a" and re.match(r"^(https?:|mailto:)", v, re.I):
|
||||||
|
extra += f' href="{_html.escape(v)}"'
|
||||||
|
elif k in _MAIL_ATTRS and _MAIL_ATTR_VALUE_RE.match(v):
|
||||||
|
extra += f' {k}="{_html.escape(v)}"'
|
||||||
|
self.out.append(f"<{tag}{extra}>")
|
||||||
|
if tag not in _MAIL_VOID:
|
||||||
|
self.stack.append(tag)
|
||||||
|
|
||||||
|
def handle_startendtag(self, tag: str, attrs: list[tuple[str, str | None]]) -> None:
|
||||||
|
if tag in _MAIL_VOID:
|
||||||
|
self.handle_starttag(tag, attrs)
|
||||||
|
|
||||||
|
def handle_endtag(self, tag: str) -> None:
|
||||||
|
if tag in _MAIL_DROP:
|
||||||
|
self.skip = max(0, self.skip - 1)
|
||||||
|
return
|
||||||
|
if self.skip or tag not in self.stack:
|
||||||
|
return
|
||||||
|
while self.stack:
|
||||||
|
t = self.stack.pop()
|
||||||
|
self.out.append(f"</{t}>")
|
||||||
|
if t == tag:
|
||||||
|
break
|
||||||
|
|
||||||
|
def handle_data(self, data: str) -> None:
|
||||||
|
if not self.skip:
|
||||||
|
self.out.append(_html.escape(data, quote=False))
|
||||||
|
|
||||||
|
def result(self) -> str:
|
||||||
|
self.close()
|
||||||
|
while self.stack:
|
||||||
|
self.out.append(f"</{self.stack.pop()}>")
|
||||||
|
return "".join(self.out)
|
||||||
|
|
||||||
|
|
||||||
|
class _MailText(_html_parser.HTMLParser):
|
||||||
|
"""HTML → 글 버전 — 문단·줄은 줄바꿈, 표 칸은 " | " 로 잇는다."""
|
||||||
|
|
||||||
|
_BLOCK = {"p", "div", "tr", "li", "h1", "h2", "h3", "h4", "blockquote", "table", "hr"}
|
||||||
|
|
||||||
|
def __init__(self) -> None:
|
||||||
|
super().__init__(convert_charrefs=True)
|
||||||
|
self.parts: list[str] = []
|
||||||
|
self.cell = False # 이 줄에 이미 칸이 있다 — 다음 칸 앞에 구분자
|
||||||
|
|
||||||
|
def handle_starttag(self, tag: str, attrs: list[tuple[str, str | None]]) -> None:
|
||||||
|
if tag == "br" or tag in self._BLOCK:
|
||||||
|
self.parts.append("\n")
|
||||||
|
self.cell = False
|
||||||
|
elif tag in ("td", "th"):
|
||||||
|
if self.cell:
|
||||||
|
self.parts.append(" | ")
|
||||||
|
self.cell = True
|
||||||
|
if tag == "li":
|
||||||
|
self.parts.append("- ")
|
||||||
|
|
||||||
|
def handle_data(self, data: str) -> None:
|
||||||
|
self.parts.append(re.sub(r"\s+", " ", data.replace("\xa0", " ")))
|
||||||
|
|
||||||
|
|
||||||
|
def clean_mail_html(html: Any) -> str:
|
||||||
|
"""고친 메일 본문 HTML → 보낼 HTML(허용 태그·속성·글자 서식만). 너무 길거나 글이 없으면 ValueError."""
|
||||||
|
raw = str(html or "")
|
||||||
|
if len(raw) > MAIL_HTML_MAX:
|
||||||
|
raise ValueError("메일 본문이 너무 깁니다.")
|
||||||
|
p = _MailSanitizer()
|
||||||
|
p.feed(raw)
|
||||||
|
out = p.result()
|
||||||
|
if not mail_html_to_text(out).strip():
|
||||||
|
raise ValueError("메일 본문이 비어 있습니다.")
|
||||||
|
return out
|
||||||
|
|
||||||
|
|
||||||
|
def mail_html_to_text(html: str) -> str:
|
||||||
|
p = _MailText()
|
||||||
|
p.feed(str(html or ""))
|
||||||
|
p.close()
|
||||||
|
lines = [ln.strip() for ln in "".join(p.parts).split("\n")]
|
||||||
|
return re.sub(r"\n{3,}", "\n\n", "\n".join(lines)).strip()
|
||||||
|
|
||||||
|
|
||||||
|
# ════════════════════════════════════════════════════════════
|
||||||
|
# 상품 정보(2026-10-16, 마이그레이션 004) — 단가·무게(개당 g = PP량)·은(Ag) 함유량(%) 수기 입력
|
||||||
|
# 은 함량(g/개) = 무게 × 은 함유량 ÷ 100 — 저장하지 않고 계산(silver_g).
|
||||||
|
# ════════════════════════════════════════════════════════════
|
||||||
|
PRODUCT_LIMITS = {"unit_price": ("단가", Decimal("1000000000"), 2), "weight_g": ("무게", Decimal("1000000"), 2),
|
||||||
|
"silver_pct": ("은 함유량", Decimal("100"), 4)}
|
||||||
|
|
||||||
|
|
||||||
|
def to_dec(v: Any) -> Decimal | None:
|
||||||
|
if v is None or v == "":
|
||||||
|
return None
|
||||||
|
try:
|
||||||
|
return Decimal(str(v))
|
||||||
|
except (InvalidOperation, ValueError):
|
||||||
|
return None
|
||||||
|
|
||||||
|
|
||||||
|
def fmt_num(v: Any, places: int = 2) -> str:
|
||||||
|
"""1234.50 → '1,234.5', 1234 → '1,234' (소수 끝 0 은 뺀다)."""
|
||||||
|
d = to_dec(v)
|
||||||
|
if d is None:
|
||||||
|
return ""
|
||||||
|
q = d.quantize(Decimal(1).scaleb(-places), rounding=ROUND_HALF_UP)
|
||||||
|
s = f"{q:,.{places}f}"
|
||||||
|
return s.rstrip("0").rstrip(".") if "." in s else s
|
||||||
|
|
||||||
|
|
||||||
|
def silver_g(weight_g: Any, silver_pct: Any) -> Decimal | None:
|
||||||
|
w, p = to_dec(weight_g), to_dec(silver_pct)
|
||||||
|
if w is None or p is None:
|
||||||
|
return None
|
||||||
|
return (w * p / Decimal(100)).quantize(Decimal("0.0001"), rounding=ROUND_HALF_UP)
|
||||||
|
|
||||||
|
|
||||||
|
def line_usage(x: dict[str, Any]) -> dict[str, Decimal | None]:
|
||||||
|
"""발주 품목 한 줄의 발주 수량 전체 사용량(kg) — 전체 무게 = 개당 g × 수량, 은 = 전체 무게 × %, PP 사용량 = 전체 − 은
|
||||||
|
(은 함유량이 없으면 PP 사용량도 없음 — order_totals 의 pp_use_kg 와 같은 기준). 메일 표·발주서 화면 품목 표가 같이 쓴다."""
|
||||||
|
w, pct, q = to_dec(x.get("weight_g")), to_dec(x.get("silver_pct")), int(x["qty"])
|
||||||
|
total_kg = w * q / Decimal(1000) if w is not None else None
|
||||||
|
ag_kg = total_kg * pct / Decimal(100) if total_kg is not None and pct is not None else None
|
||||||
|
return {"total_kg": total_kg, "ag_kg": ag_kg, "pp_use_kg": total_kg - ag_kg if ag_kg is not None else None}
|
||||||
|
|
||||||
|
|
||||||
|
def line_amount(qty: int, unit_price: Any) -> Decimal | None:
|
||||||
|
p = to_dec(unit_price)
|
||||||
|
return None if p is None else (p * int(qty)).quantize(Decimal("0.01"), rounding=ROUND_HALF_UP)
|
||||||
|
|
||||||
|
|
||||||
|
def order_totals(lines: list[dict[str, Any]]) -> dict[str, Any]:
|
||||||
|
"""발주 금액 합(단가 있는 줄만, 없으면 None)·단가 없는 줄 수·PP 총량(= 전체 무게, kg)·은 총량(g)·
|
||||||
|
PP 사용량(kg, 무게·은 함유량이 다 있는 줄의 전체 무게 − 은 무게 — 메일 표, 2026-10-19)."""
|
||||||
|
amount = pp = ag = use = None
|
||||||
|
missing = 0
|
||||||
|
for x in lines:
|
||||||
|
q = int(x["qty"])
|
||||||
|
a = line_amount(q, x.get("unit_price"))
|
||||||
|
if a is None:
|
||||||
|
if not is_bag(x.get("item_name")): # 봉투·백은 단가가 원래 없음 — "단가 미입력" 안내에서 뺀다
|
||||||
|
missing += 1
|
||||||
|
else:
|
||||||
|
amount = (amount or Decimal(0)) + a
|
||||||
|
w = to_dec(x.get("weight_g"))
|
||||||
|
if w is not None:
|
||||||
|
pp = (pp or Decimal(0)) + w * q / Decimal(1000)
|
||||||
|
p = to_dec(x.get("silver_pct"))
|
||||||
|
if w is not None and p is not None: # 개당 은 g 를 반올림하기 전 값으로 곱한다(합계 오차 방지)
|
||||||
|
ag = (ag or Decimal(0)) + w * p / Decimal(100) * q
|
||||||
|
use = (use or Decimal(0)) + w * q * (Decimal(100) - p) / Decimal(100000)
|
||||||
|
return {"amount": amount, "missing_price": missing, "pp_kg": pp, "silver_g": ag,
|
||||||
|
"pp_use_kg": use}
|
||||||
|
|
||||||
|
|
||||||
|
def parse_decimal(raw: Any, *, key: str) -> Decimal | None:
|
||||||
|
"""상품 정보 칸 하나 — 빈칸은 None(미입력), 숫자·쉼표·0 이상·한도 안·소수 자리."""
|
||||||
|
label, limit, places = PRODUCT_LIMITS[key]
|
||||||
|
s = str(raw if raw is not None else "").replace(",", "").replace("%", "").strip()
|
||||||
|
if not s:
|
||||||
|
return None
|
||||||
|
try:
|
||||||
|
d = Decimal(s)
|
||||||
|
except InvalidOperation:
|
||||||
|
raise ValueError(f"{label}은(는) 숫자로 입력하세요.") from None
|
||||||
|
if not d.is_finite() or d < 0:
|
||||||
|
raise ValueError(f"{label}은(는) 0 이상이어야 합니다.")
|
||||||
|
if d > limit:
|
||||||
|
raise ValueError(f"{label}이(가) 너무 큽니다(최대 {fmt_num(limit, 0)}).")
|
||||||
|
return d.quantize(Decimal(1).scaleb(-places), rounding=ROUND_HALF_UP)
|
||||||
|
|
||||||
|
|
||||||
|
def validate_product_values(values: dict[str, Any]) -> dict[str, Decimal | None]:
|
||||||
|
"""{"unit_price","weight_g","silver_pct"} → 정리된 값. 틀리면 ValueError(칸 이름 포함)."""
|
||||||
|
return {k: parse_decimal(values.get(k), key=k) for k in PRODUCT_LIMITS}
|
||||||
|
|
||||||
|
|
||||||
|
def has_values(p: dict[str, Any]) -> bool:
|
||||||
|
"""단가·무게·은 함유량(·그룹·색상 006·박스 입수 007) 중 하나라도 넣었나 — 넣은 상품은 다시 불러와도 그대로 둔다."""
|
||||||
|
return (any(p.get(k) is not None for k in PRODUCT_LIMITS) or p.get("group_id") is not None
|
||||||
|
or (p.get("color") or "none") != "none" or any(p.get(k) is not None for k in BOX_FIELDS)
|
||||||
|
or p.get("boxes_per_pallet") is not None)
|
||||||
|
|
||||||
|
|
||||||
|
# ════════════════════════════════════════════════════════════
|
||||||
|
# 박스 입수(2026-10-21, 마이그레이션 007) — 통·뚜껑이 한 박스에 몇 개. 뚜껑이 없는 상품은 빈칸.
|
||||||
|
# 새 발주서 화면이 수량 → 통·뚜껑 박스 수(올림)·전체 파렛트(1파렛트 = PALLET_BOXES 박스, 올림)를 계산한다(메일엔 안 넣음).
|
||||||
|
# ════════════════════════════════════════════════════════════
|
||||||
|
BOX_FIELDS = {"body_per_box": "통 수량(박스)", "lid_per_box": "뚜껑 수량(박스)"}
|
||||||
|
MAX_PER_BOX = 1_000_000
|
||||||
|
PALLET_BOXES = 30
|
||||||
|
|
||||||
|
|
||||||
|
def parse_per_box(raw: Any, *, key: str = "", label: str = "") -> int | None:
|
||||||
|
"""박스 입수 칸 하나 — 빈칸은 None(없음·미입력), 1 이상 정수(쉼표 허용)."""
|
||||||
|
label = label or BOX_FIELDS[key]
|
||||||
|
s = str(raw if raw is not None else "").replace(",", "").strip()
|
||||||
|
if not s:
|
||||||
|
return None
|
||||||
|
if not s.isdigit():
|
||||||
|
raise ValueError(f"{label}은(는) 1 이상 정수로 입력하세요.")
|
||||||
|
n = int(s)
|
||||||
|
if n < 1:
|
||||||
|
raise ValueError(f"{label}은(는) 1 이상이어야 합니다(없으면 빈칸).")
|
||||||
|
if n > MAX_PER_BOX:
|
||||||
|
raise ValueError(f"{label}이(가) 너무 큽니다.")
|
||||||
|
return n
|
||||||
|
|
||||||
|
|
||||||
|
def validate_box_values(values: dict[str, Any]) -> dict[str, int | None]:
|
||||||
|
return {k: parse_per_box(values.get(k), key=k) for k in BOX_FIELDS}
|
||||||
|
|
||||||
|
|
||||||
|
# 봉투·백(2026-11-04, 마이그레이션 008) — 이름으로 판단(저장 안 함). 뚜껑 없음, 박스당 수량 = body_per_box, 1파렛트 박스 수는 상품마다.
|
||||||
|
BAG_NAME_WORDS = ("미라클 봉투", "미라클백")
|
||||||
|
|
||||||
|
|
||||||
|
def is_bag(name: Any) -> bool:
|
||||||
|
return any(word in str(name or "") for word in BAG_NAME_WORDS)
|
||||||
|
|
||||||
|
|
||||||
|
def validate_bag_values(values: dict[str, Any]) -> dict[str, int | None]:
|
||||||
|
return {"body_per_box": parse_per_box(values.get("body_per_box"), label="박스당 수량"), "lid_per_box": None,
|
||||||
|
"boxes_per_pallet": parse_per_box(values.get("boxes_per_pallet"), label="1파렛트당 박스 수량")}
|
||||||
|
|
||||||
|
|
||||||
|
def box_info(row: dict[str, Any]) -> dict[str, Any]:
|
||||||
|
"""발주서 화면 박스 계산 값 — 008 미적용(열 없음)이면 모두 일반 상품으로."""
|
||||||
|
bag = "boxes_per_pallet" in row and is_bag(row.get("item_name"))
|
||||||
|
return {"body_per_box": row.get("body_per_box"), "lid_per_box": None if bag else row.get("lid_per_box"),
|
||||||
|
"is_bag": bag, "boxes_per_pallet": row.get("boxes_per_pallet") if bag else None}
|
||||||
|
|
||||||
|
|
||||||
|
# ════════════════════════════════════════════════════════════
|
||||||
|
# 상품 그룹·색상(2026-10-21, 마이그레이션 006)
|
||||||
|
# 그룹에 은 함유량·색상을 한 번만 — 그룹 상품은 그룹 값, 그룹 없는 상품은 자기 값(effective_product).
|
||||||
|
# 색상 = 키 → (이름, 칸 색). 발주 메일 품목 표에서 색상 있는 품목 줄 전체 배경 = 칸 색(옅게 — 글자가 읽히게).
|
||||||
|
# ════════════════════════════════════════════════════════════
|
||||||
|
COLORS = {"none": ("색없음", ""), "orange": ("오렌지", "#FFD8B0"), "blue": ("파랑", "#CFE0FA"),
|
||||||
|
"gray": ("회색", "#DDDFE3"), "ivory": ("아이보리색", "#FFF6D9")}
|
||||||
|
MAX_GROUP_NAME = 100
|
||||||
|
|
||||||
|
|
||||||
|
def norm_color(raw: Any) -> str:
|
||||||
|
"""색상 키(none·orange·blue·gray·ivory). 빈칸 = none. 모르는 값은 ValueError."""
|
||||||
|
key = str(raw if raw is not None else "").strip().lower() or "none"
|
||||||
|
if key not in COLORS:
|
||||||
|
raise ValueError("색상은 " + "·".join(v[0] for v in COLORS.values()) + " 중에서 고르세요.")
|
||||||
|
return key
|
||||||
|
|
||||||
|
|
||||||
|
def color_hex(key: Any) -> str:
|
||||||
|
"""색상 키 → 칸 색(#RRGGBB). 색없음·모름 = ''."""
|
||||||
|
return COLORS.get(str(key or "none"), ("", ""))[1]
|
||||||
|
|
||||||
|
|
||||||
|
def color_name(key: Any) -> str:
|
||||||
|
return COLORS.get(str(key or "none"), COLORS["none"])[0]
|
||||||
|
|
||||||
|
|
||||||
|
def validate_group(values: dict[str, Any]) -> dict[str, Any]:
|
||||||
|
"""그룹 저장 값 — 이름(필수, 100자)·은 함유량(빈칸 = 미입력)·색상·순서."""
|
||||||
|
name = str(values.get("name") or "").strip()
|
||||||
|
if not name:
|
||||||
|
raise ValueError("그룹 이름을 넣으세요.")
|
||||||
|
if len(name) > MAX_GROUP_NAME:
|
||||||
|
raise ValueError(f"그룹 이름은 {MAX_GROUP_NAME}자까지입니다.")
|
||||||
|
try:
|
||||||
|
sort_order = int(str(values.get("sort_order") or "0").strip() or 0)
|
||||||
|
except ValueError:
|
||||||
|
raise ValueError("순서는 숫자로 넣으세요.") from None
|
||||||
|
return {"name": name, "silver_pct": parse_decimal(values.get("silver_pct"), key="silver_pct"),
|
||||||
|
"color": norm_color(values.get("color")), "sort_order": max(-9999, min(9999, sort_order))}
|
||||||
|
|
||||||
|
|
||||||
|
# ════════════════════════════════════════════════════════════
|
||||||
|
# 입고증 사진(2026-10-16, 마이그레이션 003)
|
||||||
|
# ════════════════════════════════════════════════════════════
|
||||||
|
MAX_PHOTOS = 10 # 입고 한 건에
|
||||||
|
MAX_PHOTO_BYTES = 10 * 1024 * 1024 # 한 장(브라우저가 줄여서 보내므로 보통 0.3~1MB)
|
||||||
|
|
||||||
|
|
||||||
|
def sniff_image(data: bytes) -> str | None:
|
||||||
|
"""파일 머리로 이미지 종류 판단(브라우저가 보낸 종류는 믿지 않는다). 모르면 None."""
|
||||||
|
if data[:3] == b"\xff\xd8\xff":
|
||||||
|
return "image/jpeg"
|
||||||
|
if data[:8] == b"\x89PNG\r\n\x1a\n":
|
||||||
|
return "image/png"
|
||||||
|
if data[:4] == b"RIFF" and data[8:12] == b"WEBP":
|
||||||
|
return "image/webp"
|
||||||
|
if data[:6] in (b"GIF87a", b"GIF89a"):
|
||||||
|
return "image/gif"
|
||||||
|
if data[4:12] in (b"ftypheic", b"ftypheix", b"ftypmif1", b"ftyphevc", b"ftypheif"):
|
||||||
|
return "image/heic" # 아이폰 원본 — 사파리 외 브라우저는 미리보기 못 함(내려받기)
|
||||||
|
return None
|
||||||
|
|
||||||
|
|
||||||
|
def validate_photos(files: list[tuple[str, bytes]], *, existing: int = 0) -> list[dict[str, Any]]:
|
||||||
|
"""[(파일 이름, 내용)] → [{filename, content_type, data}]. 빈 파일은 건너뛴다. 하나라도 틀리면 ValueError."""
|
||||||
|
out: list[dict[str, Any]] = []
|
||||||
|
for name, data in files:
|
||||||
|
if not data:
|
||||||
|
continue
|
||||||
|
name = (name or "photo").replace("\\", "/").rsplit("/", 1)[-1][:120]
|
||||||
|
if len(data) > MAX_PHOTO_BYTES:
|
||||||
|
raise ValueError(f"사진이 너무 큽니다(한 장 {MAX_PHOTO_BYTES // 1024 // 1024}MB까지): {name}")
|
||||||
|
ctype = sniff_image(data)
|
||||||
|
if ctype is None:
|
||||||
|
raise ValueError(f"사진 파일(JPG·PNG·WEBP·GIF·HEIC)만 올릴 수 있습니다: {name}")
|
||||||
|
out.append({"filename": name, "content_type": ctype, "data": data})
|
||||||
|
if existing + len(out) > MAX_PHOTOS:
|
||||||
|
raise ValueError(f"입고 한 건에 사진은 {MAX_PHOTOS}장까지입니다.")
|
||||||
|
return out
|
||||||
|
|
||||||
|
|
||||||
|
def rotate_image(data: bytes, degrees: int) -> bytes:
|
||||||
|
"""사진 내용을 시계 방향 90·270도로 돌려 같은 형식으로(2026-11-02). 휴대폰 사진의 회전 정보(EXIF)는 픽셀에 반영한 뒤 돌린다."""
|
||||||
|
from io import BytesIO # noqa: WPS433
|
||||||
|
|
||||||
|
from PIL import Image, ImageOps # noqa: WPS433
|
||||||
|
|
||||||
|
if degrees not in (90, 270):
|
||||||
|
raise ValueError("사진은 왼쪽·오른쪽으로만 돌릴 수 있습니다.")
|
||||||
|
kind = sniff_image(data)
|
||||||
|
if kind == "image/heic":
|
||||||
|
raise ValueError("HEIC 사진은 돌릴 수 없습니다 — JPG 로 바꿔 다시 올려 주세요.")
|
||||||
|
try:
|
||||||
|
im = Image.open(BytesIO(data))
|
||||||
|
if getattr(im, "n_frames", 1) > 1:
|
||||||
|
raise ValueError("움직이는 사진은 돌릴 수 없습니다.")
|
||||||
|
icc = im.info.get("icc_profile")
|
||||||
|
im = ImageOps.exif_transpose(im)
|
||||||
|
# PIL 의 ROTATE_n 은 반시계 방향 — 시계 90도 = ROTATE_270
|
||||||
|
im = im.transpose(Image.Transpose.ROTATE_270 if degrees == 90 else Image.Transpose.ROTATE_90)
|
||||||
|
fmt = {"image/jpeg": "JPEG", "image/png": "PNG", "image/webp": "WEBP", "image/gif": "GIF"}[kind]
|
||||||
|
opts: dict[str, Any] = {"icc_profile": icc} if icc and fmt != "GIF" else {}
|
||||||
|
if fmt in ("JPEG", "WEBP"):
|
||||||
|
opts["quality"] = 92
|
||||||
|
buf = BytesIO()
|
||||||
|
im.save(buf, format=fmt, **opts)
|
||||||
|
except ValueError:
|
||||||
|
raise
|
||||||
|
except Exception as exc: # noqa: BLE001 — 깨진 파일 등(원본은 그대로 둔다)
|
||||||
|
raise ValueError("이 사진은 돌릴 수 없습니다.") from exc
|
||||||
|
out = buf.getvalue()
|
||||||
|
if len(out) > MAX_PHOTO_BYTES:
|
||||||
|
raise ValueError(f"돌린 사진이 너무 큽니다(한 장 {MAX_PHOTO_BYTES // 1024 // 1024}MB까지).")
|
||||||
|
return out
|
||||||
|
|
||||||
|
|
||||||
|
# ════════════════════════════════════════════════════════════
|
||||||
|
# 입고 요청 메일(2026-10-19, 마이그레이션 005) — 입고 담당이 입고를 저장한 뒤 물류센터 입고 담당자에게
|
||||||
|
# "전산 등록 부탁" 메일(입고 담당 본인 Gmail). 받는 사람 = 옵션 → 물류센터 이메일, 참조 기본 = king@·bj@dbxcorp.co.kr.
|
||||||
|
# 본문 = 입고 상품 표(상품 이름·상품 코드·입고 수량·비고) + 입고증 사진을 본문 안 이미지(CID, 첨부 아님, 가로 600px 이하).
|
||||||
|
# ════════════════════════════════════════════════════════════
|
||||||
|
SETTING_LOGISTICS_EMAILS = "logistics_emails"
|
||||||
|
SETTING_RECEIPT_MAIL_CC = "receipt_mail_cc"
|
||||||
|
SETTING_ORDER_MAIL_CC = "order_mail_cc" # 발주 메일 참조 기본값(2026-10-19 — king@, 옵션 → 공장에서 고침)
|
||||||
|
SETTING_DEFAULTS = {SETTING_LOGISTICS_EMAILS: "", SETTING_RECEIPT_MAIL_CC: "king@dbxcorp.co.kr, bj@dbxcorp.co.kr",
|
||||||
|
SETTING_ORDER_MAIL_CC: "king@dbxcorp.co.kr"}
|
||||||
|
MAIL_IMAGE_MAX_W = 600
|
||||||
|
|
||||||
|
|
||||||
|
def clean_emails(raw: Any, *, label: str) -> str:
|
||||||
|
"""옵션 저장용 — 주소 검사 후 'a@x.com, b@y.com' 로 다시 씀(비우면 '')."""
|
||||||
|
return ", ".join(parse_emails(raw, label=label))
|
||||||
|
|
||||||
|
|
||||||
|
def mail_images(photos: list[dict[str, Any]]) -> tuple[list[dict[str, Any]], int]:
|
||||||
|
"""입고증 사진 → 메일 본문용 JPEG(가로 최대 600px, 세로는 비율대로, 회전 정보 반영).
|
||||||
|
반환 ([{cid, data, width, height}], 못 넣은 장수) — HEIC 등 서버가 못 여는 사진은 빼고 센다."""
|
||||||
|
from io import BytesIO # noqa: WPS433
|
||||||
|
|
||||||
|
from PIL import Image, ImageOps # noqa: WPS433
|
||||||
|
|
||||||
|
out: list[dict[str, Any]] = []
|
||||||
|
skipped = 0
|
||||||
|
for ph in photos:
|
||||||
|
try:
|
||||||
|
im = Image.open(BytesIO(bytes(ph["data"])))
|
||||||
|
if im.format == "JPEG":
|
||||||
|
im.draft("RGB", (MAIL_IMAGE_MAX_W * 2, MAIL_IMAGE_MAX_W * 2)) # 큰 JPEG 는 줄여서 읽기(빠름)
|
||||||
|
im = ImageOps.exif_transpose(im)
|
||||||
|
if im.mode not in ("RGB", "L"):
|
||||||
|
rgba = im.convert("RGBA")
|
||||||
|
bg = Image.new("RGB", rgba.size, (255, 255, 255))
|
||||||
|
bg.paste(rgba, mask=rgba.split()[-1])
|
||||||
|
im = bg
|
||||||
|
if im.width > MAIL_IMAGE_MAX_W:
|
||||||
|
im = im.resize((MAIL_IMAGE_MAX_W, max(1, round(im.height * MAIL_IMAGE_MAX_W / im.width))), Image.LANCZOS)
|
||||||
|
buf = BytesIO()
|
||||||
|
im.convert("RGB").save(buf, "JPEG", quality=85, optimize=True)
|
||||||
|
except Exception: # noqa: BLE001 — HEIC·깨진 파일은 본문에서 뺀다(입고 기록의 사진은 그대로)
|
||||||
|
skipped += 1
|
||||||
|
continue
|
||||||
|
out.append({"cid": f"inout-photo-{ph['id']}@dbx", "data": buf.getvalue(), "width": im.width, "height": im.height})
|
||||||
|
return out, skipped
|
||||||
|
|
||||||
|
|
||||||
|
def receipt_mail_subject(receipt_date: date) -> str:
|
||||||
|
d = receipt_date
|
||||||
|
return f"[입고 요청] {d.year}년 {d.month:02d}월 {d.day:02d}일({WEEKDAYS_KO[d.weekday()]}) 입고 요청 합니다."
|
||||||
|
|
||||||
|
|
||||||
|
def receipt_mail(order: dict[str, Any], receipt: dict[str, Any], *, images: list[dict[str, Any]], skipped: int = 0,
|
||||||
|
sender_name: str, sender_email: str) -> dict[str, str]:
|
||||||
|
"""입고 1건 → 제목·글 본문·HTML 본문. 이미지는 <img src="cid:…"> (보낼 때 gmail.build_message 가 본문에 붙임).
|
||||||
|
비고 = 그 발주 품목의 줄 메모. 값은 모두 escape."""
|
||||||
|
memo_of = {int(ln["id"]): (ln.get("memo") or "") for ln in order["lines"]}
|
||||||
|
rows = [{"name": x["item_name"], "code": x["item_code"], "qty": int(x["qty"]), "note": memo_of.get(int(x["order_line_id"]), "")}
|
||||||
|
for x in receipt["lines"]]
|
||||||
|
total = sum(r["qty"] for r in rows)
|
||||||
|
who = sender_name or sender_email
|
||||||
|
when = fmt_date(receipt["receipt_date"])
|
||||||
|
info = f"입고일 {when} · 발주번호 {order['order_no']} · 공장 {order['factory_name']}"
|
||||||
|
lead = "입고된 아래 리스트 상품을 전산 등록 부탁드립니다."
|
||||||
|
# 글 본문(HTML 을 못 보는 메일 프로그램용)
|
||||||
|
text = ["안녕하세요.", "", lead, "", info, "", "[입고 상품] 상품 이름 · 상품 코드 · 입고 수량 · 비고"]
|
||||||
|
text += [f"- {r['name']} · {r['code']} · {r['qty']:,}개" + (f" · {r['note']}" if r["note"] else "") for r in rows]
|
||||||
|
text.append(f"합계 {total:,}개")
|
||||||
|
if receipt.get("memo"):
|
||||||
|
text += ["", f"메모: {receipt['memo']}"]
|
||||||
|
if images or skipped:
|
||||||
|
text += ["", f"입고 인증 사진 {len(images)}장(본문 이미지)" + (f", 본문에 넣지 못한 사진 {skipped}장(HEIC 등)" if skipped else "")]
|
||||||
|
text += ["", f"입고 담당: {who} ({sender_email})"]
|
||||||
|
# HTML 본문
|
||||||
|
e = _html.escape
|
||||||
|
td = "padding:6px 10px;border:1px solid #d9dce1;"
|
||||||
|
r_ = "text-align:right;white-space:nowrap;"
|
||||||
|
bg = "background:#f6f7f9;"
|
||||||
|
body_rows = "".join(
|
||||||
|
f'<tr><td style="{td}">{e(r["name"])}</td><td style="{td}font-family:Consolas,monospace">{e(r["code"])}</td>'
|
||||||
|
f'<td style="{td}{r_}">{r["qty"]:,}</td><td style="{td}">{e(r["note"])}</td></tr>' for r in rows)
|
||||||
|
imgs = "".join(
|
||||||
|
f'<p style="margin:8px 0"><img src="cid:{e(im["cid"])}" width="{im["width"]}" height="{im["height"]}" alt="입고 인증 사진 {i}" '
|
||||||
|
f'style="display:block;width:{im["width"]}px;max-width:100%;height:auto;border:1px solid #d9dce1"></p>'
|
||||||
|
for i, im in enumerate(images, start=1))
|
||||||
|
photo_block = ""
|
||||||
|
if images or skipped:
|
||||||
|
photo_block = (f'<p style="margin:18px 0 4px"><b>입고 인증 사진</b> <span style="color:#777">{len(images)}장</span></p>{imgs}'
|
||||||
|
+ (f'<p style="color:#777">본문에 넣지 못한 사진 {skipped}장(HEIC 등) — ERP 입고 기록에서 볼 수 있습니다.</p>' if skipped else ""))
|
||||||
|
html = (
|
||||||
|
'<div style="font-family:\'Malgun Gothic\',\'Apple SD Gothic Neo\',sans-serif;font-size:14px;color:#1d1d1f;line-height:1.6">'
|
||||||
|
f"<p>안녕하세요.<br>{e(lead)}</p>"
|
||||||
|
f'<p style="color:#555;margin:0 0 8px">{e(info)}</p>'
|
||||||
|
'<table style="border-collapse:collapse;min-width:480px">'
|
||||||
|
f'<thead><tr style="{bg}"><th style="{td}">상품 이름</th><th style="{td}">상품 코드</th><th style="{td}">입고 수량</th>'
|
||||||
|
f'<th style="{td}">비고</th></tr></thead><tbody>{body_rows}</tbody>'
|
||||||
|
f'<tfoot><tr><th colspan="2" style="{td}{bg}text-align:right">합계</th><th style="{td}{bg}{r_}">{total:,}</th>'
|
||||||
|
f'<th style="{td}{bg}"></th></tr></tfoot></table>'
|
||||||
|
+ (f'<p style="margin:10px 0 0">메모: {e(str(receipt["memo"]))}</p>' if receipt.get("memo") else "")
|
||||||
|
+ photo_block
|
||||||
|
+ f'<p style="color:#555;margin-top:18px">입고 담당: {e(who)} (<a href="mailto:{e(sender_email)}">{e(sender_email)}</a>)</p></div>'
|
||||||
|
)
|
||||||
|
return {"subject": receipt_mail_subject(receipt["receipt_date"]), "text": "\n".join(text), "html": html}
|
||||||
|
|
||||||
|
|
||||||
|
def inline_preview_html(html: str, images: list[dict[str, Any]]) -> str:
|
||||||
|
"""미리보기 창용 — cid: 를 data: 로 바꿔 브라우저에서 바로 보이게(보내는 메일은 cid 그대로)."""
|
||||||
|
import base64 # noqa: WPS433
|
||||||
|
|
||||||
|
for im in images:
|
||||||
|
html = html.replace(f'src="cid:{_html.escape(im["cid"])}"',
|
||||||
|
f'src="data:image/jpeg;base64,{base64.b64encode(im["data"]).decode("ascii")}"')
|
||||||
|
return html
|
||||||
|
|
||||||
|
|
||||||
|
# ════════════════════════════════════════════════════════════
|
||||||
|
# 사방넷 입고 파일(2026-10-19) — 입고 1건 → 엑셀. 1행 제목 A 상품코드 · B 가용수량 · C 불용수량,
|
||||||
|
# A = 코드표(itemcode_db single_items)의 사방넷 코드, B = 입고 수량, C = 수량이 아니라 상품 이름(사용자 지정).
|
||||||
|
# ════════════════════════════════════════════════════════════
|
||||||
|
SABANGNET_HEADER = ("상품코드", "가용수량", "불용수량")
|
||||||
|
|
||||||
|
|
||||||
|
def sabangnet_rows(receipt: dict[str, Any], codes: dict[str, str]) -> tuple[list[list[Any]], list[str]]:
|
||||||
|
"""입고 품목 → (엑셀 줄 [사방넷 코드, 입고 수량, 상품 이름], 사방넷 코드가 없는 품목 "코드 이름" 목록)."""
|
||||||
|
rows: list[list[Any]] = []
|
||||||
|
missing: list[str] = []
|
||||||
|
for x in receipt["lines"]:
|
||||||
|
code = (codes.get(str(x["item_code"]).strip().upper()) or "").strip()
|
||||||
|
if not code:
|
||||||
|
missing.append(f"{x['item_code']} {x['item_name']}".strip())
|
||||||
|
rows.append([code, int(x["qty"]), str(x["item_name"] or "")])
|
||||||
|
return rows, missing
|
||||||
|
|
||||||
|
|
||||||
|
def sabangnet_xlsx(rows: list[list[Any]]) -> bytes:
|
||||||
|
"""제목 행(굵게·회색 바탕) + 줄. 상품코드·불용수량(상품 이름)은 글자 칸(앞자리 0 보존)."""
|
||||||
|
from io import BytesIO # noqa: WPS433
|
||||||
|
|
||||||
|
from openpyxl import Workbook # noqa: WPS433
|
||||||
|
from openpyxl.styles import Font, PatternFill # noqa: WPS433
|
||||||
|
|
||||||
|
wb = Workbook()
|
||||||
|
ws = wb.active
|
||||||
|
ws.title = "입고"
|
||||||
|
ws.append(list(SABANGNET_HEADER))
|
||||||
|
for c in ws[1]:
|
||||||
|
c.font = Font(bold=True)
|
||||||
|
c.fill = PatternFill(start_color="FFE7E9ED", end_color="FFE7E9ED", fill_type="solid")
|
||||||
|
for code, qty, name in rows:
|
||||||
|
ws.append([code, qty, name])
|
||||||
|
r = ws.max_row
|
||||||
|
ws.cell(row=r, column=1).number_format = "@"
|
||||||
|
ws.cell(row=r, column=3).number_format = "@"
|
||||||
|
for letter, col in (("A", 0), ("B", 1), ("C", 2)):
|
||||||
|
longest = max(sum(2 if ord(ch) > 0x1100 else 1 for ch in str(v)) for v in [SABANGNET_HEADER[col]] + [r[col] for r in rows])
|
||||||
|
ws.column_dimensions[letter].width = max(10, min(60, longest + 2))
|
||||||
|
buf = BytesIO()
|
||||||
|
wb.save(buf)
|
||||||
|
return buf.getvalue()
|
||||||
|
|
||||||
|
|
||||||
|
def sabangnet_filename(order: dict[str, Any], receipt: dict[str, Any]) -> str:
|
||||||
|
return f"사방넷_입고_{receipt['receipt_date']:%Y%m%d}_{order['order_no']}.xlsx"
|
||||||
|
|
||||||
|
|
||||||
|
# ════════════════════════════════════════════════════════════
|
||||||
|
# 발주 알림 메일(2026-10-19) — 발주 담당이 발주 메일을 보낼 때 입고 담당(옵션 → 담당자)에게 같은 Gmail 로 따로 자동 발송.
|
||||||
|
# 내용 = 발주번호·발주일·제품 코드·제품명·수량만(단가·무게 등은 넣지 않음), 제목 = 발주 메일과 같음.
|
||||||
|
# ════════════════════════════════════════════════════════════
|
||||||
|
def order_notice_mail(order: dict[str, Any], *, subject: str, sender_name: str, sender_email: str) -> dict[str, str]:
|
||||||
|
e = _html.escape
|
||||||
|
lines = order["lines"]
|
||||||
|
total = sum(int(x["qty"]) for x in lines)
|
||||||
|
who = sender_name or sender_email
|
||||||
|
when = fmt_date(order["order_date"])
|
||||||
|
text = ["입고 담당자님, 안녕하세요.", "", "아래와 같이 공장에 발주했습니다. 입고 준비에 참고해 주세요.", "",
|
||||||
|
f"- 발주번호: {order['order_no']}", f"- 발주일: {when}", "", "[발주 품목] 제품 코드 · 제품명 · 수량"]
|
||||||
|
text += [f"- {x['item_code']} · {x['item_name']} · {int(x['qty']):,}개" for x in lines]
|
||||||
|
text += [f"합계 {total:,}개", "", f"발주 담당: {who} ({sender_email})"]
|
||||||
|
td = "padding:4px 10px;border:1px solid #d9dce1;font-size:14px;line-height:20px;"
|
||||||
|
th = f"{td}background:#f6f7f9;font-weight:700;white-space:nowrap;"
|
||||||
|
r = "text-align:right;white-space:nowrap;"
|
||||||
|
facts = (f'<tr><th style="{th}text-align:left">발주번호</th><td style="{td}">{e(order["order_no"])}</td>'
|
||||||
|
f'<th style="{th}text-align:left">발주일</th><td style="{td}">{e(when)}</td></tr>')
|
||||||
|
rows = "".join(f'<tr><td style="{td}font-family:Consolas,monospace">{e(x["item_code"])}</td><td style="{td}">{e(x["item_name"])}</td>'
|
||||||
|
f'<td style="{td}{r}">{int(x["qty"]):,}</td></tr>' for x in lines)
|
||||||
|
html = (
|
||||||
|
'<div style="font-family:\'Malgun Gothic\',\'Apple SD Gothic Neo\',sans-serif;font-size:14px;color:#1d1d1f;line-height:1.6">'
|
||||||
|
"<p>입고 담당자님, 안녕하세요.<br>아래와 같이 공장에 발주했습니다. 입고 준비에 참고해 주세요.</p>"
|
||||||
|
f'<table cellpadding="0" cellspacing="0" style="border-collapse:collapse;margin:8px 0 0">{facts}</table>'
|
||||||
|
'<div style="height:18px;line-height:18px;font-size:1px"> </div>'
|
||||||
|
'<table cellpadding="0" cellspacing="0" style="border-collapse:collapse;min-width:420px">'
|
||||||
|
f'<thead><tr><th style="{th}">제품 코드</th><th style="{th}">제품명</th><th style="{th}">수량</th></tr></thead>'
|
||||||
|
f'<tbody>{rows}</tbody>'
|
||||||
|
f'<tfoot><tr><th colspan="2" style="{th}text-align:right">합계</th><th style="{th}{r}">{total:,}</th></tr></tfoot></table>'
|
||||||
|
f'<p style="color:#555;margin-top:18px">발주 담당: {e(who)} (<a href="mailto:{e(sender_email)}">{e(sender_email)}</a>)</p></div>'
|
||||||
|
)
|
||||||
|
return {"subject": subject, "text": "\n".join(text), "html": html}
|
||||||
@@ -0,0 +1,32 @@
|
|||||||
|
{# 오른쪽 달력(2026-10-21) — 입출고 모든 화면 오른쪽 위 300×320, 오른쪽 열 너비 = 달력 너비.
|
||||||
|
프로젝트 달력과 같은 모양(일요일 시작 · 요일 줄 회색 · 오늘 검은 동그라미 · 토 파랑 · 일/공휴일 빨강 · 다른 달 흐리게).
|
||||||
|
날짜 칸 = 발주(발주일, 파랑) · 입고(입고일, 초록) 건수, 누르면 그날 목록(발주서로 이동). 내용은 inout.js 가 GET /inout/api/calendar 로 그린다. #}
|
||||||
|
<aside class="io-side" aria-label="발주·입고 달력">
|
||||||
|
<div class="io-cal" id="io-cal" data-month="{{ today.strftime('%Y-%m') }}">
|
||||||
|
<div class="io-cal-head">
|
||||||
|
<button type="button" class="io-cal-nav" data-step="-1" aria-label="이전 달" title="이전 달">‹</button>
|
||||||
|
<h3 class="io-cal-title" aria-live="polite">{{ today.year }}년 {{ today.month }}월</h3>
|
||||||
|
<button type="button" class="io-cal-nav" data-step="1" aria-label="다음 달" title="다음 달">›</button>
|
||||||
|
<button type="button" class="io-cal-today">오늘</button>
|
||||||
|
</div>
|
||||||
|
<div class="io-cal-box">
|
||||||
|
<div class="io-cal-wd" aria-hidden="true">
|
||||||
|
<span class="is-sun">일</span><span>월</span><span>화</span><span>수</span><span>목</span><span>금</span><span class="is-sat">토</span>
|
||||||
|
</div>
|
||||||
|
<div class="io-cal-days" role="grid"></div>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
{# 화면을 옮겨도 달력이 다시 그려지지 않게 — 마지막 달력(sessionStorage, inout.js 가 저장)을 그리기 전에 바로 붙인다.
|
||||||
|
inout.js 는 서버 값을 다시 받아 바뀐 게 있을 때만 다시 그린다. #}
|
||||||
|
<script>(function () {
|
||||||
|
try {
|
||||||
|
var c = JSON.parse(sessionStorage.getItem("io_cal_v1") || "null"), cal = document.getElementById("io-cal");
|
||||||
|
if (!c || !c.html || !c.month || !cal) return;
|
||||||
|
cal.dataset.month = c.month;
|
||||||
|
cal.dataset.restored = "1";
|
||||||
|
cal.querySelector(".io-cal-title").textContent = c.title;
|
||||||
|
cal.querySelector(".io-cal-days").innerHTML = c.html;
|
||||||
|
} catch (e) {}
|
||||||
|
})();</script>
|
||||||
|
<p class="io-cal-legend"><i class="io-cal-m is-order">n</i>발주 <i class="io-cal-m is-receipt">n</i>입고 <span class="io-sub">· 날짜를 누르면 목록</span></p>
|
||||||
|
</aside>
|
||||||
@@ -0,0 +1,5 @@
|
|||||||
|
{# 날짜 칸 = ERP 공용 달력(erp-datepop) — inout.js 가 input[type=date] 를 날짜 버튼으로 바꾼다. inout.js 보다 먼저 include. #}
|
||||||
|
<link rel="stylesheet" href="/static/vendor/material-symbols/material-symbols.css" />
|
||||||
|
<link rel="stylesheet" href="/static/erp-datepop.css?v=20261102a" />
|
||||||
|
<script type="application/json" id="io-holidays">{{ (date_holidays or {}) | tojson }}</script>
|
||||||
|
<script src="/static/erp-datepop.js?v=20261106a" defer></script>
|
||||||
@@ -0,0 +1,33 @@
|
|||||||
|
{# 상태 배지 — 발주서(open·partial·done·over·closed·cancelled) / 품목(none·partial·done·over) #}
|
||||||
|
{% macro status_badge(status, label) -%}
|
||||||
|
<span class="io-badge io-st-{{ status }}">{{ label }}</span>
|
||||||
|
{%- endmacro %}
|
||||||
|
|
||||||
|
{# 진행률 막대 — 입고 ÷ 발주 #}
|
||||||
|
{% macro progress(summary) -%}
|
||||||
|
<span class="io-progress" title="입고 {{ '{:,}'.format(summary.received) }} / 발주 {{ '{:,}'.format(summary.ordered) }}">
|
||||||
|
<span class="io-progress-bar{% if summary.over %} is-over{% endif %}" style="width:{{ summary.pct }}%"></span>
|
||||||
|
</span><span class="io-progress-pct">{{ summary.pct }}%</span>
|
||||||
|
{%- endmacro %}
|
||||||
|
|
||||||
|
{# 날짜 서식 — 2026.10.17(토) / 2026.10.17(토) 15:14 (2026-10-17 요청, 메일·JSON 은 store.fmt_date·fmt_datetime) #}
|
||||||
|
{% macro ymd(d) -%}{% if d %}{{ d.strftime('%Y.%m.%d') }}({{ '월화수목금토일'[d.weekday()] }}){% endif %}{%- endmacro %}
|
||||||
|
{% macro ymdhm(d) -%}{% if d %}{{ ymd(d) }} {{ d.strftime('%H:%M') }}{% endif %}{%- endmacro %}
|
||||||
|
|
||||||
|
{# 발주서 상태 — 모든 품목이 입고완료·초과입고면 초록 "✓ 전체 입고 완료"(초과가 있으면 "초과 포함"), 나머지는 상태 배지 #}
|
||||||
|
{% macro order_badge(status, label) -%}
|
||||||
|
{% if status in ('done', 'over') %}<span class="io-badge io-st-done io-st-all">✓ {{ label }}</span>{% if status == 'over' %}<span class="io-badge-note">초과 포함</span>{% endif %}
|
||||||
|
{%- else %}{{ status_badge(status, label) }}{% endif %}
|
||||||
|
{%- endmacro %}
|
||||||
|
|
||||||
|
{# 입고 예정일 — 지났는데 남은 게 있으면 빨강 "지연 N일" #}
|
||||||
|
{% macro due(due_date, today, active) -%}
|
||||||
|
{% if due_date %}{{ ymd(due_date) }}{% if active and due_date < today %} <span class="io-late">지연 {{ (today - due_date).days }}일</span>{% elif active %} <span class="erp-muted">D-{{ (due_date - today).days }}</span>{% endif %}{% else %}<span class="erp-muted">-</span>{% endif %}
|
||||||
|
{%- endmacro %}
|
||||||
|
|
||||||
|
{% macro n(v) -%}{{ '{:,}'.format(v or 0) }}{%- endmacro %}
|
||||||
|
|
||||||
|
{# 색상 사각형(006) — 색이 칠해진 네모. 색없음은 빗금 없는 흰 네모 + 테두리. colors = store.COLORS #}
|
||||||
|
{% macro swatch(key, colors) -%}
|
||||||
|
<i class="io-swatch{% if not colors.get(key or 'none', ('', ''))[1] %} is-none{% endif %}" style="background:{{ colors.get(key or 'none', ('', ''))[1] or '#fff' }}" aria-hidden="true"></i>
|
||||||
|
{%- endmacro %}
|
||||||
@@ -0,0 +1,36 @@
|
|||||||
|
{# 입출고 관리 공용 상단: 탭(발주 목록·미입고 현황) + 담당 표시 + 새 발주서 + 옵션 톱니(관리자, 팝업) + 알림 문구(?msg=) #}
|
||||||
|
<div class="io-nav">
|
||||||
|
<a class="erp-btn {% if tab == 'orders' %}erp-btn-primary{% else %}erp-btn-outline{% endif %}" href="/inout/">발주 목록</a>
|
||||||
|
<a class="erp-btn {% if tab == 'pending' %}erp-btn-primary{% else %}erp-btn-outline{% endif %}" href="/inout/pending">미입고 현황</a>
|
||||||
|
<span class="io-nav-gap"></span>
|
||||||
|
<span class="io-roles erp-muted">
|
||||||
|
{% if perms.can_order %}<span class="erp-badge erp-badge-neutral">발주 담당</span>{% endif %}
|
||||||
|
{% if perms.can_receive %}<span class="erp-badge erp-badge-neutral">입고 담당</span>{% endif %}
|
||||||
|
{% if not perms.can_order and not perms.can_receive %}조회만 가능 — 담당 지정은 옵션(관리자){% endif %}
|
||||||
|
</span>
|
||||||
|
{% if perms.can_order %}<a class="erp-btn erp-btn-primary" href="/inout/orders/new">+ 새 발주서</a>{% endif %}
|
||||||
|
{% if perms.admin %}
|
||||||
|
<button type="button" class="io-gear" id="io-options-btn" title="입출고 관리 옵션" aria-label="입출고 관리 옵션"
|
||||||
|
aria-haspopup="dialog" {% if open_options %}data-open="1"{% endif %}>
|
||||||
|
<svg viewBox="0 0 24 24" width="20" height="20" fill="none" stroke="currentColor" stroke-width="1.8" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true">
|
||||||
|
<circle cx="12" cy="12" r="3"/>
|
||||||
|
<path d="M19.4 15a1.65 1.65 0 0 0 .33 1.82l.06.06a2 2 0 1 1-2.83 2.83l-.06-.06a1.65 1.65 0 0 0-1.82-.33 1.65 1.65 0 0 0-1 1.51V21a2 2 0 1 1-4 0v-.09A1.65 1.65 0 0 0 9 19.4a1.65 1.65 0 0 0-1.82.33l-.06.06a2 2 0 1 1-2.83-2.83l.06-.06A1.65 1.65 0 0 0 4.68 15a1.65 1.65 0 0 0-1.51-1H3a2 2 0 1 1 0-4h.09A1.65 1.65 0 0 0 4.6 9a1.65 1.65 0 0 0-.33-1.82l-.06-.06a2 2 0 1 1 2.83-2.83l.06.06A1.65 1.65 0 0 0 9 4.68a1.65 1.65 0 0 0 1-1.51V3a2 2 0 1 1 4 0v.09a1.65 1.65 0 0 0 1 1.51 1.65 1.65 0 0 0 1.82-.33l.06-.06a2 2 0 1 1 2.83 2.83l-.06.06A1.65 1.65 0 0 0 19.4 9a1.65 1.65 0 0 0 1.51 1H21a2 2 0 1 1 0 4h-.09a1.65 1.65 0 0 0-1.51 1z"/>
|
||||||
|
</svg>
|
||||||
|
</button>
|
||||||
|
{% endif %}
|
||||||
|
</div>
|
||||||
|
{% if msg %}<p class="io-flash" role="status">{{ msg }}</p>{% endif %}
|
||||||
|
|
||||||
|
{% if perms.admin %}
|
||||||
|
{# 옵션 팝업 — 내용은 열 때 GET /inout/settings?panel=1 로 받아 넣고, 저장은 제자리에서(inout.js) #}
|
||||||
|
<dialog class="io-dlg" id="io-options" aria-labelledby="io-options-title" tabindex="-1">
|
||||||
|
<header class="io-dlg-head">
|
||||||
|
<h2 id="io-options-title">입출고 관리 옵션</h2>
|
||||||
|
<button type="button" class="io-dlg-x" data-close aria-label="닫기" title="닫기">
|
||||||
|
<svg viewBox="0 0 24 24" width="20" height="20" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" aria-hidden="true"><path d="M6 6l12 12M18 6L6 18"/></svg>
|
||||||
|
</button>
|
||||||
|
</header>
|
||||||
|
<p class="io-dlg-msg" role="status" hidden></p>
|
||||||
|
<div class="io-dlg-body" id="io-options-body"><p class="erp-muted">불러오는 중…</p></div>
|
||||||
|
</dialog>
|
||||||
|
{% endif %}
|
||||||
@@ -0,0 +1,243 @@
|
|||||||
|
{% from "inout/_macros.html" import ymd, swatch %}
|
||||||
|
{# 옵션 팝업 내용(GET /inout/settings?panel=1) — 탭: 담당자 · 공장 · 상품 정보(004). 폼 저장은 inout.js 가 제자리에서(X-Inout-Options: 1 → JSON).
|
||||||
|
공장 줄은 표(<table>) 안에 폼을 둘 수 없어 입력칸에 form="…" 속성으로 표 밖 폼에 묶는다 — 열이 머리 줄과 맞는다. #}
|
||||||
|
<div class="io-dlg-tabs" role="tablist" aria-label="옵션 분류">
|
||||||
|
<button type="button" role="tab" class="is-active" aria-selected="true" data-pane="roles">담당자</button>
|
||||||
|
<button type="button" role="tab" aria-selected="false" data-pane="factories" tabindex="-1">공장 <span class="io-dlg-count">{{ factories|length }}</span></button>
|
||||||
|
<button type="button" role="tab" aria-selected="false" data-pane="groups" tabindex="-1">상품 그룹 <span class="io-dlg-count">{{ groups|length }}</span></button>
|
||||||
|
<button type="button" role="tab" aria-selected="false" data-pane="products" tabindex="-1">상품 정보 <span class="io-dlg-count">{{ products|length }}</span></button>
|
||||||
|
<button type="button" role="tab" aria-selected="false" data-pane="logistics" tabindex="-1">물류센터</button>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<section class="io-dlg-pane" data-pane="roles" role="tabpanel">
|
||||||
|
<p class="io-help">
|
||||||
|
<b>발주 담당</b> — 발주서 작성·고치기·잔량 종결·취소. <b>입고 담당</b> — 물류에 들어온 입고 수량 입력·지우기.
|
||||||
|
그 밖의 사람은 조회만 합니다. ERP 관리자는 지정 없이도 둘 다 할 수 있습니다.
|
||||||
|
후보 = ERP 관리자 화면에서 <b>입출고 관리</b> 권한을 받은 사용자.
|
||||||
|
</p>
|
||||||
|
<form method="post" action="/inout/settings/roles" class="io-dlg-form">
|
||||||
|
<table class="io-dlg-table">
|
||||||
|
<thead><tr><th>사용자</th>{% for role, label in role_labels.items() %}<th class="io-c">{{ label }}</th>{% endfor %}</tr></thead>
|
||||||
|
<tbody>
|
||||||
|
{% for c in candidates %}
|
||||||
|
<tr>
|
||||||
|
<td><span class="io-person">
|
||||||
|
{% if c.picture %}<img class="io-avatar" src="{{ c.picture }}" alt="" referrerpolicy="no-referrer" loading="lazy" />
|
||||||
|
{% else %}<svg class="io-avatar io-avatar-empty" viewBox="0 0 24 24" aria-hidden="true"><circle cx="12" cy="12" r="12" fill="#d5d9de"/><circle cx="12" cy="9.5" r="4" fill="#fff"/><path d="M4.6 19.6a8.6 8.6 0 0 1 14.8 0A11.9 11.9 0 0 1 12 24a11.9 11.9 0 0 1-7.4-4.4z" fill="#fff"/></svg>{% endif %}
|
||||||
|
<span class="io-person-text"><b class="io-user">{{ c.name or c.email }}</b><span class="io-sub">{{ c.email }}</span></span>
|
||||||
|
</span></td>
|
||||||
|
{% for role in role_labels %}
|
||||||
|
<td class="io-c"><input type="checkbox" name="{{ role }}_email" value="{{ c.email }}" {% if c.email in roles[role] %}checked{% endif %}
|
||||||
|
aria-label="{{ c.email }} {{ role_labels[role] }}" /></td>
|
||||||
|
{% endfor %}
|
||||||
|
</tr>
|
||||||
|
{% else %}
|
||||||
|
<tr><td colspan="3" class="io-empty">입출고 관리 권한을 받은 사용자가 없습니다 — ERP 관리자 화면에서 먼저 권한을 주세요.</td></tr>
|
||||||
|
{% endfor %}
|
||||||
|
</tbody>
|
||||||
|
</table>
|
||||||
|
<div class="io-dlg-actions"><button type="submit" class="erp-btn erp-btn-primary">담당자 저장</button></div>
|
||||||
|
</form>
|
||||||
|
</section>
|
||||||
|
|
||||||
|
<section class="io-dlg-pane" data-pane="factories" role="tabpanel" hidden>
|
||||||
|
<p class="io-help">발주서에서 고르는 공장(발주처)입니다. <b>이메일</b>은 발주 메일을 받을 주소(여러 개는 쉼표). 발주 기록이 있는 공장은 지우지 말고 <b>사용</b>을 끄면 목록에서 숨겨집니다.</p>
|
||||||
|
<form method="post" action="/inout/settings/order-mail" class="io-dlg-form io-ordercc-form">
|
||||||
|
<label class="io-logi-field"><span>발주 메일 참조 <small>(모든 발주 메일의 참조 칸에 미리 들어감 — 보낼 때 고칠 수 있음, 여러 개는 쉼표)</small></span>
|
||||||
|
<span class="io-ordercc-row"><input class="io-in" type="text" inputmode="email" name="order_mail_cc" value="{{ settings.order_mail_cc }}" maxlength="1000"
|
||||||
|
aria-label="발주 메일 참조" />
|
||||||
|
<button type="submit" class="erp-btn erp-btn-outline erp-btn-sm"{% if not settings_ready %} disabled title="DB 마이그레이션 inout_db 005 필요"{% endif %}>저장</button></span></label>
|
||||||
|
</form>
|
||||||
|
{% for f in factories %}<form method="post" action="/inout/settings/factories" id="io-f{{ f.id }}" class="io-dlg-form"><input type="hidden" name="id" value="{{ f.id }}" /></form>{% endfor %}
|
||||||
|
<form method="post" action="/inout/settings/factories" id="io-fnew" class="io-dlg-form"><input type="hidden" name="is_active" value="1" /></form>
|
||||||
|
<table class="io-dlg-table io-factory-table">
|
||||||
|
<colgroup><col class="w-name" /><col class="w-man" /><col class="w-tel" /><col class="w-mail" /><col class="w-memo" /><col class="w-sort" /><col class="w-use" /><col class="w-cnt" /><col class="w-btn" /></colgroup>
|
||||||
|
<thead><tr><th>공장 이름</th><th>담당자</th><th>연락처</th><th title="발주 메일을 받을 주소 — 여러 개는 쉼표로">이메일</th><th>메모</th><th class="io-c">순서</th><th class="io-c">사용</th><th class="io-c">발주</th><th></th></tr></thead>
|
||||||
|
<tbody>
|
||||||
|
{% for f in factories %}
|
||||||
|
{% set fid = 'io-f' ~ f.id %}
|
||||||
|
<tr class="{% if not f.is_active %}is-inactive{% endif %}">
|
||||||
|
<td><input class="io-in" form="{{ fid }}" type="text" name="name" value="{{ f.name }}" maxlength="100" required aria-label="공장 이름" /></td>
|
||||||
|
<td><input class="io-in" form="{{ fid }}" type="text" name="manager" value="{{ f.manager }}" maxlength="100" aria-label="담당자" /></td>
|
||||||
|
<td><input class="io-in" form="{{ fid }}" type="tel" name="contact" value="{{ f.contact }}" maxlength="200" aria-label="연락처" /></td>
|
||||||
|
<td><input class="io-in" form="{{ fid }}" type="text" inputmode="email" name="email" value="{{ f.email }}" maxlength="600" aria-label="이메일" placeholder="발주 메일 받는 주소" /></td>
|
||||||
|
<td><input class="io-in" form="{{ fid }}" type="text" name="memo" value="{{ f.memo }}" maxlength="500" aria-label="메모" /></td>
|
||||||
|
<td class="io-c"><input class="io-in io-in-num" form="{{ fid }}" type="number" name="sort_order" value="{{ f.sort_order }}" aria-label="순서" /></td>
|
||||||
|
<td class="io-c"><input form="{{ fid }}" type="checkbox" name="is_active" value="1" {% if f.is_active %}checked{% endif %} aria-label="사용" /></td>
|
||||||
|
<td class="io-c io-sub">{{ f.order_count }}건</td>
|
||||||
|
<td class="io-btns">
|
||||||
|
<button form="{{ fid }}" type="submit" class="erp-btn erp-btn-outline erp-btn-sm">저장</button>
|
||||||
|
{% if not f.order_count %}<button form="{{ fid }}" type="submit" class="erp-btn erp-btn-outline erp-btn-sm" formaction="/inout/settings/factories/{{ f.id }}/delete"
|
||||||
|
formnovalidate data-confirm="공장 '{{ f.name }}' 을(를) 지울까요?">지우기</button>{% endif %}
|
||||||
|
</td>
|
||||||
|
</tr>
|
||||||
|
{% endfor %}
|
||||||
|
<tr class="io-new-row">
|
||||||
|
<td><input class="io-in" form="io-fnew" type="text" name="name" maxlength="100" required placeholder="새 공장 이름" aria-label="새 공장 이름" /></td>
|
||||||
|
<td><input class="io-in" form="io-fnew" type="text" name="manager" maxlength="100" placeholder="담당자" aria-label="담당자" /></td>
|
||||||
|
<td><input class="io-in" form="io-fnew" type="tel" name="contact" maxlength="200" placeholder="010-0000-0000" aria-label="연락처" /></td>
|
||||||
|
<td><input class="io-in" form="io-fnew" type="text" inputmode="email" name="email" maxlength="600" placeholder="factory@example.com" aria-label="이메일" /></td>
|
||||||
|
<td><input class="io-in" form="io-fnew" type="text" name="memo" maxlength="500" placeholder="메모" aria-label="메모" /></td>
|
||||||
|
<td class="io-c"><input class="io-in io-in-num" form="io-fnew" type="number" name="sort_order" value="0" aria-label="순서" /></td>
|
||||||
|
<td></td><td></td>
|
||||||
|
<td class="io-btns"><button form="io-fnew" type="submit" class="erp-btn erp-btn-primary erp-btn-sm">+ 추가</button></td>
|
||||||
|
</tr>
|
||||||
|
</tbody>
|
||||||
|
</table>
|
||||||
|
</section>
|
||||||
|
|
||||||
|
<section class="io-dlg-pane" data-pane="groups" role="tabpanel" hidden>
|
||||||
|
{% if not groups_ready %}
|
||||||
|
<p class="io-error">상품 그룹·색상은 DB 마이그레이션 inout_db 006 적용 후 쓸 수 있습니다 — 관리자에게 알려 주세요.</p>
|
||||||
|
{% else %}
|
||||||
|
<p class="io-help">
|
||||||
|
그룹마다 <b>은(Ag) 함유량</b>·<b>색상</b>을 한 번만 넣습니다 — <b>상품 정보</b> 탭에서 상품마다 그룹을 고르면 그 상품은 그룹 값을 씁니다(그룹 없는 상품은 상품마다).
|
||||||
|
색상 있는 품목은 발주 메일 표에서 그 줄 배경이 그 색입니다. 그룹을 지우면 그 상품들은 그룹 없음(상품마다 값)으로 바뀝니다.
|
||||||
|
</p>
|
||||||
|
{% for g in groups %}<form method="post" action="/inout/settings/groups" id="io-g{{ g.id }}" class="io-dlg-form io-group-form"><input type="hidden" name="id" value="{{ g.id }}" /></form>{% endfor %}
|
||||||
|
<form method="post" action="/inout/settings/groups" id="io-gnew" class="io-dlg-form io-group-form"></form>
|
||||||
|
<table class="io-dlg-table io-group-table">
|
||||||
|
<colgroup><col class="w-gname" /><col class="w-num" /><col class="w-color" /><col class="w-sort" /><col class="w-cnt" /><col class="w-btn" /></colgroup>
|
||||||
|
<thead><tr><th>그룹 이름</th><th class="io-r">은 함유량(%)</th><th>색상</th><th class="io-c">순서</th><th class="io-c">상품</th><th></th></tr></thead>
|
||||||
|
<tbody>
|
||||||
|
{% for g in groups %}
|
||||||
|
{% set gf = 'io-g' ~ g.id %}
|
||||||
|
<tr>
|
||||||
|
<td><input class="io-in" form="{{ gf }}" type="text" name="name" value="{{ g.name }}" maxlength="100" required aria-label="그룹 이름" /></td>
|
||||||
|
<td><input class="io-in io-in-num" form="{{ gf }}" type="text" name="silver_pct" value="{{ fmt_num(g.silver_pct, 4) if g.silver_pct is not none else '' }}" inputmode="decimal" aria-label="{{ g.name }} 은 함유량" /></td>
|
||||||
|
<td><span class="io-color">{{ swatch(g.color, colors) }}<select class="io-in io-color-select" form="{{ gf }}" name="color" aria-label="{{ g.name }} 색상">
|
||||||
|
{% for key, c in colors.items() %}<option value="{{ key }}" data-hex="{{ c[1] }}" {% if g.color == key %}selected{% endif %}>{{ c[0] }}</option>{% endfor %}
|
||||||
|
</select></span></td>
|
||||||
|
<td class="io-c"><input class="io-in io-in-num" form="{{ gf }}" type="number" name="sort_order" value="{{ g.sort_order }}" aria-label="순서" /></td>
|
||||||
|
<td class="io-c io-sub">{{ g.product_count }}개</td>
|
||||||
|
<td class="io-btns">
|
||||||
|
<button form="{{ gf }}" type="submit" class="erp-btn erp-btn-outline erp-btn-sm">저장</button>
|
||||||
|
<button form="{{ gf }}" type="submit" class="erp-btn erp-btn-outline erp-btn-sm" formaction="/inout/settings/groups/{{ g.id }}/delete"
|
||||||
|
formnovalidate data-confirm="그룹 '{{ g.name }}' 을(를) 지울까요? 그룹 상품 {{ g.product_count }}개는 그룹 없음(상품마다 값)으로 바뀝니다.">지우기</button>
|
||||||
|
</td>
|
||||||
|
</tr>
|
||||||
|
{% endfor %}
|
||||||
|
<tr class="io-new-row">
|
||||||
|
<td><input class="io-in" form="io-gnew" type="text" name="name" maxlength="100" required placeholder="새 그룹 이름" aria-label="새 그룹 이름" /></td>
|
||||||
|
<td><input class="io-in io-in-num" form="io-gnew" type="text" name="silver_pct" inputmode="decimal" placeholder="%" aria-label="새 그룹 은 함유량" /></td>
|
||||||
|
<td><span class="io-color">{{ swatch('none', colors) }}<select class="io-in io-color-select" form="io-gnew" name="color" aria-label="새 그룹 색상">
|
||||||
|
{% for key, c in colors.items() %}<option value="{{ key }}" data-hex="{{ c[1] }}">{{ c[0] }}</option>{% endfor %}
|
||||||
|
</select></span></td>
|
||||||
|
<td class="io-c"><input class="io-in io-in-num" form="io-gnew" type="number" name="sort_order" value="0" aria-label="순서" /></td>
|
||||||
|
<td></td>
|
||||||
|
<td class="io-btns"><button form="io-gnew" type="submit" class="erp-btn erp-btn-primary erp-btn-sm">+ 추가</button></td>
|
||||||
|
</tr>
|
||||||
|
</tbody>
|
||||||
|
</table>
|
||||||
|
{% endif %}
|
||||||
|
</section>
|
||||||
|
|
||||||
|
<section class="io-dlg-pane" data-pane="products" role="tabpanel" hidden>
|
||||||
|
{% if not products_ready %}
|
||||||
|
<p class="io-error">DB 마이그레이션 inout_db 004(상품 정보)가 아직 적용되지 않았습니다 — 관리자에게 알려 주세요.</p>
|
||||||
|
{% else %}
|
||||||
|
<p class="io-help">
|
||||||
|
코드표의 단품을 불러와 <b>단가</b>(원)·<b>무게</b>(개당 g = PP량)·<b>은(Ag) 함유량</b>(%)을 넣습니다 — 은 함량(g)은 무게 × %로 자동 계산.
|
||||||
|
값을 넣은 상품은 다시 불러와도 그대로이고, 지운 단품은 다음 불러오기에서 빠집니다. 발주서 제품은 이 목록에서 고르며, 발주할 때의 값이 발주서에 남습니다.
|
||||||
|
{% if groups_ready %}<b>그룹</b>을 고른 상품은 은 함유량·<b>색상</b>을 그룹 값으로 씁니다(<b>상품 그룹</b> 탭에서 한 번만 설정).{% endif %}
|
||||||
|
{% if boxes_ready %}<b>통 수량(박스)</b>·<b>뚜껑 수량(박스)</b> = 통·뚜껑이 한 박스에 몇 개씩 들어가는지(뚜껑이 없으면 빈칸) — 새 발주서에서 박스 수·파렛트 수를 계산합니다.{% endif %}
|
||||||
|
이름에 "미라클 봉투"·"미라클백"이 들어간 상품은 <b>봉투·백</b> 표에서 <b>박스당 수량</b>·<b>1파렛트당 박스 수량</b>을 넣습니다(단가·무게·은 없음).
|
||||||
|
</p>
|
||||||
|
<div class="io-prod-bar">
|
||||||
|
<button type="button" class="erp-btn erp-btn-outline erp-btn-sm" id="io-prod-import">단품 불러오기</button>
|
||||||
|
<input type="search" class="io-in io-prod-search" id="io-prod-search" placeholder="코드·제품명 찾기" aria-label="상품 찾기" />
|
||||||
|
<span class="io-sub" id="io-prod-count">{{ products|length }}개{% if excluded %} · 제외 {{ excluded|length }}개{% endif %}</span>
|
||||||
|
<span class="io-nav-gap"></span>
|
||||||
|
<button type="button" class="erp-btn erp-btn-primary erp-btn-sm" id="io-prod-save" disabled>변경 저장 <span id="io-prod-dirty"></span></button>
|
||||||
|
</div>
|
||||||
|
{% if products %}
|
||||||
|
<div class="io-prod-scroll">
|
||||||
|
{# 봉투·백(008) = 일반 상품과 표를 나눔, 짧은 목록이라 위에. 박스 칸 두 개만 다르고 나머지 칸은 같다 #}
|
||||||
|
{% set bags = products|selectattr('is_bag')|list %}
|
||||||
|
{% for bag_table, rows in [(true, bags), (false, products|rejectattr('is_bag')|list)] if rows %}
|
||||||
|
<div class="io-prod-part">
|
||||||
|
{% if bags %}<div class="io-prod-part-title">{{ '봉투·백' if bag_table else '일반 상품' }} <span class="io-sub">{{ rows|length }}개</span></div>{% endif %}
|
||||||
|
<table class="io-dlg-table io-prod-table{% if groups_ready %} has-groups{% endif %}">
|
||||||
|
<colgroup><col class="w-code" /><col />{% if groups_ready %}<col class="w-group" />{% endif %}{% if not bag_table %}<col class="w-num" /><col class="w-num" /><col class="w-num" /><col class="w-ag" />{% endif %}{% if boxes_ready %}<col class="w-box" /><col class="w-box" />{% endif %}{% if groups_ready %}<col class="w-color" />{% endif %}<col class="w-del" /></colgroup>
|
||||||
|
<thead><tr><th>코드</th><th>제품명</th>{% if groups_ready %}<th>그룹</th>{% endif %}{% if not bag_table %}<th class="io-r">단가(원)</th><th class="io-r">무게·PP(g/개)</th><th class="io-r">은 함유량(%)</th><th class="io-r">은(g/개)</th>{% endif %}{% if bag_table %}<th title="한 박스에 몇 개">박스당 수량</th><th title="한 파렛트에 몇 박스">1파렛트당 박스 수량</th>{% elif boxes_ready %}<th title="통이 한 박스에 몇 개">통 수량(박스)</th><th title="뚜껑이 한 박스에 몇 개 — 뚜껑이 없으면 빈칸">뚜껑 수량(박스)</th>{% endif %}{% if groups_ready %}<th>색상</th>{% endif %}<th></th></tr></thead>
|
||||||
|
<tbody>
|
||||||
|
{% for p in rows %}
|
||||||
|
{% set own_pct = p.own_silver_pct if groups_ready else p.silver_pct %}
|
||||||
|
<tr data-code="{{ p.item_code }}" data-search="{{ (p.item_code ~ ' ' ~ p.item_name ~ ' ' ~ (p.group_name or ''))|lower }}"{% if groups_ready and p.group_id %} class="is-grouped"{% endif %}>
|
||||||
|
<td class="io-code">{{ p.item_code }}{% if bag_table %}
|
||||||
|
{# 봉투·백엔 단가·무게·은 칸이 없다 — 전에 넣은 값이 저장 때 지워지지 않게 숨은 칸으로 그대로 보낸다 #}
|
||||||
|
<input type="hidden" data-key="unit_price" value="{{ fmt_num(p.unit_price) if p.unit_price is not none else '' }}" />
|
||||||
|
<input type="hidden" data-key="weight_g" value="{{ fmt_num(p.weight_g) if p.weight_g is not none else '' }}" />
|
||||||
|
<input type="hidden" data-key="silver_pct" value="{{ fmt_num(own_pct, 4) if own_pct is not none else '' }}" />{% endif %}</td>
|
||||||
|
<td class="io-prod-name">{{ p.item_name }}</td>
|
||||||
|
{% if groups_ready %}
|
||||||
|
<td><select class="io-in io-group-select" data-key="group_id" aria-label="{{ p.item_code }} 그룹">
|
||||||
|
<option value="" data-silver="" data-color="">그룹 없음</option>
|
||||||
|
{% for g in groups %}<option value="{{ g.id }}" data-silver="{{ fmt_num(g.silver_pct, 4) if g.silver_pct is not none else '' }}" data-color="{{ g.color }}" {% if p.group_id == g.id %}selected{% endif %}>{{ g.name }}</option>{% endfor %}
|
||||||
|
</select></td>
|
||||||
|
{% endif %}
|
||||||
|
{% if not bag_table %}
|
||||||
|
<td><input class="io-in io-in-num" data-key="unit_price" value="{{ fmt_num(p.unit_price) if p.unit_price is not none else '' }}" inputmode="decimal" aria-label="{{ p.item_code }} 단가" /></td>
|
||||||
|
<td><input class="io-in io-in-num" data-key="weight_g" value="{{ fmt_num(p.weight_g) if p.weight_g is not none else '' }}" inputmode="decimal" aria-label="{{ p.item_code }} 무게" /></td>
|
||||||
|
<td><input class="io-in io-in-num io-own" data-key="silver_pct" value="{{ fmt_num(own_pct, 4) if own_pct is not none else '' }}" inputmode="decimal" aria-label="{{ p.item_code }} 은 함유량" />
|
||||||
|
{% if groups_ready %}<span class="io-group-val io-r" title="그룹 값 — 그룹에서 바꿉니다">{{ fmt_num(p.silver_pct, 4) if p.silver_pct is not none else '-' }}</span>{% endif %}</td>
|
||||||
|
<td class="io-r io-ag" title="무게 × 은 함유량 ÷ 100">{{ fmt_num(p.silver_g, 4) if p.silver_g is not none else '-' }}</td>
|
||||||
|
{% endif %}
|
||||||
|
{% if bag_table %}
|
||||||
|
<td><input class="io-in io-in-num" data-key="body_per_box" value="{{ '{:,}'.format(p.body_per_box) if p.body_per_box else '' }}" inputmode="numeric" aria-label="{{ p.item_code }} 박스당 수량" /></td>
|
||||||
|
<td><input class="io-in io-in-num" data-key="boxes_per_pallet" value="{{ '{:,}'.format(p.boxes_per_pallet) if p.boxes_per_pallet else '' }}" inputmode="numeric" aria-label="{{ p.item_code }} 1파렛트당 박스 수량" /></td>
|
||||||
|
{% elif boxes_ready %}
|
||||||
|
<td><input class="io-in io-in-num" data-key="body_per_box" value="{{ '{:,}'.format(p.body_per_box) if p.body_per_box else '' }}" inputmode="numeric" aria-label="{{ p.item_code }} 통 수량(박스)" /></td>
|
||||||
|
<td><input class="io-in io-in-num" data-key="lid_per_box" value="{{ '{:,}'.format(p.lid_per_box) if p.lid_per_box else '' }}" inputmode="numeric" placeholder="없음" aria-label="{{ p.item_code }} 뚜껑 수량(박스)" /></td>
|
||||||
|
{% endif %}
|
||||||
|
{% if groups_ready %}
|
||||||
|
<td><span class="io-color io-own">{{ swatch(p.own_color, colors) }}<select class="io-in io-color-select" data-key="color" aria-label="{{ p.item_code }} 색상">
|
||||||
|
{% for key, c in colors.items() %}<option value="{{ key }}" data-hex="{{ c[1] }}" {% if p.own_color == key %}selected{% endif %}>{{ c[0] }}</option>{% endfor %}
|
||||||
|
</select></span>
|
||||||
|
<span class="io-color io-group-val" title="그룹 값 — 그룹에서 바꿉니다">{{ swatch(p.color, colors) }}<span class="io-color-name">{{ colors[p.color][0] if p.color in colors else '' }}</span></span></td>
|
||||||
|
{% endif %}
|
||||||
|
<td class="io-r"><button type="button" class="io-icon-btn" data-exclude="{{ p.item_code }}" title="지우기 — 다음 불러오기에서도 뺌" aria-label="{{ p.item_code }} 지우기">✕</button></td>
|
||||||
|
</tr>
|
||||||
|
{% endfor %}
|
||||||
|
</tbody>
|
||||||
|
</table>
|
||||||
|
</div>
|
||||||
|
{% endfor %}
|
||||||
|
</div>
|
||||||
|
{% else %}
|
||||||
|
<p class="io-empty">아직 불러온 단품이 없습니다 — [단품 불러오기]를 누르세요. (그 전에는 발주서에서 코드표 단품을 바로 고릅니다)</p>
|
||||||
|
{% endif %}
|
||||||
|
{% if excluded %}
|
||||||
|
<details class="io-excluded">
|
||||||
|
<summary>제외 목록 {{ excluded|length }}개 — 불러오기에서 빠지는 단품</summary>
|
||||||
|
<ul>
|
||||||
|
{% for x in excluded %}
|
||||||
|
<li><span class="io-code">{{ x.item_code }}</span> {{ x.item_name }} <span class="io-sub">· {{ ymd(x.excluded_at) }}</span>
|
||||||
|
<button type="button" class="io-link-btn" data-restore="{{ x.item_code }}">되살리기</button></li>
|
||||||
|
{% endfor %}
|
||||||
|
</ul>
|
||||||
|
</details>
|
||||||
|
{% endif %}
|
||||||
|
{% endif %}
|
||||||
|
</section>
|
||||||
|
|
||||||
|
<section class="io-dlg-pane" data-pane="logistics" role="tabpanel" hidden>
|
||||||
|
{% if not settings_ready %}
|
||||||
|
<p class="io-error">DB 마이그레이션 inout_db 005(물류센터 이메일·입고 요청 메일)가 아직 적용되지 않았습니다 — 관리자에게 알려 주세요.</p>
|
||||||
|
{% endif %}
|
||||||
|
<p class="io-help">
|
||||||
|
입고 담당이 <b>입고 저장</b>을 누르면 물류센터 입고 담당자에게 보낼 <b>입고 요청 메일</b>(전산 등록 부탁 · 입고 상품 표 · 입고증 사진)을
|
||||||
|
미리 보여 주고, [메일 발송]을 눌러 입고 담당 본인 Gmail 로 보냅니다. 아래 주소가 받는 사람·참조 칸에 미리 들어갑니다(보낼 때 고칠 수 있음).
|
||||||
|
</p>
|
||||||
|
<form method="post" action="/inout/settings/logistics" class="io-dlg-form io-logi-form">
|
||||||
|
<label class="io-logi-field"><span>물류센터 담당자 이메일 <small>(받는 사람 — 여러 개는 쉼표)</small></span>
|
||||||
|
<input class="io-in" type="text" inputmode="email" name="logistics_emails" value="{{ settings.logistics_emails }}" maxlength="1000"
|
||||||
|
placeholder="logistics@example.com" aria-label="물류센터 담당자 이메일" /></label>
|
||||||
|
<label class="io-logi-field"><span>입고 요청 메일 참조 <small>(여러 개는 쉼표)</small></span>
|
||||||
|
<input class="io-in" type="text" inputmode="email" name="receipt_mail_cc" value="{{ settings.receipt_mail_cc }}" maxlength="1000"
|
||||||
|
aria-label="입고 요청 메일 참조" /></label>
|
||||||
|
<div class="io-dlg-actions"><button type="submit" class="erp-btn erp-btn-primary"{% if not settings_ready %} disabled{% endif %}>물류센터 저장</button></div>
|
||||||
|
</form>
|
||||||
|
</section>
|
||||||
|
|
||||||
|
<p class="io-dlg-foot">코드표(단품) 연결: {{ items_status }}</p>
|
||||||
@@ -0,0 +1,77 @@
|
|||||||
|
{% extends "erp_base.html" %}
|
||||||
|
{% from "inout/_macros.html" import order_badge, progress, due, n, ymd %}
|
||||||
|
{% block head_extra %}<link rel="stylesheet" href="/static/inout.css?v=20261105d" />{% endblock %}
|
||||||
|
|
||||||
|
{% block content %}
|
||||||
|
<div class="io-split">{# 2열 — 왼쪽 화면 | 오른쪽 달력(2026-10-21) #}
|
||||||
|
<section class="io">
|
||||||
|
{% include "inout/_nav.html" %}
|
||||||
|
|
||||||
|
<form class="io-filter" method="get" action="/inout/">
|
||||||
|
{# 상태 = 링크(다른 거르기 값 유지). 검색 칸 Enter 는 아래 [찾기] — 상태는 숨은 칸 값 그대로 #}
|
||||||
|
{% set keep = {'factory': filters.factory or '', 'q': filters.q, 'from': filters['from'], 'to': filters['to']} %}
|
||||||
|
<div class="io-seg" role="group" aria-label="상태">
|
||||||
|
{% for key, f in status_filters.items() %}
|
||||||
|
<a href="/inout/?{{ dict(keep, status=key) | urlencode }}" class="io-seg-btn{% if filters.status == key %} is-active{% endif %}"
|
||||||
|
{% if filters.status == key %}aria-current="true"{% endif %}>{{ f[0] }}</a>
|
||||||
|
{% endfor %}
|
||||||
|
</div>
|
||||||
|
<input type="hidden" name="status" value="{{ filters.status }}" />
|
||||||
|
<select class="erp-select" name="factory" aria-label="공장" onchange="this.form.submit()">
|
||||||
|
<option value="">전체 공장</option>
|
||||||
|
{% for f in factories %}<option value="{{ f.id }}" {% if filters.factory == f.id %}selected{% endif %}>{{ f.name }}{% if not f.is_active %} (사용 안 함){% endif %}</option>{% endfor %}
|
||||||
|
</select>
|
||||||
|
<div class="io-filter-right">
|
||||||
|
<label class="io-date">발주일 <input class="erp-input" type="date" name="from" value="{{ filters['from'] }}" aria-label="발주일 시작" /></label>
|
||||||
|
<span class="erp-muted">~</span>
|
||||||
|
<input class="erp-input" type="date" name="to" value="{{ filters['to'] }}" aria-label="발주일 끝" />
|
||||||
|
<input class="erp-input io-search" type="search" name="q" value="{{ filters.q }}" placeholder="발주번호·제품 코드·제품 이름" />
|
||||||
|
<button type="submit" class="erp-btn erp-btn-outline">찾기</button>
|
||||||
|
</div>
|
||||||
|
</form>
|
||||||
|
|
||||||
|
<div class="erp-card-block">
|
||||||
|
<div class="erp-table-wrap">
|
||||||
|
<table class="erp-table io-table io-list-table">
|
||||||
|
<thead><tr>
|
||||||
|
<th>발주번호</th><th>공장</th><th>제품</th><th>발주일</th><th>입고 예정일</th><th>입고일</th>
|
||||||
|
<th class="io-num">발주</th><th class="io-num">입고</th><th class="io-num">미입고</th><th>진행</th><th>상태</th>
|
||||||
|
{% if perms.super %}<th class="io-col-trash"><span class="sr-only">삭제</span></th>{% endif %}
|
||||||
|
</tr></thead>
|
||||||
|
<tbody>
|
||||||
|
{% for o in orders %}
|
||||||
|
{% set active = o.status in ('open', 'partial') %}
|
||||||
|
<tr class="io-row-link" data-href="/inout/orders/{{ o.id }}">
|
||||||
|
<td><a href="/inout/orders/{{ o.id }}" class="io-order-no">{{ o.order_no }}</a></td>
|
||||||
|
<td>{{ o.factory_name }}</td>
|
||||||
|
<td class="io-items">{{ o.items_label }}<div class="erp-row-sub">{{ o.line_count }}종</div></td>
|
||||||
|
<td>{{ ymd(o.order_date) }}</td>
|
||||||
|
<td>{{ due(o.due_date, today, active) }}</td>
|
||||||
|
<td>{% for d in o.receipt_dates %}<div>{{ ymd(d) }}</div>{% else %}-{% endfor %}</td>
|
||||||
|
<td class="io-num">{{ n(o.summary.ordered) }}</td>
|
||||||
|
<td class="io-num">{{ n(o.summary.received) }}</td>
|
||||||
|
<td class="io-num{% if o.summary.remaining and active %} io-remaining{% endif %}">{{ n(o.summary.remaining) }}{% if o.summary.over %}<div class="io-over-sub">초과 +{{ n(o.summary.over) }}</div>{% endif %}</td>
|
||||||
|
<td class="io-progress-cell">{{ progress(o.summary) }}</td>
|
||||||
|
<td class="io-status-cell">{{ order_badge(o.status, o.status_label) }}</td>
|
||||||
|
{% if perms.super %}
|
||||||
|
{# 수퍼관리자만 — 완전 삭제(품목·입고 기록·사진·메일 기록까지) #}
|
||||||
|
<td class="io-col-trash"><form method="post" action="/inout/orders/{{ o.id }}/delete"
|
||||||
|
data-erp-confirm="{{ o.order_no }} 발주서를 완전히 삭제할까요?{% if o.summary.received %} 입고 {{ n(o.summary.received) }}개 기록과 입고증 사진{% else %} 품목{% endif %}·발주 메일 기록까지 모두 지워지고 되돌릴 수 없습니다.">
|
||||||
|
<input type="hidden" name="back" value="{{ request.url.path }}{% if request.url.query %}?{{ request.url.query }}{% endif %}" />
|
||||||
|
<button type="submit" class="io-icon-btn io-del-btn" title="발주 삭제(수퍼관리자)" aria-label="{{ o.order_no }} 발주 삭제">
|
||||||
|
<svg viewBox="0 0 24 24" width="15" height="15" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true"><path d="M4 7h16M9 7V4h6v3M6 7l1 13h10l1-13M10 11v6M14 11v6"/></svg>
|
||||||
|
</button></form></td>
|
||||||
|
{% endif %}
|
||||||
|
</tr>
|
||||||
|
{% else %}
|
||||||
|
<tr><td colspan="{{ 12 if perms.super else 11 }}" class="erp-empty">{% if filters.status == 'active' %}진행 중인 발주가 없습니다.{% else %}조건에 맞는 발주가 없습니다.{% endif %}</td></tr>
|
||||||
|
{% endfor %}
|
||||||
|
</tbody>
|
||||||
|
</table>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
</section>
|
||||||
|
{% include "inout/_calendar.html" %}
|
||||||
|
</div>
|
||||||
|
{% endblock %}
|
||||||
|
{% block scripts %}{% include "inout/_datepop.html" %}<script src="/static/inout.js?v=20261105a" defer></script>{% endblock %}
|
||||||
@@ -0,0 +1,265 @@
|
|||||||
|
{% extends "erp_base.html" %}
|
||||||
|
{% from "inout/_macros.html" import status_badge, order_badge, progress, due, n, ymd, ymdhm %}
|
||||||
|
{#- 메일 창(발주 메일 · 입고 요청 메일 같은 모양) — 열면 미리보기 GET, [메일 발송]을 눌러야 보낸다(inout.js initMail) -#}
|
||||||
|
{%- macro mail_dialog(id, title, open_url='', open_title='') -%}
|
||||||
|
<dialog class="io-dlg io-mail-dlg" id="{{ id }}" aria-labelledby="{{ id }}-title" tabindex="-1"
|
||||||
|
{%- if open_url %} data-open-url="{{ open_url }}" data-open-title="{{ open_title }}"{% endif %}>
|
||||||
|
<header class="io-dlg-head">
|
||||||
|
<h2 id="{{ id }}-title" data-mail-title>{{ title }}</h2>
|
||||||
|
<button type="button" class="io-dlg-x" data-close aria-label="닫기" title="닫기">
|
||||||
|
<svg viewBox="0 0 24 24" width="20" height="20" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" aria-hidden="true"><path d="M6 6l12 12M18 6L6 18"/></svg>
|
||||||
|
</button>
|
||||||
|
</header>
|
||||||
|
<p class="io-dlg-msg" role="status" hidden></p>
|
||||||
|
<div class="io-dlg-body" data-mail-body><p class="erp-muted">불러오는 중…</p></div>
|
||||||
|
<footer class="io-dlg-footbar" data-mail-foot hidden>
|
||||||
|
<button type="button" class="io-link-btn" data-gmail-disconnect>Gmail 연결 끊기</button>
|
||||||
|
<span class="io-nav-gap"></span>
|
||||||
|
<button type="button" class="erp-btn erp-btn-outline" data-close>취소</button>
|
||||||
|
<button type="button" class="erp-btn erp-btn-primary" data-mail-send>메일 발송</button>
|
||||||
|
</footer>
|
||||||
|
</dialog>
|
||||||
|
{%- endmacro -%}
|
||||||
|
{% block head_extra %}<link rel="stylesheet" href="/static/inout.css?v=20261105d" />{% endblock %}
|
||||||
|
|
||||||
|
{% block content %}
|
||||||
|
{% set active = order.status in ('open', 'partial') %}
|
||||||
|
{% set receiving = perms.can_receive and can_receive_now %}
|
||||||
|
{# 전체 입고 완료(모든 품목 입고완료·초과) — 입고 칸·[입고 저장]을 흐리게 막는다(서버도 거절, 2026-10-19). 입고 기록을 지우면 다시 열림 #}
|
||||||
|
{% set recv_done = order.status in ('done', 'over') %}
|
||||||
|
{% set dis = ' disabled' if recv_done else '' %}
|
||||||
|
{% set photo_admin = perms.can_receive and not order.cancelled_at %}
|
||||||
|
<div class="io-split">{# 2열 — 왼쪽 화면 | 오른쪽 달력(2026-10-21) #}
|
||||||
|
<section class="io">
|
||||||
|
{% include "inout/_nav.html" %}
|
||||||
|
|
||||||
|
<div class="erp-card-block io-head">
|
||||||
|
<div class="io-head-main">
|
||||||
|
<div class="io-head-title">
|
||||||
|
<h2>{{ order.order_no }}</h2>{{ order_badge(order.status, order.status_label) }}
|
||||||
|
</div>
|
||||||
|
<dl class="io-head-meta">
|
||||||
|
<div><dt>공장</dt><dd>{{ order.factory_name }}{% if order.factory_manager or order.factory_contact %}<span class="io-factory-who">{{ order.factory_manager }}{% if order.factory_manager and order.factory_contact %} · {% endif %}{{ order.factory_contact }}</span>{% endif %}</dd></div>
|
||||||
|
<div><dt>발주일</dt><dd>{{ ymd(order.order_date) }}</dd></div>
|
||||||
|
<div><dt>입고 예정일</dt><dd>{{ due(order.due_date, today, active) }}</dd></div>
|
||||||
|
<div><dt>진행</dt><dd>{{ progress(order.summary) }}</dd></div>
|
||||||
|
<div><dt>발주 메일</dt><dd>{% if order.mails %}{% set last = order.mails[-1] %}<span class="io-mail-sent">보냄 {{ ymdhm(last.sent_at) }}</span><span class="io-factory-who">{{ last.sent_by }} → {{ last.to_addrs }}{% if order.mails|length > 1 %} · 모두 {{ order.mails|length }}번{% endif %}</span>{% else %}<span class="erp-muted">아직 안 보냄</span>{% endif %}</dd></div>
|
||||||
|
{% if order.memo %}<div class="io-wide"><dt>메모</dt><dd>{{ order.memo }}</dd></div>{% endif %}
|
||||||
|
{% if order.closed_at %}<div class="io-wide"><dt>종결</dt><dd>{{ ymd(order.closed_at) }} · {{ order.closed_by }}{% if order.close_reason %} — {{ order.close_reason }}{% endif %}</dd></div>{% endif %}
|
||||||
|
{% if order.cancelled_at %}<div class="io-wide"><dt>취소</dt><dd>{{ ymd(order.cancelled_at) }} · {{ order.cancelled_by }}</dd></div>{% endif %}
|
||||||
|
</dl>
|
||||||
|
</div>
|
||||||
|
<div class="io-kpis io-kpis-head">
|
||||||
|
<div class="erp-summary-card erp-summary-card--mini"><div class="erp-summary-label">발주</div><div class="erp-summary-value">{{ n(order.summary.ordered) }}</div></div>
|
||||||
|
<div class="erp-summary-card erp-summary-card--mini"><div class="erp-summary-label">입고</div><div class="erp-summary-value">{{ n(order.summary.received) }}</div></div>
|
||||||
|
<div class="erp-summary-card erp-summary-card--mini{% if order.summary.remaining and active %} io-kpi-remaining{% endif %}"><div class="erp-summary-label">미입고</div><div class="erp-summary-value">{{ n(order.summary.remaining) }}</div></div>
|
||||||
|
{% if order.summary.over %}<div class="erp-summary-card erp-summary-card--mini io-kpi-over"><div class="erp-summary-label">초과</div><div class="erp-summary-value">+{{ n(order.summary.over) }}</div></div>{% endif %}
|
||||||
|
</div>
|
||||||
|
{% if perms.can_order and not order.cancelled_at %}
|
||||||
|
<div class="io-head-actions">
|
||||||
|
<button type="button" class="erp-btn erp-btn-primary erp-btn-sm io-mail-btn" id="io-mail-btn" data-order="{{ order.id }}"
|
||||||
|
{% if open_mail %}data-open="1"{% endif %} aria-haspopup="dialog">
|
||||||
|
<svg viewBox="0 0 24 24" width="15" height="15" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true"><rect x="3" y="5" width="18" height="14" rx="2"/><path d="m3 7 9 6 9-6"/></svg>
|
||||||
|
{% if order.mails %}발주 메일 다시 보내기{% else %}발주 메일 보내기{% endif %}</button>
|
||||||
|
<a class="erp-btn erp-btn-outline erp-btn-sm" href="/inout/orders/{{ order.id }}/edit">발주서 고치기</a>
|
||||||
|
{% if order.closed_at %}
|
||||||
|
<form method="post" action="/inout/orders/{{ order.id }}/reopen"><button class="erp-btn erp-btn-outline erp-btn-sm" type="submit">종결 풀기</button></form>
|
||||||
|
{% elif order.summary.remaining %}
|
||||||
|
<form method="post" action="/inout/orders/{{ order.id }}/close" class="io-close-form" data-erp-confirm="남은 미입고 {{ n(order.summary.remaining) }}개를 더 기다리지 않고 종결할까요? 미입고 현황에서 빠집니다.">
|
||||||
|
<input class="erp-input io-close-reason" type="text" name="reason" maxlength="500" placeholder="종결 사유(선택)" />
|
||||||
|
<button class="erp-btn erp-btn-outline erp-btn-sm" type="submit">잔량 종결</button>
|
||||||
|
</form>
|
||||||
|
{% endif %}
|
||||||
|
{% if not order.receipts %}
|
||||||
|
<form method="post" action="/inout/orders/{{ order.id }}/cancel" data-erp-confirm="이 발주서를 취소할까요? (입고 기록이 없을 때만)">
|
||||||
|
<button class="erp-btn erp-btn-danger erp-btn-sm" type="submit">발주 취소</button>
|
||||||
|
</form>
|
||||||
|
{% endif %}
|
||||||
|
</div>
|
||||||
|
{% endif %}
|
||||||
|
</div>
|
||||||
|
|
||||||
|
{% if error %}<div class="io-error" role="alert">{% for line in error.split('\n') %}<div>{{ line }}</div>{% endfor %}</div>{% endif %}
|
||||||
|
|
||||||
|
<form method="post" action="/inout/orders/{{ order.id }}/receipts" class="erp-card-block io-block" id="io-receipt-form" enctype="multipart/form-data">
|
||||||
|
{# Enter 키 = 이 버튼(일반 저장). 없으면 폼의 첫 제출 버튼인 [초과 입고로 저장]이 눌려 확인 없이 초과가 저장된다 #}
|
||||||
|
{% if receiving %}<button type="submit" class="io-default-submit" tabindex="-1" aria-hidden="true"{{ dis }}>입고 저장</button>{% endif %}
|
||||||
|
<input type="hidden" name="confirm_over" value="" id="io-confirm-over" />
|
||||||
|
<div class="erp-card-block-head">
|
||||||
|
<h2>품목</h2>
|
||||||
|
{% if receiving and recv_done %}<span class="erp-muted io-recv-done-note">✓ 전체 입고 완료 — 더 입고할 수 없습니다(잘못 넣은 입고는 아래 입고 기록에서 지운 뒤 다시 넣으세요)</span>
|
||||||
|
{% elif receiving %}<span class="erp-muted">물류에 들어온 수량을 [이번 입고]에 넣고 저장 — 여러 번 나눠 넣어도 됩니다</span>
|
||||||
|
{% elif perms.can_receive and order.closed_at %}<span class="erp-muted">종결된 발주서 — 입고하려면 발주 담당이 종결을 풀어야 합니다</span>{% endif %}
|
||||||
|
</div>
|
||||||
|
|
||||||
|
{% if over %}
|
||||||
|
<div class="io-over-box" role="alert">
|
||||||
|
<b>발주보다 많이 입고하려고 합니다.</b> 맞으면 [초과 입고로 저장]을 누르세요.
|
||||||
|
<ul>{% for o in over %}<li>{% if not items_limited %}<span class="io-code">{{ o.item_code }}</span> {% endif %}{{ o.item_name }} — 발주 {{ n(o.ordered) }}개, 입고 후 {{ n(o.after) }}개 (<b>+{{ n(o.over) }}</b>)</li>{% endfor %}</ul>
|
||||||
|
{% if photos_lost %}<p class="io-photo-lost">고른 입고증 사진은 다시 첨부해야 합니다(화면이 다시 열리면서 빠졌습니다).</p>{% endif %}
|
||||||
|
<button type="submit" class="io-btn-over" name="confirm_over" value="1">초과 입고로 저장</button>
|
||||||
|
<span class="erp-muted">숫자를 고치려면 아래 칸을 고친 뒤 [입고 저장]</span>
|
||||||
|
</div>
|
||||||
|
{% elif photos_lost %}
|
||||||
|
<p class="io-error">고른 입고증 사진은 다시 첨부해야 합니다(화면이 다시 열리면서 빠졌습니다).</p>
|
||||||
|
{% endif %}
|
||||||
|
|
||||||
|
<div class="erp-table-wrap">
|
||||||
|
<table class="erp-table io-table io-items-table">
|
||||||
|
{# 입고 담당(발주 담당 아님) = 제품 이름·발주 수량(+ 이번 입고)만, 발주 담당 = 단가·금액·PP·은 함께 #}
|
||||||
|
<thead><tr><th class="io-col-no">#</th>{% if not items_limited %}<th>제품 코드</th>{% endif %}<th>제품</th><th class="io-num">발주</th>
|
||||||
|
{% if show_prices %}<th class="io-num io-col-money">단가(원)</th><th class="io-num io-col-money">금액(원)</th><th class="io-num io-col-spec" title="발주 수량 전체 PP 사용량 = 전체 무게 − 은 무게(아래 작은 글씨 = 개당 무게)">PP 사용량</th><th class="io-num io-col-spec" title="발주 수량 전체 은 무게(아래 작은 글씨 = 함유량 %·개당 은)">은(Ag) 함유량</th>{% endif %}
|
||||||
|
{% if not items_limited %}<th class="io-num">입고</th><th class="io-num">미입고</th><th>상태</th>{% endif %}
|
||||||
|
{% if receiving %}<th class="io-col-recv">이번 입고</th>{% endif %}</tr></thead>
|
||||||
|
<tbody>
|
||||||
|
{% for ln in order.lines %}
|
||||||
|
<tr>
|
||||||
|
<td class="io-col-no">{{ loop.index }}</td>
|
||||||
|
{% if not items_limited %}<td class="io-code">{{ ln.item_code }}</td>{% endif %}
|
||||||
|
<td>{{ ln.item_name }}{% if ln.memo %}<div class="erp-row-sub">{{ ln.memo }}</div>{% endif %}</td>
|
||||||
|
<td class="io-num">{{ n(ln.qty) }}</td>
|
||||||
|
{% if show_prices %}
|
||||||
|
{% set amt = line_amount(ln.qty, ln.unit_price) %}{% set ag = silver_g(ln.weight_g, ln.silver_pct) %}{% set use = line_usage(ln) %}
|
||||||
|
<td class="io-num io-col-money">{{ fmt_num(ln.unit_price) if ln.unit_price is not none else '-' }}</td>
|
||||||
|
<td class="io-num io-col-money">{{ fmt_num(amt) if amt is not none else '-' }}</td>
|
||||||
|
{# 발주 수량 전체 사용량(2026-10-21) — PP 사용량·은 함유량 kg(메일 표와 같은 값), 아래 작은 글씨 = 개당 값 #}
|
||||||
|
<td class="io-num io-col-spec">{% if use.pp_use_kg is not none %}{{ fmt_num(use.pp_use_kg, 3) }}kg{% else %}-{% endif %}{% if ln.weight_g is not none %}<div class="erp-row-sub">{{ fmt_num(ln.weight_g) }}g/개</div>{% endif %}</td>
|
||||||
|
<td class="io-num io-col-spec">{% if use.ag_kg is not none %}{{ fmt_num(use.ag_kg, 3) }}kg{% else %}-{% endif %}{% if ln.silver_pct is not none %}<div class="erp-row-sub">{{ fmt_num(ln.silver_pct, 4) }}%{% if ag is not none %} · {{ fmt_num(ag, 4) }}g/개{% endif %}</div>{% endif %}</td>
|
||||||
|
{% endif %}
|
||||||
|
{% if not items_limited %}
|
||||||
|
<td class="io-num">{{ n(ln.received) }}</td>
|
||||||
|
<td class="io-num{% if ln.remaining and active %} io-remaining{% endif %}">{{ n(ln.remaining) }}{% if ln.over %}<div class="io-over-sub">초과 +{{ n(ln.over) }}</div>{% endif %}</td>
|
||||||
|
<td>{{ status_badge(ln.status, ln.status_label) }}</td>
|
||||||
|
{% endif %}
|
||||||
|
{% if receiving %}<td class="io-col-recv"><input class="erp-input io-qty io-recv" type="text" inputmode="numeric" name="qty_{{ ln.id }}"
|
||||||
|
value="{{ receipt_form.qty.get(ln.id, '') }}" data-remaining="{{ ln.remaining }}" data-ordered="{{ ln.qty }}" data-received="{{ ln.received }}"
|
||||||
|
data-code="{{ ln.item_code }}" data-name="{{ ln.item_name }}" placeholder="{{ ln.remaining if ln.remaining and not items_limited else '' }}"
|
||||||
|
aria-label="{{ ln.item_name }} 이번 입고 수량"{{ dis }} /></td>{% endif %}
|
||||||
|
</tr>
|
||||||
|
{% endfor %}
|
||||||
|
</tbody>
|
||||||
|
{% if show_prices and order.lines %}
|
||||||
|
<tfoot><tr class="io-total-row">
|
||||||
|
<td colspan="3" class="io-total-label">합계</td>
|
||||||
|
<td class="io-num">{{ n(order.summary.ordered) }}</td>
|
||||||
|
<td class="io-num io-col-money"></td>
|
||||||
|
<td class="io-num io-col-money"><b>{{ fmt_num(totals.amount) ~ ' 원' if totals.amount is not none else '-' }}</b>{% if totals.missing_price %}<div class="erp-row-sub">단가 미입력 {{ totals.missing_price }}종 제외</div>{% endif %}</td>
|
||||||
|
{# 합계 무게 = 소수 첫째 자리에서 반올림(정수 kg) #}
|
||||||
|
<td class="io-num io-col-spec">{% if totals.pp_use_kg is not none %}{{ fmt_num(totals.pp_use_kg, 0) }} kg{% else %}-{% endif %}</td>
|
||||||
|
<td class="io-num io-col-spec">{% if totals.silver_g is not none %}{{ fmt_num(totals.silver_g / 1000, 0) }} kg{% else %}-{% endif %}</td>
|
||||||
|
{% if not items_limited %}<td colspan="3"></td>{% endif %}
|
||||||
|
{% if receiving %}<td></td>{% endif %}
|
||||||
|
</tr></tfoot>
|
||||||
|
{% endif %}
|
||||||
|
</table>
|
||||||
|
</div>
|
||||||
|
{% if receiving %}
|
||||||
|
<div class="io-receipt-bar{% if recv_done %} is-locked{% endif %}"{% if recv_done %} aria-disabled="true" title="전체 입고 완료 — 더 입고할 수 없습니다"{% endif %}>
|
||||||
|
<label class="erp-field"><span>입고일 *</span><input type="date" name="receipt_date" value="{{ receipt_form.receipt_date }}" aria-label="입고일" required{{ dis }} /></label>
|
||||||
|
<label class="erp-field io-grow"><span>메모</span><input type="text" name="memo" value="{{ receipt_form.memo }}" maxlength="500" placeholder="차량·박스 수·검수 메모 등"{{ dis }} /></label>
|
||||||
|
<div class="erp-field io-photo-field">
|
||||||
|
<span>입고증 사진 <small>(최대 {{ max_photos }}장)</small></span>
|
||||||
|
<label class="io-photo-pick">
|
||||||
|
<input type="file" name="photos" accept="image/*" multiple id="io-photo-input" class="io-photo-input" data-max="{{ max_photos }}"{{ dis }} />
|
||||||
|
<svg class="io-photo-pick-icon" viewBox="0 0 24 24" width="28" height="28" fill="none" stroke="currentColor" stroke-width="1.7" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true"><path d="M4 8h3l2-3h6l2 3h3v11H4z"/><circle cx="12" cy="13" r="3.5"/></svg>
|
||||||
|
입고증 업로드
|
||||||
|
</label>
|
||||||
|
</div>
|
||||||
|
<button type="button" class="erp-btn erp-btn-outline" id="io-fill-remaining"{{ dis }}>남은 수량 모두 채우기</button>
|
||||||
|
<button type="submit" class="erp-btn erp-btn-primary io-recv-save"{{ dis }}>입고 저장 <span id="io-recv-total"></span></button>
|
||||||
|
<div class="io-photo-previews" id="io-photo-previews" aria-live="polite"></div>
|
||||||
|
</div>
|
||||||
|
{% endif %}
|
||||||
|
</form>
|
||||||
|
|
||||||
|
<div class="erp-card-block io-block">
|
||||||
|
<div class="erp-card-block-head"><h2>입고 기록</h2><span class="erp-muted">{{ order.receipts|length }}회</span></div>
|
||||||
|
{% if order.receipts %}
|
||||||
|
<div class="erp-table-wrap">
|
||||||
|
<table class="erp-table io-table">
|
||||||
|
<thead><tr><th>입고일</th><th>품목별 수량</th><th class="io-num">합계</th><th>입고증</th><th>입력</th><th>입고 요청 메일 · 사방넷</th>{% if photo_admin %}<th></th>{% endif %}</tr></thead>
|
||||||
|
<tbody>
|
||||||
|
{% for r in order.receipts %}
|
||||||
|
<tr>
|
||||||
|
<td>{{ ymd(r.receipt_date) }}{% if r.memo %}<div class="erp-row-sub">{{ r.memo }}</div>{% endif %}</td>
|
||||||
|
<td>{% for x in r.lines %}<span class="io-chip">{% if items_limited %}{{ x.item_name }}{% else %}<span class="io-code">{{ x.item_code }}</span>{% endif %} {{ n(x.qty) }}</span>{% endfor %}</td>
|
||||||
|
<td class="io-num">{{ n(r.total) }}</td>
|
||||||
|
<td class="io-photos-cell">
|
||||||
|
{% for ph in r.photos %}
|
||||||
|
<button type="button" class="io-thumb" data-photo="{{ ph.id }}" data-receipt="{{ r.id }}" data-type="{{ ph.content_type }}"
|
||||||
|
data-name="{{ ph.filename }}" title="{{ ph.filename }} — 크게 보기" aria-label="입고증 사진 크게 보기 {{ loop.index }}">
|
||||||
|
{% if ph.content_type == 'image/heic' %}<span class="io-thumb-heic">HEIC</span>{% else %}<img src="/inout/photos/{{ ph.id }}" alt="" loading="lazy" />{% endif %}
|
||||||
|
</button>
|
||||||
|
{% endfor %}
|
||||||
|
{% if photo_admin and r.photos|length < max_photos %}
|
||||||
|
<form method="post" action="/inout/orders/{{ order.id }}/receipts/{{ r.id }}/photos" enctype="multipart/form-data" class="io-add-photo-form">
|
||||||
|
<label class="io-thumb io-thumb-add" title="입고증 사진 더하기">
|
||||||
|
<input type="file" name="photos" accept="image/*" multiple class="io-photo-input io-photo-auto" data-max="{{ max_photos - r.photos|length }}" aria-label="입고증 사진 더하기" />
|
||||||
|
<span aria-hidden="true">+</span>
|
||||||
|
</label>
|
||||||
|
</form>
|
||||||
|
{% elif not r.photos %}<span class="erp-muted">-</span>{% endif %}
|
||||||
|
</td>
|
||||||
|
<td class="erp-muted">{{ r.created_by }}<div class="erp-row-sub">{{ ymdhm(r.created_at) }}</div></td>
|
||||||
|
<td class="io-rmail-cell">
|
||||||
|
{% if r.mails %}{% set lm = r.mails[-1] %}<span class="io-mail-sent">보냄 {{ ymdhm(lm.sent_at) }}</span>
|
||||||
|
<div class="erp-row-sub">{{ lm.sent_by }}{% if r.mails|length > 1 %} · 모두 {{ r.mails|length }}번{% endif %}</div>{% endif %}
|
||||||
|
{% if perms.can_receive %}<button type="button" class="erp-btn erp-btn-outline erp-btn-sm io-rmail-btn" aria-haspopup="dialog"
|
||||||
|
data-url="/inout/orders/{{ order.id }}/receipts/{{ r.id }}/mail" data-title="입고 요청 메일 · {{ ymd(r.receipt_date) }} 입고 {{ n(r.total) }}개">
|
||||||
|
{% if r.mails %}다시 보내기{% else %}보내기{% endif %}</button>
|
||||||
|
{% elif not r.mails %}<span class="erp-muted">-</span>{% endif %}
|
||||||
|
{% if perms.can_order or perms.can_receive %}
|
||||||
|
<a class="erp-btn erp-btn-outline erp-btn-sm io-sabang-btn" href="/inout/orders/{{ order.id }}/receipts/{{ r.id }}/sabangnet.xlsx"
|
||||||
|
title="사방넷 입고 엑셀 — 상품코드(사방넷 코드)·가용수량(입고 수량)·불용수량(상품 이름)" download>사방넷 입고 파일</a>
|
||||||
|
{% endif %}
|
||||||
|
</td>
|
||||||
|
{% if photo_admin %}
|
||||||
|
<td><form method="post" action="/inout/orders/{{ order.id }}/receipts/{{ r.id }}/delete"
|
||||||
|
data-erp-confirm="{{ ymd(r.receipt_date) }} 입고 {{ n(r.total) }}개 기록을 지울까요? 그만큼 다시 미입고가 되고 입고증 사진도 지워집니다.">
|
||||||
|
<button type="submit" class="erp-btn erp-btn-outline erp-btn-sm">지우기</button></form></td>
|
||||||
|
{% endif %}
|
||||||
|
</tr>
|
||||||
|
{% endfor %}
|
||||||
|
</tbody>
|
||||||
|
</table>
|
||||||
|
</div>
|
||||||
|
{% else %}
|
||||||
|
<p class="erp-empty">아직 입고된 것이 없습니다.</p>
|
||||||
|
{% endif %}
|
||||||
|
</div>
|
||||||
|
|
||||||
|
{# 입고증 사진 크게 보기 — 앞뒤 넘기기(←/→), 원본 열기, 지우기(입고 담당) #}
|
||||||
|
<dialog class="io-viewer" id="io-viewer" tabindex="-1" aria-label="입고증 사진" data-order="{{ order.id }}" data-can-delete="{{ '1' if photo_admin else '' }}">
|
||||||
|
<div class="io-viewer-bar">
|
||||||
|
<span class="io-viewer-title" id="io-viewer-title"></span>
|
||||||
|
{% if photo_admin %}
|
||||||
|
<button type="button" class="io-viewer-btn io-viewer-rot" data-rotate="270" title="왼쪽으로 돌리기" aria-label="왼쪽으로 돌리기"><svg viewBox="0 0 24 24" width="16" height="16" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true"><path d="M3 4v6h6"/><path d="M3.5 15a9 9 0 1 0 2.1-9.4L3 10"/></svg></button>
|
||||||
|
<button type="button" class="io-viewer-btn io-viewer-rot" data-rotate="90" title="오른쪽으로 돌리기" aria-label="오른쪽으로 돌리기"><svg viewBox="0 0 24 24" width="16" height="16" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true"><path d="M21 4v6h-6"/><path d="M20.5 15a9 9 0 1 1-2.1-9.4L21 10"/></svg></button>
|
||||||
|
{% endif %}
|
||||||
|
<a class="io-viewer-btn" id="io-viewer-open" href="#" target="_blank" rel="noopener">원본</a>
|
||||||
|
{% if photo_admin %}<form method="post" id="io-viewer-del" data-erp-confirm="이 입고증 사진을 지울까요?"><button type="submit" class="io-viewer-btn">지우기</button></form>{% endif %}
|
||||||
|
<button type="button" class="io-viewer-btn" data-close aria-label="닫기">✕</button>
|
||||||
|
</div>
|
||||||
|
<button type="button" class="io-viewer-nav is-prev" data-step="-1" aria-label="이전 사진">‹</button>
|
||||||
|
<img class="io-viewer-img" id="io-viewer-img" alt="입고증 사진" />
|
||||||
|
<p class="io-viewer-heic" id="io-viewer-heic" hidden>HEIC 사진은 이 브라우저에서 미리 볼 수 없습니다 — [원본]으로 내려받으세요.</p>
|
||||||
|
<button type="button" class="io-viewer-nav is-next" data-step="1" aria-label="다음 사진">›</button>
|
||||||
|
</dialog>
|
||||||
|
|
||||||
|
{% if perms.can_order and not order.cancelled_at %}
|
||||||
|
{# 발주 메일 — 열면 GET /inout/orders/{id}/mail 로 미리보기, [메일 발송]을 눌러야 보낸다(발주 담당 본인 Gmail) #}
|
||||||
|
{{ mail_dialog('io-mail', '발주 메일 보내기 · ' ~ order.order_no) }}
|
||||||
|
{% endif %}
|
||||||
|
{% if perms.can_receive and order.receipts %}
|
||||||
|
{# 입고 요청 메일(005) — 물류센터 입고 담당자에게 전산 등록 부탁(입고 담당 본인 Gmail). 입고 저장 뒤 ?rmail={입고 id} 면 바로 연다 #}
|
||||||
|
{% set open_r = order.receipts | selectattr('id', 'equalto', open_rmail) | list if open_rmail else [] %}
|
||||||
|
{% if open_r %}
|
||||||
|
{{ mail_dialog('io-rmail', '입고 요청 메일', '/inout/orders/' ~ order.id ~ '/receipts/' ~ open_r[0].id ~ '/mail',
|
||||||
|
'입고 요청 메일 · ' ~ ymd(open_r[0].receipt_date) ~ ' 입고 ' ~ n(open_r[0].total) ~ '개') }}
|
||||||
|
{% else %}{{ mail_dialog('io-rmail', '입고 요청 메일') }}{% endif %}
|
||||||
|
{% endif %}
|
||||||
|
</section>
|
||||||
|
{% include "inout/_calendar.html" %}
|
||||||
|
</div>
|
||||||
|
{% endblock %}
|
||||||
|
{% block scripts %}{% include "inout/_datepop.html" %}<script src="/static/inout.js?v=20261105a" defer></script>{% endblock %}
|
||||||
@@ -0,0 +1,105 @@
|
|||||||
|
{% extends "erp_base.html" %}
|
||||||
|
{% block head_extra %}<link rel="stylesheet" href="/static/inout.css?v=20261105d" />{% endblock %}
|
||||||
|
|
||||||
|
{% block content %}
|
||||||
|
<div class="io-split">{# 2열 — 왼쪽 화면 | 오른쪽 달력(2026-10-21) #}
|
||||||
|
<section class="io">
|
||||||
|
{% include "inout/_nav.html" %}
|
||||||
|
|
||||||
|
<form class="erp-card-block io-order-form" method="post" id="io-order-form"{% if boxes_ready %} data-pallet-boxes="{{ pallet_boxes }}"{% endif %}
|
||||||
|
action="{% if order %}/inout/orders/{{ order.id }}/edit{% else %}/inout/orders/new{% endif %}">
|
||||||
|
<div class="erp-card-block-head">
|
||||||
|
<h2>{% if order %}발주서 고치기 · {{ order.order_no }}{% else %}새 발주서{% endif %}</h2>
|
||||||
|
<span class="erp-muted">{% if from_catalog %}제품은 옵션 → 상품 정보의 단품에서 고릅니다(단가 함께){% else %}제품은 코드표의 단품에서 고릅니다{% endif %}</span>
|
||||||
|
</div>
|
||||||
|
{% if error %}<div class="io-error" role="alert">{% for line in error.split('\n') %}<div>{{ line }}</div>{% endfor %}</div>{% endif %}
|
||||||
|
{% if not items_enabled %}<div class="io-error" role="alert">제품을 고를 목록이 없습니다 — 관리자가 옵션 → 상품 정보에서 단품을 불러오거나 코드표 DB(ITEMCODE_DB_URL)를 연결해야 합니다.</div>{% endif %}
|
||||||
|
|
||||||
|
<div class="erp-form-grid">
|
||||||
|
<label class="erp-field"><span>공장 *</span>
|
||||||
|
<select name="factory_id" required>
|
||||||
|
<option value="">공장 고르기</option>
|
||||||
|
{% for f in factories %}<option value="{{ f.id }}" {% if vals.factory_id|string == f.id|string %}selected{% endif %}>{{ f.name }}</option>{% endfor %}
|
||||||
|
</select>
|
||||||
|
{% if not factories %}<span class="io-hint">공장이 없습니다 — 관리자가 옵션에서 먼저 공장을 추가해야 합니다.</span>{% endif %}
|
||||||
|
</label>
|
||||||
|
<label class="erp-field"><span>발주일 *</span><input type="date" name="order_date" value="{{ vals.order_date }}" aria-label="발주일" required /></label>
|
||||||
|
<label class="erp-field"><span>입고 예정일</span><input type="date" name="due_date" value="{{ vals.due_date }}" aria-label="입고 예정일" /></label>
|
||||||
|
<label class="erp-field"><span>메모</span><input type="text" name="memo" value="{{ vals.memo }}" maxlength="500" placeholder="공장 전달 사항 등" /></label>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<div class="erp-table-wrap">
|
||||||
|
<table class="erp-table io-table io-lines" id="io-lines">
|
||||||
|
<thead><tr><th class="io-col-no">#</th><th>제품(코드·이름으로 검색)</th><th class="io-col-qty">발주 수량</th><th class="io-col-money">단가(원)</th><th class="io-col-money">금액(원)</th>{% if boxes_ready %}<th class="io-col-box" title="통·뚜껑 박스 입수(옵션 → 상품 정보)로 계산 — 저장·메일에는 넣지 않습니다">통·뚜껑 박스</th>{% endif %}<th>줄 메모</th><th class="io-col-del"></th></tr></thead>
|
||||||
|
<tbody>
|
||||||
|
{% for ln in lines %}
|
||||||
|
{% set received = (order.lines | selectattr('item_code', 'equalto', ln.code) | map(attribute='received') | first) if order else 0 %}
|
||||||
|
<tr class="io-line" data-price="{{ ln.price if ln.price is not none else '' }}"{% if boxes_ready %} data-body-box="{{ ln.body_per_box or '' }}" data-lid-box="{{ ln.lid_per_box or '' }}" data-bag="{{ '1' if ln.is_bag else '' }}" data-pallet-box="{{ ln.boxes_per_pallet or '' }}"{% endif %}>
|
||||||
|
<td class="io-col-no"></td>
|
||||||
|
<td class="io-item-cell">
|
||||||
|
<input type="hidden" name="item_code" value="{{ ln.code }}" />
|
||||||
|
<input type="hidden" name="item_name" value="{{ ln.name }}" />
|
||||||
|
<input class="erp-input io-item-search" type="text" value="{{ ln.code }}{% if ln.name %} · {{ ln.name }}{% endif %}" autocomplete="off"
|
||||||
|
placeholder="코드 또는 이름" {% if received %}readonly title="입고된 제품은 바꿀 수 없습니다(수량은 바꿀 수 있음)"{% endif %} />
|
||||||
|
{% if received %}<div class="erp-row-sub">입고 {{ '{:,}'.format(received) }}개 — 제품은 그대로, 수량만 바꿀 수 있습니다</div>{% endif %}
|
||||||
|
</td>
|
||||||
|
<td class="io-col-qty"><span class="io-qty-wrap"><input class="erp-input io-qty" type="text" inputmode="numeric" name="qty" value="{{ ln.qty }}" placeholder="0" />{% if boxes_ready %}<span class="io-steps"><button type="button" class="io-step" data-step="-1" aria-label="공배수만큼 줄이기" disabled><svg viewBox="0 0 24 24" width="16" height="16" fill="none" stroke="currentColor" stroke-width="2.2" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true"><path d="M15 6l-6 6 6 6"/></svg></button><button type="button" class="io-step" data-step="1" aria-label="공배수만큼 늘리기" disabled><svg viewBox="0 0 24 24" width="16" height="16" fill="none" stroke="currentColor" stroke-width="2.2" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true"><path d="M9 6l6 6-6 6"/></svg></button></span>{% endif %}</span></td>
|
||||||
|
<td class="io-col-money io-price">{{ ln.price_label or '-' }}</td>
|
||||||
|
<td class="io-col-money io-amount">-</td>
|
||||||
|
{% if boxes_ready %}<td class="io-col-box io-box">-</td>{% endif %}
|
||||||
|
<td><input class="erp-input" type="text" name="line_memo" value="{{ ln.memo }}" maxlength="500" /></td>
|
||||||
|
<td class="io-col-del">{% if not received %}<button type="button" class="erp-btn erp-btn-outline erp-btn-sm io-del" aria-label="이 줄 지우기" title="이 줄 지우기">✕</button>{% endif %}</td>
|
||||||
|
</tr>
|
||||||
|
{% endfor %}
|
||||||
|
</tbody>
|
||||||
|
<tfoot><tr><td colspan="{{ 8 if boxes_ready else 7 }}">
|
||||||
|
<button type="button" class="erp-btn erp-btn-outline erp-btn-sm" id="io-add-line">+ 제품 줄 추가</button>
|
||||||
|
<span class="erp-muted io-total">합계 <b id="io-total-qty">0</b>개 · <b id="io-total-lines">0</b>종 · 금액 <b id="io-total-amount">0</b>원<span id="io-total-noprice"></span></span>
|
||||||
|
{% if boxes_ready %}
|
||||||
|
{# 박스·파렛트(2026-10-21) — 통·뚜껑 박스 수 합계 → 전체 파렛트(1파렛트 = {{ pallet_boxes }}박스, 올림). 화면 계산만(저장·메일 없음) #}
|
||||||
|
<div class="io-pallet" id="io-pallet" aria-live="polite">
|
||||||
|
<span>통 <b data-k="body">0</b>박스</span><span>뚜껑 <b data-k="lid">0</b>박스</span><span>전체 <b data-k="boxes">0</b>박스</span>
|
||||||
|
<span class="io-pallet-main">→ <b data-k="pallets">0</b>파렛트</span>
|
||||||
|
{# 파렛트 그림 — 꽉 찬 파렛트 + 잔량 파렛트(실린 박스만큼 색, %·몇 박스 더) #}
|
||||||
|
<span class="io-pallet-vis" data-k="vis"></span>
|
||||||
|
<span class="erp-muted" data-k="note">1파렛트 = {{ pallet_boxes }}박스</span>
|
||||||
|
</div>
|
||||||
|
{# 봉투·백(008) — 상품마다 1파렛트 박스 수가 달라 통·뚜껑 파렛트와 따로 셈 #}
|
||||||
|
<div class="io-pallet" id="io-pallet-bag" aria-live="polite" hidden>
|
||||||
|
<span>봉투·백 <b data-k="boxes">0</b>박스</span>
|
||||||
|
<span class="io-pallet-main">→ <b data-k="pallets">0</b>파렛트</span>
|
||||||
|
<span class="io-pallet-vis" data-k="vis"></span>
|
||||||
|
<span class="erp-muted" data-k="note"></span>
|
||||||
|
</div>
|
||||||
|
{% endif %}
|
||||||
|
</td></tr></tfoot>
|
||||||
|
</table>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<template id="io-line-tpl">
|
||||||
|
<tr class="io-line"{% if boxes_ready %} data-body-box="" data-lid-box="" data-bag="" data-pallet-box=""{% endif %}>
|
||||||
|
<td class="io-col-no"></td>
|
||||||
|
<td class="io-item-cell">
|
||||||
|
<input type="hidden" name="item_code" value="" />
|
||||||
|
<input type="hidden" name="item_name" value="" />
|
||||||
|
<input class="erp-input io-item-search" type="text" value="" autocomplete="off" placeholder="코드 또는 이름" />
|
||||||
|
</td>
|
||||||
|
<td class="io-col-qty"><span class="io-qty-wrap"><input class="erp-input io-qty" type="text" inputmode="numeric" name="qty" value="" placeholder="0" />{% if boxes_ready %}<span class="io-steps"><button type="button" class="io-step" data-step="-1" aria-label="공배수만큼 줄이기" disabled><svg viewBox="0 0 24 24" width="16" height="16" fill="none" stroke="currentColor" stroke-width="2.2" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true"><path d="M15 6l-6 6 6 6"/></svg></button><button type="button" class="io-step" data-step="1" aria-label="공배수만큼 늘리기" disabled><svg viewBox="0 0 24 24" width="16" height="16" fill="none" stroke="currentColor" stroke-width="2.2" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true"><path d="M9 6l6 6-6 6"/></svg></button></span>{% endif %}</span></td>
|
||||||
|
<td class="io-col-money io-price">-</td>
|
||||||
|
<td class="io-col-money io-amount">-</td>
|
||||||
|
{% if boxes_ready %}<td class="io-col-box io-box">-</td>{% endif %}
|
||||||
|
<td><input class="erp-input" type="text" name="line_memo" value="" maxlength="500" /></td>
|
||||||
|
<td class="io-col-del"><button type="button" class="erp-btn erp-btn-outline erp-btn-sm io-del" aria-label="이 줄 지우기" title="이 줄 지우기">✕</button></td>
|
||||||
|
</tr>
|
||||||
|
</template>
|
||||||
|
|
||||||
|
<div class="io-form-actions">
|
||||||
|
<a class="erp-btn erp-btn-outline" href="{% if order %}/inout/orders/{{ order.id }}{% else %}/inout/{% endif %}">취소</a>
|
||||||
|
<button type="submit" class="erp-btn erp-btn-primary">{% if order %}고친 내용 저장{% else %}발주서 저장{% endif %}</button>
|
||||||
|
</div>
|
||||||
|
</form>
|
||||||
|
</section>
|
||||||
|
{% include "inout/_calendar.html" %}
|
||||||
|
</div>
|
||||||
|
{% endblock %}
|
||||||
|
{% block scripts %}{% include "inout/_datepop.html" %}<script src="/static/inout.js?v=20261105a" defer></script>{% endblock %}
|
||||||
@@ -0,0 +1,94 @@
|
|||||||
|
{% extends "erp_base.html" %}
|
||||||
|
{% from "inout/_macros.html" import due, n, ymd %}
|
||||||
|
{% block head_extra %}<link rel="stylesheet" href="/static/inout.css?v=20261105d" />{% endblock %}
|
||||||
|
|
||||||
|
{% block content %}
|
||||||
|
<div class="io-split">{# 2열 — 왼쪽 화면 | 오른쪽 달력(2026-10-21) #}
|
||||||
|
<section class="io">
|
||||||
|
{% include "inout/_nav.html" %}
|
||||||
|
|
||||||
|
<form class="io-filter" method="get" action="/inout/pending">
|
||||||
|
<select class="erp-select" name="factory" aria-label="공장" onchange="this.form.submit()">
|
||||||
|
<option value="">전체 공장</option>
|
||||||
|
{% for f in factories %}<option value="{{ f.id }}" {% if filters.factory == f.id %}selected{% endif %}>{{ f.name }}{% if not f.is_active %} (사용 안 함){% endif %}</option>{% endfor %}
|
||||||
|
</select>
|
||||||
|
<input class="erp-input io-search" type="search" name="q" value="{{ filters.q }}" placeholder="제품 코드·제품 이름·발주번호" />
|
||||||
|
<button type="submit" class="erp-btn erp-btn-outline">찾기</button>
|
||||||
|
<span class="io-nav-gap"></span>
|
||||||
|
<span class="erp-muted">진행 중인 발주(종결·취소 제외)의 남은 수량</span>
|
||||||
|
</form>
|
||||||
|
|
||||||
|
<div class="io-kpis">
|
||||||
|
<div class="erp-summary-card erp-summary-card--mini"><div class="erp-summary-label">미입고 수량</div><div class="erp-summary-value">{{ n(total_remaining) }}</div></div>
|
||||||
|
<div class="erp-summary-card erp-summary-card--mini"><div class="erp-summary-label">미입고 제품</div><div class="erp-summary-value">{{ n(items|length) }}종</div></div>
|
||||||
|
<div class="erp-summary-card erp-summary-card--mini"><div class="erp-summary-label">미입고 발주 줄</div><div class="erp-summary-value">{{ n(rows|length) }}</div></div>
|
||||||
|
<div class="erp-summary-card erp-summary-card--mini{% if over %} io-kpi-over{% endif %}"><div class="erp-summary-label">초과 입고</div><div class="erp-summary-value">{{ n(over|length) }}건</div></div>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<div class="erp-card-block io-block">
|
||||||
|
<div class="erp-card-block-head"><h2>제품별 미입고 합계</h2><span class="erp-muted">여러 발주에 걸친 남은 수량을 제품마다 더한 값</span></div>
|
||||||
|
<div class="erp-table-wrap">
|
||||||
|
<table class="erp-table io-table">
|
||||||
|
<thead><tr><th>제품 코드</th><th>제품</th><th class="io-num">미입고</th><th class="io-num">발주 건수</th><th>가장 이른 입고 예정일</th></tr></thead>
|
||||||
|
<tbody>
|
||||||
|
{% for it in items %}
|
||||||
|
<tr>
|
||||||
|
<td class="io-code">{{ it.item_code }}</td><td>{{ it.item_name }}</td>
|
||||||
|
<td class="io-num io-remaining">{{ n(it.remaining) }}</td><td class="io-num">{{ it.orders }}</td>
|
||||||
|
<td>{{ due(it.earliest_due, today, True) }}</td>
|
||||||
|
</tr>
|
||||||
|
{% else %}
|
||||||
|
<tr><td colspan="5" class="erp-empty">미입고된 제품이 없습니다. 모두 들어왔습니다.</td></tr>
|
||||||
|
{% endfor %}
|
||||||
|
</tbody>
|
||||||
|
</table>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
{% if rows %}
|
||||||
|
<div class="erp-card-block io-block">
|
||||||
|
<div class="erp-card-block-head"><h2>발주별 미입고</h2><span class="erp-muted">입고 예정일이 이른 순 — 지난 것은 빨강</span></div>
|
||||||
|
<div class="erp-table-wrap">
|
||||||
|
<table class="erp-table io-table">
|
||||||
|
<thead><tr><th>입고 예정일</th><th>발주번호</th><th>공장</th><th>제품 코드</th><th>제품</th>
|
||||||
|
<th class="io-num">발주</th><th class="io-num">입고</th><th class="io-num">미입고</th></tr></thead>
|
||||||
|
<tbody>
|
||||||
|
{% for r in rows %}
|
||||||
|
<tr class="io-row-link{% if r.due_date and r.due_date < today %} is-late{% endif %}" data-href="/inout/orders/{{ r.order_id }}">
|
||||||
|
<td>{{ due(r.due_date, today, True) }}</td>
|
||||||
|
<td><a href="/inout/orders/{{ r.order_id }}" class="io-order-no">{{ r.order_no }}</a><div class="erp-row-sub">발주 {{ ymd(r.order_date) }}</div></td>
|
||||||
|
<td>{{ r.factory_name }}</td><td class="io-code">{{ r.item_code }}</td><td>{{ r.item_name }}</td>
|
||||||
|
<td class="io-num">{{ n(r.qty) }}</td><td class="io-num">{{ n(r.received) }}</td>
|
||||||
|
<td class="io-num io-remaining">{{ n(r.remaining) }}</td>
|
||||||
|
</tr>
|
||||||
|
{% endfor %}
|
||||||
|
</tbody>
|
||||||
|
</table>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
{% endif %}
|
||||||
|
|
||||||
|
{% if over %}
|
||||||
|
<div class="erp-card-block io-block io-block-over">
|
||||||
|
<div class="erp-card-block-head"><h2>초과 입고</h2><span class="erp-muted">발주보다 많이 들어온 제품 — 공장과 확인이 필요합니다</span></div>
|
||||||
|
<div class="erp-table-wrap">
|
||||||
|
<table class="erp-table io-table">
|
||||||
|
<thead><tr><th>발주번호</th><th>공장</th><th>제품 코드</th><th>제품</th><th class="io-num">발주</th><th class="io-num">입고</th><th class="io-num">초과</th></tr></thead>
|
||||||
|
<tbody>
|
||||||
|
{% for r in over %}
|
||||||
|
<tr class="io-row-link" data-href="/inout/orders/{{ r.order_id }}">
|
||||||
|
<td><a href="/inout/orders/{{ r.order_id }}" class="io-order-no">{{ r.order_no }}</a></td><td>{{ r.factory_name }}</td>
|
||||||
|
<td class="io-code">{{ r.item_code }}</td><td>{{ r.item_name }}</td>
|
||||||
|
<td class="io-num">{{ n(r.qty) }}</td><td class="io-num">{{ n(r.received) }}</td><td class="io-num io-over">+{{ n(r.over) }}</td>
|
||||||
|
</tr>
|
||||||
|
{% endfor %}
|
||||||
|
</tbody>
|
||||||
|
</table>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
{% endif %}
|
||||||
|
</section>
|
||||||
|
{% include "inout/_calendar.html" %}
|
||||||
|
</div>
|
||||||
|
{% endblock %}
|
||||||
|
{% block scripts %}<script src="/static/inout.js?v=20261105a" defer></script>{% endblock %}
|
||||||
@@ -0,0 +1,38 @@
|
|||||||
|
# [라이브커머스] 라이브 커머스 모듈 — `app/modules/live/`, `live_db`(2026-11-04)
|
||||||
|
|
||||||
|
> 이 모듈만 고칠 때 읽는 요약. 별도 상세 문서 없음 — 코드가 기준.
|
||||||
|
> 정적 파일: `app/static/live.js`, `live.css`. 템플릿: `templates/live/`. 테스트: `tests/test_live.py`(`LIVE_TEST_DB_URL` 이 localhost 일 때 실제 DB).
|
||||||
|
> 다른 모듈과 연결: 이미지 검사 = 자산 모듈 `app/modules/asset/media.py prepare_photo` 재사용(바꾸면 양쪽 확인). 쇼핑몰 로고 = 말레이시아 배송 모듈 `app/static/dispatch/courier/tiktok.png`·`shopee.png`(지우거나 이름을 바꾸면 호스트 설정 로고도 깨짐).
|
||||||
|
|
||||||
|
- 말레이시아 라이브 커머스 방송의 호스트 정보·방송 스케줄. 권한키 `live`, DB `LIVE_DB_URL`(없으면 "설정 필요" 안내).
|
||||||
|
- **호스트 설정** `/live/settings` — 간단한 이름(필수, `display_name`, 마이그레이션 004 — 말레이 이름은 끝이 아버지 이름이라 자동으로 줄이지 않고 사람이 입력, 빈 예전 호스트는 화면에 Full Name)·Full Name (as per IC)(필수)·Phone Number·Email·Address·Bank Name·Bank Account Number.
|
||||||
|
**계좌 등 개인정보라 ERP 관리자만**(`is_admin`) — 화면·저장·지우기 모두. 스케줄 화면에는 `db.host_choices`(이름·사용 여부)만 넘긴다.
|
||||||
|
**틱톡 계정은 호스트가 아니라 방송마다**(2026-11-05, 마이그레이션 003 `live_broadcasts.tiktok_handle`) — 호스트가 여러 계정에서 방송하므로. 방송 창에서 입력(선택), `@`·주소를 붙여 넣어도 계정명만 저장, 쓴 적 있는 계정을 제안(`db.account_choices`). `live_hosts.tiktok_handle` 은 값만 남아 있고 안 씀. 달력에서 옮기거나 맞바꿔도 계정은 그 방송에 그대로. 달력 카드 머리·스케줄표·방송 창의 호스트 = 간단한 이름, 카드 머리 아래 작은 글자 = 계정.
|
||||||
|
**`live_host_edit` 칩**(+ `live`, 관리자 페이지 토글) = 호스트 **고치기**(사용 여부 포함): 지우기 불가, 개인정보는 페이지에 싣지 않아 빈칸으로 열리고 비워 두면 그대로·입력하면 바뀜(이 칩으로는 지울 수 없음).
|
||||||
|
**`live_host` 칩**(+ `live` 칩 필요) = 새 호스트 **등록만**: 설정 화면에 이름·상태만 보이고, 입력한 계좌 등은 저장 후 못 봄. 고치기·지우기 불가, 사용 여부 못 고름(항상 사용).
|
||||||
|
**쇼핑몰**(2026-11-06, 마이그레이션 005 `live_hosts.platform`, `store.PLATFORMS` = tiktok·shopee) — 창 맨 위 라디오 + 로고(같은 상자 88×26, 안 고르면 흑백·고르면 컬러), 저장 때 필수. 목록 첫 열 = 로고. 예전 호스트는 빈 값(고치기에서 고르면 저장).
|
||||||
|
**목록의 사용 토글**(`POST /live/settings/hosts/{id}/active`, `db.set_host_active`) = 고치기 권한(관리자·`live_host_edit` 칩)만, 바로 저장·실패하면 되돌림. 권한 없으면 글자(사용/사용 안 함).
|
||||||
|
사용 안 함 = 새 방송에서 못 고름(그 호스트로 이미 등록된 방송을 고칠 때만 보임). 방송 기록이 있는 호스트는 못 지움(FK RESTRICT).
|
||||||
|
- **스케줄표** `/live/?month=YYYY-MM`(`live` 권한자 모두) — 호스트·날짜·시작/끝 시간·판매금액·시간 요금(Fee)·커미션·광고비·호스트 비용·결과 이미지. 호스트·날짜·시작·끝 시간 필수(판매금액은 방송 후 입력).
|
||||||
|
시간은 입력한 말레이시아 시간 그대로(시간대 변환 없음, DATE·TIME). 금액 단위 RM(`NUMERIC(14,2)`, `store.parse_money(값, 이름)`). 끝 시간이 시작보다 이르면 자정을 넘긴 방송.
|
||||||
|
표 첫 열 = 호스트 쇼핑몰 아이콘(`/static/live-icon-tiktok.png`·`live-icon-shopee.png` = 말레이시아 배송 로고에서 심볼만 잘라 64px, 쇼핑몰 안 고른 호스트는 빈칸), 머리글 = 가운데·굵게·검정·공용 크기 112%(`.lv-sched`, 스케줄표만).
|
||||||
|
**방송 장소는 2026-11-06 에 창·표에서 뺌**(`venue` 열은 예전 값만 남고 저장 때 건드리지 않음, 달력 카드 말풍선에만 예전 값).
|
||||||
|
- **방송 창 금액**(2026-11-06, 마이그레이션 006) — **Fee**(시간 × RM 25 `HOURLY_RATE`)·**커미션**(판매금액 × 10% `COMMISSION_PERCENT`) = 자동, 저장 안 함(`store.session_pay`, 창에서는 `live.js recalc` 가 같은 계산 — 시간·판매금액을 바꾸거나 결과 이미지에서 매출을 읽으면 다시 계산). 요율이 코드 상수라 바꾸면 지난 방송 값도 바뀐다.
|
||||||
|
**광고비**(`live_broadcasts.ad_spend`)·**호스트 비용**(`host_fee`, 일단 수기 입력) = 입력·저장. 달력 카드 Fee·날짜/달 합계 호스트 비용 = `host_fee` 합(비우면 0).
|
||||||
|
- **달력 보기** `/live/calendar?month=`(`store.build_calendar`, 사용자가 준 화면 참고, 글자도 영어 그대로) — 줄 = 1시간 칸(2026-11-06 `store.SLOT_HOURS` 2 → 1, 06:00~24:00 늘 보임, 그보다 이른 칸은 방송이 있을 때만, 칸은 시작 시간으로 정함), 열 = 날짜, 주말 노랑, 위 달 합계, 맨 아래 날짜별 TOTAL SALES·AD SPEND·HOST FEE·ROAS.
|
||||||
|
카드 머리 왼쪽 위 = 호스트 쇼핑몰 작은 아이콘(2026-11-06, 예전 ✥ 대신 — 머리 전체가 끌기 손잡이), 카드 머리 = **Tiktok Handle**(없으면 이름, 색 = 호스트 id 순 `HOST_COLORS`), SALES·COM·Fee. 카드 머리를 끌어 빈 칸으로 = 옮기기(`move`, 방송 길이 유지) · 다른 카드 위 = 맞바꾸기(`swap_with`, 날짜·시간 교환). 다시 그린 뒤 가로 위치 유지(sessionStorage). 빈 칸 + = 그 날짜·시간이 채워진 추가 창.
|
||||||
|
**AD SPEND** = 그날 방송 광고비(`ad_spend`) 합(2026-11-06 — 예전 날짜별 입력 `live_daily_ad_spend`·✎ 버튼·`/live/ad-spend` 없앰, 표는 값만 남김), ROAS = 판매금액 ÷ 광고비(광고비 없으면 `-`).
|
||||||
|
- **한 화면 맞춤**(2026-11-05) — 달력 보기는 넓은 화면(1101px 이상)에서 페이지 세로 스크롤 없음: `.lv-cal-wrap` 이 남은 높이를 쓰고, 풀HD 브라우저(세로 880px 이상)면 방송이 없는 달은 18개 시간 칸·합계 줄이 표 안 스크롤 없이 들어간다(카드가 있는 줄은 카드 높이만큼 커져서 방송이 많으면 표 안에서 스크롤, 페이지는 안 움직임). **방송이 걸친 칸은 합친다**(2026-11-06, `store._covered_slots` → `rowspan`, 가려진 칸 `skip`) — 2시간 방송 = 두 칸, 끝이 정각이 아니면 그 칸까지, 자정 넘김은 그날 마지막 칸까지. 합친 칸 안에서 시작하는 다른 방송은 같은 칸에 들어가고 칸이 더 늘어난다(겹친 방송). 끌어 놓기는 합친 칸의 첫 시간으로. 카드·표 글자·칸 크기를 늘리면 `live_calendar.browser.test.js` 로 다시 확인.
|
||||||
|
- **오른쪽 달력**(2026-11-05, 달력 보기만, 세로 2분할 `.lv-split`, 240px = 공용 달력의 80%, 예전 날짜로 이동 줄 대신, 공용 `erp-datepop` `mountRange` + `locale` 옵션으로 영문) — 날짜를 누르면 그 날이 표 맨 왼쪽(마지막 날까지 — `endGap` 이 표 끝에 여백), 다른 달이면 그 달 화면으로 가서 맨 왼쪽(sessionStorage `lv_cal_jump`). 표시만 하고 요금·일수에 안 씀. 글자 굵게, **방송 있는 날 = 숫자 오른쪽 위 초록 점**(2026-11-06, `db.broadcast_days` 보는 달 ±1년 → `#lv-live-days`, 공용 `mountRange` 의 `dayClass` 옵션 → `has-live`). 테스트 `tests/js/live_calendar.browser.test.js`(`render_live.py`).
|
||||||
|
**말레이시아 공휴일 표 = `holidays.py`**(쿠알라룸푸르 기준, 2026·2027, 대체휴일 포함) — 이슬람 명절은 달 관측으로 바뀔 수 있고, 2028 은 공고되면 손으로 추가.
|
||||||
|
- **결과 이미지 미리보기**(2026-11-06, 달력 보기) — 카드 오른쪽 아래 이미지 링크(`a[data-preview]`)에 마우스를 올리거나 탭으로 가면 오른쪽 달력 아래 빈 곳(`#lv-preview`, `.lv-side` 세로 줄)에 첫 장을 보여 주고 벗어나면 숨김. 좁은 화면(1100px 이하)은 미리보기 없음.
|
||||||
|
링크를 **누르면 화면 가운데 보기 창**(`#lv-viewer` `<dialog>`) — 원본 크기(크면 창 안 스크롤), 회전(보기만, 90°씩, 다운로드는 원본), 다운로드(올린 파일 이름), 여러 장이면 ◀▶. Ctrl·가운데 클릭은 새 탭.
|
||||||
|
- **카드 높이 = 합친 칸 높이**(2026-11-06) — `.lv-cell { height:1px }` + `.lv-cards { height:100% }` 로 칸 높이를 채운다(같은 칸 여러 카드는 나눠 가짐).
|
||||||
|
- **결과 이미지 → 매출 자동 입력**(2026-11-06, `ocr.py`, `POST /live/broadcasts/read-sales`) — 창에서 이미지를 고르면 서버의 Tesseract(Dockerfile 에서 설치, 외부 전송 없음)가 이미지 **위 절반**을 읽어 첫 `RM` 금액(틱톡 LIVE 결과 화면의 Attr. GMV)을 판매금액 칸에 채운다(저장 안 함 — 사람이 확인 후 저장, 여러 장이면 찾을 때까지 한 장씩). `RM1.2K` 처럼 줄인 값·못 찾음 = 칸 그대로 + 안내. tesseract 가 없으면(로컬 개발 PC) 안내만.
|
||||||
|
- **결과 이미지** — 방송 저장과 한 트랜잭션, JPG·PNG·WebP, 한 장 8MB, 방송당 10장(`store.MAX_IMAGES`). `prepare_photo` 가 실제 이미지 확인·긴 변 2400px·EXIF(GPS 등) 제거. BYTEA 저장.
|
||||||
|
`GET /live/images/{id}`(권한 필요, 하루 private 캐시), `?thumb=1` = 160px JPEG(그때그때 만듦). 올린 뒤 내용이 안 바뀐다는 전제 — 이미지를 고치는 기능을 넣으면 캐시도 바꿀 것.
|
||||||
|
- 라이브 커머스 화면은 공용 최대 폭(1550px)을 풀어 **화면 전체 너비**를 쓴다(`live.css` 맨 위, 스케줄표·달력·호스트 설정).
|
||||||
|
- 저장은 `live.js` 가 fetch → JSON `{ok, message}`(틀려도 창의 입력값 유지). 창 하나로 추가·고치기(`data-edit` JSON).
|
||||||
|
- **한글·영문 전환**(`i18n.py`) — 위 막대 [한글|EN], 쿠키 `live_lang`(브라우저마다, path=/live, 기본 한글). 한글 문구가 키, 템플릿 `t('…')`, 오류 `LiveError(틀, 값)`(라우터가 언어에 맞게), JS `LV_T`(`JS_KEYS`).
|
||||||
|
**새 문구는 `i18n.EN` 에도 넣는다** — `tests/test_live.py` 가 빠진 문구와 영문 화면의 한글을 잡는다. 입력한 데이터(이름·장소 등)·ERP 공용 사이드바는 번역하지 않는다.
|
||||||
|
- 메인 카드 제목 = `main.py` `card_title`(한글·영문), 사이드바는 `title` 그대로.
|
||||||
@@ -0,0 +1,21 @@
|
|||||||
|
"""라이브 커머스(live) 모듈 — 말레이시아 라이브 방송의 호스트 정보와 방송 스케줄(2026-11-04).
|
||||||
|
|
||||||
|
- 라우터: `router.py` (prefix=/live) · 저장소: `db.py` (live_db) · 순수 함수: `store.py`(입력 검사·표시 형식)
|
||||||
|
- 템플릿: `templates/live/`, 화면 스크립트·스타일 `static/live.{js,css}`
|
||||||
|
|
||||||
|
LIVE_DB_URL 미설정이면 build_live_store 가 None → 화면이 "설정 필요" 안내(앱은 죽지 않음). 권한키 `live`.
|
||||||
|
"""
|
||||||
|
|
||||||
|
from typing import Any
|
||||||
|
|
||||||
|
from .router import router
|
||||||
|
|
||||||
|
__all__ = ["router", "build_live_store"]
|
||||||
|
|
||||||
|
|
||||||
|
def build_live_store(*, dsn: str | None) -> Any:
|
||||||
|
if not dsn:
|
||||||
|
return None
|
||||||
|
from .db import LiveDBStore # 지연 import
|
||||||
|
|
||||||
|
return LiveDBStore(dsn)
|
||||||
@@ -0,0 +1,176 @@
|
|||||||
|
"""live_db PostgreSQL 저장소 — 라이브 커머스 호스트·방송 스케줄·결과 이미지(2026-11-04).
|
||||||
|
|
||||||
|
- 연결: 환경변수 `LIVE_DB_URL` (예: postgresql://live_app:<pwd>@postgres-db:5432/live_db)
|
||||||
|
- 스키마는 앱이 만들지 않는다 — `scripts/sql/live_db_init.sql` 을 superuser 가 먼저 적용(앱 계정은 CRUD 만).
|
||||||
|
- 연결 풀은 lazy open — 부팅 때 DB 가 잠시 끊겨도 컨테이너가 죽지 않게(다른 모듈과 같은 방식).
|
||||||
|
"""
|
||||||
|
|
||||||
|
from __future__ import annotations
|
||||||
|
|
||||||
|
from datetime import date, time
|
||||||
|
from typing import Any
|
||||||
|
|
||||||
|
from psycopg.errors import ForeignKeyViolation
|
||||||
|
from psycopg.rows import dict_row
|
||||||
|
from psycopg_pool import ConnectionPool
|
||||||
|
|
||||||
|
from . import store
|
||||||
|
from .i18n import LiveError
|
||||||
|
|
||||||
|
_HOST_COLUMNS = ("platform", "display_name", "full_name", "phone", "email", "address", "bank_name", "bank_account")
|
||||||
|
|
||||||
|
|
||||||
|
class LiveDBStore:
|
||||||
|
def __init__(self, dsn: str, *, min_size: int = 1, max_size: int = 4):
|
||||||
|
self._pool = ConnectionPool(conninfo=dsn, min_size=min_size, max_size=max_size,
|
||||||
|
kwargs={"row_factory": dict_row, "autocommit": True}, open=False)
|
||||||
|
self._pool.open(wait=False)
|
||||||
|
|
||||||
|
def close(self) -> None:
|
||||||
|
self._pool.close()
|
||||||
|
|
||||||
|
# ── 호스트 ─────────────────────────────────────────────
|
||||||
|
def list_hosts(self) -> list[dict[str, Any]]:
|
||||||
|
"""전체 정보(계좌 포함) — 설정 화면(ERP 관리자)에서만 쓴다."""
|
||||||
|
with self._pool.connection() as conn:
|
||||||
|
return conn.execute("SELECT * FROM live_hosts ORDER BY is_active DESC, full_name, id").fetchall()
|
||||||
|
|
||||||
|
def host_choices(self) -> list[dict[str, Any]]:
|
||||||
|
"""스케줄 화면 호스트 고르기 — 개인정보·계좌는 뺀다."""
|
||||||
|
with self._pool.connection() as conn:
|
||||||
|
return conn.execute("SELECT id, platform, display_name, full_name, is_active FROM live_hosts ORDER BY full_name, id").fetchall()
|
||||||
|
|
||||||
|
def get_host(self, host_id: int) -> dict[str, Any] | None:
|
||||||
|
with self._pool.connection() as conn:
|
||||||
|
return conn.execute("SELECT * FROM live_hosts WHERE id=%s", (host_id,)).fetchone()
|
||||||
|
|
||||||
|
def account_choices(self) -> list[str]:
|
||||||
|
"""방송 창 틱톡 계정 입력 제안 — 지금까지 방송에 쓴 계정."""
|
||||||
|
with self._pool.connection() as conn:
|
||||||
|
rows = conn.execute("SELECT DISTINCT tiktok_handle FROM live_broadcasts WHERE tiktok_handle <> '' ORDER BY tiktok_handle").fetchall()
|
||||||
|
return [r["tiktok_handle"] for r in rows]
|
||||||
|
|
||||||
|
def save_host(self, host_id: int | None, values: dict[str, str], *, is_active: bool, by: str) -> int:
|
||||||
|
cols = [values[k] for k in _HOST_COLUMNS]
|
||||||
|
with self._pool.connection() as conn:
|
||||||
|
if host_id is None:
|
||||||
|
row = conn.execute(
|
||||||
|
"INSERT INTO live_hosts (platform, display_name, full_name, phone, email, address, bank_name, bank_account, "
|
||||||
|
"is_active, created_by, updated_by) VALUES (%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s) RETURNING id",
|
||||||
|
(*cols, is_active, by, by)).fetchone()
|
||||||
|
else:
|
||||||
|
row = conn.execute(
|
||||||
|
"UPDATE live_hosts SET platform=%s, display_name=%s, full_name=%s, phone=%s, email=%s, address=%s, bank_name=%s, bank_account=%s, "
|
||||||
|
"is_active=%s, updated_by=%s WHERE id=%s RETURNING id",
|
||||||
|
(*cols, is_active, by, host_id)).fetchone()
|
||||||
|
if not row:
|
||||||
|
raise LiveError("호스트를 찾을 수 없습니다.")
|
||||||
|
return int(row["id"])
|
||||||
|
|
||||||
|
def set_host_active(self, host_id: int, is_active: bool, *, by: str) -> None:
|
||||||
|
"""목록의 사용 토글 — 사용 여부만 바꾼다."""
|
||||||
|
with self._pool.connection() as conn:
|
||||||
|
if not conn.execute("UPDATE live_hosts SET is_active=%s, updated_by=%s WHERE id=%s RETURNING id",
|
||||||
|
(is_active, by, host_id)).fetchone():
|
||||||
|
raise LiveError("호스트를 찾을 수 없습니다.")
|
||||||
|
|
||||||
|
def delete_host(self, host_id: int) -> None:
|
||||||
|
try:
|
||||||
|
with self._pool.connection() as conn:
|
||||||
|
row = conn.execute("DELETE FROM live_hosts WHERE id=%s RETURNING id", (host_id,)).fetchone()
|
||||||
|
except ForeignKeyViolation:
|
||||||
|
raise LiveError("방송 기록이 있는 호스트는 지울 수 없습니다 — 사용 안 함으로 바꾸세요.") from None
|
||||||
|
if not row:
|
||||||
|
raise LiveError("호스트를 찾을 수 없습니다.")
|
||||||
|
|
||||||
|
# ── 방송 스케줄 ─────────────────────────────────────────
|
||||||
|
def list_broadcasts(self, start: date, end: date) -> list[dict[str, Any]]:
|
||||||
|
"""start 이상 end 미만, 날짜·시간 순. 줄마다 images = [{id, filename}](내용 제외)."""
|
||||||
|
with self._pool.connection() as conn:
|
||||||
|
rows = conn.execute(
|
||||||
|
"SELECT b.*, COALESCE(NULLIF(h.display_name, ''), h.full_name) AS host_name, h.platform AS host_platform FROM live_broadcasts b JOIN live_hosts h ON h.id = b.host_id "
|
||||||
|
"WHERE b.broadcast_date >= %s AND b.broadcast_date < %s ORDER BY b.broadcast_date, b.start_time, b.id",
|
||||||
|
(start, end)).fetchall()
|
||||||
|
images = conn.execute(
|
||||||
|
"SELECT id, broadcast_id, filename FROM live_broadcast_images WHERE broadcast_id = ANY(%s) ORDER BY id",
|
||||||
|
([r["id"] for r in rows],)).fetchall()
|
||||||
|
for r in rows:
|
||||||
|
r["images"] = [i for i in images if i["broadcast_id"] == r["id"]]
|
||||||
|
return rows
|
||||||
|
|
||||||
|
def broadcast_days(self, start: date, end: date) -> list[str]:
|
||||||
|
"""start 이상 end 미만 방송이 있는 날(ISO) — 오른쪽 달력 점."""
|
||||||
|
with self._pool.connection() as conn:
|
||||||
|
rows = conn.execute("SELECT DISTINCT broadcast_date FROM live_broadcasts WHERE broadcast_date >= %s AND broadcast_date < %s ORDER BY 1",
|
||||||
|
(start, end)).fetchall()
|
||||||
|
return [r["broadcast_date"].isoformat() for r in rows]
|
||||||
|
|
||||||
|
def save_broadcast(self, broadcast_id: int | None, values: dict[str, Any], images: list[dict[str, Any]], *, by: str) -> int:
|
||||||
|
"""방송·이미지를 한 트랜잭션으로. 사용 안 함 호스트는 이미 그 호스트인 방송을 고칠 때만 허용."""
|
||||||
|
with self._pool.connection() as conn, conn.transaction():
|
||||||
|
current = None
|
||||||
|
if broadcast_id is not None:
|
||||||
|
found = conn.execute("SELECT host_id FROM live_broadcasts WHERE id=%s FOR UPDATE", (broadcast_id,)).fetchone()
|
||||||
|
if not found:
|
||||||
|
raise LiveError("방송을 찾을 수 없습니다(다른 사람이 지웠을 수 있음).")
|
||||||
|
current = found["host_id"]
|
||||||
|
host = conn.execute("SELECT is_active FROM live_hosts WHERE id=%s", (values["host_id"],)).fetchone()
|
||||||
|
if not host:
|
||||||
|
raise LiveError("호스트를 찾을 수 없습니다.")
|
||||||
|
if not host["is_active"] and values["host_id"] != current:
|
||||||
|
raise LiveError("사용 안 함으로 바뀐 호스트입니다 — 다른 호스트를 고르세요.")
|
||||||
|
# 방송 장소(venue)는 2026-11-06 부터 입력 안 받음 — 예전 값은 그대로 둔다
|
||||||
|
args = (values["host_id"], values["broadcast_date"], values["start_time"], values["end_time"],
|
||||||
|
values["tiktok_handle"], values["sales_amount"], values["ad_spend"], values["host_fee"], by)
|
||||||
|
if broadcast_id is None:
|
||||||
|
broadcast_id = int(conn.execute(
|
||||||
|
"INSERT INTO live_broadcasts (host_id, broadcast_date, start_time, end_time, tiktok_handle, sales_amount, ad_spend, host_fee, updated_by, created_by) "
|
||||||
|
"VALUES (%s,%s,%s,%s,%s,%s,%s,%s,%s,%s) RETURNING id", (*args, by)).fetchone()["id"])
|
||||||
|
else:
|
||||||
|
conn.execute("UPDATE live_broadcasts SET host_id=%s, broadcast_date=%s, start_time=%s, end_time=%s, "
|
||||||
|
"tiktok_handle=%s, sales_amount=%s, ad_spend=%s, host_fee=%s, updated_by=%s WHERE id=%s", (*args, broadcast_id))
|
||||||
|
have = conn.execute("SELECT count(*) AS n FROM live_broadcast_images WHERE broadcast_id=%s", (broadcast_id,)).fetchone()["n"]
|
||||||
|
if have + len(images) > store.MAX_IMAGES:
|
||||||
|
raise LiveError("방송 한 건에 이미지는 {max}장까지입니다(지금 {have}장).", max=store.MAX_IMAGES, have=have)
|
||||||
|
for im in images:
|
||||||
|
conn.execute("INSERT INTO live_broadcast_images (broadcast_id, filename, content_type, data, width, height, created_by) "
|
||||||
|
"VALUES (%s,%s,%s,%s,%s,%s,%s)",
|
||||||
|
(broadcast_id, im["filename"], im["content_type"], im["data"], im["width"], im["height"], by))
|
||||||
|
return broadcast_id
|
||||||
|
|
||||||
|
def delete_broadcast(self, broadcast_id: int) -> None:
|
||||||
|
with self._pool.connection() as conn:
|
||||||
|
if not conn.execute("DELETE FROM live_broadcasts WHERE id=%s RETURNING id", (broadcast_id,)).fetchone():
|
||||||
|
raise LiveError("방송을 찾을 수 없습니다.")
|
||||||
|
|
||||||
|
def move_broadcast(self, broadcast_id: int, day: date, start: time, *, by: str) -> None:
|
||||||
|
"""달력에서 빈 칸으로 옮기기 — 방송 길이는 그대로."""
|
||||||
|
with self._pool.connection() as conn, conn.transaction():
|
||||||
|
row = conn.execute("SELECT start_time, end_time FROM live_broadcasts WHERE id=%s FOR UPDATE", (broadcast_id,)).fetchone()
|
||||||
|
if not row:
|
||||||
|
raise LiveError("방송을 찾을 수 없습니다(다른 사람이 지웠을 수 있음).")
|
||||||
|
conn.execute("UPDATE live_broadcasts SET broadcast_date=%s, start_time=%s, end_time=%s, updated_by=%s WHERE id=%s",
|
||||||
|
(day, start, store.moved_end(row["start_time"], row["end_time"], start), by, broadcast_id))
|
||||||
|
|
||||||
|
def swap_broadcasts(self, first_id: int, second_id: int, *, by: str) -> None:
|
||||||
|
"""달력에서 다른 방송 위로 놓기 — 두 방송의 날짜·시간을 맞바꾼다(id 순서로 잠가 교착 방지)."""
|
||||||
|
if first_id == second_id:
|
||||||
|
return
|
||||||
|
with self._pool.connection() as conn, conn.transaction():
|
||||||
|
rows = conn.execute("SELECT id, broadcast_date, start_time, end_time FROM live_broadcasts WHERE id = ANY(%s) ORDER BY id FOR UPDATE",
|
||||||
|
([first_id, second_id],)).fetchall()
|
||||||
|
if len(rows) != 2:
|
||||||
|
raise LiveError("방송을 찾을 수 없습니다(다른 사람이 지웠을 수 있음).")
|
||||||
|
for mine, other in ((rows[0], rows[1]), (rows[1], rows[0])):
|
||||||
|
conn.execute("UPDATE live_broadcasts SET broadcast_date=%s, start_time=%s, end_time=%s, updated_by=%s WHERE id=%s",
|
||||||
|
(other["broadcast_date"], other["start_time"], other["end_time"], by, mine["id"]))
|
||||||
|
|
||||||
|
# ── 결과 이미지 ─────────────────────────────────────────
|
||||||
|
def get_image(self, image_id: int) -> dict[str, Any] | None:
|
||||||
|
with self._pool.connection() as conn:
|
||||||
|
return conn.execute("SELECT content_type, data FROM live_broadcast_images WHERE id=%s", (image_id,)).fetchone()
|
||||||
|
|
||||||
|
def delete_image(self, image_id: int) -> None:
|
||||||
|
with self._pool.connection() as conn:
|
||||||
|
if not conn.execute("DELETE FROM live_broadcast_images WHERE id=%s RETURNING id", (image_id,)).fetchone():
|
||||||
|
raise LiveError("이미지를 찾을 수 없습니다.")
|
||||||
@@ -0,0 +1,59 @@
|
|||||||
|
"""말레이시아 공휴일 표(쿠알라룸푸르 기준, 2026-11-05) — 달력 보기 오른쪽 달력에 표시만 한다(요금·일수 계산에 안 씀).
|
||||||
|
|
||||||
|
출처: publicholidays.com.my(KL 2026·2027), 2027 대체휴일은 총리실(JPM) 목록을 옮긴 maukerja.my 기준 — 공식 PDF 원문은 확인하지 못했다.
|
||||||
|
이슬람 명절(하리라야·이슬람 새해·예언자 탄신일 등)은 달 관측으로 며칠 바뀔 수 있고, 주마다 쉬는 날이 달라 다른 주 지사 생일 등은 넣지 않았다.
|
||||||
|
shortcut: 해마다 손으로 추가한다 — 2028 목록이 공고되면 여기에 더한다.
|
||||||
|
"""
|
||||||
|
|
||||||
|
from __future__ import annotations
|
||||||
|
|
||||||
|
_NAMES: dict[str, tuple[str, str]] = {
|
||||||
|
"new_year": ("새해", "New Year's Day"),
|
||||||
|
"thaipusam": ("타이푸삼", "Thaipusam"),
|
||||||
|
"ft_day": ("연방직할구의 날", "Federal Territory Day"),
|
||||||
|
"cny": ("음력 설", "Chinese New Year"),
|
||||||
|
"nuzul": ("코란 계시일", "Nuzul Al-Quran"),
|
||||||
|
"aidilfitri": ("하리라야 푸아사", "Hari Raya Aidilfitri"),
|
||||||
|
"labour": ("노동절", "Labour Day"),
|
||||||
|
"haji": ("하리라야 하지", "Hari Raya Haji"),
|
||||||
|
"wesak": ("웨삭", "Wesak Day"),
|
||||||
|
"agong": ("국왕 탄신일", "Agong's Birthday"),
|
||||||
|
"muharram": ("이슬람 새해", "Awal Muharram"),
|
||||||
|
"maulud": ("예언자 탄신일", "Maulidur Rasul"),
|
||||||
|
"merdeka": ("독립기념일", "Merdeka Day"),
|
||||||
|
"malaysia": ("말레이시아의 날", "Malaysia Day"),
|
||||||
|
"deepavali": ("디파발리", "Deepavali"),
|
||||||
|
"christmas": ("크리스마스", "Christmas Day"),
|
||||||
|
}
|
||||||
|
|
||||||
|
# 날짜 → 공휴일. "@" 로 시작 = 대체휴일(일요일·겹친 공휴일 다음 평일).
|
||||||
|
_DAYS: dict[str, str] = {
|
||||||
|
"2026-01-01": "new_year", "2026-02-01": "thaipusam", "2026-02-02": "@thaipusam", "2026-02-03": "@ft_day",
|
||||||
|
"2026-02-17": "cny", "2026-02-18": "cny", "2026-03-07": "nuzul",
|
||||||
|
"2026-03-20": "aidilfitri", "2026-03-21": "aidilfitri", "2026-03-22": "aidilfitri", "2026-03-23": "@aidilfitri",
|
||||||
|
"2026-05-01": "labour", "2026-05-27": "haji", "2026-05-31": "wesak", "2026-06-01": "agong", "2026-06-02": "@wesak",
|
||||||
|
"2026-06-17": "muharram", "2026-08-25": "maulud", "2026-08-31": "merdeka", "2026-09-16": "malaysia",
|
||||||
|
"2026-11-08": "deepavali", "2026-11-09": "@deepavali", "2026-12-25": "christmas",
|
||||||
|
|
||||||
|
"2027-01-01": "new_year", "2027-01-22": "thaipusam", "2027-02-01": "ft_day",
|
||||||
|
"2027-02-06": "cny", "2027-02-07": "cny", "2027-02-08": "@cny", "2027-02-24": "nuzul",
|
||||||
|
"2027-03-10": "aidilfitri", "2027-03-11": "aidilfitri", "2027-05-01": "labour", "2027-05-17": "haji", "2027-05-20": "wesak",
|
||||||
|
"2027-06-06": "muharram", "2027-06-07": "agong", "2027-06-08": "@muharram", "2027-08-15": "maulud", "2027-08-16": "@maulud",
|
||||||
|
"2027-08-31": "merdeka", "2027-09-16": "malaysia", "2027-10-28": "deepavali", "2027-12-25": "christmas",
|
||||||
|
}
|
||||||
|
# 같은 날 둘(2026-02-01 일요일 — 타이푸삼 + 연방직할구의 날)
|
||||||
|
_ALSO = {"2026-02-01": "ft_day"}
|
||||||
|
|
||||||
|
|
||||||
|
def holiday_names(lang: str = "ko") -> dict[str, str]:
|
||||||
|
"""{날짜: 이름} — 달력에 넘기는 값. 대체휴일은 한글 '… 대체'(공용 달력이 '대체휴일'로 줄임)·영문 '… (Replacement)'."""
|
||||||
|
i = 1 if lang == "en" else 0
|
||||||
|
out = {}
|
||||||
|
for day, key in _DAYS.items():
|
||||||
|
name = _NAMES[key.lstrip("@")][i]
|
||||||
|
if key.startswith("@"):
|
||||||
|
name += " (Replacement)" if lang == "en" else " 대체"
|
||||||
|
if day in _ALSO:
|
||||||
|
name += " · " + _NAMES[_ALSO[day]][i]
|
||||||
|
out[day] = name
|
||||||
|
return out
|
||||||
@@ -0,0 +1,125 @@
|
|||||||
|
"""라이브 커머스 한글·영문 전환(2026-11-04) — 한글 문구가 키, 없으면 한글 그대로. 언어는 쿠키 `live_lang`(브라우저마다).
|
||||||
|
|
||||||
|
새 문구는 여기에도 넣는다 — tests/test_live.py 가 템플릿·오류 문구가 모두 있는지, 영문 화면에 한글이 없는지 확인한다.
|
||||||
|
"""
|
||||||
|
|
||||||
|
from __future__ import annotations
|
||||||
|
|
||||||
|
from typing import Any
|
||||||
|
|
||||||
|
LANG_COOKIE = "live_lang"
|
||||||
|
|
||||||
|
EN: dict[str, str] = {
|
||||||
|
# 위 막대·보기
|
||||||
|
"이전 달": "Previous month", "다음 달": "Next month", "보기 방식": "View", "표": "Table", "달력": "Calendar",
|
||||||
|
"호스트 설정": "Host Settings", "+ 방송 추가": "+ Add Broadcast", "언어": "Language",
|
||||||
|
"방송을 추가하려면 먼저 호스트를 등록해야 합니다.": "Register a host before adding a broadcast.",
|
||||||
|
"ERP 관리자에게 등록을 요청하세요.": "Ask an ERP admin to register one.",
|
||||||
|
# 방송 창
|
||||||
|
"방송 추가": "Add Broadcast", "방송 고치기": "Edit Broadcast", "호스트": "Host", "호스트를 고르세요": "Select a host",
|
||||||
|
"사용 안 함": "Inactive", "방송 날짜": "Broadcast Date", "시작 시간": "Start Time", "끝 시간": "End Time",
|
||||||
|
"시간은 말레이시아 시간으로 입력합니다.": "Enter times in Malaysia time.", "판매금액 (RM)": "Sales (RM)",
|
||||||
|
"방송 후 입력": "Enter after the broadcast",
|
||||||
|
"시간 요금 (RM)": "Fee (RM)", "커미션 (RM)": "Commission (RM)", "광고비 (RM)": "Ad Spend (RM)", "호스트 비용 (RM)": "Host Fee (RM)",
|
||||||
|
"시간 × RM {rate} — 자동": "Hours × RM {rate} — auto", "판매금액 × {percent}% — 자동": "Sales × {percent}% — auto", "직접 입력": "Enter manually",
|
||||||
|
"방송 결과 이미지 (JPG·PNG·WebP, 한 장 8MB, 방송당 {n}장까지)": "Result images (JPG, PNG, WebP, 8 MB each, up to {n} per broadcast)",
|
||||||
|
"취소": "Cancel", "저장": "Save", "확인": "OK",
|
||||||
|
# 표
|
||||||
|
"날짜": "Date", "시간": "Time", "판매금액(RM)": "Sales (RM)", "커미션 10%(RM)": "Commission 10% (RM)",
|
||||||
|
"호스트 비용(RM)": "Host Fee (RM)", "방송 결과": "Result", "고치기": "Edit", "지우기": "Delete",
|
||||||
|
"시간 요금(RM)": "Fee (RM)", "광고비(RM)": "Ad Spend (RM)",
|
||||||
|
"{date} {host} 방송을 지울까요? 결과 이미지도 함께 지워집니다.": "Delete the {date} broadcast by {host}? Its result images will be deleted too.",
|
||||||
|
"이 달에 등록한 방송이 없습니다.": "No broadcasts this month.",
|
||||||
|
# 달력
|
||||||
|
"판매금액": "Sales", "커미션": "Com", "비용": "Fee", "광고비": "Ad Spend", "호스트 비용": "Host Fee", "총 판매금액": "Total Sales",
|
||||||
|
"ROAS": "ROAS", "합계 & ROAS": "Total & ROAS",
|
||||||
|
"팁: 카드 머리를 끌어 옮기거나 맞바꿀 수 있습니다. 오른쪽으로 스크롤하면 이달 {n}일을 모두 볼 수 있습니다.":
|
||||||
|
"Tip: Drag & drop any host header to move or swap dates. Scroll right to see all {n} days of the month.",
|
||||||
|
"{date} {slot} 방송 추가": "Add broadcast on {date} {slot}", "{name} {date} {times} 고치기": "Edit {name} {date} {times}",
|
||||||
|
"방송 결과 이미지": "Result images", "이미지 {n}": "IMG {n}",
|
||||||
|
# 호스트 설정
|
||||||
|
"◀ 스케줄표": "◀ Schedule", "+ 호스트 등록": "+ Add Host", "호스트 등록": "Add Host", "호스트 고치기": "Edit Host",
|
||||||
|
"간단한 이름": "Short Name", "이름 (IC 기준)": "Full Name (as per IC)", "전화번호": "Phone Number", "이메일": "Email", "주소": "Address", "은행명": "Bank Name",
|
||||||
|
"계좌번호": "Bank Account Number", "틱톡 핸들": "Tiktok Handle", "상태": "Status", "사용": "Active",
|
||||||
|
"{name} 호스트를 지울까요?": "Delete host {name}?", "등록한 호스트가 없습니다.": "No hosts registered.",
|
||||||
|
"사용 (끄면 새 방송에서 고를 수 없습니다)": "Active (when off, the host can't be selected for new broadcasts)",
|
||||||
|
"이미지 매출이 줄인 값({value})이라 정확하지 않습니다. 판매금액을 직접 입력하세요.": "The sales in the image are abbreviated ({value}), so they're not exact. Please enter the Sales yourself.",
|
||||||
|
"이미지에서 매출(RM)을 찾지 못했습니다. 판매금액을 직접 입력하세요.": "Couldn't find the sales (RM) in the image. Please enter the Sales yourself.",
|
||||||
|
"이미지에서 매출 {value} 를 읽었습니다. 확인 후 저장하세요.": "Read sales {value} from the image. Please check it, then save.",
|
||||||
|
"서버에 글자 인식 프로그램(tesseract)이 없습니다. 판매금액을 직접 입력하세요.": "Text recognition (tesseract) isn't installed on the server. Please enter the Sales yourself.",
|
||||||
|
"이미지 글자 인식이 너무 오래 걸립니다. 판매금액을 직접 입력하세요.": "Reading the image took too long. Please enter the Sales yourself.",
|
||||||
|
"이미지 글자를 읽지 못했습니다. 판매금액을 직접 입력하세요.": "Couldn't read the text in the image. Please enter the Sales yourself.",
|
||||||
|
"이미지에서 매출을 읽는 중…": "Reading sales from the image…",
|
||||||
|
"이전 이미지": "Previous image", "다음 이미지": "Next image", "회전": "Rotate", "다운로드": "Download", "닫기": "Close",
|
||||||
|
"쇼핑몰": "Platform", "쇼핑몰(틱톡·쇼피)을 고르세요.": "Choose the platform (TikTok or Shopee).",
|
||||||
|
"사용으로 바꿨습니다.": "Set to active.", "사용 안 함으로 바꿨습니다.": "Set to inactive.",
|
||||||
|
# 화면 스크립트(live.js)
|
||||||
|
"서버에 연결하지 못했습니다. 입력한 값은 그대로 있으니 다시 저장해 보세요.": "Could not reach the server. Your entries are kept — please try saving again.",
|
||||||
|
"이 이미지": "this image", "{name} 를 지울까요?": "Delete {name}?",
|
||||||
|
# 저장 결과·입력 오류
|
||||||
|
"저장했습니다.": "Saved.", "옮겼습니다.": "Moved.","방송을 지웠습니다.": "Broadcast deleted.",
|
||||||
|
"이미지를 지웠습니다.": "Image deleted.", "호스트를 저장했습니다.": "Host saved.", "호스트를 지웠습니다.": "Host deleted.",
|
||||||
|
"잘못된 요청입니다.": "Invalid request.",
|
||||||
|
"간단한 이름을 입력하세요.": "Enter the Short Name.", "이름 (IC 기준)을 입력하세요.": "Enter the Full Name (as per IC).",
|
||||||
|
"개인정보는 보이지 않습니다. 비워 두면 그대로 유지됩니다.": "Personal details are hidden. Leave them blank to keep the current values.", "{label} 이(가) 너무 깁니다({limit}자까지).": "{label} is too long (up to {limit} characters).",
|
||||||
|
"이메일 형식이 올바르지 않습니다.": "The email format is invalid.", "전화번호는 숫자·+·-·괄호만 입력하세요.": "Phone Number may contain only digits, +, - and brackets.",
|
||||||
|
"계좌번호는 숫자·-만 입력하세요.": "Bank Account Number may contain only digits and -.",
|
||||||
|
"틱톡 핸들은 영문·숫자·밑줄·점만 입력하세요.": "Tiktok Handle may contain only letters, digits, underscores and dots.",
|
||||||
|
"{label}은(는) 숫자로 입력하세요.": "{label} must be a number.", "{label}은(는) 0 이상 숫자로 입력하세요.": "{label} must be a number of 0 or more.", "{label}이(가) 너무 큽니다.": "{label} is too large.",
|
||||||
|
"{label}을 입력하세요.": "Enter the {label}.", "{label}이 올바르지 않습니다.": "The {label} is invalid.",
|
||||||
|
"호스트를 고르세요.": "Select a host.", "방송 날짜를 입력하세요.": "Enter the broadcast date.",
|
||||||
|
"끝 시간이 시작 시간과 같습니다.": "End time is the same as start time.", "날짜가 올바르지 않습니다.": "The date is invalid.",
|
||||||
|
"호스트를 찾을 수 없습니다.": "Host not found.", "방송 기록이 있는 호스트는 지울 수 없습니다 — 사용 안 함으로 바꾸세요.": "A host with broadcasts can't be deleted — set the host to Inactive instead.",
|
||||||
|
"방송을 찾을 수 없습니다(다른 사람이 지웠을 수 있음).": "Broadcast not found (someone may have deleted it).", "방송을 찾을 수 없습니다.": "Broadcast not found.",
|
||||||
|
"사용 안 함으로 바뀐 호스트입니다 — 다른 호스트를 고르세요.": "This host is Inactive — select another host.",
|
||||||
|
"방송 한 건에 이미지는 {max}장까지입니다(지금 {have}장).": "Up to {max} images per broadcast (currently {have}).", "방송 한 건에 이미지는 {max}장까지입니다.": "Up to {max} images per broadcast.",
|
||||||
|
"이미지를 찾을 수 없습니다.": "Image not found.",
|
||||||
|
"{name}: {detail}": "{name}: {detail}",
|
||||||
|
# 권한·설정
|
||||||
|
"로그인이 필요합니다.": "Please sign in.", "라이브 커머스 모듈 권한이 없습니다.": "You don't have access to the Live Commerce module.",
|
||||||
|
"호스트 정보는 ERP 관리자만 볼 수 있습니다.": "Only ERP admins can view host information.", "라이브 커머스 DB(LIVE_DB_URL)가 설정되지 않았습니다.": "The Live Commerce DB (LIVE_DB_URL) is not configured.",
|
||||||
|
"라이브 커머스 모듈 접근 권한이 없습니다.": "You don't have access to the Live Commerce module.",
|
||||||
|
"라이브 커머스 모듈이 아직 설정되지 않았습니다. scripts/sql/live_db_init.sql 로 live_db 를 만들고 .env 에 LIVE_DB_URL 을 넣은 뒤 컨테이너를 다시 시작하세요.":
|
||||||
|
"The Live Commerce module is not set up yet. Create live_db with scripts/sql/live_db_init.sql, add LIVE_DB_URL to .env and restart the container.",
|
||||||
|
# 자산 모듈 prepare_photo 오류(이미지 검사를 함께 쓴다)
|
||||||
|
"사진은 비어 있지 않은 8 MB 이하 파일이어야 합니다.": "The image must be a non-empty file of 8 MB or less.", "JPG, PNG, WebP 사진만 등록할 수 있습니다.": "Only JPG, PNG and WebP images are allowed.",
|
||||||
|
"사진은 2천만 화소 이하로 등록하세요.": "The image must be 20 megapixels or less.", "사진을 압축해 다시 등록하세요. 저장 크기는 5 MB 이하입니다.": "Please compress the image and try again (5 MB or less once stored).",
|
||||||
|
"사진을 읽을 수 없습니다. 정상적인 JPG, PNG, WebP 파일을 선택하세요.": "The image can't be read. Please choose a valid JPG, PNG or WebP file.",
|
||||||
|
}
|
||||||
|
|
||||||
|
# 화면 스크립트에 넘기는 문구(window.LV_T)
|
||||||
|
JS_KEYS = ("확인", "취소", "지우기", "서버에 연결하지 못했습니다. 입력한 값은 그대로 있으니 다시 저장해 보세요.", "이 이미지", "{name} 를 지울까요?",
|
||||||
|
"이미지에서 매출을 읽는 중…")
|
||||||
|
|
||||||
|
_MONTH_NAMES = ("January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December")
|
||||||
|
|
||||||
|
|
||||||
|
def norm_lang(raw: Any) -> str:
|
||||||
|
return "en" if raw == "en" else "ko"
|
||||||
|
|
||||||
|
|
||||||
|
def t(text: str, lang: str = "ko") -> str:
|
||||||
|
return EN.get(text, text) if lang == "en" else text
|
||||||
|
|
||||||
|
|
||||||
|
def js_text(lang: str) -> dict[str, str]:
|
||||||
|
return {k: t(k, lang) for k in JS_KEYS}
|
||||||
|
|
||||||
|
|
||||||
|
def month_label(year: int, month: int, lang: str = "ko") -> str:
|
||||||
|
return f"{_MONTH_NAMES[month - 1]} {year}" if lang == "en" else f"{year}년 {month}월"
|
||||||
|
|
||||||
|
|
||||||
|
class LiveError(ValueError):
|
||||||
|
"""입력·저장 오류 — 언어에 맞게 다시 쓸 수 있게 문구 틀과 값을 따로 둔다. str() = 한글."""
|
||||||
|
|
||||||
|
def __init__(self, template: str, **params: Any):
|
||||||
|
self.template, self.params = template, params
|
||||||
|
super().__init__(template.format(**params))
|
||||||
|
|
||||||
|
def text(self, lang: str) -> str:
|
||||||
|
return t(self.template, lang).format(**{k: t(v, lang) if isinstance(v, str) else v for k, v in self.params.items()})
|
||||||
|
|
||||||
|
|
||||||
|
def error_text(exc: Exception, lang: str) -> str:
|
||||||
|
return exc.text(lang) if isinstance(exc, LiveError) else t(str(exc), lang)
|
||||||
@@ -0,0 +1,71 @@
|
|||||||
|
"""방송 결과 이미지(틱톡 LIVE 결과 화면)에서 매출 읽기(2026-11-06).
|
||||||
|
|
||||||
|
틱톡 화면 맨 위 카드 `RM672.2 / Attr. GMV` 의 첫 `RM` 금액을 판매금액으로 쓴다. 글자 인식 = 서버의 Tesseract(`tesseract`
|
||||||
|
명령, Dockerfile 에서 설치) — 외부로 보내지 않는다. 읽은 값은 창의 칸에 채워 줄 뿐이고, 사람이 확인한 뒤 저장한다.
|
||||||
|
"""
|
||||||
|
|
||||||
|
from __future__ import annotations
|
||||||
|
|
||||||
|
import io
|
||||||
|
import re
|
||||||
|
import shutil
|
||||||
|
import subprocess
|
||||||
|
from decimal import Decimal, InvalidOperation
|
||||||
|
|
||||||
|
from PIL import Image, ImageOps
|
||||||
|
|
||||||
|
from app.modules.asset.media import prepare_photo
|
||||||
|
|
||||||
|
from .i18n import LiveError
|
||||||
|
|
||||||
|
TIMEOUT_SECONDS = 30
|
||||||
|
# 'RM672.2', 'RM 1,234.50', 'RM1.2K'(줄인 값) — OCR 이 RM 사이에 빈칸을 넣기도 한다
|
||||||
|
_RM_RE = re.compile(r"R\s?M\s*([0-9][0-9,]*(?:[.,][0-9]+)?)\s*([KkMm](?![A-Za-z]))?")
|
||||||
|
|
||||||
|
|
||||||
|
def parse_sales(text: str) -> tuple[Decimal | None, str]:
|
||||||
|
"""OCR 글자 → (금액, 읽은 원문). 첫 RM 금액을 쓴다(아래 Rewards 칸은 $). K·M 으로 줄인 값은 정확하지 않아 None."""
|
||||||
|
m = _RM_RE.search(text or "")
|
||||||
|
if not m:
|
||||||
|
return None, ""
|
||||||
|
raw, suffix = m.group(1), m.group(2)
|
||||||
|
shown = "RM" + raw + (suffix or "")
|
||||||
|
if suffix:
|
||||||
|
return None, shown
|
||||||
|
num = raw
|
||||||
|
if "." not in num and "," in num and len(num.rsplit(",", 1)[1]) <= 2: # 'RM672,2' = 점을 쉼표로 읽음
|
||||||
|
num = num[: num.rfind(",")] + "." + num.rsplit(",", 1)[1]
|
||||||
|
try:
|
||||||
|
value = Decimal(num.replace(",", ""))
|
||||||
|
except InvalidOperation:
|
||||||
|
return None, shown
|
||||||
|
return value.quantize(Decimal("0.01")), shown
|
||||||
|
|
||||||
|
|
||||||
|
def _ocr_text(img: Image.Image) -> str:
|
||||||
|
exe = shutil.which("tesseract")
|
||||||
|
if not exe:
|
||||||
|
raise LiveError("서버에 글자 인식 프로그램(tesseract)이 없습니다. 판매금액을 직접 입력하세요.")
|
||||||
|
gray = ImageOps.grayscale(img)
|
||||||
|
if gray.width < 1000: # 작은 캡처는 키워야 잘 읽힌다
|
||||||
|
gray = gray.resize((gray.width * 2, gray.height * 2), Image.LANCZOS)
|
||||||
|
buf = io.BytesIO()
|
||||||
|
gray.save(buf, format="PNG")
|
||||||
|
try:
|
||||||
|
res = subprocess.run([exe, "stdin", "stdout", "-l", "eng", "--psm", "11"], input=buf.getvalue(),
|
||||||
|
capture_output=True, timeout=TIMEOUT_SECONDS, check=False)
|
||||||
|
except subprocess.TimeoutExpired:
|
||||||
|
raise LiveError("이미지 글자 인식이 너무 오래 걸립니다. 판매금액을 직접 입력하세요.") from None
|
||||||
|
if res.returncode != 0:
|
||||||
|
raise LiveError("이미지 글자를 읽지 못했습니다. 판매금액을 직접 입력하세요.")
|
||||||
|
return res.stdout.decode("utf-8", "replace")
|
||||||
|
|
||||||
|
|
||||||
|
def read_sales(raw: bytes) -> tuple[Decimal | None, str]:
|
||||||
|
"""이미지 바이트 → (금액, 읽은 원문). 이미지가 아니면 ValueError(prepare_photo 문구)."""
|
||||||
|
data, _ctype, _w, _h = prepare_photo(raw) # 실제 이미지 확인·크기 제한(저장과 같은 규칙)
|
||||||
|
with Image.open(io.BytesIO(data)) as img:
|
||||||
|
img.load()
|
||||||
|
# 매출 카드는 화면 위쪽 — 위 절반만 읽어 빠르고, 아래 다른 금액을 잘못 잡지 않게
|
||||||
|
top = img.crop((0, 0, img.width, max(1, img.height // 2)))
|
||||||
|
return parse_sales(_ocr_text(top))
|
||||||
@@ -0,0 +1,333 @@
|
|||||||
|
"""라이브 커머스(live) 라우터 — 말레이시아 라이브 방송의 호스트 정보·방송 스케줄(2026-11-04).
|
||||||
|
|
||||||
|
GET /live/ 스케줄표(?month=YYYY-MM) · GET /live/calendar 달력 보기(같은 달 값)
|
||||||
|
POST /live/broadcasts 방송 추가·고치기(id 칸이 있으면 고치기) + 결과 이미지 올리기
|
||||||
|
POST /live/broadcasts/{id}/delete 방송 지우기(이미지도 함께)
|
||||||
|
POST /live/broadcasts/{id}/move 달력에서 끌어 옮기기(broadcast_date·start_time) 또는 맞바꾸기(swap_with)
|
||||||
|
POST /live/ad-spend 날짜별 광고비(빈칸 = 지우기)
|
||||||
|
GET /live/images/{id} 결과 이미지(?thumb=1 = 작은 그림) · POST /live/images/{id}/delete
|
||||||
|
GET /live/settings 설정 — 호스트 정보(ERP 관리자만, 계좌 등 개인정보. `live_host` 칩은 이름·틱톡·상태만)
|
||||||
|
POST /live/settings/hosts 호스트 추가·고치기 · POST /live/settings/hosts/{id}/delete
|
||||||
|
권한: 모듈 권한키 `live`(스케줄), 설정은 ERP 관리자, `live` + `live_host` 칩 = 새 호스트 등록, `live` + `live_host_edit` 칩 = 고치기(둘 다 개인정보는 안 보임).
|
||||||
|
DB: LIVE_DB_URL(live_db) — 없으면 "설정 필요" 안내.
|
||||||
|
저장 요청은 live.js 가 fetch 로 보내고 JSON {ok, message} 를 받는다(틀려도 입력한 값이 창에 남게).
|
||||||
|
"""
|
||||||
|
|
||||||
|
from __future__ import annotations
|
||||||
|
|
||||||
|
from datetime import timedelta
|
||||||
|
from pathlib import PurePath
|
||||||
|
from typing import Any
|
||||||
|
|
||||||
|
from fastapi import APIRouter, File, Form, HTTPException, Request, UploadFile
|
||||||
|
from fastapi.responses import HTMLResponse, JSONResponse, Response
|
||||||
|
|
||||||
|
from app.modules.asset.media import MAX_PHOTO_BYTES, prepare_photo
|
||||||
|
from app.timezone import today_kst
|
||||||
|
|
||||||
|
from . import holidays, i18n, ocr, store
|
||||||
|
|
||||||
|
router = APIRouter(prefix="/live", tags=["live"])
|
||||||
|
|
||||||
|
|
||||||
|
def _store(request: Request) -> Any:
|
||||||
|
return getattr(request.app.state, "live_store", None)
|
||||||
|
|
||||||
|
|
||||||
|
def _lang(request: Request) -> str:
|
||||||
|
return i18n.norm_lang(request.cookies.get(i18n.LANG_COOKIE))
|
||||||
|
|
||||||
|
|
||||||
|
def _t(request: Request, text: str) -> str:
|
||||||
|
return i18n.t(text, _lang(request))
|
||||||
|
|
||||||
|
|
||||||
|
def _user(request: Request) -> dict[str, Any]:
|
||||||
|
from app.main import get_current_user_record # noqa: WPS433
|
||||||
|
from app.store import has_module # noqa: WPS433
|
||||||
|
|
||||||
|
user = get_current_user_record(request)
|
||||||
|
if user is None:
|
||||||
|
raise HTTPException(status_code=401, detail=_t(request, "로그인이 필요합니다."))
|
||||||
|
if not has_module(user, "live"):
|
||||||
|
raise HTTPException(status_code=403, detail=_t(request, "라이브 커머스 모듈 권한이 없습니다."))
|
||||||
|
return user
|
||||||
|
|
||||||
|
|
||||||
|
def _admin(request: Request) -> dict[str, Any]:
|
||||||
|
from app.store import is_admin # noqa: WPS433
|
||||||
|
|
||||||
|
user = _user(request)
|
||||||
|
if not is_admin(user):
|
||||||
|
raise HTTPException(status_code=403, detail=_t(request, "호스트 정보는 ERP 관리자만 볼 수 있습니다."))
|
||||||
|
return user
|
||||||
|
|
||||||
|
|
||||||
|
def _can_add_host(user: dict[str, Any]) -> bool:
|
||||||
|
from app.store import has_module, is_admin # noqa: WPS433
|
||||||
|
|
||||||
|
return is_admin(user) or has_module(user, "live_host")
|
||||||
|
|
||||||
|
|
||||||
|
def _can_edit_host(user: dict[str, Any]) -> bool:
|
||||||
|
from app.store import has_module, is_admin # noqa: WPS433
|
||||||
|
|
||||||
|
return is_admin(user) or has_module(user, "live_host_edit")
|
||||||
|
|
||||||
|
|
||||||
|
def _db(request: Request) -> Any:
|
||||||
|
st = _store(request)
|
||||||
|
if st is None:
|
||||||
|
raise HTTPException(status_code=503, detail=_t(request, "라이브 커머스 DB(LIVE_DB_URL)가 설정되지 않았습니다."))
|
||||||
|
return st
|
||||||
|
|
||||||
|
|
||||||
|
def _page(request: Request) -> Any:
|
||||||
|
"""화면 공통 — (st, user) 또는 응답(로그인·권한·설정 필요)."""
|
||||||
|
from app.main import build_erp_nav, get_current_user_record, render_template # noqa: WPS433
|
||||||
|
from app.store import has_module, is_admin, login_redirect # noqa: WPS433
|
||||||
|
|
||||||
|
user = get_current_user_record(request)
|
||||||
|
if user is None:
|
||||||
|
return login_redirect(request)
|
||||||
|
if not has_module(user, "live"):
|
||||||
|
return render_template(request, "denied.html", {"reason": _t(request, "라이브 커머스 모듈 접근 권한이 없습니다."),
|
||||||
|
"is_admin": is_admin(user)}, status_code=403)
|
||||||
|
st = _store(request)
|
||||||
|
if st is None:
|
||||||
|
return render_template(request, "denied.html", {
|
||||||
|
"reason": _t(request, "라이브 커머스 모듈이 아직 설정되지 않았습니다. scripts/sql/live_db_init.sql 로 live_db 를 만들고 "
|
||||||
|
".env 에 LIVE_DB_URL 을 넣은 뒤 컨테이너를 다시 시작하세요."),
|
||||||
|
"user": user, "is_admin": is_admin(user), "nav_items": build_erp_nav(user, active="live")}, status_code=503)
|
||||||
|
return st, user
|
||||||
|
|
||||||
|
|
||||||
|
def _render(request: Request, name: str, user: dict[str, Any], ctx: dict[str, Any]) -> HTMLResponse:
|
||||||
|
from app.main import build_erp_nav, render_template # noqa: WPS433
|
||||||
|
from app.store import is_admin # noqa: WPS433
|
||||||
|
|
||||||
|
lang = _lang(request)
|
||||||
|
return render_template(request, name, {"user": user, "is_admin": is_admin(user), "can_add_host": _can_add_host(user),
|
||||||
|
"can_edit_host": _can_edit_host(user), "lang": lang,
|
||||||
|
"t": lambda text: i18n.t(text, lang), "js_text": i18n.js_text(lang),
|
||||||
|
"hourly_rate": store.fmt_short(store.HOURLY_RATE), "commission_percent": store.fmt_short(store.COMMISSION_PERCENT),
|
||||||
|
"nav_items": build_erp_nav(user, active="live"), **ctx})
|
||||||
|
|
||||||
|
|
||||||
|
def _ok(request: Request, message: str) -> JSONResponse:
|
||||||
|
return JSONResponse({"ok": True, "message": _t(request, message)})
|
||||||
|
|
||||||
|
|
||||||
|
def _fail(request: Request, exc: Exception) -> JSONResponse:
|
||||||
|
return JSONResponse({"ok": False, "message": i18n.error_text(exc, _lang(request))}, status_code=400)
|
||||||
|
|
||||||
|
|
||||||
|
def _opt_id(raw: str) -> int | None:
|
||||||
|
s = (raw or "").strip()
|
||||||
|
if not s:
|
||||||
|
return None
|
||||||
|
if not s.isdigit():
|
||||||
|
raise ValueError("잘못된 요청입니다.")
|
||||||
|
return int(s)
|
||||||
|
|
||||||
|
|
||||||
|
@router.get("/health")
|
||||||
|
def health(request: Request) -> JSONResponse:
|
||||||
|
return JSONResponse({"status": "ok" if _store(request) is not None else "not_configured"})
|
||||||
|
|
||||||
|
|
||||||
|
# ────────────────────────────────────────────────────────────
|
||||||
|
# 스케줄표
|
||||||
|
# ────────────────────────────────────────────────────────────
|
||||||
|
@router.get("/", response_class=HTMLResponse)
|
||||||
|
def index(request: Request, month: str = "") -> Any:
|
||||||
|
got = _page(request)
|
||||||
|
if not isinstance(got, tuple):
|
||||||
|
return got
|
||||||
|
st, user = got
|
||||||
|
lang = _lang(request)
|
||||||
|
span = store.month_range(month, today_kst(), lang)
|
||||||
|
rows = [store.broadcast_view(b, lang) for b in st.list_broadcasts(span["start"], span["end"])]
|
||||||
|
return _render(request, "live/index.html", user, {"view": "table", "span": span, "rows": rows, "hosts": st.host_choices(),
|
||||||
|
"accounts": st.account_choices(), "max_images": store.MAX_IMAGES})
|
||||||
|
|
||||||
|
|
||||||
|
@router.get("/calendar", response_class=HTMLResponse)
|
||||||
|
def calendar(request: Request, month: str = "") -> Any:
|
||||||
|
got = _page(request)
|
||||||
|
if not isinstance(got, tuple):
|
||||||
|
return got
|
||||||
|
st, user = got
|
||||||
|
today, lang = today_kst(), _lang(request)
|
||||||
|
span = store.month_range(month, today, lang)
|
||||||
|
cal = store.build_calendar(span, st.list_broadcasts(span["start"], span["end"]), today, lang)
|
||||||
|
return _render(request, "live/calendar.html", user, {"view": "calendar", "span": span, "cal": cal, "hosts": st.host_choices(),
|
||||||
|
"accounts": st.account_choices(), "max_images": store.MAX_IMAGES,
|
||||||
|
"my_holidays": holidays.holiday_names(lang),
|
||||||
|
# 오른쪽 달력 점 — 앞뒤로 넘겨 볼 달까지(보는 달 ±1년)
|
||||||
|
"live_days": st.broadcast_days(span["start"] - timedelta(days=366), span["end"] + timedelta(days=366))})
|
||||||
|
|
||||||
|
|
||||||
|
@router.post("/broadcasts/{broadcast_id}/move")
|
||||||
|
def broadcast_move(request: Request, broadcast_id: int, broadcast_date: str = Form(""), start_time: str = Form(""),
|
||||||
|
swap_with: str = Form("")) -> JSONResponse:
|
||||||
|
user = _user(request)
|
||||||
|
st = _db(request)
|
||||||
|
try:
|
||||||
|
other = _opt_id(swap_with)
|
||||||
|
if other is not None:
|
||||||
|
st.swap_broadcasts(broadcast_id, other, by=user.get("email", ""))
|
||||||
|
else:
|
||||||
|
day, start = store.parse_move(broadcast_date, start_time)
|
||||||
|
st.move_broadcast(broadcast_id, day, start, by=user.get("email", ""))
|
||||||
|
except ValueError as exc:
|
||||||
|
return _fail(request, exc)
|
||||||
|
return _ok(request, "옮겼습니다.")
|
||||||
|
|
||||||
|
|
||||||
|
def _read_images(files: list[UploadFile]) -> list[dict[str, Any]]:
|
||||||
|
"""고른 파일을 실제 이미지로 확인·메타데이터 제거(GPS 등). 틀리면 ValueError — 아무것도 저장하지 않게 DB 전에."""
|
||||||
|
picked = [f for f in files if f.filename]
|
||||||
|
if len(picked) > store.MAX_IMAGES:
|
||||||
|
raise i18n.LiveError("방송 한 건에 이미지는 {max}장까지입니다.", max=store.MAX_IMAGES)
|
||||||
|
out = []
|
||||||
|
for f in picked:
|
||||||
|
name = PurePath(f.filename.replace("\\", "/")).name[:200]
|
||||||
|
try:
|
||||||
|
data, ctype, width, height = prepare_photo(f.file.read(MAX_PHOTO_BYTES + 1))
|
||||||
|
except ValueError as exc:
|
||||||
|
raise i18n.LiveError("{name}: {detail}", name=name, detail=str(exc)) from None
|
||||||
|
out.append({"filename": name, "content_type": ctype, "data": data, "width": width, "height": height})
|
||||||
|
return out
|
||||||
|
|
||||||
|
|
||||||
|
@router.post("/broadcasts")
|
||||||
|
def broadcast_save(request: Request, id: str = Form(""), host_id: str = Form(""), broadcast_date: str = Form(""),
|
||||||
|
start_time: str = Form(""), end_time: str = Form(""), tiktok_handle: str = Form(""),
|
||||||
|
sales_amount: str = Form(""), ad_spend: str = Form(""), host_fee: str = Form(""),
|
||||||
|
images: list[UploadFile] = File(default=[])) -> JSONResponse:
|
||||||
|
user = _user(request)
|
||||||
|
st = _db(request)
|
||||||
|
try:
|
||||||
|
broadcast_id = _opt_id(id)
|
||||||
|
values = store.clean_broadcast({"host_id": host_id, "broadcast_date": broadcast_date, "start_time": start_time, "end_time": end_time,
|
||||||
|
"tiktok_handle": tiktok_handle, "sales_amount": sales_amount, "ad_spend": ad_spend, "host_fee": host_fee})
|
||||||
|
st.save_broadcast(broadcast_id, values, _read_images(images), by=user.get("email", ""))
|
||||||
|
except ValueError as exc:
|
||||||
|
return _fail(request, exc)
|
||||||
|
return _ok(request, "저장했습니다.")
|
||||||
|
|
||||||
|
|
||||||
|
@router.post("/broadcasts/read-sales")
|
||||||
|
def broadcast_read_sales(request: Request, image: UploadFile = File(...)) -> JSONResponse:
|
||||||
|
"""결과 이미지(틱톡 LIVE 결과 화면)에서 매출 읽기 — 저장하지 않고 값만 돌려준다(창이 판매금액 칸에 채움)."""
|
||||||
|
_user(request)
|
||||||
|
try:
|
||||||
|
amount, shown = ocr.read_sales(image.file.read(MAX_PHOTO_BYTES + 1))
|
||||||
|
except ValueError as exc:
|
||||||
|
return _fail(request, exc)
|
||||||
|
if amount is None:
|
||||||
|
msg = (_t(request, "이미지 매출이 줄인 값({value})이라 정확하지 않습니다. 판매금액을 직접 입력하세요.").format(value=shown) if shown
|
||||||
|
else _t(request, "이미지에서 매출(RM)을 찾지 못했습니다. 판매금액을 직접 입력하세요."))
|
||||||
|
return JSONResponse({"ok": True, "amount": None, "message": msg})
|
||||||
|
return JSONResponse({"ok": True, "amount": str(amount), "message": _t(request, "이미지에서 매출 {value} 를 읽었습니다. 확인 후 저장하세요.").format(value=shown)})
|
||||||
|
|
||||||
|
|
||||||
|
@router.post("/broadcasts/{broadcast_id}/delete")
|
||||||
|
def broadcast_delete(request: Request, broadcast_id: int) -> JSONResponse:
|
||||||
|
_user(request)
|
||||||
|
try:
|
||||||
|
_db(request).delete_broadcast(broadcast_id)
|
||||||
|
except ValueError as exc:
|
||||||
|
return _fail(request, exc)
|
||||||
|
return _ok(request, "방송을 지웠습니다.")
|
||||||
|
|
||||||
|
|
||||||
|
@router.get("/images/{image_id}")
|
||||||
|
def image(request: Request, image_id: int, thumb: int = 0) -> Response:
|
||||||
|
_user(request)
|
||||||
|
row = _db(request).get_image(image_id)
|
||||||
|
if not row:
|
||||||
|
raise HTTPException(status_code=404, detail=_t(request, "이미지를 찾을 수 없습니다."))
|
||||||
|
data, ctype = (store.thumbnail(row["data"]), "image/jpeg") if thumb else (bytes(row["data"]), row["content_type"])
|
||||||
|
# 올린 뒤 내용이 바뀌지 않으므로 하루 캐시. 권한이 필요한 이미지라 private.
|
||||||
|
return Response(data, media_type=ctype, headers={"Cache-Control": "private, max-age=86400", "X-Content-Type-Options": "nosniff"})
|
||||||
|
|
||||||
|
|
||||||
|
@router.post("/images/{image_id}/delete")
|
||||||
|
def image_delete(request: Request, image_id: int) -> JSONResponse:
|
||||||
|
_user(request)
|
||||||
|
try:
|
||||||
|
_db(request).delete_image(image_id)
|
||||||
|
except ValueError as exc:
|
||||||
|
return _fail(request, exc)
|
||||||
|
return _ok(request, "이미지를 지웠습니다.")
|
||||||
|
|
||||||
|
|
||||||
|
# ────────────────────────────────────────────────────────────
|
||||||
|
# 설정 — 호스트 정보(ERP 관리자만: 계좌 등 개인정보). `live_host` 칩 = 새 호스트 등록만.
|
||||||
|
# ────────────────────────────────────────────────────────────
|
||||||
|
@router.get("/settings", response_class=HTMLResponse)
|
||||||
|
def settings(request: Request) -> Any:
|
||||||
|
from app.main import render_template # noqa: WPS433
|
||||||
|
from app.store import is_admin # noqa: WPS433
|
||||||
|
|
||||||
|
got = _page(request)
|
||||||
|
if not isinstance(got, tuple):
|
||||||
|
return got
|
||||||
|
st, user = got
|
||||||
|
if not (_can_add_host(user) or _can_edit_host(user)):
|
||||||
|
return render_template(request, "denied.html", {"reason": _t(request, "호스트 정보는 ERP 관리자만 볼 수 있습니다."), "is_admin": False},
|
||||||
|
status_code=403)
|
||||||
|
# host_choices = 이름·상태뿐 — 계좌 등 개인정보는 칩이 있어도 관리자에게만
|
||||||
|
return _render(request, "live/settings.html", user, {"hosts": st.list_hosts() if is_admin(user) else st.host_choices()})
|
||||||
|
|
||||||
|
|
||||||
|
@router.post("/settings/hosts")
|
||||||
|
def host_save(request: Request, id: str = Form(""), platform: str = Form(""), display_name: str = Form(""), full_name: str = Form(""), phone: str = Form(""), email: str = Form(""),
|
||||||
|
address: str = Form(""), bank_name: str = Form(""), bank_account: str = Form(""),
|
||||||
|
is_active: str = Form("")) -> JSONResponse:
|
||||||
|
from app.store import is_admin # noqa: WPS433
|
||||||
|
|
||||||
|
# `live_host` 칩 = 새 등록, `live_host_edit` 칩 = 고치기(개인정보는 안 보이고, 비워 두면 그대로)
|
||||||
|
user = _user(request)
|
||||||
|
if not (_can_edit_host(user) if id.strip() else _can_add_host(user)):
|
||||||
|
_admin(request)
|
||||||
|
st = _db(request)
|
||||||
|
try:
|
||||||
|
values = store.clean_host({"platform": platform, "display_name": display_name, "full_name": full_name, "phone": phone, "email": email, "address": address, "bank_name": bank_name,
|
||||||
|
"bank_account": bank_account})
|
||||||
|
host_id = _opt_id(id)
|
||||||
|
if host_id is not None and not is_admin(user): # 개인정보를 못 보므로 빈칸 = 지우기가 아니라 그대로
|
||||||
|
old = st.get_host(host_id)
|
||||||
|
if not old:
|
||||||
|
raise i18n.LiveError("호스트를 찾을 수 없습니다.")
|
||||||
|
values.update({k: values[k] or old[k] for k in store.PRIVATE_HOST_FIELDS})
|
||||||
|
# 등록만 되는 칩 화면엔 사용 여부 칸이 없다 — 항상 사용(사용 안 함으로 만들면 본인이 되돌릴 수 없음)
|
||||||
|
st.save_host(host_id, values, is_active=bool(is_active) or not _can_edit_host(user), by=user.get("email", ""))
|
||||||
|
except ValueError as exc:
|
||||||
|
return _fail(request, exc)
|
||||||
|
return _ok(request, "호스트를 저장했습니다.")
|
||||||
|
|
||||||
|
|
||||||
|
@router.post("/settings/hosts/{host_id}/active")
|
||||||
|
def host_active(request: Request, host_id: int, is_active: str = Form("")) -> JSONResponse:
|
||||||
|
"""목록의 사용 토글 — 고치기 권한(ERP 관리자·`live_host_edit` 칩)."""
|
||||||
|
user = _user(request)
|
||||||
|
if not _can_edit_host(user):
|
||||||
|
_admin(request)
|
||||||
|
try:
|
||||||
|
_db(request).set_host_active(host_id, is_active == "1", by=user.get("email", ""))
|
||||||
|
except ValueError as exc:
|
||||||
|
return _fail(request, exc)
|
||||||
|
return _ok(request, "사용으로 바꿨습니다." if is_active == "1" else "사용 안 함으로 바꿨습니다.")
|
||||||
|
|
||||||
|
|
||||||
|
@router.post("/settings/hosts/{host_id}/delete")
|
||||||
|
def host_delete(request: Request, host_id: int) -> JSONResponse:
|
||||||
|
_admin(request)
|
||||||
|
try:
|
||||||
|
_db(request).delete_host(host_id)
|
||||||
|
except ValueError as exc:
|
||||||
|
return _fail(request, exc)
|
||||||
|
return _ok(request, "호스트를 지웠습니다.")
|
||||||
@@ -0,0 +1,269 @@
|
|||||||
|
"""라이브 커머스 순수 함수 — 입력 검사·표시 형식(DB 없이 시험 가능)."""
|
||||||
|
|
||||||
|
from __future__ import annotations
|
||||||
|
|
||||||
|
import io
|
||||||
|
import re
|
||||||
|
from datetime import date, datetime, time, timedelta
|
||||||
|
from decimal import ROUND_HALF_UP, Decimal, InvalidOperation
|
||||||
|
from typing import Any
|
||||||
|
|
||||||
|
from PIL import Image
|
||||||
|
|
||||||
|
from .i18n import LiveError, month_label
|
||||||
|
|
||||||
|
MAX_IMAGES = 10 # 방송 한 건에
|
||||||
|
MAX_SALES = Decimal("999999999999.99")
|
||||||
|
THUMB_SIZE = 160
|
||||||
|
# shortcut: 요율이 코드 상수라 바꾸면 지난 방송 금액도 다시 계산된다 — 요율이 바뀌는 일이 생기면 방송마다 저장하도록 바꿀 것
|
||||||
|
HOURLY_RATE = Decimal("25") # 호스트 시간당 요금(RM)
|
||||||
|
COMMISSION_PERCENT = Decimal("10") # 판매금액의 %
|
||||||
|
SLOT_HOURS = 1 # 달력 한 칸(2026-11-06, 2시간 → 1시간)
|
||||||
|
FIRST_SLOT_HOUR = 6 # 달력에 늘 보이는 첫 칸(이보다 이른 칸은 방송이 있을 때만)
|
||||||
|
HOST_COLORS = ("#66d4e6", "#6ee05a", "#d4f06a", "#e9cf7a", "#ec9d88", "#cdb9ea", "#f4a9c8", "#a9c4f5")
|
||||||
|
_CENT = Decimal("0.01")
|
||||||
|
_WEEKDAYS = ("MONDAY", "TUESDAY", "WEDNESDAY", "THURSDAY", "FRIDAY", "SATURDAY", "SUNDAY")
|
||||||
|
_MONTHS = ("JAN", "FEB", "MAR", "APR", "MAY", "JUN", "JUL", "AUG", "SEP", "OCT", "NOV", "DEC")
|
||||||
|
|
||||||
|
HOST_LIMITS = {"display_name": 50, "full_name": 200, "phone": 40, "email": 254, "address": 500, "bank_name": 100, "bank_account": 40}
|
||||||
|
HANDLE_LIMIT = 64
|
||||||
|
PLATFORMS = ("tiktok", "shopee") # 호스트 쇼핑몰(005) — 로고 = /static/dispatch/courier/<값>.png(말레이시아 배송 모듈 이미지)
|
||||||
|
PRIVATE_HOST_FIELDS = ("phone", "email", "address", "bank_name", "bank_account") # 화면에 보이는 사람 = ERP 관리자만
|
||||||
|
_LABELS = {"display_name": "간단한 이름", "full_name": "이름 (IC 기준)", "phone": "전화번호", "email": "이메일", "address": "주소", "bank_name": "은행명",
|
||||||
|
"bank_account": "계좌번호"}
|
||||||
|
_EMAIL_RE = re.compile(r"^[A-Za-z0-9._%+\-']+@[A-Za-z0-9.\-]+\.[A-Za-z]{2,}$")
|
||||||
|
_PHONE_RE = re.compile(r"^\+?[0-9()\-\s]+$")
|
||||||
|
_ACCOUNT_RE = re.compile(r"^[0-9\-\s]+$")
|
||||||
|
_HANDLE_RE = re.compile(r"^[A-Za-z0-9._]+$")
|
||||||
|
_HANDLE_URL_RE = re.compile(r"^(?:https?://)?(?:www\.|m\.)?tiktok\.com/@?", re.I)
|
||||||
|
WEEKDAYS_KO = "월화수목금토일"
|
||||||
|
_WEEKDAYS_EN_SHORT = ("Mon", "Tue", "Wed", "Thu", "Fri", "Sat", "Sun")
|
||||||
|
|
||||||
|
|
||||||
|
def clean_handle(raw: Any) -> str:
|
||||||
|
"""'@name'·'https://www.tiktok.com/@name?lang=en' → 'name'."""
|
||||||
|
s = _HANDLE_URL_RE.sub("", str(raw or "").strip())
|
||||||
|
return re.split(r"[/?#]", s, maxsplit=1)[0].lstrip("@")
|
||||||
|
|
||||||
|
|
||||||
|
def clean_host(values: dict[str, Any]) -> dict[str, str]:
|
||||||
|
"""호스트 입력 검사 — 쇼핑몰·간단한 이름·이름만 필수, 나머지는 있으면 형식 확인. 틀리면 ValueError."""
|
||||||
|
out = {k: str(values.get(k) or "").strip() for k in HOST_LIMITS}
|
||||||
|
out["platform"] = str(values.get("platform") or "").strip().lower()
|
||||||
|
if out["platform"] not in PLATFORMS:
|
||||||
|
raise LiveError("쇼핑몰(틱톡·쇼피)을 고르세요.")
|
||||||
|
if not out["display_name"]:
|
||||||
|
raise LiveError("간단한 이름을 입력하세요.")
|
||||||
|
if not out["full_name"]:
|
||||||
|
raise LiveError("이름 (IC 기준)을 입력하세요.")
|
||||||
|
for key, limit in HOST_LIMITS.items():
|
||||||
|
if len(out[key]) > limit:
|
||||||
|
raise LiveError("{label} 이(가) 너무 깁니다({limit}자까지).", label=_LABELS[key], limit=limit)
|
||||||
|
if out["email"] and not _EMAIL_RE.match(out["email"]):
|
||||||
|
raise LiveError("이메일 형식이 올바르지 않습니다.")
|
||||||
|
if out["phone"] and not _PHONE_RE.match(out["phone"]):
|
||||||
|
raise LiveError("전화번호는 숫자·+·-·괄호만 입력하세요.")
|
||||||
|
if out["bank_account"] and not _ACCOUNT_RE.match(out["bank_account"]):
|
||||||
|
raise LiveError("계좌번호는 숫자·-만 입력하세요.")
|
||||||
|
return out
|
||||||
|
|
||||||
|
|
||||||
|
def parse_money(raw: Any, label: str = "판매금액") -> Decimal | None:
|
||||||
|
"""금액(RM) — 빈칸은 None(아직 입력 안 함), 0 이상, 소수 둘째 자리까지. 쉼표·RM 허용."""
|
||||||
|
s = re.sub(r"(?i)^rm|[,\s]", "", str(raw if raw is not None else "").strip())
|
||||||
|
if not s:
|
||||||
|
return None
|
||||||
|
try:
|
||||||
|
n = Decimal(s)
|
||||||
|
except InvalidOperation:
|
||||||
|
raise LiveError("{label}은(는) 숫자로 입력하세요.", label=label) from None
|
||||||
|
if not n.is_finite() or n < 0:
|
||||||
|
raise LiveError("{label}은(는) 0 이상 숫자로 입력하세요.", label=label)
|
||||||
|
if n > MAX_SALES:
|
||||||
|
raise LiveError("{label}이(가) 너무 큽니다.", label=label)
|
||||||
|
return n.quantize(Decimal("0.01"), rounding=ROUND_HALF_UP)
|
||||||
|
|
||||||
|
|
||||||
|
def _parse_time(raw: Any, *, label: str, required: bool) -> time | None:
|
||||||
|
s = str(raw or "").strip()
|
||||||
|
if not s:
|
||||||
|
if required:
|
||||||
|
raise LiveError("{label}을 입력하세요.", label=label)
|
||||||
|
return None
|
||||||
|
try:
|
||||||
|
return time.fromisoformat(s).replace(second=0, microsecond=0, tzinfo=None)
|
||||||
|
except ValueError:
|
||||||
|
raise LiveError("{label}이 올바르지 않습니다.", label=label) from None
|
||||||
|
|
||||||
|
|
||||||
|
def clean_broadcast(values: dict[str, Any]) -> dict[str, Any]:
|
||||||
|
"""방송 입력 검사 — 호스트·날짜·시작·끝 시간 필수(끝 시간으로 시간 요금 계산). 끝이 시작보다 이르면 자정을 넘긴 방송. 틀리면 ValueError."""
|
||||||
|
host = str(values.get("host_id") or "").strip()
|
||||||
|
if not host.isdigit():
|
||||||
|
raise LiveError("호스트를 고르세요.")
|
||||||
|
try:
|
||||||
|
day = date.fromisoformat(str(values.get("broadcast_date") or "").strip())
|
||||||
|
except ValueError:
|
||||||
|
raise LiveError("방송 날짜를 입력하세요.") from None
|
||||||
|
start = _parse_time(values.get("start_time"), label="시작 시간", required=True)
|
||||||
|
end = _parse_time(values.get("end_time"), label="끝 시간", required=True)
|
||||||
|
if start == end:
|
||||||
|
raise LiveError("끝 시간이 시작 시간과 같습니다.")
|
||||||
|
handle = clean_handle(values.get("tiktok_handle"))
|
||||||
|
if len(handle) > HANDLE_LIMIT:
|
||||||
|
raise LiveError("{label} 이(가) 너무 깁니다({limit}자까지).", label="틱톡 핸들", limit=HANDLE_LIMIT)
|
||||||
|
if handle and not _HANDLE_RE.match(handle):
|
||||||
|
raise LiveError("틱톡 핸들은 영문·숫자·밑줄·점만 입력하세요.")
|
||||||
|
return {"host_id": int(host), "broadcast_date": day, "start_time": start, "end_time": end, "tiktok_handle": handle,
|
||||||
|
"sales_amount": parse_money(values.get("sales_amount")), "ad_spend": parse_money(values.get("ad_spend"), "광고비"),
|
||||||
|
"host_fee": parse_money(values.get("host_fee"), "호스트 비용")}
|
||||||
|
|
||||||
|
|
||||||
|
def parse_move(day: Any, start: Any) -> tuple[date, time]:
|
||||||
|
"""달력 칸 — 날짜·시작 시간. 틀리면 ValueError."""
|
||||||
|
try:
|
||||||
|
when = date.fromisoformat(str(day or "").strip())
|
||||||
|
except ValueError:
|
||||||
|
raise LiveError("날짜가 올바르지 않습니다.") from None
|
||||||
|
return when, _parse_time(start, label="시간", required=True)
|
||||||
|
|
||||||
|
|
||||||
|
def moved_end(old_start: time, old_end: time | None, new_start: time) -> time | None:
|
||||||
|
"""칸을 옮겨도 방송 길이는 그대로."""
|
||||||
|
if old_end is None:
|
||||||
|
return None
|
||||||
|
return (datetime.combine(date.min, new_start) + _duration(old_start, old_end)).time()
|
||||||
|
|
||||||
|
|
||||||
|
def _duration(start: time, end: time) -> timedelta:
|
||||||
|
minutes = (end.hour * 60 + end.minute - start.hour * 60 - start.minute) % 1440 # 끝이 더 이르면 자정을 넘긴 방송
|
||||||
|
return timedelta(minutes=minutes)
|
||||||
|
|
||||||
|
|
||||||
|
def session_pay(start: time, end: time | None, sales: Decimal | None) -> dict[str, Decimal]:
|
||||||
|
"""참고 금액(저장 안 함) — Fee = 시간 × 시간당 요금, 커미션 = 판매금액 × %. 같은 계산이 방송 창에도(live.js recalc).
|
||||||
|
호스트 비용은 2026-11-06 부터 수기 입력(live_broadcasts.host_fee)."""
|
||||||
|
hours = Decimal(_duration(start, end).seconds) / 3600 if end else Decimal(0)
|
||||||
|
base = (hours * HOURLY_RATE).quantize(_CENT, rounding=ROUND_HALF_UP)
|
||||||
|
commission = ((sales or Decimal(0)) * COMMISSION_PERCENT / 100).quantize(_CENT, rounding=ROUND_HALF_UP)
|
||||||
|
return {"hours": hours, "base": base, "commission": commission}
|
||||||
|
|
||||||
|
|
||||||
|
def fmt_short(n: Decimal) -> str:
|
||||||
|
"""카드·합계용 — 소수점 아래가 0 이면 뺀다(48, 4.80, 1,234.50)."""
|
||||||
|
return f"{n:,.2f}".removesuffix(".00")
|
||||||
|
|
||||||
|
|
||||||
|
def broadcast_view(b: dict[str, Any], lang: str = "ko") -> dict[str, Any]:
|
||||||
|
"""방송 한 건 화면 값 — 표·달력 공통. b = db.list_broadcasts 한 줄."""
|
||||||
|
pay = session_pay(b["start_time"], b["end_time"], b["sales_amount"])
|
||||||
|
return {
|
||||||
|
"date": fmt_date(b["broadcast_date"], lang), "times": fmt_times(b["start_time"], b["end_time"]),
|
||||||
|
"host_name": b["host_name"], "tiktok_handle": b["tiktok_handle"], "venue": b["venue"],
|
||||||
|
"platform": b["host_platform"], # 호스트 쇼핑몰(tiktok·shopee, '' = 아직 안 고름) — 아이콘 /static/live-icon-<값>.png
|
||||||
|
"sales": fmt_money(b["sales_amount"]), "base": fmt_money(pay["base"]), "commission": fmt_money(pay["commission"]),
|
||||||
|
"ad_spend": fmt_money(b["ad_spend"]), "host_fee": fmt_money(b["host_fee"]),
|
||||||
|
"images": b["images"], "id": b["id"],
|
||||||
|
"label": b["host_name"], "color": HOST_COLORS[b["host_id"] % len(HOST_COLORS)],
|
||||||
|
"card_sales": fmt_short(b["sales_amount"] or Decimal(0)), "card_commission": fmt_short(pay["commission"]),
|
||||||
|
"card_fee": fmt_short(b["host_fee"] or Decimal(0)),
|
||||||
|
"edit": {"id": b["id"], "host_id": b["host_id"], "broadcast_date": b["broadcast_date"].isoformat(),
|
||||||
|
"start_time": f"{b['start_time']:%H:%M}", "end_time": f"{b['end_time']:%H:%M}" if b["end_time"] else "",
|
||||||
|
"tiktok_handle": b["tiktok_handle"],
|
||||||
|
**{k: f"{b[k]:.2f}" if b[k] is not None else "" for k in ("sales_amount", "ad_spend", "host_fee")},
|
||||||
|
"images": [{"id": i["id"], "filename": i["filename"]} for i in b["images"]]},
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
def _roas(sales: Decimal, ad_spend: Decimal) -> str:
|
||||||
|
return f"{sales / ad_spend:.2f}" if ad_spend else "-"
|
||||||
|
|
||||||
|
|
||||||
|
def _slot_of(hour: int) -> int:
|
||||||
|
return hour // SLOT_HOURS * SLOT_HOURS
|
||||||
|
|
||||||
|
|
||||||
|
def _covered_slots(b: dict[str, Any]) -> list[int]:
|
||||||
|
"""방송이 걸친 칸(시작 칸 ~ 끝 시각 올림 직전 칸). 자정을 넘기거나 00:00 에 끝나면 그날 마지막 칸까지."""
|
||||||
|
s, e = b["start_time"], b["end_time"]
|
||||||
|
end = 24 if e <= s else e.hour + (1 if (e.minute or e.second) else 0)
|
||||||
|
return sorted({_slot_of(h) for h in range(s.hour, max(end, s.hour + 1))})
|
||||||
|
|
||||||
|
|
||||||
|
def build_calendar(span: dict[str, Any], broadcasts: list[dict[str, Any]], today: date, lang: str = "ko") -> dict[str, Any]:
|
||||||
|
"""달력 보기 값 — 날짜(열)·SLOT_HOURS 칸(줄)·날짜별 합계(판매금액·광고비·호스트 비용 = 그날 방송 값 합, 2026-11-06)·달 합계.
|
||||||
|
카드는 시작 칸에, 그 칸은 방송이 걸친 칸만큼 아래로 합친다
|
||||||
|
(rowspan, 2026-11-06). 합친 칸 안에서 시작하는 다른 방송도 같은 칸에 들어가고 더 길면 칸이 더 늘어난다. 가려진 칸 = {"skip": True}."""
|
||||||
|
views = [(b, broadcast_view(b, lang)) for b in broadcasts]
|
||||||
|
used = {h for b, _ in views for h in _covered_slots(b)}
|
||||||
|
days = []
|
||||||
|
day = span["start"]
|
||||||
|
while day < span["end"]:
|
||||||
|
mine = [(b, v) for b, v in views if b["broadcast_date"] == day]
|
||||||
|
sales, fee, spend = (sum((b[k] or Decimal(0) for b, _ in mine), Decimal(0)) for k in ("sales_amount", "host_fee", "ad_spend"))
|
||||||
|
days.append({"iso": day.isoformat(), "date": day, "day": day.day, "weekday": _WEEKDAYS[day.weekday()] if lang == "en" else WEEKDAYS_KO[day.weekday()] + "요일",
|
||||||
|
"label": f"{day.day} {_MONTHS[day.month - 1]}" if lang == "en" else f"{day.month}월 {day.day}일", "is_weekend": day.weekday() >= 5, "is_today": day == today,
|
||||||
|
"count": len(mine), "sales": sales, "fee": fee, "spend": spend,
|
||||||
|
"sales_text": fmt_short(sales), "fee_text": fmt_short(fee), "spend_text": fmt_short(spend), "roas": _roas(sales, spend)})
|
||||||
|
day += timedelta(days=1)
|
||||||
|
hours = sorted(set(range(FIRST_SLOT_HOUR, 24, SLOT_HOURS)) | used) # 방송이 걸친 칸은 늘 있음 → 합칠 칸이 이어져 있다
|
||||||
|
columns = []
|
||||||
|
for d in days:
|
||||||
|
mine = [(b, v) for b, v in views if b["broadcast_date"] == d["date"]]
|
||||||
|
col, i = [], 0
|
||||||
|
while i < len(hours):
|
||||||
|
group = [(b, v) for b, v in mine if _slot_of(b["start_time"].hour) == hours[i]]
|
||||||
|
last, j = max((_covered_slots(b)[-1] for b, _ in group), default=hours[i]), i + 1
|
||||||
|
while j < len(hours) and hours[j] <= last:
|
||||||
|
more = [(b, v) for b, v in mine if _slot_of(b["start_time"].hour) == hours[j]]
|
||||||
|
group += more
|
||||||
|
last = max([last] + [_covered_slots(b)[-1] for b, _ in more])
|
||||||
|
j += 1
|
||||||
|
col.append({"iso": d["iso"], "is_weekend": d["is_weekend"], "cards": [v for _, v in group], "rowspan": j - i})
|
||||||
|
col += [{"skip": True}] * (j - i - 1)
|
||||||
|
i = j
|
||||||
|
columns.append(col)
|
||||||
|
slots = []
|
||||||
|
for k, hour in enumerate(hours):
|
||||||
|
end_hour = (hour + SLOT_HOURS) % 24
|
||||||
|
slots.append({"start": f"{hour:02d}:00", "end": f"{end_hour:02d}:00", "label": f"{hour:02d}:00 - {end_hour:02d}:00",
|
||||||
|
"cells": [col[k] for col in columns]})
|
||||||
|
sales, fee, spend = (sum((d[k] for d in days), Decimal(0)) for k in ("sales", "fee", "spend"))
|
||||||
|
return {"days": days, "slots": slots, "slot_note": f"{SLOT_HOURS} Hour{'s' if SLOT_HOURS > 1 else ''} (RM{fmt_short(HOURLY_RATE * SLOT_HOURS)} Base)" if lang == "en" else f"{SLOT_HOURS}시간 (기본 RM{fmt_short(HOURLY_RATE * SLOT_HOURS)})",
|
||||||
|
"commission_percent": fmt_short(COMMISSION_PERCENT).split(".")[0],
|
||||||
|
"totals": {"sales": fmt_short(sales), "fee": fmt_short(fee), "spend": fmt_short(spend), "roas": _roas(sales, spend)}}
|
||||||
|
|
||||||
|
|
||||||
|
def month_range(raw: Any, today: date, lang: str = "ko") -> dict[str, Any]:
|
||||||
|
"""'YYYY-MM'(틀리거나 없으면 이번 달) → 그 달 첫날·다음 달 첫날·앞뒤 달 주소 값·제목."""
|
||||||
|
m = re.fullmatch(r"(\d{4})-(\d{2})", str(raw or "").strip())
|
||||||
|
year, month = (int(m[1]), int(m[2])) if m and 2000 <= int(m[1]) <= 2100 and 1 <= int(m[2]) <= 12 else (today.year, today.month)
|
||||||
|
start = date(year, month, 1)
|
||||||
|
end = date(year + (month == 12), month % 12 + 1, 1)
|
||||||
|
prev = date(year - (month == 1), (month - 2) % 12 + 1, 1)
|
||||||
|
return {"start": start, "end": end, "prev": prev.strftime("%Y-%m"), "next": end.strftime("%Y-%m"),
|
||||||
|
"label": month_label(year, month, lang)}
|
||||||
|
|
||||||
|
|
||||||
|
def fmt_date(d: date, lang: str = "ko") -> str:
|
||||||
|
return f"{d:%Y.%m.%d} ({_WEEKDAYS_EN_SHORT[d.weekday()]})" if lang == "en" else f"{d:%Y.%m.%d}({WEEKDAYS_KO[d.weekday()]})"
|
||||||
|
|
||||||
|
|
||||||
|
def fmt_times(start: time, end: time | None) -> str:
|
||||||
|
return f"{start:%H:%M}" + (f" ~ {end:%H:%M}" if end else "")
|
||||||
|
|
||||||
|
|
||||||
|
def fmt_money(n: Decimal | None) -> str:
|
||||||
|
return f"{n:,.2f}" if n is not None else ""
|
||||||
|
|
||||||
|
|
||||||
|
def thumbnail(data: bytes) -> bytes:
|
||||||
|
"""목록 작은 그림 — JPEG(투명은 흰 바탕). 저장할 때 이미 확인한 이미지만 들어온다."""
|
||||||
|
with Image.open(io.BytesIO(data)) as source:
|
||||||
|
source.thumbnail((THUMB_SIZE, THUMB_SIZE))
|
||||||
|
rgba = source.convert("RGBA")
|
||||||
|
canvas = Image.new("RGB", rgba.size, "white")
|
||||||
|
canvas.paste(rgba, mask=rgba.getchannel("A"))
|
||||||
|
out = io.BytesIO()
|
||||||
|
canvas.save(out, format="JPEG", quality=80)
|
||||||
|
return out.getvalue()
|
||||||
@@ -0,0 +1,19 @@
|
|||||||
|
{#- 스케줄표·달력 공통 위 막대 — 달 이동, 표/달력 전환, 언어, 호스트 설정, 방송 추가. view = table | calendar -#}
|
||||||
|
{% set here = '/live/calendar' if view == 'calendar' else '/live/' %}
|
||||||
|
{% set can_add = hosts | selectattr('is_active') | list %}
|
||||||
|
<div class="lv-bar">
|
||||||
|
<a class="erp-btn erp-btn-outline" href="{{ here }}?month={{ span.prev }}" aria-label="{{ t('이전 달') }}">◀</a>
|
||||||
|
<h2 class="lv-month">{{ span.label }}</h2>
|
||||||
|
<a class="erp-btn erp-btn-outline" href="{{ here }}?month={{ span.next }}" aria-label="{{ t('다음 달') }}">▶</a>
|
||||||
|
<nav class="lv-views" aria-label="{{ t('보기 방식') }}">
|
||||||
|
<a class="erp-btn {{ 'erp-btn-primary' if view == 'table' else 'erp-btn-outline' }}" href="/live/?month={{ span.start.strftime('%Y-%m') }}"{% if view == 'table' %} aria-current="page"{% endif %}>{{ t('표') }}</a>
|
||||||
|
<a class="erp-btn {{ 'erp-btn-primary' if view == 'calendar' else 'erp-btn-outline' }}" href="/live/calendar?month={{ span.start.strftime('%Y-%m') }}"{% if view == 'calendar' %} aria-current="page"{% endif %}>{{ t('달력') }}</a>
|
||||||
|
</nav>
|
||||||
|
<span class="lv-gap"></span>
|
||||||
|
{% include "live/_lang.html" %}
|
||||||
|
{% if can_add_host or can_edit_host %}<a class="erp-btn erp-btn-outline" href="/live/settings">{{ t('호스트 설정') }}</a>{% endif %}
|
||||||
|
<button type="button" class="erp-btn erp-btn-primary" id="lv-add"{% if not can_add %} disabled{% endif %}>{{ t('+ 방송 추가') }}</button>
|
||||||
|
</div>
|
||||||
|
{% if not can_add %}
|
||||||
|
<p class="lv-note">{{ t('방송을 추가하려면 먼저 호스트를 등록해야 합니다.') }} {% if can_add_host %}<a href="/live/settings">{{ t('호스트 설정') }}</a>{% else %}{{ t('ERP 관리자에게 등록을 요청하세요.') }}{% endif %}</p>
|
||||||
|
{% endif %}
|
||||||
@@ -0,0 +1,42 @@
|
|||||||
|
{#- 방송 추가·고치기 창 — 스케줄표·달력 공통(live.js). 호스트 고르기엔 이름만(계좌 등은 설정 화면). 틱톡 계정은 방송마다 — 쓴 적 있는 계정을 제안(새 계정도 입력 가능). -#}
|
||||||
|
<dialog class="lv-dlg" id="lv-dlg" aria-labelledby="lv-dlg-title">
|
||||||
|
<form id="lv-form" action="/live/broadcasts">
|
||||||
|
<h3 id="lv-dlg-title" data-add="{{ t('방송 추가') }}" data-edit="{{ t('방송 고치기') }}"></h3>
|
||||||
|
<input type="hidden" name="id" />
|
||||||
|
<label class="lv-field">{{ t('호스트') }}
|
||||||
|
<select class="erp-select" name="host_id" required>
|
||||||
|
<option value="">{{ t('호스트를 고르세요') }}</option>
|
||||||
|
{% for h in hosts %}<option value="{{ h.id }}"{% if not h.is_active %} data-inactive="1"{% endif %}>{{ h.display_name or h.full_name }}{% if not h.is_active %} — {{ t('사용 안 함') }}{% endif %}</option>{% endfor %}
|
||||||
|
</select>
|
||||||
|
</label>
|
||||||
|
<label class="lv-field">{{ t('틱톡 핸들') }} <input class="erp-input" type="text" name="tiktok_handle" maxlength="200" placeholder="@handle" list="lv-accounts" autocomplete="off" /></label>
|
||||||
|
<datalist id="lv-accounts">{% for a in accounts %}<option value="{{ a }}"></option>{% endfor %}</datalist>
|
||||||
|
<div class="lv-row">
|
||||||
|
<label class="lv-field">{{ t('방송 날짜') }} <input class="erp-input" type="date" name="broadcast_date" required /></label>
|
||||||
|
<label class="lv-field">{{ t('시작 시간') }} <input class="erp-input" type="time" name="start_time" required /></label>
|
||||||
|
<label class="lv-field">{{ t('끝 시간') }} <input class="erp-input" type="time" name="end_time" required /></label>
|
||||||
|
</div>
|
||||||
|
<p class="lv-sub">{{ t('시간은 말레이시아 시간으로 입력합니다.') }}</p>
|
||||||
|
<label class="lv-field">{{ t('판매금액 (RM)') }} <input class="erp-input lv-num" type="text" name="sales_amount" inputmode="decimal" placeholder="{{ t('방송 후 입력') }}" /></label>
|
||||||
|
{#- Fee·커미션 = 자동 계산(저장 안 함, live.js recalc — store.session_pay 와 같은 계산). 광고비·호스트 비용 = 입력(2026-11-06) -#}
|
||||||
|
<div class="lv-row">
|
||||||
|
<label class="lv-field">{{ t('시간 요금 (RM)') }} <input class="erp-input lv-num" type="text" data-fee="{{ hourly_rate }}" readonly />
|
||||||
|
<small class="lv-sub">{{ t('시간 × RM {rate} — 자동').format(rate=hourly_rate) }}</small></label>
|
||||||
|
<label class="lv-field">{{ t('커미션 (RM)') }} <input class="erp-input lv-num" type="text" data-commission="{{ commission_percent }}" readonly />
|
||||||
|
<small class="lv-sub">{{ t('판매금액 × {percent}% — 자동').format(percent=commission_percent) }}</small></label>
|
||||||
|
</div>
|
||||||
|
<div class="lv-row">
|
||||||
|
<label class="lv-field">{{ t('광고비 (RM)') }} <input class="erp-input lv-num" type="text" name="ad_spend" inputmode="decimal" /></label>
|
||||||
|
<label class="lv-field">{{ t('호스트 비용 (RM)') }} <input class="erp-input lv-num" type="text" name="host_fee" inputmode="decimal" placeholder="{{ t('직접 입력') }}" /></label>
|
||||||
|
</div>
|
||||||
|
<label class="lv-field">{{ t('방송 결과 이미지 (JPG·PNG·WebP, 한 장 8MB, 방송당 {n}장까지)').format(n=max_images) }}
|
||||||
|
<input type="file" name="images" accept="image/jpeg,image/png,image/webp" multiple />
|
||||||
|
</label>
|
||||||
|
<ul class="lv-saved" data-saved hidden></ul>
|
||||||
|
<p class="lv-msg" data-msg role="alert" hidden></p>
|
||||||
|
<div class="lv-foot">
|
||||||
|
<button type="button" class="erp-btn erp-btn-outline" data-close>{{ t('취소') }}</button>
|
||||||
|
<button type="submit" class="erp-btn erp-btn-primary">{{ t('저장') }}</button>
|
||||||
|
</div>
|
||||||
|
</form>
|
||||||
|
</dialog>
|
||||||
@@ -0,0 +1,5 @@
|
|||||||
|
{#- 한글·영문 전환 — 누르면 쿠키에 저장하고 다시 그린다(live.js). 언어 이름은 언어와 상관없이 그대로 보인다. -#}
|
||||||
|
<div class="lv-lang" role="group" aria-label="{{ t('언어') }}">
|
||||||
|
<button type="button" data-lang="ko"{% if lang != 'en' %} class="is-active" aria-pressed="true"{% else %} aria-pressed="false"{% endif %}>한글</button>
|
||||||
|
<button type="button" data-lang="en"{% if lang == 'en' %} class="is-active" aria-pressed="true"{% else %} aria-pressed="false"{% endif %}>EN</button>
|
||||||
|
</div>
|
||||||
@@ -0,0 +1,2 @@
|
|||||||
|
<script>window.LV_T = {{ js_text | tojson }};</script>
|
||||||
|
<script src="/static/live.js?v=20261106f" defer></script>
|
||||||
@@ -0,0 +1,111 @@
|
|||||||
|
{% extends "erp_base.html" %}
|
||||||
|
{#- 라이브 커머스 달력 보기(2026-11-04) — 줄 = 2시간 칸, 열 = 날짜, 맨 아래 = 날짜별 합계. 카드 머리 = 호스트 간단한 이름 + 그 방송의 틱톡 계정.
|
||||||
|
카드 머리를 끌어 빈 칸으로 옮기거나 다른 카드 위에 놓아 맞바꾼다(live.js). 문구 = t()(i18n.py), 영문은 CSS 로 대문자(받은 화면과 같게). -#}
|
||||||
|
{% block head_extra %}<link rel="stylesheet" href="/static/live.css?v=20261106h" />
|
||||||
|
<link rel="stylesheet" href="/static/vendor/material-symbols/material-symbols.css" />
|
||||||
|
<link rel="stylesheet" href="/static/erp-datepop.css?v=20261102a" />{% endblock %}
|
||||||
|
|
||||||
|
{% block content %}
|
||||||
|
<div class="lv-split">
|
||||||
|
<section class="lv" lang="{{ lang }}">
|
||||||
|
{% include "live/_bar.html" %}
|
||||||
|
|
||||||
|
<div class="lv-kpis">
|
||||||
|
<div class="lv-kpi"><span>{{ t('총 판매금액') }}</span><b>RM {{ cal.totals.sales }}</b></div>
|
||||||
|
<div class="lv-kpi"><span>{{ t('광고비') }}</span><b>RM {{ cal.totals.spend }}</b></div>
|
||||||
|
<div class="lv-kpi"><span>{{ t('호스트 비용') }}</span><b>RM {{ cal.totals.fee }}</b></div>
|
||||||
|
<div class="lv-kpi"><span>ROAS</span><b>{{ cal.totals.roas }}</b></div>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<p class="lv-tip">{{ t('팁: 카드 머리를 끌어 옮기거나 맞바꿀 수 있습니다. 오른쪽으로 스크롤하면 이달 {n}일을 모두 볼 수 있습니다.').format(n=cal.days | length) }}</p>
|
||||||
|
|
||||||
|
<div class="lv-cal-wrap" id="lv-cal-wrap">
|
||||||
|
<table class="lv-cal">
|
||||||
|
<thead>
|
||||||
|
<tr>
|
||||||
|
<th class="lv-cal-time" scope="col">{{ t('시간') }}</th>
|
||||||
|
{% for d in cal.days %}
|
||||||
|
<th scope="col" data-day="{{ d.iso }}"{% if d.is_today %} data-today="1"{% endif %} class="{% if d.is_weekend %}is-weekend{% endif %}{% if d.is_today %} is-today{% endif %}">
|
||||||
|
<div class="lv-cal-weekday">{{ d.weekday }} <span class="lv-cal-count">{{ d.count }}</span></div>
|
||||||
|
<div class="lv-cal-date">{{ d.label }}</div>
|
||||||
|
</th>
|
||||||
|
{% endfor %}
|
||||||
|
</tr>
|
||||||
|
</thead>
|
||||||
|
<tbody>
|
||||||
|
{% for slot in cal.slots %}
|
||||||
|
<tr>
|
||||||
|
<th class="lv-cal-time" scope="row">{{ slot.label }}<small>{{ cal.slot_note }}</small></th>
|
||||||
|
{% for cell in slot.cells %}{% if not cell.skip %}{#- skip = 위 칸에 합쳐진 칸(방송이 걸친 시간만큼 rowspan) -#}
|
||||||
|
<td class="lv-cell{% if cell.is_weekend %} is-weekend{% endif %}"{% if cell.rowspan > 1 %} rowspan="{{ cell.rowspan }}"{% endif %} data-drop data-day="{{ cell.iso }}" data-start="{{ slot.start }}">
|
||||||
|
{% if cell.cards %}<div class="lv-cards">{% endif %}{#- 카드가 합친 칸 높이를 채움(live.css) -#}
|
||||||
|
{% for c in cell.cards %}
|
||||||
|
<article class="lv-card" data-card="{{ c.id }}">
|
||||||
|
<header class="lv-card-head" draggable="true" style="background:{{ c.color }}" title="{{ c.host_name }} · {{ c.times }}{% if c.venue %} · {{ c.venue }}{% endif %}">
|
||||||
|
{% if c.platform %}<img class="lv-card-pf" src="/static/live-icon-{{ c.platform }}.png" alt="{{ {'tiktok': 'TikTok', 'shopee': 'Shopee'}[c.platform] }}" />{% endif %}
|
||||||
|
<span class="lv-card-name">{{ c.label }}{% if c.tiktok_handle %}<small>@{{ c.tiktok_handle }}</small>{% endif %}</span>
|
||||||
|
<button type="button" class="lv-card-edit" data-edit='{{ c.edit | tojson }}' aria-label="{{ t('{name} {date} {times} 고치기').format(name=c.label, date=c.date, times=c.times) }}">✎</button>
|
||||||
|
</header>
|
||||||
|
<div class="lv-card-nums">
|
||||||
|
<div><span>{{ t('판매금액') }}</span><b>{{ c.card_sales }}</b></div>
|
||||||
|
<div><span>{{ t('커미션') }} ({{ cal.commission_percent }}%)</span><b>{{ c.card_commission }}</b></div>
|
||||||
|
</div>
|
||||||
|
<footer class="lv-card-foot"><span>{{ t('비용') }}: <b>RM{{ c.card_fee }}</b></span>{% if c.images %}<a href="/live/images/{{ c.images[0].id }}" target="_blank" rel="noopener" title="{{ t('방송 결과 이미지') }}" data-preview="{{ c.label }} · {{ c.date }} {{ c.times }}{% if c.images | length > 1 %} · 1/{{ c.images | length }}{% endif %}" data-images='{{ c.images | map(attribute="id") | list | tojson }}' data-names='{{ c.images | map(attribute="filename") | list | tojson }}'>{{ t('이미지 {n}').format(n=c.images | length) }}</a>{% endif %}</footer>
|
||||||
|
</article>
|
||||||
|
{% endfor %}
|
||||||
|
{% if cell.cards %}</div>{% endif %}
|
||||||
|
{% if not cell.cards and hosts | selectattr('is_active') | list %}
|
||||||
|
<button type="button" class="lv-cell-add" data-new='{{ {"broadcast_date": cell.iso, "start_time": slot.start, "end_time": slot.end} | tojson }}' aria-label="{{ t('{date} {slot} 방송 추가').format(date=cell.iso, slot=slot.label) }}">+</button>
|
||||||
|
{% endif %}
|
||||||
|
</td>
|
||||||
|
{% endif %}{% endfor %}
|
||||||
|
</tr>
|
||||||
|
{% endfor %}
|
||||||
|
</tbody>
|
||||||
|
<tfoot>
|
||||||
|
<tr>
|
||||||
|
<th class="lv-cal-time" scope="row">{{ t('합계 & ROAS') }}</th>
|
||||||
|
{% for d in cal.days %}
|
||||||
|
<td>
|
||||||
|
<dl class="lv-total">
|
||||||
|
<div><dt>{{ t('총 판매금액') }}:</dt><dd class="is-sales">RM {{ d.sales_text }}</dd></div>
|
||||||
|
<div><dt>{{ t('광고비') }}:</dt><dd>RM {{ d.spend_text }}</dd></div>
|
||||||
|
<div><dt>{{ t('호스트 비용') }}:</dt><dd>RM {{ d.fee_text }}</dd></div>
|
||||||
|
<div><dt>ROAS:</dt><dd>{{ d.roas }}</dd></div>
|
||||||
|
</dl>
|
||||||
|
</td>
|
||||||
|
{% endfor %}
|
||||||
|
</tr>
|
||||||
|
</tfoot>
|
||||||
|
</table>
|
||||||
|
</div>
|
||||||
|
</section>
|
||||||
|
{#- 화면 오른쪽 위에 붙는 달력 — 날짜를 누르면 그 날이 표 맨 왼쪽(live.js), 말레이시아 공휴일(holidays.py) -#}
|
||||||
|
<div class="lv-side">
|
||||||
|
<aside class="lv-side-cal" id="lv-side-cal"></aside>
|
||||||
|
{#- 카드의 이미지 링크에 마우스를 올리면 달력 아래 빈 곳에 결과 이미지(live.js) -#}
|
||||||
|
<figure class="lv-preview" id="lv-preview" hidden><img alt="" /><figcaption></figcaption></figure>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
{% include "live/_dialog.html" %}
|
||||||
|
{#- 카드의 이미지 링크를 누르면 화면 가운데 원본 크기 이미지 — 회전(보기만)·다운로드(원본)·여러 장이면 앞뒤(live.js) -#}
|
||||||
|
<dialog class="lv-viewer" id="lv-viewer" aria-labelledby="lv-viewer-cap">
|
||||||
|
<div class="lv-viewer-bar">
|
||||||
|
<span class="lv-viewer-cap" id="lv-viewer-cap"></span>
|
||||||
|
<span class="lv-gap"></span>
|
||||||
|
<button type="button" class="erp-btn erp-btn-outline erp-btn-sm" data-step="-1" aria-label="{{ t('이전 이미지') }}">◀</button>
|
||||||
|
<span class="lv-viewer-count"></span>
|
||||||
|
<button type="button" class="erp-btn erp-btn-outline erp-btn-sm" data-step="1" aria-label="{{ t('다음 이미지') }}">▶</button>
|
||||||
|
<button type="button" class="erp-btn erp-btn-outline erp-btn-sm" data-rotate>↻ {{ t('회전') }}</button>
|
||||||
|
<a class="erp-btn erp-btn-outline erp-btn-sm" data-download download>{{ t('다운로드') }}</a>
|
||||||
|
<button type="button" class="erp-btn erp-btn-primary erp-btn-sm" data-viewer-close>{{ t('닫기') }}</button>
|
||||||
|
</div>
|
||||||
|
<div class="lv-viewer-body"><div class="lv-viewer-stage"><img alt="" /></div></div>
|
||||||
|
</dialog>
|
||||||
|
{% endblock %}
|
||||||
|
|
||||||
|
{% block scripts %}<script type="application/json" id="lv-my-holidays">{{ my_holidays | tojson }}</script>
|
||||||
|
<script type="application/json" id="lv-live-days">{{ live_days | tojson }}</script>
|
||||||
|
<script src="/static/erp-datepop.js?v=20261106a" defer></script>
|
||||||
|
{% include "live/_scripts.html" %}{% endblock %}
|
||||||
@@ -0,0 +1,44 @@
|
|||||||
|
{% extends "erp_base.html" %}
|
||||||
|
{#- 라이브 커머스 스케줄표(2026-11-04) — 달마다 방송 목록. 추가·고치기 창은 달력과 공용(_dialog.html, live.js). 문구 = t()(i18n.py). -#}
|
||||||
|
{% block head_extra %}<link rel="stylesheet" href="/static/live.css?v=20261106h" />{% endblock %}
|
||||||
|
|
||||||
|
{% block content %}
|
||||||
|
<section class="lv" lang="{{ lang }}">
|
||||||
|
{% include "live/_bar.html" %}
|
||||||
|
|
||||||
|
<div class="erp-card-block">
|
||||||
|
<div class="erp-table-wrap">
|
||||||
|
{% set platform_names = {"tiktok": "TikTok", "shopee": "Shopee"} %}
|
||||||
|
<table class="erp-table lv-table lv-sched">
|
||||||
|
<thead><tr><th>{{ t('쇼핑몰') }}</th><th>{{ t('날짜') }}</th><th>{{ t('시간') }}</th><th>{{ t('호스트') }}</th><th class="lv-r">{{ t('판매금액(RM)') }}</th><th class="lv-r">{{ t('시간 요금(RM)') }}</th><th class="lv-r">{{ t('커미션 10%(RM)') }}</th><th class="lv-r">{{ t('광고비(RM)') }}</th><th class="lv-r">{{ t('호스트 비용(RM)') }}</th><th>{{ t('방송 결과') }}</th><th></th></tr></thead>
|
||||||
|
<tbody>
|
||||||
|
{% for r in rows %}
|
||||||
|
<tr>
|
||||||
|
<td class="lv-c" data-label="{{ t('쇼핑몰') }}">{% if r.platform %}<img class="lv-pf" src="/static/live-icon-{{ r.platform }}.png" alt="{{ platform_names[r.platform] }}" title="{{ platform_names[r.platform] }}" />{% endif %}</td>
|
||||||
|
<td class="lv-nowrap" data-label="{{ t('날짜') }}">{{ r.date }}</td>
|
||||||
|
<td class="lv-nowrap" data-label="{{ t('시간') }}">{{ r.times }}</td>
|
||||||
|
<td data-label="{{ t('호스트') }}">{{ r.host_name }}{% if r.tiktok_handle %}<div class="lv-sub">@{{ r.tiktok_handle }}</div>{% endif %}</td>
|
||||||
|
<td class="lv-r lv-num" data-label="{{ t('판매금액(RM)') }}">{{ r.sales }}</td>
|
||||||
|
<td class="lv-r lv-num" data-label="{{ t('시간 요금(RM)') }}">{{ r.base }}</td>
|
||||||
|
<td class="lv-r lv-num" data-label="{{ t('커미션 10%(RM)') }}">{{ r.commission }}</td>
|
||||||
|
<td class="lv-r lv-num" data-label="{{ t('광고비(RM)') }}">{{ r.ad_spend }}</td>
|
||||||
|
<td class="lv-r lv-num" data-label="{{ t('호스트 비용(RM)') }}">{{ r.host_fee }}</td>
|
||||||
|
<td data-label="{{ t('방송 결과') }}"><div class="lv-thumbs">{% for im in r.images %}<a href="/live/images/{{ im.id }}" target="_blank" rel="noopener" title="{{ im.filename }}"><img src="/live/images/{{ im.id }}?thumb=1" alt="{{ im.filename }}" loading="lazy" /></a>{% endfor %}</div></td>
|
||||||
|
<td class="lv-actions">
|
||||||
|
<button type="button" class="erp-btn erp-btn-outline erp-btn-sm" data-edit='{{ r.edit | tojson }}'>{{ t('고치기') }}</button>
|
||||||
|
<button type="button" class="erp-btn erp-btn-outline erp-btn-sm" data-post="/live/broadcasts/{{ r.id }}/delete" data-confirm="{{ t('{date} {host} 방송을 지울까요? 결과 이미지도 함께 지워집니다.').format(date=r.date, host=r.host_name) }}">{{ t('지우기') }}</button>
|
||||||
|
</td>
|
||||||
|
</tr>
|
||||||
|
{% else %}
|
||||||
|
<tr><td colspan="11" class="erp-empty">{{ t('이 달에 등록한 방송이 없습니다.') }}</td></tr>
|
||||||
|
{% endfor %}
|
||||||
|
</tbody>
|
||||||
|
</table>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
</section>
|
||||||
|
|
||||||
|
{% include "live/_dialog.html" %}
|
||||||
|
{% endblock %}
|
||||||
|
|
||||||
|
{% block scripts %}{% include "live/_scripts.html" %}{% endblock %}
|
||||||
@@ -0,0 +1,90 @@
|
|||||||
|
{% extends "erp_base.html" %}
|
||||||
|
{#- 라이브 커머스 설정(2026-11-04) — 호스트 정보. 계좌 등 개인정보·지우기는 ERP 관리자만(router.settings), 칩 권한자는 이름·상태만 보임 — `live_host` = 새 등록, `live_host_edit` = 고치기(개인정보는 빈칸으로 열림, 비워 두면 그대로). 추가·고치기는 같은 창(live.js). 문구 = t()(i18n.py). -#}
|
||||||
|
{% block head_extra %}<link rel="stylesheet" href="/static/live.css?v=20261106h" />{% endblock %}
|
||||||
|
|
||||||
|
{% block content %}
|
||||||
|
{#- 쇼핑몰(005, store.PLATFORMS) — 로고는 말레이시아 배송 모듈 이미지 -#}
|
||||||
|
{% set platform_names = {"tiktok": "TikTok", "shopee": "Shopee"} %}
|
||||||
|
<section class="lv" lang="{{ lang }}">
|
||||||
|
<div class="lv-bar">
|
||||||
|
<a class="erp-btn erp-btn-outline" href="/live/">{{ t('◀ 스케줄표') }}</a>
|
||||||
|
<h2 class="lv-month">{{ t('호스트 설정') }}</h2>
|
||||||
|
<span class="lv-gap"></span>
|
||||||
|
{% include "live/_lang.html" %}
|
||||||
|
{% if can_add_host %}<button type="button" class="erp-btn erp-btn-primary" id="lv-add">{{ t('+ 호스트 등록') }}</button>{% endif %}
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<div class="erp-card-block">
|
||||||
|
<div class="erp-table-wrap">
|
||||||
|
<table class="erp-table lv-table">
|
||||||
|
<thead><tr><th>{{ t('쇼핑몰') }}</th><th>{{ t('간단한 이름') }}</th><th>{{ t('이름 (IC 기준)') }}</th>{% if is_admin %}<th>{{ t('전화번호') }}</th><th>{{ t('이메일') }}</th><th>{{ t('주소') }}</th><th>{{ t('은행명') }}</th><th>{{ t('계좌번호') }}</th>{% endif %}<th>{{ t('상태') }}</th>{% if can_edit_host %}<th></th>{% endif %}</tr></thead>
|
||||||
|
<tbody>
|
||||||
|
{% for h in hosts %}
|
||||||
|
<tr{% if not h.is_active %} class="lv-off"{% endif %}>
|
||||||
|
<td data-label="{{ t('쇼핑몰') }}">{% if h.platform %}<img class="lv-logo" src="/static/dispatch/courier/{{ h.platform }}.png" alt="{{ platform_names[h.platform] }}" title="{{ platform_names[h.platform] }}" />{% endif %}</td>
|
||||||
|
<td data-label="{{ t('간단한 이름') }}">{{ h.display_name }}</td>
|
||||||
|
<td data-label="{{ t('이름 (IC 기준)') }}">{{ h.full_name }}</td>
|
||||||
|
{% if is_admin %}
|
||||||
|
<td class="lv-nowrap" data-label="{{ t('전화번호') }}">{{ h.phone }}</td>
|
||||||
|
<td data-label="{{ t('이메일') }}">{{ h.email }}</td>
|
||||||
|
<td data-label="{{ t('주소') }}">{{ h.address }}</td>
|
||||||
|
<td data-label="{{ t('은행명') }}">{{ h.bank_name }}</td>
|
||||||
|
<td class="lv-nowrap" data-label="{{ t('계좌번호') }}">{{ h.bank_account }}</td>
|
||||||
|
{% endif %}
|
||||||
|
{% if can_edit_host %}
|
||||||
|
<td data-label="{{ t('상태') }}"><label class="erp-switch" title="{{ t('사용') }}"><input type="checkbox" data-active="/live/settings/hosts/{{ h.id }}/active" aria-label="{{ t('사용') }} — {{ h.display_name or h.full_name }}"{% if h.is_active %} checked{% endif %} /><span class="erp-switch-slider"></span></label></td>
|
||||||
|
{% else %}
|
||||||
|
<td class="lv-nowrap" data-label="{{ t('상태') }}">{{ t('사용') if h.is_active else t('사용 안 함') }}</td>
|
||||||
|
{% endif %}
|
||||||
|
{% if can_edit_host %}
|
||||||
|
<td class="lv-actions">
|
||||||
|
{% if is_admin %}
|
||||||
|
<button type="button" class="erp-btn erp-btn-outline erp-btn-sm" data-edit='{{ {"id": h.id, "platform": h.platform, "display_name": h.display_name, "full_name": h.full_name, "phone": h.phone, "email": h.email, "address": h.address, "bank_name": h.bank_name, "bank_account": h.bank_account, "is_active": h.is_active} | tojson }}'>{{ t('고치기') }}</button>
|
||||||
|
<button type="button" class="erp-btn erp-btn-outline erp-btn-sm" data-post="/live/settings/hosts/{{ h.id }}/delete" data-confirm="{{ t('{name} 호스트를 지울까요?').format(name=h.full_name) }}">{{ t('지우기') }}</button>
|
||||||
|
{% else %}
|
||||||
|
{#- 개인정보를 페이지에 싣지 않는다 -#}
|
||||||
|
<button type="button" class="erp-btn erp-btn-outline erp-btn-sm" data-edit='{{ {"id": h.id, "platform": h.platform, "display_name": h.display_name, "full_name": h.full_name, "is_active": h.is_active} | tojson }}'>{{ t('고치기') }}</button>
|
||||||
|
{% endif %}
|
||||||
|
</td>
|
||||||
|
{% endif %}
|
||||||
|
</tr>
|
||||||
|
{% else %}
|
||||||
|
<tr><td colspan="{{ 10 if is_admin else 5 if can_edit_host else 4 }}" class="erp-empty">{{ t('등록한 호스트가 없습니다.') }}</td></tr>
|
||||||
|
{% endfor %}
|
||||||
|
</tbody>
|
||||||
|
</table>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
</section>
|
||||||
|
|
||||||
|
<dialog class="lv-dlg" id="lv-dlg" aria-labelledby="lv-dlg-title">
|
||||||
|
<form id="lv-form" action="/live/settings/hosts">
|
||||||
|
<h3 id="lv-dlg-title" data-add="{{ t('호스트 등록') }}" data-edit="{{ t('호스트 고치기') }}"></h3>
|
||||||
|
<input type="hidden" name="id" />
|
||||||
|
<fieldset class="lv-platforms">
|
||||||
|
<legend>{{ t('쇼핑몰') }}</legend>
|
||||||
|
{% for p, name in platform_names.items() %}
|
||||||
|
<label class="lv-platform"><input type="radio" name="platform" value="{{ p }}" required /><img class="lv-logo" src="/static/dispatch/courier/{{ p }}.png" alt="{{ name }}" /></label>
|
||||||
|
{% endfor %}
|
||||||
|
</fieldset>
|
||||||
|
<label class="lv-field">{{ t('간단한 이름') }} <input class="erp-input" type="text" name="display_name" maxlength="50" required /></label>
|
||||||
|
<label class="lv-field">{{ t('이름 (IC 기준)') }} <input class="erp-input" type="text" name="full_name" maxlength="200" required /></label>
|
||||||
|
{% if not is_admin %}<p class="lv-sub" data-edit-only hidden>{{ t('개인정보는 보이지 않습니다. 비워 두면 그대로 유지됩니다.') }}</p>{% endif %}
|
||||||
|
<label class="lv-field">{{ t('전화번호') }} <input class="erp-input" type="tel" name="phone" maxlength="40" /></label>
|
||||||
|
<label class="lv-field">{{ t('이메일') }} <input class="erp-input" type="email" name="email" maxlength="254" /></label>
|
||||||
|
<label class="lv-field">{{ t('주소') }} <textarea class="erp-input" name="address" rows="2" maxlength="500"></textarea></label>
|
||||||
|
<div class="lv-row">
|
||||||
|
<label class="lv-field">{{ t('은행명') }} <input class="erp-input" type="text" name="bank_name" maxlength="100" /></label>
|
||||||
|
<label class="lv-field">{{ t('계좌번호') }} <input class="erp-input" type="text" name="bank_account" maxlength="40" inputmode="numeric" /></label>
|
||||||
|
</div>
|
||||||
|
{% if can_edit_host %}<label class="lv-check"><input type="checkbox" name="is_active" value="1" checked /> {{ t('사용 (끄면 새 방송에서 고를 수 없습니다)') }}</label>{% endif %}
|
||||||
|
<p class="lv-msg" data-msg role="alert" hidden></p>
|
||||||
|
<div class="lv-foot">
|
||||||
|
<button type="button" class="erp-btn erp-btn-outline" data-close>{{ t('취소') }}</button>
|
||||||
|
<button type="submit" class="erp-btn erp-btn-primary">{{ t('저장') }}</button>
|
||||||
|
</div>
|
||||||
|
</form>
|
||||||
|
</dialog>
|
||||||
|
{% endblock %}
|
||||||
|
|
||||||
|
{% block scripts %}{% include "live/_scripts.html" %}{% endblock %}
|
||||||
@@ -0,0 +1,9 @@
|
|||||||
|
# [말레이시아재고] 말레이시아 창고 재고관리 — `app/modules/malaysia/`, `malaysia_stock_db`
|
||||||
|
|
||||||
|
> 이 모듈만 고칠 때 읽는 요약. 상세는 같은 폴더 `README.md`.
|
||||||
|
> 정적 파일: `app/static/malaysia.js`, `malaysia_rack.js`, `malaysia_rack_view.js`. 템플릿: `templates/`.
|
||||||
|
> 상품은 `itemcode_db` 읽기 전용(`itemcode.py`). 세트 BOM 이 "누락"이면 `itemcode_ro` 의 `set_components` SELECT 권한부터 점검.
|
||||||
|
|
||||||
|
- 낱개(MT/MX/MZ) 입출고·조정, 세트(MY) BOM, 일일 재고조사(세트 → 낱개 자동 분해), 현재고 현황.
|
||||||
|
- 뚜껑(MD-)은 재고 집계 제외 — 단, 창고 랙에는 위치 확인용으로 배치 가능(`store.LID_ITEMS`).
|
||||||
|
- 권한키 `malaysia`.
|
||||||
@@ -90,11 +90,11 @@ def _render_config_needed(request: Request, user: dict[str, Any]) -> HTMLRespons
|
|||||||
def _guard(request: Request) -> tuple[Any, dict[str, Any]] | HTMLResponse | RedirectResponse:
|
def _guard(request: Request) -> tuple[Any, dict[str, Any]] | HTMLResponse | RedirectResponse:
|
||||||
"""로그인+권한+store 점검. 페이지 핸들러 진입부에서 사용."""
|
"""로그인+권한+store 점검. 페이지 핸들러 진입부에서 사용."""
|
||||||
from app.main import get_current_user_record, render_template # noqa: WPS433
|
from app.main import get_current_user_record, render_template # noqa: WPS433
|
||||||
from app.store import has_module, is_admin # noqa: WPS433
|
from app.store import has_module, is_admin, login_redirect # noqa: WPS433
|
||||||
|
|
||||||
user = get_current_user_record(request)
|
user = get_current_user_record(request)
|
||||||
if user is None:
|
if user is None:
|
||||||
return RedirectResponse(url="/login", status_code=303)
|
return login_redirect(request)
|
||||||
if not has_module(user, "malaysia"):
|
if not has_module(user, "malaysia"):
|
||||||
return render_template(
|
return render_template(
|
||||||
request,
|
request,
|
||||||
|
|||||||
@@ -0,0 +1,11 @@
|
|||||||
|
# [공지] 긴급 공지 모듈 — `app/modules/notice/`, `project_db`(마이그레이션 024 `urgent_notice*`)
|
||||||
|
|
||||||
|
> 이 모듈만 고칠 때 읽는 요약. 상세는 `docs/NOTICE_MODULE.md`.
|
||||||
|
> 정적 파일: `app/static/erp-notice.js`, `erp-notice.css`, `erp-notice-admin.js`.
|
||||||
|
|
||||||
|
- 수퍼관리자만 작성(`/notice/`, 진입 = ERP 왼쪽 아래 · Project ⚙ 옵션).
|
||||||
|
- 제목·내용(이미지 bytea)·띄울 시각·전체/고른 사람.
|
||||||
|
- ERP 모든 화면(`erp_base.html`·`main.html`·`admin.html` 의 `static/erp-notice.js`) 가로·세로 정가운데에
|
||||||
|
[확인] 누를 때까지 표시(Esc·바깥 클릭 무시), 확인 기록.
|
||||||
|
- 연결 풀은 `ProjectStore.pool` 공유(→ Project 모듈 DB 변경 시 영향 확인), 새 환경변수 없음.
|
||||||
|
- PC 알림 프로그램은 아직 미지원.
|
||||||
@@ -0,0 +1,23 @@
|
|||||||
|
"""긴급 공지 — ERP 전체 화면 가운데에 띄우는 공지(2026-10-12).
|
||||||
|
|
||||||
|
- 라우터: `router.py` (prefix=/notice) — 만들기·고치기는 수퍼관리자만, 받기·[확인]은 로그인 사용자 누구나
|
||||||
|
- 저장소: `db.py` (project_db 마이그레이션 024 의 urgent_notice* 표 — 프로젝트 저장소의 연결 풀을 같이 쓴다)
|
||||||
|
- 검증: `store.py`
|
||||||
|
- 화면: 관리 `templates/notice/admin.html` + `static/erp-notice-admin.js`, 표시 `static/erp-notice.js`(erp_base.html 공용)
|
||||||
|
상세는 docs/NOTICE_MODULE.md.
|
||||||
|
"""
|
||||||
|
|
||||||
|
from typing import Any
|
||||||
|
|
||||||
|
from .router import router
|
||||||
|
|
||||||
|
__all__ = ["router", "build_notice_store"]
|
||||||
|
|
||||||
|
|
||||||
|
def build_notice_store(project_store: Any) -> Any:
|
||||||
|
"""프로젝트 저장소(PROJECT_DB_URL)가 있으면 그 연결 풀로 NoticeStore, 없으면 None(공지 API 는 503)."""
|
||||||
|
if project_store is None:
|
||||||
|
return None
|
||||||
|
from .db import NoticeStore # noqa: WPS433
|
||||||
|
|
||||||
|
return NoticeStore(project_store.pool)
|
||||||
@@ -0,0 +1,238 @@
|
|||||||
|
"""긴급 공지 저장소 — project_db(마이그레이션 024)의 urgent_notice* 표. 연결 풀은 프로젝트 저장소와 같이 쓴다."""
|
||||||
|
|
||||||
|
from __future__ import annotations
|
||||||
|
|
||||||
|
from datetime import datetime, timezone
|
||||||
|
from typing import Any
|
||||||
|
|
||||||
|
from psycopg import errors as psycopg_errors
|
||||||
|
|
||||||
|
from app.modules.project import store as pj_store
|
||||||
|
from app.timezone import KST
|
||||||
|
|
||||||
|
from . import store
|
||||||
|
|
||||||
|
|
||||||
|
def _iso(v: Any) -> str:
|
||||||
|
return v.astimezone(KST).isoformat(timespec="minutes") if isinstance(v, datetime) else ""
|
||||||
|
|
||||||
|
|
||||||
|
def _version(v: Any) -> str:
|
||||||
|
"""공지 내용 버전 = updated_at(마이크로초까지, UTC) — 고치기·취소 때마다 바뀐다. 받는 사람 화면이 바뀐 내용을 다시 그리고,
|
||||||
|
[확인]이 어느 내용을 읽고 누른 것인지 서버가 가린다(2026-10-15 검토 F07)."""
|
||||||
|
return v.astimezone(timezone.utc).strftime("%Y%m%d%H%M%S%f") if isinstance(v, datetime) else ""
|
||||||
|
|
||||||
|
|
||||||
|
class NoticeStore:
|
||||||
|
def __init__(self, pool: Any) -> None:
|
||||||
|
self._pool = pool
|
||||||
|
|
||||||
|
def _conn(self) -> Any:
|
||||||
|
return self._pool.connection()
|
||||||
|
|
||||||
|
@staticmethod
|
||||||
|
def _run(fn: Any) -> Any:
|
||||||
|
try:
|
||||||
|
return fn()
|
||||||
|
except psycopg_errors.UndefinedTable:
|
||||||
|
raise store.NoticeMigrationNeeded()
|
||||||
|
|
||||||
|
# ── 읽기 ────────────────────────────────────────────────
|
||||||
|
@staticmethod
|
||||||
|
def _row(r: dict[str, Any]) -> dict[str, Any]:
|
||||||
|
return {
|
||||||
|
"id": int(r["id"]), "title": r["title"], "body_html": r["body_html"],
|
||||||
|
"show_at": _iso(r["show_at"]), "to_all": bool(r["to_all"]),
|
||||||
|
"created_by": r["created_by"], "created_at": _iso(r["created_at"]),
|
||||||
|
"updated_by": r.get("updated_by") or "", "updated_at": _iso(r.get("updated_at")),
|
||||||
|
"version": _version(r.get("updated_at")),
|
||||||
|
"cancelled_at": _iso(r.get("cancelled_at")), "cancelled_by": r.get("cancelled_by") or "",
|
||||||
|
}
|
||||||
|
|
||||||
|
def list_notices(self, *, limit: int = 200) -> list[dict[str, Any]]:
|
||||||
|
"""관리 화면 — 최근 것부터. 받는 사람·확인한 사람 목록을 함께."""
|
||||||
|
def run() -> list[dict[str, Any]]:
|
||||||
|
with self._conn() as conn:
|
||||||
|
rows = conn.execute("SELECT * FROM urgent_notices ORDER BY show_at DESC, id DESC LIMIT %s",
|
||||||
|
(int(limit),)).fetchall()
|
||||||
|
ids = [int(r["id"]) for r in rows]
|
||||||
|
targets: dict[int, list[str]] = {i: [] for i in ids}
|
||||||
|
acks: dict[int, dict[str, str]] = {i: {} for i in ids}
|
||||||
|
if ids:
|
||||||
|
for t in conn.execute("SELECT notice_id, user_email FROM urgent_notice_targets "
|
||||||
|
"WHERE notice_id = ANY(%s) ORDER BY user_email", (ids,)).fetchall():
|
||||||
|
targets[int(t["notice_id"])].append(t["user_email"])
|
||||||
|
for a in conn.execute("SELECT notice_id, user_email, acked_at FROM urgent_notice_acks "
|
||||||
|
"WHERE notice_id = ANY(%s) ORDER BY acked_at", (ids,)).fetchall():
|
||||||
|
acks[int(a["notice_id"])][a["user_email"]] = _iso(a["acked_at"])
|
||||||
|
return [{**self._row(r), "targets": targets[int(r["id"])], "acks": acks[int(r["id"])]} for r in rows]
|
||||||
|
return self._run(run)
|
||||||
|
|
||||||
|
def pending_for(self, *, email: str, now: datetime | None = None) -> list[dict[str, Any]]:
|
||||||
|
"""이 사람이 지금 봐야 할 공지 — 취소 안 됨·띄울 시각이 지남·받는 사람(전체 또는 지정)·아직 [확인] 안 함. 오래된 것부터."""
|
||||||
|
em = pj_store.norm_str(email, lower=True)
|
||||||
|
|
||||||
|
def run() -> list[dict[str, Any]]:
|
||||||
|
with self._conn() as conn:
|
||||||
|
rows = conn.execute(
|
||||||
|
"SELECT n.* FROM urgent_notices n "
|
||||||
|
"WHERE n.cancelled_at IS NULL AND n.show_at <= %s "
|
||||||
|
" AND (n.to_all OR EXISTS (SELECT 1 FROM urgent_notice_targets t "
|
||||||
|
" WHERE t.notice_id = n.id AND t.user_email = %s)) "
|
||||||
|
" AND NOT EXISTS (SELECT 1 FROM urgent_notice_acks a WHERE a.notice_id = n.id AND a.user_email = %s) "
|
||||||
|
"ORDER BY n.show_at ASC, n.id ASC LIMIT 20",
|
||||||
|
(now or datetime.now(KST), em, em),
|
||||||
|
).fetchall()
|
||||||
|
return [self._row(r) for r in rows]
|
||||||
|
return self._run(run)
|
||||||
|
|
||||||
|
def get_notice(self, *, notice_id: int) -> dict[str, Any] | None:
|
||||||
|
def run() -> dict[str, Any] | None:
|
||||||
|
with self._conn() as conn:
|
||||||
|
r = conn.execute("SELECT * FROM urgent_notices WHERE id = %s", (notice_id,)).fetchone()
|
||||||
|
if r is None:
|
||||||
|
return None
|
||||||
|
t = [x["user_email"] for x in conn.execute(
|
||||||
|
"SELECT user_email FROM urgent_notice_targets WHERE notice_id = %s ORDER BY user_email",
|
||||||
|
(notice_id,)).fetchall()]
|
||||||
|
return {**self._row(r), "targets": t}
|
||||||
|
return self._run(run)
|
||||||
|
|
||||||
|
def is_recipient(self, *, notice: dict[str, Any], email: str) -> bool:
|
||||||
|
em = pj_store.norm_str(email, lower=True)
|
||||||
|
return bool(notice["to_all"]) or em in notice.get("targets", [])
|
||||||
|
|
||||||
|
# ── 쓰기 ────────────────────────────────────────────────
|
||||||
|
def _link_images(self, conn: Any, notice_id: int, body: str, by: str) -> None:
|
||||||
|
"""본문에 든 이미지를 이 공지에 묶는다 — 내가 올린, 아직 어느 공지에도 안 묶인 이미지만(남의 공지 이미지 가로채기 방지)."""
|
||||||
|
ids = store.image_ids_in(body)
|
||||||
|
if ids:
|
||||||
|
conn.execute("UPDATE urgent_notice_images SET notice_id = %s "
|
||||||
|
"WHERE id = ANY(%s) AND notice_id IS NULL AND uploaded_by = %s", (notice_id, ids, by))
|
||||||
|
# 하루 넘게 어느 공지에도 안 묶인 이미지(올렸다가 저장 안 함)는 정리
|
||||||
|
conn.execute("DELETE FROM urgent_notice_images WHERE notice_id IS NULL AND created_at < now() - interval '1 day'")
|
||||||
|
|
||||||
|
def create_notice(self, *, title: Any, body: Any, show_at: Any, to_all: Any, targets: Any, by: str) -> dict[str, Any]:
|
||||||
|
ttl = store.validate_title(title)
|
||||||
|
html = store.sanitize_body(body)
|
||||||
|
when = store.parse_show_at(show_at)
|
||||||
|
all_, emails = store.validate_targets(to_all, targets)
|
||||||
|
who = pj_store.norm_str(by, lower=True)
|
||||||
|
|
||||||
|
def run() -> int:
|
||||||
|
with self._conn() as conn:
|
||||||
|
with conn.transaction():
|
||||||
|
nid = int(conn.execute(
|
||||||
|
"INSERT INTO urgent_notices (title, body_html, show_at, to_all, created_by, updated_by) "
|
||||||
|
"VALUES (%s,%s,%s,%s,%s,%s) RETURNING id", (ttl, html, when, all_, who, who),
|
||||||
|
).fetchone()["id"])
|
||||||
|
for em in emails:
|
||||||
|
conn.execute("INSERT INTO urgent_notice_targets (notice_id, user_email) VALUES (%s,%s) "
|
||||||
|
"ON CONFLICT DO NOTHING", (nid, em))
|
||||||
|
self._link_images(conn, nid, html, who)
|
||||||
|
return nid
|
||||||
|
return self.get_notice(notice_id=self._run(run)) # type: ignore[return-value]
|
||||||
|
|
||||||
|
def update_notice(self, *, notice_id: int, title: Any, body: Any, show_at: Any, to_all: Any, targets: Any,
|
||||||
|
by: str, reshow: bool = False) -> dict[str, Any]:
|
||||||
|
"""고치기 — 받는 사람·시각·내용 전부. reshow=True 면 이미 [확인]한 사람에게도 다시 띄운다(확인 기록 지움)."""
|
||||||
|
ttl = store.validate_title(title)
|
||||||
|
html = store.sanitize_body(body)
|
||||||
|
when = store.parse_show_at(show_at)
|
||||||
|
all_, emails = store.validate_targets(to_all, targets)
|
||||||
|
who = pj_store.norm_str(by, lower=True)
|
||||||
|
|
||||||
|
def run() -> None:
|
||||||
|
with self._conn() as conn:
|
||||||
|
with conn.transaction():
|
||||||
|
row = conn.execute("UPDATE urgent_notices SET title=%s, body_html=%s, show_at=%s, to_all=%s, "
|
||||||
|
"updated_by=%s, updated_at=now() WHERE id=%s RETURNING id",
|
||||||
|
(ttl, html, when, all_, who, notice_id)).fetchone()
|
||||||
|
if row is None:
|
||||||
|
raise KeyError(notice_id)
|
||||||
|
conn.execute("DELETE FROM urgent_notice_targets WHERE notice_id = %s", (notice_id,))
|
||||||
|
for em in emails:
|
||||||
|
conn.execute("INSERT INTO urgent_notice_targets (notice_id, user_email) VALUES (%s,%s) "
|
||||||
|
"ON CONFLICT DO NOTHING", (notice_id, em))
|
||||||
|
if reshow:
|
||||||
|
conn.execute("DELETE FROM urgent_notice_acks WHERE notice_id = %s", (notice_id,))
|
||||||
|
self._link_images(conn, notice_id, html, who)
|
||||||
|
self._run(run)
|
||||||
|
return self.get_notice(notice_id=notice_id) # type: ignore[return-value]
|
||||||
|
|
||||||
|
def cancel_notice(self, *, notice_id: int, by: str, cancel: bool = True) -> dict[str, Any]:
|
||||||
|
"""취소(더 띄우지 않음) · 취소 되돌리기. 기록은 남는다."""
|
||||||
|
def run() -> None:
|
||||||
|
with self._conn() as conn:
|
||||||
|
row = conn.execute(
|
||||||
|
"UPDATE urgent_notices SET cancelled_at = CASE WHEN %s THEN now() ELSE NULL END, "
|
||||||
|
"cancelled_by = CASE WHEN %s THEN %s ELSE '' END, updated_at = now() WHERE id = %s RETURNING id",
|
||||||
|
(cancel, cancel, pj_store.norm_str(by, lower=True), notice_id),
|
||||||
|
).fetchone()
|
||||||
|
if row is None:
|
||||||
|
raise KeyError(notice_id)
|
||||||
|
self._run(run)
|
||||||
|
return self.get_notice(notice_id=notice_id) # type: ignore[return-value]
|
||||||
|
|
||||||
|
def ack(self, *, notice_id: int, email: str, version: str | None = None, now: datetime | None = None) -> str:
|
||||||
|
"""[확인] — 결과: "acked"(처음) · "already"(이미 확인 — 여러 번 눌러도 한 번) · "stale"(그 사이 내용이 바뀜 — 읽은
|
||||||
|
version 이 지금과 다름) · "denied"(받는 사람이 아님·띄울 시각 전·취소·없음).
|
||||||
|
|
||||||
|
받는 사람·표시 시각·취소 확인과 기록이 **한 트랜잭션**(2026-10-15 검토 F08): 공지 행을 FOR SHARE 로 잠그고 조건을 본 뒤
|
||||||
|
기록한다 — 동시에 취소·고치기가 들어오면 그 쪽이 먼저 끝나거나(그러면 바뀐 행으로 다시 판정) 이 기록 뒤로 기다린다.
|
||||||
|
version 이 없으면(예전 화면) 내용 확인은 건너뛴다."""
|
||||||
|
em = pj_store.norm_str(email, lower=True)
|
||||||
|
|
||||||
|
def run() -> str:
|
||||||
|
with self._conn() as conn:
|
||||||
|
with conn.transaction():
|
||||||
|
n = conn.execute(
|
||||||
|
"SELECT n.id, n.updated_at FROM urgent_notices n "
|
||||||
|
"WHERE n.id = %s AND n.cancelled_at IS NULL AND n.show_at <= %s "
|
||||||
|
" AND (n.to_all OR EXISTS (SELECT 1 FROM urgent_notice_targets t "
|
||||||
|
" WHERE t.notice_id = n.id AND t.user_email = %s)) "
|
||||||
|
"FOR SHARE OF n",
|
||||||
|
(notice_id, now or datetime.now(KST), em),
|
||||||
|
).fetchone()
|
||||||
|
if n is None:
|
||||||
|
return "denied"
|
||||||
|
done = conn.execute("SELECT 1 FROM urgent_notice_acks WHERE notice_id = %s AND user_email = %s",
|
||||||
|
(notice_id, em)).fetchone()
|
||||||
|
if done is not None:
|
||||||
|
return "already"
|
||||||
|
if version and version != _version(n["updated_at"]):
|
||||||
|
return "stale"
|
||||||
|
r = conn.execute("INSERT INTO urgent_notice_acks (notice_id, user_email) VALUES (%s,%s) "
|
||||||
|
"ON CONFLICT DO NOTHING RETURNING notice_id", (notice_id, em)).fetchone()
|
||||||
|
return "acked" if r is not None else "already"
|
||||||
|
return self._run(run)
|
||||||
|
|
||||||
|
# ── 이미지 ──────────────────────────────────────────────
|
||||||
|
def add_image(self, *, data: bytes, filename: str, by: str) -> dict[str, Any]:
|
||||||
|
ctype = store.sniff_image(data)
|
||||||
|
|
||||||
|
def run() -> int:
|
||||||
|
with self._conn() as conn:
|
||||||
|
return int(conn.execute(
|
||||||
|
"INSERT INTO urgent_notice_images (filename, content_type, size_bytes, data, uploaded_by) "
|
||||||
|
"VALUES (%s,%s,%s,%s,%s) RETURNING id",
|
||||||
|
(pj_store.norm_str(filename)[:200], ctype, len(data), data, pj_store.norm_str(by, lower=True)),
|
||||||
|
).fetchone()["id"])
|
||||||
|
iid = self._run(run)
|
||||||
|
return {"id": iid, "url": f"/notice/images/{iid}", "content_type": ctype}
|
||||||
|
|
||||||
|
def get_image(self, *, image_id: int) -> dict[str, Any] | None:
|
||||||
|
def run() -> dict[str, Any] | None:
|
||||||
|
with self._conn() as conn:
|
||||||
|
r = conn.execute("SELECT id, notice_id, content_type, data, uploaded_by FROM urgent_notice_images "
|
||||||
|
"WHERE id = %s", (image_id,)).fetchone()
|
||||||
|
return dict(r) if r else None
|
||||||
|
return self._run(run)
|
||||||
|
|
||||||
|
def enabled(self) -> bool:
|
||||||
|
try:
|
||||||
|
with self._conn() as conn:
|
||||||
|
return bool(conn.execute("SELECT to_regclass('public.urgent_notices') AS r").fetchone()["r"])
|
||||||
|
except Exception: # noqa: BLE001
|
||||||
|
return False
|
||||||
|
|
||||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user