urban-investment-research/CodeMakeUtils.py

320 lines
11 KiB
Python
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

import shutil
from pathlib import Path
import os
import string
def code_make(dir_path, replace_dic={}, save_path="temp"):
"""
增删改查代码生成
@param dir_path: 代码模板
@param replace_dic: 需要替换的名称
@param save_path: 保存路径
"""
code_path = Path(dir_path)
if not code_path.exists():
os.makedirs(code_path)
if code_path.is_dir():
save_path = Path(save_path)
shutil.copytree(code_path, save_path)
for root, dirs, files in os.walk(save_path):
for file in files:
file_path = Path(os.path.join(root, file))
item_code_str = file_path.read_text(encoding="utf-8")
new_code_str = item_code_str
for replace_word, replaced_word in replace_dic.items():
new_code_str = new_code_str.replace(replace_word, replaced_word)
with open(file_path, "w", encoding="utf-8") as f:
f.write(new_code_str)
def to_snake(name):
new_name = ""
for i in range(len(name)):
k = name[i]
if name[i] in string.ascii_letters:
if name[i].isupper():
if i == 0:
k = name[i].lower()
else:
k = '_' + name[i].lower()
new_name += k
return new_name
def to_upper_camel_case(name):
items = name.split("_")
new_name = ""
for item in items:
new_name += item[0].upper() + item[1:]
return new_name
def table_str_convert(table_str, key='id'):
replace_dic = {
'varchar': 'String',
'char': 'String',
'date': 'Date',
'datetime': 'DateTime',
'text': 'Text',
'int': 'Integer',
'double': 'Double'
}
new_lines = []
for line in table_str.split("\n"):
if line:
cols = line.split("\t")
col_name = cols[0].replace(' ', "").replace("-", '_')
col_type = cols[1].replace(" ", '')
col_type = col_type.replace(col_type.split('(')[0], replace_dic[col_type.split('(')[0]])
comment = cols[3]
comment_str = f', comment="{comment}"' if comment.replace(" ", '') else ""
primary_key_str = f', primary_key=True' if col_name == key else ''
new_line = f'{col_name} = Column({col_type}{primary_key_str}{comment_str})'
new_lines.append(new_line)
new_content = "\n ".join(new_lines)
return new_content
def make_info_str(table_str, key='id'):
replace_dic = {
'varchar': 'str',
'char': 'str',
'text': 'str',
'double': 'float'
}
info_lines = []
add_info_lines = []
for line in table_str.split("\n"):
if line:
cols = line.split("\t")
col_name = cols[0].replace(' ', "").replace("-", '_')
col_type = cols[1].replace(" ", '')
if col_type.split('(')[0] in replace_dic:
col_type = replace_dic[col_type.split('(')[0]]
# comment = col_type[3]
# comment_str = f',comment="{col_type[3]}"' if comment else ""
# primary_key_str = f',primary_key=True' if col_name == key else ''
new_line = f'{col_name}: Optional[{col_type}]'
info_lines.append(new_line)
if col_name != "id":
add_info_lines.append(new_line)
info_content = "\n ".join(info_lines)
add_info_content = "\n ".join(add_info_lines)
return info_content, add_info_content
def crud_code_make(table_name: str, chinese_name, table_str, path: str):
model_content = table_str_convert(table_str)
info_content, add_info_content = make_info_str(table_str)
upper_camel_case_name = to_upper_camel_case(table_name)
code_make("Utils/CodeMake/CrudTemplate",
{"EditItemType": upper_camel_case_name,
"edit_item_type": table_name,
"修改项类型": chinese_name,
'"""model_content"""': model_content,
'"""info_content"""': info_content,
'"""add_info_content"""': add_info_content,
}
, f"{path}/{upper_camel_case_name}")
# crud_code_make("company_credit_rating",
# "主体评级",
# """id int unsigned auto_increment
# company_id int 企业ID
# result char(5) 评级结果
# rate_date date 评级日期
# publish_date date 披露日期
# outlook char(5) 展望
# rate_agency varchar(50) 评级机构
# rate_file text 评级报告文件地址链接""",
# "Mods/OtherInformation2/Mods")
#
# crud_code_make("company_business_compose",
# "业务构成",
# """id int unsigned auto_increment
# company_id int 企业ID
# name varchar(255) not null 业务名称
# income double 收入(元)
# total_date date 统计截至时间
# remark text 业务描述""",
# "Mods/OtherInformation2/Mods")
#
# crud_code_make("company_business_items",
# "重要项目",
# """id int unsigned auto_increment
# company_id int 企业ID
# name varchar(255) not null 项目名称
# product varchar(255) 产品类型
# industry varchar(255) 行业类型
# region int 地区
# year int 业务年度
# remark text 项目描述""",
# "Mods/OtherInformation2/Mods")
#
# crud_code_make("company_finance_main",
# "财务报表主要指标",
# """id int unsigned auto_increment
# company_id int 企业ID
# total_date date 统计截至日期
# total_assets double 资产总额
# owners_equity double 所有者权益
# short_term_debt double 短期债务
# long_term_debt double 长期债务
# total_debt double 总债务
# operating_income double 营业收入
# total_profit double 利润总额
# net_profit double 净利润
# ebdita double EBITDA
# operating_net_cash_inflow double 经营性净现金流入
# receivable_turnover_times double 应收款项周转次数(次)
# inventory_turnover_times double 存货周转次数(次)
# total_asset_turnover_times double 总资产周转次数(次)
# cash_to_income_ratio double 现金收入比
# operating_margin double 营业利润率
# long_debt_capitalization_ratio double 长期债务资本化比率
# total_debt_capitalization_ratio double 总债务资本化比率
# asset_liability_ratio double 资产负债率
# current_ratio double 流动比率
# quick_ratio double 速动比率
# ebdita_interest_coverage_ratio double EBITDA利息保障倍数(倍)
# total_debt_ebdita double 总债务/EBITDA(倍)""",
# "Mods/OtherInformation2/Mods")
#
# crud_code_make("company_restricted_assets",
# "受限资产",
# """id int unsigned auto_increment
# company_id int 企业ID
# total_date date 统计截至时间
# name varchar(255) 受限资产明细
# duration varchar(255) 受限期限期限
# amount varchar(255) 资产账面价值
# reason varchar(255) 受限原因
# remark text 受限资产说明""",
# "Mods/OtherInformation2/Mods")
# crud_code_make("company_financial_statement",
# "财务说明",
# """id int unsigned auto_increment
# company_id int 企业ID
# total_date date 评价截至时间
# assets text 资产说明
# debt text 负债说明
# rights text 权益说明""",
# "Mods/OtherInformation2/Mods")
# crud_code_make("company_credit",
# "授信情况",
# """id int unsigned auto_increment
# company_id int 企业ID
# total_date date 统计时间
# credit_amount double 授信额度(万)
# used_amount double 使用额度(万)
# unused_amount double 剩余额度(万)
# credit_institution varchar(255) 授信机构""",
# "Mods/OtherInformation2/Mods")
# crud_code_make("company_guarantee",
# "提供担保",
# """id int unsigned auto_increment
# company_id int 企业ID
# third_name varchar(255) 被担保方
# type varchar(255) 担保类型
# amount double 担保规模(万)
# duration varchar(255) 担保期限
# method varchar(255) 保证方式
# status char(2) 担保状态(存续、完成)
# remark text 担保说明""",
# "Mods/OtherInformation2/Mods")
# crud_code_make("company_bond",
# "发债情况",
# """id int unsigned auto_increment
# company_id int 企业ID
# name varchar(255) 债券简称
# code varchar(255) 债券代码
# type char(20) 债券类型
# asset varchar(255) 发行规模
# publish_date date 发行日期
# duration varchar(255) 债券期限
# raising_way char(5) 募集方式
# due_date date 到期日期
# coupon varchar(255) 票面利率
# rate_result char(5) 债项评级
# rate_agency varchar(255) 评级机构
# status char(4) 发债状态:存续、到期偿付、违约""",
# "Mods/OtherInformation2/Mods")
#
# crud_code_make("company_bank_lease",
# "银行借款",
# """id int unsigned auto_increment
# company_id int 企业ID
# third_name varchar(255) 借款机构
# amount varchar(255) 借款金额
# start_date date 借款日期
# end_date date 到期日期
# coupon varchar(255) 利率
# method varchar(255) 借款方式(信用、抵押、保证、质押...
# status char(4) 状态:存续、到期偿付、违约
# remark text 备注""",
# "Mods/OtherInformation2/Mods")
#
# crud_code_make("company_trust_lease",
# "信托融资",
# """id int unsigned auto_increment
# company_id int 企业ID
# third_name varchar(255) 借款机构
# amount varchar(255) 借款金额
# start_date date 借款日期
# end_date date 到期日期
# coupon varchar(255) 利率
# method varchar(255) 借款方式(信用、抵押、保证、质押...
# status char(4) 状态:存续、到期偿付、违约
# remark text 备注""",
# "Mods/OtherInformation2/Mods")
#
# crud_code_make("company_rental_lease",
# "租赁融资",
# """id int unsigned auto_increment
# company_id int 企业ID
# third_name varchar(255) 借款机构
# amount varchar(255) 借款金额
# start_date date 借款日期
# end_date date 到期日期
# coupon varchar(255) 利率
# method varchar(255) 借款方式(信用、抵押、保证、质押...
# status char(4) 状态:存续、到期偿付、违约
# remark text 备注""",
# "Mods/OtherInformation2/Mods")
#
# crud_code_make("company_other_lease",
# "其他融资",
# """id int unsigned auto_increment
# company_id int 企业ID
# type varchar(255) 融资类型
# third_name varchar(255) 借款机构
# amount double 借款金额(万)
# duration varchar(255) 借款期限
# coupon varchar(255) 利率
# method varchar(255) 借款方式(信用、抵押、保证、质押...
# status char(4) 状态:存续、已兑付、违约
# remark text 备注""",
# "Mods/OtherInformation2/Mods")
#
# crud_code_make("company_judicial_document",
# "裁判文书",
# """id int unsigned auto_increment
# company_id int 企业ID
# doc_type varchar(255) 文书类型
# case_date date 裁判日期
# title varchar(255) 案件名称
# code varchar(255) 案号
# type varchar(255) 案件类型
# reason varchar(255) 案由
# amount double 案件金额(万)
# identity varchar(255) 案件身份
# result text 裁判结果
# court varchar(255) 审理法院
# publish_date date 发布日期""",
# "Mods/OtherInformation2/Mods")