main.py 20 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731
  1. import xml.etree.ElementTree as ET
  2. from typing import Union
  3. from fastapi import FastAPI
  4. import os
  5. import uuid
  6. import re
  7. import zipfile
  8. import json
  9. from fastapi.middleware.cors import CORSMiddleware
  10. from fastapi.middleware.gzip import GZipMiddleware
  11. import base64
  12. from pydantic import BaseModel
  13. from subdir import service
  14. from subdir import db
  15. from subdir import util
  16. import xml.dom.minidom as MD
  17. import numpy as np
  18. from fastapi.staticfiles import StaticFiles
  19. from pymongo import AsyncMongoClient
  20. client = AsyncMongoClient()
  21. from fastapi.responses import FileResponse
  22. from fastapi_cache import FastAPICache
  23. from inmemory import InMemoryBackend
  24. from fastapi_cache.decorator import cache
  25. from contextlib import asynccontextmanager
  26. from fastapi import WebSocket, WebSocketDisconnect
  27. from fastapi import UploadFile
  28. from collections.abc import AsyncIterator
  29. class ConnectionManager:
  30. """Class defining socket events"""
  31. def __init__(self):
  32. """init method, keeping track of connections"""
  33. self.active_connections = []
  34. async def connect(self, websocket: WebSocket):
  35. """connect event"""
  36. await websocket.accept()
  37. self.active_connections.append(websocket)
  38. async def send_personal_message(self, message: str, websocket: WebSocket):
  39. """Direct Message"""
  40. await websocket.send_text(message)
  41. def disconnect(self, websocket: WebSocket):
  42. """disconnect event"""
  43. self.active_connections.remove(websocket)
  44. @asynccontextmanager
  45. async def lifespan(_: FastAPI) -> AsyncIterator[None]:
  46. FastAPICache.init(InMemoryBackend(), prefix="default")
  47. yield
  48. app = FastAPI(lifespan=lifespan)
  49. origins = [
  50. "http://localhost.tiangolo.com",
  51. "https://localhost.tiangolo.com",
  52. "http://localhost",
  53. "http://localhost:9002",
  54. "http://127.0.0.1:9002",
  55. ]
  56. app.add_middleware(
  57. CORSMiddleware,
  58. allow_origins=["*"],
  59. allow_credentials=True,
  60. allow_methods=["*"],
  61. allow_headers=["*"],
  62. )
  63. ##app.add_middleware(GZipMiddleware, minimum_size=1000, compresslevel=5)
  64. ##app.mount("/static", StaticFiles(directory="front/dist"), name="static")
  65. ##manager = ConnectionManager()
  66. class Info(BaseModel):
  67. name: str
  68. class DingeshuRequest(BaseModel):
  69. value: int
  70. class DingeXilieRequest(BaseModel):
  71. value: int
  72. id: str
  73. class SingleDingeXilieRequest(BaseModel):
  74. zhuanye: int
  75. debh: str
  76. class InfoWithID(BaseModel):
  77. name: str
  78. id: str
  79. class Tiaojia(BaseModel):
  80. biao_id: str
  81. bh: str
  82. bm: str
  83. mingcheng: str
  84. danwei: str
  85. jiage: str
  86. glf: str
  87. lr: str
  88. bz: int
  89. class SearchDe(BaseModel):
  90. zhuanye: str
  91. text: str
  92. class UpdateZjcs(BaseModel):
  93. biao_id: str
  94. bh: str
  95. mc: str
  96. fl: str
  97. @app.post("/outline2")
  98. async def read_root2(info: Info):
  99. return await db.getOutline(client, info.name)
  100. @app.post("/detail2")
  101. async def read_detail2(info: Info):
  102. return await db.getDetail(client, info.name)
  103. @app.post("/baojiahuizong2/")
  104. async def read_bjhz2(info: InfoWithID):
  105. raw = await db.getBjhz(client, info.name, info.id)
  106. raw2 = []
  107. for entry in raw:
  108. if "__children" in entry:
  109. entry["_children"] = entry["__children"]
  110. for grandchild in entry["_children"]:
  111. if "__children" in grandchild:
  112. grandchild['_children'] = grandchild['__children']
  113. del grandchild['__children']
  114. del entry["__children"]
  115. raw2.append(entry)
  116. return raw2
  117. @app.post("/guifeishuijin2/")
  118. async def read_gfsj2(info: InfoWithID):
  119. raw = await db.getGfsj(client, info.name, info.id)
  120. raw2 = []
  121. for entry in raw:
  122. if "__children" in entry:
  123. entry["_children"] = entry["__children"]
  124. del entry["__children"]
  125. raw2.append(entry)
  126. return raw2
  127. @app.post("/qitaxiangmu2/")
  128. async def read_qtxm2(info: InfoWithID):
  129. raw = await db.getQtxm(client, info.name, info.id)
  130. raw2 = []
  131. for entry in raw:
  132. if "__children" in entry:
  133. entry["_children"] = entry["__children"]
  134. del entry["__children"]
  135. raw2.append(entry)
  136. return raw2
  137. @app.post("/zygczgj/")
  138. async def zygczgj(info: InfoWithID):
  139. return await db.getZygczgj(client, info.name, info.id)
  140. @app.post("/zanliejine2/")
  141. async def read_zlje2(info: InfoWithID):
  142. return await db.getZlje(client, info.name, info.id)
  143. @app.post("/jirigong2/")
  144. async def read_jrg2(info: InfoWithID):
  145. return await db.getJrg(client, info.name, info.id)
  146. @app.post("/zongchengbaofuwufei2/")
  147. async def read_zcbfwf2(info: InfoWithID):
  148. return await db.getZcbfwf(client, info.name, info.id)
  149. @app.post("/fabaorengongyingcailiao2/")
  150. async def read_fbrgycl2(info: InfoWithID):
  151. return await db.getFbrgycl(client, info.name, info.id)
  152. @app.post("/rencaijihuizong2/")
  153. async def read_rcjhz2(info: InfoWithID):
  154. return await db.getRcjhz(client, info.name, info.id)
  155. @app.post("/qingdanxiangmu2/")
  156. async def read_qdxm2(info: InfoWithID):
  157. return await db.getQdxm(client, info.name, info.id)
  158. class Item(BaseModel):
  159. bh: str
  160. bt: str
  161. name: str
  162. class Rcj(BaseModel):
  163. bh: str
  164. bt: str
  165. bm: str
  166. name: str
  167. class Dercj(BaseModel):
  168. bh: str
  169. bt: str
  170. qdbm: str
  171. debm: str
  172. name: str
  173. class Zjcs(BaseModel):
  174. bh: str
  175. name: str
  176. @app.post("/qingdanmingxi/")
  177. async def read_qdmx(item : Item):
  178. return await db.getQdmx(client, item.name, item.bh, item.bt)
  179. @app.post("/qingdanrcj/")
  180. async def read_rcj(item : Rcj):
  181. if item.bt == "Djcs":
  182. return await db.getDjcsQingdanrcj(client, item.name, item.bh, item.bt, item.bm)
  183. return await db.getQingdanrcj(client, item.name, item.bh, item.bt, item.bm)
  184. @app.get("/qingdantuijian/{bm}")
  185. @cache(expire=86400)
  186. async def read_tuijian(bm: str):
  187. return service.getQingdanTuijian("", "", bm)
  188. @app.post("/dingercj/")
  189. async def read_dercj(item : Dercj):
  190. if item.bt == "Djcs":
  191. return await db.getDjcsDingercj(client, item.name, item.bh, item.bt, item.qdbm, item.debm)
  192. return await db.getDingercj(client, item.name, item.bh, item.bt, item.qdbm, item.debm)
  193. @app.post("/zjcs/")
  194. async def read_zjcs(item : Zjcs):
  195. raw = await db.getZjcs(client, item.name, item.bh)
  196. raw2 = []
  197. for entry in raw:
  198. if "__children" in entry:
  199. entry["_children"] = entry["__children"]
  200. del entry["__children"]
  201. raw2.append(entry)
  202. return raw2
  203. @app.post("/djcs/")
  204. async def read_djcs(item : Zjcs):
  205. raw = await db.getDjcs(client, item.name, item.bh)
  206. raw2 = []
  207. for entry in raw:
  208. if "__children" in entry:
  209. entry["_children"] = entry["__children"]
  210. del entry["__children"]
  211. raw2.append(entry)
  212. return raw2
  213. @app.post("/files2/")
  214. async def read_files2():
  215. result = await db.list_files(client)
  216. return result
  217. @app.post("/deleteFile/")
  218. async def delete(r: Info):
  219. result = await db.delete_files(client, r.name)
  220. return result
  221. @app.get("/des/{value}")
  222. @cache(expire=86400)
  223. async def read_des(value: int):
  224. result = service.getDes(value)
  225. if value == 30:
  226. result.append({
  227. "id": "2075",
  228. "key" : "2075",
  229. "value" : "2075",
  230. "label" : "安装费用",
  231. "title" : "安装费用",
  232. "children" : [
  233. {
  234. "id": "2076",
  235. "key" : "2076",
  236. "value" : "2076",
  237. "label" : "脚手架搭拆费",
  238. "title" : "脚手架搭拆费",
  239. "children" : []
  240. },
  241. {
  242. "id": "2077",
  243. "key" : "2077",
  244. "value" : "2077",
  245. "label" : "施工超高增加费",
  246. "title" : "施工超高增加费",
  247. "children" : []
  248. },
  249. {
  250. "id": "2078",
  251. "key" : "2078",
  252. "value" : "2078",
  253. "label" : "安装生产同时增加费",
  254. "title" : "安装生产同时增加费",
  255. "children" : []
  256. },
  257. {
  258. "id": "2079",
  259. "key" : "2079",
  260. "value" : "2079",
  261. "label" : "有害环境操作增加费",
  262. "title" : "有害环境操作增加费",
  263. "children" : []
  264. },
  265. {
  266. "id": "2080",
  267. "key" : "2080",
  268. "value" : "2080",
  269. "label" : "高层建筑增加费",
  270. "title" : "高层建筑增加费",
  271. "children" : [
  272. {
  273. "id": "2081",
  274. "key" : "2081",
  275. "value" : "2081",
  276. "label" : "第四册",
  277. "title" : "第四册",
  278. "children" : []
  279. },
  280. {
  281. "id": "2082",
  282. "key" : "2082",
  283. "value" : "2082",
  284. "label" : "第五册",
  285. "title" : "第五册",
  286. "children" : []
  287. },
  288. {
  289. "id": "2083",
  290. "key" : "2083",
  291. "value" : "2083",
  292. "label" : "第七册",
  293. "title" : "第七册",
  294. "children" : []
  295. },
  296. {
  297. "id": "2084",
  298. "key" : "2084",
  299. "value" : "2084",
  300. "label" : "第九册",
  301. "title" : "第九册",
  302. "children" : []
  303. },
  304. {
  305. "id": "2085",
  306. "key" : "2085",
  307. "value" : "2085",
  308. "label" : "第十册",
  309. "title" : "第十册",
  310. "children" : []
  311. },
  312. {
  313. "id": "2086",
  314. "key" : "2086",
  315. "value" : "2086",
  316. "label" : "第十一册",
  317. "title" : "第十一册",
  318. "children" : []
  319. },
  320. ]
  321. },
  322. {
  323. "id": "2087",
  324. "key" : "2087",
  325. "value" : "2087",
  326. "label" : "系统调试费",
  327. "title" : "系统调试费",
  328. "children" : []
  329. },
  330. ]
  331. })
  332. return result
  333. @app.get("/pbs/{value}")
  334. @cache(expire=86400)
  335. async def read_pbs(value:int):
  336. result = service.getPbs(value)
  337. #print(result)
  338. result.insert(0, {"id": "0","key": "0", "label": "全部", "title": "全部"})
  339. return result
  340. @app.get("/pbxl/{name}")
  341. @cache(expire=86400)
  342. async def read_pbxl(name: str):
  343. result = service.getPbxl(name)
  344. #print(result)
  345. return result
  346. @app.get("/cankao/")
  347. @cache(expire=86400)
  348. async def cankao():
  349. result = service.getCankao()
  350. #print(result)
  351. return result
  352. @app.post("/qufei/")
  353. async def read_qufei(r: Info):
  354. return await db.getQufei(client, r.name)
  355. @app.post("/jiagongcai/")
  356. async def read_jiagongcai(r: Info):
  357. return await db.getJiagongcai(client, r.name)
  358. @app.get("/dexilie/{value}/{id}")
  359. @cache(expire=86400)
  360. async def read_dexilie(value: int, id: str):
  361. if value == 30 and int(id) > 2074:
  362. return service.getDeXilie_azfy(value, id)
  363. result = service.getDeXilie(value, id)
  364. #print(result)
  365. return result
  366. @app.get("/singledexilie/{zhuanye}/{debh}")
  367. @cache(expire=86400)
  368. async def read_singledexilie(zhuanye: int, debh: str):
  369. if debh.startswith("D") :
  370. return json.dumps({
  371. "reverse": "None",
  372. "rgde": None,
  373. "jxde": None,
  374. "clde": None,
  375. "actual_zhuanye": zhuanye,
  376. "bz_selected": {"BZBH": {}},
  377. "bz_selected2": {"BZBH": {}}
  378. }, ensure_ascii=False)
  379. if "-F" in debh:
  380. return service.read_singledexilie_azfy(debh)
  381. r_debh = debh.split("!")[0]
  382. print(r_debh)
  383. result1, result2, rgde, jxde, clde, bz_selected, bz_selected2, actual_zhuanye= service.getSingleDeXilie(zhuanye, r_debh)
  384. print("get result ***************************************")
  385. if result1:
  386. result3 = json.loads(result1)
  387. else:
  388. result3 = {}
  389. result3["reverse"] = str(result2)
  390. result3["rgde"] = rgde
  391. result3["jxde"] = jxde
  392. result3["clde"] = clde
  393. result3["actual_zhuanye"] = actual_zhuanye
  394. if bz_selected != None:
  395. result3["bz_selected"] = json.loads(bz_selected)
  396. else:
  397. result3["bz_selected"] = {"BZBH": {}}
  398. if bz_selected2 != None:
  399. result3["bz_selected2"] = json.loads(bz_selected2)
  400. else:
  401. result3["bz_selected2"] = {"BZBH": {}}
  402. ####14-227+[14-228]*-2
  403. ####3-409*2
  404. print(r_debh)
  405. if "[" in r_debh:
  406. position3 = r_debh.find("*")
  407. coef = 1
  408. if position3 == -1:
  409. pass
  410. else:
  411. coef = r_debh[1 + position3:]
  412. print(coef)
  413. tail = 0
  414. for i in range(0, len(coef) + 1):
  415. if i == len(coef):
  416. tail = i
  417. break
  418. if (coef[i] > '9' or coef[i] < '0') and coef[i] != '-':
  419. tail = i
  420. break
  421. if tail == 0:
  422. print("1113111")
  423. result3["reverse"] = 'None'
  424. return json.dumps(result3, ensure_ascii=False)
  425. coef = int(coef[0:tail])
  426. position1 = r_debh.find("[")
  427. position2 = r_debh.find("]")
  428. if position2 == -1:
  429. print("1121111")
  430. result3["reverse"] = 'None'
  431. return json.dumps(result3, ensure_ascii=False)
  432. if r_debh[position1-1] == "+":
  433. pass
  434. elif r_debh[position1-1] == "-":
  435. coef = -coef
  436. else:
  437. print("111111")
  438. result3["reverse"] = 'None'
  439. return json.dumps(result3, ensure_ascii=False)
  440. debh = r_debh[position1+1: position2]
  441. if result3['GLDE']: ##csv文件里的字段,表示这个定额有没有配套的增减定额
  442. hit = False
  443. for key, value in result3['GLDE'].items():
  444. if value == debh:
  445. hit = True
  446. if not hit:
  447. result3["reverse"] = 'None'
  448. return json.dumps(result3, ensure_ascii=False)
  449. else:
  450. result3["reverse"] = 'None'
  451. return json.dumps(result3, ensure_ascii=False)
  452. result1_, result2_, rgde_, jxde_, clde_, bz_selected_, bz_selected2_, actual_zhuanye_ = service.getSingleDeXilie(zhuanye, debh)
  453. if result1_:
  454. util.mergerg(rgde, rgde_, coef)
  455. util.mergejx(jxde, jxde_, coef)
  456. util.mergecl(clde, clde_, coef)
  457. result3["rgde"] = rgde
  458. result3["jxde"] = jxde
  459. result3["clde"] = clde
  460. item_ = None
  461. for item in result3['DW'].keys():
  462. item_ = item
  463. result3['DEBH'] = {item_: util.cleanBM(r_debh)}
  464. else:
  465. result3["reverse"] = 'None'
  466. elif "*" in r_debh:##1-234*2
  467. position3 = r_debh.find("*")
  468. coef = 1
  469. coef = r_debh[1 + position3:]
  470. print(coef)
  471. tail = 0
  472. for i in range(0, len(coef) + 1):
  473. if i == len(coef):
  474. tail = i
  475. break
  476. if (coef[i] > '9' or coef[i] < '0') and coef[i] != '-':
  477. tail = i
  478. break
  479. if tail == 0:
  480. print("1113111")
  481. result3["reverse"] = 'None'
  482. return json.dumps(result3, ensure_ascii=False)
  483. coef = int(coef[0:tail])
  484. util.multirg(result3["rgde"], coef)
  485. util.multijx(result3["jxde"], coef)
  486. util.multicl(result3["clde"], coef)
  487. item_ = None
  488. for item in result3['DW'].keys():
  489. item_ = item
  490. result3['DEBH'] = {item_: (r_debh)}
  491. print(result3)
  492. return json.dumps(result3, ensure_ascii=False)
  493. @app.post("/save/")
  494. async def save(r: Info):
  495. data = json.loads(r.name)
  496. ##print(data)
  497. return await db.save(client, data)
  498. @app.post("/savedjcs/")
  499. async def savedjcs(r: Info):
  500. data = json.loads(r.name)
  501. ##print(data)
  502. return await db.savedjcs(client, data)
  503. @app.post("/applyFL/")
  504. async def applyFL(r: InfoWithID):
  505. data = json.loads(r.name)
  506. print(data)
  507. return await db.applyFL(client, r.id, data)
  508. @app.post("/tiaojia/")
  509. async def tiaojia(r: Tiaojia):
  510. ##return []
  511. glf = r.glf
  512. lr = r.lr
  513. if r.glf == '':
  514. glf = '0'
  515. if r.lr == "":
  516. lr = '0'
  517. return await db.tiaojia(client, r.biao_id, r.bh, r.bm, r.mingcheng, r.danwei, r.jiage, glf, lr, r.bz)
  518. @app.post("/searchde/")
  519. async def searchde(r: SearchDe):
  520. ##return []
  521. return await db.searchde(client, r.zhuanye, r.text)
  522. @app.post("/updatezjcs/")
  523. async def updatezjcs(r: UpdateZjcs):
  524. ##return []
  525. return await db.updatezjcs(client, r.biao_id, r.bh, r.mc, r.fl)
  526. @app.post("/upload/")
  527. async def upload(file: UploadFile):
  528. if file.filename.endswith('13jz') or file.filename.endswith("13jt"):
  529. content = await file.read()
  530. string = content.decode('utf-8')
  531. await resolve(string)
  532. return [file.filename]
  533. elif file.filename.endswith("jszf"):
  534. content = await file.read()
  535. string = content.decode('utf-8')
  536. root = ET.fromstring(string)
  537. for child in root:
  538. print(child)
  539. if child.tag == "ZBFileContent":
  540. base64_bytes = child.text.encode("ascii")
  541. sample_string_bytes = base64.b64decode(base64_bytes)
  542. tmp = str(uuid.uuid4())
  543. os.mkdir(os.path.join("tmp", tmp))
  544. with open(tmp, "wb") as file_:
  545. file_.write(sample_string_bytes)
  546. with zipfile.ZipFile(tmp, 'r') as zip_ref:
  547. zip_ref.extractall(os.path.join("tmp", tmp))
  548. dir_list = os.listdir(os.path.join("tmp", tmp))
  549. print(dir_list)
  550. for entry in dir_list:
  551. if entry.endswith("13jz"):
  552. with open(os.path.join("tmp", tmp, entry), 'r') as f:
  553. await resolve(f.read())
  554. return [file.filename]
  555. else:
  556. return [file.filename]
  557. @app.get("/download/{item_id}")
  558. async def download_file(item_id):
  559. file_path = "export/contacts.xml.b"
  560. # Create the root element
  561. root = ET.Element("JingJiBiao")
  562. # Create a sub-element
  563. ##TouBiaoXx = ET.SubElement(root, "TouBiaoXx")
  564. await db.build(client, root, item_id)
  565. # Create the tree and write to a file
  566. tree = ET.ElementTree(root)
  567. tree.write("export/contacts.xml", encoding="utf-8")
  568. dom = MD.parse("export/contacts.xml")
  569. with open("export/contacts.xml.b", 'w') as f:
  570. f.write("<?xml version=\"1.0\" encoding=\"UTF-8\" ?>\n")
  571. content = (dom.toprettyxml(indent=" "))
  572. content_ = content.split("\n")
  573. f.write("\n".join(content_[1:]))
  574. return FileResponse(file_path, media_type='application/octet-stream', filename="contacts.xml")
  575. async def resolve(data):
  576. await db.resolve(data, client)##manager.send_personal_message(f"You wrote: {data}", websocket)
  577. ##@app.websocket("/ws")
  578. ##async def websocket_endpoint(websocket: WebSocket):
  579. ## await manager.connect(websocket)
  580. ## try:
  581. ## while True:
  582. ## data = await websocket.receive_text()
  583. ## await resolve(websocket, data)
  584. ## ##await manager.broadcast(f"Client #{client_id} says: {data}")
  585. ## except WebSocketDisconnect:
  586. ## manager.disconnect(websocket)
  587. ## ##await manager.broadcast(f"Client left the chat")