1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253
| import json import os from datetime import datetime from typing import List, Dict
class SafeFinanceCalculator: """安全的财务计算器""" def __init__(self, log_file="finance_calc.log"): self.log_file = log_file self.validator = FinanceValidator() def log(self, operation: str, details: str, status: str = "SUCCESS"): """记录操作日志""" timestamp = datetime.now().strftime('%Y-%m-%d %H:%M:%S') log_entry = f"[{timestamp}] [{status}] {operation}: {details}\n" try: with open(self.log_file, 'a', encoding='utf-8') as f: f.write(log_entry) except Exception as e: print(f"⚠️ 日志写入失败: {e}") def calculate_tax_salary(self, gross_salary: str, insurance_str: str = "0") -> float: """ 计算税后工资(安全版) 返回:税后工资(出错返回0) """ try: salary = self.validator.validate_amount(gross_salary, min_value=0, max_value=100000) insurance = self.validator.validate_amount(insurance_str, min_value=0, max_value=50000) taxable = salary - insurance - 5000 if taxable <= 0: tax = 0 elif taxable <= 36000: tax = taxable * 0.03 else: tax = taxable * 0.10 - 2520 net_salary = salary - insurance - tax self.log("工资计算", f"税前{salary},五险一金{insurance},税后{net_salary:.2f}") return round(net_salary, 2) except Exception as e: error_msg = str(e) self.log("工资计算", f"输入-gross:{gross_salary},insurance:{insurance_str},错误:{error_msg}", "ERROR") print(f"❌ 计算失败: {error_msg},已返回默认值0") return 0 def reimburse_from_file(self, filepath: str) -> float: """ 从文件读取报销明细并计算总额 返回:报销总额(出错返回0) """ try: if not os.path.exists(filepath): raise FileNotFoundError(f"文件'{filepath}'不存在") try: with open(filepath, 'r', encoding='utf-8') as f: reimburse_data = json.load(f) except json.JSONDecodeError: raise ValueError(f"文件'{filepath}'不是有效的JSON格式") if 'reimbursements' not in reimburse_data: raise KeyError("缺少'reimbursements'字段") reimbursements = reimburse_data['reimbursements'] if not isinstance(reimbursements, list): raise TypeError("'reimbursements'必须是列表") total = 0 errors = [] for i, item in enumerate(reimbursements, 1): try: if 'amount' not in item: raise KeyError(f"第{i}条记录缺少'amount'字段") amount = self.validator.validate_amount( str(item['amount']), min_value=0, max_value=50000 ) status = item.get('status', 'pending') if status != 'approved': print(f"⚠️ 第{i}条记录状态为'{status}',跳过计算") continue total += amount except Exception as e: errors.append(f"第{i}条: {e}") continue if errors: self.log("报销总额计算", f"成功{len(reimbursements)-len(errors)}条,失败{len(errors)}条", "WARNING") for err in errors: self.log("报销明细错误", err, "ERROR") else: self.log("报销总额计算", f"文件{filepath},总额{total:.2f},记录数{len(reimbursements)}") return round(total, 2) except Exception as e: self.log("报销总额计算", f"文件{filepath},错误:{str(e)}", "ERROR") print(f"❌ 计算失败: {e}") return 0 def calculate_roi(self, investment: str, profit: str) -> float: """ 计算ROI投资回报率 ROI = (收益 - 成本) / 成本 * 100% 返回:ROI百分比(出错返回0) """ try: invest = self.validator.validate_amount(investment, min_value=0.01, max_value=10000000) prof = self.validator.validate_amount(profit, min_value=0, max_value=10000000) roi = (prof - invest) / invest * 100 self.log("ROI计算", f"投资{invest},收益{prof},ROI:{roi:.2f}%") return round(roi, 2) except Exception as e: self.log("ROI计算", f"输入-inv:{investment},profit:{profit},错误:{str(e)}", "ERROR") print(f"❌ 计算失败: {e}") return 0 def show_log(self, lines: int = 10): """查看最近的操作日志""" try: if not os.path.exists(self.log_file): print("📭 暂无日志") return print(f"\n📋 最近 {lines} 条操作日志:") print("=" * 70) with open(self.log_file, 'r', encoding='utf-8') as f: all_logs = f.readlines() for log in all_logs[-lines:]: print(log.strip()) except Exception as e: print(f"❌ 读取日志失败: {e}")
def main(): """主菜单""" calculator = SafeFinanceCalculator() print("=" * 55) print("安全财务计算器 v1.0") print("所有操作均有日志记录,错误自动处理") print("=" * 55) while True: print("\n" + "=" * 50) print("功能菜单") print("=" * 50) print("1. 计算税后工资") print("2. 计算报销总额(从文件)") print("3. 计算项目ROI") print("4. 查看操作日志") print("5. 退出") print("=" * 50) choice = input("请选择: ").strip() if choice == "1": salary = input("税前工资: ").strip() insurance = input("五险一金(回车默认为0): ").strip() or "0" result = calculator.calculate_tax_salary(salary, insurance) if result > 0: print(f"✅ 税后工资: ¥{result:,.2f}") else: print("⚠️ 计算失败,请检查输入") elif choice == "2": filepath = input("报销文件路径: ").strip() if not filepath: filepath = "reimbursements.json" if not os.path.exists(filepath): print("⚠️ 文件不存在,创建示例文件...") sample_data = { "reimbursements": [ {"amount": 500, "status": "approved", "category": "交通费"}, {"amount": 1200, "status": "approved", "category": "餐饮费"}, {"amount": 800, "status": "pending", "category": "办公用品"} ] } with open(filepath, 'w', encoding='utf-8') as f: json.dump(sample_data, f, ensure_ascii=False, indent=2) print(f"✅ 示例文件'{filepath}'已创建") result = calculator.reimburse_from_file(filepath) if result > 0: print(f"✅ 可报销总额: ¥{result:,.2f}") else: print("⚠️ 计算失败或无可报销项目") elif choice == "3": investment = input("项目投资成本: ").strip() profit = input("项目收益: ").strip() result = calculator.calculate_roi(investment, profit) if result > 0: print(f"✅ 投资回报率: {result:.2f}%") else: print(f"ℹ️ 投资回报率: {result:.2f}%") elif choice == "4": lines = input("显示最近多少条日志(默认10): ").strip() or "10" try: calculator.show_log(int(lines)) except: calculator.show_log() elif choice == "5": print("👋 感谢使用,日志已保存至 finance_calc.log") break else: print("请输入1-5之间的数字!")
if __name__ == "__main__": main()
|